diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/main/java/org/sakaiproject/nakamura/lite/storage/jdbc/JDBCStorageClient.java b/src/main/java/org/sakaiproject/nakamura/lite/storage/jdbc/JDBCStorageClient.java
index 03db596..1a7b751 100644
--- a/src/main/java/org/sakaiproject/nakamura/lite/storage/jdbc/JDBCStorageClient.java
+++ b/src/main/java/org/sakaiproject/nakamura/lite/storage/jdbc/JDBCStorageClient.java
@@ -1,1293 +1,1293 @@
/*
* Licensed to the Sakai Foundation (SF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The SF 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.sakaiproject.nakamura.lite.storage.jdbc;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.lang.StringUtils;
import org.sakaiproject.nakamura.api.lite.ClientPoolException;
import org.sakaiproject.nakamura.api.lite.DataFormatException;
import org.sakaiproject.nakamura.api.lite.RemoveProperty;
import org.sakaiproject.nakamura.api.lite.StorageClientException;
import org.sakaiproject.nakamura.api.lite.StorageClientUtils;
import org.sakaiproject.nakamura.api.lite.accesscontrol.AccessDeniedException;
import org.sakaiproject.nakamura.api.lite.util.PreemptiveIterator;
import org.sakaiproject.nakamura.lite.content.FileStreamContentHelper;
import org.sakaiproject.nakamura.lite.content.InternalContent;
import org.sakaiproject.nakamura.lite.content.StreamedContentHelper;
import org.sakaiproject.nakamura.lite.storage.Disposable;
import org.sakaiproject.nakamura.lite.storage.DisposableIterator;
import org.sakaiproject.nakamura.lite.storage.RowHasher;
import org.sakaiproject.nakamura.lite.storage.StorageClient;
import org.sakaiproject.nakamura.lite.types.Types;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UTFDataFormatException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
public class JDBCStorageClient implements StorageClient, RowHasher {
private static final String INVALID_DATA_ERROR = "Data invalid for storage.";
public class SlowQueryLogger {
// only used to define the logger.
}
private static final Logger LOGGER = LoggerFactory.getLogger(JDBCStorageClient.class);
private static final Logger SQL_LOGGER = LoggerFactory.getLogger(SlowQueryLogger.class);
private static final String SQL_VALIDATE = "validate";
private static final String SQL_CHECKSCHEMA = "check-schema";
private static final String SQL_COMMENT = "#";
private static final String SQL_EOL = ";";
private static final String SQL_DELETE_STRING_ROW = "delete-string-row";
private static final String SQL_INSERT_STRING_COLUMN = "insert-string-column";
private static final String SQL_UPDATE_STRING_COLUMN = "update-string-column";
private static final String SQL_REMOVE_STRING_COLUMN = "remove-string-column";
private static final String SQL_BLOCK_DELETE_ROW = "block-delete-row";
private static final String SQL_BLOCK_SELECT_ROW = "block-select-row";
private static final String SQL_BLOCK_INSERT_ROW = "block-insert-row";
private static final String SQL_BLOCK_UPDATE_ROW = "block-update-row";
private static final String SELECT_INDEX_COLUMNS = "select-index-columns";
private static final String PROP_HASH_ALG = "rowid-hash";
private static final String USE_BATCH_INSERTS = "use-batch-inserts";
private static final String JDBC_SUPPORT_LEVEL = "jdbc-support-level";
private static final Set<String> AUTO_INDEX_COLUMNS = ImmutableSet.of(
"cn:_:parenthash",
"au:_:parenthash",
"ac:_:parenthash");
private static final int STMT_BASE = 0;
private static final int STMT_TABLE_JOIN = 1;
private static final int STMT_WHERE = 2;
private static final int STMT_WHERE_SORT = 3;
private static final int STMT_ORDER = 4;
private static final int STMT_EXTRA_COLUMNS = 5;
private static final Object SLOW_QUERY_THRESHOLD = "slow-query-time";
private static final Object VERY_SLOW_QUERY_THRESHOLD = "very-slow-query-time";
private JDBCStorageClientPool jcbcStorageClientConnection;
private Map<String, Object> sqlConfig;
private boolean active;
private StreamedContentHelper streamedContentHelper;
private List<Disposable> toDispose = Lists.newArrayList();
private Exception closed;
private Exception passivate;
private String rowidHash;
private Map<String, AtomicInteger> counters = Maps.newConcurrentHashMap();
private Set<String> indexColumns;
private long slowQueryThreshold;
private long verySlowQueryThreshold;
public JDBCStorageClient(JDBCStorageClientPool jdbcStorageClientConnectionPool,
Map<String, Object> properties, Map<String, Object> sqlConfig) throws SQLException,
NoSuchAlgorithmException, StorageClientException {
this.jcbcStorageClientConnection = jdbcStorageClientConnectionPool;
streamedContentHelper = new FileStreamContentHelper(this, properties);
this.sqlConfig = sqlConfig;
rowidHash = getSql(PROP_HASH_ALG);
if (rowidHash == null) {
rowidHash = "MD5";
}
active = true;
slowQueryThreshold = 50L;
verySlowQueryThreshold = 100L;
if (sqlConfig.containsKey(SLOW_QUERY_THRESHOLD)) {
slowQueryThreshold = Long.parseLong((String)sqlConfig.get(SLOW_QUERY_THRESHOLD));
}
if (sqlConfig.containsKey(VERY_SLOW_QUERY_THRESHOLD)) {
verySlowQueryThreshold = Long.parseLong((String)sqlConfig.get(VERY_SLOW_QUERY_THRESHOLD));
}
}
public Map<String, Object> get(String keySpace, String columnFamily, String key)
throws StorageClientException {
checkClosed();
String rid = rowHash(keySpace, columnFamily, key);
return internalGet(keySpace, columnFamily, rid);
}
private Map<String, Object> internalGet(String keySpace, String columnFamily, String rid) throws StorageClientException {
ResultSet body = null;
Map<String, Object> result = Maps.newHashMap();
PreparedStatement selectStringRow = null;
try {
selectStringRow = getStatement(keySpace, columnFamily, SQL_BLOCK_SELECT_ROW, rid, null);
inc("A");
selectStringRow.clearWarnings();
selectStringRow.clearParameters();
selectStringRow.setString(1, rid);
body = selectStringRow.executeQuery();
inc("B");
if (body.next()) {
Types.loadFromStream(rid, result, body.getBinaryStream(1), columnFamily);
}
} catch (SQLException e) {
LOGGER.warn("Failed to perform get operation on " + keySpace + ":" + columnFamily
+ ":" + rid, e);
if (passivate != null) {
LOGGER.warn("Was Pasivated ", passivate);
}
if (closed != null) {
LOGGER.warn("Was Closed ", closed);
}
throw new StorageClientException(e.getMessage(), e);
} catch (IOException e) {
LOGGER.warn("Failed to perform get operation on " + keySpace + ":" + columnFamily
+ ":" + rid, e);
if (passivate != null) {
LOGGER.warn("Was Pasivated ", passivate);
}
if (closed != null) {
LOGGER.warn("Was Closed ", closed);
}
throw new StorageClientException(e.getMessage(), e);
} finally {
close(body, "B");
close(selectStringRow, "A");
}
return result;
}
public String rowHash(String keySpace, String columnFamily, String key)
throws StorageClientException {
MessageDigest hasher;
try {
hasher = MessageDigest.getInstance(rowidHash);
} catch (NoSuchAlgorithmException e1) {
throw new StorageClientException("Unable to get hash algorithm " + e1.getMessage(), e1);
}
String keystring = keySpace + ":" + columnFamily + ":" + key;
byte[] ridkey;
try {
ridkey = keystring.getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
ridkey = keystring.getBytes();
}
return StorageClientUtils.encode(hasher.digest(ridkey));
}
public void insert(String keySpace, String columnFamily, String key, Map<String, Object> values, boolean probablyNew)
throws StorageClientException {
checkClosed();
Map<String, PreparedStatement> statementCache = Maps.newHashMap();
boolean autoCommit = true;
try {
autoCommit = startBlock();
String rid = rowHash(keySpace, columnFamily, key);
for (Entry<String, Object> e : values.entrySet()) {
String k = e.getKey();
Object o = e.getValue();
if (o instanceof byte[]) {
throw new RuntimeException("Invalid content in " + k
+ ", storing byte[] rather than streaming it");
}
}
Map<String, Object> m = get(keySpace, columnFamily, key);
for (Entry<String, Object> e : values.entrySet()) {
String k = e.getKey();
Object o = e.getValue();
if (o instanceof RemoveProperty || o == null) {
m.remove(k);
} else {
m.put(k, o);
}
}
LOGGER.debug("Saving {} {} {} ", new Object[]{key, rid, m});
if ( probablyNew ) {
PreparedStatement insertBlockRow = getStatement(keySpace, columnFamily,
SQL_BLOCK_INSERT_ROW, rid, statementCache);
insertBlockRow.clearWarnings();
insertBlockRow.clearParameters();
insertBlockRow.setString(1, rid);
InputStream insertStream = null;
try {
insertStream = Types.storeMapToStream(rid, m, columnFamily);
} catch (UTFDataFormatException e) {
throw new DataFormatException(INVALID_DATA_ERROR, e);
}
if ("1.5".equals(getSql(JDBC_SUPPORT_LEVEL))) {
insertBlockRow.setBinaryStream(2, insertStream, insertStream.available());
} else {
insertBlockRow.setBinaryStream(2, insertStream);
}
int rowsInserted = 0;
try {
rowsInserted = insertBlockRow.executeUpdate();
} catch ( SQLException e ) {
LOGGER.debug(e.getMessage(),e);
}
if ( rowsInserted == 0 ) {
PreparedStatement updateBlockRow = getStatement(keySpace, columnFamily,
SQL_BLOCK_UPDATE_ROW, rid, statementCache);
updateBlockRow.clearWarnings();
updateBlockRow.clearParameters();
updateBlockRow.setString(2, rid);
try {
insertStream = Types.storeMapToStream(rid, m, columnFamily);
} catch (UTFDataFormatException e) {
throw new DataFormatException(INVALID_DATA_ERROR, e);
}
if ("1.5".equals(getSql(JDBC_SUPPORT_LEVEL))) {
updateBlockRow.setBinaryStream(1, insertStream, insertStream.available());
} else {
updateBlockRow.setBinaryStream(1, insertStream);
}
if( updateBlockRow.executeUpdate() == 0) {
throw new StorageClientException("Failed to save " + rid);
} else {
LOGGER.debug("Updated {} ", rid);
}
} else {
LOGGER.debug("Inserted {} ", rid);
}
} else {
PreparedStatement updateBlockRow = getStatement(keySpace, columnFamily,
SQL_BLOCK_UPDATE_ROW, rid, statementCache);
updateBlockRow.clearWarnings();
updateBlockRow.clearParameters();
updateBlockRow.setString(2, rid);
InputStream updateStream = null;
try {
updateStream = Types.storeMapToStream(rid, m, columnFamily);
} catch (UTFDataFormatException e) {
throw new DataFormatException(INVALID_DATA_ERROR, e);
}
if ("1.5".equals(getSql(JDBC_SUPPORT_LEVEL))) {
updateBlockRow.setBinaryStream(1, updateStream, updateStream.available());
} else {
updateBlockRow.setBinaryStream(1, updateStream);
}
if (updateBlockRow.executeUpdate() == 0) {
PreparedStatement insertBlockRow = getStatement(keySpace, columnFamily,
SQL_BLOCK_INSERT_ROW, rid, statementCache);
insertBlockRow.clearWarnings();
insertBlockRow.clearParameters();
insertBlockRow.setString(1, rid);
try {
updateStream = Types.storeMapToStream(rid, m, columnFamily);
} catch (UTFDataFormatException e) {
throw new DataFormatException(INVALID_DATA_ERROR, e);
}
if ("1.5".equals(getSql(JDBC_SUPPORT_LEVEL))) {
insertBlockRow.setBinaryStream(2, updateStream, updateStream.available());
} else {
insertBlockRow.setBinaryStream(2, updateStream);
}
if (insertBlockRow.executeUpdate() == 0) {
throw new StorageClientException("Failed to save " + rid);
} else {
LOGGER.debug("Inserted {} ", rid);
}
} else {
LOGGER.debug("Updated {} ", rid);
}
}
if ("1".equals(getSql(USE_BATCH_INSERTS))) {
Set<PreparedStatement> updateSet = Sets.newHashSet();
Map<PreparedStatement, List<Entry<String, Object>>> updateSequence = Maps
.newHashMap();
Set<PreparedStatement> removeSet = Sets.newHashSet();
// execute the updates and add the necessary inserts.
Map<PreparedStatement, List<Entry<String, Object>>> insertSequence = Maps
.newHashMap();
Set<PreparedStatement> insertSet = Sets.newHashSet();
for (Entry<String, Object> e : values.entrySet()) {
String k = e.getKey();
Object o = e.getValue();
if (shouldIndex(keySpace, columnFamily, k)) {
if ( o instanceof RemoveProperty || o == null ) {
PreparedStatement removeStringColumn = getStatement(keySpace,
columnFamily, SQL_REMOVE_STRING_COLUMN, rid, statementCache);
removeStringColumn.setString(1, rid);
removeStringColumn.setString(2, k);
removeStringColumn.addBatch();
removeSet.add(removeStringColumn);
} else {
// remove all previous values
PreparedStatement removeStringColumn = getStatement(keySpace,
columnFamily, SQL_REMOVE_STRING_COLUMN, rid, statementCache);
removeStringColumn.setString(1, rid);
removeStringColumn.setString(2, k);
removeStringColumn.addBatch();
removeSet.add(removeStringColumn);
// insert new values, as we just removed them we know we can insert, no need to attempt update
// the only thing that we know is the colum value changes so we have to re-index the whole
// property
Object[] valueMembers = (o instanceof Object[]) ? (Object[]) o : new Object[] { o };
for (Object ov : valueMembers) {
String valueMember = ov.toString();
PreparedStatement insertStringColumn = getStatement(keySpace,
columnFamily, SQL_INSERT_STRING_COLUMN, rid, statementCache);
insertStringColumn.setString(1, valueMember);
insertStringColumn.setString(2, rid);
insertStringColumn.setString(3, k);
insertStringColumn.addBatch();
LOGGER.debug("Insert Index {} {}", k, valueMember);
insertSet.add(insertStringColumn);
List<Entry<String, Object>> insertSeq = insertSequence
.get(insertStringColumn);
if (insertSeq == null) {
insertSeq = Lists.newArrayList();
insertSequence.put(insertStringColumn, insertSeq);
}
insertSeq.add(e);
}
}
}
}
if ( !StorageClientUtils.isRoot(key)) {
// create a holding map containing a rowhash of the parent and then process the entry to generate a update operation.
Map<String, Object> autoIndexMap = ImmutableMap.of(InternalContent.PARENT_HASH_FIELD, (Object)rowHash(keySpace, columnFamily, StorageClientUtils.getParentObjectPath(key)));
for ( Entry<String, Object> e : autoIndexMap.entrySet()) {
PreparedStatement updateStringColumn = getStatement(keySpace,
columnFamily, SQL_UPDATE_STRING_COLUMN, rid, statementCache);
updateStringColumn.setString(1, (String)e.getValue());
updateStringColumn.setString(2, rid);
updateStringColumn.setString(3, e.getKey());
updateStringColumn.addBatch();
LOGGER.debug("Update {} {}", e.getKey(), e.getValue());
updateSet.add(updateStringColumn);
List<Entry<String, Object>> updateSeq = updateSequence
.get(updateStringColumn);
if (updateSeq == null) {
updateSeq = Lists.newArrayList();
updateSequence.put(updateStringColumn, updateSeq);
}
updateSeq.add(e);
}
}
LOGGER.debug("Remove set {}", removeSet);
for (PreparedStatement pst : removeSet) {
pst.executeBatch();
}
LOGGER.debug("Update set {}", updateSet);
for (PreparedStatement pst : updateSet) {
int[] res = pst.executeBatch();
List<Entry<String, Object>> updateSeq = updateSequence.get(pst);
for (int i = 0; i < res.length; i++) {
Entry<String, Object> e = updateSeq.get(i);
- if (res[i] <= 0) {
+ if (res[i] <= 0 && res[i] != -2 ) { // Oracle Drivers respond with -2 on success if the exact number updated is not known. http://download.oracle.com/javase/1.3/docs/guide/jdbc/spec2/jdbc2.1.frame6.html
String k = e.getKey();
Object o = e.getValue();
Object[] valueMembers = (o instanceof Object[]) ? (Object[]) o : new Object[] { o };
for (Object ov : valueMembers) {
String valueMember = ov.toString();
PreparedStatement insertStringColumn = getStatement(keySpace,
columnFamily, SQL_INSERT_STRING_COLUMN, rid, statementCache);
insertStringColumn.setString(1, valueMember);
insertStringColumn.setString(2, rid);
insertStringColumn.setString(3, k);
insertStringColumn.addBatch();
LOGGER.debug("Insert Index {} {}", k, valueMember);
insertSet.add(insertStringColumn);
List<Entry<String, Object>> insertSeq = insertSequence
.get(insertStringColumn);
if (insertSeq == null) {
insertSeq = Lists.newArrayList();
insertSequence.put(insertStringColumn, insertSeq);
}
insertSeq.add(e);
}
} else {
LOGGER.debug("Index updated for {} {} ", new Object[] { rid, e.getKey(),
e.getValue() });
}
}
}
LOGGER.debug("Insert set {}", insertSet);
for (PreparedStatement pst : insertSet) {
int[] res = pst.executeBatch();
List<Entry<String, Object>> insertSeq = insertSequence.get(pst);
for (int i = 0; i < res.length; i++ ) {
Entry<String, Object> e = insertSeq.get(i);
- if ( res[i] <= 0 ) {
+ if ( res[i] <= 0 && res[i] != -2 ) { // Oracle drivers respond with -2 on a successful insert when the number is not known http://download.oracle.com/javase/1.3/docs/guide/jdbc/spec2/jdbc2.1.frame6.html
LOGGER.warn("Index failed for {} {} ", new Object[] { rid, e.getKey(),
e.getValue() });
} else {
LOGGER.debug("Index inserted for {} {} ", new Object[] { rid, e.getKey(),
e.getValue() });
}
}
}
} else {
for (Entry<String, Object> e : values.entrySet()) {
String k = e.getKey();
Object o = e.getValue();
if (shouldIndex(keySpace, columnFamily, k)) {
if (o instanceof RemoveProperty || o == null) {
PreparedStatement removeStringColumn = getStatement(keySpace,
columnFamily, SQL_REMOVE_STRING_COLUMN, rid, statementCache);
removeStringColumn.clearWarnings();
removeStringColumn.clearParameters();
removeStringColumn.setString(1, rid);
removeStringColumn.setString(2, k);
int nrows = removeStringColumn.executeUpdate();
if (nrows == 0) {
m = get(keySpace, columnFamily, key);
LOGGER.debug(
"Column Not present did not remove {} {} Current Column:{} ",
new Object[] { getRowId(keySpace, columnFamily, key), k, m });
} else {
LOGGER.debug("Removed Index {} {} {} ",
new Object[]{getRowId(keySpace, columnFamily, key), k, nrows});
}
} else {
PreparedStatement removeStringColumn = getStatement(keySpace,
columnFamily, SQL_REMOVE_STRING_COLUMN, rid, statementCache);
removeStringColumn.clearWarnings();
removeStringColumn.clearParameters();
removeStringColumn.setString(1, rid);
removeStringColumn.setString(2, k);
int nrows = removeStringColumn.executeUpdate();
if (nrows == 0) {
m = get(keySpace, columnFamily, key);
LOGGER.debug(
"Column Not present did not remove {} {} Current Column:{} ",
new Object[] { getRowId(keySpace, columnFamily, key), k, m });
} else {
LOGGER.debug("Removed Index {} {} {} ",
new Object[]{getRowId(keySpace, columnFamily, key), k, nrows});
}
Object[] os = (o instanceof Object[]) ? (Object[]) o : new Object[] { o };
for (Object ov : os) {
String v = ov.toString();
PreparedStatement insertStringColumn = getStatement(keySpace,
columnFamily, SQL_INSERT_STRING_COLUMN, rid, statementCache);
insertStringColumn.clearWarnings();
insertStringColumn.clearParameters();
insertStringColumn.setString(1, v);
insertStringColumn.setString(2, rid);
insertStringColumn.setString(3, k);
LOGGER.debug("Non Batch Insert Index {} {}", k, v);
if (insertStringColumn.executeUpdate() == 0) {
throw new StorageClientException("Failed to save "
+ getRowId(keySpace, columnFamily, key) + " column:["
+ k + "] ");
} else {
LOGGER.debug("Inserted Index {} {} [{}]",
new Object[] { getRowId(keySpace, columnFamily, key),
k, v });
}
}
}
}
}
if ( !StorageClientUtils.isRoot(key)) {
String parent = StorageClientUtils.getParentObjectPath(key);
String hash = rowHash(keySpace, columnFamily, parent);
LOGGER.debug("Hash of {}:{}:{} is {} ",new Object[]{keySpace, columnFamily, parent, hash});
Map<String, Object> autoIndexMap = ImmutableMap.of(InternalContent.PARENT_HASH_FIELD, (Object)hash);
for ( Entry<String, Object> e : autoIndexMap.entrySet()) {
PreparedStatement updateStringColumn = getStatement(keySpace,
columnFamily, SQL_UPDATE_STRING_COLUMN, rid, statementCache);
updateStringColumn.clearWarnings();
updateStringColumn.clearParameters();
updateStringColumn.setString(1, (String) e.getValue());
updateStringColumn.setString(2, rid);
updateStringColumn.setString(3, e.getKey());
if (updateStringColumn.executeUpdate() == 0) {
PreparedStatement insertStringColumn = getStatement(keySpace,
columnFamily, SQL_INSERT_STRING_COLUMN, rid, statementCache);
insertStringColumn.clearWarnings();
insertStringColumn.clearParameters();
insertStringColumn.setString(1, (String) e.getValue());
insertStringColumn.setString(2, rid);
insertStringColumn.setString(3, e.getKey());
if (insertStringColumn.executeUpdate() == 0) {
throw new StorageClientException("Failed to save "
+ getRowId(keySpace, columnFamily, key) + " column:["
+ e.getKey() + "] ");
} else {
LOGGER.debug("Inserted Index {} {} [{}]",
new Object[] { getRowId(keySpace, columnFamily, key),
e.getKey(), e.getValue() });
}
} else {
LOGGER.debug(
"Updated Index {} {} [{}]",
new Object[] { getRowId(keySpace, columnFamily, key), e.getKey(), e.getValue() });
}
}
}
}
endBlock(autoCommit);
} catch (SQLException e) {
abandonBlock(autoCommit);
LOGGER.warn("Failed to perform insert/update operation on {}:{}:{} ", new Object[] {
keySpace, columnFamily, key }, e);
throw new StorageClientException(e.getMessage(), e);
} catch (IOException e) {
abandonBlock(autoCommit);
LOGGER.warn("Failed to perform insert/update operation on {}:{}:{} ", new Object[] {
keySpace, columnFamily, key }, e);
throw new StorageClientException(e.getMessage(), e);
} finally {
close(statementCache);
}
}
private void abandonBlock(boolean autoCommit) {
if (autoCommit) {
try {
Connection connection = jcbcStorageClientConnection.getConnection();
connection.rollback();
connection.setAutoCommit(autoCommit);
} catch (SQLException e) {
LOGGER.warn(e.getMessage(), e);
}
}
}
private void endBlock(boolean autoCommit) throws SQLException {
if (autoCommit) {
Connection connection = jcbcStorageClientConnection.getConnection();
connection.commit();
connection.setAutoCommit(autoCommit);
}
}
private boolean startBlock() throws SQLException {
Connection connection = jcbcStorageClientConnection.getConnection();
boolean autoCommit = connection.getAutoCommit();
connection.setAutoCommit(false);
return autoCommit;
}
private boolean shouldIndex(String keySpace, String columnFamily, String k) {
if ( AUTO_INDEX_COLUMNS.contains(columnFamily+":"+k)) {
return true;
}
if (indexColumns == null) {
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst = getStatement(keySpace, columnFamily, SELECT_INDEX_COLUMNS, "default", null);
inc(SELECT_INDEX_COLUMNS);
pst.clearWarnings();
pst.clearParameters();
rs = pst.executeQuery();
inc("select-index-columns-rs");
Set<String> loadIndexColumns = Sets.newHashSet();
while (rs.next()) {
loadIndexColumns.add(rs.getString(1));
}
indexColumns = loadIndexColumns;
LOGGER.debug("Indexing Colums is {} ", indexColumns);
} catch (SQLException e) {
LOGGER.warn(e.getMessage(), e);
return false;
} finally {
close(rs, "select-index-columns-rs");
close(pst, SELECT_INDEX_COLUMNS);
}
}
if (indexColumns.contains(columnFamily + ":" + k)) {
LOGGER.debug("Will Index {}:{}", columnFamily, k);
return true;
} else {
LOGGER.debug("Should Not Index {}:{}", columnFamily, k);
return false;
}
}
private String getRowId(String keySpace, String columnFamily, String key) {
return keySpace + ":" + columnFamily + ":" + key;
}
public void remove(String keySpace, String columnFamily, String key)
throws StorageClientException {
checkClosed();
PreparedStatement deleteStringRow = null;
PreparedStatement deleteBlockRow = null;
String rid = rowHash(keySpace, columnFamily, key);
boolean autoCommit = false;
try {
autoCommit = startBlock();
deleteStringRow = getStatement(keySpace, columnFamily, SQL_DELETE_STRING_ROW, rid, null);
inc("deleteStringRow");
deleteStringRow.clearWarnings();
deleteStringRow.clearParameters();
deleteStringRow.setString(1, rid);
deleteStringRow.executeUpdate();
deleteBlockRow = getStatement(keySpace, columnFamily, SQL_BLOCK_DELETE_ROW, rid, null);
inc("deleteBlockRow");
deleteBlockRow.clearWarnings();
deleteBlockRow.clearParameters();
deleteBlockRow.setString(1, rid);
deleteBlockRow.executeUpdate();
endBlock(autoCommit);
} catch (SQLException e) {
abandonBlock(autoCommit);
LOGGER.warn("Failed to perform delete operation on {}:{}:{} ", new Object[] { keySpace,
columnFamily, key }, e);
throw new StorageClientException(e.getMessage(), e);
} finally {
close(deleteStringRow, "deleteStringRow");
close(deleteBlockRow, "deleteBlockRow");
}
}
public void close() {
if (closed == null) {
try {
closed = new Exception("Connection Closed Traceback");
shutdownConnection();
jcbcStorageClientConnection.releaseClient(this);
} catch (Throwable t) {
LOGGER.error("Failed to close connection ", t);
}
}
}
private void checkClosed() throws StorageClientException {
if (closed != null) {
throw new StorageClientException(
"Connection Has Been closed, traceback of close location follows ", closed);
}
}
/**
* Get a prepared statement, potentially optimized and sharded.
*
* @param keySpace
* @param columnFamily
* @param sqlSelectStringRow
* @param rid
* @param statementCache
* @return
* @throws SQLException
*/
private PreparedStatement getStatement(String keySpace, String columnFamily,
String sqlSelectStringRow, String rid, Map<String, PreparedStatement> statementCache)
throws SQLException {
String shard = rid.substring(0, 1);
String[] keys = new String[] {
sqlSelectStringRow + "." + keySpace + "." + columnFamily + "._" + shard,
sqlSelectStringRow + "." + columnFamily + "._" + shard,
sqlSelectStringRow + "." + keySpace + "._" + shard,
sqlSelectStringRow + "._" + shard,
sqlSelectStringRow + "." + keySpace + "." + columnFamily,
sqlSelectStringRow + "." + columnFamily, sqlSelectStringRow + "." + keySpace,
sqlSelectStringRow };
for (String k : keys) {
if (sqlConfig.containsKey(k)) {
if (statementCache != null && statementCache.containsKey(k)) {
return statementCache.get(k);
} else {
PreparedStatement pst = jcbcStorageClientConnection.getConnection()
.prepareStatement((String) sqlConfig.get(k));
if (statementCache != null) {
inc("cachedStatement");
statementCache.put(k, pst);
}
return pst;
}
}
}
return null;
}
public void shutdownConnection() {
if (active) {
disposeDisposables();
active = false;
}
}
private void disposeDisposables() {
passivate = new Exception("Passivate Traceback");
for (Disposable d : toDispose) {
d.close();
}
}
private <T extends Disposable> T registerDisposable(T disposable) {
toDispose.add(disposable);
return disposable;
}
public boolean validate() throws StorageClientException {
checkClosed();
Statement statement = null;
try {
statement = jcbcStorageClientConnection.getConnection().createStatement();
inc("vaidate");
statement.execute(getSql(SQL_VALIDATE));
return true;
} catch (SQLException e) {
LOGGER.warn("Failed to validate connection ", e);
return false;
} finally {
try {
statement.close();
dec("vaidate");
} catch (Throwable e) {
LOGGER.debug("Failed to close statement in validate ", e);
}
}
}
private String getSql(String statementName) {
return (String) sqlConfig.get(statementName);
}
public void checkSchema(String[] clientConfigLocations) throws ClientPoolException,
StorageClientException {
checkClosed();
Statement statement = null;
try {
statement = jcbcStorageClientConnection.getConnection().createStatement();
try {
statement.execute(getSql(SQL_CHECKSCHEMA));
inc("schema");
LOGGER.info("Schema Exists");
return;
} catch (SQLException e) {
LOGGER.info("Schema does not exist {}", e.getMessage());
}
for (String clientSQLLocation : clientConfigLocations) {
String clientDDL = clientSQLLocation + ".ddl";
InputStream in = this.getClass().getClassLoader().getResourceAsStream(clientDDL);
if (in != null) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF8"));
int lineNo = 1;
String line = br.readLine();
StringBuilder sqlStatement = new StringBuilder();
while (line != null) {
line = StringUtils.stripEnd(line, null);
if (!line.isEmpty()) {
if (line.startsWith(SQL_COMMENT)) {
LOGGER.info("Comment {} ", line);
} else if (line.endsWith(SQL_EOL)) {
sqlStatement.append(line.substring(0, line.length() - 1));
String ddl = sqlStatement.toString();
try {
statement.executeUpdate(ddl);
LOGGER.info("SQL OK {}:{} {} ", new Object[] {
clientDDL, lineNo, ddl });
} catch (SQLException e) {
LOGGER.warn("SQL ERROR {}:{} {} {} ", new Object[] {
clientDDL, lineNo, ddl, e.getMessage() });
}
sqlStatement = new StringBuilder();
} else {
sqlStatement.append(line);
}
}
line = br.readLine();
lineNo++;
}
br.close();
LOGGER.info("Schema Created from {} ", clientDDL);
break;
} catch (Throwable e) {
LOGGER.error("Failed to load Schema from {}", clientDDL, e);
} finally {
try {
in.close();
} catch (IOException e) {
LOGGER.error("Failed to close stream from {}", clientDDL, e);
}
}
} else {
LOGGER.info("No Schema found at {} ", clientDDL);
}
}
} catch (SQLException e) {
LOGGER.info("Failed to create schema ", e);
throw new ClientPoolException("Failed to create schema ", e);
} finally {
try {
statement.close();
dec("schema");
} catch (Throwable e) {
LOGGER.debug("Failed to close statement in validate ", e);
}
}
}
public void activate() {
passivate = null;
}
public void passivate() {
disposeDisposables();
}
public Map<String, Object> streamBodyIn(String keySpace, String columnFamily, String contentId,
String contentBlockId, String streamId, Map<String, Object> content, InputStream in)
throws StorageClientException, AccessDeniedException, IOException {
checkClosed();
return streamedContentHelper.writeBody(keySpace, columnFamily, contentId, contentBlockId,
streamId, content, in);
}
public InputStream streamBodyOut(String keySpace, String columnFamily, String contentId,
String contentBlockId, String streamId, Map<String, Object> content)
throws StorageClientException, AccessDeniedException, IOException {
checkClosed();
final InputStream in = streamedContentHelper.readBody(keySpace, columnFamily,
contentBlockId, streamId, content);
if ( in != null ) {
registerDisposable(new Disposable() {
private boolean open = true;
public void close() {
if (open && in != null) {
try {
in.close();
} catch (IOException e) {
LOGGER.warn(e.getMessage(), e);
}
open = false;
}
}
});
}
return in;
}
public boolean hasBody(Map<String, Object> content, String streamId) {
return streamedContentHelper.hasStream(content, streamId);
}
protected Connection getConnection() throws StorageClientException, SQLException {
checkClosed();
return jcbcStorageClientConnection.getConnection();
}
public DisposableIterator<Map<String, Object>> listChildren(String keySpace, String columnFamily, String key) throws StorageClientException {
// this will load all child object directly.
String hash = rowHash(keySpace, columnFamily, key);
LOGGER.debug("Finding {}:{}:{} as {} ",new Object[]{keySpace,columnFamily, key, hash});
return find(keySpace, columnFamily, ImmutableMap.of(InternalContent.PARENT_HASH_FIELD, (Object)hash));
}
public DisposableIterator<Map<String,Object>> find(final String keySpace, final String columnFamily,
Map<String, Object> properties) throws StorageClientException {
checkClosed();
String[] keys = new String[] { "block-find." + keySpace + "." + columnFamily,
"block-find." + columnFamily, "block-find" };
String sql = null;
for (String statementKey : keys) {
sql = getSql(statementKey);
if (sql != null) {
break;
}
}
if (sql == null) {
throw new StorageClientException("Failed to locate SQL statement for any of "
+ Arrays.toString(keys));
}
String[] statementParts = StringUtils.split(sql, ';');
StringBuilder tables = new StringBuilder();
StringBuilder where = new StringBuilder();
StringBuilder order = new StringBuilder();
StringBuilder extraColumns = new StringBuilder();
// collect information on paging
long page = 0;
long items = 25;
if (properties != null) {
if (properties.containsKey("_page")) {
page = Long.valueOf(String.valueOf(properties.get("_page")));
}
if (properties.containsKey("_items")) {
items = Long.valueOf(String.valueOf(properties.get("_items")));
}
}
long offset = page * items;
// collect information on sorting
String[] sorts = new String[] { null, "asc" };
String _sortProp = (String) properties.get("_sort");
if (_sortProp != null) {
String[] _sorts = StringUtils.split(_sortProp);
if (_sorts.length == 1) {
sorts[0] = _sorts[0];
} else if (_sorts.length == 2) {
sorts[0] = _sorts[0];
sorts[1] = _sorts[1];
}
}
List<Object> parameters = Lists.newArrayList();
int set = 0;
for (Entry<String, Object> e : properties.entrySet()) {
Object v = e.getValue();
String k = e.getKey();
if ( shouldIndex(keySpace, columnFamily, k) || (v instanceof Map)) {
if (v != null) {
// check for a value map and treat sub terms as for OR terms.
// Only go 1 level deep; don't recurse. That's just silly.
if (v instanceof Map) {
// start the OR grouping
where.append(" (");
@SuppressWarnings("unchecked")
Set<Entry<String, Object>> subterms = ((Map<String, Object>) v).entrySet();
for(Iterator<Entry<String, Object>> subtermsIter = subterms.iterator(); subtermsIter.hasNext();) {
Entry<String, Object> subterm = subtermsIter.next();
String subk = subterm.getKey();
Object subv = subterm.getValue();
// check that each subterm should be indexed
if (shouldIndex(keySpace, columnFamily, subk)) {
set = processEntry(statementParts, tables, where, order, extraColumns, parameters, subk, subv, sorts, set);
// as long as there are more add OR
if (subtermsIter.hasNext()) {
where.append(" OR");
}
}
}
// end the OR grouping
where.append(") AND");
} else {
// process a first level non-map value as an AND term
if (v instanceof Iterable<?>) {
for (Object vo : (Iterable<?>)v) {
set = processEntry(statementParts, tables, where, order, extraColumns, parameters, k, vo, sorts, set);
where.append(" AND");
}
} else {
set = processEntry(statementParts, tables, where, order, extraColumns, parameters, k, v, sorts, set);
where.append(" AND");
}
}
} else if (!k.startsWith("_")) {
LOGGER.debug("Search on {}:{} filter dropped due to null value.", columnFamily, k);
}
} else {
if (!k.startsWith("_")) {
LOGGER.warn("Search on {}:{} is not supported, filter dropped ",columnFamily,k);
}
}
}
if (where.length() == 0) {
return new DisposableIterator<Map<String,Object>>() {
public boolean hasNext() {
return false;
}
public Map<String, Object> next() {
return null;
}
public void remove() {
}
public void close() {
}
};
}
if (sorts[0] != null && order.length() == 0) {
if (shouldIndex(keySpace, columnFamily, sorts[0])) {
String t = "a"+set;
if ( statementParts.length > STMT_EXTRA_COLUMNS ) {
extraColumns.append(MessageFormat.format(statementParts[STMT_EXTRA_COLUMNS], t));
}
tables.append(MessageFormat.format(statementParts[STMT_TABLE_JOIN], t));
parameters.add(sorts[0]);
where.append(MessageFormat.format(statementParts[STMT_WHERE_SORT], t)).append(" AND");
order.append(MessageFormat.format(statementParts[STMT_ORDER], t, sorts[1]));
} else {
LOGGER.warn("Sort on {}:{} is not supported, sort dropped", columnFamily,
sorts[0]);
}
}
final String sqlStatement = MessageFormat.format(statementParts[STMT_BASE],
tables.toString(), where.toString(), order.toString(), items, offset, extraColumns.toString());
PreparedStatement tpst = null;
ResultSet trs = null;
try {
LOGGER.debug("Preparing {} ", sqlStatement);
tpst = jcbcStorageClientConnection.getConnection().prepareStatement(sqlStatement);
inc("iterator");
tpst.clearParameters();
int i = 1;
for (Object params : parameters) {
tpst.setObject(i, params);
LOGGER.debug("Setting {} ", params);
i++;
}
long qtime = System.currentTimeMillis();
trs = tpst.executeQuery();
qtime = System.currentTimeMillis() - qtime;
if ( qtime > slowQueryThreshold && qtime < verySlowQueryThreshold) {
SQL_LOGGER.warn("Slow Query {}ms {} params:[{}]",new Object[]{qtime,sqlStatement,Arrays.toString(parameters.toArray(new String[parameters.size()]))});
} else if ( qtime > verySlowQueryThreshold ) {
SQL_LOGGER.error("Very Slow Query {}ms {} params:[{}]",new Object[]{qtime,sqlStatement,Arrays.toString(parameters.toArray(new String[parameters.size()]))});
}
inc("iterator r");
LOGGER.debug("Executed ");
// pass control to the iterator.
final PreparedStatement pst = tpst;
final ResultSet rs = trs;
tpst = null;
trs = null;
return registerDisposable(new PreemptiveIterator<Map<String, Object>>() {
private Map<String, Object> nextValue = Maps.newHashMap();
private boolean open = true;
@Override
protected Map<String, Object> internalNext() {
return nextValue;
}
@Override
protected boolean internalHasNext() {
try {
if (open && rs.next()) {
String id = rs.getString(1);
nextValue = internalGet(keySpace, columnFamily, id);
LOGGER.debug("Got Row ID {} {} ", id, nextValue);
return true;
}
close();
nextValue = null;
LOGGER.debug("End of Set ");
return false;
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
close();
nextValue = null;
return false;
} catch (StorageClientException e) {
LOGGER.error(e.getMessage(), e);
close();
nextValue = null;
return false;
}
}
@Override
public void close() {
if (open) {
open = false;
try {
if (rs != null) {
rs.close();
dec("iterator r");
}
} catch (SQLException e) {
LOGGER.warn(e.getMessage(), e);
}
try {
if (pst != null) {
pst.close();
dec("iterator");
}
} catch (SQLException e) {
LOGGER.warn(e.getMessage(), e);
}
}
}
});
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
throw new StorageClientException(e.getMessage() + " SQL Statement was " + sqlStatement,
e);
} finally {
// trs and tpst will only be non null if control has not been passed
// to the iterator.
try {
if (trs != null) {
trs.close();
dec("iterator r");
}
} catch (SQLException e) {
LOGGER.warn(e.getMessage(), e);
}
try {
if (tpst != null) {
tpst.close();
dec("iterator");
}
} catch (SQLException e) {
LOGGER.warn(e.getMessage(), e);
}
}
}
/**
* @param statementParts
* @param where
* @param params
* @param k
* @param v
* @param t
* @param conjunctionOr
*/
private int processEntry(String[] statementParts, StringBuilder tables,
StringBuilder where, StringBuilder order, StringBuilder extraColumns, List<Object> params, String k, Object v,
String[] sorts, int set) {
String t = "a" + set;
tables.append(MessageFormat.format(statementParts[STMT_TABLE_JOIN], t));
if (v instanceof Iterable<?>) {
for (Iterator<?> vi = ((Iterable<?>) v).iterator(); vi.hasNext();) {
Object viObj = vi.next();
params.add(k);
params.add(viObj);
where.append(" (").append(MessageFormat.format(statementParts[STMT_WHERE], t)).append(")");
// as long as there are more add OR
if (vi.hasNext()) {
where.append(" OR");
}
}
} else {
params.add(k);
params.add(v);
where.append(" (").append(MessageFormat.format(statementParts[STMT_WHERE], t)).append(")");
}
// add in sorting based on the table ref and value
if (k.equals(sorts[0])) {
order.append(MessageFormat.format(statementParts[STMT_ORDER], t, sorts[1]));
if ( statementParts.length > STMT_EXTRA_COLUMNS ) {
extraColumns.append(MessageFormat.format(statementParts[STMT_EXTRA_COLUMNS], t));
}
}
return set+1;
}
private void dec(String key) {
AtomicInteger cn = counters.get(key);
if (cn == null) {
LOGGER.warn("Never Statement/ResultSet Created Counter {} ", key);
} else {
cn.decrementAndGet();
}
}
private void inc(String key) {
AtomicInteger cn = counters.get(key);
if (cn == null) {
cn = new AtomicInteger();
counters.put(key, cn);
}
int c = cn.incrementAndGet();
if (c > 10) {
LOGGER.warn(
"Counter {} Leaking {}, please investigate. This will eventually cause an OOM Error. ",
key, c);
}
}
private void close(ResultSet rs, String name) {
try {
if (rs != null) {
rs.close();
dec(name);
}
} catch (Throwable e) {
LOGGER.debug("Failed to close result set, ok to ignore this message ", e);
}
}
private void close(PreparedStatement pst, String name) {
try {
if (pst != null) {
pst.close();
dec(name);
}
} catch (Throwable e) {
LOGGER.debug("Failed to close prepared set, ok to ignore this message ", e);
}
}
private void close(Map<String, PreparedStatement> statementCache) {
for (PreparedStatement pst : statementCache.values()) {
if (pst != null) {
try {
pst.close();
dec("cachedStatement");
} catch (SQLException e) {
LOGGER.debug(e.getMessage(), e);
}
}
}
}
}
| false | true | public void insert(String keySpace, String columnFamily, String key, Map<String, Object> values, boolean probablyNew)
throws StorageClientException {
checkClosed();
Map<String, PreparedStatement> statementCache = Maps.newHashMap();
boolean autoCommit = true;
try {
autoCommit = startBlock();
String rid = rowHash(keySpace, columnFamily, key);
for (Entry<String, Object> e : values.entrySet()) {
String k = e.getKey();
Object o = e.getValue();
if (o instanceof byte[]) {
throw new RuntimeException("Invalid content in " + k
+ ", storing byte[] rather than streaming it");
}
}
Map<String, Object> m = get(keySpace, columnFamily, key);
for (Entry<String, Object> e : values.entrySet()) {
String k = e.getKey();
Object o = e.getValue();
if (o instanceof RemoveProperty || o == null) {
m.remove(k);
} else {
m.put(k, o);
}
}
LOGGER.debug("Saving {} {} {} ", new Object[]{key, rid, m});
if ( probablyNew ) {
PreparedStatement insertBlockRow = getStatement(keySpace, columnFamily,
SQL_BLOCK_INSERT_ROW, rid, statementCache);
insertBlockRow.clearWarnings();
insertBlockRow.clearParameters();
insertBlockRow.setString(1, rid);
InputStream insertStream = null;
try {
insertStream = Types.storeMapToStream(rid, m, columnFamily);
} catch (UTFDataFormatException e) {
throw new DataFormatException(INVALID_DATA_ERROR, e);
}
if ("1.5".equals(getSql(JDBC_SUPPORT_LEVEL))) {
insertBlockRow.setBinaryStream(2, insertStream, insertStream.available());
} else {
insertBlockRow.setBinaryStream(2, insertStream);
}
int rowsInserted = 0;
try {
rowsInserted = insertBlockRow.executeUpdate();
} catch ( SQLException e ) {
LOGGER.debug(e.getMessage(),e);
}
if ( rowsInserted == 0 ) {
PreparedStatement updateBlockRow = getStatement(keySpace, columnFamily,
SQL_BLOCK_UPDATE_ROW, rid, statementCache);
updateBlockRow.clearWarnings();
updateBlockRow.clearParameters();
updateBlockRow.setString(2, rid);
try {
insertStream = Types.storeMapToStream(rid, m, columnFamily);
} catch (UTFDataFormatException e) {
throw new DataFormatException(INVALID_DATA_ERROR, e);
}
if ("1.5".equals(getSql(JDBC_SUPPORT_LEVEL))) {
updateBlockRow.setBinaryStream(1, insertStream, insertStream.available());
} else {
updateBlockRow.setBinaryStream(1, insertStream);
}
if( updateBlockRow.executeUpdate() == 0) {
throw new StorageClientException("Failed to save " + rid);
} else {
LOGGER.debug("Updated {} ", rid);
}
} else {
LOGGER.debug("Inserted {} ", rid);
}
} else {
PreparedStatement updateBlockRow = getStatement(keySpace, columnFamily,
SQL_BLOCK_UPDATE_ROW, rid, statementCache);
updateBlockRow.clearWarnings();
updateBlockRow.clearParameters();
updateBlockRow.setString(2, rid);
InputStream updateStream = null;
try {
updateStream = Types.storeMapToStream(rid, m, columnFamily);
} catch (UTFDataFormatException e) {
throw new DataFormatException(INVALID_DATA_ERROR, e);
}
if ("1.5".equals(getSql(JDBC_SUPPORT_LEVEL))) {
updateBlockRow.setBinaryStream(1, updateStream, updateStream.available());
} else {
updateBlockRow.setBinaryStream(1, updateStream);
}
if (updateBlockRow.executeUpdate() == 0) {
PreparedStatement insertBlockRow = getStatement(keySpace, columnFamily,
SQL_BLOCK_INSERT_ROW, rid, statementCache);
insertBlockRow.clearWarnings();
insertBlockRow.clearParameters();
insertBlockRow.setString(1, rid);
try {
updateStream = Types.storeMapToStream(rid, m, columnFamily);
} catch (UTFDataFormatException e) {
throw new DataFormatException(INVALID_DATA_ERROR, e);
}
if ("1.5".equals(getSql(JDBC_SUPPORT_LEVEL))) {
insertBlockRow.setBinaryStream(2, updateStream, updateStream.available());
} else {
insertBlockRow.setBinaryStream(2, updateStream);
}
if (insertBlockRow.executeUpdate() == 0) {
throw new StorageClientException("Failed to save " + rid);
} else {
LOGGER.debug("Inserted {} ", rid);
}
} else {
LOGGER.debug("Updated {} ", rid);
}
}
if ("1".equals(getSql(USE_BATCH_INSERTS))) {
Set<PreparedStatement> updateSet = Sets.newHashSet();
Map<PreparedStatement, List<Entry<String, Object>>> updateSequence = Maps
.newHashMap();
Set<PreparedStatement> removeSet = Sets.newHashSet();
// execute the updates and add the necessary inserts.
Map<PreparedStatement, List<Entry<String, Object>>> insertSequence = Maps
.newHashMap();
Set<PreparedStatement> insertSet = Sets.newHashSet();
for (Entry<String, Object> e : values.entrySet()) {
String k = e.getKey();
Object o = e.getValue();
if (shouldIndex(keySpace, columnFamily, k)) {
if ( o instanceof RemoveProperty || o == null ) {
PreparedStatement removeStringColumn = getStatement(keySpace,
columnFamily, SQL_REMOVE_STRING_COLUMN, rid, statementCache);
removeStringColumn.setString(1, rid);
removeStringColumn.setString(2, k);
removeStringColumn.addBatch();
removeSet.add(removeStringColumn);
} else {
// remove all previous values
PreparedStatement removeStringColumn = getStatement(keySpace,
columnFamily, SQL_REMOVE_STRING_COLUMN, rid, statementCache);
removeStringColumn.setString(1, rid);
removeStringColumn.setString(2, k);
removeStringColumn.addBatch();
removeSet.add(removeStringColumn);
// insert new values, as we just removed them we know we can insert, no need to attempt update
// the only thing that we know is the colum value changes so we have to re-index the whole
// property
Object[] valueMembers = (o instanceof Object[]) ? (Object[]) o : new Object[] { o };
for (Object ov : valueMembers) {
String valueMember = ov.toString();
PreparedStatement insertStringColumn = getStatement(keySpace,
columnFamily, SQL_INSERT_STRING_COLUMN, rid, statementCache);
insertStringColumn.setString(1, valueMember);
insertStringColumn.setString(2, rid);
insertStringColumn.setString(3, k);
insertStringColumn.addBatch();
LOGGER.debug("Insert Index {} {}", k, valueMember);
insertSet.add(insertStringColumn);
List<Entry<String, Object>> insertSeq = insertSequence
.get(insertStringColumn);
if (insertSeq == null) {
insertSeq = Lists.newArrayList();
insertSequence.put(insertStringColumn, insertSeq);
}
insertSeq.add(e);
}
}
}
}
if ( !StorageClientUtils.isRoot(key)) {
// create a holding map containing a rowhash of the parent and then process the entry to generate a update operation.
Map<String, Object> autoIndexMap = ImmutableMap.of(InternalContent.PARENT_HASH_FIELD, (Object)rowHash(keySpace, columnFamily, StorageClientUtils.getParentObjectPath(key)));
for ( Entry<String, Object> e : autoIndexMap.entrySet()) {
PreparedStatement updateStringColumn = getStatement(keySpace,
columnFamily, SQL_UPDATE_STRING_COLUMN, rid, statementCache);
updateStringColumn.setString(1, (String)e.getValue());
updateStringColumn.setString(2, rid);
updateStringColumn.setString(3, e.getKey());
updateStringColumn.addBatch();
LOGGER.debug("Update {} {}", e.getKey(), e.getValue());
updateSet.add(updateStringColumn);
List<Entry<String, Object>> updateSeq = updateSequence
.get(updateStringColumn);
if (updateSeq == null) {
updateSeq = Lists.newArrayList();
updateSequence.put(updateStringColumn, updateSeq);
}
updateSeq.add(e);
}
}
LOGGER.debug("Remove set {}", removeSet);
for (PreparedStatement pst : removeSet) {
pst.executeBatch();
}
LOGGER.debug("Update set {}", updateSet);
for (PreparedStatement pst : updateSet) {
int[] res = pst.executeBatch();
List<Entry<String, Object>> updateSeq = updateSequence.get(pst);
for (int i = 0; i < res.length; i++) {
Entry<String, Object> e = updateSeq.get(i);
if (res[i] <= 0) {
String k = e.getKey();
Object o = e.getValue();
Object[] valueMembers = (o instanceof Object[]) ? (Object[]) o : new Object[] { o };
for (Object ov : valueMembers) {
String valueMember = ov.toString();
PreparedStatement insertStringColumn = getStatement(keySpace,
columnFamily, SQL_INSERT_STRING_COLUMN, rid, statementCache);
insertStringColumn.setString(1, valueMember);
insertStringColumn.setString(2, rid);
insertStringColumn.setString(3, k);
insertStringColumn.addBatch();
LOGGER.debug("Insert Index {} {}", k, valueMember);
insertSet.add(insertStringColumn);
List<Entry<String, Object>> insertSeq = insertSequence
.get(insertStringColumn);
if (insertSeq == null) {
insertSeq = Lists.newArrayList();
insertSequence.put(insertStringColumn, insertSeq);
}
insertSeq.add(e);
}
} else {
LOGGER.debug("Index updated for {} {} ", new Object[] { rid, e.getKey(),
e.getValue() });
}
}
}
LOGGER.debug("Insert set {}", insertSet);
for (PreparedStatement pst : insertSet) {
int[] res = pst.executeBatch();
List<Entry<String, Object>> insertSeq = insertSequence.get(pst);
for (int i = 0; i < res.length; i++ ) {
Entry<String, Object> e = insertSeq.get(i);
if ( res[i] <= 0 ) {
LOGGER.warn("Index failed for {} {} ", new Object[] { rid, e.getKey(),
e.getValue() });
} else {
LOGGER.debug("Index inserted for {} {} ", new Object[] { rid, e.getKey(),
e.getValue() });
}
}
}
} else {
for (Entry<String, Object> e : values.entrySet()) {
String k = e.getKey();
Object o = e.getValue();
if (shouldIndex(keySpace, columnFamily, k)) {
if (o instanceof RemoveProperty || o == null) {
PreparedStatement removeStringColumn = getStatement(keySpace,
columnFamily, SQL_REMOVE_STRING_COLUMN, rid, statementCache);
removeStringColumn.clearWarnings();
removeStringColumn.clearParameters();
removeStringColumn.setString(1, rid);
removeStringColumn.setString(2, k);
int nrows = removeStringColumn.executeUpdate();
if (nrows == 0) {
m = get(keySpace, columnFamily, key);
LOGGER.debug(
"Column Not present did not remove {} {} Current Column:{} ",
new Object[] { getRowId(keySpace, columnFamily, key), k, m });
} else {
LOGGER.debug("Removed Index {} {} {} ",
new Object[]{getRowId(keySpace, columnFamily, key), k, nrows});
}
} else {
PreparedStatement removeStringColumn = getStatement(keySpace,
columnFamily, SQL_REMOVE_STRING_COLUMN, rid, statementCache);
removeStringColumn.clearWarnings();
removeStringColumn.clearParameters();
removeStringColumn.setString(1, rid);
removeStringColumn.setString(2, k);
int nrows = removeStringColumn.executeUpdate();
if (nrows == 0) {
m = get(keySpace, columnFamily, key);
LOGGER.debug(
"Column Not present did not remove {} {} Current Column:{} ",
new Object[] { getRowId(keySpace, columnFamily, key), k, m });
} else {
LOGGER.debug("Removed Index {} {} {} ",
new Object[]{getRowId(keySpace, columnFamily, key), k, nrows});
}
Object[] os = (o instanceof Object[]) ? (Object[]) o : new Object[] { o };
for (Object ov : os) {
String v = ov.toString();
PreparedStatement insertStringColumn = getStatement(keySpace,
columnFamily, SQL_INSERT_STRING_COLUMN, rid, statementCache);
insertStringColumn.clearWarnings();
insertStringColumn.clearParameters();
insertStringColumn.setString(1, v);
insertStringColumn.setString(2, rid);
insertStringColumn.setString(3, k);
LOGGER.debug("Non Batch Insert Index {} {}", k, v);
if (insertStringColumn.executeUpdate() == 0) {
throw new StorageClientException("Failed to save "
+ getRowId(keySpace, columnFamily, key) + " column:["
+ k + "] ");
} else {
LOGGER.debug("Inserted Index {} {} [{}]",
new Object[] { getRowId(keySpace, columnFamily, key),
k, v });
}
}
}
}
}
if ( !StorageClientUtils.isRoot(key)) {
String parent = StorageClientUtils.getParentObjectPath(key);
String hash = rowHash(keySpace, columnFamily, parent);
LOGGER.debug("Hash of {}:{}:{} is {} ",new Object[]{keySpace, columnFamily, parent, hash});
Map<String, Object> autoIndexMap = ImmutableMap.of(InternalContent.PARENT_HASH_FIELD, (Object)hash);
for ( Entry<String, Object> e : autoIndexMap.entrySet()) {
PreparedStatement updateStringColumn = getStatement(keySpace,
columnFamily, SQL_UPDATE_STRING_COLUMN, rid, statementCache);
updateStringColumn.clearWarnings();
updateStringColumn.clearParameters();
updateStringColumn.setString(1, (String) e.getValue());
updateStringColumn.setString(2, rid);
updateStringColumn.setString(3, e.getKey());
if (updateStringColumn.executeUpdate() == 0) {
PreparedStatement insertStringColumn = getStatement(keySpace,
columnFamily, SQL_INSERT_STRING_COLUMN, rid, statementCache);
insertStringColumn.clearWarnings();
insertStringColumn.clearParameters();
insertStringColumn.setString(1, (String) e.getValue());
insertStringColumn.setString(2, rid);
insertStringColumn.setString(3, e.getKey());
if (insertStringColumn.executeUpdate() == 0) {
throw new StorageClientException("Failed to save "
+ getRowId(keySpace, columnFamily, key) + " column:["
+ e.getKey() + "] ");
} else {
LOGGER.debug("Inserted Index {} {} [{}]",
new Object[] { getRowId(keySpace, columnFamily, key),
e.getKey(), e.getValue() });
}
} else {
LOGGER.debug(
"Updated Index {} {} [{}]",
new Object[] { getRowId(keySpace, columnFamily, key), e.getKey(), e.getValue() });
}
}
}
}
endBlock(autoCommit);
} catch (SQLException e) {
abandonBlock(autoCommit);
LOGGER.warn("Failed to perform insert/update operation on {}:{}:{} ", new Object[] {
keySpace, columnFamily, key }, e);
throw new StorageClientException(e.getMessage(), e);
} catch (IOException e) {
abandonBlock(autoCommit);
LOGGER.warn("Failed to perform insert/update operation on {}:{}:{} ", new Object[] {
keySpace, columnFamily, key }, e);
throw new StorageClientException(e.getMessage(), e);
} finally {
close(statementCache);
}
}
| public void insert(String keySpace, String columnFamily, String key, Map<String, Object> values, boolean probablyNew)
throws StorageClientException {
checkClosed();
Map<String, PreparedStatement> statementCache = Maps.newHashMap();
boolean autoCommit = true;
try {
autoCommit = startBlock();
String rid = rowHash(keySpace, columnFamily, key);
for (Entry<String, Object> e : values.entrySet()) {
String k = e.getKey();
Object o = e.getValue();
if (o instanceof byte[]) {
throw new RuntimeException("Invalid content in " + k
+ ", storing byte[] rather than streaming it");
}
}
Map<String, Object> m = get(keySpace, columnFamily, key);
for (Entry<String, Object> e : values.entrySet()) {
String k = e.getKey();
Object o = e.getValue();
if (o instanceof RemoveProperty || o == null) {
m.remove(k);
} else {
m.put(k, o);
}
}
LOGGER.debug("Saving {} {} {} ", new Object[]{key, rid, m});
if ( probablyNew ) {
PreparedStatement insertBlockRow = getStatement(keySpace, columnFamily,
SQL_BLOCK_INSERT_ROW, rid, statementCache);
insertBlockRow.clearWarnings();
insertBlockRow.clearParameters();
insertBlockRow.setString(1, rid);
InputStream insertStream = null;
try {
insertStream = Types.storeMapToStream(rid, m, columnFamily);
} catch (UTFDataFormatException e) {
throw new DataFormatException(INVALID_DATA_ERROR, e);
}
if ("1.5".equals(getSql(JDBC_SUPPORT_LEVEL))) {
insertBlockRow.setBinaryStream(2, insertStream, insertStream.available());
} else {
insertBlockRow.setBinaryStream(2, insertStream);
}
int rowsInserted = 0;
try {
rowsInserted = insertBlockRow.executeUpdate();
} catch ( SQLException e ) {
LOGGER.debug(e.getMessage(),e);
}
if ( rowsInserted == 0 ) {
PreparedStatement updateBlockRow = getStatement(keySpace, columnFamily,
SQL_BLOCK_UPDATE_ROW, rid, statementCache);
updateBlockRow.clearWarnings();
updateBlockRow.clearParameters();
updateBlockRow.setString(2, rid);
try {
insertStream = Types.storeMapToStream(rid, m, columnFamily);
} catch (UTFDataFormatException e) {
throw new DataFormatException(INVALID_DATA_ERROR, e);
}
if ("1.5".equals(getSql(JDBC_SUPPORT_LEVEL))) {
updateBlockRow.setBinaryStream(1, insertStream, insertStream.available());
} else {
updateBlockRow.setBinaryStream(1, insertStream);
}
if( updateBlockRow.executeUpdate() == 0) {
throw new StorageClientException("Failed to save " + rid);
} else {
LOGGER.debug("Updated {} ", rid);
}
} else {
LOGGER.debug("Inserted {} ", rid);
}
} else {
PreparedStatement updateBlockRow = getStatement(keySpace, columnFamily,
SQL_BLOCK_UPDATE_ROW, rid, statementCache);
updateBlockRow.clearWarnings();
updateBlockRow.clearParameters();
updateBlockRow.setString(2, rid);
InputStream updateStream = null;
try {
updateStream = Types.storeMapToStream(rid, m, columnFamily);
} catch (UTFDataFormatException e) {
throw new DataFormatException(INVALID_DATA_ERROR, e);
}
if ("1.5".equals(getSql(JDBC_SUPPORT_LEVEL))) {
updateBlockRow.setBinaryStream(1, updateStream, updateStream.available());
} else {
updateBlockRow.setBinaryStream(1, updateStream);
}
if (updateBlockRow.executeUpdate() == 0) {
PreparedStatement insertBlockRow = getStatement(keySpace, columnFamily,
SQL_BLOCK_INSERT_ROW, rid, statementCache);
insertBlockRow.clearWarnings();
insertBlockRow.clearParameters();
insertBlockRow.setString(1, rid);
try {
updateStream = Types.storeMapToStream(rid, m, columnFamily);
} catch (UTFDataFormatException e) {
throw new DataFormatException(INVALID_DATA_ERROR, e);
}
if ("1.5".equals(getSql(JDBC_SUPPORT_LEVEL))) {
insertBlockRow.setBinaryStream(2, updateStream, updateStream.available());
} else {
insertBlockRow.setBinaryStream(2, updateStream);
}
if (insertBlockRow.executeUpdate() == 0) {
throw new StorageClientException("Failed to save " + rid);
} else {
LOGGER.debug("Inserted {} ", rid);
}
} else {
LOGGER.debug("Updated {} ", rid);
}
}
if ("1".equals(getSql(USE_BATCH_INSERTS))) {
Set<PreparedStatement> updateSet = Sets.newHashSet();
Map<PreparedStatement, List<Entry<String, Object>>> updateSequence = Maps
.newHashMap();
Set<PreparedStatement> removeSet = Sets.newHashSet();
// execute the updates and add the necessary inserts.
Map<PreparedStatement, List<Entry<String, Object>>> insertSequence = Maps
.newHashMap();
Set<PreparedStatement> insertSet = Sets.newHashSet();
for (Entry<String, Object> e : values.entrySet()) {
String k = e.getKey();
Object o = e.getValue();
if (shouldIndex(keySpace, columnFamily, k)) {
if ( o instanceof RemoveProperty || o == null ) {
PreparedStatement removeStringColumn = getStatement(keySpace,
columnFamily, SQL_REMOVE_STRING_COLUMN, rid, statementCache);
removeStringColumn.setString(1, rid);
removeStringColumn.setString(2, k);
removeStringColumn.addBatch();
removeSet.add(removeStringColumn);
} else {
// remove all previous values
PreparedStatement removeStringColumn = getStatement(keySpace,
columnFamily, SQL_REMOVE_STRING_COLUMN, rid, statementCache);
removeStringColumn.setString(1, rid);
removeStringColumn.setString(2, k);
removeStringColumn.addBatch();
removeSet.add(removeStringColumn);
// insert new values, as we just removed them we know we can insert, no need to attempt update
// the only thing that we know is the colum value changes so we have to re-index the whole
// property
Object[] valueMembers = (o instanceof Object[]) ? (Object[]) o : new Object[] { o };
for (Object ov : valueMembers) {
String valueMember = ov.toString();
PreparedStatement insertStringColumn = getStatement(keySpace,
columnFamily, SQL_INSERT_STRING_COLUMN, rid, statementCache);
insertStringColumn.setString(1, valueMember);
insertStringColumn.setString(2, rid);
insertStringColumn.setString(3, k);
insertStringColumn.addBatch();
LOGGER.debug("Insert Index {} {}", k, valueMember);
insertSet.add(insertStringColumn);
List<Entry<String, Object>> insertSeq = insertSequence
.get(insertStringColumn);
if (insertSeq == null) {
insertSeq = Lists.newArrayList();
insertSequence.put(insertStringColumn, insertSeq);
}
insertSeq.add(e);
}
}
}
}
if ( !StorageClientUtils.isRoot(key)) {
// create a holding map containing a rowhash of the parent and then process the entry to generate a update operation.
Map<String, Object> autoIndexMap = ImmutableMap.of(InternalContent.PARENT_HASH_FIELD, (Object)rowHash(keySpace, columnFamily, StorageClientUtils.getParentObjectPath(key)));
for ( Entry<String, Object> e : autoIndexMap.entrySet()) {
PreparedStatement updateStringColumn = getStatement(keySpace,
columnFamily, SQL_UPDATE_STRING_COLUMN, rid, statementCache);
updateStringColumn.setString(1, (String)e.getValue());
updateStringColumn.setString(2, rid);
updateStringColumn.setString(3, e.getKey());
updateStringColumn.addBatch();
LOGGER.debug("Update {} {}", e.getKey(), e.getValue());
updateSet.add(updateStringColumn);
List<Entry<String, Object>> updateSeq = updateSequence
.get(updateStringColumn);
if (updateSeq == null) {
updateSeq = Lists.newArrayList();
updateSequence.put(updateStringColumn, updateSeq);
}
updateSeq.add(e);
}
}
LOGGER.debug("Remove set {}", removeSet);
for (PreparedStatement pst : removeSet) {
pst.executeBatch();
}
LOGGER.debug("Update set {}", updateSet);
for (PreparedStatement pst : updateSet) {
int[] res = pst.executeBatch();
List<Entry<String, Object>> updateSeq = updateSequence.get(pst);
for (int i = 0; i < res.length; i++) {
Entry<String, Object> e = updateSeq.get(i);
if (res[i] <= 0 && res[i] != -2 ) { // Oracle Drivers respond with -2 on success if the exact number updated is not known. http://download.oracle.com/javase/1.3/docs/guide/jdbc/spec2/jdbc2.1.frame6.html
String k = e.getKey();
Object o = e.getValue();
Object[] valueMembers = (o instanceof Object[]) ? (Object[]) o : new Object[] { o };
for (Object ov : valueMembers) {
String valueMember = ov.toString();
PreparedStatement insertStringColumn = getStatement(keySpace,
columnFamily, SQL_INSERT_STRING_COLUMN, rid, statementCache);
insertStringColumn.setString(1, valueMember);
insertStringColumn.setString(2, rid);
insertStringColumn.setString(3, k);
insertStringColumn.addBatch();
LOGGER.debug("Insert Index {} {}", k, valueMember);
insertSet.add(insertStringColumn);
List<Entry<String, Object>> insertSeq = insertSequence
.get(insertStringColumn);
if (insertSeq == null) {
insertSeq = Lists.newArrayList();
insertSequence.put(insertStringColumn, insertSeq);
}
insertSeq.add(e);
}
} else {
LOGGER.debug("Index updated for {} {} ", new Object[] { rid, e.getKey(),
e.getValue() });
}
}
}
LOGGER.debug("Insert set {}", insertSet);
for (PreparedStatement pst : insertSet) {
int[] res = pst.executeBatch();
List<Entry<String, Object>> insertSeq = insertSequence.get(pst);
for (int i = 0; i < res.length; i++ ) {
Entry<String, Object> e = insertSeq.get(i);
if ( res[i] <= 0 && res[i] != -2 ) { // Oracle drivers respond with -2 on a successful insert when the number is not known http://download.oracle.com/javase/1.3/docs/guide/jdbc/spec2/jdbc2.1.frame6.html
LOGGER.warn("Index failed for {} {} ", new Object[] { rid, e.getKey(),
e.getValue() });
} else {
LOGGER.debug("Index inserted for {} {} ", new Object[] { rid, e.getKey(),
e.getValue() });
}
}
}
} else {
for (Entry<String, Object> e : values.entrySet()) {
String k = e.getKey();
Object o = e.getValue();
if (shouldIndex(keySpace, columnFamily, k)) {
if (o instanceof RemoveProperty || o == null) {
PreparedStatement removeStringColumn = getStatement(keySpace,
columnFamily, SQL_REMOVE_STRING_COLUMN, rid, statementCache);
removeStringColumn.clearWarnings();
removeStringColumn.clearParameters();
removeStringColumn.setString(1, rid);
removeStringColumn.setString(2, k);
int nrows = removeStringColumn.executeUpdate();
if (nrows == 0) {
m = get(keySpace, columnFamily, key);
LOGGER.debug(
"Column Not present did not remove {} {} Current Column:{} ",
new Object[] { getRowId(keySpace, columnFamily, key), k, m });
} else {
LOGGER.debug("Removed Index {} {} {} ",
new Object[]{getRowId(keySpace, columnFamily, key), k, nrows});
}
} else {
PreparedStatement removeStringColumn = getStatement(keySpace,
columnFamily, SQL_REMOVE_STRING_COLUMN, rid, statementCache);
removeStringColumn.clearWarnings();
removeStringColumn.clearParameters();
removeStringColumn.setString(1, rid);
removeStringColumn.setString(2, k);
int nrows = removeStringColumn.executeUpdate();
if (nrows == 0) {
m = get(keySpace, columnFamily, key);
LOGGER.debug(
"Column Not present did not remove {} {} Current Column:{} ",
new Object[] { getRowId(keySpace, columnFamily, key), k, m });
} else {
LOGGER.debug("Removed Index {} {} {} ",
new Object[]{getRowId(keySpace, columnFamily, key), k, nrows});
}
Object[] os = (o instanceof Object[]) ? (Object[]) o : new Object[] { o };
for (Object ov : os) {
String v = ov.toString();
PreparedStatement insertStringColumn = getStatement(keySpace,
columnFamily, SQL_INSERT_STRING_COLUMN, rid, statementCache);
insertStringColumn.clearWarnings();
insertStringColumn.clearParameters();
insertStringColumn.setString(1, v);
insertStringColumn.setString(2, rid);
insertStringColumn.setString(3, k);
LOGGER.debug("Non Batch Insert Index {} {}", k, v);
if (insertStringColumn.executeUpdate() == 0) {
throw new StorageClientException("Failed to save "
+ getRowId(keySpace, columnFamily, key) + " column:["
+ k + "] ");
} else {
LOGGER.debug("Inserted Index {} {} [{}]",
new Object[] { getRowId(keySpace, columnFamily, key),
k, v });
}
}
}
}
}
if ( !StorageClientUtils.isRoot(key)) {
String parent = StorageClientUtils.getParentObjectPath(key);
String hash = rowHash(keySpace, columnFamily, parent);
LOGGER.debug("Hash of {}:{}:{} is {} ",new Object[]{keySpace, columnFamily, parent, hash});
Map<String, Object> autoIndexMap = ImmutableMap.of(InternalContent.PARENT_HASH_FIELD, (Object)hash);
for ( Entry<String, Object> e : autoIndexMap.entrySet()) {
PreparedStatement updateStringColumn = getStatement(keySpace,
columnFamily, SQL_UPDATE_STRING_COLUMN, rid, statementCache);
updateStringColumn.clearWarnings();
updateStringColumn.clearParameters();
updateStringColumn.setString(1, (String) e.getValue());
updateStringColumn.setString(2, rid);
updateStringColumn.setString(3, e.getKey());
if (updateStringColumn.executeUpdate() == 0) {
PreparedStatement insertStringColumn = getStatement(keySpace,
columnFamily, SQL_INSERT_STRING_COLUMN, rid, statementCache);
insertStringColumn.clearWarnings();
insertStringColumn.clearParameters();
insertStringColumn.setString(1, (String) e.getValue());
insertStringColumn.setString(2, rid);
insertStringColumn.setString(3, e.getKey());
if (insertStringColumn.executeUpdate() == 0) {
throw new StorageClientException("Failed to save "
+ getRowId(keySpace, columnFamily, key) + " column:["
+ e.getKey() + "] ");
} else {
LOGGER.debug("Inserted Index {} {} [{}]",
new Object[] { getRowId(keySpace, columnFamily, key),
e.getKey(), e.getValue() });
}
} else {
LOGGER.debug(
"Updated Index {} {} [{}]",
new Object[] { getRowId(keySpace, columnFamily, key), e.getKey(), e.getValue() });
}
}
}
}
endBlock(autoCommit);
} catch (SQLException e) {
abandonBlock(autoCommit);
LOGGER.warn("Failed to perform insert/update operation on {}:{}:{} ", new Object[] {
keySpace, columnFamily, key }, e);
throw new StorageClientException(e.getMessage(), e);
} catch (IOException e) {
abandonBlock(autoCommit);
LOGGER.warn("Failed to perform insert/update operation on {}:{}:{} ", new Object[] {
keySpace, columnFamily, key }, e);
throw new StorageClientException(e.getMessage(), e);
} finally {
close(statementCache);
}
}
|
diff --git a/overwatch/src/overwatch/db/Database.java b/overwatch/src/overwatch/db/Database.java
index 4298835..72f365f 100644
--- a/overwatch/src/overwatch/db/Database.java
+++ b/overwatch/src/overwatch/db/Database.java
@@ -1,272 +1,274 @@
package overwatch.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Provides basic global database functions.
*
* @author Lee Coakley
* @version 3
*/
public class Database
{
private static final ConnectionPool connPool = new ConnectionPool( 6, true );
/**
* Start making connections to the database.
* For the moment, this is automatic and doesn't need to be used.
*/
public static void connect() {
connPool.start();
}
/**
* Disconnect from the database.
* Closes all connections and cleans up resources.
*/
public static void disconnect() {
connPool.stop();
}
/**
* Check if the pool has an unused connection ready.
* Informational -
* @return status
* @see ConnectionPool
*/
public static boolean hasConnection() {
return connPool.getConnectionCount() > 0;
}
/**
* Get a database connection from the pool.
* Return it when finished!
* @return Connection
* @see ConnectionPool
*/
public static Connection getConnection() {
return connPool.getConnection();
}
/**
* Return a database connection to the pool so it can be reused.
* @param conn
* @see ConnectionPool
*/
public static void returnConnection( Connection conn ) {
connPool.returnConnection( conn );
}
/**
* Run an SQL query that yields a single set of integers.
* @param sql
* @return Integer[]
*/
public static Integer[] queryInts( String sql ) {
return query(sql).getColumnAs( 0, Integer[].class );
}
/**
* Run a query, get an EnhancedResultSet.
* Handles cleanup and conversion automatically.
* @param ps
* @return EnhancedResultSet
* @throws SQLException
*/
public static EnhancedResultSet query( PreparedStatement ps )
{
EnhancedResultSet ers = null;
try {
ResultSet rs = ps.executeQuery();
ers = new EnhancedResultSet( rs );
rs.close();
}
catch( SQLException ex) {
throw new RuntimeException( ex );
}
return ers;
}
/**
* Run a query, get an EnhancedResultSet.
* Handles cleanup and conversion automatically.
* @param sql
* @return EnhancedResultSet
*/
public static EnhancedResultSet query( String sql )
{
Connection conn = getConnection();
EnhancedResultSet ers = null;
try {
Statement st = conn.createStatement();
- ers = new EnhancedResultSet( st.executeQuery(sql) );
+ ResultSet rs = st.executeQuery( sql );
+ ers = new EnhancedResultSet( rs );
+ rs.close();
st.close();
}
catch (SQLException ex) {
throw new RuntimeException( ex );
}
returnConnection( conn );
return ers;
}
/**
* Dump the contents of an entire table into an EnhancedResultSet.
* @param tableName
* @return EnhancedResultSet
*/
public EnhancedResultSet dumpTable( String tableName ) {
return query( "SELECT * FROM " + tableName + ";" );
}
/**
* Run update/insert/delete SQL and get back the number of rows modified.
* @param sql
* @return number rows modified
*/
public static int update( String sql )
{
int rowsModified = -1;
Connection conn = getConnection();
try {
Statement st = conn.createStatement();
rowsModified = st.executeUpdate( sql );
st.close();
}
catch (SQLException ex) {
throw new RuntimeException( ex );
}
returnConnection( conn );
return rowsModified;
}
}
| true | true | public static EnhancedResultSet query( String sql )
{
Connection conn = getConnection();
EnhancedResultSet ers = null;
try {
Statement st = conn.createStatement();
ers = new EnhancedResultSet( st.executeQuery(sql) );
st.close();
}
catch (SQLException ex) {
throw new RuntimeException( ex );
}
returnConnection( conn );
return ers;
}
| public static EnhancedResultSet query( String sql )
{
Connection conn = getConnection();
EnhancedResultSet ers = null;
try {
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery( sql );
ers = new EnhancedResultSet( rs );
rs.close();
st.close();
}
catch (SQLException ex) {
throw new RuntimeException( ex );
}
returnConnection( conn );
return ers;
}
|
diff --git a/Camml/camml/test/core/models/dTree/TestMLDTreeLearner.java b/Camml/camml/test/core/models/dTree/TestMLDTreeLearner.java
index 9221b4d..1a30053 100644
--- a/Camml/camml/test/core/models/dTree/TestMLDTreeLearner.java
+++ b/Camml/camml/test/core/models/dTree/TestMLDTreeLearner.java
@@ -1,92 +1,92 @@
//
//JUnit test routines for DTreeGenerator model
//
//Copyright (C) 2005 Rodney O'Donnell. All Rights Reserved.
//
//Source formatted to 100 columns.
//4567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
package camml.test.core.models.dTree;
import java.util.Random;
import weka.core.WeightedInstancesHandler;
import junit.framework.*;
import camml.core.library.SelectedVector;
import camml.core.models.cpt.CPTLearner;
import camml.core.models.dTree.*;
import camml.core.search.SearchDataCreator;
import camml.plugin.weka.Weka;
import cdms.core.*;
/**
* @author rodo
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class TestMLDTreeLearner extends TestCase {
/** BNet model used in testing*/
protected static DTree model;
/** Parameters corresponding to model */
protected static Value.Vector params;
/** */
public TestMLDTreeLearner() { super(); }
/** */
public TestMLDTreeLearner(String name) { super(name); }
public static Test suite()
{
return new TestSuite( TestMLDTreeLearner.class );
}
/** Initialise. */
protected void setUp() throws Exception {
}
/** Ensure that Max LH CPT and DTree models return the same answer. */
public final void testMLTreeVsCPT2() throws Exception {
Random r = new Random(123);
Value.Vector data30 = SearchDataCreator.generateWallaceKorbStyleDataset(r,1000,20,1,1);
for (int ii = 0; ii < 15; ii++) {
Value.Vector x = data30.cmpnt(0);
int[] cmpnts = new int[ii];
for (int i = 0; i < cmpnts.length; i++) { cmpnts[i] = i+1;}
Value.Vector z = new SelectedVector(data30,null,cmpnts);
double cost1 = MLDTreeLearner.mlDTreeLearner.parameterizeAndCost(Value.TRIV, x, z);
double cost2 = CPTLearner.mlMultinomialCPTLearner.parameterizeAndCost(Value.TRIV, x, z);
assertEquals( cost1, cost2, 0.0001 );
}
}
/** Ensure that Max LH CPT and DTree models return the same answer. */
public final void testMLTreeVsCPT() throws Exception {
Value.Vector data =
- Weka.load("/home/rodo/Repository/data/UCI/medium/letter.symbolic.arff", false, false);
+ Weka.load("camml/test/letter.symbolic.arff", false, false);
for (int ii = 0; ii < 3; ii++) {
Value.Vector x = data.cmpnt(0);
int[] cmpnts = new int[ii];
for (int i = 0; i < cmpnts.length; i++) { cmpnts[i] = i+1;}
Value.Vector z = new SelectedVector(data,null,cmpnts);
double cost1 = MLDTreeLearner.mlDTreeLearner.parameterizeAndCost(Value.TRIV, x, z);
double cost2 = CPTLearner.mlMultinomialCPTLearner.parameterizeAndCost(Value.TRIV, x, z);
//System.out.println(ii + "\t" + cost1 + "\t" + cost2);
assertEquals( cost1, cost2, 0.0001 );
}
}
}
| true | true | public final void testMLTreeVsCPT() throws Exception {
Value.Vector data =
Weka.load("/home/rodo/Repository/data/UCI/medium/letter.symbolic.arff", false, false);
for (int ii = 0; ii < 3; ii++) {
Value.Vector x = data.cmpnt(0);
int[] cmpnts = new int[ii];
for (int i = 0; i < cmpnts.length; i++) { cmpnts[i] = i+1;}
Value.Vector z = new SelectedVector(data,null,cmpnts);
double cost1 = MLDTreeLearner.mlDTreeLearner.parameterizeAndCost(Value.TRIV, x, z);
double cost2 = CPTLearner.mlMultinomialCPTLearner.parameterizeAndCost(Value.TRIV, x, z);
//System.out.println(ii + "\t" + cost1 + "\t" + cost2);
assertEquals( cost1, cost2, 0.0001 );
}
}
| public final void testMLTreeVsCPT() throws Exception {
Value.Vector data =
Weka.load("camml/test/letter.symbolic.arff", false, false);
for (int ii = 0; ii < 3; ii++) {
Value.Vector x = data.cmpnt(0);
int[] cmpnts = new int[ii];
for (int i = 0; i < cmpnts.length; i++) { cmpnts[i] = i+1;}
Value.Vector z = new SelectedVector(data,null,cmpnts);
double cost1 = MLDTreeLearner.mlDTreeLearner.parameterizeAndCost(Value.TRIV, x, z);
double cost2 = CPTLearner.mlMultinomialCPTLearner.parameterizeAndCost(Value.TRIV, x, z);
//System.out.println(ii + "\t" + cost1 + "\t" + cost2);
assertEquals( cost1, cost2, 0.0001 );
}
}
|
diff --git a/plugins/org.eclipse.dltk.ruby.launching/src/org/eclipse/dltk/ruby/internal/launching/RubyInterpreterRunner.java b/plugins/org.eclipse.dltk.ruby.launching/src/org/eclipse/dltk/ruby/internal/launching/RubyInterpreterRunner.java
index 1e8a3e79..90b2dd90 100644
--- a/plugins/org.eclipse.dltk.ruby.launching/src/org/eclipse/dltk/ruby/internal/launching/RubyInterpreterRunner.java
+++ b/plugins/org.eclipse.dltk.ruby.launching/src/org/eclipse/dltk/ruby/internal/launching/RubyInterpreterRunner.java
@@ -1,24 +1,24 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package org.eclipse.dltk.ruby.internal.launching;
import org.eclipse.dltk.launching.AbstractInterpreterRunner;
import org.eclipse.dltk.launching.IInterpreterInstall;
import org.eclipse.dltk.ruby.launching.RubyLaunchConfigurationConstants;
public class RubyInterpreterRunner extends AbstractInterpreterRunner {
- public RubyInterpreterRunner(IInterpreterInstall InterpreterInstance) {
- super(InterpreterInstance);
+ public RubyInterpreterRunner(IInterpreterInstall install) {
+ super(install);
}
protected String getProcessType() {
return RubyLaunchConfigurationConstants.ID_RUBY_PROCESS_TYPE;
}
}
| true | true | public RubyInterpreterRunner(IInterpreterInstall InterpreterInstance) {
super(InterpreterInstance);
}
| public RubyInterpreterRunner(IInterpreterInstall install) {
super(install);
}
|
diff --git a/src/be/ibridge/kettle/job/entry/ftp/JobEntryFTP.java b/src/be/ibridge/kettle/job/entry/ftp/JobEntryFTP.java
index abbc293e..0ae01d3e 100644
--- a/src/be/ibridge/kettle/job/entry/ftp/JobEntryFTP.java
+++ b/src/be/ibridge/kettle/job/entry/ftp/JobEntryFTP.java
@@ -1,548 +1,551 @@
/**********************************************************************
** **
** This code belongs to the KETTLE project. **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** [email protected] **
** **
**********************************************************************/
package be.ibridge.kettle.job.entry.ftp;
import java.io.File;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import org.eclipse.swt.widgets.Shell;
import org.w3c.dom.Node;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.Result;
import be.ibridge.kettle.core.ResultFile;
import be.ibridge.kettle.core.XMLHandler;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleXMLException;
import be.ibridge.kettle.core.util.StringUtil;
import be.ibridge.kettle.job.Job;
import be.ibridge.kettle.job.JobMeta;
import be.ibridge.kettle.job.entry.JobEntryBase;
import be.ibridge.kettle.job.entry.JobEntryDialogInterface;
import be.ibridge.kettle.job.entry.JobEntryInterface;
import be.ibridge.kettle.repository.Repository;
import com.enterprisedt.net.ftp.FTPClient;
import com.enterprisedt.net.ftp.FTPConnectMode;
import com.enterprisedt.net.ftp.FTPException;
import com.enterprisedt.net.ftp.FTPTransferType;
/**
* This defines an FTP job entry.
*
* @author Matt
* @since 05-11-2003
*
*/
public class JobEntryFTP extends JobEntryBase implements JobEntryInterface
{
private static Logger log4j = Logger.getLogger(JobEntryFTP.class);
private String serverName;
private String userName;
private String password;
private String ftpDirectory;
private String targetDirectory;
private String wildcard;
private boolean binaryMode;
private int timeout;
private boolean remove;
private boolean onlyGettingNewFiles; /* Don't overwrite files */
private boolean activeConnection;
public JobEntryFTP(String n)
{
super(n, "");
serverName=null;
setID(-1L);
setType(JobEntryInterface.TYPE_JOBENTRY_FTP);
}
public JobEntryFTP()
{
this("");
}
public JobEntryFTP(JobEntryBase jeb)
{
super(jeb);
}
public String getXML()
{
StringBuffer retval = new StringBuffer(128);
retval.append(super.getXML());
retval.append(" ").append(XMLHandler.addTagValue("servername", serverName));
retval.append(" ").append(XMLHandler.addTagValue("username", userName));
retval.append(" ").append(XMLHandler.addTagValue("password", password));
retval.append(" ").append(XMLHandler.addTagValue("ftpdirectory", ftpDirectory));
retval.append(" ").append(XMLHandler.addTagValue("targetdirectory", targetDirectory));
retval.append(" ").append(XMLHandler.addTagValue("wildcard", wildcard));
retval.append(" ").append(XMLHandler.addTagValue("binary", binaryMode));
retval.append(" ").append(XMLHandler.addTagValue("timeout", timeout));
retval.append(" ").append(XMLHandler.addTagValue("remove", remove));
retval.append(" ").append(XMLHandler.addTagValue("only_new", onlyGettingNewFiles));
retval.append(" ").append(XMLHandler.addTagValue("active", activeConnection));
return retval.toString();
}
public void loadXML(Node entrynode, ArrayList databases, Repository rep)
throws KettleXMLException
{
try
{
super.loadXML(entrynode, databases);
serverName = XMLHandler.getTagValue(entrynode, "servername");
userName = XMLHandler.getTagValue(entrynode, "username");
password = XMLHandler.getTagValue(entrynode, "password");
ftpDirectory = XMLHandler.getTagValue(entrynode, "ftpdirectory");
targetDirectory = XMLHandler.getTagValue(entrynode, "targetdirectory");
wildcard = XMLHandler.getTagValue(entrynode, "wildcard");
binaryMode = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "binary") );
timeout = Const.toInt(XMLHandler.getTagValue(entrynode, "timeout"), 10000);
remove = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "remove") );
onlyGettingNewFiles = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "only_new") );
activeConnection = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "active") );
}
catch(KettleXMLException xe)
{
throw new KettleXMLException("Unable to load file exists job entry from XML node", xe);
}
}
public void loadRep(Repository rep, long id_jobentry, ArrayList databases)
throws KettleException
{
try
{
super.loadRep(rep, id_jobentry, databases);
serverName = rep.getJobEntryAttributeString(id_jobentry, "servername");
userName = rep.getJobEntryAttributeString(id_jobentry, "username");
password = rep.getJobEntryAttributeString(id_jobentry, "password");
ftpDirectory = rep.getJobEntryAttributeString(id_jobentry, "ftpdirectory");
targetDirectory = rep.getJobEntryAttributeString(id_jobentry, "targetdirectory");
wildcard = rep.getJobEntryAttributeString(id_jobentry, "wildcard");
binaryMode = rep.getJobEntryAttributeBoolean(id_jobentry, "binary");
timeout = (int)rep.getJobEntryAttributeInteger(id_jobentry, "timeout");
remove = rep.getJobEntryAttributeBoolean(id_jobentry, "remove");
onlyGettingNewFiles = rep.getJobEntryAttributeBoolean(id_jobentry, "only_new");
activeConnection = rep.getJobEntryAttributeBoolean(id_jobentry, "active");
}
catch(KettleException dbe)
{
throw new KettleException("Unable to load job entry for type file exists from the repository for id_jobentry="+id_jobentry, dbe);
}
}
public void saveRep(Repository rep, long id_job)
throws KettleException
{
try
{
super.saveRep(rep, id_job);
rep.saveJobEntryAttribute(id_job, getID(), "servername", serverName);
rep.saveJobEntryAttribute(id_job, getID(), "username", userName);
rep.saveJobEntryAttribute(id_job, getID(), "password", password);
rep.saveJobEntryAttribute(id_job, getID(), "ftpdirectory", ftpDirectory);
rep.saveJobEntryAttribute(id_job, getID(), "targetdirectory", targetDirectory);
rep.saveJobEntryAttribute(id_job, getID(), "wildcard", wildcard);
rep.saveJobEntryAttribute(id_job, getID(), "binary", binaryMode);
rep.saveJobEntryAttribute(id_job, getID(), "timeout", timeout);
rep.saveJobEntryAttribute(id_job, getID(), "remove", remove);
rep.saveJobEntryAttribute(id_job, getID(), "only_new", onlyGettingNewFiles);
rep.saveJobEntryAttribute(id_job, getID(), "active", activeConnection);
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("unable to save jobentry of type 'file exists' to the repository for id_job="+id_job, dbe);
}
}
/**
* @return Returns the binaryMode.
*/
public boolean isBinaryMode()
{
return binaryMode;
}
/**
* @param binaryMode The binaryMode to set.
*/
public void setBinaryMode(boolean binaryMode)
{
this.binaryMode = binaryMode;
}
/**
* @return Returns the directory.
*/
public String getFtpDirectory()
{
return ftpDirectory;
}
/**
* @param directory The directory to set.
*/
public void setFtpDirectory(String directory)
{
this.ftpDirectory = directory;
}
/**
* @return Returns the password.
*/
public String getPassword()
{
return password;
}
/**
* @param password The password to set.
*/
public void setPassword(String password)
{
this.password = password;
}
/**
* @return Returns the serverName.
*/
public String getServerName()
{
return serverName;
}
/**
* @param serverName The serverName to set.
*/
public void setServerName(String serverName)
{
this.serverName = serverName;
}
/**
* @return Returns the userName.
*/
public String getUserName()
{
return userName;
}
/**
* @param userName The userName to set.
*/
public void setUserName(String userName)
{
this.userName = userName;
}
/**
* @return Returns the wildcard.
*/
public String getWildcard()
{
return wildcard;
}
/**
* @param wildcard The wildcard to set.
*/
public void setWildcard(String wildcard)
{
this.wildcard = wildcard;
}
/**
* @return Returns the targetDirectory.
*/
public String getTargetDirectory()
{
return targetDirectory;
}
/**
* @param targetDirectory The targetDirectory to set.
*/
public void setTargetDirectory(String targetDirectory)
{
this.targetDirectory = targetDirectory;
}
/**
* @param timeout The timeout to set.
*/
public void setTimeout(int timeout)
{
this.timeout = timeout;
}
/**
* @return Returns the timeout.
*/
public int getTimeout()
{
return timeout;
}
/**
* @param remove The remove to set.
*/
public void setRemove(boolean remove)
{
this.remove = remove;
}
/**
* @return Returns the remove.
*/
public boolean getRemove()
{
return remove;
}
/**
* @return Returns the onlyGettingNewFiles.
*/
public boolean isOnlyGettingNewFiles()
{
return onlyGettingNewFiles;
}
/**
* @param onlyGettingNewFiles The onlyGettingNewFiles to set.
*/
public void setOnlyGettingNewFiles(boolean onlyGettingNewFiles)
{
this.onlyGettingNewFiles = onlyGettingNewFiles;
}
public Result execute(Result prev_result, int nr, Repository rep, Job parentJob)
{
LogWriter log = LogWriter.getInstance();
log4j.info("Started FTP job to "+serverName);
Result result = new Result(nr);
result.setResult( false );
long filesRetrieved = 0;
log.logDetailed(toString(), "Start of FTP job entry");
FTPClient ftpclient=null;
try
{
// Create ftp client to host:port ...
ftpclient = new FTPClient();
- ftpclient.setRemoteAddr(InetAddress.getByName(serverName));
+ String realServername = StringUtil.environmentSubstitute(serverName);
+ ftpclient.setRemoteAddr(InetAddress.getByName(realServername));
- log.logDetailed(toString(), "Opened FTP connection to server ["+serverName+"]");
+ log.logDetailed(toString(), "Opened FTP connection to server ["+realServername+"]");
// set activeConnection connectmode ...
if (activeConnection)
{
ftpclient.setConnectMode(FTPConnectMode.ACTIVE);
log.logDetailed(toString(), "set active ftp connection mode");
}
else
{
ftpclient.setConnectMode(FTPConnectMode.PASV);
log.logDetailed(toString(), "set passive ftp connection mode");
}
// Set the timeout
ftpclient.setTimeout(timeout);
log.logDetailed(toString(), "set timeout to "+timeout);
// login to ftp host ...
ftpclient.connect();
- ftpclient.login(userName, password);
+ String realUsername = StringUtil.environmentSubstitute(userName);
+ String realPassword = StringUtil.environmentSubstitute(password);
+ ftpclient.login(realUsername, realPassword);
// Remove password from logging, you don't know where it ends up.
- log.logDetailed(toString(), "logged in using "+userName);
+ log.logDetailed(toString(), "logged in using "+realPassword);
// move to spool dir ...
- String realFtpDirectory = StringUtil.environmentSubstitute(ftpDirectory);
- if (!Const.isEmpty(realFtpDirectory))
+ if (!Const.isEmpty(ftpDirectory))
{
+ String realFtpDirectory = StringUtil.environmentSubstitute(ftpDirectory);
ftpclient.chdir(realFtpDirectory);
log.logDetailed(toString(), "Changed to directory ["+realFtpDirectory+"]");
}
// Get all the files in the current directory...
String[] filelist = ftpclient.dir();
log.logDetailed(toString(), "Found "+filelist.length+" files in the remote ftp directory");
// set transfertype ...
if (binaryMode)
{
ftpclient.setType(FTPTransferType.BINARY);
log.logDetailed(toString(), "set binary transfer mode");
}
else
{
ftpclient.setType(FTPTransferType.ASCII);
log.logDetailed(toString(), "set ASCII transfer mode");
}
// Some FTP servers return a message saying no files found as a string in the filenlist
// e.g. Solaris 8
// CHECK THIS !!!
if (filelist.length == 1)
{
String translatedWildcard = StringUtil.environmentSubstitute(wildcard);
if (filelist[0].startsWith(translatedWildcard))
{
throw new FTPException(filelist[0]);
}
}
Pattern pattern = null;
if (!Const.isEmpty(wildcard))
{
- String realWildcard = StringUtil.environmentSubstitute(wildcard);
+ String realWildcard = StringUtil.environmentSubstitute(wildcard);
pattern = Pattern.compile(realWildcard);
}
// Get the files in the list...
for (int i=0;i<filelist.length && !parentJob.isStopped();i++)
{
boolean getIt = true;
// First see if the file matches the regular expression!
if (pattern!=null)
{
Matcher matcher = pattern.matcher(filelist[i]);
getIt = matcher.matches();
}
if (getIt)
{
log.logDebug(toString(), "Getting file ["+filelist[i]+"] to directory ["+StringUtil.environmentSubstitute(targetDirectory)+"]");
String targetFilename = getTargetFilename(filelist[i]);
File targetFile = new File(targetFilename);
if ( (onlyGettingNewFiles == false) ||
(onlyGettingNewFiles == true) && needsDownload(filelist[i]))
{
ftpclient.get(targetFilename, filelist[i]);
filesRetrieved++;
// Add to the result files...
ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, targetFile, parentJob.getJobname(), toString());
resultFile.setComment("Downloaded from ftp server "+serverName);
result.getResultFiles().add(resultFile);
log.logDetailed(toString(), "Got file ["+filelist[i]+"]");
}
// Delete the file if this is needed!
if (remove)
{
ftpclient.delete(filelist[i]);
log.logDetailed(toString(), "deleted file ["+filelist[i]+"]");
}
}
}
result.setResult( true );
result.setNrFilesRetrieved(filesRetrieved);
}
catch(Exception e)
{
result.setNrErrors(1);
log.logError(toString(), "Error getting files from FTP : "+e.getMessage());
log.logError(toString(), Const.getStackTracker(e));
}
finally
{
if (ftpclient!=null && ftpclient.connected())
{
try
{
ftpclient.quit();
}
catch(Exception e)
{
log.logError(toString(), "Error quiting FTP connection: "+e.getMessage());
}
}
}
return result;
}
/**
* @param string the filename from the FTP server
*
* @return the calculated target filename
*/
protected String getTargetFilename(String string)
{
return StringUtil.environmentSubstitute(targetDirectory)+Const.FILE_SEPARATOR+string;
}
public boolean evaluates()
{
return true;
}
/**
* See if the filename on the FTP server needs downloading.
* The default is to check the presence of the file in the target directory.
* If you need other functionality, extend this class and build it into a plugin.
*
* @param filename The filename to check
* @return true if the file needs downloading
*/
protected boolean needsDownload(String filename)
{
File file = new File(getTargetFilename(filename));
return !file.exists();
}
public JobEntryDialogInterface getDialog(Shell shell,JobEntryInterface jei,JobMeta jobMeta,String jobName,Repository rep) {
return new JobEntryFTPDialog(shell,this,jobMeta);
}
/**
* @return the activeConnection
*/
public boolean isActiveConnection()
{
return activeConnection;
}
/**
* @param activeConnection the activeConnection to set
*/
public void setActiveConnection(boolean passive)
{
this.activeConnection = passive;
}
}
| false | true | public Result execute(Result prev_result, int nr, Repository rep, Job parentJob)
{
LogWriter log = LogWriter.getInstance();
log4j.info("Started FTP job to "+serverName);
Result result = new Result(nr);
result.setResult( false );
long filesRetrieved = 0;
log.logDetailed(toString(), "Start of FTP job entry");
FTPClient ftpclient=null;
try
{
// Create ftp client to host:port ...
ftpclient = new FTPClient();
ftpclient.setRemoteAddr(InetAddress.getByName(serverName));
log.logDetailed(toString(), "Opened FTP connection to server ["+serverName+"]");
// set activeConnection connectmode ...
if (activeConnection)
{
ftpclient.setConnectMode(FTPConnectMode.ACTIVE);
log.logDetailed(toString(), "set active ftp connection mode");
}
else
{
ftpclient.setConnectMode(FTPConnectMode.PASV);
log.logDetailed(toString(), "set passive ftp connection mode");
}
// Set the timeout
ftpclient.setTimeout(timeout);
log.logDetailed(toString(), "set timeout to "+timeout);
// login to ftp host ...
ftpclient.connect();
ftpclient.login(userName, password);
// Remove password from logging, you don't know where it ends up.
log.logDetailed(toString(), "logged in using "+userName);
// move to spool dir ...
String realFtpDirectory = StringUtil.environmentSubstitute(ftpDirectory);
if (!Const.isEmpty(realFtpDirectory))
{
ftpclient.chdir(realFtpDirectory);
log.logDetailed(toString(), "Changed to directory ["+realFtpDirectory+"]");
}
// Get all the files in the current directory...
String[] filelist = ftpclient.dir();
log.logDetailed(toString(), "Found "+filelist.length+" files in the remote ftp directory");
// set transfertype ...
if (binaryMode)
{
ftpclient.setType(FTPTransferType.BINARY);
log.logDetailed(toString(), "set binary transfer mode");
}
else
{
ftpclient.setType(FTPTransferType.ASCII);
log.logDetailed(toString(), "set ASCII transfer mode");
}
// Some FTP servers return a message saying no files found as a string in the filenlist
// e.g. Solaris 8
// CHECK THIS !!!
if (filelist.length == 1)
{
String translatedWildcard = StringUtil.environmentSubstitute(wildcard);
if (filelist[0].startsWith(translatedWildcard))
{
throw new FTPException(filelist[0]);
}
}
Pattern pattern = null;
if (!Const.isEmpty(wildcard))
{
String realWildcard = StringUtil.environmentSubstitute(wildcard);
pattern = Pattern.compile(realWildcard);
}
// Get the files in the list...
for (int i=0;i<filelist.length && !parentJob.isStopped();i++)
{
boolean getIt = true;
// First see if the file matches the regular expression!
if (pattern!=null)
{
Matcher matcher = pattern.matcher(filelist[i]);
getIt = matcher.matches();
}
if (getIt)
{
log.logDebug(toString(), "Getting file ["+filelist[i]+"] to directory ["+StringUtil.environmentSubstitute(targetDirectory)+"]");
String targetFilename = getTargetFilename(filelist[i]);
File targetFile = new File(targetFilename);
if ( (onlyGettingNewFiles == false) ||
(onlyGettingNewFiles == true) && needsDownload(filelist[i]))
{
ftpclient.get(targetFilename, filelist[i]);
filesRetrieved++;
// Add to the result files...
ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, targetFile, parentJob.getJobname(), toString());
resultFile.setComment("Downloaded from ftp server "+serverName);
result.getResultFiles().add(resultFile);
log.logDetailed(toString(), "Got file ["+filelist[i]+"]");
}
// Delete the file if this is needed!
if (remove)
{
ftpclient.delete(filelist[i]);
log.logDetailed(toString(), "deleted file ["+filelist[i]+"]");
}
}
}
result.setResult( true );
result.setNrFilesRetrieved(filesRetrieved);
}
catch(Exception e)
{
result.setNrErrors(1);
log.logError(toString(), "Error getting files from FTP : "+e.getMessage());
log.logError(toString(), Const.getStackTracker(e));
}
finally
{
if (ftpclient!=null && ftpclient.connected())
{
try
{
ftpclient.quit();
}
catch(Exception e)
{
log.logError(toString(), "Error quiting FTP connection: "+e.getMessage());
}
}
}
return result;
}
| public Result execute(Result prev_result, int nr, Repository rep, Job parentJob)
{
LogWriter log = LogWriter.getInstance();
log4j.info("Started FTP job to "+serverName);
Result result = new Result(nr);
result.setResult( false );
long filesRetrieved = 0;
log.logDetailed(toString(), "Start of FTP job entry");
FTPClient ftpclient=null;
try
{
// Create ftp client to host:port ...
ftpclient = new FTPClient();
String realServername = StringUtil.environmentSubstitute(serverName);
ftpclient.setRemoteAddr(InetAddress.getByName(realServername));
log.logDetailed(toString(), "Opened FTP connection to server ["+realServername+"]");
// set activeConnection connectmode ...
if (activeConnection)
{
ftpclient.setConnectMode(FTPConnectMode.ACTIVE);
log.logDetailed(toString(), "set active ftp connection mode");
}
else
{
ftpclient.setConnectMode(FTPConnectMode.PASV);
log.logDetailed(toString(), "set passive ftp connection mode");
}
// Set the timeout
ftpclient.setTimeout(timeout);
log.logDetailed(toString(), "set timeout to "+timeout);
// login to ftp host ...
ftpclient.connect();
String realUsername = StringUtil.environmentSubstitute(userName);
String realPassword = StringUtil.environmentSubstitute(password);
ftpclient.login(realUsername, realPassword);
// Remove password from logging, you don't know where it ends up.
log.logDetailed(toString(), "logged in using "+realPassword);
// move to spool dir ...
if (!Const.isEmpty(ftpDirectory))
{
String realFtpDirectory = StringUtil.environmentSubstitute(ftpDirectory);
ftpclient.chdir(realFtpDirectory);
log.logDetailed(toString(), "Changed to directory ["+realFtpDirectory+"]");
}
// Get all the files in the current directory...
String[] filelist = ftpclient.dir();
log.logDetailed(toString(), "Found "+filelist.length+" files in the remote ftp directory");
// set transfertype ...
if (binaryMode)
{
ftpclient.setType(FTPTransferType.BINARY);
log.logDetailed(toString(), "set binary transfer mode");
}
else
{
ftpclient.setType(FTPTransferType.ASCII);
log.logDetailed(toString(), "set ASCII transfer mode");
}
// Some FTP servers return a message saying no files found as a string in the filenlist
// e.g. Solaris 8
// CHECK THIS !!!
if (filelist.length == 1)
{
String translatedWildcard = StringUtil.environmentSubstitute(wildcard);
if (filelist[0].startsWith(translatedWildcard))
{
throw new FTPException(filelist[0]);
}
}
Pattern pattern = null;
if (!Const.isEmpty(wildcard))
{
String realWildcard = StringUtil.environmentSubstitute(wildcard);
pattern = Pattern.compile(realWildcard);
}
// Get the files in the list...
for (int i=0;i<filelist.length && !parentJob.isStopped();i++)
{
boolean getIt = true;
// First see if the file matches the regular expression!
if (pattern!=null)
{
Matcher matcher = pattern.matcher(filelist[i]);
getIt = matcher.matches();
}
if (getIt)
{
log.logDebug(toString(), "Getting file ["+filelist[i]+"] to directory ["+StringUtil.environmentSubstitute(targetDirectory)+"]");
String targetFilename = getTargetFilename(filelist[i]);
File targetFile = new File(targetFilename);
if ( (onlyGettingNewFiles == false) ||
(onlyGettingNewFiles == true) && needsDownload(filelist[i]))
{
ftpclient.get(targetFilename, filelist[i]);
filesRetrieved++;
// Add to the result files...
ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, targetFile, parentJob.getJobname(), toString());
resultFile.setComment("Downloaded from ftp server "+serverName);
result.getResultFiles().add(resultFile);
log.logDetailed(toString(), "Got file ["+filelist[i]+"]");
}
// Delete the file if this is needed!
if (remove)
{
ftpclient.delete(filelist[i]);
log.logDetailed(toString(), "deleted file ["+filelist[i]+"]");
}
}
}
result.setResult( true );
result.setNrFilesRetrieved(filesRetrieved);
}
catch(Exception e)
{
result.setNrErrors(1);
log.logError(toString(), "Error getting files from FTP : "+e.getMessage());
log.logError(toString(), Const.getStackTracker(e));
}
finally
{
if (ftpclient!=null && ftpclient.connected())
{
try
{
ftpclient.quit();
}
catch(Exception e)
{
log.logError(toString(), "Error quiting FTP connection: "+e.getMessage());
}
}
}
return result;
}
|
diff --git a/ardor3d-awt/src/main/java/com/ardor3d/input/awt/AwtMouseWrapper.java b/ardor3d-awt/src/main/java/com/ardor3d/input/awt/AwtMouseWrapper.java
index e9ea264..547c5f4 100644
--- a/ardor3d-awt/src/main/java/com/ardor3d/input/awt/AwtMouseWrapper.java
+++ b/ardor3d-awt/src/main/java/com/ardor3d/input/awt/AwtMouseWrapper.java
@@ -1,298 +1,300 @@
/**
* Copyright (c) 2008-2009 Ardor Labs, Inc.
*
* This file is part of Ardor3D.
*
* Ardor3D is free software: you can redistribute it and/or modify it
* under the terms of its license which may be found in the accompanying
* LICENSE file or at <http://www.ardor3d.com/LICENSE>.
*/
package com.ardor3d.input.awt;
import static com.google.common.base.Preconditions.checkNotNull;
import java.awt.Component;
import java.awt.Frame;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.LinkedList;
import com.ardor3d.annotation.GuardedBy;
import com.ardor3d.input.ButtonState;
import com.ardor3d.input.GrabbedState;
import com.ardor3d.input.MouseButton;
import com.ardor3d.input.MouseManager;
import com.ardor3d.input.MouseState;
import com.ardor3d.input.MouseWrapper;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.EnumMultiset;
import com.google.common.collect.Maps;
import com.google.common.collect.Multiset;
import com.google.common.collect.PeekingIterator;
import com.google.inject.Inject;
/**
* Mouse wrapper class for use with AWT.
*/
public class AwtMouseWrapper implements MouseWrapper, MouseListener, MouseWheelListener, MouseMotionListener {
@GuardedBy("this")
private final LinkedList<MouseState> _upcomingEvents = new LinkedList<MouseState>();
@GuardedBy("this")
private AwtMouseIterator _currentIterator = null;
@GuardedBy("this")
private MouseState _lastState = null;
private final Component _component;
private final Frame _frame;
private final MouseManager _manager;
private final Multiset<MouseButton> _clicks = EnumMultiset.create(MouseButton.class);
private final EnumMap<MouseButton, Long> _lastClickTime = Maps.newEnumMap(MouseButton.class);
private final EnumSet<MouseButton> _clickArmed = EnumSet.noneOf(MouseButton.class);
private int _ignoreX = Integer.MAX_VALUE;
private int _ignoreY = Integer.MAX_VALUE;
@Inject
public AwtMouseWrapper(final Component component, final MouseManager manager) {
_manager = manager;
if (component instanceof Frame) {
_frame = (Frame) (_component = component);
} else {
_component = checkNotNull(component, "component");
_frame = null;
}
for (final MouseButton mb : MouseButton.values()) {
_lastClickTime.put(mb, 0L);
}
}
public void init() {
_component.addMouseListener(this);
_component.addMouseMotionListener(this);
_component.addMouseWheelListener(this);
}
public synchronized PeekingIterator<MouseState> getEvents() {
expireClickEvents();
if (_currentIterator == null || !_currentIterator.hasNext()) {
_currentIterator = new AwtMouseIterator();
}
return _currentIterator;
}
private void expireClickEvents() {
if (!_clicks.isEmpty()) {
for (final MouseButton mb : MouseButton.values()) {
if (System.currentTimeMillis() - _lastClickTime.get(mb) > MouseState.CLICK_TIME_MS) {
_clicks.setCount(mb, 0);
}
}
}
}
public synchronized void mousePressed(final MouseEvent e) {
final MouseButton b = getButtonForEvent(e);
if (_clickArmed.contains(b)) {
_clicks.setCount(b, 0);
}
_clickArmed.add(b);
_lastClickTime.put(b, System.currentTimeMillis());
initState(e);
final EnumMap<MouseButton, ButtonState> buttons = _lastState.getButtonStates();
setStateForButton(e, buttons, ButtonState.DOWN);
addNewState(e, buttons, null);
}
public synchronized void mouseReleased(final MouseEvent e) {
initState(e);
final EnumMap<MouseButton, ButtonState> buttons = _lastState.getButtonStates();
setStateForButton(e, buttons, ButtonState.UP);
final MouseButton b = getButtonForEvent(e);
if (_clickArmed.contains(b) && (System.currentTimeMillis() - _lastClickTime.get(b) <= MouseState.CLICK_TIME_MS)) {
_clicks.add(b); // increment count of clicks for button b.
// XXX: Note the double event add... this prevents sticky click counts, but is it the best way?
addNewState(e, buttons, EnumMultiset.create(_clicks));
} else {
_clicks.setCount(b, 0); // clear click count for button b.
}
_clickArmed.remove(b);
addNewState(e, buttons, null);
}
public synchronized void mouseDragged(final MouseEvent e) {
// forward to mouseMoved.
mouseMoved(e);
}
public synchronized void mouseMoved(final MouseEvent e) {
_clickArmed.clear();
_clicks.clear();
// check that we have a valid _lastState
initState(e);
// remember our current ardor3d position
final int oldX = _lastState.getX(), oldY = _lastState.getY();
// check the state against the "ignore next" values
if (_ignoreX != Integer.MAX_VALUE // shortcut to prevent dx/dy calculations
&& (_ignoreX == getDX(e) && _ignoreY == getDY(e))) {
// we matched, so we'll consider this a "mouse pointer reset move"
// so reset ignore to let the next move event through.
_ignoreX = Integer.MAX_VALUE;
_ignoreY = Integer.MAX_VALUE;
// exit without adding an event to our queue
return;
}
// save our old "last state."
final MouseState _savedState = _lastState;
// Add our latest state info to the queue
+ // FIXME: Since this happens in the event queue, it's likely we'll get more than 1 move event added to the
+ // queue between calls to getEvents. This can cause issues.
addNewState(e, _lastState.getButtonStates(), null);
// If we have a valid move... should always be the case, but occasionally something slips through.
if (_lastState.getDx() != 0 || _lastState.getDy() != 0) {
// Ask our manager if we're currently "captured"
if (_manager.getGrabbed() == GrabbedState.GRABBED) {
// if so, set "ignore next" to the inverse of this move
_ignoreX = -_lastState.getDx();
_ignoreY = -_lastState.getDy();
// Move us back to our last position.
_manager.setPosition(oldX, oldY);
// And finally, revert our _lastState.
_lastState = _savedState;
} else {
// otherwise, set us to not ignore anything. This may be unnecessary, but prevents any possible
// "ignore" bleeding.
_ignoreX = Integer.MAX_VALUE;
_ignoreY = Integer.MAX_VALUE;
}
}
}
public void mouseWheelMoved(final MouseWheelEvent e) {
initState(e);
addNewState(e, _lastState.getButtonStates(), null);
}
private void initState(final MouseEvent mouseEvent) {
if (_lastState == null) {
final int height = (_frame != null && _frame.getComponentCount() > 0) ? _frame.getComponent(0).getHeight()
: _component.getHeight();
_lastState = new MouseState(mouseEvent.getX(), height - mouseEvent.getY(), 0, 0, 0, null, null);
}
}
private void addNewState(final MouseEvent mouseEvent, final EnumMap<MouseButton, ButtonState> enumMap,
final Multiset<MouseButton> clicks) {
final int fixedY = getArdor3DY(mouseEvent);
final MouseState newState = new MouseState(mouseEvent.getX(), fixedY, getDX(mouseEvent), getDY(mouseEvent),
(mouseEvent instanceof MouseWheelEvent ? ((MouseWheelEvent) mouseEvent).getWheelRotation() : 0),
enumMap, clicks);
_upcomingEvents.add(newState);
_lastState = newState;
}
private int getDX(final MouseEvent e) {
return e.getX() - _lastState.getX();
}
private int getDY(final MouseEvent e) {
return getArdor3DY(e) - _lastState.getY();
}
/**
* @param e
* our mouseEvent
* @return the Y coordinate of the event, flipped relative to the component since we expect an origin in the lower
* left corner.
*/
private int getArdor3DY(final MouseEvent e) {
final int height = (_frame != null && _frame.getComponentCount() > 0) ? _frame.getComponent(0).getHeight()
: _component.getHeight();
return height - e.getY();
}
private void setStateForButton(final MouseEvent e, final EnumMap<MouseButton, ButtonState> buttons,
final ButtonState buttonState) {
final MouseButton button = getButtonForEvent(e);
buttons.put(button, buttonState);
}
private MouseButton getButtonForEvent(final MouseEvent e) {
MouseButton button;
switch (e.getButton()) {
case MouseEvent.BUTTON1:
button = MouseButton.LEFT;
break;
case MouseEvent.BUTTON2:
button = MouseButton.MIDDLE;
break;
case MouseEvent.BUTTON3:
button = MouseButton.RIGHT;
break;
default:
throw new RuntimeException("unknown button: " + e.getButton());
}
return button;
}
private class AwtMouseIterator extends AbstractIterator<MouseState> implements PeekingIterator<MouseState> {
@Override
protected MouseState computeNext() {
synchronized (AwtMouseWrapper.this) {
if (_upcomingEvents.isEmpty()) {
return endOfData();
}
return _upcomingEvents.poll();
}
}
}
// -- The following interface methods are not used. --
public synchronized void mouseClicked(final MouseEvent e) {
// Yes, we could use the click count here, but in the interests of this working the same way as SWT and Native, we
// will do it the same way they do it.
}
public synchronized void mouseEntered(final MouseEvent e) {
// ignore this
}
public synchronized void mouseExited(final MouseEvent e) {
// ignore this
}
}
| true | true | public synchronized void mouseMoved(final MouseEvent e) {
_clickArmed.clear();
_clicks.clear();
// check that we have a valid _lastState
initState(e);
// remember our current ardor3d position
final int oldX = _lastState.getX(), oldY = _lastState.getY();
// check the state against the "ignore next" values
if (_ignoreX != Integer.MAX_VALUE // shortcut to prevent dx/dy calculations
&& (_ignoreX == getDX(e) && _ignoreY == getDY(e))) {
// we matched, so we'll consider this a "mouse pointer reset move"
// so reset ignore to let the next move event through.
_ignoreX = Integer.MAX_VALUE;
_ignoreY = Integer.MAX_VALUE;
// exit without adding an event to our queue
return;
}
// save our old "last state."
final MouseState _savedState = _lastState;
// Add our latest state info to the queue
addNewState(e, _lastState.getButtonStates(), null);
// If we have a valid move... should always be the case, but occasionally something slips through.
if (_lastState.getDx() != 0 || _lastState.getDy() != 0) {
// Ask our manager if we're currently "captured"
if (_manager.getGrabbed() == GrabbedState.GRABBED) {
// if so, set "ignore next" to the inverse of this move
_ignoreX = -_lastState.getDx();
_ignoreY = -_lastState.getDy();
// Move us back to our last position.
_manager.setPosition(oldX, oldY);
// And finally, revert our _lastState.
_lastState = _savedState;
} else {
// otherwise, set us to not ignore anything. This may be unnecessary, but prevents any possible
// "ignore" bleeding.
_ignoreX = Integer.MAX_VALUE;
_ignoreY = Integer.MAX_VALUE;
}
}
}
| public synchronized void mouseMoved(final MouseEvent e) {
_clickArmed.clear();
_clicks.clear();
// check that we have a valid _lastState
initState(e);
// remember our current ardor3d position
final int oldX = _lastState.getX(), oldY = _lastState.getY();
// check the state against the "ignore next" values
if (_ignoreX != Integer.MAX_VALUE // shortcut to prevent dx/dy calculations
&& (_ignoreX == getDX(e) && _ignoreY == getDY(e))) {
// we matched, so we'll consider this a "mouse pointer reset move"
// so reset ignore to let the next move event through.
_ignoreX = Integer.MAX_VALUE;
_ignoreY = Integer.MAX_VALUE;
// exit without adding an event to our queue
return;
}
// save our old "last state."
final MouseState _savedState = _lastState;
// Add our latest state info to the queue
// FIXME: Since this happens in the event queue, it's likely we'll get more than 1 move event added to the
// queue between calls to getEvents. This can cause issues.
addNewState(e, _lastState.getButtonStates(), null);
// If we have a valid move... should always be the case, but occasionally something slips through.
if (_lastState.getDx() != 0 || _lastState.getDy() != 0) {
// Ask our manager if we're currently "captured"
if (_manager.getGrabbed() == GrabbedState.GRABBED) {
// if so, set "ignore next" to the inverse of this move
_ignoreX = -_lastState.getDx();
_ignoreY = -_lastState.getDy();
// Move us back to our last position.
_manager.setPosition(oldX, oldY);
// And finally, revert our _lastState.
_lastState = _savedState;
} else {
// otherwise, set us to not ignore anything. This may be unnecessary, but prevents any possible
// "ignore" bleeding.
_ignoreX = Integer.MAX_VALUE;
_ignoreY = Integer.MAX_VALUE;
}
}
}
|
diff --git a/Interpreter/src/edu/tum/lua/junit/ToNumberTest.java b/Interpreter/src/edu/tum/lua/junit/ToNumberTest.java
index 0aaa665..337de2f 100644
--- a/Interpreter/src/edu/tum/lua/junit/ToNumberTest.java
+++ b/Interpreter/src/edu/tum/lua/junit/ToNumberTest.java
@@ -1,44 +1,44 @@
package edu.tum.lua.junit;
import static org.junit.Assert.*;
import java.util.LinkedList;
import org.junit.Test;
import edu.tum.lua.LuaRuntimeException;
import edu.tum.lua.stdlib.ToNumber;
public class ToNumberTest {
@Test
public void test() {
ToNumber p = new ToNumber();
LinkedList<Object> l;
l = new LinkedList<Object>();
try {
p.apply(l);
fail("Accept empty input");
} catch (LuaRuntimeException e) {
assertTrue("Don't accept empty input", true);
} catch (Exception e) {
fail("Unknow exception");
}
l.add("1234");
- assertEquals("Translating a true int String", 1234, (int) p.apply(l).get(0));
+ assertEquals("Translating a true int String", 1234, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add("42.21");
assertEquals("Translating a true double String", new Double(42.21), p.apply(l).get(0));
l = new LinkedList<Object>();
l.add("Hello123");
assertEquals("Translating a false String", null, (double) p.apply(l).get(0));
// TODO Test for base argument not completed yet
}
}
| true | true | public void test() {
ToNumber p = new ToNumber();
LinkedList<Object> l;
l = new LinkedList<Object>();
try {
p.apply(l);
fail("Accept empty input");
} catch (LuaRuntimeException e) {
assertTrue("Don't accept empty input", true);
} catch (Exception e) {
fail("Unknow exception");
}
l.add("1234");
assertEquals("Translating a true int String", 1234, (int) p.apply(l).get(0));
l = new LinkedList<Object>();
l.add("42.21");
assertEquals("Translating a true double String", new Double(42.21), p.apply(l).get(0));
l = new LinkedList<Object>();
l.add("Hello123");
assertEquals("Translating a false String", null, (double) p.apply(l).get(0));
// TODO Test for base argument not completed yet
}
| public void test() {
ToNumber p = new ToNumber();
LinkedList<Object> l;
l = new LinkedList<Object>();
try {
p.apply(l);
fail("Accept empty input");
} catch (LuaRuntimeException e) {
assertTrue("Don't accept empty input", true);
} catch (Exception e) {
fail("Unknow exception");
}
l.add("1234");
assertEquals("Translating a true int String", 1234, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add("42.21");
assertEquals("Translating a true double String", new Double(42.21), p.apply(l).get(0));
l = new LinkedList<Object>();
l.add("Hello123");
assertEquals("Translating a false String", null, (double) p.apply(l).get(0));
// TODO Test for base argument not completed yet
}
|
diff --git a/plugins/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java b/plugins/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java
index bf233c02f..146598916 100644
--- a/plugins/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java
+++ b/plugins/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java
@@ -1,1197 +1,1197 @@
/*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.engine.emitter.postscript;
import java.awt.Color;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.awt.image.PixelGrabber;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import org.eclipse.birt.report.engine.content.IImageContent;
import org.eclipse.birt.report.engine.emitter.EmitterUtil;
import org.eclipse.birt.report.engine.emitter.postscript.truetypefont.ITrueTypeWriter;
import org.eclipse.birt.report.engine.emitter.postscript.truetypefont.TrueTypeFont;
import org.eclipse.birt.report.engine.emitter.postscript.truetypefont.Util;
import org.eclipse.birt.report.engine.emitter.postscript.util.FileUtil;
import org.eclipse.birt.report.engine.layout.emitter.util.BackgroundImageLayout;
import org.eclipse.birt.report.engine.layout.emitter.util.Position;
import org.eclipse.birt.report.engine.layout.pdf.font.FontInfo;
import org.eclipse.birt.report.engine.nLayout.area.style.BorderInfo;
import org.w3c.dom.css.CSSValue;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.FontFactoryImp;
import com.lowagie.text.pdf.BaseFont;
public class PostscriptWriter
{
/** This is a possible value of a base 14 type 1 font */
public static final String COURIER = BaseFont.COURIER;
/** This is a possible value of a base 14 type 1 font */
public static final String COURIER_BOLD = BaseFont.COURIER_BOLD;
/** This is a possible value of a base 14 type 1 font */
public static final String COURIER_OBLIQUE = BaseFont.COURIER_OBLIQUE;
/** This is a possible value of a base 14 type 1 font */
public static final String COURIER_BOLDOBLIQUE = BaseFont.COURIER_BOLDOBLIQUE;
/** This is a possible value of a base 14 type 1 font */
public static final String HELVETICA = BaseFont.HELVETICA;
/** This is a possible value of a base 14 type 1 font */
public static final String HELVETICA_BOLD = BaseFont.HELVETICA_BOLD;
/** This is a possible value of a base 14 type 1 font */
public static final String HELVETICA_OBLIQUE = BaseFont.HELVETICA_OBLIQUE;
/** This is a possible value of a base 14 type 1 font */
public static final String HELVETICA_BOLDOBLIQUE = BaseFont.HELVETICA_BOLDOBLIQUE;
/** This is a possible value of a base 14 type 1 font */
public static final String SYMBOL = BaseFont.SYMBOL;
/** This is a possible value of a base 14 type 1 font */
public static final String TIMES = "Times";
/** This is a possible value of a base 14 type 1 font */
public static final String TIMES_ROMAN = BaseFont.TIMES_ROMAN;
/** This is a possible value of a base 14 type 1 font */
public static final String TIMES_BOLD = BaseFont.TIMES_BOLD;
/** This is a possible value of a base 14 type 1 font */
public static final String TIMES_ITALIC = BaseFont.TIMES_ITALIC;
/** This is a possible value of a base 14 type 1 font */
public static final String TIMES_BOLDITALIC = BaseFont.TIMES_BOLDITALIC;
/** This is a possible value of a base 14 type 1 font */
public static final String ZAPFDINGBATS = BaseFont.ZAPFDINGBATS;
/**
* Default page height.
*/
final protected static int DEFAULT_PAGE_HEIGHT = 792;
/**
* Default page width.
*/
final protected static int DEFAULT_PAGE_WIDTH = 612;
/**
* Table mapping decimal numbers to hexadecimal numbers.
*/
final protected static char hd[] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
/**
* Output stream where postscript to be output.
*/
protected PrintStream out = System.out;
/**
* The current color
*/
protected Color clr = Color.white;
/**
* The current font
*/
protected Font font = new Font( Font.HELVETICA, 12, Font.NORMAL );
/**
* log
*/
protected static Logger log = Logger.getLogger( PostscriptWriter.class
.getName( ) );
/**
* Current page index with 1 as default value.
*/
private int pageIndex = 1;
/**
* Height of current page.
*/
private float pageHeight = DEFAULT_PAGE_HEIGHT;
private static Set<String> intrinsicFonts = new HashSet<String>( );
private int imageIndex = 0;
private Map<String, String> cachedImageSource;
private Stack<Graphic> graphics = new Stack<Graphic>( );
private final static String[] stringCommands = {"drawSStr", "drawStr",
"drawSBStr", "drawBStr", "drawSIStr", "drawIStr", "drawSBIStr",
"drawBIStr"};
static
{
intrinsicFonts.add( COURIER );
intrinsicFonts.add( COURIER_BOLD );
intrinsicFonts.add( COURIER_OBLIQUE );
intrinsicFonts.add( COURIER_BOLDOBLIQUE );
intrinsicFonts.add( HELVETICA );
intrinsicFonts.add( HELVETICA_BOLD );
intrinsicFonts.add( HELVETICA_OBLIQUE );
intrinsicFonts.add( HELVETICA_BOLDOBLIQUE );
intrinsicFonts.add( SYMBOL );
intrinsicFonts.add( TIMES );
intrinsicFonts.add( TIMES_ROMAN );
intrinsicFonts.add( TIMES_BOLD );
intrinsicFonts.add( TIMES_ITALIC );
intrinsicFonts.add( TIMES_BOLDITALIC );
intrinsicFonts.add( ZAPFDINGBATS );
}
public static boolean isIntrinsicFont( String fontName )
{
return intrinsicFonts.contains( fontName );
}
/**
* Constructor.
*
* @param out
* Output stream for PostScript output.
* @param title
* title of the postscript document.
*/
public PostscriptWriter( OutputStream o, String title )
{
this.out = new PrintStream( o );
this.cachedImageSource = new HashMap<String, String>();
emitProlog( title );
}
public void clipRect( float x, float y, float width, float height )
{
y = transformY( y );
out.println( x + " " + y + " " + width + " " + height + " rcl" );
}
public void clipSave()
{
gSave( );
}
public void clipRestore()
{
gRestore( );
}
/**
* Draws a image.
*
* @param imageStream
* the source input stream of the image.
* @param x
* the x position.
* @param y
* the y position.
* @param width
* the image width.
* @param height
* the image height.
* @throws IOException
*/
public void drawImage( String imageId, InputStream imageStream, float x, float y,
float width, float height ) throws Exception
{
Image image = ImageIO.read( imageStream );
drawImage( imageId, image, x, y, width, height );
}
/**
* Draws a image with specified image data, position, size and background
* color.
*
* @param image
* the source image data.
* @param x
* the x position.
* @param y
* the y position.
* @param width
* the image width.
* @param height
* the image height.
* @param bgcolor
* the background color.
* @throws Exception
*/
public void drawImage( String imageId, Image image, float x, float y, float width,
float height ) throws IOException
{
if ( image == null )
{
throw new IllegalArgumentException( "null image." );
}
y = transformY( y );
//if imageId is null, the image will not be cached.
if ( imageId == null )
{
outputUncachedImage( image, x, y, width, height );
}
else
{
// NOTICE: if width or height is 0, then the width and height will
// be replaced by the intrinsic width and height of the image. This
// logic is hard coded in postscript code and can't be found in java
// code.
outputCachedImage( imageId, image, x, y, width, height );
}
}
private void outputCachedImage( String imageId, Image image, float x,
float y, float width, float height ) throws IOException
{
String imageName = getImageName( imageId, image );
out.print( imageName + " ");
out.print( x + " " + y + " ");
out.println( width + " " + height + " drawimage");
}
private void outputUncachedImage( Image image, float x, float y,
float width, float height ) throws IOException
{
ArrayImageSource imageSource = getImageSource( image );
out.print( x + " " + y + " ");
out.print( width + " " + height + " " );
out.print( imageSource.getWidth( ) + " " + imageSource.getHeight( ) );
out.println( " drawstreamimage");
outputImageSource( imageSource );
out.println( "grestore" );
}
private ArrayImageSource getImageSource( Image image ) throws IOException
{
ImageIcon imageIcon = new ImageIcon( image );
int w = imageIcon.getIconWidth( );
int h = imageIcon.getIconHeight( );
int[] pixels = new int[w * h];
try
{
PixelGrabber pg = new PixelGrabber( image, 0, 0, w, h, pixels, 0, w );
pg.grabPixels( );
if ( ( pg.getStatus( ) & ImageObserver.ABORT ) != 0 )
{
throw new IOException( "failed to load image contents" );
}
}
catch ( InterruptedException e )
{
throw new IOException( "image load interrupted" );
}
ArrayImageSource imageSource = new ArrayImageSource( w, h, pixels );
return imageSource;
}
private String getImageName( String imageId, Image image ) throws IOException
{
String name = (String) cachedImageSource.get( imageId );
if ( name == null )
{
name = "image" + imageIndex++;
cachedImageSource.put( imageId, name );
ArrayImageSource imageSource = getImageSource( image );
outputNamedImageSource( name, imageSource );
}
return name;
}
private void outputNamedImageSource( String name, ArrayImageSource imageSource )
{
out.println( "startDefImage" );
outputImageSource( imageSource );
out.println( "/" + name + " " + imageSource.getWidth( ) + " "
+ imageSource.getHeight( ) + " endDefImage" );
}
private void outputImageSource( ArrayImageSource imageSource )
{
int originalWidth = imageSource.getWidth( );
int originalHeight = imageSource.getHeight( );
byte[] buffer = new byte[3 * originalHeight * originalWidth];
int index = 0;
for ( int i = 0; i < originalHeight; i++ )
{
for ( int j = 0; j < originalWidth; j++ )
{
int pixel = imageSource.getRGB( j, i );
int alpha = ( pixel >> 24 ) & 0xff;
int red = ( pixel >> 16 ) & 0xff;
int green = ( pixel >> 8 ) & 0xff;
int blue = pixel & 0xff;
buffer[index++] = (byte) transferColor( alpha, red );
buffer[index++] = (byte) transferColor( alpha, green );
buffer[index++] = (byte) transferColor( alpha, blue );
}
}
try
{
buffer = deflate( buffer );
out.print( Util.toHexString( buffer ) + ">" );
}
catch ( IOException e )
{
log.log( Level.WARNING, e.getLocalizedMessage( ), e );
}
}
private byte[] deflate( byte[] source ) throws IOException
{
ByteArrayOutputStream deflateSource = new ByteArrayOutputStream( );
DeflaterOutputStream deflateOut = new DeflaterOutputStream(
deflateSource, new Deflater( Deflater.DEFAULT_COMPRESSION ) );
deflateOut.write( source );
deflateOut.finish( );
deflateOut.close( );
byte[] byteArray = deflateSource.toByteArray( );
deflateSource.close( );
return byteArray;
}
private int transferColor( int alpha, int color )
{
return 255 - (255 - color) * alpha / 255;
}
protected void drawRect( float x, float y, float width, float height )
{
drawRawRect( x, y, width, height );
out.println( "fill" );
}
private void drawRawRect( float x, float y, float width, float height )
{
y = transformY( y );
out.println( x + " " + y + " " + width + " " + height + " rect" );
}
/**
* Draws background image in a rectangle area with specified repeat pattern.
* <br>
* <br>
* The repeat mode can be: <table border="solid">
* <tr>
* <td align="center"><B>Name</td>
* <td align="center"><B>What for</td>
* </tr>
* <tr>
* <td>no-repeat</td>
* <td>Don't repeat.</td>
* </tr>
* <tr>
* <td>repeat-x</td>
* <td>Only repeat on x orientation.</td>
* </tr>
* <tr>
* <td>repeat-y</td>
* <td>Only repeat on y orientation.</td>
* </tr>
* <tr>
* <td>repeat</td>
* <td>Repeat on x and y orientation.</td>
* </tr>
* </table>
*
* @param imageURI
* the uri of the background image.
* @param x
* the x coordinate of the rectangle area.
* @param y
* the y coordinate of the rectangle area.
* @param width
* the width of the rectangle area.
* @param height
* the height of the rectangle area.
* @param positionX
* the initial x position of the background image.
* @param positionY
* the initial y position of the background image.
* @param repeat
* the repeat mode.
* @throws Exception
*/
public void drawBackgroundImage( String imageURI, float x, float y,
float width, float height, float imageWidth, float imageHeight,
float positionX, float positionY, int repeat ) throws IOException
{
if ( imageURI == null || imageURI.length( ) == 0 )
{
return;
}
org.eclipse.birt.report.engine.layout.emitter.Image image = EmitterUtil
.parseImage( null, IImageContent.IMAGE_URL, imageURI, null,
null );
byte[] imageData = image.getData( );
if ( imageWidth == 0 || imageHeight == 0 )
{
int resolutionX = image.getPhysicalWidthDpi( );
int resolutionY = image.getPhysicalHeightDpi( );
if ( 0 == resolutionX || 0 == resolutionY )
{
resolutionX = 96;
resolutionY = 96;
}
- imageWidth = image.getWidth( ) / resolutionX * 72;
- imageHeight = image.getHeight( ) / resolutionY * 72;
+ imageWidth = ( (float) image.getWidth( ) ) / resolutionX * 72;
+ imageHeight = ( (float) image.getHeight( ) ) / resolutionY * 72;
}
Position imageSize = new Position( imageWidth, imageHeight );
Position areaPosition = new Position( x, y );
Position areaSize = new Position( width, height );
Position imagePosition = new Position( x + positionX, y + positionY );
BackgroundImageLayout layout = new BackgroundImageLayout( areaPosition,
areaSize, imagePosition, imageSize );
Collection positions = layout.getImagePositions( repeat );
gSave( );
setColor( Color.WHITE );
out.println( "newpath" );
drawRawRect( x, y, width, height );
out.println( "closepath clip" );
Iterator iterator = positions.iterator( );
while ( iterator.hasNext( ) )
{
Position position = (Position) iterator.next( );
try
{
drawImage( imageURI, new ByteArrayInputStream( imageData ),
position.getX( ), position.getY( ), imageSize.getX( ),
imageSize.getY( ) );
}
catch ( Exception e )
{
log.log( Level.WARNING, e.getLocalizedMessage( ) );
}
}
gRestore( );
}
/**
* Draws a line from (startX, startY) to (endX, endY) with specified line
* width, color and line style.
*
* Line style can be "dotted", "dash", and "double".
*
* @param startX
* the x coordinate of start point.
* @param startY
* the y coordinate of start point.
* @param endX
* the x coordinate of end point.
* @param endY
* the y coordinate of end point.
* @param width
* the line width.
* @param color
* the color.
* @param lineStyle
* the line style.
*/
public void drawLine( float startX, float startY, float endX, float endY,
float width, Color color, int lineStyle )
{
if ( null == color || 0f == width
|| lineStyle==BorderInfo.BORDER_STYLE_NONE ) //$NON-NLS-1$
{
return;
}
// double is not supported.
if ( lineStyle==BorderInfo.BORDER_STYLE_DOUBLE ) //$NON-NLS-1$
{
return;
}
int dashMode = 0;
if ( lineStyle==BorderInfo.BORDER_STYLE_DASHED ) //$NON-NLS-1$
{
dashMode = 1;
}
else if (lineStyle==BorderInfo.BORDER_STYLE_DOTTED ) //$NON-NLS-1$
{
dashMode = 2;
}
startY = transformY( startY );
endY = transformY( endY );
outputColor( color );
out.print( width + " " + dashMode + " ");
out.print( startX + " " + startY + " ");
out.print( endX + " " + endY + " ");
out.println( "drawline");
}
private void gRestore( )
{
out.println( "grestore" );
graphics.pop();
}
private void gSave( )
{
out.println( "gsave" );
graphics.push( new Graphic( ) );
}
private Map<File, ITrueTypeWriter> trueTypeFontWriters = new HashMap<File, ITrueTypeWriter>( );
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.postscript.IWriter#drawString(java.lang.String,
* int, int, org.eclipse.birt.report.engine.layout.pdf.font.FontInfo,
* float, float, java.awt.Color, boolean, boolean, boolean)
*/
public void drawString( String str, float x, float y, FontInfo fontInfo,
float letterSpacing, float wordSpacing, Color color,
boolean linethrough, boolean overline, boolean underline,
CSSValue align )
{
y = transformY( y );
String text = str;
boolean needSimulateItalic = false;
boolean needSimulateBold = false;
boolean hasSpace = wordSpacing != 0 || letterSpacing != 0;
float offset = 0;
if ( fontInfo != null )
{
float fontSize = fontInfo.getFontSize( );
int fontStyle = fontInfo.getFontStyle( );
if ( fontInfo.getSimulation( ) )
{
if ( fontStyle == Font.BOLD || fontStyle == Font.BOLDITALIC )
{
offset = (float) ( fontSize * Math.log10( fontSize ) / 100 );
needSimulateBold = true;
}
if ( fontStyle == Font.ITALIC || fontStyle == Font.BOLDITALIC )
{
needSimulateItalic = true;
}
}
BaseFont baseFont = fontInfo.getBaseFont( );
String fontName = baseFont.getPostscriptFontName( );
text = applyFont( fontName, fontStyle, fontSize, text );
}
outputColor( color );
out.print( x + " " + y + " " );
if ( hasSpace )
out.print( wordSpacing + " " + letterSpacing + " " );
out.print( text + " ");
if ( needSimulateBold )
out.print( offset + " " );
String command = getCommand( hasSpace, needSimulateBold,
needSimulateItalic );
out.println( command );
}
private String getCommand( boolean hasSpace, boolean needSimulateBold,
boolean needSimulateItalic )
{
int index = toInt( hasSpace );
index += toInt( needSimulateBold ) << 1;
index += toInt( needSimulateItalic ) << 2 ;
return stringCommands[index];
}
private int toInt( boolean b )
{
return b ? 1 : 0;
}
/**
* Top of every PS file
*/
protected void emitProlog( String title )
{
out.println( "%!PS-Adobe-3.0" );
if ( title != null )
{
out.println( "%%Title: " + title );
}
out.println( "% (C)2006 Actuate Inc." );
}
public void fillRect( float x, float y, float width, float height,
Color color )
{
gSave( );
setColor( color );
drawRect( x, y, width, height );
gRestore( );
}
/**
* Disposes of this graphics context once it is no longer referenced.
*
* @see #dispose
*/
public void finalize( )
{
dispose( );
}
public void dispose( )
{
out.println( "%dispose" );
}
public Color getColor( )
{
return clr;
}
public Font getFont( )
{
return font;
}
public void setColor( Color c )
{
outputColor( c );
}
private void outputColor( Color c )
{
if ( c == null )
{
c = Color.black;
}
Graphic currentGraphic = getCurrentGraphic( );
if ( c.equals( currentGraphic.color ) )
{
return;
}
currentGraphic.color = c;
out.print( c.getRed( ) / 255.0 );
out.print( " " );
out.print( c.getGreen( ) / 255.0 );
out.print( " " );
out.print( c.getBlue( ) / 255.0 );
out.print( " " );
out.println( "setrgbcolor");
}
public void setFont( Font f )
{
if ( f != null )
{
this.font = f;
String javaName = font.getFamilyname( );
int javaStyle = font.getStyle( );
setFont( javaName, javaStyle );
}
}
private boolean needSetFont( String fontName, float fontSize )
{
Graphic graphic = getCurrentGraphic( );
float currentFontSize = graphic.fontSize;
String currentFont = graphic.font;
//If fontSize is changed, set font.
if ( fontSize != currentFontSize )
{
return true;
}
//If font name is changed, set font.
if ( currentFont == null && fontName != null )
{
return true;
}
if ( currentFont != null && !currentFont.equals( fontName ) )
{
return true;
}
return false;
}
private void setFont( String font, float size )
{
if ( needSetFont( font, size) )
{
setCurrentGraphic( font, size );
out.println( "/" + font + " " + size + " usefont" );
}
}
private void setCurrentGraphic( String font, float fontSize )
{
Graphic graphic = getCurrentGraphic( );
graphic.font = font;
graphic.fontSize = fontSize;
}
private Graphic getCurrentGraphic( )
{
Graphic currentGraphic = null;
if ( graphics.isEmpty( ) )
{
currentGraphic = new Graphic( );
graphics.push( currentGraphic );
}
else
{
currentGraphic = graphics.peek( );
}
return currentGraphic;
}
private String applyFont( String fontName, int fontStyle, float fontSize,
String text )
{
if ( isIntrinsicFont( fontName ) )
{
return applyIntrinsicFont( fontName, fontStyle, fontSize, text );
}
else
{
try
{
String fontPath = getFontPath( fontName );
if ( fontPath == null )
{
return applyIntrinsicFont( fontName, fontStyle, fontSize, text );
}
ITrueTypeWriter trueTypeWriter = getTrueTypeFontWriter(
fontPath, fontName );
//Space can't be included in a identity.
trueTypeWriter.ensureGlyphsAvailable( text );
String displayName = trueTypeWriter.getDisplayName( );
setFont( displayName, fontSize );
return trueTypeWriter.toHexString( text );
}
catch ( Exception e )
{
log.log( Level.WARNING, "apply font: " + fontName );
}
return null;
}
}
private String applyIntrinsicFont( String fontName, int fontStyle, float fontSize, String text )
{
setFont( fontName, fontSize );
text = escapeSpecialCharacter( text );
return ( "(" + text + ")" );
}
/**
* Escape the characters "(", ")", and "\" in a postscript string by "\".
*
* @param source
* @return
*/
private static String escapeSpecialCharacter( String source )
{
Pattern pattern = Pattern.compile( "(\\\\|\\)|\\()" );
Matcher matcher = pattern.matcher( source );
StringBuffer buffer = new StringBuffer( );
while ( matcher.find( ) )
{
matcher.appendReplacement( buffer, "\\\\\\" + matcher.group( 1 ) );
}
matcher.appendTail( buffer );
return buffer.toString( );
}
private ITrueTypeWriter getTrueTypeFontWriter( String fontPath, String fontName )
throws DocumentException, IOException
{
File file = new File( fontPath );
ITrueTypeWriter trueTypeWriter = (ITrueTypeWriter) trueTypeFontWriters
.get( file );
if ( trueTypeWriter != null )
{
return trueTypeWriter;
}
else
{
TrueTypeFont ttFont = TrueTypeFont.getInstance( fontPath );
trueTypeWriter = ttFont.getTrueTypeWriter( out );
trueTypeWriter.initialize( fontName );
trueTypeFontWriters.put( file, trueTypeWriter );
return trueTypeWriter;
}
}
private String getFontPath( String fontName )
{
try
{
FontFactoryImp fontImpl = FontFactory.getFontImp( );
Properties trueTypeFonts = (Properties) getField(
FontFactoryImp.class, "trueTypeFonts", fontImpl );
String fontPath = trueTypeFonts.getProperty( fontName.toLowerCase( ) );
return fontPath;
}
catch ( Exception e )
{
log.log( Level.WARNING, "font path: " + fontName );
}
return null;
}
private Object getField( final Class fontFactoryClass,
final String fieldName, final Object instaces )
throws NoSuchFieldException, IllegalAccessException
{
try
{
Object field = (Object) AccessController
.doPrivileged( new PrivilegedExceptionAction<Object>( ) {
public Object run( ) throws IllegalArgumentException,
IllegalAccessException, NoSuchFieldException
{
Field fldTrueTypeFonts = fontFactoryClass
.getDeclaredField( fieldName );// $NON-SEC-3
fldTrueTypeFonts.setAccessible( true );// $NON-SEC-2
return fldTrueTypeFonts.get( instaces );
}
} );
return field;
}
catch ( PrivilegedActionException e )
{
Exception typedException = e.getException( );
if ( typedException instanceof IllegalArgumentException )
{
throw (IllegalArgumentException) typedException;
}
if ( typedException instanceof IllegalAccessException )
{
throw (IllegalAccessException) typedException;
}
if ( typedException instanceof NoSuchFieldException )
{
throw (NoSuchFieldException) typedException;
}
}
return null;
}
protected float transformY( float y )
{
return pageHeight - y;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.postscript.IWriter#translate(int,
* int)
*/
public void translate( int x, int y )
{
out.print( x );
out.print( " " );
out.print( y );
out.println( " translate" );
}
public void startRenderer( String paperSize, String paperTray,
String duplex, int copies, boolean collate ) throws IOException
{
startRenderer( null, null, paperSize, paperTray, duplex, copies,
collate );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.postscript.IWriter#startRenderer()
*/
public void startRenderer( String author, String description,
String paperSize, String paperTray, String duplex, int copies,
boolean collate ) throws IOException
{
if ( author != null )
{
out.println("%%Creator: " + author);
}
out.println( "%%Pages: (atend)");
out.println( "%%DocumentProcessColors: Black");
out.println( "%%BeginSetup");
setCollate( collate );
setCopies( copies );
setPaperSize( paperSize );
setPaperTray( paperTray );
setDuplex( duplex );
FileUtil.load(
"org/eclipse/birt/report/engine/emitter/postscript/header.ps",
out );
}
private void setPaperTray( String paperTray )
{
if ( paperTray != null )
{
out.println( "%%BeginFeature: *InputSlot " + paperTray );
out.println("%%EndFeature");
}
}
private void setPaperSize( String paperSize )
{
if ( paperSize != null )
{
out.println( "%%BeginFeature: *PageSize " + paperSize );
out.println( "<</PageSize [" + getPaperSize( paperSize )
+ "] /ImagingBBox null>> setpagedevice" );
out.println("%%EndFeature");
}
}
private void setCopies( int copies )
{
if ( copies > 1 )
{
out.println( "%%BeginNonPPDFeature: NumCopies " + copies );
out.println( "<</NumCopies " + copies + ">> setpagedevice" );
out.println( "%%EndNonPPDFeature" );
}
}
private void setCollate( boolean collate )
{
if ( collate )
{
out.println( "%%Requirements: collate");
}
}
private void setDuplex( String duplex )
{
if ( duplex != null && !"SIMPLEX".equalsIgnoreCase( duplex ))
{
String duplexValue = duplex;
if ("HORIZONTAL".equalsIgnoreCase( duplex ))
{
duplexValue = "DuplexTumble";
}
else if ("VERTICAL".equalsIgnoreCase( duplex ) )
{
duplexValue = "DuplexNoTumble";
}
out.println( "%%BeginFeature: *Duplex " + duplexValue );
out.println("<</Duplex true /Tumble true>> setpagedevice");
out.println("%%EndFeature");
}
}
private String getPaperSize( String paperSize )
{
int width = 595;
int height = 842;
if ( "Letter".equalsIgnoreCase( paperSize ) )
{
width = 612;
height = 792;
}
else if ( "Legal".equalsIgnoreCase( paperSize ) )
{
width = 612;
height = 1008;
}
else if ( "A5".equalsIgnoreCase( paperSize ) )
{
width = 419;
height = 595;
}
else if ( "A4".equalsIgnoreCase( paperSize ) )
{
width = 595;
height = 842;
}
else if ( "A3".equalsIgnoreCase( paperSize ) )
{
width = 842;
height = 1191;
}
else if ( "B5".equalsIgnoreCase( paperSize ) )
{
width = 499;
height = 709;
}
else if ( "B4".equalsIgnoreCase( paperSize ) )
{
width = 729;
height = 1032;
}
return width + " " + height;
}
public void fillPage( Color color )
{
if ( color == null )
{
return;
}
gSave( );
setColor( color );
out.println( "clippath fill" );
gRestore( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.postscript.IWriter#startPage(float,
* float)
*/
public void startPage( float pageWidth, float pageHeight )
{
this.pageHeight = pageHeight;
out.println( "%%Page: " + pageIndex + " " + pageIndex );
out.println( "%%PageBoundingBox: 0 0 " + (int) Math.round( pageWidth )
+ " " + (int) Math.round( pageHeight ) );
out.println( "%%BeginPage" );
++pageIndex;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.postscript.IWriter#endPage()
*/
public void endPage( )
{
out.println( "showpage" );
out.println( "%%PageTrailer" );
out.println( "%%EndPage" );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.postscript.IWriter#stopRenderer()
*/
public void stopRenderer( ) throws IOException
{
out.println( "%%Trailer" );
out.println( "%%Pages: " + ( pageIndex - 1 ) );
out.println( "%%EOF" );
out.flush( );
}
public abstract class ImageSource
{
protected int height;
protected int width;
public ImageSource( int width, int height )
{
this.width = width;
this.height = height;
}
public int getHeight( )
{
return height;
}
public int getWidth( )
{
return width;
}
public abstract int getRGB( int x, int y );
}
public class ArrayImageSource extends ImageSource
{
private int[] imageSource;
public ArrayImageSource( int width, int height, int[] imageSource )
{
super( width, height );
this.imageSource = imageSource;
}
public int getRGB( int x, int y )
{
return imageSource[y * width + x];
}
public int[] getData()
{
return imageSource;
}
}
public void close( ) throws IOException
{
stopRenderer( );
out.close( );
}
private static class Graphic {
private String font;
private float fontSize;
private Color color;
public Graphic( )
{
}
public Graphic( String font, float fontSize )
{
this.font = font;
this.fontSize = fontSize;
}
}
}
| true | true | public void drawBackgroundImage( String imageURI, float x, float y,
float width, float height, float imageWidth, float imageHeight,
float positionX, float positionY, int repeat ) throws IOException
{
if ( imageURI == null || imageURI.length( ) == 0 )
{
return;
}
org.eclipse.birt.report.engine.layout.emitter.Image image = EmitterUtil
.parseImage( null, IImageContent.IMAGE_URL, imageURI, null,
null );
byte[] imageData = image.getData( );
if ( imageWidth == 0 || imageHeight == 0 )
{
int resolutionX = image.getPhysicalWidthDpi( );
int resolutionY = image.getPhysicalHeightDpi( );
if ( 0 == resolutionX || 0 == resolutionY )
{
resolutionX = 96;
resolutionY = 96;
}
imageWidth = image.getWidth( ) / resolutionX * 72;
imageHeight = image.getHeight( ) / resolutionY * 72;
}
Position imageSize = new Position( imageWidth, imageHeight );
Position areaPosition = new Position( x, y );
Position areaSize = new Position( width, height );
Position imagePosition = new Position( x + positionX, y + positionY );
BackgroundImageLayout layout = new BackgroundImageLayout( areaPosition,
areaSize, imagePosition, imageSize );
Collection positions = layout.getImagePositions( repeat );
gSave( );
setColor( Color.WHITE );
out.println( "newpath" );
drawRawRect( x, y, width, height );
out.println( "closepath clip" );
Iterator iterator = positions.iterator( );
while ( iterator.hasNext( ) )
{
Position position = (Position) iterator.next( );
try
{
drawImage( imageURI, new ByteArrayInputStream( imageData ),
position.getX( ), position.getY( ), imageSize.getX( ),
imageSize.getY( ) );
}
catch ( Exception e )
{
log.log( Level.WARNING, e.getLocalizedMessage( ) );
}
}
gRestore( );
}
| public void drawBackgroundImage( String imageURI, float x, float y,
float width, float height, float imageWidth, float imageHeight,
float positionX, float positionY, int repeat ) throws IOException
{
if ( imageURI == null || imageURI.length( ) == 0 )
{
return;
}
org.eclipse.birt.report.engine.layout.emitter.Image image = EmitterUtil
.parseImage( null, IImageContent.IMAGE_URL, imageURI, null,
null );
byte[] imageData = image.getData( );
if ( imageWidth == 0 || imageHeight == 0 )
{
int resolutionX = image.getPhysicalWidthDpi( );
int resolutionY = image.getPhysicalHeightDpi( );
if ( 0 == resolutionX || 0 == resolutionY )
{
resolutionX = 96;
resolutionY = 96;
}
imageWidth = ( (float) image.getWidth( ) ) / resolutionX * 72;
imageHeight = ( (float) image.getHeight( ) ) / resolutionY * 72;
}
Position imageSize = new Position( imageWidth, imageHeight );
Position areaPosition = new Position( x, y );
Position areaSize = new Position( width, height );
Position imagePosition = new Position( x + positionX, y + positionY );
BackgroundImageLayout layout = new BackgroundImageLayout( areaPosition,
areaSize, imagePosition, imageSize );
Collection positions = layout.getImagePositions( repeat );
gSave( );
setColor( Color.WHITE );
out.println( "newpath" );
drawRawRect( x, y, width, height );
out.println( "closepath clip" );
Iterator iterator = positions.iterator( );
while ( iterator.hasNext( ) )
{
Position position = (Position) iterator.next( );
try
{
drawImage( imageURI, new ByteArrayInputStream( imageData ),
position.getX( ), position.getY( ), imageSize.getX( ),
imageSize.getY( ) );
}
catch ( Exception e )
{
log.log( Level.WARNING, e.getLocalizedMessage( ) );
}
}
gRestore( );
}
|
diff --git a/src/com/linkomnia/android/StrokeFiveKeyboard/Stroke5Table.java b/src/com/linkomnia/android/StrokeFiveKeyboard/Stroke5Table.java
index e1b912f..1f5f71c 100644
--- a/src/com/linkomnia/android/StrokeFiveKeyboard/Stroke5Table.java
+++ b/src/com/linkomnia/android/StrokeFiveKeyboard/Stroke5Table.java
@@ -1,83 +1,84 @@
package com.linkomnia.android.StrokeFiveKeyboard;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class Stroke5Table {
public static final String TABLE_NAME = "stroke5";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_CHAR = "char";
public static final String COLUMN_CODE = "code";
public static final String COLUMN_USAGE = "usage";
protected static final String TABLE_CREATE = "create table " + TABLE_NAME + "( "
+ COLUMN_ID + " integer primary key autoincrement, "
+ COLUMN_CHAR + " VARCHAR(5) not null, "
+ COLUMN_CODE + " VARCHAR(5) not null, "
+ COLUMN_USAGE + " integer DEFAULT 0 "
+ " );";
protected static final String TABLE_DROP = "DROP TABLE IF EXISTS " + TABLE_NAME;
private boolean isWritable;
private SQLiteDatabase database;
private Stroke5SQLiteHelper dbHelper;
private String[] searchColumns = { Stroke5Table.COLUMN_CHAR };
public Stroke5Table(Context context, boolean isWritable) {
dbHelper = new Stroke5SQLiteHelper(context);
this.isWritable = isWritable;
}
public void open() throws SQLException {
if (isWritable) {
database = dbHelper.getWritableDatabase();
} else {
database = dbHelper.getReadableDatabase();
}
}
public void close() {
dbHelper.close();
}
public void createRecord(String ch, String code) {
if (!isWritable) {
return;
}
ContentValues values = new ContentValues();
values.put(Stroke5Table.COLUMN_CHAR, ch);
values.put(Stroke5Table.COLUMN_CODE, code);
database.insert(Stroke5Table.TABLE_NAME, null,
values);
// To show how to query
}
public ArrayList<String> searchRecord(String input) {
ArrayList<String> result = new ArrayList<String>();
- String[] args = {input};
- String order = Stroke5Table.COLUMN_USAGE+" DESC , "+ Stroke5Table.COLUMN_ID +" ASC";
+ String[] args = {input+"%"};
+ String groupby = " " + Stroke5Table.COLUMN_CODE + " ";
+ String order = Stroke5Table.COLUMN_USAGE+" DESC , "+ Stroke5Table.COLUMN_ID +" ASC ";
Cursor cursor = database.query(Stroke5Table.TABLE_NAME,
- searchColumns, Stroke5Table.COLUMN_CODE + " = ? ", args, null, null, order );
+ searchColumns, Stroke5Table.COLUMN_CODE + " like ? ", args, null, null, order );
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
String ch = cursor.getString(cursor.getColumnIndex(Stroke5Table.COLUMN_CHAR)) ;
result.add(ch);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return result;
}
}
| false | true | public ArrayList<String> searchRecord(String input) {
ArrayList<String> result = new ArrayList<String>();
String[] args = {input};
String order = Stroke5Table.COLUMN_USAGE+" DESC , "+ Stroke5Table.COLUMN_ID +" ASC";
Cursor cursor = database.query(Stroke5Table.TABLE_NAME,
searchColumns, Stroke5Table.COLUMN_CODE + " = ? ", args, null, null, order );
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
String ch = cursor.getString(cursor.getColumnIndex(Stroke5Table.COLUMN_CHAR)) ;
result.add(ch);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return result;
}
| public ArrayList<String> searchRecord(String input) {
ArrayList<String> result = new ArrayList<String>();
String[] args = {input+"%"};
String groupby = " " + Stroke5Table.COLUMN_CODE + " ";
String order = Stroke5Table.COLUMN_USAGE+" DESC , "+ Stroke5Table.COLUMN_ID +" ASC ";
Cursor cursor = database.query(Stroke5Table.TABLE_NAME,
searchColumns, Stroke5Table.COLUMN_CODE + " like ? ", args, null, null, order );
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
String ch = cursor.getString(cursor.getColumnIndex(Stroke5Table.COLUMN_CHAR)) ;
result.add(ch);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return result;
}
|
diff --git a/source/de/anomic/http/httpdFileHandler.java b/source/de/anomic/http/httpdFileHandler.java
index 78240b13e..92723e514 100644
--- a/source/de/anomic/http/httpdFileHandler.java
+++ b/source/de/anomic/http/httpdFileHandler.java
@@ -1,1003 +1,1003 @@
// httpdFileHandler.java
// -----------------------
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004, 2005
// last major change: 05.10.2005
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
/*
Class documentation:
this class provides a file servlet and CGI interface
for the httpd server.
Whenever this server is addressed to load a local file,
this class searches for the file in the local path as
configured in the setting property 'rootPath'
The servlet loads the file and returns it to the client.
Every file can also act as an template for the built-in
CGI interface. There is no specific path for CGI functions.
CGI functionality is triggered, if for the file to-be-served
'template.html' also a file 'template.class' exists. Then,
the class file is called with the GET/POST properties that
are attached to the http call.
Possible variable hand-over are:
- form method GET
- form method POST, enctype text/plain
- form method POST, enctype multipart/form-data
The class that creates the CGI respond must have at least one
static method of the form
public static java.util.Hashtable respond(java.util.HashMap, serverSwitch)
In the HashMap, the GET/POST variables are handed over.
The return value is a Property object that contains replacement
key/value pairs for the patterns in the template file.
The templates must have the form
either '#['<name>']#' for single attributes, or
'#{'<enumname>'}#' and '#{/'<enumname>'}#' for enumerations of
values '#['<value>']#'.
A single value in repetitions/enumerations in the template has
the property key '_'<enumname><count>'_'<value>
Please see also the example files 'test.html' and 'test.java'
*/
package de.anomic.http;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.ref.SoftReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.zip.GZIPOutputStream;
import de.anomic.htmlFilter.htmlFilterContentScraper;
import de.anomic.plasma.plasmaParser;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.plasma.plasmaSwitchboardConstants;
import de.anomic.server.serverByteBuffer;
import de.anomic.server.serverClassLoader;
import de.anomic.server.serverCore;
import de.anomic.server.serverDate;
import de.anomic.server.serverFileUtils;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.server.servletProperties;
import de.anomic.server.logging.serverLog;
import de.anomic.ymage.ymageMatrix;
public final class httpdFileHandler {
private static final boolean safeServletsMode = false; // if true then all servlets are called synchronized
private static final Properties mimeTable = new Properties();
// create a class loader
private static final serverClassLoader provider = new serverClassLoader(/*this.getClass().getClassLoader()*/);
private static serverSwitch<?> switchboard = null;
private static plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
private static File htRootPath = null;
private static File htDocsPath = null;
private static File htTemplatePath = null;
private static String[] defaultFiles = null;
private static File htDefaultPath = null;
private static File htLocalePath = null;
private static final HashMap<File, SoftReference<byte[]>> templateCache;
private static final HashMap<File, SoftReference<Method>> templateMethodCache;
public static final boolean useTemplateCache;
//private Properties connectionProperties = null;
// creating a logger
private static final serverLog theLogger = new serverLog("FILEHANDLER");
static {
final serverSwitch<?> theSwitchboard = plasmaSwitchboard.getSwitchboard();
useTemplateCache = theSwitchboard.getConfig("enableTemplateCache","true").equalsIgnoreCase("true");
templateCache = (useTemplateCache)? new HashMap<File, SoftReference<byte[]>>() : new HashMap<File, SoftReference<byte[]>>(0);
templateMethodCache = (useTemplateCache) ? new HashMap<File, SoftReference<Method>>() : new HashMap<File, SoftReference<Method>>(0);
if (httpdFileHandler.switchboard == null) {
httpdFileHandler.switchboard = theSwitchboard;
if (mimeTable.size() == 0) {
// load the mime table
final String mimeTablePath = theSwitchboard.getConfig("mimeConfig","");
BufferedInputStream mimeTableInputStream = null;
try {
serverLog.logConfig("HTTPDFiles", "Loading mime mapping file " + mimeTablePath);
mimeTableInputStream = new BufferedInputStream(new FileInputStream(new File(theSwitchboard.getRootPath(), mimeTablePath)));
mimeTable.load(mimeTableInputStream);
} catch (final Exception e) {
serverLog.logSevere("HTTPDFiles", "ERROR: path to configuration file or configuration invalid\n" + e);
System.exit(1);
} finally {
if (mimeTableInputStream != null) try { mimeTableInputStream.close(); } catch (final Exception e1) {}
}
}
// create default files array
initDefaultPath();
// create a htRootPath: system pages
if (htRootPath == null) {
htRootPath = new File(theSwitchboard.getRootPath(), theSwitchboard.getConfig(plasmaSwitchboardConstants.HTROOT_PATH, plasmaSwitchboardConstants.HTROOT_PATH_DEFAULT));
if (!(htRootPath.exists())) htRootPath.mkdir();
}
// create a htDocsPath: user defined pages
if (htDocsPath == null) {
htDocsPath = theSwitchboard.getConfigPath(plasmaSwitchboardConstants.HTDOCS_PATH, plasmaSwitchboardConstants.HTDOCS_PATH_DEFAULT);
if (!(htDocsPath.exists())) htDocsPath.mkdirs();
}
// create a repository path
final File repository = new File(htDocsPath, "repository");
if (!repository.exists()) repository.mkdirs();
// create a htTemplatePath
if (htTemplatePath == null) {
htTemplatePath = theSwitchboard.getConfigPath("htTemplatePath","htroot/env/templates");
if (!(htTemplatePath.exists())) htTemplatePath.mkdir();
}
//This is now handles by #%env/templates/foo%#
//if (templates.size() == 0) templates.putAll(httpTemplate.loadTemplates(htTemplatePath));
// create htLocaleDefault, htLocalePath
if (htDefaultPath == null) htDefaultPath = theSwitchboard.getConfigPath("htDefaultPath", "htroot");
if (htLocalePath == null) htLocalePath = theSwitchboard.getConfigPath("locale.translated_html", "DATA/LOCALE/htroot");
}
}
public static final void initDefaultPath() {
// create default files array
defaultFiles = switchboard.getConfig("defaultFiles","index.html").split(",");
if (defaultFiles.length == 0) defaultFiles = new String[] {"index.html"};
}
/** Returns a path to the localized or default file according to the locale.language (from he switchboard)
* @param path relative from htroot */
public static File getLocalizedFile(final String path){
return getLocalizedFile(path, switchboard.getConfig("locale.language","default"));
}
/** Returns a path to the localized or default file according to the parameter localeSelection
* @param path relative from htroot
* @param localeSelection language of localized file; locale.language from switchboard is used if localeSelection.equals("") */
public static File getLocalizedFile(final String path, final String localeSelection){
if (htDefaultPath == null) htDefaultPath = switchboard.getConfigPath("htDefaultPath","htroot");
if (htLocalePath == null) htLocalePath = switchboard.getConfigPath("locale.translated_html","DATA/LOCALE/htroot");
if (!(localeSelection.equals("default"))) {
final File localePath = new File(htLocalePath, localeSelection + '/' + path);
if (localePath.exists()) // avoid "NoSuchFile" troubles if the "localeSelection" is misspelled
return localePath;
}
return new File(htDefaultPath, path);
}
// private void textMessage(OutputStream out, int retcode, String body) throws IOException {
// httpd.sendRespondHeader(
// this.connectionProperties, // the connection properties
// out, // the output stream
// "HTTP/1.1", // the http version that should be used
// retcode, // the http status code
// null, // the http status message
// "text/plain", // the mimetype
// body.length(), // the content length
// httpc.nowDate(), // the modification date
// null, // the expires date
// null, // cookies
// null, // content encoding
// null); // transfer encoding
// out.write(body.getBytes());
// out.flush();
// }
private static final httpResponseHeader getDefaultHeaders(final String path) {
final httpResponseHeader headers = new httpResponseHeader();
String ext;
int pos;
if ((pos = path.lastIndexOf('.')) < 0) {
ext = "";
} else {
ext = path.substring(pos + 1).toLowerCase();
}
headers.put(httpResponseHeader.SERVER, "AnomicHTTPD (www.anomic.de)");
headers.put(httpResponseHeader.DATE, HttpClient.dateString(new Date()));
if(!(plasmaParser.mediaExtContains(ext))){
headers.put(httpResponseHeader.PRAGMA, "no-cache");
}
return headers;
}
public static void doGet(final Properties conProp, final httpRequestHeader requestHeader, final OutputStream response) {
doResponse(conProp, requestHeader, response, null);
}
public static void doHead(final Properties conProp, final httpRequestHeader requestHeader, final OutputStream response) {
doResponse(conProp, requestHeader, response, null);
}
public static void doPost(final Properties conProp, final httpRequestHeader requestHeader, final OutputStream response, final InputStream body) {
doResponse(conProp, requestHeader, response, body);
}
public static void doResponse(final Properties conProp, final httpRequestHeader requestHeader, final OutputStream out, final InputStream body) {
String path = null;
try {
// getting some connection properties
final String method = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD);
path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH);
String argsString = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // is null if no args were given
final String httpVersion = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER);
final String clientIP = conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP, "unknown-host");
// check hack attacks in path
if (path.indexOf("..") >= 0) {
httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null);
return;
}
// url decoding of path
try {
path = URLDecoder.decode(path, "UTF-8");
} catch (final UnsupportedEncodingException e) {
// This should never occur
assert(false) : "UnsupportedEncodingException: " + e.getMessage();
}
// check again hack attacks in path
if (path.indexOf("..") >= 0) {
httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null);
return;
}
// check permission/granted access
String authorization = requestHeader.get(httpRequestHeader.AUTHORIZATION);
if (authorization != null && authorization.length() == 0) authorization = null;
final String adminAccountBase64MD5 = switchboard.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "");
int pos = path.lastIndexOf(".");
final boolean adminAccountForLocalhost = sb.getConfigBool("adminAccountForLocalhost", false);
final String refererHost = requestHeader.refererHost();
final boolean accessFromLocalhost = serverCore.isLocalhost(clientIP) && (refererHost.length() == 0 || serverCore.isLocalhost(refererHost));
final boolean grantedForLocalhost = adminAccountForLocalhost && accessFromLocalhost;
final boolean protectedPage = (path.substring(0,(pos==-1)?path.length():pos)).endsWith("_p");
final boolean accountEmpty = adminAccountBase64MD5.length() == 0;
if (!grantedForLocalhost && protectedPage && !accountEmpty) {
// authentication required
if (authorization == null) {
// no authorization given in response. Ask for that
final httpResponseHeader responseHeader = getDefaultHeaders(path);
responseHeader.put(httpRequestHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\"");
//httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
final servletProperties tp=new servletProperties();
tp.put("returnto", path);
//TODO: separate error page Wrong Login / No Login
httpd.sendRespondError(conProp, out, 5, 401, "Wrong Authentication", "", new File("proxymsg/authfail.inc"), tp, null, responseHeader);
return;
} else if (
(httpd.staticAdminAuthenticated(authorization.trim().substring(6), switchboard) == 4) ||
(sb.userDB.hasAdminRight(authorization, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP), requestHeader.getHeaderCookies()))) {
//Authentication successful. remove brute-force flag
serverCore.bfHost.remove(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
} else {
// a wrong authentication was given or the userDB user does not have admin access. Ask again
serverLog.logInfo("HTTPD", "Wrong log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
final Integer attempts = serverCore.bfHost.get(clientIP);
if (attempts == null)
serverCore.bfHost.put(clientIP, Integer.valueOf(1));
else
serverCore.bfHost.put(clientIP, Integer.valueOf(attempts.intValue() + 1));
final httpResponseHeader headers = getDefaultHeaders(path);
headers.put(httpRequestHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
}
}
// parse arguments
serverObjects args = new serverObjects();
int argc = 0;
if (argsString == null) {
// no args here, maybe a POST with multipart extension
- int length = 0;
+ int length = requestHeader.getContentLength();
//System.out.println("HEADER: " + requestHeader.toString()); // DEBUG
if (method.equals(httpHeader.METHOD_POST)) {
// if its a POST, it can be either multipart or as args in the body
if ((requestHeader.containsKey(httpHeader.CONTENT_TYPE)) &&
(requestHeader.get(httpHeader.CONTENT_TYPE).toLowerCase().startsWith("multipart"))) {
// parse multipart
final HashMap<String, byte[]> files = httpd.parseMultipart(requestHeader, args, body);
// integrate these files into the args
if (files != null) {
final Iterator<Map.Entry<String, byte[]>> fit = files.entrySet().iterator();
Map.Entry<String, byte[]> entry;
while (fit.hasNext()) {
entry = fit.next();
args.put(entry.getKey() + "$file", entry.getValue());
}
}
argc = Integer.parseInt(requestHeader.get("ARGC"));
} else {
// parse args in body
argc = httpd.parseArgs(args, body, length);
}
} else {
// no args
argsString = null;
args = null;
argc = 0;
}
} else {
// simple args in URL (stuff after the "?")
argc = httpd.parseArgs(args, argsString);
}
// check for cross site scripting - attacks in request arguments
if (args != null && argc > 0) {
// check all values for occurrences of script values
final Iterator<String> e = args.values().iterator(); // enumeration of values
String val;
while (e.hasNext()) {
val = e.next();
if ((val != null) && (val.indexOf("<script") >= 0)) {
// deny request
httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null);
return;
}
}
}
// we are finished with parsing
// the result of value hand-over is in args and argc
if (path.length() == 0) {
httpd.sendRespondError(conProp,out,4,400,null,"Bad Request",null);
out.flush();
return;
}
File targetClass=null;
// locate the file
if (!(path.startsWith("/"))) path = "/" + path; // attach leading slash
// a different language can be desired (by i.e. ConfigBasic.html) than the one stored in the locale.language
String localeSelection = switchboard.getConfig("locale.language","default");
if (args != null && (args.containsKey("language"))) {
// TODO 9.11.06 Bost: a class with information about available languages is needed.
// the indexOf(".") is just a workaround because there from ConfigLanguage.html commes "de.lng" and
// from ConfigBasic.html comes just "de" in the "language" parameter
localeSelection = args.get("language", localeSelection);
if (localeSelection.indexOf(".") != -1)
localeSelection = localeSelection.substring(0, localeSelection.indexOf("."));
}
File targetFile = getLocalizedFile(path, localeSelection);
final String targetExt = conProp.getProperty("EXT","");
targetClass = rewriteClassFile(new File(htDefaultPath, path));
if (path.endsWith("/")) {
String testpath;
// attach default file name
for (int i = 0; i < defaultFiles.length; i++) {
testpath = path + defaultFiles[i];
targetFile = getOverlayedFile(testpath);
targetClass = getOverlayedClass(testpath);
if (targetFile.exists()) {
path = testpath;
break;
}
}
//no defaultfile, send a dirlisting
if (targetFile == null || !targetFile.exists()) {
final StringBuffer aBuffer = new StringBuffer();
aBuffer.append("<html>\n<head>\n</head>\n<body>\n<h1>Index of " + path + "</h1>\n <ul>\n");
final File dir = new File(htDocsPath, path);
String[] list = dir.list();
if (list == null) list = new String[0]; // should not occur!
File f;
String size;
long sz;
String headline, author, description;
int images, links;
htmlFilterContentScraper scraper;
for (int i = 0; i < list.length; i++) {
f = new File(dir, list[i]);
if (f.isDirectory()) {
aBuffer.append(" <li><a href=\"" + path + list[i] + "/\">" + list[i] + "/</a><br></li>\n");
} else {
if (list[i].endsWith("html") || (list[i].endsWith("htm"))) {
scraper = htmlFilterContentScraper.parseResource(f);
headline = scraper.getTitle();
author = scraper.getAuthor();
description = scraper.getDescription();
images = scraper.getImages().size();
links = scraper.getAnchors().size();
} else {
headline = null;
author = null;
description = null;
images = 0;
links = 0;
}
sz = f.length();
if (sz < 1024) {
size = sz + " bytes";
} else if (sz < 1024 * 1024) {
size = (sz / 1024) + " KB";
} else {
size = (sz / 1024 / 1024) + " MB";
}
aBuffer.append(" <li>");
if ((headline != null) && (headline.length() > 0)) aBuffer.append("<a href=\"" + list[i] + "\"><b>" + headline + "</b></a><br>");
aBuffer.append("<a href=\"" + path + list[i] + "\">" + list[i] + "</a><br>");
if ((author != null) && (author.length() > 0)) aBuffer.append("Author: " + author + "<br>");
if ((description != null) && (description.length() > 0)) aBuffer.append("Description: " + description + "<br>");
aBuffer.append(serverDate.formatShortDay(new Date(f.lastModified())) + ", " + size + ((images > 0) ? ", " + images + " images" : "") + ((links > 0) ? ", " + links + " links" : "") + "<br></li>\n");
}
}
aBuffer.append(" </ul>\n</body>\n</html>\n");
// write the list to the client
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, "text/html", aBuffer.length(), new Date(dir.lastModified()), null, new httpResponseHeader(), null, null, true);
if (!method.equals(httpHeader.METHOD_HEAD)) {
out.write(aBuffer.toString().getBytes());
}
return;
}
} else {
//XXX: you cannot share a .png/.gif file with a name like a class in htroot.
if ( !(targetFile.exists()) && !((path.endsWith("png")||path.endsWith("gif")||path.endsWith(".stream"))&&targetClass!=null ) ){
targetFile = new File(htDocsPath, path);
targetClass = rewriteClassFile(new File(htDocsPath, path));
}
}
//File targetClass = rewriteClassFile(targetFile);
//We need tp here
servletProperties tp = new servletProperties();
Date targetDate;
boolean nocache = false;
if ((targetClass != null) && (path.endsWith("png"))) {
// call an image-servlet to produce an on-the-fly - generated image
Object img = null;
try {
requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path);
// in case that there are no args given, args = null or empty hashmap
img = invokeServlet(targetClass, requestHeader, args);
} catch (final InvocationTargetException e) {
theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" +
e.getMessage() +
" target exception at " + targetClass + ": " +
e.getTargetException().toString() + ":" +
e.getTargetException().getMessage() +
"; java.awt.graphicsenv='" + System.getProperty("java.awt.graphicsenv","") + "'",e);
targetClass = null;
}
if (img == null) {
// error with image generation; send file-not-found
httpd.sendRespondError(conProp, out, 3, 404, "File not Found", null, null);
} else {
if (img instanceof ymageMatrix) {
final ymageMatrix yp = (ymageMatrix) img;
// send an image to client
targetDate = new Date(System.currentTimeMillis());
nocache = true;
final String mimeType = mimeTable.getProperty(targetExt, "text/html");
final serverByteBuffer result = ymageMatrix.exportImage(yp.getImage(), targetExt);
// write the array to the client
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, result.length(), targetDate, null, null, null, null, nocache);
if (!method.equals(httpHeader.METHOD_HEAD)) {
result.writeTo(out);
}
}
if (img instanceof Image) {
final Image i = (Image) img;
// send an image to client
targetDate = new Date(System.currentTimeMillis());
nocache = true;
final String mimeType = mimeTable.getProperty(targetExt, "text/html");
// generate an byte array from the generated image
int width = i.getWidth(null); if (width < 0) width = 96; // bad hack
int height = i.getHeight(null); if (height < 0) height = 96; // bad hack
final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
bi.createGraphics().drawImage(i, 0, 0, width, height, null);
final serverByteBuffer result = ymageMatrix.exportImage(bi, targetExt);
// write the array to the client
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, result.length(), targetDate, null, null, null, null, nocache);
if (!method.equals(httpHeader.METHOD_HEAD)) {
result.writeTo(out);
}
}
}
} else if ((targetClass != null) && (path.endsWith(".stream"))) {
// call rewrite-class
requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path);
//requestHeader.put(httpHeader.CONNECTION_PROP_INPUTSTREAM, body);
//requestHeader.put(httpHeader.CONNECTION_PROP_OUTPUTSTREAM, out);
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null);
// in case that there are no args given, args = null or empty hashmap
/* servletProperties tp = (servlerObjects) */ invokeServlet(targetClass, requestHeader, args);
forceConnectionClose(conProp);
return;
} else if ((targetFile.exists()) && (targetFile.canRead())) {
// we have found a file that can be written to the client
// if this file uses templates, then we use the template
// re-write - method to create an result
final String mimeType = mimeTable.getProperty(targetExt,"text/html");
final boolean zipContent = requestHeader.acceptGzip() && httpd.shallTransportZipped("." + conProp.getProperty("EXT",""));
if (path.endsWith("html") ||
path.endsWith("xml") ||
path.endsWith("rdf") ||
path.endsWith("rss") ||
path.endsWith("csv") ||
path.endsWith("pac") ||
path.endsWith("src") ||
path.endsWith("vcf") ||
path.endsWith("/") ||
path.equals("/robots.txt")) {
/*targetFile = getLocalizedFile(path);
if (!(targetFile.exists())) {
// try to find that file in the htDocsPath
File trialFile = new File(htDocsPath, path);
if (trialFile.exists()) targetFile = trialFile;
}*/
// call rewrite-class
if (targetClass == null) {
targetDate = new Date(targetFile.lastModified());
} else {
// CGI-class: call the class to create a property for rewriting
try {
requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path);
// in case that there are no args given, args = null or empty hashmap
final Object tmp = invokeServlet(targetClass, requestHeader, args);
if (tmp == null) {
// if no args given, then tp will be an empty Hashtable object (not null)
tp = new servletProperties();
} else if (tmp instanceof servletProperties) {
tp = (servletProperties) tmp;
} else {
tp = new servletProperties((serverObjects) tmp);
}
// check if the servlets requests authentification
if (tp.containsKey(servletProperties.ACTION_AUTHENTICATE)) {
// handle brute-force protection
if (authorization != null) {
serverLog.logInfo("HTTPD", "dynamic log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
final Integer attempts = serverCore.bfHost.get(clientIP);
if (attempts == null)
serverCore.bfHost.put(clientIP, Integer.valueOf(1));
else
serverCore.bfHost.put(clientIP, Integer.valueOf(attempts.intValue() + 1));
}
// send authentication request to browser
final httpResponseHeader headers = getDefaultHeaders(path);
headers.put(httpRequestHeader.WWW_AUTHENTICATE,"Basic realm=\"" + tp.get(servletProperties.ACTION_AUTHENTICATE, "") + "\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
} else if (tp.containsKey(servletProperties.ACTION_LOCATION)) {
String location = tp.get(servletProperties.ACTION_LOCATION, "");
if (location.length() == 0) location = path;
final httpResponseHeader headers = getDefaultHeaders(path);
headers.setCookieVector(tp.getOutgoingHeader().getCookieVector()); //put the cookies into the new header TODO: can we put all headerlines, without trouble?
headers.put(httpHeader.LOCATION,location);
httpd.sendRespondHeader(conProp,out,httpVersion,302,headers);
return;
}
// add the application version, the uptime and the client name to every rewrite table
tp.put(servletProperties.PEER_STAT_VERSION, switchboard.getConfig("version", ""));
tp.put(servletProperties.PEER_STAT_UPTIME, ((System.currentTimeMillis() - serverCore.startupTime) / 1000) / 60); // uptime in minutes
tp.putHTML(servletProperties.PEER_STAT_CLIENTNAME, switchboard.getConfig("peerName", "anomic"));
tp.put(servletProperties.PEER_STAT_MYTIME, serverDate.formatShortSecond());
//System.out.println("respond props: " + ((tp == null) ? "null" : tp.toString())); // debug
} catch (final InvocationTargetException e) {
if (e.getCause() instanceof InterruptedException) {
throw new InterruptedException(e.getCause().getMessage());
}
theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" +
e.getMessage() +
" target exception at " + targetClass + ": " +
e.getTargetException().toString() + ":" +
e.getTargetException().getMessage(),e);
targetClass = null;
throw e;
}
targetDate = new Date(System.currentTimeMillis());
nocache = true;
}
// rewrite the file
InputStream fis = null;
// read the file/template
byte[] templateContent = null;
if (useTemplateCache) {
final long fileSize = targetFile.length();
if (fileSize <= 512 * 1024) {
// read from cache
SoftReference<byte[]> ref = templateCache.get(targetFile);
if (ref != null) {
templateContent = ref.get();
if (templateContent == null) templateCache.remove(targetFile);
}
if (templateContent == null) {
// loading the content of the template file into
// a byte array
templateContent = serverFileUtils.read(targetFile);
// storing the content into the cache
ref = new SoftReference<byte[]>(templateContent);
templateCache.put(targetFile, ref);
if (theLogger.isFinest()) theLogger.logFinest("Cache MISS for file " + targetFile);
} else {
if (theLogger.isFinest()) theLogger.logFinest("Cache HIT for file " + targetFile);
}
// creating an inputstream needed by the template
// rewrite function
fis = new ByteArrayInputStream(templateContent);
templateContent = null;
} else {
// read from file directly
fis = new BufferedInputStream(new FileInputStream(targetFile));
}
} else {
fis = new BufferedInputStream(new FileInputStream(targetFile));
}
// write the array to the client
// we can do that either in standard mode (whole thing completely) or in chunked mode
// since yacy clients do not understand chunked mode (yet), we use this only for communication with the administrator
final boolean yacyClient = requestHeader.userAgent().startsWith("yacy");
final boolean chunked = !method.equals(httpHeader.METHOD_HEAD) && !yacyClient && httpVersion.equals(httpHeader.HTTP_VERSION_1_1);
if (chunked) {
// send page in chunks and parse SSIs
final serverByteBuffer o = new serverByteBuffer();
// apply templates
httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, -1, targetDate, null, tp.getOutgoingHeader(), null, "chunked", nocache);
// send the content in chunked parts, see RFC 2616 section 3.6.1
final httpChunkedOutputStream chos = new httpChunkedOutputStream(out);
httpSSI.writeSSI(o, chos, authorization, clientIP);
//chos.write(result);
chos.finish();
} else {
// send page as whole thing, SSIs are not possible
final String contentEncoding = (zipContent) ? "gzip" : null;
// apply templates
final serverByteBuffer o1 = new serverByteBuffer();
httpTemplate.writeTemplate(fis, o1, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
final serverByteBuffer o = new serverByteBuffer();
if (zipContent) {
GZIPOutputStream zippedOut = new GZIPOutputStream(o);
httpSSI.writeSSI(o1, zippedOut, authorization, clientIP);
//httpTemplate.writeTemplate(fis, zippedOut, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
zippedOut.finish();
zippedOut.flush();
zippedOut.close();
zippedOut = null;
} else {
httpSSI.writeSSI(o1, o, authorization, clientIP);
//httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
}
if (method.equals(httpHeader.METHOD_HEAD)) {
httpd.sendRespondHeader(conProp, out,
httpVersion, 200, null, mimeType, o.length(),
targetDate, null, tp.getOutgoingHeader(),
contentEncoding, null, nocache);
} else {
final byte[] result = o.getBytes(); // this interrupts streaming (bad idea!)
httpd.sendRespondHeader(conProp, out,
httpVersion, 200, null, mimeType, result.length,
targetDate, null, tp.getOutgoingHeader(),
contentEncoding, null, nocache);
serverFileUtils.copy(result, out);
}
}
} else { // no html
int statusCode = 200;
int rangeStartOffset = 0;
httpResponseHeader header = new httpResponseHeader();
// adding the accept ranges header
header.put(httpHeader.ACCEPT_RANGES, "bytes");
// reading the files md5 hash if availabe and use it as ETAG of the resource
String targetMD5 = null;
final File targetMd5File = new File(targetFile + ".md5");
try {
if (targetMd5File.exists()) {
//String description = null;
targetMD5 = new String(serverFileUtils.read(targetMd5File));
pos = targetMD5.indexOf('\n');
if (pos >= 0) {
//description = targetMD5.substring(pos + 1);
targetMD5 = targetMD5.substring(0, pos);
}
// using the checksum as ETAG header
header.put(httpHeader.ETAG, targetMD5);
}
} catch (final IOException e) {
e.printStackTrace();
}
if (requestHeader.containsKey(httpHeader.RANGE)) {
final Object ifRange = requestHeader.ifRange();
if ((ifRange == null)||
(ifRange instanceof Date && targetFile.lastModified() == ((Date)ifRange).getTime()) ||
(ifRange instanceof String && ifRange.equals(targetMD5))) {
final String rangeHeaderVal = requestHeader.get(httpHeader.RANGE).trim();
if (rangeHeaderVal.startsWith("bytes=")) {
final String rangesVal = rangeHeaderVal.substring("bytes=".length());
final String[] ranges = rangesVal.split(",");
if ((ranges.length == 1)&&(ranges[0].endsWith("-"))) {
rangeStartOffset = Integer.valueOf(ranges[0].substring(0,ranges[0].length()-1)).intValue();
statusCode = 206;
if (header == null) header = new httpResponseHeader();
header.put(httpHeader.CONTENT_RANGE, "bytes " + rangeStartOffset + "-" + (targetFile.length()-1) + "/" + targetFile.length());
}
}
}
}
// write the file to the client
targetDate = new Date(targetFile.lastModified());
final long contentLength = (zipContent)?-1:targetFile.length()-rangeStartOffset;
final String contentEncoding = (zipContent)?"gzip":null;
final String transferEncoding = (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1))?null:(zipContent)?"chunked":null;
if (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1) && zipContent) forceConnectionClose(conProp);
httpd.sendRespondHeader(conProp, out, httpVersion, statusCode, null, mimeType, contentLength, targetDate, null, header, contentEncoding, transferEncoding, nocache);
if (!method.equals(httpHeader.METHOD_HEAD)) {
httpChunkedOutputStream chunkedOut = null;
GZIPOutputStream zipped = null;
OutputStream newOut = out;
if (transferEncoding != null) {
chunkedOut = new httpChunkedOutputStream(newOut);
newOut = chunkedOut;
}
if (contentEncoding != null) {
zipped = new GZIPOutputStream(newOut);
newOut = zipped;
}
serverFileUtils.copyRange(targetFile, newOut, rangeStartOffset);
if (zipped != null) {
zipped.flush();
zipped.finish();
}
if (chunkedOut != null) {
chunkedOut.finish();
}
// flush all
try {newOut.flush();}catch (final Exception e) {}
// wait a little time until everything closes so that clients can read from the streams/sockets
if ((contentLength >= 0) && ((String)requestHeader.get(httpRequestHeader.CONNECTION, "close")).indexOf("keep-alive") == -1) {
// in case that the client knows the size in advance (contentLength present) the waiting will have no effect on the interface performance
// but if the client waits on a connection interruption this will slow down.
try {Thread.sleep(2000);} catch (final InterruptedException e) {} // FIXME: is this necessary?
}
}
// check mime type again using the result array: these are 'magics'
// if (serverByteBuffer.equals(result, 1, "PNG".getBytes())) mimeType = mimeTable.getProperty("png","text/html");
// else if (serverByteBuffer.equals(result, 0, "GIF89".getBytes())) mimeType = mimeTable.getProperty("gif","text/html");
// else if (serverByteBuffer.equals(result, 6, "JFIF".getBytes())) mimeType = mimeTable.getProperty("jpg","text/html");
//System.out.print("MAGIC:"); for (int i = 0; i < 10; i++) System.out.print(Integer.toHexString((int) result[i]) + ","); System.out.println();
}
} else {
httpd.sendRespondError(conProp,out,3,404,"File not Found",null,null);
return;
}
} catch (final Exception e) {
try {
// doing some errorhandling ...
int httpStatusCode = 400;
final String httpStatusText = null;
final StringBuffer errorMessage = new StringBuffer();
Exception errorExc = null;
final String errorMsg = e.getMessage();
if (
(e instanceof InterruptedException) ||
((errorMsg != null) && (errorMsg.startsWith("Socket closed")) && (Thread.currentThread().isInterrupted()))
) {
errorMessage.append("Interruption detected while processing query.");
httpStatusCode = 503;
} else {
if ((errorMsg != null) &&
(
errorMsg.startsWith("Broken pipe") ||
errorMsg.startsWith("Connection reset") ||
errorMsg.startsWith("Software caused connection abort")
)) {
// client closed the connection, so we just end silently
errorMessage.append("Client unexpectedly closed connection while processing query.");
} else if ((errorMsg != null) && (errorMsg.startsWith("Connection timed out"))) {
errorMessage.append("Connection timed out.");
} else {
errorMessage.append("Unexpected error while processing query.");
httpStatusCode = 500;
errorExc = e;
}
}
errorMessage.append("\nSession: ").append(Thread.currentThread().getName())
.append("\nQuery: ").append(path)
.append("\nClient: ").append(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP,"unknown"))
.append("\nReason: ").append(e.toString());
if (!conProp.containsKey(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER)) {
// sending back an error message to the client
// if we have not already send an http header
httpd.sendRespondError(conProp,out, 4, httpStatusCode, httpStatusText, new String(errorMessage),errorExc);
} else {
// otherwise we close the connection
forceConnectionClose(conProp);
}
// if it is an unexpected error we log it
if (httpStatusCode == 500) {
theLogger.logWarning(new String(errorMessage),e);
}
} catch (final Exception ee) {
forceConnectionClose(conProp);
}
} finally {
try {out.flush();}catch (final Exception e) {}
}
}
public static final File getOverlayedClass(final String path) {
File targetClass;
targetClass = rewriteClassFile(new File(htDefaultPath, path)); //works for default and localized files
if (targetClass == null || !targetClass.exists()) {
//works for htdocs
targetClass=rewriteClassFile(new File(htDocsPath, path));
}
return targetClass;
}
public static final File getOverlayedFile(final String path) {
File targetFile;
targetFile = getLocalizedFile(path);
if (!targetFile.exists()) {
targetFile = new File(htDocsPath, path);
}
return targetFile;
}
private static final void forceConnectionClose(final Properties conprop) {
if (conprop != null) {
conprop.setProperty(httpHeader.CONNECTION_PROP_PERSISTENT,"close");
}
}
private static final File rewriteClassFile(final File template) {
try {
String f = template.getCanonicalPath();
final int p = f.lastIndexOf(".");
if (p < 0) return null;
f = f.substring(0, p) + ".class";
//System.out.println("constructed class path " + f);
final File cf = new File(f);
if (cf.exists()) return cf;
return null;
} catch (final IOException e) {
return null;
}
}
private static final Method rewriteMethod(final File classFile) {
Method m = null;
// now make a class out of the stream
try {
if (useTemplateCache) {
final SoftReference<Method> ref = templateMethodCache.get(classFile);
if (ref != null) {
m = ref.get();
if (m == null) {
templateMethodCache.remove(classFile);
} else {
return m;
}
}
}
final Class<?> c = provider.loadClass(classFile);
final Class<?>[] params = new Class[] {
httpRequestHeader.class,
serverObjects.class,
serverSwitch.class };
m = c.getMethod("respond", params);
if (useTemplateCache) {
// storing the method into the cache
final SoftReference<Method> ref = new SoftReference<Method>(m);
templateMethodCache.put(classFile, ref);
}
} catch (final ClassNotFoundException e) {
System.out.println("INTERNAL ERROR: class " + classFile + " is missing:" + e.getMessage());
} catch (final NoSuchMethodException e) {
System.out.println("INTERNAL ERROR: method respond not found in class " + classFile + ": " + e.getMessage());
}
//System.out.println("found method: " + m.toString());
return m;
}
public static final Object invokeServlet(final File targetClass, final httpRequestHeader request, final serverObjects args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Object result;
if (safeServletsMode) synchronized (switchboard) {
result = rewriteMethod(targetClass).invoke(null, new Object[] {request, args, switchboard});
} else {
result = rewriteMethod(targetClass).invoke(null, new Object[] {request, args, switchboard});
}
return result;
}
// public void doConnect(Properties conProp, httpHeader requestHeader, InputStream clientIn, OutputStream clientOut) {
// throw new UnsupportedOperationException();
// }
}
| true | true | public static void doResponse(final Properties conProp, final httpRequestHeader requestHeader, final OutputStream out, final InputStream body) {
String path = null;
try {
// getting some connection properties
final String method = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD);
path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH);
String argsString = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // is null if no args were given
final String httpVersion = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER);
final String clientIP = conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP, "unknown-host");
// check hack attacks in path
if (path.indexOf("..") >= 0) {
httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null);
return;
}
// url decoding of path
try {
path = URLDecoder.decode(path, "UTF-8");
} catch (final UnsupportedEncodingException e) {
// This should never occur
assert(false) : "UnsupportedEncodingException: " + e.getMessage();
}
// check again hack attacks in path
if (path.indexOf("..") >= 0) {
httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null);
return;
}
// check permission/granted access
String authorization = requestHeader.get(httpRequestHeader.AUTHORIZATION);
if (authorization != null && authorization.length() == 0) authorization = null;
final String adminAccountBase64MD5 = switchboard.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "");
int pos = path.lastIndexOf(".");
final boolean adminAccountForLocalhost = sb.getConfigBool("adminAccountForLocalhost", false);
final String refererHost = requestHeader.refererHost();
final boolean accessFromLocalhost = serverCore.isLocalhost(clientIP) && (refererHost.length() == 0 || serverCore.isLocalhost(refererHost));
final boolean grantedForLocalhost = adminAccountForLocalhost && accessFromLocalhost;
final boolean protectedPage = (path.substring(0,(pos==-1)?path.length():pos)).endsWith("_p");
final boolean accountEmpty = adminAccountBase64MD5.length() == 0;
if (!grantedForLocalhost && protectedPage && !accountEmpty) {
// authentication required
if (authorization == null) {
// no authorization given in response. Ask for that
final httpResponseHeader responseHeader = getDefaultHeaders(path);
responseHeader.put(httpRequestHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\"");
//httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
final servletProperties tp=new servletProperties();
tp.put("returnto", path);
//TODO: separate error page Wrong Login / No Login
httpd.sendRespondError(conProp, out, 5, 401, "Wrong Authentication", "", new File("proxymsg/authfail.inc"), tp, null, responseHeader);
return;
} else if (
(httpd.staticAdminAuthenticated(authorization.trim().substring(6), switchboard) == 4) ||
(sb.userDB.hasAdminRight(authorization, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP), requestHeader.getHeaderCookies()))) {
//Authentication successful. remove brute-force flag
serverCore.bfHost.remove(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
} else {
// a wrong authentication was given or the userDB user does not have admin access. Ask again
serverLog.logInfo("HTTPD", "Wrong log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
final Integer attempts = serverCore.bfHost.get(clientIP);
if (attempts == null)
serverCore.bfHost.put(clientIP, Integer.valueOf(1));
else
serverCore.bfHost.put(clientIP, Integer.valueOf(attempts.intValue() + 1));
final httpResponseHeader headers = getDefaultHeaders(path);
headers.put(httpRequestHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
}
}
// parse arguments
serverObjects args = new serverObjects();
int argc = 0;
if (argsString == null) {
// no args here, maybe a POST with multipart extension
int length = 0;
//System.out.println("HEADER: " + requestHeader.toString()); // DEBUG
if (method.equals(httpHeader.METHOD_POST)) {
// if its a POST, it can be either multipart or as args in the body
if ((requestHeader.containsKey(httpHeader.CONTENT_TYPE)) &&
(requestHeader.get(httpHeader.CONTENT_TYPE).toLowerCase().startsWith("multipart"))) {
// parse multipart
final HashMap<String, byte[]> files = httpd.parseMultipart(requestHeader, args, body);
// integrate these files into the args
if (files != null) {
final Iterator<Map.Entry<String, byte[]>> fit = files.entrySet().iterator();
Map.Entry<String, byte[]> entry;
while (fit.hasNext()) {
entry = fit.next();
args.put(entry.getKey() + "$file", entry.getValue());
}
}
argc = Integer.parseInt(requestHeader.get("ARGC"));
} else {
// parse args in body
argc = httpd.parseArgs(args, body, length);
}
} else {
// no args
argsString = null;
args = null;
argc = 0;
}
} else {
// simple args in URL (stuff after the "?")
argc = httpd.parseArgs(args, argsString);
}
// check for cross site scripting - attacks in request arguments
if (args != null && argc > 0) {
// check all values for occurrences of script values
final Iterator<String> e = args.values().iterator(); // enumeration of values
String val;
while (e.hasNext()) {
val = e.next();
if ((val != null) && (val.indexOf("<script") >= 0)) {
// deny request
httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null);
return;
}
}
}
// we are finished with parsing
// the result of value hand-over is in args and argc
if (path.length() == 0) {
httpd.sendRespondError(conProp,out,4,400,null,"Bad Request",null);
out.flush();
return;
}
File targetClass=null;
// locate the file
if (!(path.startsWith("/"))) path = "/" + path; // attach leading slash
// a different language can be desired (by i.e. ConfigBasic.html) than the one stored in the locale.language
String localeSelection = switchboard.getConfig("locale.language","default");
if (args != null && (args.containsKey("language"))) {
// TODO 9.11.06 Bost: a class with information about available languages is needed.
// the indexOf(".") is just a workaround because there from ConfigLanguage.html commes "de.lng" and
// from ConfigBasic.html comes just "de" in the "language" parameter
localeSelection = args.get("language", localeSelection);
if (localeSelection.indexOf(".") != -1)
localeSelection = localeSelection.substring(0, localeSelection.indexOf("."));
}
File targetFile = getLocalizedFile(path, localeSelection);
final String targetExt = conProp.getProperty("EXT","");
targetClass = rewriteClassFile(new File(htDefaultPath, path));
if (path.endsWith("/")) {
String testpath;
// attach default file name
for (int i = 0; i < defaultFiles.length; i++) {
testpath = path + defaultFiles[i];
targetFile = getOverlayedFile(testpath);
targetClass = getOverlayedClass(testpath);
if (targetFile.exists()) {
path = testpath;
break;
}
}
//no defaultfile, send a dirlisting
if (targetFile == null || !targetFile.exists()) {
final StringBuffer aBuffer = new StringBuffer();
aBuffer.append("<html>\n<head>\n</head>\n<body>\n<h1>Index of " + path + "</h1>\n <ul>\n");
final File dir = new File(htDocsPath, path);
String[] list = dir.list();
if (list == null) list = new String[0]; // should not occur!
File f;
String size;
long sz;
String headline, author, description;
int images, links;
htmlFilterContentScraper scraper;
for (int i = 0; i < list.length; i++) {
f = new File(dir, list[i]);
if (f.isDirectory()) {
aBuffer.append(" <li><a href=\"" + path + list[i] + "/\">" + list[i] + "/</a><br></li>\n");
} else {
if (list[i].endsWith("html") || (list[i].endsWith("htm"))) {
scraper = htmlFilterContentScraper.parseResource(f);
headline = scraper.getTitle();
author = scraper.getAuthor();
description = scraper.getDescription();
images = scraper.getImages().size();
links = scraper.getAnchors().size();
} else {
headline = null;
author = null;
description = null;
images = 0;
links = 0;
}
sz = f.length();
if (sz < 1024) {
size = sz + " bytes";
} else if (sz < 1024 * 1024) {
size = (sz / 1024) + " KB";
} else {
size = (sz / 1024 / 1024) + " MB";
}
aBuffer.append(" <li>");
if ((headline != null) && (headline.length() > 0)) aBuffer.append("<a href=\"" + list[i] + "\"><b>" + headline + "</b></a><br>");
aBuffer.append("<a href=\"" + path + list[i] + "\">" + list[i] + "</a><br>");
if ((author != null) && (author.length() > 0)) aBuffer.append("Author: " + author + "<br>");
if ((description != null) && (description.length() > 0)) aBuffer.append("Description: " + description + "<br>");
aBuffer.append(serverDate.formatShortDay(new Date(f.lastModified())) + ", " + size + ((images > 0) ? ", " + images + " images" : "") + ((links > 0) ? ", " + links + " links" : "") + "<br></li>\n");
}
}
aBuffer.append(" </ul>\n</body>\n</html>\n");
// write the list to the client
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, "text/html", aBuffer.length(), new Date(dir.lastModified()), null, new httpResponseHeader(), null, null, true);
if (!method.equals(httpHeader.METHOD_HEAD)) {
out.write(aBuffer.toString().getBytes());
}
return;
}
} else {
//XXX: you cannot share a .png/.gif file with a name like a class in htroot.
if ( !(targetFile.exists()) && !((path.endsWith("png")||path.endsWith("gif")||path.endsWith(".stream"))&&targetClass!=null ) ){
targetFile = new File(htDocsPath, path);
targetClass = rewriteClassFile(new File(htDocsPath, path));
}
}
//File targetClass = rewriteClassFile(targetFile);
//We need tp here
servletProperties tp = new servletProperties();
Date targetDate;
boolean nocache = false;
if ((targetClass != null) && (path.endsWith("png"))) {
// call an image-servlet to produce an on-the-fly - generated image
Object img = null;
try {
requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path);
// in case that there are no args given, args = null or empty hashmap
img = invokeServlet(targetClass, requestHeader, args);
} catch (final InvocationTargetException e) {
theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" +
e.getMessage() +
" target exception at " + targetClass + ": " +
e.getTargetException().toString() + ":" +
e.getTargetException().getMessage() +
"; java.awt.graphicsenv='" + System.getProperty("java.awt.graphicsenv","") + "'",e);
targetClass = null;
}
if (img == null) {
// error with image generation; send file-not-found
httpd.sendRespondError(conProp, out, 3, 404, "File not Found", null, null);
} else {
if (img instanceof ymageMatrix) {
final ymageMatrix yp = (ymageMatrix) img;
// send an image to client
targetDate = new Date(System.currentTimeMillis());
nocache = true;
final String mimeType = mimeTable.getProperty(targetExt, "text/html");
final serverByteBuffer result = ymageMatrix.exportImage(yp.getImage(), targetExt);
// write the array to the client
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, result.length(), targetDate, null, null, null, null, nocache);
if (!method.equals(httpHeader.METHOD_HEAD)) {
result.writeTo(out);
}
}
if (img instanceof Image) {
final Image i = (Image) img;
// send an image to client
targetDate = new Date(System.currentTimeMillis());
nocache = true;
final String mimeType = mimeTable.getProperty(targetExt, "text/html");
// generate an byte array from the generated image
int width = i.getWidth(null); if (width < 0) width = 96; // bad hack
int height = i.getHeight(null); if (height < 0) height = 96; // bad hack
final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
bi.createGraphics().drawImage(i, 0, 0, width, height, null);
final serverByteBuffer result = ymageMatrix.exportImage(bi, targetExt);
// write the array to the client
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, result.length(), targetDate, null, null, null, null, nocache);
if (!method.equals(httpHeader.METHOD_HEAD)) {
result.writeTo(out);
}
}
}
} else if ((targetClass != null) && (path.endsWith(".stream"))) {
// call rewrite-class
requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path);
//requestHeader.put(httpHeader.CONNECTION_PROP_INPUTSTREAM, body);
//requestHeader.put(httpHeader.CONNECTION_PROP_OUTPUTSTREAM, out);
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null);
// in case that there are no args given, args = null or empty hashmap
/* servletProperties tp = (servlerObjects) */ invokeServlet(targetClass, requestHeader, args);
forceConnectionClose(conProp);
return;
} else if ((targetFile.exists()) && (targetFile.canRead())) {
// we have found a file that can be written to the client
// if this file uses templates, then we use the template
// re-write - method to create an result
final String mimeType = mimeTable.getProperty(targetExt,"text/html");
final boolean zipContent = requestHeader.acceptGzip() && httpd.shallTransportZipped("." + conProp.getProperty("EXT",""));
if (path.endsWith("html") ||
path.endsWith("xml") ||
path.endsWith("rdf") ||
path.endsWith("rss") ||
path.endsWith("csv") ||
path.endsWith("pac") ||
path.endsWith("src") ||
path.endsWith("vcf") ||
path.endsWith("/") ||
path.equals("/robots.txt")) {
/*targetFile = getLocalizedFile(path);
if (!(targetFile.exists())) {
// try to find that file in the htDocsPath
File trialFile = new File(htDocsPath, path);
if (trialFile.exists()) targetFile = trialFile;
}*/
// call rewrite-class
if (targetClass == null) {
targetDate = new Date(targetFile.lastModified());
} else {
// CGI-class: call the class to create a property for rewriting
try {
requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path);
// in case that there are no args given, args = null or empty hashmap
final Object tmp = invokeServlet(targetClass, requestHeader, args);
if (tmp == null) {
// if no args given, then tp will be an empty Hashtable object (not null)
tp = new servletProperties();
} else if (tmp instanceof servletProperties) {
tp = (servletProperties) tmp;
} else {
tp = new servletProperties((serverObjects) tmp);
}
// check if the servlets requests authentification
if (tp.containsKey(servletProperties.ACTION_AUTHENTICATE)) {
// handle brute-force protection
if (authorization != null) {
serverLog.logInfo("HTTPD", "dynamic log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
final Integer attempts = serverCore.bfHost.get(clientIP);
if (attempts == null)
serverCore.bfHost.put(clientIP, Integer.valueOf(1));
else
serverCore.bfHost.put(clientIP, Integer.valueOf(attempts.intValue() + 1));
}
// send authentication request to browser
final httpResponseHeader headers = getDefaultHeaders(path);
headers.put(httpRequestHeader.WWW_AUTHENTICATE,"Basic realm=\"" + tp.get(servletProperties.ACTION_AUTHENTICATE, "") + "\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
} else if (tp.containsKey(servletProperties.ACTION_LOCATION)) {
String location = tp.get(servletProperties.ACTION_LOCATION, "");
if (location.length() == 0) location = path;
final httpResponseHeader headers = getDefaultHeaders(path);
headers.setCookieVector(tp.getOutgoingHeader().getCookieVector()); //put the cookies into the new header TODO: can we put all headerlines, without trouble?
headers.put(httpHeader.LOCATION,location);
httpd.sendRespondHeader(conProp,out,httpVersion,302,headers);
return;
}
// add the application version, the uptime and the client name to every rewrite table
tp.put(servletProperties.PEER_STAT_VERSION, switchboard.getConfig("version", ""));
tp.put(servletProperties.PEER_STAT_UPTIME, ((System.currentTimeMillis() - serverCore.startupTime) / 1000) / 60); // uptime in minutes
tp.putHTML(servletProperties.PEER_STAT_CLIENTNAME, switchboard.getConfig("peerName", "anomic"));
tp.put(servletProperties.PEER_STAT_MYTIME, serverDate.formatShortSecond());
//System.out.println("respond props: " + ((tp == null) ? "null" : tp.toString())); // debug
} catch (final InvocationTargetException e) {
if (e.getCause() instanceof InterruptedException) {
throw new InterruptedException(e.getCause().getMessage());
}
theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" +
e.getMessage() +
" target exception at " + targetClass + ": " +
e.getTargetException().toString() + ":" +
e.getTargetException().getMessage(),e);
targetClass = null;
throw e;
}
targetDate = new Date(System.currentTimeMillis());
nocache = true;
}
// rewrite the file
InputStream fis = null;
// read the file/template
byte[] templateContent = null;
if (useTemplateCache) {
final long fileSize = targetFile.length();
if (fileSize <= 512 * 1024) {
// read from cache
SoftReference<byte[]> ref = templateCache.get(targetFile);
if (ref != null) {
templateContent = ref.get();
if (templateContent == null) templateCache.remove(targetFile);
}
if (templateContent == null) {
// loading the content of the template file into
// a byte array
templateContent = serverFileUtils.read(targetFile);
// storing the content into the cache
ref = new SoftReference<byte[]>(templateContent);
templateCache.put(targetFile, ref);
if (theLogger.isFinest()) theLogger.logFinest("Cache MISS for file " + targetFile);
} else {
if (theLogger.isFinest()) theLogger.logFinest("Cache HIT for file " + targetFile);
}
// creating an inputstream needed by the template
// rewrite function
fis = new ByteArrayInputStream(templateContent);
templateContent = null;
} else {
// read from file directly
fis = new BufferedInputStream(new FileInputStream(targetFile));
}
} else {
fis = new BufferedInputStream(new FileInputStream(targetFile));
}
// write the array to the client
// we can do that either in standard mode (whole thing completely) or in chunked mode
// since yacy clients do not understand chunked mode (yet), we use this only for communication with the administrator
final boolean yacyClient = requestHeader.userAgent().startsWith("yacy");
final boolean chunked = !method.equals(httpHeader.METHOD_HEAD) && !yacyClient && httpVersion.equals(httpHeader.HTTP_VERSION_1_1);
if (chunked) {
// send page in chunks and parse SSIs
final serverByteBuffer o = new serverByteBuffer();
// apply templates
httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, -1, targetDate, null, tp.getOutgoingHeader(), null, "chunked", nocache);
// send the content in chunked parts, see RFC 2616 section 3.6.1
final httpChunkedOutputStream chos = new httpChunkedOutputStream(out);
httpSSI.writeSSI(o, chos, authorization, clientIP);
//chos.write(result);
chos.finish();
} else {
// send page as whole thing, SSIs are not possible
final String contentEncoding = (zipContent) ? "gzip" : null;
// apply templates
final serverByteBuffer o1 = new serverByteBuffer();
httpTemplate.writeTemplate(fis, o1, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
final serverByteBuffer o = new serverByteBuffer();
if (zipContent) {
GZIPOutputStream zippedOut = new GZIPOutputStream(o);
httpSSI.writeSSI(o1, zippedOut, authorization, clientIP);
//httpTemplate.writeTemplate(fis, zippedOut, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
zippedOut.finish();
zippedOut.flush();
zippedOut.close();
zippedOut = null;
} else {
httpSSI.writeSSI(o1, o, authorization, clientIP);
//httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
}
if (method.equals(httpHeader.METHOD_HEAD)) {
httpd.sendRespondHeader(conProp, out,
httpVersion, 200, null, mimeType, o.length(),
targetDate, null, tp.getOutgoingHeader(),
contentEncoding, null, nocache);
} else {
final byte[] result = o.getBytes(); // this interrupts streaming (bad idea!)
httpd.sendRespondHeader(conProp, out,
httpVersion, 200, null, mimeType, result.length,
targetDate, null, tp.getOutgoingHeader(),
contentEncoding, null, nocache);
serverFileUtils.copy(result, out);
}
}
} else { // no html
int statusCode = 200;
int rangeStartOffset = 0;
httpResponseHeader header = new httpResponseHeader();
// adding the accept ranges header
header.put(httpHeader.ACCEPT_RANGES, "bytes");
// reading the files md5 hash if availabe and use it as ETAG of the resource
String targetMD5 = null;
final File targetMd5File = new File(targetFile + ".md5");
try {
if (targetMd5File.exists()) {
//String description = null;
targetMD5 = new String(serverFileUtils.read(targetMd5File));
pos = targetMD5.indexOf('\n');
if (pos >= 0) {
//description = targetMD5.substring(pos + 1);
targetMD5 = targetMD5.substring(0, pos);
}
// using the checksum as ETAG header
header.put(httpHeader.ETAG, targetMD5);
}
} catch (final IOException e) {
e.printStackTrace();
}
if (requestHeader.containsKey(httpHeader.RANGE)) {
final Object ifRange = requestHeader.ifRange();
if ((ifRange == null)||
(ifRange instanceof Date && targetFile.lastModified() == ((Date)ifRange).getTime()) ||
(ifRange instanceof String && ifRange.equals(targetMD5))) {
final String rangeHeaderVal = requestHeader.get(httpHeader.RANGE).trim();
if (rangeHeaderVal.startsWith("bytes=")) {
final String rangesVal = rangeHeaderVal.substring("bytes=".length());
final String[] ranges = rangesVal.split(",");
if ((ranges.length == 1)&&(ranges[0].endsWith("-"))) {
rangeStartOffset = Integer.valueOf(ranges[0].substring(0,ranges[0].length()-1)).intValue();
statusCode = 206;
if (header == null) header = new httpResponseHeader();
header.put(httpHeader.CONTENT_RANGE, "bytes " + rangeStartOffset + "-" + (targetFile.length()-1) + "/" + targetFile.length());
}
}
}
}
// write the file to the client
targetDate = new Date(targetFile.lastModified());
final long contentLength = (zipContent)?-1:targetFile.length()-rangeStartOffset;
final String contentEncoding = (zipContent)?"gzip":null;
final String transferEncoding = (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1))?null:(zipContent)?"chunked":null;
if (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1) && zipContent) forceConnectionClose(conProp);
httpd.sendRespondHeader(conProp, out, httpVersion, statusCode, null, mimeType, contentLength, targetDate, null, header, contentEncoding, transferEncoding, nocache);
if (!method.equals(httpHeader.METHOD_HEAD)) {
httpChunkedOutputStream chunkedOut = null;
GZIPOutputStream zipped = null;
OutputStream newOut = out;
if (transferEncoding != null) {
chunkedOut = new httpChunkedOutputStream(newOut);
newOut = chunkedOut;
}
if (contentEncoding != null) {
zipped = new GZIPOutputStream(newOut);
newOut = zipped;
}
serverFileUtils.copyRange(targetFile, newOut, rangeStartOffset);
if (zipped != null) {
zipped.flush();
zipped.finish();
}
if (chunkedOut != null) {
chunkedOut.finish();
}
// flush all
try {newOut.flush();}catch (final Exception e) {}
// wait a little time until everything closes so that clients can read from the streams/sockets
if ((contentLength >= 0) && ((String)requestHeader.get(httpRequestHeader.CONNECTION, "close")).indexOf("keep-alive") == -1) {
// in case that the client knows the size in advance (contentLength present) the waiting will have no effect on the interface performance
// but if the client waits on a connection interruption this will slow down.
try {Thread.sleep(2000);} catch (final InterruptedException e) {} // FIXME: is this necessary?
}
}
// check mime type again using the result array: these are 'magics'
// if (serverByteBuffer.equals(result, 1, "PNG".getBytes())) mimeType = mimeTable.getProperty("png","text/html");
// else if (serverByteBuffer.equals(result, 0, "GIF89".getBytes())) mimeType = mimeTable.getProperty("gif","text/html");
// else if (serverByteBuffer.equals(result, 6, "JFIF".getBytes())) mimeType = mimeTable.getProperty("jpg","text/html");
//System.out.print("MAGIC:"); for (int i = 0; i < 10; i++) System.out.print(Integer.toHexString((int) result[i]) + ","); System.out.println();
}
} else {
httpd.sendRespondError(conProp,out,3,404,"File not Found",null,null);
return;
}
} catch (final Exception e) {
try {
// doing some errorhandling ...
int httpStatusCode = 400;
final String httpStatusText = null;
final StringBuffer errorMessage = new StringBuffer();
Exception errorExc = null;
final String errorMsg = e.getMessage();
if (
(e instanceof InterruptedException) ||
((errorMsg != null) && (errorMsg.startsWith("Socket closed")) && (Thread.currentThread().isInterrupted()))
) {
errorMessage.append("Interruption detected while processing query.");
httpStatusCode = 503;
} else {
if ((errorMsg != null) &&
(
errorMsg.startsWith("Broken pipe") ||
errorMsg.startsWith("Connection reset") ||
errorMsg.startsWith("Software caused connection abort")
)) {
// client closed the connection, so we just end silently
errorMessage.append("Client unexpectedly closed connection while processing query.");
} else if ((errorMsg != null) && (errorMsg.startsWith("Connection timed out"))) {
errorMessage.append("Connection timed out.");
} else {
errorMessage.append("Unexpected error while processing query.");
httpStatusCode = 500;
errorExc = e;
}
}
errorMessage.append("\nSession: ").append(Thread.currentThread().getName())
.append("\nQuery: ").append(path)
.append("\nClient: ").append(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP,"unknown"))
.append("\nReason: ").append(e.toString());
if (!conProp.containsKey(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER)) {
// sending back an error message to the client
// if we have not already send an http header
httpd.sendRespondError(conProp,out, 4, httpStatusCode, httpStatusText, new String(errorMessage),errorExc);
} else {
// otherwise we close the connection
forceConnectionClose(conProp);
}
// if it is an unexpected error we log it
if (httpStatusCode == 500) {
theLogger.logWarning(new String(errorMessage),e);
}
} catch (final Exception ee) {
forceConnectionClose(conProp);
}
} finally {
try {out.flush();}catch (final Exception e) {}
}
}
| public static void doResponse(final Properties conProp, final httpRequestHeader requestHeader, final OutputStream out, final InputStream body) {
String path = null;
try {
// getting some connection properties
final String method = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD);
path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH);
String argsString = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // is null if no args were given
final String httpVersion = conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER);
final String clientIP = conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP, "unknown-host");
// check hack attacks in path
if (path.indexOf("..") >= 0) {
httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null);
return;
}
// url decoding of path
try {
path = URLDecoder.decode(path, "UTF-8");
} catch (final UnsupportedEncodingException e) {
// This should never occur
assert(false) : "UnsupportedEncodingException: " + e.getMessage();
}
// check again hack attacks in path
if (path.indexOf("..") >= 0) {
httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null);
return;
}
// check permission/granted access
String authorization = requestHeader.get(httpRequestHeader.AUTHORIZATION);
if (authorization != null && authorization.length() == 0) authorization = null;
final String adminAccountBase64MD5 = switchboard.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "");
int pos = path.lastIndexOf(".");
final boolean adminAccountForLocalhost = sb.getConfigBool("adminAccountForLocalhost", false);
final String refererHost = requestHeader.refererHost();
final boolean accessFromLocalhost = serverCore.isLocalhost(clientIP) && (refererHost.length() == 0 || serverCore.isLocalhost(refererHost));
final boolean grantedForLocalhost = adminAccountForLocalhost && accessFromLocalhost;
final boolean protectedPage = (path.substring(0,(pos==-1)?path.length():pos)).endsWith("_p");
final boolean accountEmpty = adminAccountBase64MD5.length() == 0;
if (!grantedForLocalhost && protectedPage && !accountEmpty) {
// authentication required
if (authorization == null) {
// no authorization given in response. Ask for that
final httpResponseHeader responseHeader = getDefaultHeaders(path);
responseHeader.put(httpRequestHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\"");
//httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
final servletProperties tp=new servletProperties();
tp.put("returnto", path);
//TODO: separate error page Wrong Login / No Login
httpd.sendRespondError(conProp, out, 5, 401, "Wrong Authentication", "", new File("proxymsg/authfail.inc"), tp, null, responseHeader);
return;
} else if (
(httpd.staticAdminAuthenticated(authorization.trim().substring(6), switchboard) == 4) ||
(sb.userDB.hasAdminRight(authorization, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP), requestHeader.getHeaderCookies()))) {
//Authentication successful. remove brute-force flag
serverCore.bfHost.remove(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
} else {
// a wrong authentication was given or the userDB user does not have admin access. Ask again
serverLog.logInfo("HTTPD", "Wrong log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
final Integer attempts = serverCore.bfHost.get(clientIP);
if (attempts == null)
serverCore.bfHost.put(clientIP, Integer.valueOf(1));
else
serverCore.bfHost.put(clientIP, Integer.valueOf(attempts.intValue() + 1));
final httpResponseHeader headers = getDefaultHeaders(path);
headers.put(httpRequestHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
}
}
// parse arguments
serverObjects args = new serverObjects();
int argc = 0;
if (argsString == null) {
// no args here, maybe a POST with multipart extension
int length = requestHeader.getContentLength();
//System.out.println("HEADER: " + requestHeader.toString()); // DEBUG
if (method.equals(httpHeader.METHOD_POST)) {
// if its a POST, it can be either multipart or as args in the body
if ((requestHeader.containsKey(httpHeader.CONTENT_TYPE)) &&
(requestHeader.get(httpHeader.CONTENT_TYPE).toLowerCase().startsWith("multipart"))) {
// parse multipart
final HashMap<String, byte[]> files = httpd.parseMultipart(requestHeader, args, body);
// integrate these files into the args
if (files != null) {
final Iterator<Map.Entry<String, byte[]>> fit = files.entrySet().iterator();
Map.Entry<String, byte[]> entry;
while (fit.hasNext()) {
entry = fit.next();
args.put(entry.getKey() + "$file", entry.getValue());
}
}
argc = Integer.parseInt(requestHeader.get("ARGC"));
} else {
// parse args in body
argc = httpd.parseArgs(args, body, length);
}
} else {
// no args
argsString = null;
args = null;
argc = 0;
}
} else {
// simple args in URL (stuff after the "?")
argc = httpd.parseArgs(args, argsString);
}
// check for cross site scripting - attacks in request arguments
if (args != null && argc > 0) {
// check all values for occurrences of script values
final Iterator<String> e = args.values().iterator(); // enumeration of values
String val;
while (e.hasNext()) {
val = e.next();
if ((val != null) && (val.indexOf("<script") >= 0)) {
// deny request
httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null);
return;
}
}
}
// we are finished with parsing
// the result of value hand-over is in args and argc
if (path.length() == 0) {
httpd.sendRespondError(conProp,out,4,400,null,"Bad Request",null);
out.flush();
return;
}
File targetClass=null;
// locate the file
if (!(path.startsWith("/"))) path = "/" + path; // attach leading slash
// a different language can be desired (by i.e. ConfigBasic.html) than the one stored in the locale.language
String localeSelection = switchboard.getConfig("locale.language","default");
if (args != null && (args.containsKey("language"))) {
// TODO 9.11.06 Bost: a class with information about available languages is needed.
// the indexOf(".") is just a workaround because there from ConfigLanguage.html commes "de.lng" and
// from ConfigBasic.html comes just "de" in the "language" parameter
localeSelection = args.get("language", localeSelection);
if (localeSelection.indexOf(".") != -1)
localeSelection = localeSelection.substring(0, localeSelection.indexOf("."));
}
File targetFile = getLocalizedFile(path, localeSelection);
final String targetExt = conProp.getProperty("EXT","");
targetClass = rewriteClassFile(new File(htDefaultPath, path));
if (path.endsWith("/")) {
String testpath;
// attach default file name
for (int i = 0; i < defaultFiles.length; i++) {
testpath = path + defaultFiles[i];
targetFile = getOverlayedFile(testpath);
targetClass = getOverlayedClass(testpath);
if (targetFile.exists()) {
path = testpath;
break;
}
}
//no defaultfile, send a dirlisting
if (targetFile == null || !targetFile.exists()) {
final StringBuffer aBuffer = new StringBuffer();
aBuffer.append("<html>\n<head>\n</head>\n<body>\n<h1>Index of " + path + "</h1>\n <ul>\n");
final File dir = new File(htDocsPath, path);
String[] list = dir.list();
if (list == null) list = new String[0]; // should not occur!
File f;
String size;
long sz;
String headline, author, description;
int images, links;
htmlFilterContentScraper scraper;
for (int i = 0; i < list.length; i++) {
f = new File(dir, list[i]);
if (f.isDirectory()) {
aBuffer.append(" <li><a href=\"" + path + list[i] + "/\">" + list[i] + "/</a><br></li>\n");
} else {
if (list[i].endsWith("html") || (list[i].endsWith("htm"))) {
scraper = htmlFilterContentScraper.parseResource(f);
headline = scraper.getTitle();
author = scraper.getAuthor();
description = scraper.getDescription();
images = scraper.getImages().size();
links = scraper.getAnchors().size();
} else {
headline = null;
author = null;
description = null;
images = 0;
links = 0;
}
sz = f.length();
if (sz < 1024) {
size = sz + " bytes";
} else if (sz < 1024 * 1024) {
size = (sz / 1024) + " KB";
} else {
size = (sz / 1024 / 1024) + " MB";
}
aBuffer.append(" <li>");
if ((headline != null) && (headline.length() > 0)) aBuffer.append("<a href=\"" + list[i] + "\"><b>" + headline + "</b></a><br>");
aBuffer.append("<a href=\"" + path + list[i] + "\">" + list[i] + "</a><br>");
if ((author != null) && (author.length() > 0)) aBuffer.append("Author: " + author + "<br>");
if ((description != null) && (description.length() > 0)) aBuffer.append("Description: " + description + "<br>");
aBuffer.append(serverDate.formatShortDay(new Date(f.lastModified())) + ", " + size + ((images > 0) ? ", " + images + " images" : "") + ((links > 0) ? ", " + links + " links" : "") + "<br></li>\n");
}
}
aBuffer.append(" </ul>\n</body>\n</html>\n");
// write the list to the client
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, "text/html", aBuffer.length(), new Date(dir.lastModified()), null, new httpResponseHeader(), null, null, true);
if (!method.equals(httpHeader.METHOD_HEAD)) {
out.write(aBuffer.toString().getBytes());
}
return;
}
} else {
//XXX: you cannot share a .png/.gif file with a name like a class in htroot.
if ( !(targetFile.exists()) && !((path.endsWith("png")||path.endsWith("gif")||path.endsWith(".stream"))&&targetClass!=null ) ){
targetFile = new File(htDocsPath, path);
targetClass = rewriteClassFile(new File(htDocsPath, path));
}
}
//File targetClass = rewriteClassFile(targetFile);
//We need tp here
servletProperties tp = new servletProperties();
Date targetDate;
boolean nocache = false;
if ((targetClass != null) && (path.endsWith("png"))) {
// call an image-servlet to produce an on-the-fly - generated image
Object img = null;
try {
requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path);
// in case that there are no args given, args = null or empty hashmap
img = invokeServlet(targetClass, requestHeader, args);
} catch (final InvocationTargetException e) {
theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" +
e.getMessage() +
" target exception at " + targetClass + ": " +
e.getTargetException().toString() + ":" +
e.getTargetException().getMessage() +
"; java.awt.graphicsenv='" + System.getProperty("java.awt.graphicsenv","") + "'",e);
targetClass = null;
}
if (img == null) {
// error with image generation; send file-not-found
httpd.sendRespondError(conProp, out, 3, 404, "File not Found", null, null);
} else {
if (img instanceof ymageMatrix) {
final ymageMatrix yp = (ymageMatrix) img;
// send an image to client
targetDate = new Date(System.currentTimeMillis());
nocache = true;
final String mimeType = mimeTable.getProperty(targetExt, "text/html");
final serverByteBuffer result = ymageMatrix.exportImage(yp.getImage(), targetExt);
// write the array to the client
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, result.length(), targetDate, null, null, null, null, nocache);
if (!method.equals(httpHeader.METHOD_HEAD)) {
result.writeTo(out);
}
}
if (img instanceof Image) {
final Image i = (Image) img;
// send an image to client
targetDate = new Date(System.currentTimeMillis());
nocache = true;
final String mimeType = mimeTable.getProperty(targetExt, "text/html");
// generate an byte array from the generated image
int width = i.getWidth(null); if (width < 0) width = 96; // bad hack
int height = i.getHeight(null); if (height < 0) height = 96; // bad hack
final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
bi.createGraphics().drawImage(i, 0, 0, width, height, null);
final serverByteBuffer result = ymageMatrix.exportImage(bi, targetExt);
// write the array to the client
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, result.length(), targetDate, null, null, null, null, nocache);
if (!method.equals(httpHeader.METHOD_HEAD)) {
result.writeTo(out);
}
}
}
} else if ((targetClass != null) && (path.endsWith(".stream"))) {
// call rewrite-class
requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path);
//requestHeader.put(httpHeader.CONNECTION_PROP_INPUTSTREAM, body);
//requestHeader.put(httpHeader.CONNECTION_PROP_OUTPUTSTREAM, out);
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null);
// in case that there are no args given, args = null or empty hashmap
/* servletProperties tp = (servlerObjects) */ invokeServlet(targetClass, requestHeader, args);
forceConnectionClose(conProp);
return;
} else if ((targetFile.exists()) && (targetFile.canRead())) {
// we have found a file that can be written to the client
// if this file uses templates, then we use the template
// re-write - method to create an result
final String mimeType = mimeTable.getProperty(targetExt,"text/html");
final boolean zipContent = requestHeader.acceptGzip() && httpd.shallTransportZipped("." + conProp.getProperty("EXT",""));
if (path.endsWith("html") ||
path.endsWith("xml") ||
path.endsWith("rdf") ||
path.endsWith("rss") ||
path.endsWith("csv") ||
path.endsWith("pac") ||
path.endsWith("src") ||
path.endsWith("vcf") ||
path.endsWith("/") ||
path.equals("/robots.txt")) {
/*targetFile = getLocalizedFile(path);
if (!(targetFile.exists())) {
// try to find that file in the htDocsPath
File trialFile = new File(htDocsPath, path);
if (trialFile.exists()) targetFile = trialFile;
}*/
// call rewrite-class
if (targetClass == null) {
targetDate = new Date(targetFile.lastModified());
} else {
// CGI-class: call the class to create a property for rewriting
try {
requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path);
// in case that there are no args given, args = null or empty hashmap
final Object tmp = invokeServlet(targetClass, requestHeader, args);
if (tmp == null) {
// if no args given, then tp will be an empty Hashtable object (not null)
tp = new servletProperties();
} else if (tmp instanceof servletProperties) {
tp = (servletProperties) tmp;
} else {
tp = new servletProperties((serverObjects) tmp);
}
// check if the servlets requests authentification
if (tp.containsKey(servletProperties.ACTION_AUTHENTICATE)) {
// handle brute-force protection
if (authorization != null) {
serverLog.logInfo("HTTPD", "dynamic log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
final Integer attempts = serverCore.bfHost.get(clientIP);
if (attempts == null)
serverCore.bfHost.put(clientIP, Integer.valueOf(1));
else
serverCore.bfHost.put(clientIP, Integer.valueOf(attempts.intValue() + 1));
}
// send authentication request to browser
final httpResponseHeader headers = getDefaultHeaders(path);
headers.put(httpRequestHeader.WWW_AUTHENTICATE,"Basic realm=\"" + tp.get(servletProperties.ACTION_AUTHENTICATE, "") + "\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
} else if (tp.containsKey(servletProperties.ACTION_LOCATION)) {
String location = tp.get(servletProperties.ACTION_LOCATION, "");
if (location.length() == 0) location = path;
final httpResponseHeader headers = getDefaultHeaders(path);
headers.setCookieVector(tp.getOutgoingHeader().getCookieVector()); //put the cookies into the new header TODO: can we put all headerlines, without trouble?
headers.put(httpHeader.LOCATION,location);
httpd.sendRespondHeader(conProp,out,httpVersion,302,headers);
return;
}
// add the application version, the uptime and the client name to every rewrite table
tp.put(servletProperties.PEER_STAT_VERSION, switchboard.getConfig("version", ""));
tp.put(servletProperties.PEER_STAT_UPTIME, ((System.currentTimeMillis() - serverCore.startupTime) / 1000) / 60); // uptime in minutes
tp.putHTML(servletProperties.PEER_STAT_CLIENTNAME, switchboard.getConfig("peerName", "anomic"));
tp.put(servletProperties.PEER_STAT_MYTIME, serverDate.formatShortSecond());
//System.out.println("respond props: " + ((tp == null) ? "null" : tp.toString())); // debug
} catch (final InvocationTargetException e) {
if (e.getCause() instanceof InterruptedException) {
throw new InterruptedException(e.getCause().getMessage());
}
theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" +
e.getMessage() +
" target exception at " + targetClass + ": " +
e.getTargetException().toString() + ":" +
e.getTargetException().getMessage(),e);
targetClass = null;
throw e;
}
targetDate = new Date(System.currentTimeMillis());
nocache = true;
}
// rewrite the file
InputStream fis = null;
// read the file/template
byte[] templateContent = null;
if (useTemplateCache) {
final long fileSize = targetFile.length();
if (fileSize <= 512 * 1024) {
// read from cache
SoftReference<byte[]> ref = templateCache.get(targetFile);
if (ref != null) {
templateContent = ref.get();
if (templateContent == null) templateCache.remove(targetFile);
}
if (templateContent == null) {
// loading the content of the template file into
// a byte array
templateContent = serverFileUtils.read(targetFile);
// storing the content into the cache
ref = new SoftReference<byte[]>(templateContent);
templateCache.put(targetFile, ref);
if (theLogger.isFinest()) theLogger.logFinest("Cache MISS for file " + targetFile);
} else {
if (theLogger.isFinest()) theLogger.logFinest("Cache HIT for file " + targetFile);
}
// creating an inputstream needed by the template
// rewrite function
fis = new ByteArrayInputStream(templateContent);
templateContent = null;
} else {
// read from file directly
fis = new BufferedInputStream(new FileInputStream(targetFile));
}
} else {
fis = new BufferedInputStream(new FileInputStream(targetFile));
}
// write the array to the client
// we can do that either in standard mode (whole thing completely) or in chunked mode
// since yacy clients do not understand chunked mode (yet), we use this only for communication with the administrator
final boolean yacyClient = requestHeader.userAgent().startsWith("yacy");
final boolean chunked = !method.equals(httpHeader.METHOD_HEAD) && !yacyClient && httpVersion.equals(httpHeader.HTTP_VERSION_1_1);
if (chunked) {
// send page in chunks and parse SSIs
final serverByteBuffer o = new serverByteBuffer();
// apply templates
httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
httpd.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, -1, targetDate, null, tp.getOutgoingHeader(), null, "chunked", nocache);
// send the content in chunked parts, see RFC 2616 section 3.6.1
final httpChunkedOutputStream chos = new httpChunkedOutputStream(out);
httpSSI.writeSSI(o, chos, authorization, clientIP);
//chos.write(result);
chos.finish();
} else {
// send page as whole thing, SSIs are not possible
final String contentEncoding = (zipContent) ? "gzip" : null;
// apply templates
final serverByteBuffer o1 = new serverByteBuffer();
httpTemplate.writeTemplate(fis, o1, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
final serverByteBuffer o = new serverByteBuffer();
if (zipContent) {
GZIPOutputStream zippedOut = new GZIPOutputStream(o);
httpSSI.writeSSI(o1, zippedOut, authorization, clientIP);
//httpTemplate.writeTemplate(fis, zippedOut, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
zippedOut.finish();
zippedOut.flush();
zippedOut.close();
zippedOut = null;
} else {
httpSSI.writeSSI(o1, o, authorization, clientIP);
//httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8"));
}
if (method.equals(httpHeader.METHOD_HEAD)) {
httpd.sendRespondHeader(conProp, out,
httpVersion, 200, null, mimeType, o.length(),
targetDate, null, tp.getOutgoingHeader(),
contentEncoding, null, nocache);
} else {
final byte[] result = o.getBytes(); // this interrupts streaming (bad idea!)
httpd.sendRespondHeader(conProp, out,
httpVersion, 200, null, mimeType, result.length,
targetDate, null, tp.getOutgoingHeader(),
contentEncoding, null, nocache);
serverFileUtils.copy(result, out);
}
}
} else { // no html
int statusCode = 200;
int rangeStartOffset = 0;
httpResponseHeader header = new httpResponseHeader();
// adding the accept ranges header
header.put(httpHeader.ACCEPT_RANGES, "bytes");
// reading the files md5 hash if availabe and use it as ETAG of the resource
String targetMD5 = null;
final File targetMd5File = new File(targetFile + ".md5");
try {
if (targetMd5File.exists()) {
//String description = null;
targetMD5 = new String(serverFileUtils.read(targetMd5File));
pos = targetMD5.indexOf('\n');
if (pos >= 0) {
//description = targetMD5.substring(pos + 1);
targetMD5 = targetMD5.substring(0, pos);
}
// using the checksum as ETAG header
header.put(httpHeader.ETAG, targetMD5);
}
} catch (final IOException e) {
e.printStackTrace();
}
if (requestHeader.containsKey(httpHeader.RANGE)) {
final Object ifRange = requestHeader.ifRange();
if ((ifRange == null)||
(ifRange instanceof Date && targetFile.lastModified() == ((Date)ifRange).getTime()) ||
(ifRange instanceof String && ifRange.equals(targetMD5))) {
final String rangeHeaderVal = requestHeader.get(httpHeader.RANGE).trim();
if (rangeHeaderVal.startsWith("bytes=")) {
final String rangesVal = rangeHeaderVal.substring("bytes=".length());
final String[] ranges = rangesVal.split(",");
if ((ranges.length == 1)&&(ranges[0].endsWith("-"))) {
rangeStartOffset = Integer.valueOf(ranges[0].substring(0,ranges[0].length()-1)).intValue();
statusCode = 206;
if (header == null) header = new httpResponseHeader();
header.put(httpHeader.CONTENT_RANGE, "bytes " + rangeStartOffset + "-" + (targetFile.length()-1) + "/" + targetFile.length());
}
}
}
}
// write the file to the client
targetDate = new Date(targetFile.lastModified());
final long contentLength = (zipContent)?-1:targetFile.length()-rangeStartOffset;
final String contentEncoding = (zipContent)?"gzip":null;
final String transferEncoding = (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1))?null:(zipContent)?"chunked":null;
if (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1) && zipContent) forceConnectionClose(conProp);
httpd.sendRespondHeader(conProp, out, httpVersion, statusCode, null, mimeType, contentLength, targetDate, null, header, contentEncoding, transferEncoding, nocache);
if (!method.equals(httpHeader.METHOD_HEAD)) {
httpChunkedOutputStream chunkedOut = null;
GZIPOutputStream zipped = null;
OutputStream newOut = out;
if (transferEncoding != null) {
chunkedOut = new httpChunkedOutputStream(newOut);
newOut = chunkedOut;
}
if (contentEncoding != null) {
zipped = new GZIPOutputStream(newOut);
newOut = zipped;
}
serverFileUtils.copyRange(targetFile, newOut, rangeStartOffset);
if (zipped != null) {
zipped.flush();
zipped.finish();
}
if (chunkedOut != null) {
chunkedOut.finish();
}
// flush all
try {newOut.flush();}catch (final Exception e) {}
// wait a little time until everything closes so that clients can read from the streams/sockets
if ((contentLength >= 0) && ((String)requestHeader.get(httpRequestHeader.CONNECTION, "close")).indexOf("keep-alive") == -1) {
// in case that the client knows the size in advance (contentLength present) the waiting will have no effect on the interface performance
// but if the client waits on a connection interruption this will slow down.
try {Thread.sleep(2000);} catch (final InterruptedException e) {} // FIXME: is this necessary?
}
}
// check mime type again using the result array: these are 'magics'
// if (serverByteBuffer.equals(result, 1, "PNG".getBytes())) mimeType = mimeTable.getProperty("png","text/html");
// else if (serverByteBuffer.equals(result, 0, "GIF89".getBytes())) mimeType = mimeTable.getProperty("gif","text/html");
// else if (serverByteBuffer.equals(result, 6, "JFIF".getBytes())) mimeType = mimeTable.getProperty("jpg","text/html");
//System.out.print("MAGIC:"); for (int i = 0; i < 10; i++) System.out.print(Integer.toHexString((int) result[i]) + ","); System.out.println();
}
} else {
httpd.sendRespondError(conProp,out,3,404,"File not Found",null,null);
return;
}
} catch (final Exception e) {
try {
// doing some errorhandling ...
int httpStatusCode = 400;
final String httpStatusText = null;
final StringBuffer errorMessage = new StringBuffer();
Exception errorExc = null;
final String errorMsg = e.getMessage();
if (
(e instanceof InterruptedException) ||
((errorMsg != null) && (errorMsg.startsWith("Socket closed")) && (Thread.currentThread().isInterrupted()))
) {
errorMessage.append("Interruption detected while processing query.");
httpStatusCode = 503;
} else {
if ((errorMsg != null) &&
(
errorMsg.startsWith("Broken pipe") ||
errorMsg.startsWith("Connection reset") ||
errorMsg.startsWith("Software caused connection abort")
)) {
// client closed the connection, so we just end silently
errorMessage.append("Client unexpectedly closed connection while processing query.");
} else if ((errorMsg != null) && (errorMsg.startsWith("Connection timed out"))) {
errorMessage.append("Connection timed out.");
} else {
errorMessage.append("Unexpected error while processing query.");
httpStatusCode = 500;
errorExc = e;
}
}
errorMessage.append("\nSession: ").append(Thread.currentThread().getName())
.append("\nQuery: ").append(path)
.append("\nClient: ").append(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP,"unknown"))
.append("\nReason: ").append(e.toString());
if (!conProp.containsKey(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER)) {
// sending back an error message to the client
// if we have not already send an http header
httpd.sendRespondError(conProp,out, 4, httpStatusCode, httpStatusText, new String(errorMessage),errorExc);
} else {
// otherwise we close the connection
forceConnectionClose(conProp);
}
// if it is an unexpected error we log it
if (httpStatusCode == 500) {
theLogger.logWarning(new String(errorMessage),e);
}
} catch (final Exception ee) {
forceConnectionClose(conProp);
}
} finally {
try {out.flush();}catch (final Exception e) {}
}
}
|
diff --git a/src/cz/muni/stanse/codestructures/traversal/CFGTraversal.java b/src/cz/muni/stanse/codestructures/traversal/CFGTraversal.java
index f4ec0aa..536ea33 100644
--- a/src/cz/muni/stanse/codestructures/traversal/CFGTraversal.java
+++ b/src/cz/muni/stanse/codestructures/traversal/CFGTraversal.java
@@ -1,374 +1,380 @@
/*
* Licensed under GPLv2.
*/
package cz.muni.stanse.codestructures.traversal;
import cz.muni.stanse.codestructures.CFGsNavigator;
import cz.muni.stanse.utils.Pair;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
import java.util.Collections;
import cz.muni.stanse.codestructures.CFGHandle;
import cz.muni.stanse.codestructures.CFGNode;
// Node followers --------------------------------------------------------------
abstract class CFGNodeFollowers {
abstract List<CFGNode> get(final CFGNode node);
}
final class ForwardCFGNodeFollowers extends CFGNodeFollowers {
ForwardCFGNodeFollowers() { super(); }
@Override
List<CFGNode> get(final CFGNode node) { return node.getSuccessors(); }
}
final class BackwardCFGNodeFollowers extends CFGNodeFollowers {
BackwardCFGNodeFollowers() { super(); }
@Override
List<CFGNode> get(final CFGNode node) { return node.getPredecessors(); }
}
// Node followers Interprocedural ----------------------------------------------
abstract class CFGNodeFollowersInterprocedural {
abstract List<CFGNode> get(final CFGNode node);
abstract boolean isCallNode(final CFGNode node);
abstract boolean isReturnNode(final CFGNode node);
abstract CFGNode getCalleeNode(final CFGNode node);
}
final class ForwardCFGNodeFollowersInterprocedural extends
CFGNodeFollowersInterprocedural {
ForwardCFGNodeFollowersInterprocedural(final CFGsNavigator navigator) {
super();
this.navigator = navigator;
}
@Override
List<CFGNode> get(final CFGNode node) { return node.getSuccessors(); }
@Override
boolean isCallNode(final CFGNode node) {
return navigator.isCallNode(node);
}
@Override
boolean isReturnNode(final CFGNode node) {
return navigator.isEndNode(node);
}
@Override
CFGNode getCalleeNode(final CFGNode node) {
return navigator.getCalleeStart(node);
}
private final CFGsNavigator navigator;
}
final class BackwardCFGNodeFollowersInterprocedural extends
CFGNodeFollowersInterprocedural {
BackwardCFGNodeFollowersInterprocedural(final CFGsNavigator navigator){
super();
this.navigator = navigator;
}
@Override
List<CFGNode> get(final CFGNode node) { return node.getPredecessors(); }
@Override
boolean isCallNode(final CFGNode node) {
return navigator.isCallNode(node);
}
@Override
boolean isReturnNode(final CFGNode node) {
return navigator.isStartNode(node);
}
@Override
CFGNode getCalleeNode(final CFGNode node) {
return navigator.getCalleeEnd(node);
}
private final CFGsNavigator navigator;
}
// Traversation container ------------------------------------------------------
abstract class CFGTraversationContainer<T> {
abstract void insert(final T node);
abstract T remove();
abstract boolean isEmpty();
}
final class CFGTraversationQueue<T> extends CFGTraversationContainer<T> {
CFGTraversationQueue() { super(); queue = new LinkedList<T>(); }
@Override
void insert(final T obj) { queue.add(obj); }
@Override
T remove() { return queue.remove(); }
@Override
boolean isEmpty() { return queue.isEmpty(); }
private final LinkedList<T> queue;
}
final class CFGTraversationStack<T> extends CFGTraversationContainer<T> {
CFGTraversationStack() { super(); stack = new Stack<T>(); }
@Override
void insert(final T obj) { stack.push(obj); }
@Override
T remove() { return stack.pop(); }
@Override
boolean isEmpty() { return stack.isEmpty(); }
private final Stack<T> stack;
}
// CFG traversal itself --------------------------------------------------------
public final class CFGTraversal {
// public section
public static <T extends CFGvisitor>
T traverseCFGToBreadthForward(final CFGHandle cfg,
final CFGNode startNode, final T visitor) {
traverseCFG(cfg,startNode,
new ForwardCFGNodeFollowers(),
new CFGTraversationQueue<CFGNode>(),
visitor);
return visitor;
}
public static <T extends CFGvisitor>
T traverseCFGToBreadthBackward(final CFGHandle cfg,
final CFGNode startNode, final T visitor) {
traverseCFG(cfg,startNode,
new BackwardCFGNodeFollowers(),
new CFGTraversationQueue<CFGNode>(),
visitor);
return visitor;
}
public static <T extends CFGvisitor>
T traverseCFGToDepthForward(final CFGHandle cfg,
final CFGNode startNode, final T visitor) {
traverseCFG(cfg,startNode,
new ForwardCFGNodeFollowers(),
new CFGTraversationStack<CFGNode>(),
visitor);
return visitor;
}
public static <T extends CFGvisitor>
T traverseCFGToDepthBackward(final CFGHandle cfg,
final CFGNode startNode, final T visitor) {
traverseCFG(cfg,startNode,
new BackwardCFGNodeFollowers(),
new CFGTraversationStack<CFGNode>(),
visitor);
return visitor;
}
public static <T extends CFGPathVisitor>
T traverseFunctionForward(final CFGHandle cfg, final T visitor) {
final LinkedList<CFGNode> path = new LinkedList<CFGNode>();
path.add(cfg.getStartNode());
traverseCFGPaths(cfg,path,
new ForwardCFGNodeFollowers(),
visitor,new HashSet<Pair<CFGNode,CFGNode>>());
return visitor;
}
public static <T extends CFGPathVisitor>
T traverseFunctionBackward(final CFGHandle cfg, final T visitor) {
final LinkedList<CFGNode> path = new LinkedList<CFGNode>();
path.add(cfg.getEndNode());
traverseCFGPaths(cfg,path,
new BackwardCFGNodeFollowers(),
visitor,new HashSet<Pair<CFGNode,CFGNode>>());
return visitor;
}
public static <T extends CFGPathVisitor>
T traverseCFGPathsForward(final CFGHandle cfg,
final CFGNode startNode,final T visitor) {
final LinkedList<CFGNode> path = new LinkedList<CFGNode>();
path.add(startNode);
traverseCFGPaths(cfg,path,
new ForwardCFGNodeFollowers(),
visitor,new HashSet<Pair<CFGNode,CFGNode>>());
return visitor;
}
public static <T extends CFGPathVisitor>
T traverseCFGPathsBackward(final CFGHandle cfg,
final CFGNode startNode,final T visitor) {
final LinkedList<CFGNode> path = new LinkedList<CFGNode>();
path.add(startNode);
traverseCFGPaths(cfg,path,
new BackwardCFGNodeFollowers(),
visitor,new HashSet<Pair<CFGNode,CFGNode>>());
return visitor;
}
public static <T extends CFGPathVisitor>
T traverseCFGPathsForwardInterprocedural(final CFGsNavigator navigator,
final CFGNode startNode, final T visitor) {
return traverseCFGPathsForwardInterprocedural(navigator,startNode,
visitor,new Stack<CFGNode>());
}
public static <T extends CFGPathVisitor>
T traverseCFGPathsForwardInterprocedural(final CFGsNavigator navigator,
final CFGNode startNode, final T visitor,
final Stack<CFGNode> stack) {
final LinkedList<CFGNode> path = new LinkedList<CFGNode>();
path.add(startNode);
traverseCFGPathsInterprocedural(path,
new ForwardCFGNodeFollowersInterprocedural(navigator),
visitor,createVisitedStack(stack.size()+1),stack);
return visitor;
}
public static <T extends CFGPathVisitor>
T traverseCFGPathsBackwardInterprocedural(final CFGsNavigator navigator,
final CFGNode startNode, final T visitor) {
return traverseCFGPathsBackwardInterprocedural(navigator,startNode,
visitor,new Stack<CFGNode>());
}
public static <T extends CFGPathVisitor>
T traverseCFGPathsBackwardInterprocedural(final CFGsNavigator navigator,
final CFGNode startNode, final T visitor,
final Stack<CFGNode> stack) {
final LinkedList<CFGNode> path = new LinkedList<CFGNode>();
path.add(startNode);
traverseCFGPathsInterprocedural(path,
new BackwardCFGNodeFollowersInterprocedural(navigator),
visitor,createVisitedStack(stack.size()+1),stack);
return visitor;
}
// private section
private static Stack<HashSet<Pair<CFGNode,CFGNode>>>
createVisitedStack(int size) {
final Stack<HashSet<Pair<CFGNode,CFGNode>>> stack =
new Stack<HashSet<Pair<CFGNode,CFGNode>>>();
for (int i = 0; i < size; ++i)
stack.push(new HashSet<Pair<CFGNode,CFGNode>>());
return stack;
}
private static void traverseCFG(final CFGHandle cfg,
final CFGNode startNode,
final CFGNodeFollowers nodeFollowers,
final CFGTraversationContainer<CFGNode> nodesToVisit,
final CFGvisitor visitor) {
final HashSet<CFGNode> visitedNodes = new HashSet<CFGNode>();
nodesToVisit.insert(startNode);
do {
final CFGNode currentNode = nodesToVisit.remove();
if (visitedNodes.contains(currentNode))
continue;
visitedNodes.add(currentNode);
if (!visitor.visitInternal(currentNode,currentNode.getElement()))
continue;
for (CFGNode currentNodeFollower : nodeFollowers.get(currentNode))
nodesToVisit.insert(currentNodeFollower);
}
while (!nodesToVisit.isEmpty());
}
private static void traverseCFGPaths(final CFGHandle cfg,
final LinkedList<CFGNode> path,
final CFGNodeFollowers nodeFollowers,
final CFGPathVisitor visitor,
final HashSet<Pair<CFGNode,CFGNode>> visitedEdges) {
if (!visitor.visitInternal(Collections.unmodifiableList(path),
new Stack<CFGNode>()))
return;
for (CFGNode currentNodeFollower : nodeFollowers.get(path.getFirst())) {
final Pair<CFGNode,CFGNode> edge =
new Pair<CFGNode,CFGNode>(path.getFirst(),currentNodeFollower);
if (visitedEdges.contains(edge))
continue;
path.addFirst(currentNodeFollower);
visitedEdges.add(edge);
traverseCFGPaths(cfg,path,nodeFollowers,visitor,visitedEdges);
visitedEdges.remove(edge);
path.removeFirst();
}
}
private static void traverseCFGPathsInterprocedural(
final LinkedList<CFGNode> path,
final CFGNodeFollowersInterprocedural nodeFollowers,
final CFGPathVisitor visitor,
final Stack<HashSet<Pair<CFGNode,CFGNode>>> visitedStack,
final Stack<CFGNode> callStack) {
final HashSet<Pair<CFGNode,CFGNode>> visitedEdges = visitedStack.peek();
if (nodeFollowers.isCallNode(path.get(0))) {
if (path.size() < 2 || !nodeFollowers.isReturnNode(path.get(1))) {
final Pair<CFGNode,CFGNode> edge = Pair.make(path.getFirst(),
nodeFollowers.getCalleeNode(path.getFirst()));
if (visitedEdges.contains(edge))
return;
if (visitor.onCFGchange(path.getFirst(),edge.getSecond())) {
visitedStack.push(
new HashSet<Pair<CFGNode,CFGNode>>(visitedEdges));
callStack.push(edge.getFirst());
traverseCFGPathsInterproceduralByEdge(edge,path,
nodeFollowers,visitor,visitedStack,callStack);
+ callStack.pop();
+ visitedStack.pop();
+ visitor.onCFGchange(edge.getSecond(),path.getFirst());
return;
}
}
}
else if (!visitor.visitInternal(Collections.unmodifiableList(path),
callStack))
return;
if (nodeFollowers.isReturnNode(path.get(0)) && !callStack.isEmpty()) {
final Pair<CFGNode,CFGNode> edge = Pair.make(path.getFirst(),
callStack.peek());
if (visitedEdges.contains(edge))
return;
- callStack.pop();
- visitedStack.pop();
+ CFGNode lastCallStackNode = callStack.pop();
+ HashSet<Pair<CFGNode,CFGNode>> lastVisitedStack = visitedStack.pop();
visitor.onCFGchange(path.getFirst(),edge.getSecond());
traverseCFGPathsInterproceduralByEdge(edge,path,nodeFollowers,
visitor,visitedStack,callStack);
+ visitor.onCFGchange(edge.getSecond(),path.getFirst());
+ visitedStack.push(lastVisitedStack);
+ callStack.push(lastCallStackNode);
return;
}
for (CFGNode currentNodeFollower : nodeFollowers.get(path.getFirst())) {
final Pair<CFGNode,CFGNode> edge = Pair.make(path.getFirst(),
currentNodeFollower);
if (visitedEdges.contains(edge))
continue;
traverseCFGPathsInterproceduralByEdge(edge,path,nodeFollowers,
visitor,visitedStack,callStack);
}
}
private static void traverseCFGPathsInterproceduralByEdge(
final Pair<CFGNode,CFGNode> edge,
final LinkedList<CFGNode> path,
final CFGNodeFollowersInterprocedural nodeFollowers,
final CFGPathVisitor visitor,
final Stack<HashSet<Pair<CFGNode,CFGNode>>> visitedStack,
final Stack<CFGNode> callStack) {
final HashSet<Pair<CFGNode,CFGNode>> visitedEdges = visitedStack.peek();
path.addFirst(edge.getSecond());
visitedEdges.add(edge);
traverseCFGPathsInterprocedural(path,nodeFollowers,visitor,
visitedStack,callStack);
visitedEdges.remove(edge);
path.removeFirst();
}
private CFGTraversal() {
}
}
| false | true | private static void traverseCFGPathsInterprocedural(
final LinkedList<CFGNode> path,
final CFGNodeFollowersInterprocedural nodeFollowers,
final CFGPathVisitor visitor,
final Stack<HashSet<Pair<CFGNode,CFGNode>>> visitedStack,
final Stack<CFGNode> callStack) {
final HashSet<Pair<CFGNode,CFGNode>> visitedEdges = visitedStack.peek();
if (nodeFollowers.isCallNode(path.get(0))) {
if (path.size() < 2 || !nodeFollowers.isReturnNode(path.get(1))) {
final Pair<CFGNode,CFGNode> edge = Pair.make(path.getFirst(),
nodeFollowers.getCalleeNode(path.getFirst()));
if (visitedEdges.contains(edge))
return;
if (visitor.onCFGchange(path.getFirst(),edge.getSecond())) {
visitedStack.push(
new HashSet<Pair<CFGNode,CFGNode>>(visitedEdges));
callStack.push(edge.getFirst());
traverseCFGPathsInterproceduralByEdge(edge,path,
nodeFollowers,visitor,visitedStack,callStack);
return;
}
}
}
else if (!visitor.visitInternal(Collections.unmodifiableList(path),
callStack))
return;
if (nodeFollowers.isReturnNode(path.get(0)) && !callStack.isEmpty()) {
final Pair<CFGNode,CFGNode> edge = Pair.make(path.getFirst(),
callStack.peek());
if (visitedEdges.contains(edge))
return;
callStack.pop();
visitedStack.pop();
visitor.onCFGchange(path.getFirst(),edge.getSecond());
traverseCFGPathsInterproceduralByEdge(edge,path,nodeFollowers,
visitor,visitedStack,callStack);
return;
}
for (CFGNode currentNodeFollower : nodeFollowers.get(path.getFirst())) {
final Pair<CFGNode,CFGNode> edge = Pair.make(path.getFirst(),
currentNodeFollower);
if (visitedEdges.contains(edge))
continue;
traverseCFGPathsInterproceduralByEdge(edge,path,nodeFollowers,
visitor,visitedStack,callStack);
}
}
| private static void traverseCFGPathsInterprocedural(
final LinkedList<CFGNode> path,
final CFGNodeFollowersInterprocedural nodeFollowers,
final CFGPathVisitor visitor,
final Stack<HashSet<Pair<CFGNode,CFGNode>>> visitedStack,
final Stack<CFGNode> callStack) {
final HashSet<Pair<CFGNode,CFGNode>> visitedEdges = visitedStack.peek();
if (nodeFollowers.isCallNode(path.get(0))) {
if (path.size() < 2 || !nodeFollowers.isReturnNode(path.get(1))) {
final Pair<CFGNode,CFGNode> edge = Pair.make(path.getFirst(),
nodeFollowers.getCalleeNode(path.getFirst()));
if (visitedEdges.contains(edge))
return;
if (visitor.onCFGchange(path.getFirst(),edge.getSecond())) {
visitedStack.push(
new HashSet<Pair<CFGNode,CFGNode>>(visitedEdges));
callStack.push(edge.getFirst());
traverseCFGPathsInterproceduralByEdge(edge,path,
nodeFollowers,visitor,visitedStack,callStack);
callStack.pop();
visitedStack.pop();
visitor.onCFGchange(edge.getSecond(),path.getFirst());
return;
}
}
}
else if (!visitor.visitInternal(Collections.unmodifiableList(path),
callStack))
return;
if (nodeFollowers.isReturnNode(path.get(0)) && !callStack.isEmpty()) {
final Pair<CFGNode,CFGNode> edge = Pair.make(path.getFirst(),
callStack.peek());
if (visitedEdges.contains(edge))
return;
CFGNode lastCallStackNode = callStack.pop();
HashSet<Pair<CFGNode,CFGNode>> lastVisitedStack = visitedStack.pop();
visitor.onCFGchange(path.getFirst(),edge.getSecond());
traverseCFGPathsInterproceduralByEdge(edge,path,nodeFollowers,
visitor,visitedStack,callStack);
visitor.onCFGchange(edge.getSecond(),path.getFirst());
visitedStack.push(lastVisitedStack);
callStack.push(lastCallStackNode);
return;
}
for (CFGNode currentNodeFollower : nodeFollowers.get(path.getFirst())) {
final Pair<CFGNode,CFGNode> edge = Pair.make(path.getFirst(),
currentNodeFollower);
if (visitedEdges.contains(edge))
continue;
traverseCFGPathsInterproceduralByEdge(edge,path,nodeFollowers,
visitor,visitedStack,callStack);
}
}
|
diff --git a/src/eionet/meta/exports/ods/OdsServlet.java b/src/eionet/meta/exports/ods/OdsServlet.java
index 998fc8a7..cc7bbff3 100644
--- a/src/eionet/meta/exports/ods/OdsServlet.java
+++ b/src/eionet/meta/exports/ods/OdsServlet.java
@@ -1,222 +1,223 @@
/*
* Created on 4.05.2006
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package eionet.meta.exports.ods;
import java.io.*;
import java.sql.Connection;
import javax.servlet.*;
import javax.servlet.http.*;
import eionet.meta.DDSearchEngine;
import eionet.util.Props;
import eionet.util.PropsIF;
import eionet.util.Util;
import eionet.util.sql.ConnectionUtil;
/**
*
* @author jaanus
*/
public class OdsServlet extends HttpServlet{
/*
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
Connection conn = null;
String workingFolderPath = null;
try{
// get object id
String id = req.getParameter("id");
if (Util.voidStr(id)) throw new Exception("Missing request parameter: id");
// get object type
String type = req.getParameter("type");
if (Util.voidStr(type)) throw new Exception("Missing request parameter: type");
// get schema URL base
String schemaURLBase = Props.getProperty(PropsIF.XLS_SCHEMA_URL);
if (Util.voidStr(schemaURLBase))
throw new Exception("Missing property: " + PropsIF.XLS_SCHEMA_URL);
// prepare workinf folder
workingFolderPath = prepareWorkingFolder(req.getSession().getId());
// get db connection
conn = ConnectionUtil.getConnection();
// set up the ods object
Ods ods = null;
DDSearchEngine searchEngine = new DDSearchEngine(conn);
if (type.equals("dst")){
ods = new DstOds(searchEngine, id);
}
else if (type.equals("tbl")){
ods = new TblOds(searchEngine, id);
}
else
throw new Exception("Unknown object type: " + type);
ods.setWorkingFolderPath(workingFolderPath);
ods.setSchemaURLBase(schemaURLBase);
// process the ods object
ods.processContent();
ods.processMeta();
// prepare response
+ res.setContentType("application/vnd.oasis.opendocument.spreadsheet");
StringBuffer buf = new StringBuffer("attachment; filename=\"").
append(ods.getFinalFileName()).append("\"");
res.setHeader("Content-Disposition", buf.toString());
// write the ods result file into response
writeFileIntoResponse(new File(ods.getWorkingFolderPath() + Ods.ODS_FILE_NAME), res);
}
catch (Exception e){
e.printStackTrace(System.out);
throw new ServletException(Util.getStack(e));
}
finally{
// close DB connection
try{
if (conn != null) conn.close();
}
catch(Exception e){}
// clean up the working folder
try{
if (req.getParameter("keep_working_folder")==null)
deleteFolder(workingFolderPath);
}
catch(Exception e){}
}
}
/**
*
*
*/
private String prepareWorkingFolder(String sessionID) throws Exception{
// get ods-folder path
String odsFolder = Props.getProperty(PropsIF.OPENDOC_ODS_PATH);
if (odsFolder==null)
throw new Exception("Missing property: " + PropsIF.OPENDOC_ODS_PATH);
else if (!odsFolder.endsWith(File.separator))
odsFolder = odsFolder + File.separator;
// get DD temporary folder
String tmpFilePath = Props.getProperty(PropsIF.TEMP_FILE_PATH);
if (tmpFilePath==null)
throw new Exception("Missing property: " + PropsIF.TEMP_FILE_PATH);
else if (!tmpFilePath.endsWith(File.separator))
tmpFilePath = tmpFilePath + File.separator;
// build working folder name
StringBuffer buf = new StringBuffer(tmpFilePath);
buf.append("ods_");
buf.append(sessionID);
buf.append("_");
buf.append(System.currentTimeMillis());
// create working folder
File workginFolder = new File(buf.toString());
if (workginFolder.mkdir()==false)
throw new Exception("Failed to create directory: " + buf.toString());
String s = buf.toString() + File.separator;
// copy ods-file into working folder
File odsFile = new File(odsFolder + Ods.ODS_FILE_NAME);
File cpyOdsFile = new File(s + Ods.ODS_FILE_NAME);
copyFile(odsFile, cpyOdsFile);
// copy content-file into working folder
File contentFile = new File(odsFolder + Ods.CONTENT_FILE_NAME);
File cpyContentFile = new File(s + Ods.CONTENT_FILE_NAME);
copyFile(contentFile, cpyContentFile);
// copy meta-file into working folder
File metaFile = new File(odsFolder + Ods.META_FILE_NAME);
File cpyMetaFile = new File(s + Ods.META_FILE_NAME);
copyFile(metaFile, cpyMetaFile);
// return the newly created working folder's path
return buf.toString();
}
/*
*
*/
private void deleteFolder(String folderPath){
File folder = new File(folderPath);
File[] files = folder.listFiles();
for (int i=0; files!=null && i<files.length; i++){
files[i].delete();
}
folder.delete();
}
/**
*
* @param in
* @param out
* @throws Exception
*/
public void copyFile(File in, File out) throws Exception {
FileInputStream fis = null;
FileOutputStream fos = null;
try{
fis = new FileInputStream(in);
fos = new FileOutputStream(out);
byte[] buf = new byte[1024];
int i = 0;
while((i=fis.read(buf))!=-1){
fos.write(buf, 0, i);
}
}
finally{
if (fis!=null) fis.close();
if (fos!=null) fos.close();
}
}
/**
*
* @param file
* @param res
* @throws IOException
*/
private void writeFileIntoResponse(File file, HttpServletResponse res) throws IOException{
int i = 0;
byte[] buf = new byte[1024];
FileInputStream in = null;
OutputStream out = null;
try{
in = new FileInputStream(file);
res.setContentLength(in.available());
out = res.getOutputStream();
while ((i=in.read(buf, 0, buf.length)) != -1){
out.write(buf, 0, i);
}
}
finally{
if (in!=null) in.close();
if (out!=null) out.close();
}
}
}
| true | true | protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
Connection conn = null;
String workingFolderPath = null;
try{
// get object id
String id = req.getParameter("id");
if (Util.voidStr(id)) throw new Exception("Missing request parameter: id");
// get object type
String type = req.getParameter("type");
if (Util.voidStr(type)) throw new Exception("Missing request parameter: type");
// get schema URL base
String schemaURLBase = Props.getProperty(PropsIF.XLS_SCHEMA_URL);
if (Util.voidStr(schemaURLBase))
throw new Exception("Missing property: " + PropsIF.XLS_SCHEMA_URL);
// prepare workinf folder
workingFolderPath = prepareWorkingFolder(req.getSession().getId());
// get db connection
conn = ConnectionUtil.getConnection();
// set up the ods object
Ods ods = null;
DDSearchEngine searchEngine = new DDSearchEngine(conn);
if (type.equals("dst")){
ods = new DstOds(searchEngine, id);
}
else if (type.equals("tbl")){
ods = new TblOds(searchEngine, id);
}
else
throw new Exception("Unknown object type: " + type);
ods.setWorkingFolderPath(workingFolderPath);
ods.setSchemaURLBase(schemaURLBase);
// process the ods object
ods.processContent();
ods.processMeta();
// prepare response
StringBuffer buf = new StringBuffer("attachment; filename=\"").
append(ods.getFinalFileName()).append("\"");
res.setHeader("Content-Disposition", buf.toString());
// write the ods result file into response
writeFileIntoResponse(new File(ods.getWorkingFolderPath() + Ods.ODS_FILE_NAME), res);
}
catch (Exception e){
e.printStackTrace(System.out);
throw new ServletException(Util.getStack(e));
}
finally{
// close DB connection
try{
if (conn != null) conn.close();
}
catch(Exception e){}
// clean up the working folder
try{
if (req.getParameter("keep_working_folder")==null)
deleteFolder(workingFolderPath);
}
catch(Exception e){}
}
}
| protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
Connection conn = null;
String workingFolderPath = null;
try{
// get object id
String id = req.getParameter("id");
if (Util.voidStr(id)) throw new Exception("Missing request parameter: id");
// get object type
String type = req.getParameter("type");
if (Util.voidStr(type)) throw new Exception("Missing request parameter: type");
// get schema URL base
String schemaURLBase = Props.getProperty(PropsIF.XLS_SCHEMA_URL);
if (Util.voidStr(schemaURLBase))
throw new Exception("Missing property: " + PropsIF.XLS_SCHEMA_URL);
// prepare workinf folder
workingFolderPath = prepareWorkingFolder(req.getSession().getId());
// get db connection
conn = ConnectionUtil.getConnection();
// set up the ods object
Ods ods = null;
DDSearchEngine searchEngine = new DDSearchEngine(conn);
if (type.equals("dst")){
ods = new DstOds(searchEngine, id);
}
else if (type.equals("tbl")){
ods = new TblOds(searchEngine, id);
}
else
throw new Exception("Unknown object type: " + type);
ods.setWorkingFolderPath(workingFolderPath);
ods.setSchemaURLBase(schemaURLBase);
// process the ods object
ods.processContent();
ods.processMeta();
// prepare response
res.setContentType("application/vnd.oasis.opendocument.spreadsheet");
StringBuffer buf = new StringBuffer("attachment; filename=\"").
append(ods.getFinalFileName()).append("\"");
res.setHeader("Content-Disposition", buf.toString());
// write the ods result file into response
writeFileIntoResponse(new File(ods.getWorkingFolderPath() + Ods.ODS_FILE_NAME), res);
}
catch (Exception e){
e.printStackTrace(System.out);
throw new ServletException(Util.getStack(e));
}
finally{
// close DB connection
try{
if (conn != null) conn.close();
}
catch(Exception e){}
// clean up the working folder
try{
if (req.getParameter("keep_working_folder")==null)
deleteFolder(workingFolderPath);
}
catch(Exception e){}
}
}
|
diff --git a/src/com/bekvon/bukkit/residence/listeners/ResidencePlayerListener.java b/src/com/bekvon/bukkit/residence/listeners/ResidencePlayerListener.java
index 1d1ad32..20fed19 100644
--- a/src/com/bekvon/bukkit/residence/listeners/ResidencePlayerListener.java
+++ b/src/com/bekvon/bukkit/residence/listeners/ResidencePlayerListener.java
@@ -1,464 +1,463 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.bekvon.bukkit.residence.listeners;
import org.bukkit.ChatColor;
import com.bekvon.bukkit.residence.chat.ChatChannel;
import com.bekvon.bukkit.residence.permissions.PermissionGroup;
import com.bekvon.bukkit.residence.protection.ResidencePermissions;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.time.StopWatch;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerBucketFillEvent;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerQuitEvent;
import com.bekvon.bukkit.residence.Residence;
import com.bekvon.bukkit.residence.event.ResidenceEnterEvent;
import com.bekvon.bukkit.residence.event.ResidenceLeaveEvent;
import com.bekvon.bukkit.residence.protection.ClaimedResidence;
import com.bekvon.bukkit.residence.protection.FlagPermissions;
import com.bekvon.bukkit.residence.protection.ResidenceManager;
import com.inori.utils.ILog;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.inventory.InventoryHolder;
/**
*
* @author Administrator
*/
public class ResidencePlayerListener implements Listener {
protected Map<String,String> cache;
protected Map<String,Long> lastUpdate;
protected Map<String,Location> lastOutsideLoc;
protected List<String> healing;
protected int minUpdateTime;
protected boolean chatenabled;
protected List<String> playerToggleChat;
public ResidencePlayerListener()
{
cache = new HashMap<String,String>();
lastUpdate = new HashMap<String,Long>();
lastOutsideLoc = new HashMap<String,Location>();
healing = Collections.synchronizedList(new ArrayList<String>());
playerToggleChat = new ArrayList<String>();
minUpdateTime = Residence.getConfigManager().getMinMoveUpdateInterval();
chatenabled = Residence.getConfigManager().chatEnabled();
}
public void reload()
{
cache = new HashMap<String,String>();
lastUpdate = new HashMap<String,Long>();
lastOutsideLoc = new HashMap<String,Location>();
healing = Collections.synchronizedList(new ArrayList<String>());
playerToggleChat = new ArrayList<String>();
minUpdateTime = Residence.getConfigManager().getMinMoveUpdateInterval();
chatenabled = Residence.getConfigManager().chatEnabled();
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerQuit(PlayerQuitEvent event) {
String pname = event.getPlayer().getName();
cache.remove(pname);
lastUpdate.remove(pname);
lastOutsideLoc.remove(pname);
healing.remove(pname);
Residence.getChatManager().removeFromChannel(pname);
}
private boolean isContainer(Material mat, Block block) {
return mat == Material.CHEST || mat == Material.FURNACE || mat == Material.BURNING_FURNACE || mat == Material.DISPENSER || Residence.getConfigManager().getCustomContainers().contains(Integer.valueOf(block.getTypeId()));
}
private boolean isCanUseEntity_BothClick(Material mat, Block block) {
return mat == Material.LEVER || mat == Material.STONE_BUTTON ||
mat == Material.WOODEN_DOOR || mat == Material.TRAP_DOOR ||
mat == Material.PISTON_BASE || mat == Material.PISTON_STICKY_BASE ||
Residence.getConfigManager().getCustomBothClick().contains(Integer.valueOf(block.getTypeId()));
}
private boolean isCanUseEntity_RClickOnly(Material mat, Block block) {
return mat == Material.BED_BLOCK || mat == Material.WORKBENCH || mat == Material.BREWING_STAND || mat == Material.ENCHANTMENT_TABLE ||
Residence.getConfigManager().getCustomRightClick().contains(Integer.valueOf(block.getTypeId()));
}
private boolean isCanUseEntity(Material mat, Block block) {
return isCanUseEntity_BothClick(mat, block) || isCanUseEntity_RClickOnly(mat, block);
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerInteract(PlayerInteractEvent event) {
if(event.isCancelled())
return;
Player player = event.getPlayer();
Material heldItem = player.getItemInHand().getType();
Block block = event.getClickedBlock();
Material mat = block.getType();
ILog.sendToPlayer(player, mat.toString());
if(!(((isContainer(mat, block) || isCanUseEntity_RClickOnly(mat, block)) && event.getAction() == Action.RIGHT_CLICK_BLOCK) ||
isCanUseEntity_BothClick(mat, block)))
{
int typeId = player.getItemInHand().getTypeId();
if(typeId != Residence.getConfigManager().getSelectionTooldID() &&
typeId != Residence.getConfigManager().getInfoToolID())
{
return;
}
}
ILog.sendToPlayer(player, "onPlayerInteract Fired");
String world = player.getWorld().getName();
String permgroup = Residence.getPermissionManager().getGroupNameByPlayer(player);
boolean resadmin = Residence.getPermissionManager().isResidenceAdmin(player);
if(!resadmin && !Residence.getItemManager().isAllowed(heldItem, permgroup, world))
{
player.sendMessage(ChatColor.RED+Residence.getLanguage().getPhrase("ItemBlacklisted"));
event.setCancelled(true);
return;
}
if(event.getAction() == Action.LEFT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_BLOCK)
{
if (player.getItemInHand().getTypeId() == Residence.getConfigManager().getSelectionTooldID()) {
PermissionGroup group = Residence.getPermissionManager().getGroup(player);
if(player.hasPermission("residence.create") || group.canCreateResidences() || resadmin)
{
if (event.getAction() == Action.LEFT_CLICK_BLOCK) {
Location loc = block.getLocation();
Residence.getSelectionManager().placeLoc1(player, loc);
player.sendMessage(ChatColor.GREEN+Residence.getLanguage().getPhrase("SelectPoint",Residence.getLanguage().getPhrase("Primary"))+ChatColor.RED+"(" + loc.getBlockX() + "," + loc.getBlockY() + "," + loc.getBlockZ() + ")"+ChatColor.GREEN+"!");
} else if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Location loc = block.getLocation();
Residence.getSelectionManager().placeLoc2(player, loc);
player.sendMessage(ChatColor.GREEN+Residence.getLanguage().getPhrase("SelectPoint",Residence.getLanguage().getPhrase("Secondary"))+ChatColor.RED+"(" + loc.getBlockX() + "," + loc.getBlockY() + "," + loc.getBlockZ() + ")"+ChatColor.GREEN+"!");
}
}
}
if(player.getItemInHand().getTypeId() == Residence.getConfigManager().getInfoToolID())
{
if(event.getAction() == Action.LEFT_CLICK_BLOCK)
{
Location loc = block.getLocation();
String res = Residence.getResidenceManager().getNameByLoc(loc);
if(res!=null)
Residence.getResidenceManager().printAreaInfo(res, player);
event.setCancelled(true);
if(res==null)
event.setCancelled(true);
player.sendMessage(Residence.getLanguage().getPhrase("NoResHere"));
}
}
if(!resadmin)
{
ClaimedResidence res = Residence.getResidenceManager().getByLoc(block.getLocation());
if(isContainer(mat, block))
{
boolean hasuse;
boolean hascontainer;
if (res != null) {
hasuse = res.getPermissions().playerHas(player.getName(), "use", true);
hascontainer = res.getPermissions().playerHas(player.getName(), "container", hasuse);
} else {
FlagPermissions perms = Residence.getWorldFlags().getPerms(player);
hasuse = perms.playerHas(player.getName(), player.getWorld().getName(), "use", true);
hascontainer = perms.playerHas(player.getName(), player.getWorld().getName(), "container", hasuse);
}
if ((!hasuse && !hascontainer) || !hascontainer) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED+Residence.getLanguage().getPhrase("FlagDeny","container"));
}
}
else if(isCanUseEntity(mat, block))
{
if(res!=null)
{
if(!res.getPermissions().playerHas(player.getName(),"use", true))
{
event.setCancelled(true);
player.sendMessage(ChatColor.RED+Residence.getLanguage().getPhrase("FlagDeny","use"));
}
}
else
{
if(!Residence.getWorldFlags().getPerms(player).has("use", true))
{
event.setCancelled(true);
player.sendMessage(ChatColor.RED+Residence.getLanguage().getPhrase("FlagDeny","use"));
}
}
}
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) {
if(event.isCancelled())
return;
String resname = Residence.getResidenceManager().getNameByLoc(event.getBlockClicked().getLocation());
ClaimedResidence res = Residence.getResidenceManager().getByName(resname);
Player player = event.getPlayer();
String pname = player.getName();
boolean hasbuild;
boolean hasbucket;
if(res!=null)
{
if (Residence.getConfigManager().preventRentModify() && Residence.getConfigManager().enabledRentSystem()) {
if (Residence.getRentManager().isRented(resname)) {
player.sendMessage(ChatColor.RED+Residence.getLanguage().getPhrase("RentedModifyDeny"));
event.setCancelled(true);
return;
}
res = Residence.getResidenceManager().getByName(resname);
}
ResidencePermissions perms = res.getPermissions();
hasbuild = perms.playerHas(pname,"build", true);
hasbucket = perms.playerHas(pname,"bucket", hasbuild);
}
else
{
hasbuild = Residence.getWorldFlags().getPerms(player).playerHas(pname, player.getWorld().getName(), "build", true);
hasbucket = Residence.getWorldFlags().getPerms(player).playerHas(pname, player.getWorld().getName(), "bucket", hasbuild);
}
if ((!hasbuild && !hasbucket) || !hasbucket) {
player.sendMessage(ChatColor.RED+Residence.getLanguage().getPhrase("FlagDeny","bucket"));
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerBucketFill(PlayerBucketFillEvent event) {
if(event.isCancelled())
return;
String resname = Residence.getResidenceManager().getNameByLoc(event.getBlockClicked().getLocation());
ClaimedResidence res = Residence.getResidenceManager().getByName(resname);
Player player = event.getPlayer();
String pname = player.getName();
boolean hasbuild;
boolean hasbucket;
if(res!=null)
{
if (Residence.getConfigManager().preventRentModify() && Residence.getConfigManager().enabledRentSystem()) {
if (Residence.getRentManager().isRented(resname)) {
player.sendMessage(ChatColor.RED+Residence.getLanguage().getPhrase("RentedModifyDeny"));
event.setCancelled(true);
return;
}
res = Residence.getResidenceManager().getByName(resname);
}
ResidencePermissions perms = res.getPermissions();
hasbuild = perms.playerHas(pname,"build", true);
hasbucket = perms.playerHas(pname,"bucket", hasbuild);
}
else
{
hasbuild = Residence.getWorldFlags().getPerms(player).playerHas(pname, player.getWorld().getName(), "build", true);
hasbucket = Residence.getWorldFlags().getPerms(player).playerHas(pname, player.getWorld().getName(), "bucket", hasbuild);
}
if ((!hasbuild && !hasbucket) || !hasbucket) {
player.sendMessage(ChatColor.RED+Residence.getLanguage().getPhrase("FlagDeny","bucket"));
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerMove(PlayerMoveEvent event) {
- if(event.getFrom().distance(event.getTo()) == 0)
- {
+ if(event.getFrom().getWorld() == event.getTo().getWorld())
+ if(event.getFrom().distance(event.getTo()) == 0)
return;
- }
Player player = event.getPlayer();
ILog.sendToPlayer(player, "onPlayerMove("+event.getFrom().distance(event.getTo())+") Fired");
String pname = player.getName();
long lastCheck = 0;
if (lastUpdate.containsKey(pname)) {
lastCheck = lastUpdate.get(pname);
}
long now = System.currentTimeMillis();
if (now - lastCheck > minUpdateTime) {
ResidenceManager manager = Residence.getResidenceManager();
ClaimedResidence res = null;
Location ploc = event.getTo();
boolean enterArea = false;
boolean chatchange = false;
String areaname = cache.get(pname);
if (areaname != null) {
res = manager.getByName(areaname);
if (res == null) {
cache.remove(pname);
areaname = null;
} else {
if (!res.containsLoc(ploc)) {
String leave = res.getLeaveMessage();
ResidenceLeaveEvent leaveevent = new ResidenceLeaveEvent(res,player);
Residence.getServ().getPluginManager().callEvent(leaveevent);
if (leave != null && !leave.equals("")) {
player.sendMessage(ChatColor.YELLOW + this.insertMessages(player, areaname, res, leave));
}
res = res.getParent();
while (res != null && !res.containsLoc(ploc)) {
res = res.getParent();
}
if (res == null) {
cache.remove(pname);
areaname = null;
Residence.getChatManager().removeFromChannel(pname);
} else {
areaname = Residence.getResidenceManager().getNameByLoc(ploc);
cache.put(pname, areaname);
chatchange = true;
}
} else {
String subzone = res.getSubzoneNameByLoc(ploc);
if (subzone != null) {
areaname = areaname + "." + subzone;
cache.put(pname, areaname);
res = res.getSubzone(subzone);
enterArea = true;
chatchange = true;
}
}
}
}
if(areaname == null)
{
areaname = manager.getNameByLoc(ploc);
chatchange = true;
enterArea = true;
}
if (areaname != null) {
if(chatchange && chatenabled)
Residence.getChatManager().setChannel(pname, areaname);
res = manager.getByName(areaname);
if (res.getPermissions().playerHas(pname, "move", true) || Residence.getPermissionManager().isResidenceAdmin(player)) {
cache.put(pname, areaname);
if (enterArea) {
String enterMessage = res.getEnterMessage();
ResidenceEnterEvent enterevent = new ResidenceEnterEvent(res, player);
Residence.getServ().getPluginManager().callEvent(enterevent);
if(enterMessage!=null)
player.sendMessage(ChatColor.YELLOW + this.insertMessages(player, areaname, res, enterMessage));
}
} else {
event.setCancelled(true);
Location lastLoc = lastOutsideLoc.get(pname);
if (lastLoc != null) {
player.teleport(lastLoc);
} else {
player.teleport(res.getOutsideFreeLoc(event.getTo()));
}
player.sendMessage(ChatColor.RED+Residence.getLanguage().getPhrase("ResidenceMoveDeny",areaname));
}
int health = player.getHealth();
if(health<20)
{
if(res.getPermissions().has("healing", false))
{
if(!healing.contains(pname))
healing.add(pname);
}
else
{
if(healing.contains(pname))
healing.remove(pname);
}
}
}
else
{
lastOutsideLoc.put(pname, ploc);
if(healing.contains(pname))
healing.remove(pname);
}
lastUpdate.put(pname, System.currentTimeMillis());
}
}
public String insertMessages(Player player, String areaname, ClaimedResidence res, String message) {
try
{
message = message.replaceAll("%player", player.getName());
message = message.replaceAll("%owner", res.getPermissions().getOwner());
message = message.replaceAll("%residence", areaname);
} catch(Exception ex)
{
return "";
}
return message;
}
public void doHeals() {
try {
Player[] p = Residence.getServ().getOnlinePlayers();
for (Player player : p) {
if (healing.contains(player.getName())) {
int health = player.getHealth();
if (health < 20) {
player.setHealth(health + 1);
//System.out.println("heal:" +player.getName() + " oldhealth = "+health+" newhealth = " + player.getHealth());
}
}
}
} catch (Exception ex) {
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerChat(PlayerChatEvent event) {
if(event.isCancelled()){return;}
String pname = event.getPlayer().getName();
if(chatenabled && playerToggleChat.contains(pname))
{
String area = cache.get(pname);
if(area!=null)
{
ChatChannel channel = Residence.getChatManager().getChannel(area);
if(channel!=null)
channel.chat(pname, event.getMessage());
event.setCancelled(true);
}
}
}
public void tooglePlayerResidenceChat(Player player)
{
String pname = player.getName();
if(playerToggleChat.contains(pname))
{
playerToggleChat.remove(pname);
player.sendMessage(ChatColor.YELLOW+Residence.getLanguage().getPhrase("ResidenceChat",ChatColor.RED+"OFF"+ChatColor.YELLOW+"!"));
}
else
{
playerToggleChat.add(pname);
player.sendMessage(ChatColor.YELLOW+Residence.getLanguage().getPhrase("ResidenceChat",ChatColor.RED+"ON"+ChatColor.YELLOW+"!"));
}
}
public String getLastAreaName(String player)
{
return cache.get(player);
}
}
| false | true | public void onPlayerMove(PlayerMoveEvent event) {
if(event.getFrom().distance(event.getTo()) == 0)
{
return;
}
Player player = event.getPlayer();
ILog.sendToPlayer(player, "onPlayerMove("+event.getFrom().distance(event.getTo())+") Fired");
String pname = player.getName();
long lastCheck = 0;
if (lastUpdate.containsKey(pname)) {
lastCheck = lastUpdate.get(pname);
}
long now = System.currentTimeMillis();
if (now - lastCheck > minUpdateTime) {
ResidenceManager manager = Residence.getResidenceManager();
ClaimedResidence res = null;
Location ploc = event.getTo();
boolean enterArea = false;
boolean chatchange = false;
String areaname = cache.get(pname);
if (areaname != null) {
res = manager.getByName(areaname);
if (res == null) {
cache.remove(pname);
areaname = null;
} else {
if (!res.containsLoc(ploc)) {
String leave = res.getLeaveMessage();
ResidenceLeaveEvent leaveevent = new ResidenceLeaveEvent(res,player);
Residence.getServ().getPluginManager().callEvent(leaveevent);
if (leave != null && !leave.equals("")) {
player.sendMessage(ChatColor.YELLOW + this.insertMessages(player, areaname, res, leave));
}
res = res.getParent();
while (res != null && !res.containsLoc(ploc)) {
res = res.getParent();
}
if (res == null) {
cache.remove(pname);
areaname = null;
Residence.getChatManager().removeFromChannel(pname);
} else {
areaname = Residence.getResidenceManager().getNameByLoc(ploc);
cache.put(pname, areaname);
chatchange = true;
}
} else {
String subzone = res.getSubzoneNameByLoc(ploc);
if (subzone != null) {
areaname = areaname + "." + subzone;
cache.put(pname, areaname);
res = res.getSubzone(subzone);
enterArea = true;
chatchange = true;
}
}
}
}
if(areaname == null)
{
areaname = manager.getNameByLoc(ploc);
chatchange = true;
enterArea = true;
}
if (areaname != null) {
if(chatchange && chatenabled)
Residence.getChatManager().setChannel(pname, areaname);
res = manager.getByName(areaname);
if (res.getPermissions().playerHas(pname, "move", true) || Residence.getPermissionManager().isResidenceAdmin(player)) {
cache.put(pname, areaname);
if (enterArea) {
String enterMessage = res.getEnterMessage();
ResidenceEnterEvent enterevent = new ResidenceEnterEvent(res, player);
Residence.getServ().getPluginManager().callEvent(enterevent);
if(enterMessage!=null)
player.sendMessage(ChatColor.YELLOW + this.insertMessages(player, areaname, res, enterMessage));
}
} else {
event.setCancelled(true);
Location lastLoc = lastOutsideLoc.get(pname);
if (lastLoc != null) {
player.teleport(lastLoc);
} else {
player.teleport(res.getOutsideFreeLoc(event.getTo()));
}
player.sendMessage(ChatColor.RED+Residence.getLanguage().getPhrase("ResidenceMoveDeny",areaname));
}
int health = player.getHealth();
if(health<20)
{
if(res.getPermissions().has("healing", false))
{
if(!healing.contains(pname))
healing.add(pname);
}
else
{
if(healing.contains(pname))
healing.remove(pname);
}
}
}
else
{
lastOutsideLoc.put(pname, ploc);
if(healing.contains(pname))
healing.remove(pname);
}
lastUpdate.put(pname, System.currentTimeMillis());
}
}
| public void onPlayerMove(PlayerMoveEvent event) {
if(event.getFrom().getWorld() == event.getTo().getWorld())
if(event.getFrom().distance(event.getTo()) == 0)
return;
Player player = event.getPlayer();
ILog.sendToPlayer(player, "onPlayerMove("+event.getFrom().distance(event.getTo())+") Fired");
String pname = player.getName();
long lastCheck = 0;
if (lastUpdate.containsKey(pname)) {
lastCheck = lastUpdate.get(pname);
}
long now = System.currentTimeMillis();
if (now - lastCheck > minUpdateTime) {
ResidenceManager manager = Residence.getResidenceManager();
ClaimedResidence res = null;
Location ploc = event.getTo();
boolean enterArea = false;
boolean chatchange = false;
String areaname = cache.get(pname);
if (areaname != null) {
res = manager.getByName(areaname);
if (res == null) {
cache.remove(pname);
areaname = null;
} else {
if (!res.containsLoc(ploc)) {
String leave = res.getLeaveMessage();
ResidenceLeaveEvent leaveevent = new ResidenceLeaveEvent(res,player);
Residence.getServ().getPluginManager().callEvent(leaveevent);
if (leave != null && !leave.equals("")) {
player.sendMessage(ChatColor.YELLOW + this.insertMessages(player, areaname, res, leave));
}
res = res.getParent();
while (res != null && !res.containsLoc(ploc)) {
res = res.getParent();
}
if (res == null) {
cache.remove(pname);
areaname = null;
Residence.getChatManager().removeFromChannel(pname);
} else {
areaname = Residence.getResidenceManager().getNameByLoc(ploc);
cache.put(pname, areaname);
chatchange = true;
}
} else {
String subzone = res.getSubzoneNameByLoc(ploc);
if (subzone != null) {
areaname = areaname + "." + subzone;
cache.put(pname, areaname);
res = res.getSubzone(subzone);
enterArea = true;
chatchange = true;
}
}
}
}
if(areaname == null)
{
areaname = manager.getNameByLoc(ploc);
chatchange = true;
enterArea = true;
}
if (areaname != null) {
if(chatchange && chatenabled)
Residence.getChatManager().setChannel(pname, areaname);
res = manager.getByName(areaname);
if (res.getPermissions().playerHas(pname, "move", true) || Residence.getPermissionManager().isResidenceAdmin(player)) {
cache.put(pname, areaname);
if (enterArea) {
String enterMessage = res.getEnterMessage();
ResidenceEnterEvent enterevent = new ResidenceEnterEvent(res, player);
Residence.getServ().getPluginManager().callEvent(enterevent);
if(enterMessage!=null)
player.sendMessage(ChatColor.YELLOW + this.insertMessages(player, areaname, res, enterMessage));
}
} else {
event.setCancelled(true);
Location lastLoc = lastOutsideLoc.get(pname);
if (lastLoc != null) {
player.teleport(lastLoc);
} else {
player.teleport(res.getOutsideFreeLoc(event.getTo()));
}
player.sendMessage(ChatColor.RED+Residence.getLanguage().getPhrase("ResidenceMoveDeny",areaname));
}
int health = player.getHealth();
if(health<20)
{
if(res.getPermissions().has("healing", false))
{
if(!healing.contains(pname))
healing.add(pname);
}
else
{
if(healing.contains(pname))
healing.remove(pname);
}
}
}
else
{
lastOutsideLoc.put(pname, ploc);
if(healing.contains(pname))
healing.remove(pname);
}
lastUpdate.put(pname, System.currentTimeMillis());
}
}
|
diff --git a/src/algvis/avltree/AVLNode.java b/src/algvis/avltree/AVLNode.java
index 5b3b1a9..c394309 100644
--- a/src/algvis/avltree/AVLNode.java
+++ b/src/algvis/avltree/AVLNode.java
@@ -1,116 +1,116 @@
package algvis.avltree;
import java.awt.Color;
import algvis.bst.BSTNode;
import algvis.core.NodeColor;
import algvis.core.DataStructure;
import algvis.core.Node;
import algvis.core.View;
import algvis.scenario.commands.avlnode.SetBalanceCommand;
//import static java.lang.Math.random;
//import static java.lang.Math.round;
public class AVLNode extends BSTNode {
private int bal = 0;
public AVLNode(DataStructure D, int key, int x, int y) {
super(D, key, x, y);
}
public AVLNode(DataStructure D, int key) {
this(D, key, 0, 0);
getReady();
}
public AVLNode(BSTNode v) {
this(v.D, v.key, v.x, v.y);
}
@Override
public AVLNode getLeft() {
return (AVLNode) super.getLeft();
}
@Override
public AVLNode getRight() {
return (AVLNode) super.getRight();
}
@Override
public AVLNode getParent() {
return (AVLNode) super.getParent();
}
public int balance() {
int l = (getLeft() == null) ? 0 : getLeft().height, r = (getRight() == null) ? 0
: getRight().height;
setBalance(r - l);
return bal;
}
public void setBalance(int bal) {
if (this.bal != bal) {
D.scenario.add(new SetBalanceCommand(this, bal));
this.bal = bal;
}
}
public int getBalance() {
return bal;
}
@Override
public void calc() {
super.calc();
balance();
}
@Override
public void draw(View V) {
if (state == Node.INVISIBLE || key == NULL) {
return;
}
drawBg(V);
drawArrow(V);
drawArc(V);
int xx = x - Node.radius, yy = y - Node.radius, dx = 2 * Node.radius, dy = 2 * Node.radius;
String b = "";
- if (getColor() == NodeColor.NORMAL) {
+ if (getBgColor() == NodeColor.NORMAL.bgColor) {
V.setColor(Color.ORANGE);
switch (bal) {
case +2:
b = "++";
V.fillArc(xx, yy, dx, dy, 270, 180);
break;
case +1:
b = "+";
V.fillArc(xx, yy, dx, dy, 210, 180);
break;
case 0:
b = "\u00b7";
V.fillArc(xx, yy, dx, dy, 180, 180);
break;
case -1:
b = "\u2013";
V.fillArc(xx, yy, dx, dy, 150, 180);
break;
case -2:
b = "\u2013\u2013";
V.fillArc(xx, yy, dx, dy, 90, 180);
break;
}
V.setColor(getFgColor());
V.drawOval(x - Node.radius, y - Node.radius, 2 * Node.radius, 2 * Node.radius);
}
drawKey(V);
if (getParent() != null && getParent().getLeft() == this) {
V.drawString(b, x - Node.radius - 1, y - Node.radius - 1, 10);
} else {
V.drawString(b, x + Node.radius + 1, y - Node.radius - 1, 10);
}
}
}
| true | true | public void draw(View V) {
if (state == Node.INVISIBLE || key == NULL) {
return;
}
drawBg(V);
drawArrow(V);
drawArc(V);
int xx = x - Node.radius, yy = y - Node.radius, dx = 2 * Node.radius, dy = 2 * Node.radius;
String b = "";
if (getColor() == NodeColor.NORMAL) {
V.setColor(Color.ORANGE);
switch (bal) {
case +2:
b = "++";
V.fillArc(xx, yy, dx, dy, 270, 180);
break;
case +1:
b = "+";
V.fillArc(xx, yy, dx, dy, 210, 180);
break;
case 0:
b = "\u00b7";
V.fillArc(xx, yy, dx, dy, 180, 180);
break;
case -1:
b = "\u2013";
V.fillArc(xx, yy, dx, dy, 150, 180);
break;
case -2:
b = "\u2013\u2013";
V.fillArc(xx, yy, dx, dy, 90, 180);
break;
}
V.setColor(getFgColor());
V.drawOval(x - Node.radius, y - Node.radius, 2 * Node.radius, 2 * Node.radius);
}
drawKey(V);
if (getParent() != null && getParent().getLeft() == this) {
V.drawString(b, x - Node.radius - 1, y - Node.radius - 1, 10);
} else {
V.drawString(b, x + Node.radius + 1, y - Node.radius - 1, 10);
}
}
| public void draw(View V) {
if (state == Node.INVISIBLE || key == NULL) {
return;
}
drawBg(V);
drawArrow(V);
drawArc(V);
int xx = x - Node.radius, yy = y - Node.radius, dx = 2 * Node.radius, dy = 2 * Node.radius;
String b = "";
if (getBgColor() == NodeColor.NORMAL.bgColor) {
V.setColor(Color.ORANGE);
switch (bal) {
case +2:
b = "++";
V.fillArc(xx, yy, dx, dy, 270, 180);
break;
case +1:
b = "+";
V.fillArc(xx, yy, dx, dy, 210, 180);
break;
case 0:
b = "\u00b7";
V.fillArc(xx, yy, dx, dy, 180, 180);
break;
case -1:
b = "\u2013";
V.fillArc(xx, yy, dx, dy, 150, 180);
break;
case -2:
b = "\u2013\u2013";
V.fillArc(xx, yy, dx, dy, 90, 180);
break;
}
V.setColor(getFgColor());
V.drawOval(x - Node.radius, y - Node.radius, 2 * Node.radius, 2 * Node.radius);
}
drawKey(V);
if (getParent() != null && getParent().getLeft() == this) {
V.drawString(b, x - Node.radius - 1, y - Node.radius - 1, 10);
} else {
V.drawString(b, x + Node.radius + 1, y - Node.radius - 1, 10);
}
}
|
diff --git a/src/be/ibridge/kettle/core/database/DatabaseMetaInformation.java b/src/be/ibridge/kettle/core/database/DatabaseMetaInformation.java
index 84197f58..f75f4092 100644
--- a/src/be/ibridge/kettle/core/database/DatabaseMetaInformation.java
+++ b/src/be/ibridge/kettle/core/database/DatabaseMetaInformation.java
@@ -1,281 +1,280 @@
package be.ibridge.kettle.core.database;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import org.eclipse.core.runtime.IProgressMonitor;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
/**
* Contains the schema's, catalogs, tables, views, synonyms, etc we can find in the databases...
*
* @author Matt
* @since 7-apr-2005
*/
public class DatabaseMetaInformation
{
private String[] tables;
private String[] views;
private String[] synonyms;
private Catalog[] catalogs;
private Schema[] schemas;
private DatabaseMeta dbInfo;
/**
* Create a new DatabaseMetaData object for the given database connection
*/
public DatabaseMetaInformation(DatabaseMeta dbInfo)
{
this.dbInfo = dbInfo;
}
/**
* @return Returns the catalogs.
*/
public Catalog[] getCatalogs()
{
return catalogs;
}
/**
* @param catalogs The catalogs to set.
*/
public void setCatalogs(Catalog[] catalogs)
{
this.catalogs = catalogs;
}
/**
* @return Returns the dbInfo.
*/
public DatabaseMeta getDbInfo()
{
return dbInfo;
}
/**
* @param dbInfo The dbInfo to set.
*/
public void setDbInfo(DatabaseMeta dbInfo)
{
this.dbInfo = dbInfo;
}
/**
* @return Returns the schemas.
*/
public Schema[] getSchemas()
{
return schemas;
}
/**
* @param schemas The schemas to set.
*/
public void setSchemas(Schema[] schemas)
{
this.schemas = schemas;
}
/**
* @return Returns the tables.
*/
public String[] getTables()
{
return tables;
}
/**
* @param tables The tables to set.
*/
public void setTables(String[] tables)
{
this.tables = tables;
}
/**
* @return Returns the views.
*/
public String[] getViews()
{
return views;
}
/**
* @param views The views to set.
*/
public void setViews(String[] views)
{
this.views = views;
}
/**
* @param synonyms The synonyms to set.
*/
public void setSynonyms(String[] synonyms)
{
this.synonyms = synonyms;
}
/**
* @return Returns the synonyms.
*/
public String[] getSynonyms()
{
return synonyms;
}
public void getData(IProgressMonitor monitor) throws KettleDatabaseException
{
if (monitor!=null)
{
monitor.beginTask("Getting information from the database...", 8);
}
Database db = new Database(dbInfo);
try
{
if (monitor!=null) monitor.subTask("Connecting to database");
db.connect();
if (monitor!=null) monitor.worked(1);
if (monitor!=null && monitor.isCanceled()) return;
if (monitor!=null) monitor.subTask("Getting database metadata");
DatabaseMetaData dbmd = db.getDatabaseMetaData();
if (monitor!=null) monitor.worked(1);
if (monitor!=null && monitor.isCanceled()) return;
if (monitor!=null) monitor.subTask("Getting catalog information");
if (dbInfo.supportsCatalogs() && dbmd.supportsCatalogsInTableDefinitions())
{
ArrayList catalogList = new ArrayList();
ResultSet catalogs = dbmd.getCatalogs();
while (catalogs!=null && catalogs.next())
{
String catalogName = catalogs.getString(1);
ArrayList catalogItems = new ArrayList();
ResultSet tables = null;
try
{
tables = dbmd.getTables(catalogName, null, null, null );
while (tables.next())
{
String table_name = tables.getString(3);
if (!db.isSystemTable(table_name))
{
catalogItems.add(table_name);
}
}
- tables.close();
}
catch(Exception e)
{
// Obviously, we're not allowed to snoop around in this catalog.
// Just ignore it!
}
finally
{
if ( tables != null ) tables.close();
}
Catalog catalog = new Catalog(catalogName, (String[])catalogItems.toArray(new String[catalogItems.size()]));
catalogList.add(catalog);
}
catalogs.close();
// Save for later...
setCatalogs((Catalog[])catalogList.toArray(new Catalog[catalogList.size()]));
}
if (monitor!=null) monitor.worked(1);
if (monitor!=null && monitor.isCanceled()) return;
if (monitor!=null) monitor.subTask("Getting schema information");
if (dbInfo.supportsSchemas() && dbmd.supportsSchemasInTableDefinitions())
{
ArrayList schemaList = new ArrayList();
ResultSet schemas = null;
try
{
schemas = dbmd.getSchemas();
while (schemas!=null && schemas.next())
{
ArrayList schemaItems = new ArrayList();
String schemaName = schemas.getString(1);
ResultSet tables = null;
try
{
tables = dbmd.getTables(null, schemaName, null, null );
while (tables.next())
{
String table_name = tables.getString(3);
if (!db.isSystemTable(table_name))
{
schemaItems.add(table_name);
}
}
Collections.sort(schemaItems);
}
catch(Exception e)
{
// Obviously, we're not allowed to snoop around in this catalog.
// Just ignore it!
}
finally
{
if ( tables != null ) tables.close();
}
Schema schema = new Schema(schemaName, (String[])schemaItems.toArray(new String[schemaItems.size()]));
schemaList.add(schema);
}
}
finally
{
if ( schemas != null ) schemas.close();
}
// Save for later...
setSchemas((Schema[])schemaList.toArray(new Schema[schemaList.size()]));
}
if (monitor!=null) monitor.worked(1);
if (monitor!=null && monitor.isCanceled()) return;
if (monitor!=null) monitor.subTask("Getting tables");
setTables(db.getTablenames());
if (monitor!=null) monitor.worked(1);
if (monitor!=null && monitor.isCanceled()) return;
if (monitor!=null) monitor.subTask("Getting views");
if (dbInfo.supportsViews())
{
setViews(db.getViews());
}
if (monitor!=null) monitor.worked(1);
if (monitor!=null && monitor.isCanceled()) return;
if (monitor!=null) monitor.subTask("Getting synonyms");
if (dbInfo.supportsSynonyms())
{
setSynonyms(db.getSynonyms());
}
if (monitor!=null) monitor.worked(1);
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to retrieve database information because of an error", e);
}
finally
{
if (monitor!=null) monitor.subTask("Closing database connection");
db.disconnect();
if (monitor!=null) monitor.worked(1);
}
if (monitor!=null) monitor.done();
}
}
| true | true | public void getData(IProgressMonitor monitor) throws KettleDatabaseException
{
if (monitor!=null)
{
monitor.beginTask("Getting information from the database...", 8);
}
Database db = new Database(dbInfo);
try
{
if (monitor!=null) monitor.subTask("Connecting to database");
db.connect();
if (monitor!=null) monitor.worked(1);
if (monitor!=null && monitor.isCanceled()) return;
if (monitor!=null) monitor.subTask("Getting database metadata");
DatabaseMetaData dbmd = db.getDatabaseMetaData();
if (monitor!=null) monitor.worked(1);
if (monitor!=null && monitor.isCanceled()) return;
if (monitor!=null) monitor.subTask("Getting catalog information");
if (dbInfo.supportsCatalogs() && dbmd.supportsCatalogsInTableDefinitions())
{
ArrayList catalogList = new ArrayList();
ResultSet catalogs = dbmd.getCatalogs();
while (catalogs!=null && catalogs.next())
{
String catalogName = catalogs.getString(1);
ArrayList catalogItems = new ArrayList();
ResultSet tables = null;
try
{
tables = dbmd.getTables(catalogName, null, null, null );
while (tables.next())
{
String table_name = tables.getString(3);
if (!db.isSystemTable(table_name))
{
catalogItems.add(table_name);
}
}
tables.close();
}
catch(Exception e)
{
// Obviously, we're not allowed to snoop around in this catalog.
// Just ignore it!
}
finally
{
if ( tables != null ) tables.close();
}
Catalog catalog = new Catalog(catalogName, (String[])catalogItems.toArray(new String[catalogItems.size()]));
catalogList.add(catalog);
}
catalogs.close();
// Save for later...
setCatalogs((Catalog[])catalogList.toArray(new Catalog[catalogList.size()]));
}
if (monitor!=null) monitor.worked(1);
if (monitor!=null && monitor.isCanceled()) return;
if (monitor!=null) monitor.subTask("Getting schema information");
if (dbInfo.supportsSchemas() && dbmd.supportsSchemasInTableDefinitions())
{
ArrayList schemaList = new ArrayList();
ResultSet schemas = null;
try
{
schemas = dbmd.getSchemas();
while (schemas!=null && schemas.next())
{
ArrayList schemaItems = new ArrayList();
String schemaName = schemas.getString(1);
ResultSet tables = null;
try
{
tables = dbmd.getTables(null, schemaName, null, null );
while (tables.next())
{
String table_name = tables.getString(3);
if (!db.isSystemTable(table_name))
{
schemaItems.add(table_name);
}
}
Collections.sort(schemaItems);
}
catch(Exception e)
{
// Obviously, we're not allowed to snoop around in this catalog.
// Just ignore it!
}
finally
{
if ( tables != null ) tables.close();
}
Schema schema = new Schema(schemaName, (String[])schemaItems.toArray(new String[schemaItems.size()]));
schemaList.add(schema);
}
}
finally
{
if ( schemas != null ) schemas.close();
}
// Save for later...
setSchemas((Schema[])schemaList.toArray(new Schema[schemaList.size()]));
}
if (monitor!=null) monitor.worked(1);
if (monitor!=null && monitor.isCanceled()) return;
if (monitor!=null) monitor.subTask("Getting tables");
setTables(db.getTablenames());
if (monitor!=null) monitor.worked(1);
if (monitor!=null && monitor.isCanceled()) return;
if (monitor!=null) monitor.subTask("Getting views");
if (dbInfo.supportsViews())
{
setViews(db.getViews());
}
if (monitor!=null) monitor.worked(1);
if (monitor!=null && monitor.isCanceled()) return;
if (monitor!=null) monitor.subTask("Getting synonyms");
if (dbInfo.supportsSynonyms())
{
setSynonyms(db.getSynonyms());
}
if (monitor!=null) monitor.worked(1);
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to retrieve database information because of an error", e);
}
finally
{
if (monitor!=null) monitor.subTask("Closing database connection");
db.disconnect();
if (monitor!=null) monitor.worked(1);
}
if (monitor!=null) monitor.done();
}
| public void getData(IProgressMonitor monitor) throws KettleDatabaseException
{
if (monitor!=null)
{
monitor.beginTask("Getting information from the database...", 8);
}
Database db = new Database(dbInfo);
try
{
if (monitor!=null) monitor.subTask("Connecting to database");
db.connect();
if (monitor!=null) monitor.worked(1);
if (monitor!=null && monitor.isCanceled()) return;
if (monitor!=null) monitor.subTask("Getting database metadata");
DatabaseMetaData dbmd = db.getDatabaseMetaData();
if (monitor!=null) monitor.worked(1);
if (monitor!=null && monitor.isCanceled()) return;
if (monitor!=null) monitor.subTask("Getting catalog information");
if (dbInfo.supportsCatalogs() && dbmd.supportsCatalogsInTableDefinitions())
{
ArrayList catalogList = new ArrayList();
ResultSet catalogs = dbmd.getCatalogs();
while (catalogs!=null && catalogs.next())
{
String catalogName = catalogs.getString(1);
ArrayList catalogItems = new ArrayList();
ResultSet tables = null;
try
{
tables = dbmd.getTables(catalogName, null, null, null );
while (tables.next())
{
String table_name = tables.getString(3);
if (!db.isSystemTable(table_name))
{
catalogItems.add(table_name);
}
}
}
catch(Exception e)
{
// Obviously, we're not allowed to snoop around in this catalog.
// Just ignore it!
}
finally
{
if ( tables != null ) tables.close();
}
Catalog catalog = new Catalog(catalogName, (String[])catalogItems.toArray(new String[catalogItems.size()]));
catalogList.add(catalog);
}
catalogs.close();
// Save for later...
setCatalogs((Catalog[])catalogList.toArray(new Catalog[catalogList.size()]));
}
if (monitor!=null) monitor.worked(1);
if (monitor!=null && monitor.isCanceled()) return;
if (monitor!=null) monitor.subTask("Getting schema information");
if (dbInfo.supportsSchemas() && dbmd.supportsSchemasInTableDefinitions())
{
ArrayList schemaList = new ArrayList();
ResultSet schemas = null;
try
{
schemas = dbmd.getSchemas();
while (schemas!=null && schemas.next())
{
ArrayList schemaItems = new ArrayList();
String schemaName = schemas.getString(1);
ResultSet tables = null;
try
{
tables = dbmd.getTables(null, schemaName, null, null );
while (tables.next())
{
String table_name = tables.getString(3);
if (!db.isSystemTable(table_name))
{
schemaItems.add(table_name);
}
}
Collections.sort(schemaItems);
}
catch(Exception e)
{
// Obviously, we're not allowed to snoop around in this catalog.
// Just ignore it!
}
finally
{
if ( tables != null ) tables.close();
}
Schema schema = new Schema(schemaName, (String[])schemaItems.toArray(new String[schemaItems.size()]));
schemaList.add(schema);
}
}
finally
{
if ( schemas != null ) schemas.close();
}
// Save for later...
setSchemas((Schema[])schemaList.toArray(new Schema[schemaList.size()]));
}
if (monitor!=null) monitor.worked(1);
if (monitor!=null && monitor.isCanceled()) return;
if (monitor!=null) monitor.subTask("Getting tables");
setTables(db.getTablenames());
if (monitor!=null) monitor.worked(1);
if (monitor!=null && monitor.isCanceled()) return;
if (monitor!=null) monitor.subTask("Getting views");
if (dbInfo.supportsViews())
{
setViews(db.getViews());
}
if (monitor!=null) monitor.worked(1);
if (monitor!=null && monitor.isCanceled()) return;
if (monitor!=null) monitor.subTask("Getting synonyms");
if (dbInfo.supportsSynonyms())
{
setSynonyms(db.getSynonyms());
}
if (monitor!=null) monitor.worked(1);
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to retrieve database information because of an error", e);
}
finally
{
if (monitor!=null) monitor.subTask("Closing database connection");
db.disconnect();
if (monitor!=null) monitor.worked(1);
}
if (monitor!=null) monitor.done();
}
|
diff --git a/plugins/org.eclipse.m2m.atl.emftvm/src/org/eclipse/m2m/atl/emftvm/impl/LocalVariableInstructionImpl.java b/plugins/org.eclipse.m2m.atl.emftvm/src/org/eclipse/m2m/atl/emftvm/impl/LocalVariableInstructionImpl.java
index 0d551a05..02a1d20c 100644
--- a/plugins/org.eclipse.m2m.atl.emftvm/src/org/eclipse/m2m/atl/emftvm/impl/LocalVariableInstructionImpl.java
+++ b/plugins/org.eclipse.m2m.atl.emftvm/src/org/eclipse/m2m/atl/emftvm/impl/LocalVariableInstructionImpl.java
@@ -1,426 +1,426 @@
/*******************************************************************************
* Copyright (c) 2011 Vrije Universiteit Brussel.
* 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:
* Dennis Wagelaar, Vrije Universiteit Brussel - initial API and
* implementation and/or initial documentation
*******************************************************************************/
package org.eclipse.m2m.atl.emftvm.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.m2m.atl.emftvm.CodeBlock;
import org.eclipse.m2m.atl.emftvm.EmftvmPackage;
import org.eclipse.m2m.atl.emftvm.LocalVariable;
import org.eclipse.m2m.atl.emftvm.LocalVariableInstruction;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Local Variable Instruction</b></em>'.
* @author <a href="mailto:[email protected]">Dennis Wagelaar</a>
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.eclipse.m2m.atl.emftvm.impl.LocalVariableInstructionImpl#getCbOffset <em>Cb Offset</em>}</li>
* <li>{@link org.eclipse.m2m.atl.emftvm.impl.LocalVariableInstructionImpl#getSlot <em>Slot</em>}</li>
* <li>{@link org.eclipse.m2m.atl.emftvm.impl.LocalVariableInstructionImpl#getLocalVariableIndex <em>Local Variable Index</em>}</li>
* <li>{@link org.eclipse.m2m.atl.emftvm.impl.LocalVariableInstructionImpl#getLocalVariable <em>Local Variable</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public abstract class LocalVariableInstructionImpl extends InstructionImpl implements LocalVariableInstruction {
/**
* The default value of the '{@link #getCbOffset() <em>Cb Offset</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCbOffset()
* @generated
* @ordered
*/
protected static final int CB_OFFSET_EDEFAULT = -1;
/**
* The default value of the '{@link #getSlot() <em>Slot</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSlot()
* @generated
* @ordered
*/
protected static final int SLOT_EDEFAULT = -1;
/**
* The default value of the '{@link #getLocalVariableIndex() <em>Local Variable Index</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLocalVariableIndex()
* @generated
* @ordered
*/
protected static final int LOCAL_VARIABLE_INDEX_EDEFAULT = -1;
/**
* The cached value of the '{@link #getCbOffset() <em>Cb Offset</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCbOffset()
* @generated NOT
* @ordered
*/
protected int cbOffset = CB_OFFSET_EDEFAULT;
/**
* The cached value of the '{@link #getLocalVariableIndex() <em>Local Variable Index</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLocalVariableIndex()
* @generated NOT
* @ordered
*/
protected int localVariableIndex = LOCAL_VARIABLE_INDEX_EDEFAULT;
/**
* The cached value of the '{@link #getSlot() <em>Slot</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSlot()
* @generated NOT
* @ordered
*/
protected int slot = SLOT_EDEFAULT;
/**
* The cached value of the '{@link #getLocalVariable() <em>Local Variable</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLocalVariable()
* @generated NOT
* @ordered
*/
protected LocalVariable localVariable;
/**
* <!-- begin-user-doc -->
* Creates a new {@link LocalVariableInstructionImpl}.
* <!-- end-user-doc -->
* @generated
*/
protected LocalVariableInstructionImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* Returns the {@link EClass} that correspond to this metaclass.
* @return the {@link EClass} that correspond to this metaclass.
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return EmftvmPackage.Literals.LOCAL_VARIABLE_INSTRUCTION;
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated NOT
*/
public int getCbOffset() {
if (cbOffset == CB_OFFSET_EDEFAULT) {
final LocalVariable lv = getLocalVariable();
if (lv != null) {
final CodeBlock lvBlock = lv.getOwningBlock();
if (lvBlock != null) {
CodeBlock cb = getOwningBlock();
int offset = 0;
while (cb != null && lvBlock != cb) {
cb = cb.getNestedFor();
offset++;
}
if (cb == lvBlock) {
cbOffset = offset;
} else {
throw new IllegalArgumentException(String.format(
"Referred local variable %s::%s not reachable from %s::%s",
lvBlock, lv, getOwningBlock(), this));
}
}
}
}
return cbOffset;
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated NOT
*/
public void setCbOffset(int newCbOffset) {
int oldCbOffset = cbOffset;
cbOffset = newCbOffset;
if (newCbOffset != CB_OFFSET_EDEFAULT) { // this value is normally derived
localVariable = null;
}
slot = SLOT_EDEFAULT;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, EmftvmPackage.LOCAL_VARIABLE_INSTRUCTION__CB_OFFSET, oldCbOffset, cbOffset));
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated NOT
*/
public int getSlot() {
if (slot == SLOT_EDEFAULT) {
final LocalVariable lv = getLocalVariable();
if (lv != null) {
slot = lv.getSlot();
}
}
return slot;
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated NOT
*/
public int getLocalVariableIndex() {
if (localVariableIndex == LOCAL_VARIABLE_INDEX_EDEFAULT) {
final LocalVariable lv = getLocalVariable();
if (lv != null) {
CodeBlock lvBlock = lv.getOwningBlock();
if (lvBlock != null) {
localVariableIndex = lvBlock.getLocalVariables().indexOf(lv);
assert localVariableIndex > -1;
}
}
}
return localVariableIndex;
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated NOT
*/
public void setLocalVariableIndex(int newLocalVariableIndex) {
int oldLocalVariableIndex = localVariableIndex;
localVariableIndex = newLocalVariableIndex;
if (newLocalVariableIndex != LOCAL_VARIABLE_INDEX_EDEFAULT) { // this value is normally derived
localVariable = null;
}
slot = SLOT_EDEFAULT;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, EmftvmPackage.LOCAL_VARIABLE_INSTRUCTION__LOCAL_VARIABLE_INDEX, oldLocalVariableIndex, localVariableIndex));
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated NOT
*/
public LocalVariable getLocalVariable() {
if (localVariable == null) {
if (cbOffset != CB_OFFSET_EDEFAULT && localVariableIndex != LOCAL_VARIABLE_INDEX_EDEFAULT) {
final CodeBlock cb = getOwningBlock();
if (cb != null) {
final int index = cb.getCode().indexOf(this);
assert index > -1;
CodeBlock lvBlock = cb;
for (int i = 0; i < cbOffset; i++) {
lvBlock = lvBlock.getNestedFor();
if (lvBlock == null) {
throw new IllegalArgumentException(String.format(
"Code block of referred local variable at (cbOffset = %d, index = %d) not found for %s::%s",
- cbOffset, localVariableIndex, cb, this));
+ cbOffset, localVariableIndex, cb, super.toString()));
}
}
localVariable = lvBlock.getLocalVariables().get(localVariableIndex);
if (localVariable == null) {
throw new IllegalArgumentException(String.format(
"Referred local variable at (cbOffset = %d, index = %d) not found for %s::%s",
- cbOffset, localVariableIndex, cb, this));
+ cbOffset, localVariableIndex, cb, super.toString()));
}
}
}
}
if (localVariable != null && localVariable.eIsProxy()) {
InternalEObject oldLocalVariable = (InternalEObject)localVariable;
localVariable = (LocalVariable)eResolveProxy(oldLocalVariable);
if (localVariable != oldLocalVariable) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, EmftvmPackage.LOCAL_VARIABLE_INSTRUCTION__LOCAL_VARIABLE, oldLocalVariable, localVariable));
}
}
return localVariable;
}
/**
* <!-- begin-user-doc. -->
* @see #getLocalVariable()
* <!-- end-user-doc -->
* @generated NOT
*/
public LocalVariable basicGetLocalVariable() {
if (localVariable == null) {
if (cbOffset != CB_OFFSET_EDEFAULT && localVariableIndex != LOCAL_VARIABLE_INDEX_EDEFAULT) {
final CodeBlock cb = getOwningBlock();
if (cb != null) {
final int index = cb.getCode().indexOf(this);
assert index > -1;
CodeBlock lvBlock = cb;
for (int i = 0; i < cbOffset; i++) {
lvBlock = lvBlock.getNestedFor();
if (lvBlock == null) {
throw new IllegalArgumentException(String.format(
"Code block of referred local variable at (cbOffset = %d, index = %d) not found for %s::%s",
cbOffset, localVariableIndex, cb, this));
}
}
localVariable = lvBlock.getLocalVariables().get(localVariableIndex);
if (localVariable == null) {
throw new IllegalArgumentException(String.format(
"Referred local variable at (cbOffset = %d, index = %d) not found for %s::%s",
cbOffset, localVariableIndex, cb, this));
}
}
}
}
return localVariable;
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated NOT
*/
public void setLocalVariable(LocalVariable newLocalVariable) {
LocalVariable oldLocalVariable = localVariable;
localVariable = newLocalVariable;
cbOffset = CB_OFFSET_EDEFAULT;
localVariableIndex = LOCAL_VARIABLE_INDEX_EDEFAULT;
slot = SLOT_EDEFAULT;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, EmftvmPackage.LOCAL_VARIABLE_INSTRUCTION__LOCAL_VARIABLE, oldLocalVariable, localVariable));
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case EmftvmPackage.LOCAL_VARIABLE_INSTRUCTION__CB_OFFSET:
return getCbOffset();
case EmftvmPackage.LOCAL_VARIABLE_INSTRUCTION__SLOT:
return getSlot();
case EmftvmPackage.LOCAL_VARIABLE_INSTRUCTION__LOCAL_VARIABLE_INDEX:
return getLocalVariableIndex();
case EmftvmPackage.LOCAL_VARIABLE_INSTRUCTION__LOCAL_VARIABLE:
if (resolve) return getLocalVariable();
return basicGetLocalVariable();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case EmftvmPackage.LOCAL_VARIABLE_INSTRUCTION__CB_OFFSET:
setCbOffset((Integer)newValue);
return;
case EmftvmPackage.LOCAL_VARIABLE_INSTRUCTION__LOCAL_VARIABLE_INDEX:
setLocalVariableIndex((Integer)newValue);
return;
case EmftvmPackage.LOCAL_VARIABLE_INSTRUCTION__LOCAL_VARIABLE:
setLocalVariable((LocalVariable)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case EmftvmPackage.LOCAL_VARIABLE_INSTRUCTION__CB_OFFSET:
setCbOffset(CB_OFFSET_EDEFAULT);
return;
case EmftvmPackage.LOCAL_VARIABLE_INSTRUCTION__LOCAL_VARIABLE_INDEX:
setLocalVariableIndex(LOCAL_VARIABLE_INDEX_EDEFAULT);
return;
case EmftvmPackage.LOCAL_VARIABLE_INSTRUCTION__LOCAL_VARIABLE:
setLocalVariable((LocalVariable)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case EmftvmPackage.LOCAL_VARIABLE_INSTRUCTION__CB_OFFSET:
return getCbOffset() != CB_OFFSET_EDEFAULT;
case EmftvmPackage.LOCAL_VARIABLE_INSTRUCTION__SLOT:
return getSlot() != SLOT_EDEFAULT;
case EmftvmPackage.LOCAL_VARIABLE_INSTRUCTION__LOCAL_VARIABLE_INDEX:
return getLocalVariableIndex() != LOCAL_VARIABLE_INDEX_EDEFAULT;
case EmftvmPackage.LOCAL_VARIABLE_INSTRUCTION__LOCAL_VARIABLE:
return basicGetLocalVariable() != null;
}
return super.eIsSet(featureID);
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(' ');
result.append(getCbOffset());
result.append(", ");
result.append(getSlot());
result.append(" (");
result.append(getLocalVariable());
result.append(')');
return result.toString();
}
} //LocalVariableInstructionImpl
| false | true | public LocalVariable getLocalVariable() {
if (localVariable == null) {
if (cbOffset != CB_OFFSET_EDEFAULT && localVariableIndex != LOCAL_VARIABLE_INDEX_EDEFAULT) {
final CodeBlock cb = getOwningBlock();
if (cb != null) {
final int index = cb.getCode().indexOf(this);
assert index > -1;
CodeBlock lvBlock = cb;
for (int i = 0; i < cbOffset; i++) {
lvBlock = lvBlock.getNestedFor();
if (lvBlock == null) {
throw new IllegalArgumentException(String.format(
"Code block of referred local variable at (cbOffset = %d, index = %d) not found for %s::%s",
cbOffset, localVariableIndex, cb, this));
}
}
localVariable = lvBlock.getLocalVariables().get(localVariableIndex);
if (localVariable == null) {
throw new IllegalArgumentException(String.format(
"Referred local variable at (cbOffset = %d, index = %d) not found for %s::%s",
cbOffset, localVariableIndex, cb, this));
}
}
}
}
if (localVariable != null && localVariable.eIsProxy()) {
InternalEObject oldLocalVariable = (InternalEObject)localVariable;
localVariable = (LocalVariable)eResolveProxy(oldLocalVariable);
if (localVariable != oldLocalVariable) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, EmftvmPackage.LOCAL_VARIABLE_INSTRUCTION__LOCAL_VARIABLE, oldLocalVariable, localVariable));
}
}
return localVariable;
}
| public LocalVariable getLocalVariable() {
if (localVariable == null) {
if (cbOffset != CB_OFFSET_EDEFAULT && localVariableIndex != LOCAL_VARIABLE_INDEX_EDEFAULT) {
final CodeBlock cb = getOwningBlock();
if (cb != null) {
final int index = cb.getCode().indexOf(this);
assert index > -1;
CodeBlock lvBlock = cb;
for (int i = 0; i < cbOffset; i++) {
lvBlock = lvBlock.getNestedFor();
if (lvBlock == null) {
throw new IllegalArgumentException(String.format(
"Code block of referred local variable at (cbOffset = %d, index = %d) not found for %s::%s",
cbOffset, localVariableIndex, cb, super.toString()));
}
}
localVariable = lvBlock.getLocalVariables().get(localVariableIndex);
if (localVariable == null) {
throw new IllegalArgumentException(String.format(
"Referred local variable at (cbOffset = %d, index = %d) not found for %s::%s",
cbOffset, localVariableIndex, cb, super.toString()));
}
}
}
}
if (localVariable != null && localVariable.eIsProxy()) {
InternalEObject oldLocalVariable = (InternalEObject)localVariable;
localVariable = (LocalVariable)eResolveProxy(oldLocalVariable);
if (localVariable != oldLocalVariable) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, EmftvmPackage.LOCAL_VARIABLE_INSTRUCTION__LOCAL_VARIABLE, oldLocalVariable, localVariable));
}
}
return localVariable;
}
|
diff --git a/chapter03/http/src/test/java/com/muleinaction/HttpPollingFunctionalTestCase.java b/chapter03/http/src/test/java/com/muleinaction/HttpPollingFunctionalTestCase.java
index 66e4282..b2fe1f5 100644
--- a/chapter03/http/src/test/java/com/muleinaction/HttpPollingFunctionalTestCase.java
+++ b/chapter03/http/src/test/java/com/muleinaction/HttpPollingFunctionalTestCase.java
@@ -1,60 +1,59 @@
package com.muleinaction;
import org.mule.api.service.Service;
import org.mule.api.context.notification.EndpointMessageNotificationListener;
import org.mule.api.context.notification.ServerNotification;
import org.mule.tck.FunctionalTestCase;
import org.mule.context.notification.EndpointMessageNotification;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import java.io.File;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* @author John D'Emic ([email protected])
*/
public class HttpPollingFunctionalTestCase extends FunctionalTestCase {
private static String DEST_DIRECTORY = "./data/polling";
private CountDownLatch latch = new CountDownLatch(1);
protected void doSetUp() throws Exception {
super.doSetUp();
- FileUtils.cleanDirectory(new File(DEST_DIRECTORY));
for (Object o : FileUtils.listFiles(new File(DEST_DIRECTORY), new String[]{"html"}, false)) {
File file = (File) o;
file.delete();
}
muleContext.registerListener(new EndpointMessageNotificationListener() {
public void onNotification(final ServerNotification notification) {
if ("httpPollingService".equals(notification.getResourceIdentifier())) {
final EndpointMessageNotification messageNotification = (EndpointMessageNotification) notification;
if (messageNotification.getEndpoint().getName().equals("endpoint.file.data.polling")) {
latch.countDown();
}
}
}
});
}
@Override
protected String getConfigResources() {
return "conf/http-polling-config.xml";
}
public void testCorrectlyInitialized() throws Exception {
final Service service = muleContext.getRegistry().lookupService(
"httpPollingService");
assertNotNull(service);
assertEquals("httpPollingModel", service.getModel().getName());
assertTrue("Message did not reach directory on time", latch.await(15, TimeUnit.SECONDS));
assertEquals(1, FileUtils.listFiles(new File(DEST_DIRECTORY), new WildcardFileFilter("*.*"), null).size());
}
}
| true | true | protected void doSetUp() throws Exception {
super.doSetUp();
FileUtils.cleanDirectory(new File(DEST_DIRECTORY));
for (Object o : FileUtils.listFiles(new File(DEST_DIRECTORY), new String[]{"html"}, false)) {
File file = (File) o;
file.delete();
}
muleContext.registerListener(new EndpointMessageNotificationListener() {
public void onNotification(final ServerNotification notification) {
if ("httpPollingService".equals(notification.getResourceIdentifier())) {
final EndpointMessageNotification messageNotification = (EndpointMessageNotification) notification;
if (messageNotification.getEndpoint().getName().equals("endpoint.file.data.polling")) {
latch.countDown();
}
}
}
});
}
| protected void doSetUp() throws Exception {
super.doSetUp();
for (Object o : FileUtils.listFiles(new File(DEST_DIRECTORY), new String[]{"html"}, false)) {
File file = (File) o;
file.delete();
}
muleContext.registerListener(new EndpointMessageNotificationListener() {
public void onNotification(final ServerNotification notification) {
if ("httpPollingService".equals(notification.getResourceIdentifier())) {
final EndpointMessageNotification messageNotification = (EndpointMessageNotification) notification;
if (messageNotification.getEndpoint().getName().equals("endpoint.file.data.polling")) {
latch.countDown();
}
}
}
});
}
|
diff --git a/src/kg/apc/jmeter/gui/CopyRowAction.java b/src/kg/apc/jmeter/gui/CopyRowAction.java
index 6f912494..569249ba 100644
--- a/src/kg/apc/jmeter/gui/CopyRowAction.java
+++ b/src/kg/apc/jmeter/gui/CopyRowAction.java
@@ -1,52 +1,52 @@
package kg.apc.jmeter.gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import org.apache.jmeter.gui.util.PowerTableModel;
/**
*
* @author undera
*/
public class CopyRowAction
implements ActionListener {
private JTable grid;
private PowerTableModel tableModel;
private JButton deleteRowButton;
private JComponent sender;
public CopyRowAction(JComponent aSender, JTable grid, PowerTableModel tableModel, JButton deleteRowButton) {
this.grid = grid;
this.tableModel = tableModel;
this.deleteRowButton = deleteRowButton;
this.sender = aSender;
}
public void actionPerformed(ActionEvent e) {
if (grid.isEditing()) {
TableCellEditor cellEditor = grid.getCellEditor(grid.getEditingRow(), grid.getEditingColumn());
cellEditor.stopCellEditing();
}
final int selectedRow = grid.getSelectedRow();
if (tableModel.getRowCount() == 0 || selectedRow < 0) {
return;
}
tableModel.addRow(tableModel.getRowData(selectedRow));
tableModel.fireTableDataChanged();
// Enable DELETE (which may already be enabled, but it won't hurt)
deleteRowButton.setEnabled(true);
// Highlight (select) the appropriate row.
- int rowToSelect = selectedRow + 1;
+ int rowToSelect = tableModel.getRowCount() - 1;
grid.setRowSelectionInterval(rowToSelect, rowToSelect);
sender.updateUI();
}
}
| true | true | public void actionPerformed(ActionEvent e) {
if (grid.isEditing()) {
TableCellEditor cellEditor = grid.getCellEditor(grid.getEditingRow(), grid.getEditingColumn());
cellEditor.stopCellEditing();
}
final int selectedRow = grid.getSelectedRow();
if (tableModel.getRowCount() == 0 || selectedRow < 0) {
return;
}
tableModel.addRow(tableModel.getRowData(selectedRow));
tableModel.fireTableDataChanged();
// Enable DELETE (which may already be enabled, but it won't hurt)
deleteRowButton.setEnabled(true);
// Highlight (select) the appropriate row.
int rowToSelect = selectedRow + 1;
grid.setRowSelectionInterval(rowToSelect, rowToSelect);
sender.updateUI();
}
| public void actionPerformed(ActionEvent e) {
if (grid.isEditing()) {
TableCellEditor cellEditor = grid.getCellEditor(grid.getEditingRow(), grid.getEditingColumn());
cellEditor.stopCellEditing();
}
final int selectedRow = grid.getSelectedRow();
if (tableModel.getRowCount() == 0 || selectedRow < 0) {
return;
}
tableModel.addRow(tableModel.getRowData(selectedRow));
tableModel.fireTableDataChanged();
// Enable DELETE (which may already be enabled, but it won't hurt)
deleteRowButton.setEnabled(true);
// Highlight (select) the appropriate row.
int rowToSelect = tableModel.getRowCount() - 1;
grid.setRowSelectionInterval(rowToSelect, rowToSelect);
sender.updateUI();
}
|
diff --git a/src/minecraft/kaijin/InventoryStocker/BlockInventoryStocker.java b/src/minecraft/kaijin/InventoryStocker/BlockInventoryStocker.java
index 82b923f..ec8fe51 100644
--- a/src/minecraft/kaijin/InventoryStocker/BlockInventoryStocker.java
+++ b/src/minecraft/kaijin/InventoryStocker/BlockInventoryStocker.java
@@ -1,134 +1,134 @@
package kaijin.InventoryStocker;
import net.minecraft.src.forge.*;
import java.util.*;
import net.minecraft.src.*;
import net.minecraft.src.mod_InventoryStocker.*;
import kaijin.InventoryStocker.*;
public class BlockInventoryStocker extends BlockContainer implements ITextureProvider
{
public BlockInventoryStocker(int i, int j)
{
super(i, j, Material.iron);
}
public void addCreativeItems(ArrayList itemList)
{
itemList.add(new ItemStack(this));
}
public String getTextureFile()
{
return "/kaijin/InventoryStocker/terrain.png";
}
public int getBlockTextureFromSide(int i)
{
// Needs to call tile entity to determine correct facing and animation state?
switch (i)
{
case 0: // Bottom
return 16;
case 1: // Top
return 16;
case 2: // North/South
return 1;
case 3: // North/South
return 0;
default: // 4-5 East/West
return 19;
}
}
public int getBlockTextureFromSideAndMetadata(int i, int m)
{
int dir = m & 7;
if (dir == i)
{
// front face
return 1;
}
if (dir <= 1) // Up or down
{
if (i >= 4)
{
- return 18; // Side face
+ return 16; // Side face
}
if (i >= 2)
{
- return 16; // Top/bottom face
+ return 16; // Top/bottom face (as sides, so using 16 instead of 18 for now)
}
return 0; // Back face
}
if (i <= 1)
{
- return 16; // Horizontal, top or bottom face
+ return 18; // Horizontal, top or bottom face
}
- if (dir == 2 || dir == 4)
+ if (dir <= 3)
{
- if (i == 3 || i == 5)
+ if (i == 4 || i == 5)
{
- return 18; // Side face
+ return 16; // Side face
}
}
else
{
- if (i == 2 || i == 4)
+ if (i == 2 || i == 3)
{
- return 18; // Side face
+ return 16; // Side face
}
}
return 0; // Back face
}
private int determineOrientation(World world, int x, int y, int z, EntityPlayer player)
{
if (player.rotationPitch > 45D)
{
return 1;
}
if (player.rotationPitch < -45D)
{
return 0;
}
int dir = MathHelper.floor_double((double)(player.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3;
return dir == 0 ? 2 : (dir == 1 ? 5 : (dir == 2 ? 3 : (dir == 3 ? 4 : 0)));
}
public void onBlockPlacedBy(World world, int x, int y, int z, EntityLiving par5EntityLiving)
{
int dir = determineOrientation(world, x, y, z, (EntityPlayer)par5EntityLiving);
world.setBlockMetadataWithNotify(x, y, z, dir);
}
@Override
public boolean blockActivated(World world, int x, int y, int z, EntityPlayer entityplayer)
{
if (!Utils.isClient(world))
{
entityplayer.openGui(mod_InventoryStocker.instance, 1, world, x, y, z);
}
return true;
}
@Override
public TileEntity getBlockEntity()
{
return new TileEntityInventoryStocker();
}
public void onBlockPlaced(World world, int x, int y, int z, int facing)
{
// TileEntity tile = world.getBlockTileEntity(x, y, z);
};
public void onBlockRemoval(World world, int x, int y, int z)
{
Utils.preDestroyBlock(world, x, y, z);
super.onBlockRemoval(world, x, y, z);
}
}
| false | true | public int getBlockTextureFromSideAndMetadata(int i, int m)
{
int dir = m & 7;
if (dir == i)
{
// front face
return 1;
}
if (dir <= 1) // Up or down
{
if (i >= 4)
{
return 18; // Side face
}
if (i >= 2)
{
return 16; // Top/bottom face
}
return 0; // Back face
}
if (i <= 1)
{
return 16; // Horizontal, top or bottom face
}
if (dir == 2 || dir == 4)
{
if (i == 3 || i == 5)
{
return 18; // Side face
}
}
else
{
if (i == 2 || i == 4)
{
return 18; // Side face
}
}
return 0; // Back face
}
| public int getBlockTextureFromSideAndMetadata(int i, int m)
{
int dir = m & 7;
if (dir == i)
{
// front face
return 1;
}
if (dir <= 1) // Up or down
{
if (i >= 4)
{
return 16; // Side face
}
if (i >= 2)
{
return 16; // Top/bottom face (as sides, so using 16 instead of 18 for now)
}
return 0; // Back face
}
if (i <= 1)
{
return 18; // Horizontal, top or bottom face
}
if (dir <= 3)
{
if (i == 4 || i == 5)
{
return 16; // Side face
}
}
else
{
if (i == 2 || i == 3)
{
return 16; // Side face
}
}
return 0; // Back face
}
|
diff --git a/tests/org.eclipse.graphiti.testtool.sketch/src/org/eclipse/graphiti/testtool/sketch/features/SketchResizeShapeFeature.java b/tests/org.eclipse.graphiti.testtool.sketch/src/org/eclipse/graphiti/testtool/sketch/features/SketchResizeShapeFeature.java
index 07be0d0b..e93ac0e2 100644
--- a/tests/org.eclipse.graphiti.testtool.sketch/src/org/eclipse/graphiti/testtool/sketch/features/SketchResizeShapeFeature.java
+++ b/tests/org.eclipse.graphiti.testtool.sketch/src/org/eclipse/graphiti/testtool/sketch/features/SketchResizeShapeFeature.java
@@ -1,31 +1,31 @@
package org.eclipse.graphiti.testtool.sketch.features;
import org.eclipse.graphiti.features.DefaultResizeConfiguration;
import org.eclipse.graphiti.features.IFeatureProvider;
import org.eclipse.graphiti.features.IResizeConfiguration;
import org.eclipse.graphiti.features.context.IResizeShapeContext;
import org.eclipse.graphiti.features.impl.DefaultResizeShapeFeature;
public class SketchResizeShapeFeature extends DefaultResizeShapeFeature {
private static final boolean RANDOM_CAN_RESIZE = false;
public SketchResizeShapeFeature(IFeatureProvider fp) {
super(fp);
}
@Override
public boolean canResizeShape(IResizeShapeContext context) {
return RANDOM_CAN_RESIZE ? Math.random() > 0.5 : super.canResizeShape(context);
}
@Override
- public IResizeConfiguration getResizeConfiguration() {
+ public IResizeConfiguration getResizeConfiguration(IResizeShapeContext context) {
return new DefaultResizeConfiguration() {
@Override
- public boolean isHorizantalResizeAllowed() {
+ public boolean isHorizontalResizeAllowed() {
return false;
}
};
}
}
| false | true | public IResizeConfiguration getResizeConfiguration() {
return new DefaultResizeConfiguration() {
@Override
public boolean isHorizantalResizeAllowed() {
return false;
}
};
}
| public IResizeConfiguration getResizeConfiguration(IResizeShapeContext context) {
return new DefaultResizeConfiguration() {
@Override
public boolean isHorizontalResizeAllowed() {
return false;
}
};
}
|
diff --git a/src/com/nexus/webserver/WebServer.java b/src/com/nexus/webserver/WebServer.java
index f3af486..0c64187 100644
--- a/src/com/nexus/webserver/WebServer.java
+++ b/src/com/nexus/webserver/WebServer.java
@@ -1,135 +1,135 @@
package com.nexus.webserver;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Logger;
import com.nexus.logging.NexusFormattedLogger;
import com.nexus.main.EnumShutdownCause;
import com.nexus.main.ShutdownManager;
public class WebServer implements Runnable{
private boolean IsRunning = false;
private final InetSocketAddress Address;
public static Logger Log = NexusFormattedLogger.getLogger("WebServer");
private ServerSocket Socket;
private ServerSocketChannel SocketChannel;
private Selector SocketSelector;
private Thread WebserverThread;
public WebServer(InetSocketAddress Address){
this.Address = Address;
}
//@SuppressWarnings("resource")
@Override
public void run(){
WebServer.Log.info("Server starting...");
try{
SocketChannel = ServerSocketChannel.open();
SocketChannel.configureBlocking(false);
Socket = this.SocketChannel.socket();
Socket.bind(this.Address);
SocketSelector = Selector.open();
SocketChannel.register(SocketSelector, SocketChannel.validOps());
}catch (IOException e){
WebServer.Log.severe("Could not listen on port " + this.Address.getPort() + "!");
return;
}
WebServer.Log.info("Server started!");
while(IsRunning){
SelectionKey Key = null;
try{
SocketSelector.select();
Set<SelectionKey> keys = SocketSelector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while(i.hasNext()){
Key = i.next();
i.remove();
if(!Key.isValid()){
continue;
}
try{
if(Key.isAcceptable()){
SocketChannel Channel = SocketChannel.accept();
Channel.configureBlocking(false);
Channel.register(SocketSelector, SelectionKey.OP_READ);
}else if(Key.isReadable()){
/*SocketChannel Channel = (SocketChannel) Key.channel();
WebServerSession Session = (WebServerSession) Key.attachment();
if(Session == null){
Session = new WebServerSession(Channel);
Key.attach(Session);
}
Session.readData();
WebServer.Log.fine("Connected by " + Channel.getRemoteAddress().toString().substring(1).split(":")[0] + ".");
WebServerClientThread.LaunchNewThread(Session);*/
SocketChannel Channel = (SocketChannel) Key.channel();
WebServerSession Session = (WebServerSession) Key.attachment();
if(Session == null){
Session = new WebServerSession(Channel);
Key.attach(Session);
}
- WebServer.Log.finest("Connected by " + Channel.getRemoteAddress().toString().substring(1).split(":")[0] + ".");
+ WebServer.Log.finest("Connected by " + Channel.socket().getInetAddress().toString().split("/")[1] + ".");
Session.readData();
while(Session.readLine() != null){}
WebServerClientThread.LaunchNewThread(Session);
}
}catch(Exception e){
if(Key.attachment() instanceof WebServerSession){
((WebServerSession) Key.attachment()).Close();
}
}
}
}catch(IOException e){
WebServer.Log.severe("Error while accepting connections.");
e.printStackTrace();
this.IsRunning = false;
ShutdownManager.ShutdownServer(EnumShutdownCause.CRASH);
}
}
try{
this.Socket.close();
this.SocketSelector.close();
this.SocketChannel.close();
}catch(IOException e){}
}
public void Start(){
this.WebserverThread = new Thread(this);
this.WebserverThread.setName("WebServerListener");
this.IsRunning = true;
this.WebserverThread.start();
}
public void Stop(){
this.IsRunning = false;
try{
this.Socket.close();
this.SocketSelector.close();
this.SocketChannel.close();
}catch(IOException e){
}
}
}
| true | true | public void run(){
WebServer.Log.info("Server starting...");
try{
SocketChannel = ServerSocketChannel.open();
SocketChannel.configureBlocking(false);
Socket = this.SocketChannel.socket();
Socket.bind(this.Address);
SocketSelector = Selector.open();
SocketChannel.register(SocketSelector, SocketChannel.validOps());
}catch (IOException e){
WebServer.Log.severe("Could not listen on port " + this.Address.getPort() + "!");
return;
}
WebServer.Log.info("Server started!");
while(IsRunning){
SelectionKey Key = null;
try{
SocketSelector.select();
Set<SelectionKey> keys = SocketSelector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while(i.hasNext()){
Key = i.next();
i.remove();
if(!Key.isValid()){
continue;
}
try{
if(Key.isAcceptable()){
SocketChannel Channel = SocketChannel.accept();
Channel.configureBlocking(false);
Channel.register(SocketSelector, SelectionKey.OP_READ);
}else if(Key.isReadable()){
/*SocketChannel Channel = (SocketChannel) Key.channel();
WebServerSession Session = (WebServerSession) Key.attachment();
if(Session == null){
Session = new WebServerSession(Channel);
Key.attach(Session);
}
Session.readData();
WebServer.Log.fine("Connected by " + Channel.getRemoteAddress().toString().substring(1).split(":")[0] + ".");
WebServerClientThread.LaunchNewThread(Session);*/
SocketChannel Channel = (SocketChannel) Key.channel();
WebServerSession Session = (WebServerSession) Key.attachment();
if(Session == null){
Session = new WebServerSession(Channel);
Key.attach(Session);
}
WebServer.Log.finest("Connected by " + Channel.getRemoteAddress().toString().substring(1).split(":")[0] + ".");
Session.readData();
while(Session.readLine() != null){}
WebServerClientThread.LaunchNewThread(Session);
}
}catch(Exception e){
if(Key.attachment() instanceof WebServerSession){
((WebServerSession) Key.attachment()).Close();
}
}
}
}catch(IOException e){
WebServer.Log.severe("Error while accepting connections.");
e.printStackTrace();
this.IsRunning = false;
ShutdownManager.ShutdownServer(EnumShutdownCause.CRASH);
}
}
try{
this.Socket.close();
this.SocketSelector.close();
this.SocketChannel.close();
}catch(IOException e){}
}
| public void run(){
WebServer.Log.info("Server starting...");
try{
SocketChannel = ServerSocketChannel.open();
SocketChannel.configureBlocking(false);
Socket = this.SocketChannel.socket();
Socket.bind(this.Address);
SocketSelector = Selector.open();
SocketChannel.register(SocketSelector, SocketChannel.validOps());
}catch (IOException e){
WebServer.Log.severe("Could not listen on port " + this.Address.getPort() + "!");
return;
}
WebServer.Log.info("Server started!");
while(IsRunning){
SelectionKey Key = null;
try{
SocketSelector.select();
Set<SelectionKey> keys = SocketSelector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while(i.hasNext()){
Key = i.next();
i.remove();
if(!Key.isValid()){
continue;
}
try{
if(Key.isAcceptable()){
SocketChannel Channel = SocketChannel.accept();
Channel.configureBlocking(false);
Channel.register(SocketSelector, SelectionKey.OP_READ);
}else if(Key.isReadable()){
/*SocketChannel Channel = (SocketChannel) Key.channel();
WebServerSession Session = (WebServerSession) Key.attachment();
if(Session == null){
Session = new WebServerSession(Channel);
Key.attach(Session);
}
Session.readData();
WebServer.Log.fine("Connected by " + Channel.getRemoteAddress().toString().substring(1).split(":")[0] + ".");
WebServerClientThread.LaunchNewThread(Session);*/
SocketChannel Channel = (SocketChannel) Key.channel();
WebServerSession Session = (WebServerSession) Key.attachment();
if(Session == null){
Session = new WebServerSession(Channel);
Key.attach(Session);
}
WebServer.Log.finest("Connected by " + Channel.socket().getInetAddress().toString().split("/")[1] + ".");
Session.readData();
while(Session.readLine() != null){}
WebServerClientThread.LaunchNewThread(Session);
}
}catch(Exception e){
if(Key.attachment() instanceof WebServerSession){
((WebServerSession) Key.attachment()).Close();
}
}
}
}catch(IOException e){
WebServer.Log.severe("Error while accepting connections.");
e.printStackTrace();
this.IsRunning = false;
ShutdownManager.ShutdownServer(EnumShutdownCause.CRASH);
}
}
try{
this.Socket.close();
this.SocketSelector.close();
this.SocketChannel.close();
}catch(IOException e){}
}
|
diff --git a/src/main/java/de/hd/cl/haas/distributedcrawl/map/IndexerMap.java b/src/main/java/de/hd/cl/haas/distributedcrawl/map/IndexerMap.java
index 5cddf4c..49aca78 100644
--- a/src/main/java/de/hd/cl/haas/distributedcrawl/map/IndexerMap.java
+++ b/src/main/java/de/hd/cl/haas/distributedcrawl/map/IndexerMap.java
@@ -1,86 +1,88 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.hd.cl.haas.distributedcrawl.map;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import net.htmlparser.jericho.Source;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
/**
*
*
* @author Michael Haas
*/
public class IndexerMap extends Mapper<LongWritable, Text, Text, String[]> {
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
System.out.println("key is " + key.toString());
System.out.println("value is " + value.toString());
URL url = new URL(value.toString());
url.openConnection();
InputStream stream = url.openStream();
Source source = new Source(stream);
source.fullSequentialParse();
String completeContent = source.getTextExtractor().toString();
System.out.println("CompleteContent: ");
System.out.println(completeContent);
// poor man's tokenizer
String[] tokens = completeContent.split(" ");
// count absolute frequencies for terms
HashMap<String, Integer> counts = new HashMap<String, Integer>();
for (int ii = 0; ii < tokens.length; ii++) {
String term = tokens[ii];
if (!counts.containsKey(term)) {
counts.put(term, 0);
}
- counts.put(term, counts.get(key) + 1);
+ counts.put(term, counts.get(term) + 1);
}
+ Text tTerm = new Text();
for (String term : counts.keySet()) {
// Emit(term t, posting <n,H{t}>)
String[] compositeValue = {value.toString(), counts.get(term).toString()};
System.out.println("Out-key: " + term);
System.out.println("Out-value: " + compositeValue);
// TODO: is compositeValue properly serialized?
- context.write(new Text(term), compositeValue);
+ tTerm.set(term);
+ context.write(tTerm, compositeValue);
}
}
public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
Configuration conf = new Configuration();
Job job = new Job(conf, "IndexerMap");
//job.setOutputKeyClass(Text.class);
//job.setOutputValueClass(IntWritable.class);
job.setJarByClass(IndexerMap.class);
job.setMapperClass(IndexerMap.class);
//job.setReducerClass(Reduce.class);
// TextInputFormat: key is offset in file, value is line
job.setInputFormatClass(TextInputFormat.class);
//job.setOutputFormatClass(TextOutputFormat.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.waitForCompletion(true);
}
}
| false | true | protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
System.out.println("key is " + key.toString());
System.out.println("value is " + value.toString());
URL url = new URL(value.toString());
url.openConnection();
InputStream stream = url.openStream();
Source source = new Source(stream);
source.fullSequentialParse();
String completeContent = source.getTextExtractor().toString();
System.out.println("CompleteContent: ");
System.out.println(completeContent);
// poor man's tokenizer
String[] tokens = completeContent.split(" ");
// count absolute frequencies for terms
HashMap<String, Integer> counts = new HashMap<String, Integer>();
for (int ii = 0; ii < tokens.length; ii++) {
String term = tokens[ii];
if (!counts.containsKey(term)) {
counts.put(term, 0);
}
counts.put(term, counts.get(key) + 1);
}
for (String term : counts.keySet()) {
// Emit(term t, posting <n,H{t}>)
String[] compositeValue = {value.toString(), counts.get(term).toString()};
System.out.println("Out-key: " + term);
System.out.println("Out-value: " + compositeValue);
// TODO: is compositeValue properly serialized?
context.write(new Text(term), compositeValue);
}
}
| protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
System.out.println("key is " + key.toString());
System.out.println("value is " + value.toString());
URL url = new URL(value.toString());
url.openConnection();
InputStream stream = url.openStream();
Source source = new Source(stream);
source.fullSequentialParse();
String completeContent = source.getTextExtractor().toString();
System.out.println("CompleteContent: ");
System.out.println(completeContent);
// poor man's tokenizer
String[] tokens = completeContent.split(" ");
// count absolute frequencies for terms
HashMap<String, Integer> counts = new HashMap<String, Integer>();
for (int ii = 0; ii < tokens.length; ii++) {
String term = tokens[ii];
if (!counts.containsKey(term)) {
counts.put(term, 0);
}
counts.put(term, counts.get(term) + 1);
}
Text tTerm = new Text();
for (String term : counts.keySet()) {
// Emit(term t, posting <n,H{t}>)
String[] compositeValue = {value.toString(), counts.get(term).toString()};
System.out.println("Out-key: " + term);
System.out.println("Out-value: " + compositeValue);
// TODO: is compositeValue properly serialized?
tTerm.set(term);
context.write(tTerm, compositeValue);
}
}
|
diff --git a/src/com/fsck/k9/view/MessageWebView.java b/src/com/fsck/k9/view/MessageWebView.java
index 6ec7f50b..e81016df 100644
--- a/src/com/fsck/k9/view/MessageWebView.java
+++ b/src/com/fsck/k9/view/MessageWebView.java
@@ -1,154 +1,160 @@
package com.fsck.k9.view;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;
import com.fsck.k9.K9;
import com.fsck.k9.R;
import java.lang.reflect.Method;
public class MessageWebView extends WebView {
/**
* We use WebSettings.getBlockNetworkLoads() to prevent the WebView that displays email
* bodies from loading external resources over the network. Unfortunately this method
* isn't exposed via the official Android API. That's why we use reflection to be able
* to call the method.
*/
public static final Method mGetBlockNetworkLoads = K9.getMethod(WebSettings.class, "setBlockNetworkLoads");
public MessageWebView(Context context) {
super(context);
}
public MessageWebView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MessageWebView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* Configure a web view to load or not load network data. A <b>true</b> setting here means that
* network data will be blocked.
* @param shouldBlockNetworkData True if network data should be blocked, false to allow network data.
*/
public void blockNetworkData(final boolean shouldBlockNetworkData) {
// Sanity check to make sure we don't blow up.
if (getSettings() == null) {
return;
}
// Block network loads.
if (mGetBlockNetworkLoads != null) {
try {
mGetBlockNetworkLoads.invoke(getSettings(), shouldBlockNetworkData);
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Error on invoking WebSettings.setBlockNetworkLoads()", e);
}
}
// Block network images.
getSettings().setBlockNetworkImage(shouldBlockNetworkData);
}
/**
* Configure a {@link android.webkit.WebView} to display a Message. This method takes into account a user's
* preferences when configuring the view. This message is used to view a message and to display a message being
* replied to.
*/
public void configure() {
this.setVerticalScrollBarEnabled(true);
this.setVerticalScrollbarOverlay(true);
this.setScrollBarStyle(SCROLLBARS_INSIDE_OVERLAY);
this.setLongClickable(true);
if (K9.getK9Theme() == K9.THEME_DARK) {
// Black theme should get a black webview background
// we'll set the background of the messages on load
this.setBackgroundColor(0xff000000);
}
final WebSettings webSettings = this.getSettings();
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setSupportZoom(true);
webSettings.setJavaScriptEnabled(false);
webSettings.setLoadsImagesAutomatically(true);
webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
if (K9.zoomControlsEnabled()) {
webSettings.setBuiltInZoomControls(true);
}
// SINGLE_COLUMN layout was broken on Android < 2.2, so we
// administratively disable it
if (Build.VERSION.SDK_INT > 7 && K9.mobileOptimizedLayout()) {
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
} else {
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
}
- if (Integer.parseInt(Build.VERSION.SDK) >= 9 ) {
+ /*
+ * Build.VERSION.SDK is deprecated cause it just returns the
+ * "its raw String representation"
+ * http://developer.android.com/reference/android/os/Build.VERSION_CODES.html#GINGERBREAD
+ * http://developer.android.com/reference/android/os/Build.VERSION.html#SDK
+ */
+ if (Build.VERSION.SDK_INT >= 9) {
setOverScrollMode(OVER_SCROLL_NEVER);
}
webSettings.setTextSize(K9.getFontSizes().getMessageViewContent());
// Disable network images by default. This is overridden by preferences.
blockNetworkData(true);
}
public void setText(String text, String contentType) {
String content = text;
if (K9.getK9Theme() == K9.THEME_DARK) {
// It's a little wrong to just throw in the <style> before the opening <html>
// but it's less wrong than trying to edit the html stream
content = "<style>* { background: black ! important; color: white !important }" +
":link, :link * { color: #CCFF33 !important }" +
":visited, :visited * { color: #551A8B !important }</style> "
+ content;
}
loadDataWithBaseURL("http://", content, contentType, "utf-8", null);
}
/*
* Emulate the shift key being pressed to trigger the text selection mode
* of a WebView.
*/
@Override
public void emulateShiftHeld() {
try {
KeyEvent shiftPressEvent = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0);
shiftPressEvent.dispatch(this);
Toast.makeText(getContext() , R.string.select_text_now, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Exception in emulateShiftHeld()", e);
}
}
public void wrapSetTitleBar(final View title) {
try {
Class<?> webViewClass = Class.forName("android.webkit.WebView");
Method setEmbeddedTitleBar = webViewClass.getMethod("setEmbeddedTitleBar", View.class);
setEmbeddedTitleBar.invoke(this, title);
}
catch (Exception e) {
Log.v(K9.LOG_TAG, "failed to find the setEmbeddedTitleBar method",e);
}
}
}
| true | true | public void configure() {
this.setVerticalScrollBarEnabled(true);
this.setVerticalScrollbarOverlay(true);
this.setScrollBarStyle(SCROLLBARS_INSIDE_OVERLAY);
this.setLongClickable(true);
if (K9.getK9Theme() == K9.THEME_DARK) {
// Black theme should get a black webview background
// we'll set the background of the messages on load
this.setBackgroundColor(0xff000000);
}
final WebSettings webSettings = this.getSettings();
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setSupportZoom(true);
webSettings.setJavaScriptEnabled(false);
webSettings.setLoadsImagesAutomatically(true);
webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
if (K9.zoomControlsEnabled()) {
webSettings.setBuiltInZoomControls(true);
}
// SINGLE_COLUMN layout was broken on Android < 2.2, so we
// administratively disable it
if (Build.VERSION.SDK_INT > 7 && K9.mobileOptimizedLayout()) {
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
} else {
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
}
if (Integer.parseInt(Build.VERSION.SDK) >= 9 ) {
setOverScrollMode(OVER_SCROLL_NEVER);
}
webSettings.setTextSize(K9.getFontSizes().getMessageViewContent());
// Disable network images by default. This is overridden by preferences.
blockNetworkData(true);
}
| public void configure() {
this.setVerticalScrollBarEnabled(true);
this.setVerticalScrollbarOverlay(true);
this.setScrollBarStyle(SCROLLBARS_INSIDE_OVERLAY);
this.setLongClickable(true);
if (K9.getK9Theme() == K9.THEME_DARK) {
// Black theme should get a black webview background
// we'll set the background of the messages on load
this.setBackgroundColor(0xff000000);
}
final WebSettings webSettings = this.getSettings();
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setSupportZoom(true);
webSettings.setJavaScriptEnabled(false);
webSettings.setLoadsImagesAutomatically(true);
webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
if (K9.zoomControlsEnabled()) {
webSettings.setBuiltInZoomControls(true);
}
// SINGLE_COLUMN layout was broken on Android < 2.2, so we
// administratively disable it
if (Build.VERSION.SDK_INT > 7 && K9.mobileOptimizedLayout()) {
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
} else {
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
}
/*
* Build.VERSION.SDK is deprecated cause it just returns the
* "its raw String representation"
* http://developer.android.com/reference/android/os/Build.VERSION_CODES.html#GINGERBREAD
* http://developer.android.com/reference/android/os/Build.VERSION.html#SDK
*/
if (Build.VERSION.SDK_INT >= 9) {
setOverScrollMode(OVER_SCROLL_NEVER);
}
webSettings.setTextSize(K9.getFontSizes().getMessageViewContent());
// Disable network images by default. This is overridden by preferences.
blockNetworkData(true);
}
|
diff --git a/src/com/github/joakimpersson/tda367/Main.java b/src/com/github/joakimpersson/tda367/Main.java
index 6999f71..ed8694b 100644
--- a/src/com/github/joakimpersson/tda367/Main.java
+++ b/src/com/github/joakimpersson/tda367/Main.java
@@ -1,51 +1,51 @@
package com.github.joakimpersson.tda367;
import java.io.File;
import org.lwjgl.LWJGLUtil;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.SlickException;
import com.github.joakimpersson.tda367.controller.BombermanGame;
import com.github.joakimpersson.tda367.gui.guiutils.GUIUtils;
/**
*
* @author joakimpersson
*
*/
public class Main {
public static void main(String[] args) {
// Get the game size
int gameWidth = GUIUtils.getGameWidth();
int gameHeight = GUIUtils.getGameHeight();
/*
* Dynamically uses the correct native files for lwjgl
*/
System.setProperty("org.lwjgl.librarypath",
new File(new File(new File(System.getProperty("user.dir"),
"lib"), "native"), LWJGLUtil.getPlatformName())
.getAbsolutePath());
System.setProperty("net.java.games.input.librarypath",
System.getProperty("org.lwjgl.librarypath"));
try {
- AppGameContainer app = new AppGameContainer(new BombermanGame(
- "Bomberman"));
+ AppGameContainer application = new AppGameContainer(
+ new BombermanGame("Pyromaniacs"));
- app.setDisplayMode(gameWidth, gameHeight, false);
+ application.setDisplayMode(gameWidth, gameHeight, false);
// make sure that we are using the players screen
- app.setVSync(true);
+ application.setVSync(true);
// remove the fps meter
- app.setShowFPS(false);
+ application.setShowFPS(false);
// launch the game
- app.start();
+ application.start();
} catch (SlickException e) {
e.printStackTrace();
}
}
}
| false | true | public static void main(String[] args) {
// Get the game size
int gameWidth = GUIUtils.getGameWidth();
int gameHeight = GUIUtils.getGameHeight();
/*
* Dynamically uses the correct native files for lwjgl
*/
System.setProperty("org.lwjgl.librarypath",
new File(new File(new File(System.getProperty("user.dir"),
"lib"), "native"), LWJGLUtil.getPlatformName())
.getAbsolutePath());
System.setProperty("net.java.games.input.librarypath",
System.getProperty("org.lwjgl.librarypath"));
try {
AppGameContainer app = new AppGameContainer(new BombermanGame(
"Bomberman"));
app.setDisplayMode(gameWidth, gameHeight, false);
// make sure that we are using the players screen
app.setVSync(true);
// remove the fps meter
app.setShowFPS(false);
// launch the game
app.start();
} catch (SlickException e) {
e.printStackTrace();
}
}
| public static void main(String[] args) {
// Get the game size
int gameWidth = GUIUtils.getGameWidth();
int gameHeight = GUIUtils.getGameHeight();
/*
* Dynamically uses the correct native files for lwjgl
*/
System.setProperty("org.lwjgl.librarypath",
new File(new File(new File(System.getProperty("user.dir"),
"lib"), "native"), LWJGLUtil.getPlatformName())
.getAbsolutePath());
System.setProperty("net.java.games.input.librarypath",
System.getProperty("org.lwjgl.librarypath"));
try {
AppGameContainer application = new AppGameContainer(
new BombermanGame("Pyromaniacs"));
application.setDisplayMode(gameWidth, gameHeight, false);
// make sure that we are using the players screen
application.setVSync(true);
// remove the fps meter
application.setShowFPS(false);
// launch the game
application.start();
} catch (SlickException e) {
e.printStackTrace();
}
}
|
diff --git a/x10.compiler/src/x10/ast/X10AmbTypeNode_c.java b/x10.compiler/src/x10/ast/X10AmbTypeNode_c.java
index 6554b138b..9c767c20e 100644
--- a/x10.compiler/src/x10/ast/X10AmbTypeNode_c.java
+++ b/x10.compiler/src/x10/ast/X10AmbTypeNode_c.java
@@ -1,299 +1,300 @@
/*
* This file is part of the X10 project (http://x10-lang.org).
*
* This file is licensed to You under the Eclipse Public License (EPL);
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* (C) Copyright IBM Corporation 2006-2010.
*/
package x10.ast;
import java.util.Collections;
import polyglot.ast.AmbTypeNode;
import polyglot.ast.AmbTypeNode_c;
import polyglot.ast.CanonicalTypeNode;
import polyglot.ast.Disamb;
import polyglot.ast.Expr;
import polyglot.ast.Id;
import polyglot.ast.Node;
import polyglot.ast.NodeFactory;
import polyglot.ast.PackageNode;
import polyglot.ast.Prefix;
import polyglot.ast.TypeNode;
import polyglot.frontend.Globals;
import polyglot.frontend.Goal;
import polyglot.types.Context;
import polyglot.types.Flags;
import polyglot.types.LazyRef;
import polyglot.types.QName;
import polyglot.types.Ref;
import polyglot.types.SemanticException;
import polyglot.types.Type;
import polyglot.types.Types;
import polyglot.util.CodeWriter;
import polyglot.util.InternalCompilerError;
import polyglot.util.Position;
import polyglot.visit.ContextVisitor;
import polyglot.visit.NodeVisitor;
import polyglot.visit.PrettyPrinter;
import polyglot.visit.TypeCheckPreparer;
import polyglot.visit.TypeChecker;
import x10.errors.Errors;
import x10.extension.X10Del;
import x10.extension.X10Del_c;
import x10.types.MacroType;
import x10.types.X10ClassType;
import polyglot.types.Context;
import x10.types.X10ParsedClassType;
import polyglot.types.TypeSystem;
import x10.visit.X10TypeChecker;
/**
* An <code>AmbTypeNode</code> is an ambiguous AST node composed of
* dot-separated list of identifiers that must resolve to a type.
*/
public class X10AmbTypeNode_c extends AmbTypeNode_c implements X10AmbTypeNode, AddFlags {
protected Prefix prefix;
protected Id name;
public X10AmbTypeNode_c(Position pos, Prefix qual, Id name) {
super(pos, qual, name);
assert(name != null); // qual may be null
this.prefix = qual;
this.name = name;
}
protected TypeNode disambiguateAnnotation(ContextVisitor tc) throws SemanticException {
Position pos = position();
TypeSystem ts = (TypeSystem) tc.typeSystem();
NodeFactory nf = (NodeFactory) tc.nodeFactory();
Context c = (Context) tc.context();
if (! c.inAnnotation())
return null;
SemanticException ex;
Prefix prefix = this.prefix;
// Look for a simply-named type.
try {
Disamb disamb = tc.nodeFactory().disamb();
Node n = disamb.disambiguate(this, tc, pos, prefix, name);
if (n instanceof TypeNode) {
TypeNode tn = (TypeNode) n;
Ref<Type> tref = (Ref<Type>) tn.typeRef();
Type t = tref.get();
if (t instanceof X10ParsedClassType) {
X10ParsedClassType ct = (X10ParsedClassType) t;
if (ct.flags().isInterface()) {
return postprocess((X10CanonicalTypeNode) tn, this, tc);
}
}
throw new SemanticException("Annotation type must be an interface.", position());
}
ex = new SemanticException("Could not find type \"" +(prefix == null ? name.toString() : prefix.toString() + "." + name.toString()) +"\".", pos);
}
catch (SemanticException e) {
ex = e;
}
throw ex;
}
public Node disambiguate(ContextVisitor ar) {
SemanticException ex;
Position pos = position();
ContextVisitor tc = ar;
TypeSystem ts = tc.typeSystem();
NodeFactory nf = (NodeFactory) tc.nodeFactory();
try {
TypeNode tn = disambiguateAnnotation(tc);
if (tn != null)
return tn;
}
catch (SemanticException e) {
+ LazyRef<Type> sym = (LazyRef<Type>) type;
X10ClassType ut = ts.createFakeClass(QName.make(fullName(this.prefix), name().id()), e);
ut.def().position(pos);
- ((Ref<Type>) type).update(ut);
- // FIXME: should never return an ambiguous node
- return this;
+ sym.update(ut);
+ Errors.issue(tc.job(), e, this);
+ return nf.CanonicalTypeNode(pos, sym);
}
Prefix prefix = this.prefix;
// First look for a typedef. FIXME: remove
try {
X10ParsedClassType typeDefContainer = null;
if (prefix instanceof PackageNode || prefix == null) {
// TODO: vj check isf this should be uncommented.
// PackageNode pn = (PackageNode) prefix;
// String dummyName = DUMMY_PACKAGE_CLASS_NAME;
// String fullName = (pn != null ? Types.get(pn.package_()).fullName() + "." : "") + dummyName;
// Named n = ts.systemResolver().find(fullName);
// if (n instanceof X10ParsedClassType) {
// typeDefContainer = (X10ParsedClassType) n;
// }
}
else if (prefix instanceof TypeNode) {
TypeNode tn = (TypeNode) prefix;
if (tn.type() instanceof X10ParsedClassType) {
typeDefContainer = (X10ParsedClassType) tn.type();
}
}
else if (prefix instanceof Expr) {
throw new SemanticException("Non-static type members not implemented: " + prefix + " cannot be understood.", pos);
}
if (typeDefContainer != null) {
Context context = tc.context();
MacroType mt = ts.findTypeDef(typeDefContainer, name.id(), Collections.<Type>emptyList(), Collections.<Type>emptyList(), context);
LazyRef<Type> sym = (LazyRef<Type>) type;
sym.update(mt);
// Reset the resolver goal to one that can run when the ref is deserialized.
Goal resolver = tc.job().extensionInfo().scheduler().LookupGlobalType(sym);
resolver.update(Goal.Status.SUCCESS);
sym.setResolver(resolver);
return postprocess(nf.CanonicalTypeNode(pos, sym), this, ar);
}
}
catch (SemanticException e) {
}
// Otherwise, look for a simply-named type.
try {
Disamb disamb = ar.nodeFactory().disamb();
Node n = disamb.disambiguate(this, ar, pos, prefix, name);
if (n instanceof TypeNode) {
TypeNode tn = (TypeNode) n;
LazyRef<Type> sym = (LazyRef<Type>) type;
Type t2 = tn.type();
/* if (t2 instanceof X10ParsedClassType) {
X10ParsedClassType ct = (X10ParsedClassType) tn.type();
if (ct.x10Def().typeParameters().size() != 0) {
throw new SemanticException("Invalid type " + ct + "; incorrect number of type arguments.", position());
}
}*/
// Reset the resolver goal to one that can run when the ref is deserialized.
Goal resolver = tc.job().extensionInfo().scheduler().LookupGlobalType(sym);
resolver.update(Goal.Status.SUCCESS);
sym.setResolver(resolver);
return postprocess((X10CanonicalTypeNode) tn, this, ar);
}
ex = new SemanticException("Could not find type \"" +(prefix == null ? name.toString() : prefix.toString() + "." + name.toString()) +"\".", pos);
}
catch (SemanticException e) {
ex = e;
}
// Mark the type as an error, so we don't try looking it up again.
LazyRef<Type> sym = (LazyRef<Type>) type;
X10ClassType ut = ts.createFakeClass(QName.make(fullName(prefix), name().id()), ex);
ut.def().position(position());
sym.update(ut);
Errors.issue(tc.job(), ex, this);
return nf.CanonicalTypeNode(position(), sym);
}
public static QName fullName(Prefix prefix) {
if (prefix instanceof PackageNode) {
PackageNode pn = (PackageNode) prefix;
return Types.get(pn.package_()).fullName();
}
else if (prefix instanceof TypeNode) {
TypeNode tn = (TypeNode) prefix;
return tn.type().fullName();
}
return null;
}
static TypeNode postprocess(X10CanonicalTypeNode result, TypeNode n, ContextVisitor childtc) {
Flags f = ((X10AmbTypeNode_c) n).flags;
if (f != null) {
LazyRef<Type> sym = (LazyRef<Type>) result.typeRef();
Type t = Types.get(sym);
t = Types.processFlags(f, t);
sym.update(t);
}
return AmbDepTypeNode_c.postprocess(result, n, childtc);
}
public void prettyPrint(CodeWriter w, PrettyPrinter tr) {
if (prefix != null) {
print(prefix, w, tr);
w.write(".");
w.allowBreak(2, 3, "", 0);
}
tr.print(this, name, w);
}
public String toString() {
return (prefix == null
? name.toString()
: prefix.toString() + "." + name.toString()) + "{amb}";
}
Flags flags;
public void addFlags(Flags f) {
this.flags = f;
}
public Id name() {
return this.name;
}
public AmbTypeNode name(Id name) {
X10AmbTypeNode_c n = (X10AmbTypeNode_c) copy();
n.name = name;
return n;
}
public Prefix prefix() {
return this.prefix;
}
public AmbTypeNode prefix(Prefix prefix) {
X10AmbTypeNode_c n = (X10AmbTypeNode_c) copy();
n.prefix = prefix;
return n;
}
protected AmbTypeNode_c reconstruct(Prefix qual, Id name) {
if (qual != this.prefix || name != this.name) {
X10AmbTypeNode_c n = (X10AmbTypeNode_c) copy();
n.prefix = qual;
n.name = name;
return n;
}
return this;
}
public Node visitChildren(NodeVisitor v) {
Prefix prefix = (Prefix) visitChild(this.prefix, v);
Id name = (Id) visitChild(this.name, v);
return reconstruct(prefix, name);
}
}
| false | true | public Node disambiguate(ContextVisitor ar) {
SemanticException ex;
Position pos = position();
ContextVisitor tc = ar;
TypeSystem ts = tc.typeSystem();
NodeFactory nf = (NodeFactory) tc.nodeFactory();
try {
TypeNode tn = disambiguateAnnotation(tc);
if (tn != null)
return tn;
}
catch (SemanticException e) {
X10ClassType ut = ts.createFakeClass(QName.make(fullName(this.prefix), name().id()), e);
ut.def().position(pos);
((Ref<Type>) type).update(ut);
// FIXME: should never return an ambiguous node
return this;
}
Prefix prefix = this.prefix;
// First look for a typedef. FIXME: remove
try {
X10ParsedClassType typeDefContainer = null;
if (prefix instanceof PackageNode || prefix == null) {
// TODO: vj check isf this should be uncommented.
// PackageNode pn = (PackageNode) prefix;
// String dummyName = DUMMY_PACKAGE_CLASS_NAME;
// String fullName = (pn != null ? Types.get(pn.package_()).fullName() + "." : "") + dummyName;
// Named n = ts.systemResolver().find(fullName);
// if (n instanceof X10ParsedClassType) {
// typeDefContainer = (X10ParsedClassType) n;
// }
}
else if (prefix instanceof TypeNode) {
TypeNode tn = (TypeNode) prefix;
if (tn.type() instanceof X10ParsedClassType) {
typeDefContainer = (X10ParsedClassType) tn.type();
}
}
else if (prefix instanceof Expr) {
throw new SemanticException("Non-static type members not implemented: " + prefix + " cannot be understood.", pos);
}
if (typeDefContainer != null) {
Context context = tc.context();
MacroType mt = ts.findTypeDef(typeDefContainer, name.id(), Collections.<Type>emptyList(), Collections.<Type>emptyList(), context);
LazyRef<Type> sym = (LazyRef<Type>) type;
sym.update(mt);
// Reset the resolver goal to one that can run when the ref is deserialized.
Goal resolver = tc.job().extensionInfo().scheduler().LookupGlobalType(sym);
resolver.update(Goal.Status.SUCCESS);
sym.setResolver(resolver);
return postprocess(nf.CanonicalTypeNode(pos, sym), this, ar);
}
}
catch (SemanticException e) {
}
// Otherwise, look for a simply-named type.
try {
Disamb disamb = ar.nodeFactory().disamb();
Node n = disamb.disambiguate(this, ar, pos, prefix, name);
if (n instanceof TypeNode) {
TypeNode tn = (TypeNode) n;
LazyRef<Type> sym = (LazyRef<Type>) type;
Type t2 = tn.type();
/* if (t2 instanceof X10ParsedClassType) {
X10ParsedClassType ct = (X10ParsedClassType) tn.type();
if (ct.x10Def().typeParameters().size() != 0) {
throw new SemanticException("Invalid type " + ct + "; incorrect number of type arguments.", position());
}
}*/
// Reset the resolver goal to one that can run when the ref is deserialized.
Goal resolver = tc.job().extensionInfo().scheduler().LookupGlobalType(sym);
resolver.update(Goal.Status.SUCCESS);
sym.setResolver(resolver);
return postprocess((X10CanonicalTypeNode) tn, this, ar);
}
ex = new SemanticException("Could not find type \"" +(prefix == null ? name.toString() : prefix.toString() + "." + name.toString()) +"\".", pos);
}
| public Node disambiguate(ContextVisitor ar) {
SemanticException ex;
Position pos = position();
ContextVisitor tc = ar;
TypeSystem ts = tc.typeSystem();
NodeFactory nf = (NodeFactory) tc.nodeFactory();
try {
TypeNode tn = disambiguateAnnotation(tc);
if (tn != null)
return tn;
}
catch (SemanticException e) {
LazyRef<Type> sym = (LazyRef<Type>) type;
X10ClassType ut = ts.createFakeClass(QName.make(fullName(this.prefix), name().id()), e);
ut.def().position(pos);
sym.update(ut);
Errors.issue(tc.job(), e, this);
return nf.CanonicalTypeNode(pos, sym);
}
Prefix prefix = this.prefix;
// First look for a typedef. FIXME: remove
try {
X10ParsedClassType typeDefContainer = null;
if (prefix instanceof PackageNode || prefix == null) {
// TODO: vj check isf this should be uncommented.
// PackageNode pn = (PackageNode) prefix;
// String dummyName = DUMMY_PACKAGE_CLASS_NAME;
// String fullName = (pn != null ? Types.get(pn.package_()).fullName() + "." : "") + dummyName;
// Named n = ts.systemResolver().find(fullName);
// if (n instanceof X10ParsedClassType) {
// typeDefContainer = (X10ParsedClassType) n;
// }
}
else if (prefix instanceof TypeNode) {
TypeNode tn = (TypeNode) prefix;
if (tn.type() instanceof X10ParsedClassType) {
typeDefContainer = (X10ParsedClassType) tn.type();
}
}
else if (prefix instanceof Expr) {
throw new SemanticException("Non-static type members not implemented: " + prefix + " cannot be understood.", pos);
}
if (typeDefContainer != null) {
Context context = tc.context();
MacroType mt = ts.findTypeDef(typeDefContainer, name.id(), Collections.<Type>emptyList(), Collections.<Type>emptyList(), context);
LazyRef<Type> sym = (LazyRef<Type>) type;
sym.update(mt);
// Reset the resolver goal to one that can run when the ref is deserialized.
Goal resolver = tc.job().extensionInfo().scheduler().LookupGlobalType(sym);
resolver.update(Goal.Status.SUCCESS);
sym.setResolver(resolver);
return postprocess(nf.CanonicalTypeNode(pos, sym), this, ar);
}
}
catch (SemanticException e) {
}
// Otherwise, look for a simply-named type.
try {
Disamb disamb = ar.nodeFactory().disamb();
Node n = disamb.disambiguate(this, ar, pos, prefix, name);
if (n instanceof TypeNode) {
TypeNode tn = (TypeNode) n;
LazyRef<Type> sym = (LazyRef<Type>) type;
Type t2 = tn.type();
/* if (t2 instanceof X10ParsedClassType) {
X10ParsedClassType ct = (X10ParsedClassType) tn.type();
if (ct.x10Def().typeParameters().size() != 0) {
throw new SemanticException("Invalid type " + ct + "; incorrect number of type arguments.", position());
}
}*/
// Reset the resolver goal to one that can run when the ref is deserialized.
Goal resolver = tc.job().extensionInfo().scheduler().LookupGlobalType(sym);
resolver.update(Goal.Status.SUCCESS);
sym.setResolver(resolver);
return postprocess((X10CanonicalTypeNode) tn, this, ar);
}
ex = new SemanticException("Could not find type \"" +(prefix == null ? name.toString() : prefix.toString() + "." + name.toString()) +"\".", pos);
}
|
diff --git a/org/python/core/imp.java b/org/python/core/imp.java
index 423554d4..d255676f 100644
--- a/org/python/core/imp.java
+++ b/org/python/core/imp.java
@@ -1,795 +1,795 @@
// Copyright (c) Corporation for National Research Initiatives
package org.python.core;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Utility functions for "import" support.
*/
public class imp {
public static final int APIVersion = 12;
private static Object syspathJavaLoaderLock = new Object();
private static ClassLoader syspathJavaLoader = null;
public static ClassLoader getSyspathJavaLoader() {
synchronized (syspathJavaLoaderLock) {
if (syspathJavaLoader == null) {
syspathJavaLoader = new SyspathJavaLoader();
}
}
return syspathJavaLoader;
}
private imp() {
;
}
public static PyModule addModule(String name) {
// System.err.println("AddModule:" + name);
name = name.intern();
PyObject modules = Py.getSystemState().modules;
PyModule module = (PyModule) modules.__finditem__(name);
if (module != null) {
return module;
}
module = new PyModule(name, null);
modules.__setitem__(name, module);
return module;
}
private static byte[] readBytes(InputStream fp) {
try {
byte[] buf = FileUtil.readBytes(fp);
fp.close();
return buf;
} catch (IOException ioe) {
throw Py.IOError(ioe);
}
}
private static InputStream makeStream(File file) {
try {
return new FileInputStream(file);
} catch (IOException ioe) {
throw Py.IOError(ioe);
}
}
static PyObject createFromPyClass(String name, InputStream fp,
boolean testing, String fileName) {
byte[] data = readBytes(fp);
int n = data.length;
int api = (data[n - 4] << 24) + (data[n - 3] << 16)
+ (data[n - 2] << 8) + data[n - 1];
if (api != APIVersion) {
if (testing) {
return null;
} else {
throw Py.ImportError("invalid api version(" + api + " != "
+ APIVersion + ") in: " + name);
}
}
// System.err.println("APIVersion: "+api);
PyCode code;
try {
code = BytecodeLoader.makeCode(name + "$py", data);
} catch (Throwable t) {
if (testing) {
return null;
} else {
throw Py.JavaError(t);
}
}
Py.writeComment("import", "'" + name + "' as " + fileName);
return createFromCode(name, code);
}
public static byte[] compileSource(String name, File file) {
return compileSource(name, file, null, null);
}
public static byte[] compileSource(String name, File file, String filename,
String outFilename) {
if (filename == null) {
filename = file.toString();
}
if (outFilename == null) {
outFilename = filename.substring(0, filename.length() - 3)
+ "$py.class";
}
return compileSource(name, makeStream(file), filename, outFilename);
}
static byte[] compileSource(String name, InputStream fp, String filename) {
String outFilename = null;
if (filename != null) {
outFilename = filename.substring(0, filename.length() - 3)
+ "$py.class";
}
return compileSource(name, fp, filename, outFilename);
}
static byte[] compileSource(String name, InputStream fp, String filename,
String outFilename) {
try {
ByteArrayOutputStream ofp = new ByteArrayOutputStream();
if (filename == null) {
filename = "<unknown>";
}
org.python.parser.ast.modType node = null; // *Forte*
try {
node = parser.parse(fp, "exec", filename, null);
} finally {
fp.close();
}
org.python.compiler.Module.compile(node, ofp, name + "$py",
filename, true, false, true, null);
if (outFilename != null) {
File classFile = new File(outFilename);
try {
FileOutputStream fop = new FileOutputStream(classFile);
ofp.writeTo(fop);
fop.close();
} catch (IOException exc) {
// If we can't write the cache file, just fail silently
}
}
return ofp.toByteArray();
} catch (Throwable t) {
throw parser.fixParseError(null, t, filename);
}
}
public static PyObject createFromSource(String name, InputStream fp,
String filename) {
byte[] bytes = compileSource(name, fp, filename);
Py.writeComment("import", "'" + name + "' as " + filename);
PyCode code = BytecodeLoader.makeCode(name + "$py", bytes);
return createFromCode(name, code);
}
static PyObject createFromSource(String name, InputStream fp,
String filename, String outFilename) {
byte[] bytes = compileSource(name, fp, filename, outFilename);
Py.writeComment("import", "'" + name + "' as " + filename);
PyCode code = BytecodeLoader.makeCode(name + "$py", bytes);
return createFromCode(name, code);
}
static PyObject createFromCode(String name, PyCode c) {
PyModule module = addModule(name);
PyTableCode code = null;
if (c instanceof PyTableCode) {
code = (PyTableCode) c;
}
PyFrame f = new PyFrame(code, module.__dict__, module.__dict__, null);
code.call(f);
return module;
}
static PyObject createFromClass(String name, Class c) {
// Two choices. c implements PyRunnable or c is Java package
// System.err.println("create from class: "+name+", "+c);
Class interfaces[] = c.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
if (interfaces[i] == PyRunnable.class) {
// System.err.println("is runnable");
try {
PyObject o = createFromCode(name, ((PyRunnable) c
.newInstance()).getMain());
return o;
} catch (InstantiationException e) {
throw Py.JavaError(e);
} catch (IllegalAccessException e) {
throw Py.JavaError(e);
}
}
}
return PyJavaClass.lookup(c); // xxx?
}
static PyObject getPathImporter(PyObject cache, PyList hooks, PyObject p) {
// attempt to get an importer for the path
// use null as default value since Py.None is
// a valid value in the cache for the default
// importer
PyObject importer = cache.__finditem__(p);
if (importer != null) {
return importer;
}
// nothing in the cache, so check all hooks
PyObject iter = hooks.__iter__();
for (PyObject hook; (hook = iter.__iternext__()) != null;) {
try {
importer = hook.__call__(p);
break;
} catch (PyException e) {
if (!Py.matchException(e, Py.ImportError)) {
throw e;
}
}
}
importer = (importer == null ? Py.None : importer);
cache.__setitem__(p, importer);
return importer;
}
static PyObject replacePathItem(PyObject path) {
if (path instanceof SyspathArchive) {
// already an archive
return null;
}
try {
// this has the side affect of adding the jar to the PackageManager
// during the initialization of the SyspathArchive
return new SyspathArchive(path.toString());
} catch (Exception e) {
return null;
}
}
static PyObject find_module(String name, String moduleName, PyList path) {
PyObject loader = Py.None;
PySystemState sys = Py.getSystemState();
PyObject metaPath = sys.meta_path;
/*
* Needed to convert all entries on the path to SyspathArchives if
* necessary.
*/
PyList ppath = path == null ? sys.path : path;
for (int i = 0; i < ppath.__len__(); i++) {
PyObject p = ppath.__getitem__(i);
PyObject q = replacePathItem(p);
if (q == null) {
continue;
}
ppath.__setitem__(i, q);
}
PyObject iter = metaPath.__iter__();
for (PyObject importer; (importer = iter.__iternext__()) != null;) {
PyObject findModule = importer.__getattr__("find_module");
loader = findModule.__call__(new PyObject[] {
new PyString(moduleName), path == null ? Py.None : path });
if (loader != Py.None) {
return loadFromLoader(loader, moduleName);
}
}
PyObject ret = loadBuiltin(moduleName);
if (ret != null) {
return ret;
}
path = path == null ? sys.path : path;
for (int i = 0; i < path.__len__(); i++) {
PyObject p = path.__getitem__(i);
// System.err.println("find_module (" + name + ", " + moduleName +
// ") Path: " + path);
PyObject importer = getPathImporter(sys.path_importer_cache,
sys.path_hooks, p);
if (importer != Py.None) {
PyObject findModule = importer.__getattr__("find_module");
loader = findModule.__call__(new PyObject[] { new PyString(
moduleName) });
if (loader != Py.None) {
return loadFromLoader(loader, moduleName);
}
}
ret = loadFromSource(name, moduleName, p);
if (ret != null) {
return ret;
}
}
return ret;
}
private static PyObject loadBuiltin(String name) {
if (name == "sys") {
Py.writeComment("import", "'" + name + "' as sys in "
+ "builtin modules");
return Py.java2py(Py.getSystemState());
}
String mod = PySystemState.getBuiltin(name);
if (mod != null) {
Class c = Py.findClassEx(mod, "builtin modules");
if (c != null) {
Py.writeComment("import", "'" + name + "' as " + mod
+ " in builtin modules");
try {
if (PyObject.class.isAssignableFrom(c)) { // xxx ok?
return PyType.fromClass(c);
}
return createFromClass(name, c);
} catch (NoClassDefFoundError e) {
throw Py.ImportError("Cannot import " + name
+ ", missing class " + c.getName());
}
}
}
return null;
}
static PyObject loadFromLoader(PyObject importer, String name) {
PyObject load_module = importer.__getattr__("load_module");
return load_module.__call__(new PyObject[] { new PyString(name) });
}
public static PyObject loadFromSource(String name, InputStream stream,
String filename) {
return createFromSource(name, stream, filename);
}
public static PyObject loadFromCompiled(String name, InputStream stream,
String filename) {
return createFromPyClass(name, stream, false, filename);
}
static PyObject loadFromSource(String name, String modName, PyObject entry) {
// System.err.println("load-from-source: "+name+" "+modName+" "+entry);
int nlen = name.length();
String sourceName = "__init__.py";
String compiledName = "__init__$py.class";
String directoryName = entry.toString();
// The empty string translates into the current working
// directory, which is usually provided on the system property
// "user.dir". Don't rely on File's constructor to provide
// this correctly.
if (directoryName.length() == 0) {
directoryName = null;
}
// First check for packages
File dir = new File(directoryName, name);
File sourceFile = new File(dir, sourceName);
File compiledFile = new File(dir, compiledName);
boolean pkg = (dir.isDirectory() && caseok(dir, name, nlen) && (sourceFile
.isFile() || compiledFile.isFile()));
if (!pkg) {
Py.writeDebug("import", "trying source " + dir.getPath());
sourceName = name + ".py";
compiledName = name + "$py.class";
sourceFile = new File(directoryName, sourceName);
compiledFile = new File(directoryName, compiledName);
} else {
PyModule m = addModule(modName);
PyObject filename = new PyString(dir.getPath());
m.__dict__.__setitem__("__path__", new PyList(
new PyObject[] { filename }));
m.__dict__.__setitem__("__file__", filename);
}
- if (sourceFile.isFile() && caseok(sourceFile, sourceName, nlen)) {
+ if (sourceFile.isFile() && caseok(sourceFile, sourceName, sourceName.length())) {
if (compiledFile.isFile()
- && caseok(compiledFile, compiledName, nlen)) {
+ && caseok(compiledFile, compiledName, compiledName.length())) {
Py.writeDebug("import", "trying precompiled "
+ compiledFile.getPath());
long pyTime = sourceFile.lastModified();
long classTime = compiledFile.lastModified();
if (classTime >= pyTime) {
PyObject ret = createFromPyClass(modName,
makeStream(compiledFile), true, compiledFile
.getPath());
if (ret != null) {
return ret;
}
}
}
return createFromSource(modName, makeStream(sourceFile), sourceFile
.getAbsolutePath());
}
// If no source, try loading precompiled
Py.writeDebug("import", "trying " + compiledFile.getPath());
- if (compiledFile.isFile() && caseok(compiledFile, compiledName, nlen)) {
+ if (compiledFile.isFile() && caseok(compiledFile, compiledName, compiledName.length())) {
return createFromPyClass(modName, makeStream(compiledFile), false,
compiledFile.getPath());
}
return null;
}
public static boolean caseok(File file, String filename, int namelen) {
if (Options.caseok) {
return true;
}
try {
File canFile = new File(file.getCanonicalPath());
return filename.regionMatches(0, canFile.getName(), 0, namelen);
} catch (IOException exc) {
return false;
}
}
/**
* Load the module by name. Upon loading the module it will be added to
* sys.modules.
*
* @param name the name of the module to load
* @return the loaded module
*/
public static PyObject load(String name) {
return import_first(name, new StringBuffer());
}
/**
* Find the parent module name for a module. If __name__ does not exist in
* the module then the parent is null. If __name__ does exist then the
* __path__ is checked for the parent module. For example, the __name__
* 'a.b.c' would return 'a.b'.
*
* @param dict the __dict__ of a loaded module
* @return the parent name for a module
*/
private static String getParent(PyObject dict) {
PyObject tmp = dict.__finditem__("__name__");
if (tmp == null) {
return null;
}
String name = tmp.toString();
tmp = dict.__finditem__("__path__");
if (tmp != null && tmp instanceof PyList) {
return name.intern();
} else {
int dot = name.lastIndexOf('.');
if (dot == -1) {
return null;
}
return name.substring(0, dot).intern();
}
}
/**
*
* @param mod a previously loaded module
* @param parentNameBuffer
* @param name the name of the module to load
* @return null or None
*/
private static PyObject import_next(PyObject mod,
StringBuffer parentNameBuffer, String name) {
if (parentNameBuffer.length() > 0) {
parentNameBuffer.append('.');
}
parentNameBuffer.append(name);
String fullName = parentNameBuffer.toString().intern();
PyObject modules = Py.getSystemState().modules;
PyObject ret = modules.__finditem__(fullName);
if (ret != null) {
return ret;
}
if (mod == null) {
ret = find_module(fullName.intern(), name, null);
} else {
ret = mod.impAttr(name.intern());
}
if (ret == null || ret == Py.None) {
return ret;
}
if (modules.__finditem__(fullName) == null) {
modules.__setitem__(fullName, ret);
} else {
ret = modules.__finditem__(fullName);
}
return ret;
}
// never returns null or None
private static PyObject import_first(String name,
StringBuffer parentNameBuffer) {
PyObject ret = import_next(null, parentNameBuffer, name);
if (ret == null || ret == Py.None) {
throw Py.ImportError("no module named " + name);
}
return ret;
}
// Hierarchy-recursively search for dotted name in mod;
// never returns null or None
// ??pending: check if result is really a module/jpkg/jclass?
private static PyObject import_logic(PyObject mod,
StringBuffer parentNameBuffer, String dottedName) {
int dot = 0;
int last_dot = 0;
do {
String name;
dot = dottedName.indexOf('.', last_dot);
if (dot == -1) {
name = dottedName.substring(last_dot);
} else {
name = dottedName.substring(last_dot, dot);
}
mod = import_next(mod, parentNameBuffer, name);
if (mod == null || mod == Py.None) {
throw Py.ImportError("No module named " + name);
}
last_dot = dot + 1;
} while (dot != -1);
return mod;
}
/**
* Most similar to import.c:import_module_ex.
*
* @param name
* @param top
* @param modDict
* @return a module
*/
private static PyObject import_name(String name, boolean top,
PyObject modDict) {
// System.err.println("import_name " + name);
if (name.length() == 0) {
throw Py.ValueError("Empty module name");
}
PyObject modules = Py.getSystemState().modules;
PyObject pkgMod = null;
String pkgName = null;
if (modDict != null) {
pkgName = getParent(modDict);
pkgMod = modules.__finditem__(pkgName);
// System.err.println("GetParent: " + pkgName + " => " + pkgMod);
if (pkgMod != null && !(pkgMod instanceof PyModule)) {
pkgMod = null;
}
}
int dot = name.indexOf('.');
String firstName;
if (dot == -1) {
firstName = name;
} else {
firstName = name.substring(0, dot);
}
StringBuffer parentNameBuffer = new StringBuffer(
pkgMod != null ? pkgName : "");
PyObject topMod = import_next(pkgMod, parentNameBuffer, firstName);
if (topMod == Py.None || topMod == null) {
if (topMod == null) {
modules.__setitem__(parentNameBuffer.toString().intern(),
Py.None);
}
parentNameBuffer = new StringBuffer("");
// could throw ImportError
topMod = import_first(firstName, parentNameBuffer);
}
PyObject mod = topMod;
if (dot != -1) {
// could throw ImportError
mod = import_logic(topMod, parentNameBuffer, name
.substring(dot + 1));
}
if (top) {
return topMod;
}
return mod;
}
/**
* Import a module by name.
*
* @param name the name of the package to import
* @param top if true, return the top module in the name, otherwise the last
* @return an imported module (Java or Python)
*/
public static PyObject importName(String name, boolean top) {
return import_name(name, top, null);
}
/**
* Import a module by name. This is the default call for
* __builtin__.__import__.
*
* @param name the name of the package to import
* @param top if true, return the top module in the name, otherwise the last
* @param modDict the __dict__ of an already imported module
* @return an imported module (Java or Python)
*/
public synchronized static PyObject importName(String name, boolean top,
PyObject modDict) {
return import_name(name, top, modDict);
}
/**
* Called from jpython generated code when a statement like "import spam" is
* executed.
*/
public static PyObject importOne(String mod, PyFrame frame) {
// System.out.println("importOne(" + mod + ")");
PyObject module = __builtin__.__import__(mod, frame.f_globals, frame
.getf_locals(), Py.EmptyTuple);
/*
* int dot = mod.indexOf('.'); if (dot != -1) { mod = mod.substring(0,
* dot).intern(); }
*/
// System.err.println("mod: "+mod+", "+dot);
return module;
}
/**
* Called from jpython generated code when a statement like "import spam as
* foo" is executed.
*/
public static PyObject importOneAs(String mod, PyFrame frame) {
// System.out.println("importOne(" + mod + ")");
PyObject module = __builtin__.__import__(mod, frame.f_globals, frame
.getf_locals(), getStarArg());
// frame.setlocal(asname, module);
return module;
}
/**
* Called from jpython generated code when a stamenet like "from spam.eggs
* import foo, bar" is executed.
*/
public static PyObject[] importFrom(String mod, String[] names,
PyFrame frame) {
return importFromAs(mod, names, null, frame);
}
/**
* Called from jpython generated code when a stamenet like "from spam.eggs
* import foo as spam" is executed.
*/
public static PyObject[] importFromAs(String mod, String[] names,
String[] asnames, PyFrame frame) {
// StringBuffer sb = new StringBuffer();
// for(int i=0; i<names.length; i++)
// sb.append(names[i] + " ");
// System.out.println("importFrom(" + mod + ", [" + sb + "]");
PyObject[] pynames = new PyObject[names.length];
for (int i = 0; i < names.length; i++)
pynames[i] = Py.newString(names[i]);
PyObject module = __builtin__.__import__(mod, frame.f_globals, frame
.getf_locals(), new PyTuple(pynames));
PyObject[] submods = new PyObject[names.length];
for (int i = 0; i < names.length; i++) {
PyObject submod = module.__findattr__(names[i]);
if (submod == null) {
throw Py.ImportError("cannot import name " + names[i]);
}
submods[i] = submod;
}
return submods;
}
private static PyTuple all = null;
private synchronized static PyTuple getStarArg() {
if (all == null) {
all = new PyTuple(new PyString[] { Py.newString('*') });
}
return all;
}
/**
* Called from jython generated code when a statement like "from spam.eggs
* import *" is executed.
*/
public static void importAll(String mod, PyFrame frame) {
// System.out.println("importAll(" + mod + ")");
PyObject module = __builtin__.__import__(mod, frame.f_globals, frame
.getf_locals(), getStarArg());
PyObject names;
boolean filter = true;
if (module instanceof PyJavaPackage) {
names = ((PyJavaPackage) module).fillDir();
} else {
PyObject __all__ = module.__findattr__("__all__");
if (__all__ != null) {
names = __all__;
filter = false;
} else {
names = module.__dir__();
}
}
loadNames(names, module, frame.getf_locals(), filter);
}
/**
* From a module, load the attributes found in <code>names</code> into
* locals.
*
* @param filter if true, if the name starts with an underscore '_' do not
* add it to locals
* @param locals the namespace into which names will be loaded
* @param names the names to load from the module
* @param module the fully imported module
*/
private static void loadNames(PyObject names, PyObject module,
PyObject locals, boolean filter) {
PyObject iter = names.__iter__();
for (PyObject name; (name = iter.__iternext__()) != null;) {
String sname = ((PyString) name).internedString();
if (filter && sname.startsWith("_")) {
continue;
} else {
try {
locals.__setitem__(sname, module.__getattr__(sname));
} catch (Exception exc) {
continue;
}
}
}
}
/* Reloading */
static PyObject reload(PyJavaClass c) {
// This is a dummy placeholder for the feature that allow
// reloading of java classes. But this feature does not yet
// work.
return c;
}
static PyObject reload(PyModule m) {
String name = m.__getattr__("__name__").toString().intern();
PyObject modules = Py.getSystemState().modules;
PyModule nm = (PyModule) modules.__finditem__(name);
if (nm == null || !nm.__getattr__("__name__").toString().equals(name)) {
throw Py.ImportError("reload(): module " + name
+ " not in sys.modules");
}
PyList path = Py.getSystemState().path;
String modName = name;
int dot = name.lastIndexOf('.');
if (dot != -1) {
String iname = name.substring(0, dot).intern();
PyObject pkg = modules.__finditem__(iname);
if (pkg == null) {
throw Py.ImportError("reload(): parent not in sys.modules");
}
path = (PyList) pkg.__getattr__("__path__");
name = name.substring(dot + 1, name.length()).intern();
}
// This should be better "protected"
// ((PyStringMap)nm.__dict__).clear();
nm.__setattr__("__name__", new PyString(modName));
PyObject ret = find_module(name, modName, path);
modules.__setitem__(modName, ret);
return ret;
}
}
| false | true | static PyObject loadFromSource(String name, String modName, PyObject entry) {
// System.err.println("load-from-source: "+name+" "+modName+" "+entry);
int nlen = name.length();
String sourceName = "__init__.py";
String compiledName = "__init__$py.class";
String directoryName = entry.toString();
// The empty string translates into the current working
// directory, which is usually provided on the system property
// "user.dir". Don't rely on File's constructor to provide
// this correctly.
if (directoryName.length() == 0) {
directoryName = null;
}
// First check for packages
File dir = new File(directoryName, name);
File sourceFile = new File(dir, sourceName);
File compiledFile = new File(dir, compiledName);
boolean pkg = (dir.isDirectory() && caseok(dir, name, nlen) && (sourceFile
.isFile() || compiledFile.isFile()));
if (!pkg) {
Py.writeDebug("import", "trying source " + dir.getPath());
sourceName = name + ".py";
compiledName = name + "$py.class";
sourceFile = new File(directoryName, sourceName);
compiledFile = new File(directoryName, compiledName);
} else {
PyModule m = addModule(modName);
PyObject filename = new PyString(dir.getPath());
m.__dict__.__setitem__("__path__", new PyList(
new PyObject[] { filename }));
m.__dict__.__setitem__("__file__", filename);
}
if (sourceFile.isFile() && caseok(sourceFile, sourceName, nlen)) {
if (compiledFile.isFile()
&& caseok(compiledFile, compiledName, nlen)) {
Py.writeDebug("import", "trying precompiled "
+ compiledFile.getPath());
long pyTime = sourceFile.lastModified();
long classTime = compiledFile.lastModified();
if (classTime >= pyTime) {
PyObject ret = createFromPyClass(modName,
makeStream(compiledFile), true, compiledFile
.getPath());
if (ret != null) {
return ret;
}
}
}
return createFromSource(modName, makeStream(sourceFile), sourceFile
.getAbsolutePath());
}
// If no source, try loading precompiled
Py.writeDebug("import", "trying " + compiledFile.getPath());
if (compiledFile.isFile() && caseok(compiledFile, compiledName, nlen)) {
return createFromPyClass(modName, makeStream(compiledFile), false,
compiledFile.getPath());
}
return null;
}
| static PyObject loadFromSource(String name, String modName, PyObject entry) {
// System.err.println("load-from-source: "+name+" "+modName+" "+entry);
int nlen = name.length();
String sourceName = "__init__.py";
String compiledName = "__init__$py.class";
String directoryName = entry.toString();
// The empty string translates into the current working
// directory, which is usually provided on the system property
// "user.dir". Don't rely on File's constructor to provide
// this correctly.
if (directoryName.length() == 0) {
directoryName = null;
}
// First check for packages
File dir = new File(directoryName, name);
File sourceFile = new File(dir, sourceName);
File compiledFile = new File(dir, compiledName);
boolean pkg = (dir.isDirectory() && caseok(dir, name, nlen) && (sourceFile
.isFile() || compiledFile.isFile()));
if (!pkg) {
Py.writeDebug("import", "trying source " + dir.getPath());
sourceName = name + ".py";
compiledName = name + "$py.class";
sourceFile = new File(directoryName, sourceName);
compiledFile = new File(directoryName, compiledName);
} else {
PyModule m = addModule(modName);
PyObject filename = new PyString(dir.getPath());
m.__dict__.__setitem__("__path__", new PyList(
new PyObject[] { filename }));
m.__dict__.__setitem__("__file__", filename);
}
if (sourceFile.isFile() && caseok(sourceFile, sourceName, sourceName.length())) {
if (compiledFile.isFile()
&& caseok(compiledFile, compiledName, compiledName.length())) {
Py.writeDebug("import", "trying precompiled "
+ compiledFile.getPath());
long pyTime = sourceFile.lastModified();
long classTime = compiledFile.lastModified();
if (classTime >= pyTime) {
PyObject ret = createFromPyClass(modName,
makeStream(compiledFile), true, compiledFile
.getPath());
if (ret != null) {
return ret;
}
}
}
return createFromSource(modName, makeStream(sourceFile), sourceFile
.getAbsolutePath());
}
// If no source, try loading precompiled
Py.writeDebug("import", "trying " + compiledFile.getPath());
if (compiledFile.isFile() && caseok(compiledFile, compiledName, compiledName.length())) {
return createFromPyClass(modName, makeStream(compiledFile), false,
compiledFile.getPath());
}
return null;
}
|
diff --git a/src/com/jidesoft/plaf/basic/BasicStyledLabelUI.java b/src/com/jidesoft/plaf/basic/BasicStyledLabelUI.java
index 72e97dd7..058a5dac 100644
--- a/src/com/jidesoft/plaf/basic/BasicStyledLabelUI.java
+++ b/src/com/jidesoft/plaf/basic/BasicStyledLabelUI.java
@@ -1,1704 +1,1704 @@
/*
* @(#)BasicStyledLabelUI.java 6/8/2012
*
* Copyright 2002 - 2012 JIDE Software Inc. All rights reserved.
*/
package com.jidesoft.plaf.basic;
import com.jidesoft.plaf.UIDefaultsLookup;
import com.jidesoft.swing.JideSwingUtilities;
import com.jidesoft.swing.StyleRange;
import com.jidesoft.swing.StyledLabel;
import com.jidesoft.swing.FontUtils;
import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicLabelUI;
import javax.swing.text.View;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class BasicStyledLabelUI extends BasicLabelUI implements SwingConstants {
public static Comparator<StyleRange> _comparator;
protected static BasicStyledLabelUI styledLabelUI = new BasicStyledLabelUI();
@SuppressWarnings({"UnusedDeclaration"})
public static ComponentUI createUI(JComponent c) {
return styledLabelUI;
}
class StyledText {
StyleRange styleRange;
String text;
public StyledText(String text) {
this.text = text;
}
public StyledText(String text, StyleRange styleRange) {
this.text = text;
this.styleRange = styleRange;
}
}
private final List<StyledText> _styledTexts = new ArrayList<StyledText>();
private int _preferredRowCount = 1;
@Override
public void propertyChange(PropertyChangeEvent e) {
super.propertyChange(e);
if (StyledLabel.PROPERTY_STYLE_RANGE.equals(e.getPropertyName())) {
synchronized (_styledTexts) {
_styledTexts.clear();
}
if (e.getSource() instanceof StyledLabel) {
((StyledLabel) e.getSource()).revalidate();
((StyledLabel) e.getSource()).repaint();
}
}
else if (StyledLabel.PROPERTY_IGNORE_COLOR_SETTINGS.equals(e.getPropertyName())) {
if (e.getSource() instanceof StyledLabel) {
((StyledLabel) e.getSource()).repaint();
}
}
}
@Override
protected void paintEnabledText(JLabel l, Graphics g, String s, int textX, int textY) {
View v = (l != null) ? (View) l.getClientProperty("html") : null;
if (v != null) {
super.paintEnabledText(l, g, s, textX, textY);
}
else {
paintStyledText((StyledLabel) l, g, textX, textY);
}
}
@Override
protected void paintDisabledText(JLabel l, Graphics g, String s, int textX, int textY) {
View v = (l != null) ? (View) l.getClientProperty("html") : null;
if (v != null) {
super.paintDisabledText(l, g, s, textX, textY);
}
else {
paintStyledText((StyledLabel) l, g, textX, textY);
}
}
protected void buildStyledText(StyledLabel label) {
synchronized (_styledTexts) {
_styledTexts.clear();
StyleRange[] styleRanges = label.getStyleRanges();
if (_comparator == null) {
_comparator = new Comparator<StyleRange>() {
public int compare(StyleRange r1, StyleRange r2) {
if (r1.getStart() < r2.getStart()) {
return -1;
}
else if (r1.getStart() > r2.getStart()) {
return 1;
}
else {
return 0;
}
}
};
}
Arrays.sort(styleRanges, _comparator);
String s = label.getText();
if (s != null && s.length() > 0) { // do not do anything if the text is empty
int index = 0;
for (StyleRange styleRange : styleRanges) {
if (index >= s.length()) {
break;
}
if (styleRange.getStart() > index) { // fill in the gap
String text = s.substring(index, Math.min(styleRange.getStart(), s.length()));
StyleRange newRange = new StyleRange(index, styleRange.getStart() - index, -1);
addStyledTexts(text, newRange, label);
index = styleRange.getStart();
}
if (styleRange.getStart() == index) { // exactly on
if (styleRange.getLength() == -1) {
String text = s.substring(index);
addStyledTexts(text, styleRange, label);
index = s.length();
}
else {
String text = s.substring(index, Math.min(index + styleRange.getLength(), s.length()));
addStyledTexts(text, styleRange, label);
index += styleRange.getLength();
}
}
else if (styleRange.getStart() < index) { // overlap
// ignore
}
}
if (index < s.length()) {
String text = s.substring(index, s.length());
StyleRange range = new StyleRange(index, s.length() - index, -1);
addStyledTexts(text, range, label);
}
}
}
}
private void addStyledTexts(String text, StyleRange range, StyledLabel label) {
range = new StyleRange(range); // keep the passed-in parameter no change
int index1 = text.indexOf('\r');
int index2 = text.indexOf('\n');
while (index1 >= 0 || index2 >= 0) {
int index = index1 >= 0 ? index1 : -1;
if (index2 >= 0 && (index2 < index1 || index < 0)) {
index = index2;
}
String subString = text.substring(0, index);
StyleRange newRange = new StyleRange(range);
newRange.setStart(range.getStart());
newRange.setLength(index);
_styledTexts.add(new StyledText(subString, newRange));
int length = 1;
if (text.charAt(index) == '\r' && index + 1 < text.length() && text.charAt(index + 1) == '\n') {
length++;
}
newRange = new StyleRange(range);
newRange.setStart(range.getStart() + index);
newRange.setLength(length);
_styledTexts.add(new StyledText(text.substring(index, index + length), newRange));
text = text.substring(index + length);
range.setStart(range.getStart() + index + length);
range.setLength(range.getLength() - index - length);
index1 = text.indexOf('\r');
index2 = text.indexOf('\n');
}
if (text.length() > 0) {
_styledTexts.add(new StyledText(text, range));
}
}
private boolean _gettingPreferredSize;
@Override
public Dimension getPreferredSize(JComponent c) {
_gettingPreferredSize = true;
Dimension preferredSize;
try {
preferredSize = super.getPreferredSize(c);
}
finally {
_gettingPreferredSize = false;
}
return preferredSize;
}
@Override
protected String layoutCL(JLabel label, FontMetrics fontMetrics, String text, Icon icon, Rectangle viewR, Rectangle iconR, Rectangle textR) {
Dimension size = null;
if (label instanceof StyledLabel) {
int oldPreferredWidth = ((StyledLabel) label).getPreferredWidth();
int oldRows = ((StyledLabel) label).getRows();
try {
if (((StyledLabel) label).isLineWrap() && label.getWidth() > 0) {
((StyledLabel) label).setPreferredWidth(label.getWidth());
}
size = getPreferredSize((StyledLabel) label);
if (oldPreferredWidth > 0 && oldPreferredWidth < label.getWidth()) {
((StyledLabel) label).setPreferredWidth(oldPreferredWidth);
size = getPreferredSize((StyledLabel) label);
}
else if (((StyledLabel) label).isLineWrap() && ((StyledLabel) label).getMinRows() > 0) {
((StyledLabel) label).setPreferredWidth(0);
((StyledLabel) label).setRows(0);
Dimension minSize = getPreferredSize((StyledLabel) label);
if (minSize.height > size.height) {
size = minSize;
}
}
}
finally {
((StyledLabel) label).setPreferredWidth(oldPreferredWidth);
((StyledLabel) label).setRows(oldRows);
}
}
else {
size = label.getPreferredSize();
}
textR.width = size.width;
textR.height = size.height;
if (label.getIcon() != null) {
textR.width -= label.getIcon().getIconWidth() + label.getIconTextGap();
}
return layoutCompoundLabel(
label,
fontMetrics,
text,
icon,
label.getVerticalAlignment(),
label.getHorizontalAlignment(),
label.getVerticalTextPosition(),
label.getHorizontalTextPosition(),
viewR,
iconR,
textR,
label.getIconTextGap());
}
/**
* Gets the preferred size of the text portion of the StyledLabel including the icon.
*
* @param label the StyledLabel
* @return the preferred size.
*/
protected Dimension getPreferredSize(StyledLabel label) {
buildStyledText(label);
Font font = getFont(label);
FontMetrics fm = label.getFontMetrics(font);
FontMetrics fm2;
int defaultFontSize = font.getSize();
boolean lineWrap = label.isLineWrap() || (label.getText() != null && (label.getText().contains("\r") || label.getText().contains("\n")));
synchronized (_styledTexts) {
StyledText[] texts = _styledTexts.toArray(new StyledText[_styledTexts.size()]);
// get maximum row height first by comparing all fonts of styled texts
int maxRowHeight = fm.getHeight();
for (StyledText styledText : texts) {
StyleRange style = styledText.styleRange;
int size = (style != null && (style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
int styleHeight = fm.getHeight();
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
styleHeight = fm2.getHeight();
}
styleHeight++;
/*
if (style != null) {
if (style.isWaved()) {
styleHeight += 4;
}
else if (style.isDotted()) {
styleHeight += 3;
}
else if (style.isUnderlined()) {
styleHeight += 2;
}
}
*/
maxRowHeight = Math.max(maxRowHeight, styleHeight);
}
int naturalRowCount = 1;
int nextRowStartIndex = 0;
int width = 0;
int maxWidth = 0;
List<Integer> lineWidths = new ArrayList<Integer>();
// get one line width
for (StyledText styledText : _styledTexts) {
StyleRange style = styledText.styleRange;
int size = (style != null &&
(style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
String s = styledText.text.substring(nextRowStartIndex);
if (s.startsWith("\r") || s.startsWith("\n")) {
lineWidths.add(width);
maxWidth = Math.max(width, maxWidth);
width = 0;
naturalRowCount++;
if (label.getMaxRows() > 0 && naturalRowCount >= label.getMaxRows()) {
break;
}
continue;
}
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
width += fm2.stringWidth(s);
}
else {
// fm2 = fm;
width += fm.stringWidth(s);
}
}
lineWidths.add(width);
maxWidth = Math.max(width, maxWidth);
int maxLineWidth = maxWidth;
_preferredRowCount = naturalRowCount;
// if getPreferredWidth() is not set but getRows() is set, get maximum width and row count based on the required rows.
if (lineWrap && label.getPreferredWidth() <= 0 && label.getRows() > 0) {
maxWidth = getMaximumWidth(label, maxWidth, naturalRowCount, label.getRows());
}
// if calculated maximum width is larger than label's maximum size, wrap again to get the updated row count and use the label's maximum width as the maximum width.
int preferredWidth = label.getPreferredWidth();
if (preferredWidth > 0 && label.getInsets() != null) {
preferredWidth -= label.getInsets().left + label.getInsets().right;
}
if (label.getIcon() != null && label.getHorizontalTextPosition() != SwingConstants.CENTER) {
preferredWidth -= label.getIcon().getIconWidth() + label.getIconTextGap();
}
if (lineWrap && preferredWidth > 0 && maxWidth > preferredWidth) {
maxWidth = getLayoutWidth(label, preferredWidth);
}
// label.getPreferredWidth() <= 0 && label.getMaxRows() > 0 && rowCount > label.getMaxRows(), recalculate the maximum width according to the maximum rows
if (lineWrap && label.getMaxRows() > 0 && _preferredRowCount > label.getMaxRows()) {
if (label.getPreferredWidth() <= 0) {
maxWidth = getMaximumWidth(label, maxWidth, naturalRowCount, label.getMaxRows());
}
else {
_preferredRowCount = label.getMaxRows();
}
}
// label.getPreferredWidth() <= 0 && label.getMinRows() > 0 && rowCount < label.getMinRows(), recalculate the maximum width according to the minimum rows
if (lineWrap && label.getPreferredWidth() <= 0 && label.getMinRows() > 0 && _preferredRowCount < label.getMinRows()) {
maxWidth = getMaximumWidth(label, maxWidth, naturalRowCount, label.getMinRows());
}
if (_gettingPreferredSize && label.getRows() > 0 && _preferredRowCount > label.getRows() && (label.getPreferredWidth() <= 0 || label.getPreferredWidth() >= maxLineWidth)) {
_preferredRowCount = label.getRows();
maxLineWidth = 0;
for (int i = 0; i < lineWidths.size() && i < _preferredRowCount; i++) {
maxLineWidth = Math.max(maxLineWidth, lineWidths.get(i));
}
}
Dimension dimension = new Dimension(Math.min(maxWidth, maxLineWidth), (maxRowHeight + Math.max(0, label.getRowGap())) * _preferredRowCount);
if (label.getIcon() != null) {
dimension = new Dimension(dimension.width + label.getIconTextGap() + label.getIcon().getIconWidth(), dimension.height);
}
return dimension;
}
}
private int getLayoutWidth(StyledLabel label, int maxWidth) {
int nextRowStartIndex;
Font font = getFont(label);
int defaultFontSize = font.getSize();
FontMetrics fm = label.getFontMetrics(font);
FontMetrics fm2;
nextRowStartIndex = 0;
int x = 0;
_preferredRowCount = 1;
for (int i = 0; i < _styledTexts.size(); i++) {
StyledText styledText = _styledTexts.get(i);
StyleRange style = styledText.styleRange;
if (styledText.text.contains("\r") || styledText.text.contains("\n")) {
x = 0;
_preferredRowCount++;
continue;
}
int size = (style != null &&
(style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label); // cannot omit this one
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
}
else {
fm2 = fm;
}
String s = styledText.text.substring(nextRowStartIndex);
int strWidth = fm2.stringWidth(s);
boolean wrapped = false;
int widthLeft = maxWidth - x;
if (widthLeft < strWidth) {
wrapped = true;
int availLength = s.length() * widthLeft / strWidth + 1;
int nextWordStartIndex;
int nextRowStartIndexInSubString = 0;
boolean needBreak = false;
boolean needContinue = false;
int loopCount = 0;
do {
String subString = s.substring(0, Math.min(availLength, s.length()));
int firstRowWordEndIndex = findFirstRowWordEndIndex(subString);
nextWordStartIndex = firstRowWordEndIndex < 0 ? 0 : findNextWordStartIndex(s, firstRowWordEndIndex);
if (firstRowWordEndIndex < 0) {
if (x != 0) {
x = 0;
i--;
_preferredRowCount++;
if (label.getMaxRows() > 0 && _preferredRowCount >= label.getMaxRows()) {
needBreak = true;
}
needContinue = true;
break;
}
else {
firstRowWordEndIndex = 0;
nextWordStartIndex = Math.min(s.length(), availLength);
}
}
nextRowStartIndexInSubString = firstRowWordEndIndex + 1;
String subStringThisRow = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(subStringThisRow);
if (strWidth > widthLeft) {
availLength = subString.length() * widthLeft / strWidth;
}
loopCount++;
if (loopCount > 50) {
System.err.println("Painting Styled Label Error: " + styledText);
break;
}
} while (strWidth > widthLeft && availLength > 0);
if (needBreak) {
break;
}
if (needContinue) {
continue;
}
while (nextRowStartIndexInSubString < nextWordStartIndex) {
strWidth += fm2.charWidth(s.charAt(nextRowStartIndexInSubString));
if (strWidth >= widthLeft) {
break;
}
nextRowStartIndexInSubString++;
}
String subStringThisRow = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(subStringThisRow);
while (nextRowStartIndexInSubString < nextWordStartIndex) {
strWidth += fm2.charWidth(s.charAt(nextRowStartIndexInSubString));
if (strWidth >= widthLeft) {
break;
}
nextRowStartIndexInSubString++;
}
s = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(s);
nextRowStartIndex += nextRowStartIndexInSubString;
}
else {
nextRowStartIndex = 0;
}
if (wrapped) {
_preferredRowCount++;
x = 0;
i--;
}
else {
x += strWidth;
}
}
return maxWidth;
}
private int getMaximumWidth(StyledLabel label, int maxWidth, int naturalRowCount, int limitedRows) {
int textWidth = label.getWidth() - label.getInsets().left - label.getInsets().right;
if (label.getIcon() != null) {
textWidth -= label.getIcon().getIconWidth() + label.getIconTextGap();
}
if (naturalRowCount > 1) {
int proposedMaxWidthMin = 1;
int proposedMaxWidthMax = maxWidth;
_preferredRowCount = naturalRowCount;
while (proposedMaxWidthMin < proposedMaxWidthMax) {
int middle = (proposedMaxWidthMax + proposedMaxWidthMin) / 2;
maxWidth = getLayoutWidth(label, middle);
if (_preferredRowCount > limitedRows) {
proposedMaxWidthMin = middle + 1;
_preferredRowCount = naturalRowCount;
}
else {
proposedMaxWidthMax = middle - 1;
}
}
return maxWidth + maxWidth / 20;
}
int estimatedWidth = maxWidth / limitedRows + 1;
int x = 0;
int nextRowStartIndex = 0;
Font font = getFont(label);
FontMetrics fm = label.getFontMetrics(font);
int defaultFontSize = font.getSize();
FontMetrics fm2;
for (int i = 0; i < _styledTexts.size(); i++) {
StyledText styledText = _styledTexts.get(i);
StyleRange style = styledText.styleRange;
int size = (style != null && (style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
}
else {
fm2 = fm;
}
String s = styledText.text.substring(nextRowStartIndex);
int strWidth = fm2.stringWidth(s);
int widthLeft = estimatedWidth - x;
if (widthLeft < strWidth) {
int availLength = s.length() * widthLeft / strWidth + 1;
String subString = s.substring(0, Math.min(availLength, s.length()));
int firstRowWordEndIndex = findFirstRowWordEndIndex(subString);
int nextWordStartIndex = findNextWordStartIndex(s, firstRowWordEndIndex);
if (firstRowWordEndIndex < 0) {
if (nextWordStartIndex < s.length()) {
firstRowWordEndIndex = findFirstRowWordEndIndex(s.substring(0, nextWordStartIndex));
}
else {
firstRowWordEndIndex = nextWordStartIndex;
}
}
int nextRowStartIndexInSubString = firstRowWordEndIndex + 1;
String subStringThisRow = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(subStringThisRow);
while (nextRowStartIndexInSubString < nextWordStartIndex) {
strWidth += fm2.charWidth(s.charAt(nextRowStartIndexInSubString));
nextRowStartIndexInSubString++;
if (strWidth >= widthLeft) {
break;
}
}
s = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(s);
nextRowStartIndex += nextRowStartIndexInSubString;
if (x + strWidth >= maxWidth) {
x = Math.max(x, strWidth);
break;
}
if (x + strWidth >= estimatedWidth) {
x += strWidth;
break;
}
i--;
}
x += strWidth;
}
int paintWidth = x;
if (label.getInsets() != null) {
paintWidth += label.getInsets().left + label.getInsets().right;
}
int paintRows = internalPaintStyledText(label, null, 0, 0, paintWidth);
if (paintRows != limitedRows) {
maxWidth = Math.min(maxWidth, textWidth);
while (paintRows > limitedRows && paintWidth < maxWidth) {
paintWidth += 2;
paintRows = internalPaintStyledText(label, null, 0, 0, paintWidth);
}
while (paintRows < limitedRows && paintWidth > 0) {
paintWidth -= 2;
paintRows = internalPaintStyledText(label, null, 0, 0, paintWidth);
}
x = paintWidth;
if (label.getInsets() != null) {
x -= label.getInsets().left + label.getInsets().right;
}
}
_preferredRowCount = limitedRows;
return x;
}
/**
* Gets the font from the label.
*
* @param label the label.
* @return the font. If label's getFont is null, we will use Label.font instead.
*/
protected Font getFont(StyledLabel label) {
Font font = label.getFont();
if (font == null) {
font = UIDefaultsLookup.getFont("Label.font");
}
return font;
}
protected void paintStyledText(StyledLabel label, Graphics g, int textX, int textY) {
label.setTruncated(false);
int paintWidth = label.getWidth();
if (label.isLineWrap()) {
int oldPreferredWidth = label.getPreferredWidth();
int oldRows = label.getRows();
try {
label.setRows(0);
paintWidth = getPreferredSize(label).width;
label.setPreferredWidth(oldPreferredWidth > 0 ? Math.min(label.getWidth(), oldPreferredWidth) : label.getWidth());
Dimension sizeOnWidth = getPreferredSize(label);
if (sizeOnWidth.width < paintWidth) {
paintWidth = sizeOnWidth.width;
}
}
finally {
label.setPreferredWidth(oldPreferredWidth);
label.setRows(oldRows);
}
}
Color oldColor = g.getColor();
int textWidth = label.getWidth();
if (label.getInsets() != null) {
textWidth -= label.getInsets().left + label.getInsets().right;
}
if (label.getIcon() != null && label.getHorizontalTextPosition() != SwingConstants.CENTER) {
textWidth -= label.getIcon().getIconWidth() + label.getIconTextGap();
}
paintWidth = Math.min(paintWidth, textWidth);
internalPaintStyledText(label, g, textX, textY, paintWidth);
g.setColor(oldColor);
}
private int internalPaintStyledText(StyledLabel label, Graphics g, int textX, int textY, int paintWidth) {
int labelHeight = label.getHeight();
if (labelHeight <= 0) {
labelHeight = Integer.MAX_VALUE;
}
Insets insets = label.getInsets();
if (insets != null) {
labelHeight -= insets.top + insets.bottom;
}
int leftMostX = 0;
if (insets != null) {
leftMostX += insets.left;
}
if (label.getIcon() != null) {
int horizontalTextPosition = label.getHorizontalTextPosition();
if ((horizontalTextPosition == SwingConstants.TRAILING && label.getComponentOrientation().isLeftToRight()) ||(horizontalTextPosition == SwingConstants.LEADING && !label.getComponentOrientation().isLeftToRight())) {
horizontalTextPosition = SwingConstants.RIGHT;
}
if (horizontalTextPosition == SwingConstants.RIGHT) {
leftMostX += label.getIcon().getIconWidth() + label.getIconTextGap();
}
}
int startX = textX < leftMostX ? leftMostX : textX;
int y;
int endX = paintWidth + startX;
int x = startX;
int mnemonicIndex = label.getDisplayedMnemonicIndex();
if (UIManager.getLookAndFeel() instanceof WindowsLookAndFeel &&
WindowsLookAndFeel.isMnemonicHidden()) {
mnemonicIndex = -1;
}
int charDisplayed = 0;
boolean displayMnemonic;
int mneIndex = 0;
Font font = getFont(label);
FontMetrics fm = label.getFontMetrics(font);
FontMetrics fm2;
FontMetrics nextFm2 = null;
int defaultFontSize = font.getSize();
synchronized (_styledTexts) {
String nextS;
int maxRowHeight = fm.getHeight();
int minStartY = fm.getAscent();
int horizontalAlignment = label.getHorizontalAlignment();
switch (horizontalAlignment) {
case LEADING:
horizontalAlignment = label.getComponentOrientation().isLeftToRight() ? LEFT : RIGHT;
break;
case TRAILING:
horizontalAlignment = label.getComponentOrientation().isLeftToRight() ? RIGHT : LEFT;
break;
}
for (StyledText styledText : _styledTexts) {
StyleRange style = styledText.styleRange;
int size = (style != null && (style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
maxRowHeight = Math.max(maxRowHeight, fm2.getHeight());
minStartY = Math.max(minStartY, fm2.getAscent());
}
}
boolean lineWrap = label.isLineWrap();
if (!lineWrap) {
for (StyledText styledText : _styledTexts) {
if (styledText.text.endsWith("\n")) {
lineWrap = true;
break;
}
}
}
if (lineWrap && textY < minStartY) {
textY = minStartY;
}
int nextRowStartIndex = 0;
int rowCount = 0;
int rowStartOffset = 0;
for (int i = 0; i < _styledTexts.size(); i++) {
StyledText styledText = _styledTexts.get(i);
StyleRange style = styledText.styleRange;
if (mnemonicIndex >= 0 && styledText.text.length() - nextRowStartIndex > mnemonicIndex - charDisplayed) {
displayMnemonic = true;
mneIndex = mnemonicIndex - charDisplayed;
}
else {
displayMnemonic = false;
}
charDisplayed += styledText.text.length() - nextRowStartIndex;
if (styledText.text.contains("\r") || styledText.text.contains("\n")) {
boolean lastRow = (label.getMaxRows() > 0 && rowCount >= label.getMaxRows() - 1) || textY + maxRowHeight + Math.max(0, label.getRowGap()) > labelHeight;
if (horizontalAlignment != LEFT && g != null) {
if (lastRow && i != _styledTexts.size() - 1) {
x += fm.stringWidth("...");
}
paintRow(label, g, startX, x, endX, textY, rowStartOffset, style.getStart() + styledText.text.length(), lastRow);
}
rowStartOffset = style.getStart();
nextRowStartIndex = 0;
nextFm2 = null;
if (!lastRow) {
rowStartOffset += style.getLength();
rowCount++;
x = startX;
textY += maxRowHeight + Math.max(0, label.getRowGap());
continue; // continue to paint "..." if lastRow is true
}
else if (horizontalAlignment != LEFT && g != null) {
break;
}
}
y = textY;
if (nextFm2 == null) {
int size = (style != null &&
(style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
}
else {
fm2 = fm;
}
}
else {
fm2 = nextFm2;
}
if (g != null) {
g.setFont(font);
}
boolean stop = false;
String s = styledText.text.substring(Math.min(nextRowStartIndex, styledText.text.length()));
if (s.contains("\r") || s.contains("\n")) {
s = "...";
stop = true;
}
int strWidth = fm2.stringWidth(s);
boolean wrapped = false;
int widthLeft = endX - x;
- if (widthLeft < strWidth) {
+ if (widthLeft < strWidth && widthLeft >= 0) {
if (label.isLineWrap() && ((label.getMaxRows() > 0 && rowCount < label.getMaxRows() - 1) || label.getMaxRows() <= 0) && y + maxRowHeight + Math.max(0, label.getRowGap()) <= labelHeight) {
wrapped = true;
int availLength = s.length() * widthLeft / strWidth + 1;
int nextWordStartIndex;
int nextRowStartIndexInSubString = 0;
boolean needBreak = false;
boolean needContinue = false;
int loopCount = 0;
do {
String subString = s.substring(0, Math.max(0, Math.min(availLength, s.length())));
int firstRowWordEndIndex = findFirstRowWordEndIndex(subString);
nextWordStartIndex = firstRowWordEndIndex < 0 ? 0 : findNextWordStartIndex(s, firstRowWordEndIndex);
if (firstRowWordEndIndex < 0) {
if (x != startX) {
boolean lastRow = label.getMaxRows() > 0 && rowCount >= label.getMaxRows() - 1;
if (horizontalAlignment != LEFT && g != null) {
paintRow(label, g, startX, x, endX, textY, rowStartOffset, style.getStart() + Math.min(nextRowStartIndex, styledText.text.length()), lastRow);
}
textY += maxRowHeight + Math.max(0, label.getRowGap());
x = startX;
i--;
rowCount++;
rowStartOffset = style.getStart() + Math.min(nextRowStartIndex, styledText.text.length());
if (lastRow) {
needBreak = true;
}
needContinue = true;
break;
}
else {
firstRowWordEndIndex = 0;
nextWordStartIndex = Math.min(s.length(), availLength);
}
}
nextRowStartIndexInSubString = firstRowWordEndIndex + 1;
String subStringThisRow = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(subStringThisRow);
if (strWidth > widthLeft) {
availLength = subString.length() * widthLeft / strWidth;
}
loopCount++;
if (loopCount > 15) {
System.err.println("Painting Styled Label Error: " + styledText);
break;
}
} while (strWidth > widthLeft && availLength > 0);
if (needBreak) {
break;
}
if (needContinue) {
continue;
}
while (nextRowStartIndexInSubString < nextWordStartIndex) {
strWidth += fm2.charWidth(s.charAt(nextRowStartIndexInSubString));
if (strWidth >= widthLeft) {
break;
}
nextRowStartIndexInSubString++;
}
s = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(s);
charDisplayed -= styledText.text.length() - nextRowStartIndex;
if (displayMnemonic) {
if (mnemonicIndex >= 0 && s.length() > mnemonicIndex - charDisplayed) {
displayMnemonic = true;
mneIndex = mnemonicIndex - charDisplayed;
}
else {
displayMnemonic = false;
}
}
charDisplayed += s.length();
nextRowStartIndex += nextRowStartIndexInSubString;
}
else {
// use this method to clip string
s = SwingUtilities.layoutCompoundLabel(label, fm2, s, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x, y, widthLeft, labelHeight), new Rectangle(), new Rectangle(), 0);
strWidth = fm2.stringWidth(s);
}
stop = !lineWrap || y + maxRowHeight + Math.max(0, label.getRowGap()) > labelHeight || (label.getMaxRows() > 0 && rowCount >= label.getMaxRows() - 1);
}
else if (lineWrap) {
nextRowStartIndex = 0;
}
else if (i < _styledTexts.size() - 1) {
StyledText nextStyledText = _styledTexts.get(i + 1);
String nextText = nextStyledText.text;
StyleRange nextStyle = nextStyledText.styleRange;
int size = (nextStyle != null &&
(nextStyle.isSuperscript() || nextStyle.isSubscript())) ? Math.round((float) defaultFontSize / nextStyle.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (nextStyle != null && ((nextStyle.getFontStyle() != -1 && font.getStyle() != nextStyle.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, nextStyle.getFontStyle() == -1 ? font.getStyle() : nextStyle.getFontStyle(), size);
nextFm2 = label.getFontMetrics(font);
}
else {
nextFm2 = fm;
}
if (nextFm2.stringWidth(nextText) > widthLeft - strWidth) {
nextS = SwingUtilities.layoutCompoundLabel(label, nextFm2, nextText, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x + strWidth, y, widthLeft - strWidth, labelHeight), new Rectangle(), new Rectangle(), 0);
if (nextFm2.stringWidth(nextS) > widthLeft - strWidth) {
s = SwingUtilities.layoutCompoundLabel(label, fm2, s, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x, y, strWidth - 1, labelHeight), new Rectangle(), new Rectangle(), 0);
strWidth = fm2.stringWidth(s);
stop = true;
}
}
}
// start of actual painting
if (rowCount > 0 && x == startX && s.startsWith(" ")) {
s = s.substring(1);
strWidth = fm2.stringWidth(s);
}
if (horizontalAlignment == LEFT && g != null) {
if (style != null && style.isSuperscript()) {
y -= fm.getHeight() - fm2.getHeight();
}
if (style != null && style.getBackgroundColor() != null) {
g.setColor(style.getBackgroundColor());
g.fillRect(x, y - fm2.getHeight(), strWidth, fm2.getHeight() + 4);
}
Color textColor = (style != null && !label.isIgnoreColorSettings() && style.getFontColor() != null) ? style.getFontColor() : label.getForeground();
if (!label.isEnabled()) {
textColor = UIDefaultsLookup.getColor("Label.disabledForeground");
}
g.setColor(textColor);
if (displayMnemonic) {
JideSwingUtilities.drawStringUnderlineCharAt(label, g, s, mneIndex, x, y);
}
else {
JideSwingUtilities.drawString(label, g, s, x, y);
}
if (style != null) {
Stroke oldStroke = ((Graphics2D) g).getStroke();
if (style.getLineStroke() != null) {
((Graphics2D) g).setStroke(style.getLineStroke());
}
if (!label.isIgnoreColorSettings() && style.getLineColor() != null) {
g.setColor(style.getLineColor());
}
if (style.isStrikethrough()) {
int lineY = y + (fm2.getDescent() - fm2.getAscent()) / 2;
g.drawLine(x, lineY, x + strWidth - 1, lineY);
}
if (style.isDoublestrikethrough()) {
int lineY = y + (fm2.getDescent() - fm2.getAscent()) / 2;
g.drawLine(x, lineY - 1, x + strWidth - 1, lineY - 1);
g.drawLine(x, lineY + 1, x + strWidth - 1, lineY + 1);
}
if (style.isUnderlined()) {
int lineY = y + 1;
g.drawLine(x, lineY, x + strWidth - 1, lineY);
}
if (style.isDotted()) {
int dotY = y + 1;
for (int dotX = x; dotX < x + strWidth; dotX += 4) {
g.drawRect(dotX, dotY, 1, 1);
}
}
if (style.isWaved()) {
int waveY = y + 1;
for (int waveX = x; waveX < x + strWidth; waveX += 4) {
if (waveX + 2 <= x + strWidth - 1)
g.drawLine(waveX, waveY + 2, waveX + 2, waveY);
if (waveX + 4 <= x + strWidth - 1)
g.drawLine(waveX + 3, waveY + 1, waveX + 4, waveY + 2);
}
}
if (style.getLineStroke() != null) {
((Graphics2D) g).setStroke(oldStroke);
}
}
}
// end of actual painting
if (stop) {
if (horizontalAlignment != LEFT && g != null) {
x += strWidth;
paintRow(label, g, startX, x, endX, textY, rowStartOffset, label.getText().length(), true);
}
label.setTruncated(true);
break;
}
if (wrapped) {
boolean lastRow = (label.getMaxRows() > 0 && rowCount >= label.getMaxRows() - 1) || textY + maxRowHeight + Math.max(0, label.getRowGap()) > labelHeight;
if (horizontalAlignment != LEFT && g != null) {
x += strWidth;
paintRow(label, g, startX, x, endX, textY, rowStartOffset, style.getStart() + Math.min(nextRowStartIndex, styledText.text.length()), lastRow);
}
textY += maxRowHeight + Math.max(0, label.getRowGap());
x = startX;
i--;
rowCount++;
rowStartOffset = style.getStart() + Math.min(nextRowStartIndex, styledText.text.length());
if (lastRow) {
break;
}
}
else {
x += strWidth;
}
if (i == _styledTexts.size() - 1) {
if (horizontalAlignment != LEFT && g != null) {
paintRow(label, g, startX, x, endX, textY, rowStartOffset, -1, true);
}
}
}
return (int) Math.ceil((double) textY / maxRowHeight);
}
}
private void paintRow(StyledLabel label, Graphics g, int leftAlignmentX, int thisLineEndX, int rightMostX, int textY, int startOffset, int endOffset, boolean lastRow) {
if (g == null) {
return;
}
int horizontalTextPosition = label.getHorizontalTextPosition();
int horizontalAlignment = label.getHorizontalAlignment();
if ((horizontalTextPosition == SwingConstants.TRAILING && !label.getComponentOrientation().isLeftToRight()) ||(horizontalTextPosition == SwingConstants.LEADING && label.getComponentOrientation().isLeftToRight())) {
horizontalTextPosition = SwingConstants.LEFT;
}
if ((horizontalTextPosition == SwingConstants.LEADING && !label.getComponentOrientation().isLeftToRight()) ||(horizontalTextPosition == SwingConstants.TRAILING && label.getComponentOrientation().isLeftToRight())) {
horizontalTextPosition = SwingConstants.RIGHT;
}
if ((horizontalAlignment == SwingConstants.TRAILING && !label.getComponentOrientation().isLeftToRight()) ||(horizontalAlignment == SwingConstants.LEADING && label.getComponentOrientation().isLeftToRight())) {
horizontalAlignment = SwingConstants.LEFT;
}
if ((horizontalAlignment == SwingConstants.LEADING && !label.getComponentOrientation().isLeftToRight()) ||(horizontalAlignment == SwingConstants.TRAILING && label.getComponentOrientation().isLeftToRight())) {
horizontalAlignment = SwingConstants.RIGHT;
}
Insets insets = label.getInsets();
int textX = leftAlignmentX;
int paintWidth = thisLineEndX - leftAlignmentX;
if (horizontalAlignment == RIGHT) {
paintWidth = thisLineEndX - textX;
textX = label.getWidth() - paintWidth;
if (insets != null) {
textX -= insets.right;
}
if (label.getIcon() != null && horizontalTextPosition == SwingConstants.LEFT) {
textX -= label.getIcon().getIconWidth() + label.getIconTextGap();
}
}
else if (horizontalAlignment == CENTER) {
int leftMostX = 0;
if (horizontalTextPosition == SwingConstants.RIGHT && label.getIcon() != null) {
leftMostX += label.getIcon().getIconWidth() + label.getIconTextGap();
}
int labelWidth = label.getWidth();
if (insets != null) {
labelWidth -= insets.right + insets.left;
leftMostX += insets.left;
}
if (label.getIcon() != null && horizontalTextPosition != SwingConstants.CENTER) {
labelWidth -= label.getIcon().getIconWidth() + label.getIconTextGap();
}
textX = leftMostX + (labelWidth - paintWidth) / 2;
}
paintWidth = Math.min(paintWidth, rightMostX - leftAlignmentX);
int mnemonicIndex = label.getDisplayedMnemonicIndex();
if (UIManager.getLookAndFeel() instanceof WindowsLookAndFeel &&
WindowsLookAndFeel.isMnemonicHidden()) {
mnemonicIndex = -1;
}
int charDisplayed = 0;
boolean displayMnemonic;
int mneIndex = 0;
Font font = getFont(label);
FontMetrics fm = label.getFontMetrics(font);
FontMetrics fm2;
FontMetrics nextFm2 = null;
int defaultFontSize = font.getSize();
int x = textX;
for (int i = 0; i < _styledTexts.size() && (endOffset < 0 || charDisplayed < endOffset); i++) {
StyledText styledText = _styledTexts.get(i);
StyleRange style = styledText.styleRange;
int length = style.getLength();
if (length < 0) {
length = styledText.text.length();
}
if (style.getStart() + length <= startOffset) {
charDisplayed += length;
continue;
}
int nextRowStartIndex = style.getStart() >= startOffset ? 0 : startOffset - style.getStart();
charDisplayed += nextRowStartIndex;
if (mnemonicIndex >= 0 && styledText.text.length() - nextRowStartIndex > mnemonicIndex - charDisplayed) {
displayMnemonic = true;
mneIndex = mnemonicIndex - charDisplayed;
}
else {
displayMnemonic = false;
}
int paintLength = styledText.text.length() - nextRowStartIndex;
if (endOffset >= 0 && charDisplayed + paintLength >= endOffset) {
paintLength = endOffset - charDisplayed;
}
charDisplayed += paintLength;
int y = textY;
if (nextFm2 == null) {
int size = (style != null &&
(style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
}
else {
fm2 = fm;
}
}
else {
fm2 = nextFm2;
}
g.setFont(font);
String s = styledText.text.substring(Math.min(nextRowStartIndex, styledText.text.length()));
if (startOffset > 0 && x == textX && s.startsWith(" ")) {
s = s.substring(1);
}
if (s.length() > paintLength) {
s = s.substring(0, paintLength);
}
if (s.contains("\r") || s.contains("\n")) {
if (styledText.styleRange.getStart() + styledText.styleRange.getLength() >= endOffset) {
break;
}
s = "...";
}
int strWidth = fm2.stringWidth(s);
int widthLeft = paintWidth + textX - x;
if (widthLeft < strWidth) {
if (strWidth <= 0) {
return;
}
if (label.isLineWrap() && !lastRow) {
int availLength = s.length() * widthLeft / strWidth + 1;
int nextWordStartIndex;
int nextRowStartIndexInSubString;
int loopCount = 0;
do {
String subString = s.substring(0, Math.max(0, Math.min(availLength, s.length())));
int firstRowWordEndIndex = findFirstRowWordEndIndex(subString);
nextWordStartIndex = firstRowWordEndIndex < 0 ? 0 : findNextWordStartIndex(s, firstRowWordEndIndex);
if (firstRowWordEndIndex < 0) {
if (x == textX) {
firstRowWordEndIndex = 0;
nextWordStartIndex = Math.min(s.length(), availLength);
}
}
nextRowStartIndexInSubString = firstRowWordEndIndex + 1;
String subStringThisRow = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(subStringThisRow);
if (strWidth > widthLeft) {
availLength = subString.length() * widthLeft / strWidth;
}
loopCount++;
if (loopCount > 50) {
System.err.println("Painting Styled Label Error: " + styledText);
break;
}
}
while (strWidth > widthLeft && availLength > 0);
while (nextRowStartIndexInSubString < nextWordStartIndex) {
strWidth += fm2.charWidth(s.charAt(nextRowStartIndexInSubString));
if (strWidth >= widthLeft) {
break;
}
nextRowStartIndexInSubString++;
}
s = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(s);
charDisplayed -= styledText.text.length() - nextRowStartIndex;
if (displayMnemonic) {
if (mnemonicIndex >= 0 && s.length() > mnemonicIndex - charDisplayed) {
displayMnemonic = true;
mneIndex = mnemonicIndex - charDisplayed;
}
else {
displayMnemonic = false;
}
}
charDisplayed += s.length();
nextRowStartIndex += nextRowStartIndexInSubString;
}
else {
// use this method to clip string
s = SwingUtilities.layoutCompoundLabel(label, fm2, s, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x, y, widthLeft, label.getHeight()), new Rectangle(), new Rectangle(), 0);
strWidth = fm2.stringWidth(s);
}
}
else if (label.isLineWrap()) {
nextRowStartIndex = 0;
}
else if (i < _styledTexts.size() - 1) {
StyledText nextStyledText = _styledTexts.get(i + 1);
String nextText = nextStyledText.text;
StyleRange nextStyle = nextStyledText.styleRange;
int size = (nextStyle != null &&
(nextStyle.isSuperscript() || nextStyle.isSubscript())) ? Math.round((float) defaultFontSize / nextStyle.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (nextStyle != null && ((nextStyle.getFontStyle() != -1 && font.getStyle() != nextStyle.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, nextStyle.getFontStyle() == -1 ? font.getStyle() : nextStyle.getFontStyle(), size);
nextFm2 = label.getFontMetrics(font);
}
else {
nextFm2 = fm;
}
if (nextFm2.stringWidth(nextText) > widthLeft - strWidth) {
String nextS = SwingUtilities.layoutCompoundLabel(label, nextFm2, nextText, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x + strWidth, y, widthLeft - strWidth, label.getHeight()), new Rectangle(), new Rectangle(), 0);
if (nextFm2.stringWidth(nextS) > widthLeft - strWidth) {
s = SwingUtilities.layoutCompoundLabel(label, fm2, s, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x, y, strWidth - 1, label.getHeight()), new Rectangle(), new Rectangle(), 0);
strWidth = fm2.stringWidth(s);
}
}
}
// start of actual painting
if (style != null && style.isSuperscript()) {
y -= fm.getHeight() - fm2.getHeight();
}
if (style != null && style.getBackgroundColor() != null) {
g.setColor(style.getBackgroundColor());
g.fillRect(x, y - fm2.getHeight(), strWidth, fm2.getHeight() + 4);
}
Color textColor = (style != null && !label.isIgnoreColorSettings() && style.getFontColor() != null) ? style.getFontColor() : label.getForeground();
if (!label.isEnabled()) {
textColor = UIDefaultsLookup.getColor("Label.disabledForeground");
}
g.setColor(textColor);
if (displayMnemonic) {
JideSwingUtilities.drawStringUnderlineCharAt(label, g, s, mneIndex, x, y);
}
else {
JideSwingUtilities.drawString(label, g, s, x, y);
}
if (style != null) {
Stroke oldStroke = ((Graphics2D) g).getStroke();
if (style.getLineStroke() != null) {
((Graphics2D) g).setStroke(style.getLineStroke());
}
if (!label.isIgnoreColorSettings() && style.getLineColor() != null) {
g.setColor(style.getLineColor());
}
if (style.isStrikethrough()) {
int lineY = y + (fm2.getDescent() - fm2.getAscent()) / 2;
g.drawLine(x, lineY, x + strWidth - 1, lineY);
}
if (style.isDoublestrikethrough()) {
int lineY = y + (fm2.getDescent() - fm2.getAscent()) / 2;
g.drawLine(x, lineY - 1, x + strWidth - 1, lineY - 1);
g.drawLine(x, lineY + 1, x + strWidth - 1, lineY + 1);
}
if (style.isUnderlined()) {
int lineY = y + 1;
g.drawLine(x, lineY, x + strWidth - 1, lineY);
}
if (style.isDotted()) {
int dotY = y + 1;
for (int dotX = x; dotX < x + strWidth; dotX += 4) {
g.drawRect(dotX, dotY, 1, 1);
}
}
if (style.isWaved()) {
int waveY = y + 1;
for (int waveX = x; waveX < x + strWidth; waveX += 4) {
if (waveX + 2 <= x + strWidth - 1)
g.drawLine(waveX, waveY + 2, waveX + 2, waveY);
if (waveX + 4 <= x + strWidth - 1)
g.drawLine(waveX + 3, waveY + 1, waveX + 4, waveY + 2);
}
}
if (style.getLineStroke() != null) {
((Graphics2D) g).setStroke(oldStroke);
}
}
// end of actual painting
x += strWidth;
}
}
private int findNextWordStartIndex(String string, int firstRowEndIndex) {
boolean skipFirstWord = firstRowEndIndex < 0;
for (int i = firstRowEndIndex + 1; i < string.length(); i++) {
char c = string.charAt(i);
if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
if (!skipFirstWord) {
return i;
}
}
else {
skipFirstWord = false;
}
}
return string.length();
}
private int findFirstRowWordEndIndex(String string) {
boolean spaceFound = false;
for (int i = string.length() - 1; i >= 0; i--) {
char c = string.charAt(i);
if (!spaceFound) {
if (c == ' ' || c == '\t' || c == '\r' || c == '\n') {
spaceFound = true;
}
}
else {
if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
return i;
}
}
}
return -1;
}
/**
* Compute and return the location of the icons origin, the location of origin of the text baseline, and a possibly
* clipped version of the compound labels string. Locations are computed relative to the viewR rectangle. The
* JComponents orientation (LEADING/TRAILING) will also be taken into account and translated into LEFT/RIGHT values
* accordingly.
*
* @param c the component
* @param fm the font metrics
* @param text the text
* @param icon the icon
* @param verticalAlignment vertical alignment mode
* @param horizontalAlignment horizontal alignment mode
* @param verticalTextPosition vertical text position
* @param horizontalTextPosition horizontal text position
* @param viewR view rectangle
* @param iconR icon rectangle
* @param textR text rectangle
* @param textIconGap the gap between text and icon
* @return the layout string
*/
public static String layoutCompoundLabel(JComponent c,
FontMetrics fm,
String text,
Icon icon,
int verticalAlignment,
int horizontalAlignment,
int verticalTextPosition,
int horizontalTextPosition,
Rectangle viewR,
Rectangle iconR,
Rectangle textR,
int textIconGap) {
boolean orientationIsLeftToRight = true;
int hAlign = horizontalAlignment;
int hTextPos = horizontalTextPosition;
if (c != null) {
if (!(c.getComponentOrientation().isLeftToRight())) {
orientationIsLeftToRight = false;
}
}
// Translate LEADING/TRAILING values in horizontalAlignment
// to LEFT/RIGHT values depending on the components orientation
switch (horizontalAlignment) {
case LEADING:
hAlign = (orientationIsLeftToRight) ? LEFT : RIGHT;
break;
case TRAILING:
hAlign = (orientationIsLeftToRight) ? RIGHT : LEFT;
break;
}
// Translate LEADING/TRAILING values in horizontalTextPosition
// to LEFT/RIGHT values depending on the components orientation
switch (horizontalTextPosition) {
case LEADING:
hTextPos = (orientationIsLeftToRight) ? LEFT : RIGHT;
break;
case TRAILING:
hTextPos = (orientationIsLeftToRight) ? RIGHT : LEFT;
break;
}
return layoutCompoundLabelImpl(c,
fm,
text,
icon,
verticalAlignment,
hAlign,
verticalTextPosition,
hTextPos,
viewR,
iconR,
textR,
textIconGap);
}
/**
* Compute and return the location of the icons origin, the location of origin of the text baseline, and a possibly
* clipped version of the compound labels string. Locations are computed relative to the viewR rectangle. This
* layoutCompoundLabel() does not know how to handle LEADING/TRAILING values in horizontalTextPosition (they will
* default to RIGHT) and in horizontalAlignment (they will default to CENTER). Use the other version of
* layoutCompoundLabel() instead.
*
* @param fm the font metrics
* @param text the text
* @param icon the icon
* @param verticalAlignment vertical alignment mode
* @param horizontalAlignment horizontal alignment mode
* @param verticalTextPosition vertical text position
* @param horizontalTextPosition horizontal text position
* @param viewR view rectangle
* @param iconR icon rectangle
* @param textR text rectangle
* @param textIconGap the gap between text and icon
* @return the layout string
*/
public static String layoutCompoundLabel(
FontMetrics fm,
String text,
Icon icon,
int verticalAlignment,
int horizontalAlignment,
int verticalTextPosition,
int horizontalTextPosition,
Rectangle viewR,
Rectangle iconR,
Rectangle textR,
int textIconGap) {
return layoutCompoundLabelImpl(null, fm, text, icon,
verticalAlignment,
horizontalAlignment,
verticalTextPosition,
horizontalTextPosition,
viewR, iconR, textR, textIconGap);
}
/**
* Compute and return the location of the icons origin, the location of origin of the text baseline, and a possibly
* clipped version of the compound labels string. Locations are computed relative to the viewR rectangle. This
* layoutCompoundLabel() does not know how to handle LEADING/TRAILING values in horizontalTextPosition (they will
* default to RIGHT) and in horizontalAlignment (they will default to CENTER). Use the other version of
* layoutCompoundLabel() instead.
*
* @param c the component
* @param fm the font metrics
* @param text the text
* @param icon the icon
* @param verticalAlignment vertical alignment mode
* @param horizontalAlignment horizontal alignment mode
* @param verticalTextPosition vertical text position
* @param horizontalTextPosition horizontal text position
* @param viewR view rectangle
* @param iconR icon rectangle
* @param textR text rectangle
* @param textIconGap the gap between text and icon
* @return the layout string
*/
@SuppressWarnings({"UnusedDeclaration"})
private static String layoutCompoundLabelImpl(
JComponent c,
FontMetrics fm,
String text,
Icon icon,
int verticalAlignment,
int horizontalAlignment,
int verticalTextPosition,
int horizontalTextPosition,
Rectangle viewR,
Rectangle iconR,
Rectangle textR,
int textIconGap) {
/* Initialize the icon bounds rectangle iconR.
*/
if (icon != null) {
iconR.width = icon.getIconWidth();
iconR.height = icon.getIconHeight();
}
else {
iconR.width = iconR.height = 0;
}
/* Initialize the text bounds rectangle textR. If a null
* or and empty String was specified we substitute "" here
* and use 0,0,0,0 for textR.
*/
boolean textIsEmpty = (text == null) || text.equals("");
int lsb = 0;
/* Unless both text and icon are non-null, we effectively ignore
* the value of textIconGap.
*/
int gap;
View v;
if (textIsEmpty) {
textR.width = textR.height = 0;
text = "";
gap = 0;
}
else {
int availTextWidth;
gap = (icon == null) ? 0 : textIconGap;
if (horizontalTextPosition == CENTER) {
availTextWidth = viewR.width;
}
else {
availTextWidth = viewR.width - (iconR.width + gap);
}
v = (c != null) ? (View) c.getClientProperty("html") : null;
if (v != null) {
textR.width = Math.min(availTextWidth, (int) v.getPreferredSpan(View.X_AXIS));
textR.height = (int) v.getPreferredSpan(View.Y_AXIS);
}
else {
// this is only place that is changed for StyledLabel
// textR.width = SwingUtilities2.stringWidth(c, fm, text);
// lsb = SwingUtilities2.getLeftSideBearing(c, fm, text);
// if (lsb < 0) {
// // If lsb is negative, add it to the width and later
// // adjust the x location. This gives more space than is
// // actually needed.
// // This is done like this for two reasons:
// // 1. If we set the width to the actual bounds all
// // callers would have to account for negative lsb
// // (pref size calculations ONLY look at width of
// // textR)
// // 2. You can do a drawString at the returned location
// // and the text won't be clipped.
// textR.width -= lsb;
// }
// if (textR.width > availTextWidth) {
// text = SwingUtilities2.clipString(c, fm, text,
// availTextWidth);
// textR.width = SwingUtilities2.stringWidth(c, fm, text);
// }
// textR.height = fm.getHeight();
}
}
/* Compute textR.x,y given the verticalTextPosition and
* horizontalTextPosition properties
*/
if (verticalTextPosition == TOP) {
if (horizontalTextPosition != CENTER) {
textR.y = 0;
}
else {
textR.y = -(textR.height + gap);
}
}
else if (verticalTextPosition == CENTER) {
textR.y = (iconR.height / 2) - (textR.height / 2);
}
else { // (verticalTextPosition == BOTTOM)
if (horizontalTextPosition != CENTER) {
textR.y = iconR.height - textR.height;
}
else {
textR.y = (iconR.height + gap);
}
}
if (horizontalTextPosition == LEFT) {
textR.x = -(textR.width + gap);
}
else if (horizontalTextPosition == CENTER) {
textR.x = (iconR.width / 2) - (textR.width / 2);
}
else { // (horizontalTextPosition == RIGHT)
textR.x = (iconR.width + gap);
}
/* labelR is the rectangle that contains iconR and textR.
* Move it to its proper position given the labelAlignment
* properties.
*
* To avoid actually allocating a Rectangle, Rectangle.union
* has been inlined below.
*/
int labelR_x = Math.min(iconR.x, textR.x);
int labelR_width = Math.max(iconR.x + iconR.width,
textR.x + textR.width) - labelR_x;
int labelR_y = Math.min(iconR.y, textR.y);
int labelR_height = Math.max(iconR.y + iconR.height,
textR.y + textR.height) - labelR_y;
int dx, dy;
if (verticalAlignment == TOP) {
dy = viewR.y - labelR_y;
}
else if (verticalAlignment == CENTER) {
dy = (viewR.y + (viewR.height / 2)) - (labelR_y + (labelR_height / 2));
}
else { // (verticalAlignment == BOTTOM)
dy = (viewR.y + viewR.height) - (labelR_y + labelR_height);
}
if (horizontalAlignment == LEFT) {
dx = viewR.x - labelR_x;
}
else if (horizontalAlignment == RIGHT) {
dx = (viewR.x + viewR.width) - (labelR_x + labelR_width);
}
else { // (horizontalAlignment == CENTER)
dx = (viewR.x + (viewR.width / 2)) -
(labelR_x + (labelR_width / 2));
}
/* Translate textR and glypyR by dx,dy.
*/
textR.x += dx;
textR.y += dy;
iconR.x += dx;
iconR.y += dy;
if (lsb < 0) {
// lsb is negative. Shift the x location so that the text is
// visually drawn at the right location.
textR.x -= lsb;
}
int maxIconY = viewR.height / 2;
Insets insets = c.getInsets();
int leftMostX = viewR.x;
int rightMostX = viewR.width;
rightMostX -= iconR.width;
if (horizontalTextPosition == SwingConstants.CENTER) {
if (viewR.width < textR.width) {
iconR.x = (leftMostX + rightMostX) / 2;
}
else {
int leftMostTextX = textR.x;
int rightMostTextX = textR.x + textR.width - iconR.width;
iconR.x = textR.x + (textR.width - iconR.width) / 2;
}
}
else if (iconR.x < leftMostX) {
textR.x += leftMostX - iconR.x;
iconR.x = leftMostX;
}
else if (iconR.x > rightMostX && horizontalAlignment != LEFT) {
iconR.x = rightMostX;
textR.x -= iconR.x - rightMostX;
}
if (insets != null) {
maxIconY -= (insets.bottom + insets.top) / 2;
}
if (icon != null) {
maxIconY -= icon.getIconHeight() / 2;
}
if (verticalAlignment == TOP) {
iconR.y = Math.min(maxIconY, iconR.y);
}
else if (verticalAlignment == BOTTOM) {
iconR.y = Math.max(maxIconY, iconR.y);
}
return text;
}
}
| true | true | private int internalPaintStyledText(StyledLabel label, Graphics g, int textX, int textY, int paintWidth) {
int labelHeight = label.getHeight();
if (labelHeight <= 0) {
labelHeight = Integer.MAX_VALUE;
}
Insets insets = label.getInsets();
if (insets != null) {
labelHeight -= insets.top + insets.bottom;
}
int leftMostX = 0;
if (insets != null) {
leftMostX += insets.left;
}
if (label.getIcon() != null) {
int horizontalTextPosition = label.getHorizontalTextPosition();
if ((horizontalTextPosition == SwingConstants.TRAILING && label.getComponentOrientation().isLeftToRight()) ||(horizontalTextPosition == SwingConstants.LEADING && !label.getComponentOrientation().isLeftToRight())) {
horizontalTextPosition = SwingConstants.RIGHT;
}
if (horizontalTextPosition == SwingConstants.RIGHT) {
leftMostX += label.getIcon().getIconWidth() + label.getIconTextGap();
}
}
int startX = textX < leftMostX ? leftMostX : textX;
int y;
int endX = paintWidth + startX;
int x = startX;
int mnemonicIndex = label.getDisplayedMnemonicIndex();
if (UIManager.getLookAndFeel() instanceof WindowsLookAndFeel &&
WindowsLookAndFeel.isMnemonicHidden()) {
mnemonicIndex = -1;
}
int charDisplayed = 0;
boolean displayMnemonic;
int mneIndex = 0;
Font font = getFont(label);
FontMetrics fm = label.getFontMetrics(font);
FontMetrics fm2;
FontMetrics nextFm2 = null;
int defaultFontSize = font.getSize();
synchronized (_styledTexts) {
String nextS;
int maxRowHeight = fm.getHeight();
int minStartY = fm.getAscent();
int horizontalAlignment = label.getHorizontalAlignment();
switch (horizontalAlignment) {
case LEADING:
horizontalAlignment = label.getComponentOrientation().isLeftToRight() ? LEFT : RIGHT;
break;
case TRAILING:
horizontalAlignment = label.getComponentOrientation().isLeftToRight() ? RIGHT : LEFT;
break;
}
for (StyledText styledText : _styledTexts) {
StyleRange style = styledText.styleRange;
int size = (style != null && (style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
maxRowHeight = Math.max(maxRowHeight, fm2.getHeight());
minStartY = Math.max(minStartY, fm2.getAscent());
}
}
boolean lineWrap = label.isLineWrap();
if (!lineWrap) {
for (StyledText styledText : _styledTexts) {
if (styledText.text.endsWith("\n")) {
lineWrap = true;
break;
}
}
}
if (lineWrap && textY < minStartY) {
textY = minStartY;
}
int nextRowStartIndex = 0;
int rowCount = 0;
int rowStartOffset = 0;
for (int i = 0; i < _styledTexts.size(); i++) {
StyledText styledText = _styledTexts.get(i);
StyleRange style = styledText.styleRange;
if (mnemonicIndex >= 0 && styledText.text.length() - nextRowStartIndex > mnemonicIndex - charDisplayed) {
displayMnemonic = true;
mneIndex = mnemonicIndex - charDisplayed;
}
else {
displayMnemonic = false;
}
charDisplayed += styledText.text.length() - nextRowStartIndex;
if (styledText.text.contains("\r") || styledText.text.contains("\n")) {
boolean lastRow = (label.getMaxRows() > 0 && rowCount >= label.getMaxRows() - 1) || textY + maxRowHeight + Math.max(0, label.getRowGap()) > labelHeight;
if (horizontalAlignment != LEFT && g != null) {
if (lastRow && i != _styledTexts.size() - 1) {
x += fm.stringWidth("...");
}
paintRow(label, g, startX, x, endX, textY, rowStartOffset, style.getStart() + styledText.text.length(), lastRow);
}
rowStartOffset = style.getStart();
nextRowStartIndex = 0;
nextFm2 = null;
if (!lastRow) {
rowStartOffset += style.getLength();
rowCount++;
x = startX;
textY += maxRowHeight + Math.max(0, label.getRowGap());
continue; // continue to paint "..." if lastRow is true
}
else if (horizontalAlignment != LEFT && g != null) {
break;
}
}
y = textY;
if (nextFm2 == null) {
int size = (style != null &&
(style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
}
else {
fm2 = fm;
}
}
else {
fm2 = nextFm2;
}
if (g != null) {
g.setFont(font);
}
boolean stop = false;
String s = styledText.text.substring(Math.min(nextRowStartIndex, styledText.text.length()));
if (s.contains("\r") || s.contains("\n")) {
s = "...";
stop = true;
}
int strWidth = fm2.stringWidth(s);
boolean wrapped = false;
int widthLeft = endX - x;
if (widthLeft < strWidth) {
if (label.isLineWrap() && ((label.getMaxRows() > 0 && rowCount < label.getMaxRows() - 1) || label.getMaxRows() <= 0) && y + maxRowHeight + Math.max(0, label.getRowGap()) <= labelHeight) {
wrapped = true;
int availLength = s.length() * widthLeft / strWidth + 1;
int nextWordStartIndex;
int nextRowStartIndexInSubString = 0;
boolean needBreak = false;
boolean needContinue = false;
int loopCount = 0;
do {
String subString = s.substring(0, Math.max(0, Math.min(availLength, s.length())));
int firstRowWordEndIndex = findFirstRowWordEndIndex(subString);
nextWordStartIndex = firstRowWordEndIndex < 0 ? 0 : findNextWordStartIndex(s, firstRowWordEndIndex);
if (firstRowWordEndIndex < 0) {
if (x != startX) {
boolean lastRow = label.getMaxRows() > 0 && rowCount >= label.getMaxRows() - 1;
if (horizontalAlignment != LEFT && g != null) {
paintRow(label, g, startX, x, endX, textY, rowStartOffset, style.getStart() + Math.min(nextRowStartIndex, styledText.text.length()), lastRow);
}
textY += maxRowHeight + Math.max(0, label.getRowGap());
x = startX;
i--;
rowCount++;
rowStartOffset = style.getStart() + Math.min(nextRowStartIndex, styledText.text.length());
if (lastRow) {
needBreak = true;
}
needContinue = true;
break;
}
else {
firstRowWordEndIndex = 0;
nextWordStartIndex = Math.min(s.length(), availLength);
}
}
nextRowStartIndexInSubString = firstRowWordEndIndex + 1;
String subStringThisRow = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(subStringThisRow);
if (strWidth > widthLeft) {
availLength = subString.length() * widthLeft / strWidth;
}
loopCount++;
if (loopCount > 15) {
System.err.println("Painting Styled Label Error: " + styledText);
break;
}
} while (strWidth > widthLeft && availLength > 0);
if (needBreak) {
break;
}
if (needContinue) {
continue;
}
while (nextRowStartIndexInSubString < nextWordStartIndex) {
strWidth += fm2.charWidth(s.charAt(nextRowStartIndexInSubString));
if (strWidth >= widthLeft) {
break;
}
nextRowStartIndexInSubString++;
}
s = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(s);
charDisplayed -= styledText.text.length() - nextRowStartIndex;
if (displayMnemonic) {
if (mnemonicIndex >= 0 && s.length() > mnemonicIndex - charDisplayed) {
displayMnemonic = true;
mneIndex = mnemonicIndex - charDisplayed;
}
else {
displayMnemonic = false;
}
}
charDisplayed += s.length();
nextRowStartIndex += nextRowStartIndexInSubString;
}
else {
// use this method to clip string
s = SwingUtilities.layoutCompoundLabel(label, fm2, s, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x, y, widthLeft, labelHeight), new Rectangle(), new Rectangle(), 0);
strWidth = fm2.stringWidth(s);
}
stop = !lineWrap || y + maxRowHeight + Math.max(0, label.getRowGap()) > labelHeight || (label.getMaxRows() > 0 && rowCount >= label.getMaxRows() - 1);
}
else if (lineWrap) {
nextRowStartIndex = 0;
}
else if (i < _styledTexts.size() - 1) {
StyledText nextStyledText = _styledTexts.get(i + 1);
String nextText = nextStyledText.text;
StyleRange nextStyle = nextStyledText.styleRange;
int size = (nextStyle != null &&
(nextStyle.isSuperscript() || nextStyle.isSubscript())) ? Math.round((float) defaultFontSize / nextStyle.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (nextStyle != null && ((nextStyle.getFontStyle() != -1 && font.getStyle() != nextStyle.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, nextStyle.getFontStyle() == -1 ? font.getStyle() : nextStyle.getFontStyle(), size);
nextFm2 = label.getFontMetrics(font);
}
else {
nextFm2 = fm;
}
if (nextFm2.stringWidth(nextText) > widthLeft - strWidth) {
nextS = SwingUtilities.layoutCompoundLabel(label, nextFm2, nextText, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x + strWidth, y, widthLeft - strWidth, labelHeight), new Rectangle(), new Rectangle(), 0);
if (nextFm2.stringWidth(nextS) > widthLeft - strWidth) {
s = SwingUtilities.layoutCompoundLabel(label, fm2, s, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x, y, strWidth - 1, labelHeight), new Rectangle(), new Rectangle(), 0);
strWidth = fm2.stringWidth(s);
stop = true;
}
}
}
// start of actual painting
if (rowCount > 0 && x == startX && s.startsWith(" ")) {
s = s.substring(1);
strWidth = fm2.stringWidth(s);
}
if (horizontalAlignment == LEFT && g != null) {
if (style != null && style.isSuperscript()) {
y -= fm.getHeight() - fm2.getHeight();
}
if (style != null && style.getBackgroundColor() != null) {
g.setColor(style.getBackgroundColor());
g.fillRect(x, y - fm2.getHeight(), strWidth, fm2.getHeight() + 4);
}
Color textColor = (style != null && !label.isIgnoreColorSettings() && style.getFontColor() != null) ? style.getFontColor() : label.getForeground();
if (!label.isEnabled()) {
textColor = UIDefaultsLookup.getColor("Label.disabledForeground");
}
g.setColor(textColor);
if (displayMnemonic) {
JideSwingUtilities.drawStringUnderlineCharAt(label, g, s, mneIndex, x, y);
}
else {
JideSwingUtilities.drawString(label, g, s, x, y);
}
if (style != null) {
Stroke oldStroke = ((Graphics2D) g).getStroke();
if (style.getLineStroke() != null) {
((Graphics2D) g).setStroke(style.getLineStroke());
}
if (!label.isIgnoreColorSettings() && style.getLineColor() != null) {
g.setColor(style.getLineColor());
}
if (style.isStrikethrough()) {
int lineY = y + (fm2.getDescent() - fm2.getAscent()) / 2;
g.drawLine(x, lineY, x + strWidth - 1, lineY);
}
if (style.isDoublestrikethrough()) {
int lineY = y + (fm2.getDescent() - fm2.getAscent()) / 2;
g.drawLine(x, lineY - 1, x + strWidth - 1, lineY - 1);
g.drawLine(x, lineY + 1, x + strWidth - 1, lineY + 1);
}
if (style.isUnderlined()) {
int lineY = y + 1;
g.drawLine(x, lineY, x + strWidth - 1, lineY);
}
if (style.isDotted()) {
int dotY = y + 1;
for (int dotX = x; dotX < x + strWidth; dotX += 4) {
g.drawRect(dotX, dotY, 1, 1);
}
}
if (style.isWaved()) {
int waveY = y + 1;
for (int waveX = x; waveX < x + strWidth; waveX += 4) {
if (waveX + 2 <= x + strWidth - 1)
g.drawLine(waveX, waveY + 2, waveX + 2, waveY);
if (waveX + 4 <= x + strWidth - 1)
g.drawLine(waveX + 3, waveY + 1, waveX + 4, waveY + 2);
}
}
if (style.getLineStroke() != null) {
((Graphics2D) g).setStroke(oldStroke);
}
}
}
// end of actual painting
if (stop) {
if (horizontalAlignment != LEFT && g != null) {
x += strWidth;
paintRow(label, g, startX, x, endX, textY, rowStartOffset, label.getText().length(), true);
}
label.setTruncated(true);
break;
}
if (wrapped) {
boolean lastRow = (label.getMaxRows() > 0 && rowCount >= label.getMaxRows() - 1) || textY + maxRowHeight + Math.max(0, label.getRowGap()) > labelHeight;
if (horizontalAlignment != LEFT && g != null) {
x += strWidth;
paintRow(label, g, startX, x, endX, textY, rowStartOffset, style.getStart() + Math.min(nextRowStartIndex, styledText.text.length()), lastRow);
}
textY += maxRowHeight + Math.max(0, label.getRowGap());
x = startX;
i--;
rowCount++;
rowStartOffset = style.getStart() + Math.min(nextRowStartIndex, styledText.text.length());
if (lastRow) {
break;
}
}
else {
x += strWidth;
}
if (i == _styledTexts.size() - 1) {
if (horizontalAlignment != LEFT && g != null) {
paintRow(label, g, startX, x, endX, textY, rowStartOffset, -1, true);
}
}
}
return (int) Math.ceil((double) textY / maxRowHeight);
}
}
| private int internalPaintStyledText(StyledLabel label, Graphics g, int textX, int textY, int paintWidth) {
int labelHeight = label.getHeight();
if (labelHeight <= 0) {
labelHeight = Integer.MAX_VALUE;
}
Insets insets = label.getInsets();
if (insets != null) {
labelHeight -= insets.top + insets.bottom;
}
int leftMostX = 0;
if (insets != null) {
leftMostX += insets.left;
}
if (label.getIcon() != null) {
int horizontalTextPosition = label.getHorizontalTextPosition();
if ((horizontalTextPosition == SwingConstants.TRAILING && label.getComponentOrientation().isLeftToRight()) ||(horizontalTextPosition == SwingConstants.LEADING && !label.getComponentOrientation().isLeftToRight())) {
horizontalTextPosition = SwingConstants.RIGHT;
}
if (horizontalTextPosition == SwingConstants.RIGHT) {
leftMostX += label.getIcon().getIconWidth() + label.getIconTextGap();
}
}
int startX = textX < leftMostX ? leftMostX : textX;
int y;
int endX = paintWidth + startX;
int x = startX;
int mnemonicIndex = label.getDisplayedMnemonicIndex();
if (UIManager.getLookAndFeel() instanceof WindowsLookAndFeel &&
WindowsLookAndFeel.isMnemonicHidden()) {
mnemonicIndex = -1;
}
int charDisplayed = 0;
boolean displayMnemonic;
int mneIndex = 0;
Font font = getFont(label);
FontMetrics fm = label.getFontMetrics(font);
FontMetrics fm2;
FontMetrics nextFm2 = null;
int defaultFontSize = font.getSize();
synchronized (_styledTexts) {
String nextS;
int maxRowHeight = fm.getHeight();
int minStartY = fm.getAscent();
int horizontalAlignment = label.getHorizontalAlignment();
switch (horizontalAlignment) {
case LEADING:
horizontalAlignment = label.getComponentOrientation().isLeftToRight() ? LEFT : RIGHT;
break;
case TRAILING:
horizontalAlignment = label.getComponentOrientation().isLeftToRight() ? RIGHT : LEFT;
break;
}
for (StyledText styledText : _styledTexts) {
StyleRange style = styledText.styleRange;
int size = (style != null && (style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
maxRowHeight = Math.max(maxRowHeight, fm2.getHeight());
minStartY = Math.max(minStartY, fm2.getAscent());
}
}
boolean lineWrap = label.isLineWrap();
if (!lineWrap) {
for (StyledText styledText : _styledTexts) {
if (styledText.text.endsWith("\n")) {
lineWrap = true;
break;
}
}
}
if (lineWrap && textY < minStartY) {
textY = minStartY;
}
int nextRowStartIndex = 0;
int rowCount = 0;
int rowStartOffset = 0;
for (int i = 0; i < _styledTexts.size(); i++) {
StyledText styledText = _styledTexts.get(i);
StyleRange style = styledText.styleRange;
if (mnemonicIndex >= 0 && styledText.text.length() - nextRowStartIndex > mnemonicIndex - charDisplayed) {
displayMnemonic = true;
mneIndex = mnemonicIndex - charDisplayed;
}
else {
displayMnemonic = false;
}
charDisplayed += styledText.text.length() - nextRowStartIndex;
if (styledText.text.contains("\r") || styledText.text.contains("\n")) {
boolean lastRow = (label.getMaxRows() > 0 && rowCount >= label.getMaxRows() - 1) || textY + maxRowHeight + Math.max(0, label.getRowGap()) > labelHeight;
if (horizontalAlignment != LEFT && g != null) {
if (lastRow && i != _styledTexts.size() - 1) {
x += fm.stringWidth("...");
}
paintRow(label, g, startX, x, endX, textY, rowStartOffset, style.getStart() + styledText.text.length(), lastRow);
}
rowStartOffset = style.getStart();
nextRowStartIndex = 0;
nextFm2 = null;
if (!lastRow) {
rowStartOffset += style.getLength();
rowCount++;
x = startX;
textY += maxRowHeight + Math.max(0, label.getRowGap());
continue; // continue to paint "..." if lastRow is true
}
else if (horizontalAlignment != LEFT && g != null) {
break;
}
}
y = textY;
if (nextFm2 == null) {
int size = (style != null &&
(style.isSuperscript() || style.isSubscript())) ? Math.round((float) defaultFontSize / style.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (style != null && ((style.getFontStyle() != -1 && font.getStyle() != style.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, style.getFontStyle() == -1 ? font.getStyle() : style.getFontStyle(), size);
fm2 = label.getFontMetrics(font);
}
else {
fm2 = fm;
}
}
else {
fm2 = nextFm2;
}
if (g != null) {
g.setFont(font);
}
boolean stop = false;
String s = styledText.text.substring(Math.min(nextRowStartIndex, styledText.text.length()));
if (s.contains("\r") || s.contains("\n")) {
s = "...";
stop = true;
}
int strWidth = fm2.stringWidth(s);
boolean wrapped = false;
int widthLeft = endX - x;
if (widthLeft < strWidth && widthLeft >= 0) {
if (label.isLineWrap() && ((label.getMaxRows() > 0 && rowCount < label.getMaxRows() - 1) || label.getMaxRows() <= 0) && y + maxRowHeight + Math.max(0, label.getRowGap()) <= labelHeight) {
wrapped = true;
int availLength = s.length() * widthLeft / strWidth + 1;
int nextWordStartIndex;
int nextRowStartIndexInSubString = 0;
boolean needBreak = false;
boolean needContinue = false;
int loopCount = 0;
do {
String subString = s.substring(0, Math.max(0, Math.min(availLength, s.length())));
int firstRowWordEndIndex = findFirstRowWordEndIndex(subString);
nextWordStartIndex = firstRowWordEndIndex < 0 ? 0 : findNextWordStartIndex(s, firstRowWordEndIndex);
if (firstRowWordEndIndex < 0) {
if (x != startX) {
boolean lastRow = label.getMaxRows() > 0 && rowCount >= label.getMaxRows() - 1;
if (horizontalAlignment != LEFT && g != null) {
paintRow(label, g, startX, x, endX, textY, rowStartOffset, style.getStart() + Math.min(nextRowStartIndex, styledText.text.length()), lastRow);
}
textY += maxRowHeight + Math.max(0, label.getRowGap());
x = startX;
i--;
rowCount++;
rowStartOffset = style.getStart() + Math.min(nextRowStartIndex, styledText.text.length());
if (lastRow) {
needBreak = true;
}
needContinue = true;
break;
}
else {
firstRowWordEndIndex = 0;
nextWordStartIndex = Math.min(s.length(), availLength);
}
}
nextRowStartIndexInSubString = firstRowWordEndIndex + 1;
String subStringThisRow = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(subStringThisRow);
if (strWidth > widthLeft) {
availLength = subString.length() * widthLeft / strWidth;
}
loopCount++;
if (loopCount > 15) {
System.err.println("Painting Styled Label Error: " + styledText);
break;
}
} while (strWidth > widthLeft && availLength > 0);
if (needBreak) {
break;
}
if (needContinue) {
continue;
}
while (nextRowStartIndexInSubString < nextWordStartIndex) {
strWidth += fm2.charWidth(s.charAt(nextRowStartIndexInSubString));
if (strWidth >= widthLeft) {
break;
}
nextRowStartIndexInSubString++;
}
s = s.substring(0, Math.min(nextRowStartIndexInSubString, s.length()));
strWidth = fm2.stringWidth(s);
charDisplayed -= styledText.text.length() - nextRowStartIndex;
if (displayMnemonic) {
if (mnemonicIndex >= 0 && s.length() > mnemonicIndex - charDisplayed) {
displayMnemonic = true;
mneIndex = mnemonicIndex - charDisplayed;
}
else {
displayMnemonic = false;
}
}
charDisplayed += s.length();
nextRowStartIndex += nextRowStartIndexInSubString;
}
else {
// use this method to clip string
s = SwingUtilities.layoutCompoundLabel(label, fm2, s, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x, y, widthLeft, labelHeight), new Rectangle(), new Rectangle(), 0);
strWidth = fm2.stringWidth(s);
}
stop = !lineWrap || y + maxRowHeight + Math.max(0, label.getRowGap()) > labelHeight || (label.getMaxRows() > 0 && rowCount >= label.getMaxRows() - 1);
}
else if (lineWrap) {
nextRowStartIndex = 0;
}
else if (i < _styledTexts.size() - 1) {
StyledText nextStyledText = _styledTexts.get(i + 1);
String nextText = nextStyledText.text;
StyleRange nextStyle = nextStyledText.styleRange;
int size = (nextStyle != null &&
(nextStyle.isSuperscript() || nextStyle.isSubscript())) ? Math.round((float) defaultFontSize / nextStyle.getFontShrinkRatio()) : defaultFontSize;
font = getFont(label);
if (nextStyle != null && ((nextStyle.getFontStyle() != -1 && font.getStyle() != nextStyle.getFontStyle()) || font.getSize() != size)) {
font = FontUtils.getCachedDerivedFont(font, nextStyle.getFontStyle() == -1 ? font.getStyle() : nextStyle.getFontStyle(), size);
nextFm2 = label.getFontMetrics(font);
}
else {
nextFm2 = fm;
}
if (nextFm2.stringWidth(nextText) > widthLeft - strWidth) {
nextS = SwingUtilities.layoutCompoundLabel(label, nextFm2, nextText, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x + strWidth, y, widthLeft - strWidth, labelHeight), new Rectangle(), new Rectangle(), 0);
if (nextFm2.stringWidth(nextS) > widthLeft - strWidth) {
s = SwingUtilities.layoutCompoundLabel(label, fm2, s, null, label.getVerticalAlignment(), label.getHorizontalAlignment(),
label.getVerticalTextPosition(), label.getHorizontalTextPosition(), new Rectangle(x, y, strWidth - 1, labelHeight), new Rectangle(), new Rectangle(), 0);
strWidth = fm2.stringWidth(s);
stop = true;
}
}
}
// start of actual painting
if (rowCount > 0 && x == startX && s.startsWith(" ")) {
s = s.substring(1);
strWidth = fm2.stringWidth(s);
}
if (horizontalAlignment == LEFT && g != null) {
if (style != null && style.isSuperscript()) {
y -= fm.getHeight() - fm2.getHeight();
}
if (style != null && style.getBackgroundColor() != null) {
g.setColor(style.getBackgroundColor());
g.fillRect(x, y - fm2.getHeight(), strWidth, fm2.getHeight() + 4);
}
Color textColor = (style != null && !label.isIgnoreColorSettings() && style.getFontColor() != null) ? style.getFontColor() : label.getForeground();
if (!label.isEnabled()) {
textColor = UIDefaultsLookup.getColor("Label.disabledForeground");
}
g.setColor(textColor);
if (displayMnemonic) {
JideSwingUtilities.drawStringUnderlineCharAt(label, g, s, mneIndex, x, y);
}
else {
JideSwingUtilities.drawString(label, g, s, x, y);
}
if (style != null) {
Stroke oldStroke = ((Graphics2D) g).getStroke();
if (style.getLineStroke() != null) {
((Graphics2D) g).setStroke(style.getLineStroke());
}
if (!label.isIgnoreColorSettings() && style.getLineColor() != null) {
g.setColor(style.getLineColor());
}
if (style.isStrikethrough()) {
int lineY = y + (fm2.getDescent() - fm2.getAscent()) / 2;
g.drawLine(x, lineY, x + strWidth - 1, lineY);
}
if (style.isDoublestrikethrough()) {
int lineY = y + (fm2.getDescent() - fm2.getAscent()) / 2;
g.drawLine(x, lineY - 1, x + strWidth - 1, lineY - 1);
g.drawLine(x, lineY + 1, x + strWidth - 1, lineY + 1);
}
if (style.isUnderlined()) {
int lineY = y + 1;
g.drawLine(x, lineY, x + strWidth - 1, lineY);
}
if (style.isDotted()) {
int dotY = y + 1;
for (int dotX = x; dotX < x + strWidth; dotX += 4) {
g.drawRect(dotX, dotY, 1, 1);
}
}
if (style.isWaved()) {
int waveY = y + 1;
for (int waveX = x; waveX < x + strWidth; waveX += 4) {
if (waveX + 2 <= x + strWidth - 1)
g.drawLine(waveX, waveY + 2, waveX + 2, waveY);
if (waveX + 4 <= x + strWidth - 1)
g.drawLine(waveX + 3, waveY + 1, waveX + 4, waveY + 2);
}
}
if (style.getLineStroke() != null) {
((Graphics2D) g).setStroke(oldStroke);
}
}
}
// end of actual painting
if (stop) {
if (horizontalAlignment != LEFT && g != null) {
x += strWidth;
paintRow(label, g, startX, x, endX, textY, rowStartOffset, label.getText().length(), true);
}
label.setTruncated(true);
break;
}
if (wrapped) {
boolean lastRow = (label.getMaxRows() > 0 && rowCount >= label.getMaxRows() - 1) || textY + maxRowHeight + Math.max(0, label.getRowGap()) > labelHeight;
if (horizontalAlignment != LEFT && g != null) {
x += strWidth;
paintRow(label, g, startX, x, endX, textY, rowStartOffset, style.getStart() + Math.min(nextRowStartIndex, styledText.text.length()), lastRow);
}
textY += maxRowHeight + Math.max(0, label.getRowGap());
x = startX;
i--;
rowCount++;
rowStartOffset = style.getStart() + Math.min(nextRowStartIndex, styledText.text.length());
if (lastRow) {
break;
}
}
else {
x += strWidth;
}
if (i == _styledTexts.size() - 1) {
if (horizontalAlignment != LEFT && g != null) {
paintRow(label, g, startX, x, endX, textY, rowStartOffset, -1, true);
}
}
}
return (int) Math.ceil((double) textY / maxRowHeight);
}
}
|
diff --git a/cprprime/src/edu/psu/iam/cpr/utility/UiFieldTypesLoader.java b/cprprime/src/edu/psu/iam/cpr/utility/UiFieldTypesLoader.java
index 31b7f63..4d4db52 100755
--- a/cprprime/src/edu/psu/iam/cpr/utility/UiFieldTypesLoader.java
+++ b/cprprime/src/edu/psu/iam/cpr/utility/UiFieldTypesLoader.java
@@ -1,68 +1,68 @@
package edu.psu.iam.cpr.utility;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Date;
import org.hibernate.Query;
import org.hibernate.Session;
import edu.psu.iam.cpr.core.database.Database;
import edu.psu.iam.cpr.core.database.SessionFactoryUtil;
import edu.psu.iam.cpr.utility.beans.UiFieldTypes;
public class UiFieldTypesLoader implements BeanLoader {
@Override
public void loadTable(Database db, String primeDirectory, String tableName) {
BufferedReader bufferedReader = null;
try {
Date d = new Date();
String requestor = "SYSTEM";
db.openSession(SessionFactoryUtil.getSessionFactory());
Session session = db.getSession();
// Remove all of the records from the database table.
String sqlQuery = "delete from " + tableName;
Query query = session.createQuery(sqlQuery);
query.executeUpdate();
// Read in the first record containing the column headers.
bufferedReader = new BufferedReader(new FileReader(primeDirectory + System.getProperty("file.separator") + tableName));
String[] columns = bufferedReader.readLine().split("[|]");
String line;
// ui_field_types
while ((line = bufferedReader.readLine()) != null) {
String[] fields = line.split("[|]");
UiFieldTypes bean = new UiFieldTypes();
bean.setCreatedBy(requestor);
bean.setCreatedOn(d);
bean.setLastUpdateBy(requestor);
bean.setLastUpdateOn(d);
for (int i = 0; i < columns.length; ++i) {
- if (columns[i].equals("ui_field_types")) {
+ if (columns[i].equals("ui_field_type")) {
bean.setUiFieldType(fields[i]);
}
}
session.save(bean);
}
db.closeSession();
}
catch (Exception e) {
db.rollbackSession();
e.printStackTrace();
}
finally {
try {
bufferedReader.close();
}
catch (Exception e) {
}
}
}
}
| true | true | public void loadTable(Database db, String primeDirectory, String tableName) {
BufferedReader bufferedReader = null;
try {
Date d = new Date();
String requestor = "SYSTEM";
db.openSession(SessionFactoryUtil.getSessionFactory());
Session session = db.getSession();
// Remove all of the records from the database table.
String sqlQuery = "delete from " + tableName;
Query query = session.createQuery(sqlQuery);
query.executeUpdate();
// Read in the first record containing the column headers.
bufferedReader = new BufferedReader(new FileReader(primeDirectory + System.getProperty("file.separator") + tableName));
String[] columns = bufferedReader.readLine().split("[|]");
String line;
// ui_field_types
while ((line = bufferedReader.readLine()) != null) {
String[] fields = line.split("[|]");
UiFieldTypes bean = new UiFieldTypes();
bean.setCreatedBy(requestor);
bean.setCreatedOn(d);
bean.setLastUpdateBy(requestor);
bean.setLastUpdateOn(d);
for (int i = 0; i < columns.length; ++i) {
if (columns[i].equals("ui_field_types")) {
bean.setUiFieldType(fields[i]);
}
}
session.save(bean);
}
db.closeSession();
}
catch (Exception e) {
db.rollbackSession();
e.printStackTrace();
}
finally {
try {
bufferedReader.close();
}
catch (Exception e) {
}
}
}
| public void loadTable(Database db, String primeDirectory, String tableName) {
BufferedReader bufferedReader = null;
try {
Date d = new Date();
String requestor = "SYSTEM";
db.openSession(SessionFactoryUtil.getSessionFactory());
Session session = db.getSession();
// Remove all of the records from the database table.
String sqlQuery = "delete from " + tableName;
Query query = session.createQuery(sqlQuery);
query.executeUpdate();
// Read in the first record containing the column headers.
bufferedReader = new BufferedReader(new FileReader(primeDirectory + System.getProperty("file.separator") + tableName));
String[] columns = bufferedReader.readLine().split("[|]");
String line;
// ui_field_types
while ((line = bufferedReader.readLine()) != null) {
String[] fields = line.split("[|]");
UiFieldTypes bean = new UiFieldTypes();
bean.setCreatedBy(requestor);
bean.setCreatedOn(d);
bean.setLastUpdateBy(requestor);
bean.setLastUpdateOn(d);
for (int i = 0; i < columns.length; ++i) {
if (columns[i].equals("ui_field_type")) {
bean.setUiFieldType(fields[i]);
}
}
session.save(bean);
}
db.closeSession();
}
catch (Exception e) {
db.rollbackSession();
e.printStackTrace();
}
finally {
try {
bufferedReader.close();
}
catch (Exception e) {
}
}
}
|
diff --git a/src/jDistsim/utils/logging/handlers/FileLoggerHandler.java b/src/jDistsim/utils/logging/handlers/FileLoggerHandler.java
index a5c1278..82c6ccb 100644
--- a/src/jDistsim/utils/logging/handlers/FileLoggerHandler.java
+++ b/src/jDistsim/utils/logging/handlers/FileLoggerHandler.java
@@ -1,79 +1,77 @@
package jDistsim.utils.logging.handlers;
import jDistsim.utils.logging.LogMessage;
import jDistsim.utils.logging.Logger;
import jDistsim.utils.logging.formatters.DefaultLoggerFormatter;
import jDistsim.utils.logging.formatters.ILoggerFormatter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.UUID;
/**
* Author: Jirka Pénzeš
* Date: 23.9.12
* Time: 21:53
*/
public class FileLoggerHandler implements ILoggerHandler {
private String fileName;
private String directory;
private ILoggerFormatter loggerFormatter;
public FileLoggerHandler() {
this(createFileName());
}
public FileLoggerHandler(String fileName) {
this(fileName, "");
}
public FileLoggerHandler(String fileName, String directory) {
this(new DefaultLoggerFormatter(), fileName, directory);
}
public FileLoggerHandler(ILoggerFormatter loggerFormatter) {
this(loggerFormatter, createFileName());
}
public FileLoggerHandler(ILoggerFormatter loggerFormatter, String fileName) {
this(loggerFormatter, fileName, "");
}
public FileLoggerHandler(ILoggerFormatter loggerFormatter, String fileName, String directory) {
this.loggerFormatter = loggerFormatter;
this.fileName = fileName;
this.directory = directory;
}
@Override
public void publish(LogMessage logMessage) {
- PrintWriter output = null;
try {
File file;
file = new File(fileName);
if (!file.exists())
file.createNewFile();
- output = new PrintWriter(new FileWriter(file));
+ PrintWriter output = new PrintWriter(new FileWriter(file));
output.println(loggerFormatter.applyFormat(logMessage));
output.close();
} catch (IOException exception) {
Logger.log(exception);
} finally {
- output.close();
}
}
private static String createFileName() {
Date currentDate = new Date();
UUID uuid = UUID.randomUUID();
String guid = uuid.toString();
return guid + ".log";
}
}
| false | true | public void publish(LogMessage logMessage) {
PrintWriter output = null;
try {
File file;
file = new File(fileName);
if (!file.exists())
file.createNewFile();
output = new PrintWriter(new FileWriter(file));
output.println(loggerFormatter.applyFormat(logMessage));
output.close();
} catch (IOException exception) {
Logger.log(exception);
} finally {
output.close();
}
}
| public void publish(LogMessage logMessage) {
try {
File file;
file = new File(fileName);
if (!file.exists())
file.createNewFile();
PrintWriter output = new PrintWriter(new FileWriter(file));
output.println(loggerFormatter.applyFormat(logMessage));
output.close();
} catch (IOException exception) {
Logger.log(exception);
} finally {
}
}
|
diff --git a/src/com/ftwinston/Killer/CraftBukkit/CraftBukkitAccess.java b/src/com/ftwinston/Killer/CraftBukkit/CraftBukkitAccess.java
index 56ba371..11e9e06 100644
--- a/src/com/ftwinston/Killer/CraftBukkit/CraftBukkitAccess.java
+++ b/src/com/ftwinston/Killer/CraftBukkit/CraftBukkitAccess.java
@@ -1,74 +1,74 @@
package com.ftwinston.Killer.CraftBukkit;
import java.lang.reflect.Field;
import java.util.HashMap;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.Plugin;
// a holder for everything that dives into the versioned CraftBukkit code that will break with every minecraft update
public abstract class CraftBukkitAccess
{
public static CraftBukkitAccess createCorrectVersion(Plugin plugin)
{
// Get full package string of CraftServer class, then extract the version name from that
// org.bukkit.craftbukkit.versionstring (or for pre-refactor, just org.bukkit.craftbukkit
String packageName = plugin.getServer().getClass().getPackage().getName();
String version = packageName.substring(packageName.lastIndexOf('.') + 1);
- if ( version.equals("v1_4_7"))
+ if ( version.equals("v1_4_R1"))
return new v1_4_7(plugin);
if ( version.equals("v1_4_6"))
return new v1_4_6(plugin);
if ( version.equals("v1_4_5"))
return new v1_4_5(plugin);
if ( version.equals("craftbukkit"))
plugin.getLogger().warning("Killer minecraft requires at least CraftBukkit 1.4.5-R1.0 to function. Sorry.");
else
plugin.getLogger().warning("This version of Killer minecraft is not compatible with your server's version of CraftBukkit! (" + version + ") Please download a newer version of Killer minecraft.");
return null;
}
protected CraftBukkitAccess(Plugin plugin) { this.plugin = plugin; }
protected Plugin plugin;
@SuppressWarnings("rawtypes")
protected HashMap regionfiles;
protected Field rafField;
public abstract String getDefaultLevelName();
public abstract YamlConfiguration getBukkitConfiguration();
public abstract void saveBukkitConfiguration(YamlConfiguration configuration);
public abstract String getServerProperty(String name, String defaultVal);
public abstract void setServerProperty(String name, String value);
public abstract void saveServerPropertiesFile();
public abstract void sendForScoreboard(Player viewer, String name, boolean show);
public abstract void sendForScoreboard(Player viewer, Player other, boolean show);
public abstract void forceRespawn(final Player player);
public abstract void bindRegionFiles();
public void unbindRegionFiles()
{
regionfiles = null;
rafField = null;
}
public abstract boolean clearWorldReference(String worldName);
public abstract void forceUnloadWorld(World world);
public abstract void accountForDefaultWorldDeletion(World newDefault);
public abstract World createWorld(org.bukkit.WorldType type, Environment env, String name, long seed, ChunkGenerator generator, String generatorSettings, boolean generateStructures);
public abstract Location findNearestNetherFortress(Location loc);
public abstract boolean createFlyingEnderEye(Player player, Location target);
}
| true | true | public static CraftBukkitAccess createCorrectVersion(Plugin plugin)
{
// Get full package string of CraftServer class, then extract the version name from that
// org.bukkit.craftbukkit.versionstring (or for pre-refactor, just org.bukkit.craftbukkit
String packageName = plugin.getServer().getClass().getPackage().getName();
String version = packageName.substring(packageName.lastIndexOf('.') + 1);
if ( version.equals("v1_4_7"))
return new v1_4_7(plugin);
if ( version.equals("v1_4_6"))
return new v1_4_6(plugin);
if ( version.equals("v1_4_5"))
return new v1_4_5(plugin);
if ( version.equals("craftbukkit"))
plugin.getLogger().warning("Killer minecraft requires at least CraftBukkit 1.4.5-R1.0 to function. Sorry.");
else
plugin.getLogger().warning("This version of Killer minecraft is not compatible with your server's version of CraftBukkit! (" + version + ") Please download a newer version of Killer minecraft.");
return null;
}
| public static CraftBukkitAccess createCorrectVersion(Plugin plugin)
{
// Get full package string of CraftServer class, then extract the version name from that
// org.bukkit.craftbukkit.versionstring (or for pre-refactor, just org.bukkit.craftbukkit
String packageName = plugin.getServer().getClass().getPackage().getName();
String version = packageName.substring(packageName.lastIndexOf('.') + 1);
if ( version.equals("v1_4_R1"))
return new v1_4_7(plugin);
if ( version.equals("v1_4_6"))
return new v1_4_6(plugin);
if ( version.equals("v1_4_5"))
return new v1_4_5(plugin);
if ( version.equals("craftbukkit"))
plugin.getLogger().warning("Killer minecraft requires at least CraftBukkit 1.4.5-R1.0 to function. Sorry.");
else
plugin.getLogger().warning("This version of Killer minecraft is not compatible with your server's version of CraftBukkit! (" + version + ") Please download a newer version of Killer minecraft.");
return null;
}
|
diff --git a/src/java/org/infoglue/deliver/util/SelectiveLivePublicationThread.java b/src/java/org/infoglue/deliver/util/SelectiveLivePublicationThread.java
index b0573f296..5ac012ac6 100755
--- a/src/java/org/infoglue/deliver/util/SelectiveLivePublicationThread.java
+++ b/src/java/org/infoglue/deliver/util/SelectiveLivePublicationThread.java
@@ -1,348 +1,351 @@
/* ===============================================================================
*
* Part of the InfoGlue Content Management Platform (www.infoglue.org)
*
* ===============================================================================
*
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2, as published by the
* Free Software Foundation. See the file LICENSE.html for more information.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
* Place, Suite 330 / Boston, MA 02111-1307 / USA.
*
* ===============================================================================
*/
package org.infoglue.deliver.util;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import org.exolab.castor.jdo.Database;
import org.infoglue.cms.controllers.kernel.impl.simple.CastorDatabaseService;
import org.infoglue.cms.controllers.kernel.impl.simple.ContentController;
import org.infoglue.cms.controllers.kernel.impl.simple.ContentVersionController;
import org.infoglue.cms.controllers.kernel.impl.simple.PublicationController;
import org.infoglue.cms.controllers.kernel.impl.simple.SiteNodeController;
import org.infoglue.cms.controllers.kernel.impl.simple.SiteNodeVersionController;
import org.infoglue.cms.entities.content.Content;
import org.infoglue.cms.entities.content.ContentVersion;
import org.infoglue.cms.entities.content.ContentVersionVO;
import org.infoglue.cms.entities.content.impl.simple.ContentImpl;
import org.infoglue.cms.entities.content.impl.simple.ContentVersionImpl;
import org.infoglue.cms.entities.content.impl.simple.DigitalAssetImpl;
import org.infoglue.cms.entities.content.impl.simple.MediumContentImpl;
import org.infoglue.cms.entities.content.impl.simple.MediumDigitalAssetImpl;
import org.infoglue.cms.entities.content.impl.simple.SmallContentImpl;
import org.infoglue.cms.entities.content.impl.simple.SmallContentVersionImpl;
import org.infoglue.cms.entities.content.impl.simple.SmallDigitalAssetImpl;
import org.infoglue.cms.entities.content.impl.simple.SmallishContentImpl;
import org.infoglue.cms.entities.management.impl.simple.AvailableServiceBindingImpl;
import org.infoglue.cms.entities.management.impl.simple.GroupImpl;
import org.infoglue.cms.entities.management.impl.simple.RoleImpl;
import org.infoglue.cms.entities.management.impl.simple.SmallAvailableServiceBindingImpl;
import org.infoglue.cms.entities.management.impl.simple.SystemUserImpl;
import org.infoglue.cms.entities.publishing.PublicationDetailVO;
import org.infoglue.cms.entities.publishing.impl.simple.PublicationDetailImpl;
import org.infoglue.cms.entities.publishing.impl.simple.PublicationImpl;
import org.infoglue.cms.entities.structure.SiteNodeVO;
import org.infoglue.cms.entities.structure.SiteNodeVersion;
import org.infoglue.cms.entities.structure.impl.simple.SiteNodeImpl;
import org.infoglue.cms.entities.structure.impl.simple.SmallSiteNodeImpl;
import org.infoglue.cms.util.CmsPropertyHandler;
import org.infoglue.cms.util.NotificationMessage;
import org.infoglue.deliver.applications.databeans.CacheEvictionBean;
import org.infoglue.deliver.controllers.kernel.impl.simple.DigitalAssetDeliveryController;
/**
* @author mattias
*
* This is a selective publication thread. What that means is that it only throws
* away objects and pages in the cache which are affected. Experimental for now.
*/
public class SelectiveLivePublicationThread extends PublicationThread
{
public final static Logger logger = Logger.getLogger(SelectiveLivePublicationThread.class.getName());
private List cacheEvictionBeans = new ArrayList();
public SelectiveLivePublicationThread()
{
}
public List getCacheEvictionBeans()
{
return cacheEvictionBeans;
}
public void run()
{
logger.info("Run in SelectiveLivePublicationThread....");
int publicationDelay = 5000;
String publicationThreadDelay = CmsPropertyHandler.getPublicationThreadDelay();
if(publicationThreadDelay != null && !publicationThreadDelay.equalsIgnoreCase("") && publicationThreadDelay.indexOf("publicationThreadDelay") == -1)
publicationDelay = Integer.parseInt(publicationThreadDelay);
logger.info("\n\n\nSleeping " + publicationDelay + "ms.\n\n\n");
try
{
sleep(publicationDelay);
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
logger.info("cacheEvictionBeans.size:" + cacheEvictionBeans.size() + ":" + RequestAnalyser.getRequestAnalyser().getBlockRequests());
if(cacheEvictionBeans.size() > 0)
{
try
{
logger.info("setting block");
RequestAnalyser.getRequestAnalyser().setBlockRequests(true);
Iterator i = cacheEvictionBeans.iterator();
while(i.hasNext())
{
CacheEvictionBean cacheEvictionBean = (CacheEvictionBean)i.next();
String className = cacheEvictionBean.getClassName();
String objectId = cacheEvictionBean.getObjectId();
String objectName = cacheEvictionBean.getObjectName();
String typeId = cacheEvictionBean.getTypeId();
logger.info("className:" + className);
logger.info("objectId:" + objectId);
logger.info("objectName:" + objectName);
logger.info("typeId:" + typeId);
boolean isDependsClass = false;
if(className != null && className.equalsIgnoreCase(PublicationDetailImpl.class.getName()))
isDependsClass = true;
- CacheController.clearCaches(className, objectId, null);
+ if(!typeId.equalsIgnoreCase("" + NotificationMessage.SYSTEM))
+ CacheController.clearCaches(className, objectId, null);
logger.info("Updating className with id:" + className + ":" + objectId);
if(className != null && !typeId.equalsIgnoreCase("" + NotificationMessage.SYSTEM))
{
Class type = Class.forName(className);
if(!isDependsClass && className.equalsIgnoreCase(SystemUserImpl.class.getName()) || className.equalsIgnoreCase(RoleImpl.class.getName()) || className.equalsIgnoreCase(GroupImpl.class.getName()))
{
Object[] ids = {objectId};
CacheController.clearCache(type, ids);
}
else if(!isDependsClass)
{
Object[] ids = {new Integer(objectId)};
CacheController.clearCache(type, ids);
}
//If it's an contentVersion we should delete all images it might have generated from attributes.
if(Class.forName(className).getName().equals(ContentImpl.class.getName()))
{
logger.info("We clear all small contents as well " + objectId);
Class typesExtra = SmallContentImpl.class;
Object[] idsExtra = {new Integer(objectId)};
CacheController.clearCache(typesExtra, idsExtra);
logger.info("We clear all small contents as well " + objectId);
Class typesExtraSmallish = SmallishContentImpl.class;
Object[] idsExtraSmallish = {new Integer(objectId)};
CacheController.clearCache(typesExtraSmallish, idsExtraSmallish);
logger.info("We clear all medium contents as well " + objectId);
Class typesExtraMedium = MediumContentImpl.class;
Object[] idsExtraMedium = {new Integer(objectId)};
CacheController.clearCache(typesExtraMedium, idsExtraMedium);
}
if(Class.forName(className).getName().equals(ContentVersionImpl.class.getName()))
{
logger.info("We clear all small contents as well " + objectId);
Class typesExtra = SmallContentVersionImpl.class;
Object[] idsExtra = {new Integer(objectId)};
CacheController.clearCache(typesExtra, idsExtra);
}
else if(Class.forName(className).getName().equals(AvailableServiceBindingImpl.class.getName()))
{
Class typesExtra = SmallAvailableServiceBindingImpl.class;
Object[] idsExtra = {new Integer(objectId)};
CacheController.clearCache(typesExtra, idsExtra);
}
else if(Class.forName(className).getName().equals(SiteNodeImpl.class.getName()))
{
Class typesExtra = SmallSiteNodeImpl.class;
Object[] idsExtra = {new Integer(objectId)};
CacheController.clearCache(typesExtra, idsExtra);
}
else if(Class.forName(className).getName().equals(DigitalAssetImpl.class.getName()))
{
CacheController.clearCache("digitalAssetCache");
Class typesExtra = SmallDigitalAssetImpl.class;
Object[] idsExtra = {new Integer(objectId)};
CacheController.clearCache(typesExtra, idsExtra);
Class typesExtraMedium = MediumDigitalAssetImpl.class;
Object[] idsExtraMedium = {new Integer(objectId)};
CacheController.clearCache(typesExtraMedium, idsExtraMedium);
String disableAssetDeletionInLiveThread = CmsPropertyHandler.getDisableAssetDeletionInLiveThread();
if(disableAssetDeletionInLiveThread != null && !disableAssetDeletionInLiveThread.equals("true"))
{
logger.info("We should delete all images with digitalAssetId " + objectId);
DigitalAssetDeliveryController.getDigitalAssetDeliveryController().deleteDigitalAssets(new Integer(objectId));
}
}
else if(Class.forName(className).getName().equals(PublicationImpl.class.getName()))
{
List publicationDetailVOList = PublicationController.getController().getPublicationDetailVOList(new Integer(objectId));
Iterator publicationDetailVOListIterator = publicationDetailVOList.iterator();
while(publicationDetailVOListIterator.hasNext())
{
PublicationDetailVO publicationDetailVO = (PublicationDetailVO)publicationDetailVOListIterator.next();
logger.info("publicationDetailVO.getEntityClass():" + publicationDetailVO.getEntityClass());
logger.info("publicationDetailVO.getEntityId():" + publicationDetailVO.getEntityId());
if(Class.forName(publicationDetailVO.getEntityClass()).getName().equals(ContentVersion.class.getName()))
{
logger.info("We clear all caches having references to contentVersion: " + publicationDetailVO.getEntityId());
Integer contentId = ContentVersionController.getContentVersionController().getContentIdForContentVersion(publicationDetailVO.getEntityId());
CacheController.clearCaches(publicationDetailVO.getEntityClass(), publicationDetailVO.getEntityId().toString(), null);
logger.info("We clear all small contents as well " + contentId);
Class typesExtra = SmallContentImpl.class;
Object[] idsExtra = {contentId};
CacheController.clearCache(typesExtra, idsExtra);
logger.info("We clear all small contents as well " + objectId);
Class typesExtraSmallish = SmallishContentImpl.class;
Object[] idsExtraSmallish = {new Integer(objectId)};
CacheController.clearCache(typesExtraSmallish, idsExtraSmallish);
logger.info("We clear all medium contents as well " + contentId);
Class typesExtraMedium = MediumContentImpl.class;
Object[] idsExtraMedium = {contentId};
CacheController.clearCache(typesExtraMedium, idsExtraMedium);
}
else if(Class.forName(publicationDetailVO.getEntityClass()).getName().equals(SiteNodeVersion.class.getName()))
{
Integer siteNodeId = SiteNodeVersionController.getController().getSiteNodeVersionVOWithId(publicationDetailVO.getEntityId()).getSiteNodeId();
CacheController.clearCaches(publicationDetailVO.getEntityClass(), publicationDetailVO.getEntityId().toString(), null);
logger.info("We clear all small siteNodes as well " + siteNodeId);
Class typesExtra = SmallSiteNodeImpl.class;
Object[] idsExtra = {siteNodeId};
CacheController.clearCache(typesExtra, idsExtra);
logger.info("We also clear the meta info content..");
SiteNodeVO siteNodeVO = SiteNodeController.getController().getSiteNodeVOWithId(siteNodeId);
logger.info("We clear all contents as well " + siteNodeVO.getMetaInfoContentId());
Class metaInfoContentExtra = ContentImpl.class;
Object[] idsMetaInfoContentExtra = {siteNodeVO.getMetaInfoContentId()};
CacheController.clearCache(metaInfoContentExtra, idsMetaInfoContentExtra);
logger.info("We clear all small contents as well " + siteNodeVO.getMetaInfoContentId());
Class metaInfoContentExtraSmall = SmallContentImpl.class;
CacheController.clearCache(metaInfoContentExtraSmall, idsMetaInfoContentExtra);
logger.info("We clear all smallish contents as well " + siteNodeVO.getMetaInfoContentId());
Class metaInfoContentExtraSmallish = SmallishContentImpl.class;
CacheController.clearCache(metaInfoContentExtraSmallish, idsMetaInfoContentExtra);
logger.info("We clear all medium contents as well " + siteNodeVO.getMetaInfoContentId());
Class metaInfoContentExtraMedium = MediumContentImpl.class;
CacheController.clearCache(metaInfoContentExtraMedium, idsMetaInfoContentExtra);
CacheController.clearCaches(ContentImpl.class.getName(), siteNodeVO.getMetaInfoContentId().toString(), null);
Database db = CastorDatabaseService.getDatabase();
db.begin();
Content content = ContentController.getContentController().getContentWithId(siteNodeVO.getMetaInfoContentId(), db);
List contentVersionIds = new ArrayList();
Iterator contentVersionIterator = content.getContentVersions().iterator();
logger.info("Versions:" + content.getContentVersions().size());
while(contentVersionIterator.hasNext())
{
ContentVersion contentVersion = (ContentVersion)contentVersionIterator.next();
contentVersionIds.add(contentVersion.getId());
logger.info("We clear the meta info contentVersion " + contentVersion.getId());
}
db.rollback();
db.close();
Iterator contentVersionIdsIterator = contentVersionIds.iterator();
logger.info("Versions:" + contentVersionIds.size());
while(contentVersionIdsIterator.hasNext())
{
Integer contentVersionId = (Integer)contentVersionIdsIterator.next();
logger.info("We clear the meta info contentVersion " + contentVersionId);
Class metaInfoContentVersionExtra = ContentVersionImpl.class;
Object[] idsMetaInfoContentVersionExtra = {contentVersionId};
CacheController.clearCache(metaInfoContentVersionExtra, idsMetaInfoContentVersionExtra);
CacheController.clearCaches(ContentVersionImpl.class.getName(), contentVersionId.toString(), null);
}
logger.info("After:" + content.getContentVersions().size());
}
}
}
}
else
{
/*
System.out.println("Was notification message in selective live publication...");
System.out.println("className:" + className);
System.out.println("objectId:" + objectId);
System.out.println("objectName:" + objectName);
System.out.println("typeId:" + typeId);
*/
if(className.equals("ServerNodeProperties"))
{
logger.info("\n\n\nUpdating all caches as this was a publishing-update\n\n\n");
- CacheController.clearCastorCaches();
+ //CacheController.clearCastorCaches();
logger.info("\n\n\nclearing all except page cache as we are in publish mode..\n\n\n");
CacheController.clearCaches(null, null, new String[] {"ServerNodeProperties", "serverNodePropertiesCache", "pageCache", "pageCacheExtra", "componentCache", "NavigationCache", "pagePathCache", "userCache", "pageCacheParentSiteNodeCache", "pageCacheLatestSiteNodeVersions", "pageCacheSiteNodeTypeDefinition", "JNDIAuthorizationCache", "WebServiceAuthorizationCache"});
- logger.info("\n\n\nRecaching all caches as this was a publishing-update\n\n\n");
- CacheController.cacheCentralCastorCaches();
+ //logger.info("\n\n\nRecaching all caches as this was a publishing-update\n\n\n");
+ //CacheController.cacheCentralCastorCaches();
- logger.info("\n\n\nFinally clearing page cache and other caches as this was a publishing-update\n\n\n");
- CacheController.clearCache("ServerNodeProperties");
- CacheController.clearCache("serverNodePropertiesCache");
+ //logger.info("\n\n\nFinally clearing page cache and other caches as this was a publishing-update\n\n\n");
+ logger.info("\n\n\nFinally clearing page cache and some other caches as this was a publishing-update\n\n\n");
+ //CacheController.clearCache("ServerNodeProperties");
+ //CacheController.clearCache("serverNodePropertiesCache");
+ CacheController.clearCache("boundContentCache");
CacheController.clearCache("pageCache");
CacheController.clearCache("pageCacheExtra");
- CacheController.clearCache("componentCache");
- CacheController.clearCache("NavigationCache");
- CacheController.clearCache("pagePathCache");
- CacheController.clearCache("pageCacheParentSiteNodeCache");
- CacheController.clearCache("pageCacheLatestSiteNodeVersions");
- CacheController.clearCache("pageCacheSiteNodeTypeDefinition");
+ CacheController.clearCache("componentCache");
+ CacheController.clearCache("NavigationCache");
+ CacheController.clearCache("pagePathCache");
+ CacheController.clearCache("pageCacheParentSiteNodeCache");
+ CacheController.clearCache("pageCacheLatestSiteNodeVersions");
+ CacheController.clearCache("pageCacheSiteNodeTypeDefinition");
}
}
}
}
catch (Exception e)
{
logger.error("An error occurred in the SelectiveLivePublicationThread:" + e.getMessage(), e);
}
}
logger.info("released block \n\n DONE---");
RequestAnalyser.getRequestAnalyser().setBlockRequests(false);
}
}
| false | true | public void run()
{
logger.info("Run in SelectiveLivePublicationThread....");
int publicationDelay = 5000;
String publicationThreadDelay = CmsPropertyHandler.getPublicationThreadDelay();
if(publicationThreadDelay != null && !publicationThreadDelay.equalsIgnoreCase("") && publicationThreadDelay.indexOf("publicationThreadDelay") == -1)
publicationDelay = Integer.parseInt(publicationThreadDelay);
logger.info("\n\n\nSleeping " + publicationDelay + "ms.\n\n\n");
try
{
sleep(publicationDelay);
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
logger.info("cacheEvictionBeans.size:" + cacheEvictionBeans.size() + ":" + RequestAnalyser.getRequestAnalyser().getBlockRequests());
if(cacheEvictionBeans.size() > 0)
{
try
{
logger.info("setting block");
RequestAnalyser.getRequestAnalyser().setBlockRequests(true);
Iterator i = cacheEvictionBeans.iterator();
while(i.hasNext())
{
CacheEvictionBean cacheEvictionBean = (CacheEvictionBean)i.next();
String className = cacheEvictionBean.getClassName();
String objectId = cacheEvictionBean.getObjectId();
String objectName = cacheEvictionBean.getObjectName();
String typeId = cacheEvictionBean.getTypeId();
logger.info("className:" + className);
logger.info("objectId:" + objectId);
logger.info("objectName:" + objectName);
logger.info("typeId:" + typeId);
boolean isDependsClass = false;
if(className != null && className.equalsIgnoreCase(PublicationDetailImpl.class.getName()))
isDependsClass = true;
CacheController.clearCaches(className, objectId, null);
logger.info("Updating className with id:" + className + ":" + objectId);
if(className != null && !typeId.equalsIgnoreCase("" + NotificationMessage.SYSTEM))
{
Class type = Class.forName(className);
if(!isDependsClass && className.equalsIgnoreCase(SystemUserImpl.class.getName()) || className.equalsIgnoreCase(RoleImpl.class.getName()) || className.equalsIgnoreCase(GroupImpl.class.getName()))
{
Object[] ids = {objectId};
CacheController.clearCache(type, ids);
}
else if(!isDependsClass)
{
Object[] ids = {new Integer(objectId)};
CacheController.clearCache(type, ids);
}
//If it's an contentVersion we should delete all images it might have generated from attributes.
if(Class.forName(className).getName().equals(ContentImpl.class.getName()))
{
logger.info("We clear all small contents as well " + objectId);
Class typesExtra = SmallContentImpl.class;
Object[] idsExtra = {new Integer(objectId)};
CacheController.clearCache(typesExtra, idsExtra);
logger.info("We clear all small contents as well " + objectId);
Class typesExtraSmallish = SmallishContentImpl.class;
Object[] idsExtraSmallish = {new Integer(objectId)};
CacheController.clearCache(typesExtraSmallish, idsExtraSmallish);
logger.info("We clear all medium contents as well " + objectId);
Class typesExtraMedium = MediumContentImpl.class;
Object[] idsExtraMedium = {new Integer(objectId)};
CacheController.clearCache(typesExtraMedium, idsExtraMedium);
}
if(Class.forName(className).getName().equals(ContentVersionImpl.class.getName()))
{
logger.info("We clear all small contents as well " + objectId);
Class typesExtra = SmallContentVersionImpl.class;
Object[] idsExtra = {new Integer(objectId)};
CacheController.clearCache(typesExtra, idsExtra);
}
else if(Class.forName(className).getName().equals(AvailableServiceBindingImpl.class.getName()))
{
Class typesExtra = SmallAvailableServiceBindingImpl.class;
Object[] idsExtra = {new Integer(objectId)};
CacheController.clearCache(typesExtra, idsExtra);
}
else if(Class.forName(className).getName().equals(SiteNodeImpl.class.getName()))
{
Class typesExtra = SmallSiteNodeImpl.class;
Object[] idsExtra = {new Integer(objectId)};
CacheController.clearCache(typesExtra, idsExtra);
}
else if(Class.forName(className).getName().equals(DigitalAssetImpl.class.getName()))
{
CacheController.clearCache("digitalAssetCache");
Class typesExtra = SmallDigitalAssetImpl.class;
Object[] idsExtra = {new Integer(objectId)};
CacheController.clearCache(typesExtra, idsExtra);
Class typesExtraMedium = MediumDigitalAssetImpl.class;
Object[] idsExtraMedium = {new Integer(objectId)};
CacheController.clearCache(typesExtraMedium, idsExtraMedium);
String disableAssetDeletionInLiveThread = CmsPropertyHandler.getDisableAssetDeletionInLiveThread();
if(disableAssetDeletionInLiveThread != null && !disableAssetDeletionInLiveThread.equals("true"))
{
logger.info("We should delete all images with digitalAssetId " + objectId);
DigitalAssetDeliveryController.getDigitalAssetDeliveryController().deleteDigitalAssets(new Integer(objectId));
}
}
else if(Class.forName(className).getName().equals(PublicationImpl.class.getName()))
{
List publicationDetailVOList = PublicationController.getController().getPublicationDetailVOList(new Integer(objectId));
Iterator publicationDetailVOListIterator = publicationDetailVOList.iterator();
while(publicationDetailVOListIterator.hasNext())
{
PublicationDetailVO publicationDetailVO = (PublicationDetailVO)publicationDetailVOListIterator.next();
logger.info("publicationDetailVO.getEntityClass():" + publicationDetailVO.getEntityClass());
logger.info("publicationDetailVO.getEntityId():" + publicationDetailVO.getEntityId());
if(Class.forName(publicationDetailVO.getEntityClass()).getName().equals(ContentVersion.class.getName()))
{
logger.info("We clear all caches having references to contentVersion: " + publicationDetailVO.getEntityId());
Integer contentId = ContentVersionController.getContentVersionController().getContentIdForContentVersion(publicationDetailVO.getEntityId());
CacheController.clearCaches(publicationDetailVO.getEntityClass(), publicationDetailVO.getEntityId().toString(), null);
logger.info("We clear all small contents as well " + contentId);
Class typesExtra = SmallContentImpl.class;
Object[] idsExtra = {contentId};
CacheController.clearCache(typesExtra, idsExtra);
logger.info("We clear all small contents as well " + objectId);
Class typesExtraSmallish = SmallishContentImpl.class;
Object[] idsExtraSmallish = {new Integer(objectId)};
CacheController.clearCache(typesExtraSmallish, idsExtraSmallish);
logger.info("We clear all medium contents as well " + contentId);
Class typesExtraMedium = MediumContentImpl.class;
Object[] idsExtraMedium = {contentId};
CacheController.clearCache(typesExtraMedium, idsExtraMedium);
}
else if(Class.forName(publicationDetailVO.getEntityClass()).getName().equals(SiteNodeVersion.class.getName()))
{
Integer siteNodeId = SiteNodeVersionController.getController().getSiteNodeVersionVOWithId(publicationDetailVO.getEntityId()).getSiteNodeId();
CacheController.clearCaches(publicationDetailVO.getEntityClass(), publicationDetailVO.getEntityId().toString(), null);
logger.info("We clear all small siteNodes as well " + siteNodeId);
Class typesExtra = SmallSiteNodeImpl.class;
Object[] idsExtra = {siteNodeId};
CacheController.clearCache(typesExtra, idsExtra);
logger.info("We also clear the meta info content..");
SiteNodeVO siteNodeVO = SiteNodeController.getController().getSiteNodeVOWithId(siteNodeId);
logger.info("We clear all contents as well " + siteNodeVO.getMetaInfoContentId());
Class metaInfoContentExtra = ContentImpl.class;
Object[] idsMetaInfoContentExtra = {siteNodeVO.getMetaInfoContentId()};
CacheController.clearCache(metaInfoContentExtra, idsMetaInfoContentExtra);
logger.info("We clear all small contents as well " + siteNodeVO.getMetaInfoContentId());
Class metaInfoContentExtraSmall = SmallContentImpl.class;
CacheController.clearCache(metaInfoContentExtraSmall, idsMetaInfoContentExtra);
logger.info("We clear all smallish contents as well " + siteNodeVO.getMetaInfoContentId());
Class metaInfoContentExtraSmallish = SmallishContentImpl.class;
CacheController.clearCache(metaInfoContentExtraSmallish, idsMetaInfoContentExtra);
logger.info("We clear all medium contents as well " + siteNodeVO.getMetaInfoContentId());
Class metaInfoContentExtraMedium = MediumContentImpl.class;
CacheController.clearCache(metaInfoContentExtraMedium, idsMetaInfoContentExtra);
CacheController.clearCaches(ContentImpl.class.getName(), siteNodeVO.getMetaInfoContentId().toString(), null);
Database db = CastorDatabaseService.getDatabase();
db.begin();
Content content = ContentController.getContentController().getContentWithId(siteNodeVO.getMetaInfoContentId(), db);
List contentVersionIds = new ArrayList();
Iterator contentVersionIterator = content.getContentVersions().iterator();
logger.info("Versions:" + content.getContentVersions().size());
while(contentVersionIterator.hasNext())
{
ContentVersion contentVersion = (ContentVersion)contentVersionIterator.next();
contentVersionIds.add(contentVersion.getId());
logger.info("We clear the meta info contentVersion " + contentVersion.getId());
}
db.rollback();
db.close();
Iterator contentVersionIdsIterator = contentVersionIds.iterator();
logger.info("Versions:" + contentVersionIds.size());
while(contentVersionIdsIterator.hasNext())
{
Integer contentVersionId = (Integer)contentVersionIdsIterator.next();
logger.info("We clear the meta info contentVersion " + contentVersionId);
Class metaInfoContentVersionExtra = ContentVersionImpl.class;
Object[] idsMetaInfoContentVersionExtra = {contentVersionId};
CacheController.clearCache(metaInfoContentVersionExtra, idsMetaInfoContentVersionExtra);
CacheController.clearCaches(ContentVersionImpl.class.getName(), contentVersionId.toString(), null);
}
logger.info("After:" + content.getContentVersions().size());
}
}
}
}
else
{
/*
System.out.println("Was notification message in selective live publication...");
System.out.println("className:" + className);
System.out.println("objectId:" + objectId);
System.out.println("objectName:" + objectName);
System.out.println("typeId:" + typeId);
*/
if(className.equals("ServerNodeProperties"))
{
logger.info("\n\n\nUpdating all caches as this was a publishing-update\n\n\n");
CacheController.clearCastorCaches();
logger.info("\n\n\nclearing all except page cache as we are in publish mode..\n\n\n");
CacheController.clearCaches(null, null, new String[] {"ServerNodeProperties", "serverNodePropertiesCache", "pageCache", "pageCacheExtra", "componentCache", "NavigationCache", "pagePathCache", "userCache", "pageCacheParentSiteNodeCache", "pageCacheLatestSiteNodeVersions", "pageCacheSiteNodeTypeDefinition", "JNDIAuthorizationCache", "WebServiceAuthorizationCache"});
logger.info("\n\n\nRecaching all caches as this was a publishing-update\n\n\n");
CacheController.cacheCentralCastorCaches();
logger.info("\n\n\nFinally clearing page cache and other caches as this was a publishing-update\n\n\n");
CacheController.clearCache("ServerNodeProperties");
CacheController.clearCache("serverNodePropertiesCache");
CacheController.clearCache("pageCache");
CacheController.clearCache("pageCacheExtra");
CacheController.clearCache("componentCache");
CacheController.clearCache("NavigationCache");
CacheController.clearCache("pagePathCache");
CacheController.clearCache("pageCacheParentSiteNodeCache");
CacheController.clearCache("pageCacheLatestSiteNodeVersions");
CacheController.clearCache("pageCacheSiteNodeTypeDefinition");
}
}
}
}
catch (Exception e)
{
logger.error("An error occurred in the SelectiveLivePublicationThread:" + e.getMessage(), e);
}
}
logger.info("released block \n\n DONE---");
RequestAnalyser.getRequestAnalyser().setBlockRequests(false);
}
| public void run()
{
logger.info("Run in SelectiveLivePublicationThread....");
int publicationDelay = 5000;
String publicationThreadDelay = CmsPropertyHandler.getPublicationThreadDelay();
if(publicationThreadDelay != null && !publicationThreadDelay.equalsIgnoreCase("") && publicationThreadDelay.indexOf("publicationThreadDelay") == -1)
publicationDelay = Integer.parseInt(publicationThreadDelay);
logger.info("\n\n\nSleeping " + publicationDelay + "ms.\n\n\n");
try
{
sleep(publicationDelay);
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
logger.info("cacheEvictionBeans.size:" + cacheEvictionBeans.size() + ":" + RequestAnalyser.getRequestAnalyser().getBlockRequests());
if(cacheEvictionBeans.size() > 0)
{
try
{
logger.info("setting block");
RequestAnalyser.getRequestAnalyser().setBlockRequests(true);
Iterator i = cacheEvictionBeans.iterator();
while(i.hasNext())
{
CacheEvictionBean cacheEvictionBean = (CacheEvictionBean)i.next();
String className = cacheEvictionBean.getClassName();
String objectId = cacheEvictionBean.getObjectId();
String objectName = cacheEvictionBean.getObjectName();
String typeId = cacheEvictionBean.getTypeId();
logger.info("className:" + className);
logger.info("objectId:" + objectId);
logger.info("objectName:" + objectName);
logger.info("typeId:" + typeId);
boolean isDependsClass = false;
if(className != null && className.equalsIgnoreCase(PublicationDetailImpl.class.getName()))
isDependsClass = true;
if(!typeId.equalsIgnoreCase("" + NotificationMessage.SYSTEM))
CacheController.clearCaches(className, objectId, null);
logger.info("Updating className with id:" + className + ":" + objectId);
if(className != null && !typeId.equalsIgnoreCase("" + NotificationMessage.SYSTEM))
{
Class type = Class.forName(className);
if(!isDependsClass && className.equalsIgnoreCase(SystemUserImpl.class.getName()) || className.equalsIgnoreCase(RoleImpl.class.getName()) || className.equalsIgnoreCase(GroupImpl.class.getName()))
{
Object[] ids = {objectId};
CacheController.clearCache(type, ids);
}
else if(!isDependsClass)
{
Object[] ids = {new Integer(objectId)};
CacheController.clearCache(type, ids);
}
//If it's an contentVersion we should delete all images it might have generated from attributes.
if(Class.forName(className).getName().equals(ContentImpl.class.getName()))
{
logger.info("We clear all small contents as well " + objectId);
Class typesExtra = SmallContentImpl.class;
Object[] idsExtra = {new Integer(objectId)};
CacheController.clearCache(typesExtra, idsExtra);
logger.info("We clear all small contents as well " + objectId);
Class typesExtraSmallish = SmallishContentImpl.class;
Object[] idsExtraSmallish = {new Integer(objectId)};
CacheController.clearCache(typesExtraSmallish, idsExtraSmallish);
logger.info("We clear all medium contents as well " + objectId);
Class typesExtraMedium = MediumContentImpl.class;
Object[] idsExtraMedium = {new Integer(objectId)};
CacheController.clearCache(typesExtraMedium, idsExtraMedium);
}
if(Class.forName(className).getName().equals(ContentVersionImpl.class.getName()))
{
logger.info("We clear all small contents as well " + objectId);
Class typesExtra = SmallContentVersionImpl.class;
Object[] idsExtra = {new Integer(objectId)};
CacheController.clearCache(typesExtra, idsExtra);
}
else if(Class.forName(className).getName().equals(AvailableServiceBindingImpl.class.getName()))
{
Class typesExtra = SmallAvailableServiceBindingImpl.class;
Object[] idsExtra = {new Integer(objectId)};
CacheController.clearCache(typesExtra, idsExtra);
}
else if(Class.forName(className).getName().equals(SiteNodeImpl.class.getName()))
{
Class typesExtra = SmallSiteNodeImpl.class;
Object[] idsExtra = {new Integer(objectId)};
CacheController.clearCache(typesExtra, idsExtra);
}
else if(Class.forName(className).getName().equals(DigitalAssetImpl.class.getName()))
{
CacheController.clearCache("digitalAssetCache");
Class typesExtra = SmallDigitalAssetImpl.class;
Object[] idsExtra = {new Integer(objectId)};
CacheController.clearCache(typesExtra, idsExtra);
Class typesExtraMedium = MediumDigitalAssetImpl.class;
Object[] idsExtraMedium = {new Integer(objectId)};
CacheController.clearCache(typesExtraMedium, idsExtraMedium);
String disableAssetDeletionInLiveThread = CmsPropertyHandler.getDisableAssetDeletionInLiveThread();
if(disableAssetDeletionInLiveThread != null && !disableAssetDeletionInLiveThread.equals("true"))
{
logger.info("We should delete all images with digitalAssetId " + objectId);
DigitalAssetDeliveryController.getDigitalAssetDeliveryController().deleteDigitalAssets(new Integer(objectId));
}
}
else if(Class.forName(className).getName().equals(PublicationImpl.class.getName()))
{
List publicationDetailVOList = PublicationController.getController().getPublicationDetailVOList(new Integer(objectId));
Iterator publicationDetailVOListIterator = publicationDetailVOList.iterator();
while(publicationDetailVOListIterator.hasNext())
{
PublicationDetailVO publicationDetailVO = (PublicationDetailVO)publicationDetailVOListIterator.next();
logger.info("publicationDetailVO.getEntityClass():" + publicationDetailVO.getEntityClass());
logger.info("publicationDetailVO.getEntityId():" + publicationDetailVO.getEntityId());
if(Class.forName(publicationDetailVO.getEntityClass()).getName().equals(ContentVersion.class.getName()))
{
logger.info("We clear all caches having references to contentVersion: " + publicationDetailVO.getEntityId());
Integer contentId = ContentVersionController.getContentVersionController().getContentIdForContentVersion(publicationDetailVO.getEntityId());
CacheController.clearCaches(publicationDetailVO.getEntityClass(), publicationDetailVO.getEntityId().toString(), null);
logger.info("We clear all small contents as well " + contentId);
Class typesExtra = SmallContentImpl.class;
Object[] idsExtra = {contentId};
CacheController.clearCache(typesExtra, idsExtra);
logger.info("We clear all small contents as well " + objectId);
Class typesExtraSmallish = SmallishContentImpl.class;
Object[] idsExtraSmallish = {new Integer(objectId)};
CacheController.clearCache(typesExtraSmallish, idsExtraSmallish);
logger.info("We clear all medium contents as well " + contentId);
Class typesExtraMedium = MediumContentImpl.class;
Object[] idsExtraMedium = {contentId};
CacheController.clearCache(typesExtraMedium, idsExtraMedium);
}
else if(Class.forName(publicationDetailVO.getEntityClass()).getName().equals(SiteNodeVersion.class.getName()))
{
Integer siteNodeId = SiteNodeVersionController.getController().getSiteNodeVersionVOWithId(publicationDetailVO.getEntityId()).getSiteNodeId();
CacheController.clearCaches(publicationDetailVO.getEntityClass(), publicationDetailVO.getEntityId().toString(), null);
logger.info("We clear all small siteNodes as well " + siteNodeId);
Class typesExtra = SmallSiteNodeImpl.class;
Object[] idsExtra = {siteNodeId};
CacheController.clearCache(typesExtra, idsExtra);
logger.info("We also clear the meta info content..");
SiteNodeVO siteNodeVO = SiteNodeController.getController().getSiteNodeVOWithId(siteNodeId);
logger.info("We clear all contents as well " + siteNodeVO.getMetaInfoContentId());
Class metaInfoContentExtra = ContentImpl.class;
Object[] idsMetaInfoContentExtra = {siteNodeVO.getMetaInfoContentId()};
CacheController.clearCache(metaInfoContentExtra, idsMetaInfoContentExtra);
logger.info("We clear all small contents as well " + siteNodeVO.getMetaInfoContentId());
Class metaInfoContentExtraSmall = SmallContentImpl.class;
CacheController.clearCache(metaInfoContentExtraSmall, idsMetaInfoContentExtra);
logger.info("We clear all smallish contents as well " + siteNodeVO.getMetaInfoContentId());
Class metaInfoContentExtraSmallish = SmallishContentImpl.class;
CacheController.clearCache(metaInfoContentExtraSmallish, idsMetaInfoContentExtra);
logger.info("We clear all medium contents as well " + siteNodeVO.getMetaInfoContentId());
Class metaInfoContentExtraMedium = MediumContentImpl.class;
CacheController.clearCache(metaInfoContentExtraMedium, idsMetaInfoContentExtra);
CacheController.clearCaches(ContentImpl.class.getName(), siteNodeVO.getMetaInfoContentId().toString(), null);
Database db = CastorDatabaseService.getDatabase();
db.begin();
Content content = ContentController.getContentController().getContentWithId(siteNodeVO.getMetaInfoContentId(), db);
List contentVersionIds = new ArrayList();
Iterator contentVersionIterator = content.getContentVersions().iterator();
logger.info("Versions:" + content.getContentVersions().size());
while(contentVersionIterator.hasNext())
{
ContentVersion contentVersion = (ContentVersion)contentVersionIterator.next();
contentVersionIds.add(contentVersion.getId());
logger.info("We clear the meta info contentVersion " + contentVersion.getId());
}
db.rollback();
db.close();
Iterator contentVersionIdsIterator = contentVersionIds.iterator();
logger.info("Versions:" + contentVersionIds.size());
while(contentVersionIdsIterator.hasNext())
{
Integer contentVersionId = (Integer)contentVersionIdsIterator.next();
logger.info("We clear the meta info contentVersion " + contentVersionId);
Class metaInfoContentVersionExtra = ContentVersionImpl.class;
Object[] idsMetaInfoContentVersionExtra = {contentVersionId};
CacheController.clearCache(metaInfoContentVersionExtra, idsMetaInfoContentVersionExtra);
CacheController.clearCaches(ContentVersionImpl.class.getName(), contentVersionId.toString(), null);
}
logger.info("After:" + content.getContentVersions().size());
}
}
}
}
else
{
/*
System.out.println("Was notification message in selective live publication...");
System.out.println("className:" + className);
System.out.println("objectId:" + objectId);
System.out.println("objectName:" + objectName);
System.out.println("typeId:" + typeId);
*/
if(className.equals("ServerNodeProperties"))
{
logger.info("\n\n\nUpdating all caches as this was a publishing-update\n\n\n");
//CacheController.clearCastorCaches();
logger.info("\n\n\nclearing all except page cache as we are in publish mode..\n\n\n");
CacheController.clearCaches(null, null, new String[] {"ServerNodeProperties", "serverNodePropertiesCache", "pageCache", "pageCacheExtra", "componentCache", "NavigationCache", "pagePathCache", "userCache", "pageCacheParentSiteNodeCache", "pageCacheLatestSiteNodeVersions", "pageCacheSiteNodeTypeDefinition", "JNDIAuthorizationCache", "WebServiceAuthorizationCache"});
//logger.info("\n\n\nRecaching all caches as this was a publishing-update\n\n\n");
//CacheController.cacheCentralCastorCaches();
//logger.info("\n\n\nFinally clearing page cache and other caches as this was a publishing-update\n\n\n");
logger.info("\n\n\nFinally clearing page cache and some other caches as this was a publishing-update\n\n\n");
//CacheController.clearCache("ServerNodeProperties");
//CacheController.clearCache("serverNodePropertiesCache");
CacheController.clearCache("boundContentCache");
CacheController.clearCache("pageCache");
CacheController.clearCache("pageCacheExtra");
CacheController.clearCache("componentCache");
CacheController.clearCache("NavigationCache");
CacheController.clearCache("pagePathCache");
CacheController.clearCache("pageCacheParentSiteNodeCache");
CacheController.clearCache("pageCacheLatestSiteNodeVersions");
CacheController.clearCache("pageCacheSiteNodeTypeDefinition");
}
}
}
}
catch (Exception e)
{
logger.error("An error occurred in the SelectiveLivePublicationThread:" + e.getMessage(), e);
}
}
logger.info("released block \n\n DONE---");
RequestAnalyser.getRequestAnalyser().setBlockRequests(false);
}
|
diff --git a/VisualizationModule/src/org/gephi/visualization/VizModel.java b/VisualizationModule/src/org/gephi/visualization/VizModel.java
index 61259e0d8..b68b0fd8f 100644
--- a/VisualizationModule/src/org/gephi/visualization/VizModel.java
+++ b/VisualizationModule/src/org/gephi/visualization/VizModel.java
@@ -1,565 +1,564 @@
/*
Copyright 2008-2010 Gephi
Authors : Mathieu Bastian <[email protected]>
Website : http://www.gephi.org
This file is part of Gephi.
Gephi 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.
Gephi 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 Gephi. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gephi.visualization;
import java.awt.Color;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.SwingUtilities;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import org.gephi.project.api.Workspace;
import org.gephi.ui.utils.ColorUtils;
import org.gephi.visualization.apiimpl.GraphDrawable;
import org.gephi.visualization.apiimpl.VizConfig;
import org.gephi.visualization.opengl.text.TextModel;
/**
*
* @author Mathieu Bastian
*/
public class VizModel {
protected VizConfig config;
protected GraphLimits limits;
//Variable
protected float[] cameraPosition;
protected float[] cameraTarget;
protected TextModel textModel;
protected boolean use3d;
protected boolean lighting;
protected boolean culling;
protected boolean material;
protected Color backgroundColor;
protected boolean rotatingEnable;
protected boolean showEdges;
protected boolean lightenNonSelectedAuto;
protected boolean autoSelectNeighbor;
protected boolean hideNonSelectedEdges;
protected boolean uniColorSelected;
protected boolean edgeHasUniColor;
protected float[] edgeUniColor;
protected boolean edgeSelectionColor;
protected float[] edgeInSelectionColor;
protected float[] edgeOutSelectionColor;
protected float[] edgeBothSelectionColor;
protected boolean adjustByText;
protected String nodeModeler;
protected boolean showHulls;
protected float edgeScale;
protected float metaEdgeScale;
//Listener
protected List<PropertyChangeListener> listeners = new ArrayList<PropertyChangeListener>();
private boolean defaultModel = false;
public VizModel() {
defaultValues();
limits = VizController.getInstance().getLimits();
}
public VizModel(boolean defaultModel) {
this.defaultModel = defaultModel;
defaultValues();
limits = VizController.getInstance().getLimits();
}
public void init() {
final PropertyChangeEvent evt = new PropertyChangeEvent(this, "init", null, null);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
for (PropertyChangeListener l : listeners) {
l.propertyChange(evt);
}
}
});
}
public boolean isDefaultModel() {
return defaultModel;
}
public List<PropertyChangeListener> getListeners() {
return listeners;
}
public void setListeners(List<PropertyChangeListener> listeners) {
this.listeners = listeners;
}
private void defaultValues() {
config = VizController.getInstance().getVizConfig();
cameraPosition = Arrays.copyOf(config.getDefaultCameraPosition(), 3);
cameraTarget = Arrays.copyOf(config.getDefaultCameraTarget(), 3);
textModel = new TextModel();
use3d = config.isDefaultUse3d();
lighting = use3d;
culling = use3d;
material = use3d;
rotatingEnable = use3d;
backgroundColor = config.getDefaultBackgroundColor();
showEdges = config.isDefaultShowEdges();
lightenNonSelectedAuto = config.isDefaultLightenNonSelectedAuto();
autoSelectNeighbor = config.isDefaultAutoSelectNeighbor();
hideNonSelectedEdges = config.isDefaultHideNonSelectedEdges();
uniColorSelected = config.isDefaultUniColorSelected();
edgeHasUniColor = config.isDefaultEdgeHasUniColor();
edgeUniColor = config.getDefaultEdgeUniColor().getRGBComponents(null);
adjustByText = config.isDefaultAdjustByText();
nodeModeler = use3d ? "CompatibilityNodeSphereModeler" : "CompatibilityNodeDiskModeler";
edgeSelectionColor = config.isDefaultEdgeSelectionColor();
edgeInSelectionColor = config.getDefaultEdgeInSelectedColor().getRGBComponents(null);
edgeOutSelectionColor = config.getDefaultEdgeOutSelectedColor().getRGBComponents(null);
edgeBothSelectionColor = config.getDefaultEdgeBothSelectedColor().getRGBComponents(null);
showHulls = config.isDefaultShowHulls();
edgeScale = config.getDefaultEdgeScale();
metaEdgeScale = config.getDefaultMetaEdgeScale();
}
//GETTERS
public boolean isAdjustByText() {
return adjustByText;
}
public boolean isAutoSelectNeighbor() {
return autoSelectNeighbor;
}
public Color getBackgroundColor() {
return backgroundColor;
}
public float[] getCameraPosition() {
return cameraPosition;
}
public float[] getCameraTarget() {
return cameraTarget;
}
public boolean isCulling() {
return culling;
}
public boolean isShowEdges() {
return showEdges;
}
public boolean isEdgeHasUniColor() {
return edgeHasUniColor;
}
public float[] getEdgeUniColor() {
return edgeUniColor;
}
public boolean isHideNonSelectedEdges() {
return hideNonSelectedEdges;
}
public boolean isLightenNonSelectedAuto() {
return lightenNonSelectedAuto;
}
public boolean isLighting() {
return lighting;
}
public boolean isMaterial() {
return material;
}
public boolean isRotatingEnable() {
return rotatingEnable;
}
public TextModel getTextModel() {
return textModel;
}
public boolean isUniColorSelected() {
return uniColorSelected;
}
public boolean isUse3d() {
return use3d;
}
public VizConfig getConfig() {
return config;
}
public String getNodeModeler() {
return nodeModeler;
}
public boolean isEdgeSelectionColor() {
return edgeSelectionColor;
}
public float[] getEdgeInSelectionColor() {
return edgeInSelectionColor;
}
public float[] getEdgeOutSelectionColor() {
return edgeOutSelectionColor;
}
public float[] getEdgeBothSelectionColor() {
return edgeBothSelectionColor;
}
public boolean isShowHulls() {
return showHulls;
}
public float getEdgeScale() {
return edgeScale;
}
public float getMetaEdgeScale() {
return metaEdgeScale;
}
//SETTERS
public void setAdjustByText(boolean adjustByText) {
this.adjustByText = adjustByText;
fireProperyChange("adjustByText", null, adjustByText);
}
public void setAutoSelectNeighbor(boolean autoSelectNeighbor) {
this.autoSelectNeighbor = autoSelectNeighbor;
fireProperyChange("autoSelectNeighbor", null, autoSelectNeighbor);
}
public void setBackgroundColor(Color backgroundColor) {
this.backgroundColor = backgroundColor;
fireProperyChange("backgroundColor", null, backgroundColor);
}
public void setShowEdges(boolean showEdges) {
this.showEdges = showEdges;
fireProperyChange("showEdges", null, showEdges);
}
public void setEdgeHasUniColor(boolean edgeHasUniColor) {
this.edgeHasUniColor = edgeHasUniColor;
fireProperyChange("edgeHasUniColor", null, edgeHasUniColor);
}
public void setEdgeUniColor(float[] edgeUniColor) {
this.edgeUniColor = edgeUniColor;
fireProperyChange("edgeUniColor", null, edgeUniColor);
}
public void setHideNonSelectedEdges(boolean hideNonSelectedEdges) {
this.hideNonSelectedEdges = hideNonSelectedEdges;
fireProperyChange("hideNonSelectedEdges", null, hideNonSelectedEdges);
}
public void setLightenNonSelectedAuto(boolean lightenNonSelectedAuto) {
this.lightenNonSelectedAuto = lightenNonSelectedAuto;
fireProperyChange("lightenNonSelectedAuto", null, lightenNonSelectedAuto);
}
public void setUniColorSelected(boolean uniColorSelected) {
this.uniColorSelected = uniColorSelected;
fireProperyChange("uniColorSelected", null, uniColorSelected);
}
public void setUse3d(boolean use3d) {
this.use3d = use3d;
//Additional
this.lighting = use3d;
this.culling = use3d;
this.rotatingEnable = use3d;
this.material = use3d;
fireProperyChange("use3d", null, use3d);
}
public void setNodeModeler(String nodeModeler) {
this.nodeModeler = nodeModeler;
fireProperyChange("nodeModeler", null, nodeModeler);
}
public void setEdgeSelectionColor(boolean edgeSelectionColor) {
this.edgeSelectionColor = edgeSelectionColor;
fireProperyChange("edgeSelectionColor", null, edgeSelectionColor);
}
public void setEdgeInSelectionColor(float[] edgeInSelectionColor) {
this.edgeInSelectionColor = edgeInSelectionColor;
fireProperyChange("edgeInSelectionColor", null, edgeInSelectionColor);
}
public void setEdgeOutSelectionColor(float[] edgeOutSelectionColor) {
this.edgeOutSelectionColor = edgeOutSelectionColor;
fireProperyChange("edgeOutSelectionColor", null, edgeOutSelectionColor);
}
public void setEdgeBothSelectionColor(float[] edgeBothSelectionColor) {
this.edgeBothSelectionColor = edgeBothSelectionColor;
fireProperyChange("edgeBothSelectionColor", null, edgeBothSelectionColor);
}
public void setShowHulls(boolean showHulls) {
this.showHulls = showHulls;
fireProperyChange("showHulls", null, showHulls);
}
public void setEdgeScale(float edgeScale) {
this.edgeScale = edgeScale;
fireProperyChange("edgeScale", null, edgeScale);
}
public void setMetaEdgeScale(float metaEdgeScale) {
this.metaEdgeScale = metaEdgeScale;
fireProperyChange("metaEdgeScale", null, metaEdgeScale);
}
public GraphLimits getLimits() {
return limits;
}
public float getCameraDistance() {
GraphDrawable drawable = VizController.getInstance().getDrawable();
return drawable.getCameraVector().length();
}
public void setCameraDistance(float distance) {
}
//EVENTS
public void addPropertyChangeListener(PropertyChangeListener listener) {
listeners.add(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
listeners.remove(listener);
}
public void fireProperyChange(String propertyName, Object oldvalue, Object newValue) {
PropertyChangeEvent evt = new PropertyChangeEvent(this, propertyName, oldvalue, newValue);
for (PropertyChangeListener l : listeners) {
l.propertyChange(evt);
}
}
//XML
public void readXML(XMLStreamReader reader, Workspace workspace) throws XMLStreamException {
boolean end = false;
while (reader.hasNext() && !end) {
int type = reader.next();
switch (type) {
case XMLStreamReader.START_ELEMENT:
String name = reader.getLocalName();
if ("textmodel".equalsIgnoreCase(name)) {
textModel.readXML(reader, workspace);
} else if ("cameraposition".equalsIgnoreCase(name)) {
cameraPosition[0] = Float.parseFloat(reader.getAttributeValue(null, "x"));
cameraPosition[1] = Float.parseFloat(reader.getAttributeValue(null, "y"));
cameraPosition[2] = Float.parseFloat(reader.getAttributeValue(null, "z"));
} else if ("cameratarget".equalsIgnoreCase(name)) {
cameraTarget[0] = Float.parseFloat(reader.getAttributeValue(null, "x"));
cameraTarget[1] = Float.parseFloat(reader.getAttributeValue(null, "y"));
cameraTarget[2] = Float.parseFloat(reader.getAttributeValue(null, "z"));
} else if ("use3d".equalsIgnoreCase(name)) {
use3d = Boolean.parseBoolean(reader.getAttributeValue(null, "value"));
} else if ("lighting".equalsIgnoreCase(name)) {
lighting = Boolean.parseBoolean(reader.getAttributeValue(null, "value"));
} else if ("culling".equalsIgnoreCase(name)) {
culling = Boolean.parseBoolean(reader.getAttributeValue(null, "value"));
} else if ("material".equalsIgnoreCase(name)) {
material = Boolean.parseBoolean(reader.getAttributeValue(null, "value"));
} else if ("rotatingenable".equalsIgnoreCase(name)) {
rotatingEnable = Boolean.parseBoolean(reader.getAttributeValue(null, "value"));
} else if ("showedges".equalsIgnoreCase(name)) {
showEdges = Boolean.parseBoolean(reader.getAttributeValue(null, "value"));
} else if ("lightennonselectedauto".equalsIgnoreCase(name)) {
lightenNonSelectedAuto = Boolean.parseBoolean(reader.getAttributeValue(null, "value"));
} else if ("autoselectneighbor".equalsIgnoreCase(name)) {
autoSelectNeighbor = Boolean.parseBoolean(reader.getAttributeValue(null, "value"));
} else if ("hidenonselectededges".equalsIgnoreCase(name)) {
hideNonSelectedEdges = Boolean.parseBoolean(reader.getAttributeValue(null, "value"));
} else if ("unicolorselected".equalsIgnoreCase(name)) {
uniColorSelected = Boolean.parseBoolean(reader.getAttributeValue(null, "value"));
} else if ("edgehasunicolor".equalsIgnoreCase(name)) {
edgeHasUniColor = Boolean.parseBoolean(reader.getAttributeValue(null, "value"));
} else if ("adjustbytext".equalsIgnoreCase(name)) {
adjustByText = Boolean.parseBoolean(reader.getAttributeValue(null, "value"));
} else if ("edgeSelectionColor".equalsIgnoreCase(name)) {
edgeSelectionColor = Boolean.parseBoolean(reader.getAttributeValue(null, "value"));
} else if ("showHulls".equalsIgnoreCase(name)) {
showHulls = Boolean.parseBoolean(reader.getAttributeValue(null, "value"));
} else if ("backgroundcolor".equalsIgnoreCase(name)) {
backgroundColor = ColorUtils.decode(reader.getAttributeValue(null, "value"));
} else if ("edgeunicolor".equalsIgnoreCase(name)) {
edgeUniColor = ColorUtils.decode(reader.getAttributeValue(null, "value")).getRGBComponents(null);
} else if ("edgeInSelectionColor".equalsIgnoreCase(name)) {
edgeInSelectionColor = ColorUtils.decode(reader.getAttributeValue(null, "value")).getRGBComponents(null);
} else if ("edgeOutSelectionColor".equalsIgnoreCase(name)) {
edgeOutSelectionColor = ColorUtils.decode(reader.getAttributeValue(null, "value")).getRGBComponents(null);
} else if ("edgeBothSelectionColor".equalsIgnoreCase(name)) {
edgeBothSelectionColor = ColorUtils.decode(reader.getAttributeValue(null, "value")).getRGBComponents(null);
} else if ("nodemodeler".equalsIgnoreCase(name)) {
nodeModeler = reader.getAttributeValue(null, "value");
} else if ("edgeScale".equalsIgnoreCase(name)) {
edgeScale = Float.parseFloat(reader.getAttributeValue(null, "value"));
} else if ("metaEdgeScale".equalsIgnoreCase(name)) {
metaEdgeScale = Float.parseFloat(reader.getAttributeValue(null, "value"));
}
break;
case XMLStreamReader.END_ELEMENT:
if ("vizmodel".equalsIgnoreCase(reader.getLocalName())) {
end = true;
}
break;
}
}
}
public void writeXML(XMLStreamWriter writer) throws XMLStreamException {
writer.writeStartElement("vizmodel");
//Fast refreh
GraphDrawable drawable = VizController.getInstance().getDrawable();
cameraPosition = Arrays.copyOf(drawable.getCameraLocation(), 3);
cameraTarget = Arrays.copyOf(drawable.getCameraTarget(), 3);
//TextModel
textModel.writeXML(writer);
- writer.writeEndElement();
//Camera
writer.writeStartElement("cameraposition");
writer.writeAttribute("x", Float.toString(cameraPosition[0]));
writer.writeAttribute("y", Float.toString(cameraPosition[1]));
writer.writeAttribute("z", Float.toString(cameraPosition[2]));
writer.writeEndElement();
writer.writeStartElement("cameratarget");
writer.writeAttribute("x", Float.toString(cameraTarget[0]));
writer.writeAttribute("y", Float.toString(cameraTarget[1]));
writer.writeAttribute("z", Float.toString(cameraTarget[2]));
writer.writeEndElement();
//Boolean values
writer.writeStartElement("use3d");
writer.writeAttribute("value", String.valueOf(use3d));
writer.writeEndElement();
writer.writeStartElement("lighting");
writer.writeAttribute("value", String.valueOf(lighting));
writer.writeEndElement();
writer.writeStartElement("culling");
writer.writeAttribute("value", String.valueOf(culling));
writer.writeEndElement();
writer.writeStartElement("material");
writer.writeAttribute("value", String.valueOf(material));
writer.writeEndElement();
writer.writeStartElement("rotatingenable");
writer.writeAttribute("value", String.valueOf(rotatingEnable));
writer.writeEndElement();
writer.writeStartElement("showedges");
writer.writeAttribute("value", String.valueOf(showEdges));
writer.writeEndElement();
writer.writeStartElement("lightennonselectedauto");
writer.writeAttribute("value", String.valueOf(lightenNonSelectedAuto));
writer.writeEndElement();
writer.writeStartElement("autoselectneighbor");
writer.writeAttribute("value", String.valueOf(autoSelectNeighbor));
writer.writeEndElement();
writer.writeStartElement("hidenonselectededges");
writer.writeAttribute("value", String.valueOf(hideNonSelectedEdges));
writer.writeEndElement();
writer.writeStartElement("unicolorselected");
writer.writeAttribute("value", String.valueOf(uniColorSelected));
writer.writeEndElement();
writer.writeStartElement("edgehasunicolor");
writer.writeAttribute("value", String.valueOf(edgeHasUniColor));
writer.writeEndElement();
writer.writeStartElement("adjustbytext");
writer.writeAttribute("value", String.valueOf(adjustByText));
writer.writeEndElement();
writer.writeStartElement("edgeSelectionColor");
writer.writeAttribute("value", String.valueOf(edgeSelectionColor));
writer.writeEndElement();
writer.writeStartElement("showHulls");
writer.writeAttribute("value", String.valueOf(showHulls));
writer.writeEndElement();
//Colors
writer.writeStartElement("backgroundcolor");
writer.writeAttribute("value", ColorUtils.encode(backgroundColor));
writer.writeEndElement();
writer.writeStartElement("edgeunicolor");
writer.writeAttribute("value", ColorUtils.encode(ColorUtils.decode(edgeUniColor)));
writer.writeEndElement();
writer.writeStartElement("edgeInSelectionColor");
writer.writeAttribute("value", ColorUtils.encode(ColorUtils.decode(edgeInSelectionColor)));
writer.writeEndElement();
writer.writeStartElement("edgeOutSelectionColor");
writer.writeAttribute("value", ColorUtils.encode(ColorUtils.decode(edgeOutSelectionColor)));
writer.writeEndElement();
writer.writeStartElement("edgeBothSelectionColor");
writer.writeAttribute("value", ColorUtils.encode(ColorUtils.decode(edgeBothSelectionColor)));
writer.writeEndElement();
//Misc
writer.writeStartElement("nodemodeler");
writer.writeAttribute("value", nodeModeler);
writer.writeEndElement();
//Float
writer.writeStartElement("edgeScale");
writer.writeAttribute("value", String.valueOf(edgeScale));
writer.writeEndElement();
writer.writeStartElement("metaEdgeScale");
writer.writeAttribute("value", String.valueOf(metaEdgeScale));
writer.writeEndElement();
writer.writeEndElement();
}
}
| true | true | public void writeXML(XMLStreamWriter writer) throws XMLStreamException {
writer.writeStartElement("vizmodel");
//Fast refreh
GraphDrawable drawable = VizController.getInstance().getDrawable();
cameraPosition = Arrays.copyOf(drawable.getCameraLocation(), 3);
cameraTarget = Arrays.copyOf(drawable.getCameraTarget(), 3);
//TextModel
textModel.writeXML(writer);
writer.writeEndElement();
//Camera
writer.writeStartElement("cameraposition");
writer.writeAttribute("x", Float.toString(cameraPosition[0]));
writer.writeAttribute("y", Float.toString(cameraPosition[1]));
writer.writeAttribute("z", Float.toString(cameraPosition[2]));
writer.writeEndElement();
writer.writeStartElement("cameratarget");
writer.writeAttribute("x", Float.toString(cameraTarget[0]));
writer.writeAttribute("y", Float.toString(cameraTarget[1]));
writer.writeAttribute("z", Float.toString(cameraTarget[2]));
writer.writeEndElement();
//Boolean values
writer.writeStartElement("use3d");
writer.writeAttribute("value", String.valueOf(use3d));
writer.writeEndElement();
writer.writeStartElement("lighting");
writer.writeAttribute("value", String.valueOf(lighting));
writer.writeEndElement();
writer.writeStartElement("culling");
writer.writeAttribute("value", String.valueOf(culling));
writer.writeEndElement();
writer.writeStartElement("material");
writer.writeAttribute("value", String.valueOf(material));
writer.writeEndElement();
writer.writeStartElement("rotatingenable");
writer.writeAttribute("value", String.valueOf(rotatingEnable));
writer.writeEndElement();
writer.writeStartElement("showedges");
writer.writeAttribute("value", String.valueOf(showEdges));
writer.writeEndElement();
writer.writeStartElement("lightennonselectedauto");
writer.writeAttribute("value", String.valueOf(lightenNonSelectedAuto));
writer.writeEndElement();
writer.writeStartElement("autoselectneighbor");
writer.writeAttribute("value", String.valueOf(autoSelectNeighbor));
writer.writeEndElement();
writer.writeStartElement("hidenonselectededges");
writer.writeAttribute("value", String.valueOf(hideNonSelectedEdges));
writer.writeEndElement();
writer.writeStartElement("unicolorselected");
writer.writeAttribute("value", String.valueOf(uniColorSelected));
writer.writeEndElement();
writer.writeStartElement("edgehasunicolor");
writer.writeAttribute("value", String.valueOf(edgeHasUniColor));
writer.writeEndElement();
writer.writeStartElement("adjustbytext");
writer.writeAttribute("value", String.valueOf(adjustByText));
writer.writeEndElement();
writer.writeStartElement("edgeSelectionColor");
writer.writeAttribute("value", String.valueOf(edgeSelectionColor));
writer.writeEndElement();
writer.writeStartElement("showHulls");
writer.writeAttribute("value", String.valueOf(showHulls));
writer.writeEndElement();
//Colors
writer.writeStartElement("backgroundcolor");
writer.writeAttribute("value", ColorUtils.encode(backgroundColor));
writer.writeEndElement();
writer.writeStartElement("edgeunicolor");
writer.writeAttribute("value", ColorUtils.encode(ColorUtils.decode(edgeUniColor)));
writer.writeEndElement();
writer.writeStartElement("edgeInSelectionColor");
writer.writeAttribute("value", ColorUtils.encode(ColorUtils.decode(edgeInSelectionColor)));
writer.writeEndElement();
writer.writeStartElement("edgeOutSelectionColor");
writer.writeAttribute("value", ColorUtils.encode(ColorUtils.decode(edgeOutSelectionColor)));
writer.writeEndElement();
writer.writeStartElement("edgeBothSelectionColor");
writer.writeAttribute("value", ColorUtils.encode(ColorUtils.decode(edgeBothSelectionColor)));
writer.writeEndElement();
//Misc
writer.writeStartElement("nodemodeler");
writer.writeAttribute("value", nodeModeler);
writer.writeEndElement();
//Float
writer.writeStartElement("edgeScale");
writer.writeAttribute("value", String.valueOf(edgeScale));
writer.writeEndElement();
writer.writeStartElement("metaEdgeScale");
writer.writeAttribute("value", String.valueOf(metaEdgeScale));
writer.writeEndElement();
writer.writeEndElement();
}
| public void writeXML(XMLStreamWriter writer) throws XMLStreamException {
writer.writeStartElement("vizmodel");
//Fast refreh
GraphDrawable drawable = VizController.getInstance().getDrawable();
cameraPosition = Arrays.copyOf(drawable.getCameraLocation(), 3);
cameraTarget = Arrays.copyOf(drawable.getCameraTarget(), 3);
//TextModel
textModel.writeXML(writer);
//Camera
writer.writeStartElement("cameraposition");
writer.writeAttribute("x", Float.toString(cameraPosition[0]));
writer.writeAttribute("y", Float.toString(cameraPosition[1]));
writer.writeAttribute("z", Float.toString(cameraPosition[2]));
writer.writeEndElement();
writer.writeStartElement("cameratarget");
writer.writeAttribute("x", Float.toString(cameraTarget[0]));
writer.writeAttribute("y", Float.toString(cameraTarget[1]));
writer.writeAttribute("z", Float.toString(cameraTarget[2]));
writer.writeEndElement();
//Boolean values
writer.writeStartElement("use3d");
writer.writeAttribute("value", String.valueOf(use3d));
writer.writeEndElement();
writer.writeStartElement("lighting");
writer.writeAttribute("value", String.valueOf(lighting));
writer.writeEndElement();
writer.writeStartElement("culling");
writer.writeAttribute("value", String.valueOf(culling));
writer.writeEndElement();
writer.writeStartElement("material");
writer.writeAttribute("value", String.valueOf(material));
writer.writeEndElement();
writer.writeStartElement("rotatingenable");
writer.writeAttribute("value", String.valueOf(rotatingEnable));
writer.writeEndElement();
writer.writeStartElement("showedges");
writer.writeAttribute("value", String.valueOf(showEdges));
writer.writeEndElement();
writer.writeStartElement("lightennonselectedauto");
writer.writeAttribute("value", String.valueOf(lightenNonSelectedAuto));
writer.writeEndElement();
writer.writeStartElement("autoselectneighbor");
writer.writeAttribute("value", String.valueOf(autoSelectNeighbor));
writer.writeEndElement();
writer.writeStartElement("hidenonselectededges");
writer.writeAttribute("value", String.valueOf(hideNonSelectedEdges));
writer.writeEndElement();
writer.writeStartElement("unicolorselected");
writer.writeAttribute("value", String.valueOf(uniColorSelected));
writer.writeEndElement();
writer.writeStartElement("edgehasunicolor");
writer.writeAttribute("value", String.valueOf(edgeHasUniColor));
writer.writeEndElement();
writer.writeStartElement("adjustbytext");
writer.writeAttribute("value", String.valueOf(adjustByText));
writer.writeEndElement();
writer.writeStartElement("edgeSelectionColor");
writer.writeAttribute("value", String.valueOf(edgeSelectionColor));
writer.writeEndElement();
writer.writeStartElement("showHulls");
writer.writeAttribute("value", String.valueOf(showHulls));
writer.writeEndElement();
//Colors
writer.writeStartElement("backgroundcolor");
writer.writeAttribute("value", ColorUtils.encode(backgroundColor));
writer.writeEndElement();
writer.writeStartElement("edgeunicolor");
writer.writeAttribute("value", ColorUtils.encode(ColorUtils.decode(edgeUniColor)));
writer.writeEndElement();
writer.writeStartElement("edgeInSelectionColor");
writer.writeAttribute("value", ColorUtils.encode(ColorUtils.decode(edgeInSelectionColor)));
writer.writeEndElement();
writer.writeStartElement("edgeOutSelectionColor");
writer.writeAttribute("value", ColorUtils.encode(ColorUtils.decode(edgeOutSelectionColor)));
writer.writeEndElement();
writer.writeStartElement("edgeBothSelectionColor");
writer.writeAttribute("value", ColorUtils.encode(ColorUtils.decode(edgeBothSelectionColor)));
writer.writeEndElement();
//Misc
writer.writeStartElement("nodemodeler");
writer.writeAttribute("value", nodeModeler);
writer.writeEndElement();
//Float
writer.writeStartElement("edgeScale");
writer.writeAttribute("value", String.valueOf(edgeScale));
writer.writeEndElement();
writer.writeStartElement("metaEdgeScale");
writer.writeAttribute("value", String.valueOf(metaEdgeScale));
writer.writeEndElement();
writer.writeEndElement();
}
|
diff --git a/modules/compute4/org/molgenis/compute/commandline/ComputeBundleValidator.java b/modules/compute4/org/molgenis/compute/commandline/ComputeBundleValidator.java
index bcb1a6a06..73dcee423 100644
--- a/modules/compute4/org/molgenis/compute/commandline/ComputeBundleValidator.java
+++ b/modules/compute4/org/molgenis/compute/commandline/ComputeBundleValidator.java
@@ -1,157 +1,162 @@
package org.molgenis.compute.commandline;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.molgenis.compute.design.ComputeParameter;
import org.molgenis.compute.design.ComputeProtocol;
import org.molgenis.compute.design.WorkflowElement;
import org.molgenis.util.CsvFileReader;
import org.molgenis.util.CsvReader;
public class ComputeBundleValidator
{
ComputeBundleFromDirectory cb;
/*
* Validate workflow, protocols, parameters, worksheet
*/
public ComputeBundleValidator(ComputeBundleFromDirectory cb)
{
this.cb = cb;
}
public void validateFileHeaders(ComputeCommandLine options) throws Exception
{
CsvReader reader = new CsvFileReader(options.workflowfile);
List<String> header = Arrays.asList("name", "protocol_name", "PreviousSteps_name");
if (!reader.colnames().containsAll(header)) headerError("Workflow", header, reader.colnames(),
options.workflowfile);
reader = new CsvFileReader(options.parametersfile);
header = Arrays.asList("Name", "defaultValue", "description", "dataType", "hasOne_name");
if (!reader.colnames().containsAll(header)) headerError("Parameters", header, reader.colnames(),
options.parametersfile);
}
private void headerError(String inputName, List<String> targetHeader, List<String> currentHeader, File workflowfile)
{
printError(inputName + " file does not have the right header. Please correct this.\n"
+ "Columns that should be contained in the header are: " + targetHeader + "\n" + "Current header is: "
+ currentHeader + "\n" + "Your workflow file: " + workflowfile);
}
private void exit()
{
System.err.println("\nProgram exits with status code 1.");
System.exit(1);
}
private void printErrorHeaderFooter(boolean b)
{
System.err.println("\n#");
System.err.println("##");
System.err.println("### " + (b ? "Begin" : "End") + " of error message.");
System.err.println("##");
System.err.println("#\n");
}
private void printError(String msg)
{
printErrorHeaderFooter(true);
System.err.println(msg);
printErrorHeaderFooter(false);
exit();
}
public void validateBundle()
{
// VALIDATE WORKFLOW
List<WorkflowElement> wfelements = cb.getWorkflowElements();
// Validate that all wfe step names are different
List<String> wfeNamesList = new ArrayList<String>();
Set<String> wfeNamesSet = new HashSet();
for (WorkflowElement wfe : wfelements)
{
wfeNamesList.add(wfe.getName());
wfeNamesSet.add(wfe.getName());
}
if (wfeNamesList.size() != wfeNamesSet.size())
{
printError("In your workflow file, you have duplicate workflow step names. All values in the column 'name' should be different. Please fix this.");
}
// Validate that PreviousSteps_name's all refer to workflow steps.
for (WorkflowElement wfe : wfelements)
{
for (String ps : wfe.getPreviousSteps_Name())
{
if (!wfeNamesSet.contains(ps)) printError("In your workflow, the PreviousSteps_name '"
+ ps
+ "' is not a workflow step name, because it does not match to a value in the 'name' column. Please fix this.");
}
}
// Validate that all protocols referred to, exist.
// First put protocol names in a list
List<String> protocolNames = new ArrayList<String>();
for (ComputeProtocol cp : cb.getComputeProtocols())
{
protocolNames.add(cp.getName());
}
for (WorkflowElement wfe : wfelements)
{
String pn = wfe.getProtocol_Name();
if (!protocolNames.contains(pn))
{
printError("In your workflow file, the protocol name '"
+ pn
+ "' in the 'protocol_name' column, does not refer to an known protocol.\nPlease upload a protocol with the name '"
+ pn + ".ftl' or change '" + pn + "' to the name of an known protocol.");
}
}
// Validate that a file called 'Submit.sh.ftl' exists.
if (!protocolNames.contains("Submit.sh"))
{
printError("You should have a protocol 'Submit.sh.ftl' in which you define how to submit the generated scripts.\n"
+ "You may use the following code that is compatible with a PBS-scheduler.\n\n"
+ "DIR=\"$( cd \"$( dirname \"<#noparse>${BASH_SOURCE[0]}</#noparse>\" )\" && pwd )\""
+ + "\n"
+ "touch $DIR/${workflowfilename}.started\n"
+ "\n"
+ "<#foreach j in jobs>\n"
+ "#${j.name}\n"
+ "${j.name}=$(qsub -N ${j.name}<#if j.prevSteps_Name?size > 0> -W depend=afterok<#foreach d in j.prevSteps_Name>:$${d}</#foreach></#if> ${j.name}.sh)\n"
- + "echo $${j.name}\n" + "sleep 0\n" + "</#foreach>");
+ + "echo $${j.name}\n"
+ + "sleep 0\n"
+ + "</#foreach>\n"
+ + "\n"
+ + "touch $DIR/${workflowfilename}.finished");
}
// VALIDATE PARAMETERS
// Validate that all hasOne_name's refer to parameter names
// Moreover, only allow one instance of each parameter
HashSet<String> params = new HashSet<String>();
HashSet<String> hasOnes = new HashSet<String>();
for (ComputeParameter cp : cb.getComputeParameters())
{
String p = cp.getName();
if (params.contains(p)) printError("In your paramer file, parameter '" + p
+ "' occurs more than once, which is not allowed.\nPlease fix this.");
params.add(p);
hasOnes.addAll(cp.getHasOne_Name());
}
for (String h : hasOnes)
{
if (!params.contains(h)) printError("In your parameters file, in your hasOne_name column, you refer to a non-existing parameter '"
+ h + "'. Please add this parameter to your file.");
}
}
}
| false | true | public void validateBundle()
{
// VALIDATE WORKFLOW
List<WorkflowElement> wfelements = cb.getWorkflowElements();
// Validate that all wfe step names are different
List<String> wfeNamesList = new ArrayList<String>();
Set<String> wfeNamesSet = new HashSet();
for (WorkflowElement wfe : wfelements)
{
wfeNamesList.add(wfe.getName());
wfeNamesSet.add(wfe.getName());
}
if (wfeNamesList.size() != wfeNamesSet.size())
{
printError("In your workflow file, you have duplicate workflow step names. All values in the column 'name' should be different. Please fix this.");
}
// Validate that PreviousSteps_name's all refer to workflow steps.
for (WorkflowElement wfe : wfelements)
{
for (String ps : wfe.getPreviousSteps_Name())
{
if (!wfeNamesSet.contains(ps)) printError("In your workflow, the PreviousSteps_name '"
+ ps
+ "' is not a workflow step name, because it does not match to a value in the 'name' column. Please fix this.");
}
}
// Validate that all protocols referred to, exist.
// First put protocol names in a list
List<String> protocolNames = new ArrayList<String>();
for (ComputeProtocol cp : cb.getComputeProtocols())
{
protocolNames.add(cp.getName());
}
for (WorkflowElement wfe : wfelements)
{
String pn = wfe.getProtocol_Name();
if (!protocolNames.contains(pn))
{
printError("In your workflow file, the protocol name '"
+ pn
+ "' in the 'protocol_name' column, does not refer to an known protocol.\nPlease upload a protocol with the name '"
+ pn + ".ftl' or change '" + pn + "' to the name of an known protocol.");
}
}
// Validate that a file called 'Submit.sh.ftl' exists.
if (!protocolNames.contains("Submit.sh"))
{
printError("You should have a protocol 'Submit.sh.ftl' in which you define how to submit the generated scripts.\n"
+ "You may use the following code that is compatible with a PBS-scheduler.\n\n"
+ "DIR=\"$( cd \"$( dirname \"<#noparse>${BASH_SOURCE[0]}</#noparse>\" )\" && pwd )\""
+ "touch $DIR/${workflowfilename}.started\n"
+ "\n"
+ "<#foreach j in jobs>\n"
+ "#${j.name}\n"
+ "${j.name}=$(qsub -N ${j.name}<#if j.prevSteps_Name?size > 0> -W depend=afterok<#foreach d in j.prevSteps_Name>:$${d}</#foreach></#if> ${j.name}.sh)\n"
+ "echo $${j.name}\n" + "sleep 0\n" + "</#foreach>");
}
// VALIDATE PARAMETERS
// Validate that all hasOne_name's refer to parameter names
// Moreover, only allow one instance of each parameter
HashSet<String> params = new HashSet<String>();
HashSet<String> hasOnes = new HashSet<String>();
for (ComputeParameter cp : cb.getComputeParameters())
{
String p = cp.getName();
if (params.contains(p)) printError("In your paramer file, parameter '" + p
+ "' occurs more than once, which is not allowed.\nPlease fix this.");
params.add(p);
hasOnes.addAll(cp.getHasOne_Name());
}
for (String h : hasOnes)
{
if (!params.contains(h)) printError("In your parameters file, in your hasOne_name column, you refer to a non-existing parameter '"
+ h + "'. Please add this parameter to your file.");
}
}
| public void validateBundle()
{
// VALIDATE WORKFLOW
List<WorkflowElement> wfelements = cb.getWorkflowElements();
// Validate that all wfe step names are different
List<String> wfeNamesList = new ArrayList<String>();
Set<String> wfeNamesSet = new HashSet();
for (WorkflowElement wfe : wfelements)
{
wfeNamesList.add(wfe.getName());
wfeNamesSet.add(wfe.getName());
}
if (wfeNamesList.size() != wfeNamesSet.size())
{
printError("In your workflow file, you have duplicate workflow step names. All values in the column 'name' should be different. Please fix this.");
}
// Validate that PreviousSteps_name's all refer to workflow steps.
for (WorkflowElement wfe : wfelements)
{
for (String ps : wfe.getPreviousSteps_Name())
{
if (!wfeNamesSet.contains(ps)) printError("In your workflow, the PreviousSteps_name '"
+ ps
+ "' is not a workflow step name, because it does not match to a value in the 'name' column. Please fix this.");
}
}
// Validate that all protocols referred to, exist.
// First put protocol names in a list
List<String> protocolNames = new ArrayList<String>();
for (ComputeProtocol cp : cb.getComputeProtocols())
{
protocolNames.add(cp.getName());
}
for (WorkflowElement wfe : wfelements)
{
String pn = wfe.getProtocol_Name();
if (!protocolNames.contains(pn))
{
printError("In your workflow file, the protocol name '"
+ pn
+ "' in the 'protocol_name' column, does not refer to an known protocol.\nPlease upload a protocol with the name '"
+ pn + ".ftl' or change '" + pn + "' to the name of an known protocol.");
}
}
// Validate that a file called 'Submit.sh.ftl' exists.
if (!protocolNames.contains("Submit.sh"))
{
printError("You should have a protocol 'Submit.sh.ftl' in which you define how to submit the generated scripts.\n"
+ "You may use the following code that is compatible with a PBS-scheduler.\n\n"
+ "DIR=\"$( cd \"$( dirname \"<#noparse>${BASH_SOURCE[0]}</#noparse>\" )\" && pwd )\""
+ "\n"
+ "touch $DIR/${workflowfilename}.started\n"
+ "\n"
+ "<#foreach j in jobs>\n"
+ "#${j.name}\n"
+ "${j.name}=$(qsub -N ${j.name}<#if j.prevSteps_Name?size > 0> -W depend=afterok<#foreach d in j.prevSteps_Name>:$${d}</#foreach></#if> ${j.name}.sh)\n"
+ "echo $${j.name}\n"
+ "sleep 0\n"
+ "</#foreach>\n"
+ "\n"
+ "touch $DIR/${workflowfilename}.finished");
}
// VALIDATE PARAMETERS
// Validate that all hasOne_name's refer to parameter names
// Moreover, only allow one instance of each parameter
HashSet<String> params = new HashSet<String>();
HashSet<String> hasOnes = new HashSet<String>();
for (ComputeParameter cp : cb.getComputeParameters())
{
String p = cp.getName();
if (params.contains(p)) printError("In your paramer file, parameter '" + p
+ "' occurs more than once, which is not allowed.\nPlease fix this.");
params.add(p);
hasOnes.addAll(cp.getHasOne_Name());
}
for (String h : hasOnes)
{
if (!params.contains(h)) printError("In your parameters file, in your hasOne_name column, you refer to a non-existing parameter '"
+ h + "'. Please add this parameter to your file.");
}
}
|
diff --git a/src/net/reichholf/dreamdroid/helpers/SimpleHttpClient.java b/src/net/reichholf/dreamdroid/helpers/SimpleHttpClient.java
index 691dc667..27ce15bc 100644
--- a/src/net/reichholf/dreamdroid/helpers/SimpleHttpClient.java
+++ b/src/net/reichholf/dreamdroid/helpers/SimpleHttpClient.java
@@ -1,255 +1,257 @@
/* © 2010 Stephan Reichholf <stephan at reichholf dot net>
*
* Licensed under the Create-Commons Attribution-Noncommercial-Share Alike 3.0 Unported
* http://creativecommons.org/licenses/by-nc-sa/3.0/
*/
package net.reichholf.dreamdroid.helpers;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import net.reichholf.dreamdroid.DreamDroid;
import net.reichholf.dreamdroid.Profile;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.ByteArrayBuffer;
import android.util.Log;
/**
* @author sreichholf
*
*/
public class SimpleHttpClient {
public static String LOG_TAG = "SimpleHttpClient";
private String mPrefix;
private String mHostname;
private String mStreamHostname;
private String mPort;
private String mFilePort;
private String mUser;
private String mPass;
private byte[] mBytes;
private String mErrorText;
private boolean mLogin;
private boolean mSsl;
private boolean mError;
private boolean mIsLoopProtected;
/**
* @param sp
* SharedPreferences of the Base-Context
*/
public SimpleHttpClient() {
try {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[] { new EasyX509TrustManager(null) }, null);
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
} catch (KeyManagementException e) {
} catch (NoSuchAlgorithmException e) {
} catch (KeyStoreException e) {
}
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
applyConfig();
}
/**
* @param user
* Username for http-auth
* @param pass
* Password for http-auth
*/
public void setCredentials(final String user, final String pass) {
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass.toCharArray());
}
});
}
/**
*
*/
public void unsetCrendentials() {
// mDhc.getCredentialsProvider().setCredentials(AuthScope.ANY, null);
}
/**
* @param uri
* @param parameters
* @return
*/
public String buildUrl(String uri, List<NameValuePair> parameters) {
String parms = URLEncodedUtils.format(parameters, HTTP.UTF_8).replace("+", "%20");
return mPrefix + mHostname + ":" + mPort + uri + parms;
}
/**
* @param uri
* @param parameters
* @return
*/
public String buildFileStreamUrl(String uri, List<NameValuePair> parameters) {
String parms = URLEncodedUtils.format(parameters, HTTP.UTF_8).replace("+", "%20");
return "http://" + mStreamHostname + ":" + mFilePort + uri + parms;
}
public boolean fetchPageContent(String uri) {
return fetchPageContent(uri, new ArrayList<NameValuePair>());
}
/**
* @param uri
* @param parameters
* @return
*/
public boolean fetchPageContent(String uri, List<NameValuePair> parameters) {
// Set login, ssl, port, host etc;
applyConfig();
mErrorText = "";
mError = false;
mBytes = new byte[0];
if (!uri.startsWith("/")) {
uri = "/".concat(uri);
}
HttpURLConnection conn = null;
try {
URL url = new URL(buildUrl(uri, parameters));
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
if (DreamDroid.featurePostRequest())
conn.setRequestMethod("POST");
if (conn.getResponseCode() != 200) {
if (conn.getResponseCode() == 405 && !mIsLoopProtected) {
// Method not allowed, the target device either can't handle
// POST or GET requests (old device or Anti-Hijack enabled)
DreamDroid.setFeaturePostRequest(!DreamDroid.featurePostRequest());
conn.disconnect();
mIsLoopProtected = true;
return fetchPageContent(uri, parameters);
}
mIsLoopProtected = false;
mErrorText = conn.getResponseMessage();
mError = true;
return false;
}
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int read = 0;
int bufSize = 512;
byte[] buffer = new byte[bufSize];
while ((read = bis.read(buffer)) != -1) {
baf.append(buffer, 0, read);
}
mBytes = baf.toByteArray();
return true;
} catch (MalformedURLException e) {
mError = true;
mErrorText = e.toString();
} catch (IOException e) {
mError = true;
mErrorText = e.toString();
} catch (Exception e) {
mError = true;
mErrorText = e.toString();
} finally {
if (conn != null)
conn.disconnect();
if (mError)
+ if(mErrorText == null)
+ mErrorText = "Error text is null";
Log.e(LOG_TAG, mErrorText);
}
return false;
}
/**
* @return
*/
public String getPageContentString() {
return new String(mBytes);
}
public byte[] getBytes() {
return mBytes;
}
/**
* @return
*/
public String getErrorText() {
return mErrorText;
}
/**
* @return
*/
public boolean hasError() {
return mError;
}
/**
*
*/
public void applyConfig() {
Profile p = DreamDroid.getCurrentProfile();
mHostname = p.getHost().trim();
mStreamHostname = p.getStreamHost().trim();
mPort = p.getPortString();
mFilePort = p.getFilePortString();
mLogin = p.isLogin();
mSsl = p.isSsl();
if (mSsl) {
mPrefix = "https://";
} else {
mPrefix = "http://";
}
if (mLogin) {
mUser = p.getUser();
mPass = p.getPass();
setCredentials(mUser, mPass);
}
}
/**
* @param sp
* @return
*/
public static SimpleHttpClient getInstance() {
return new SimpleHttpClient();
}
}
| true | true | public boolean fetchPageContent(String uri, List<NameValuePair> parameters) {
// Set login, ssl, port, host etc;
applyConfig();
mErrorText = "";
mError = false;
mBytes = new byte[0];
if (!uri.startsWith("/")) {
uri = "/".concat(uri);
}
HttpURLConnection conn = null;
try {
URL url = new URL(buildUrl(uri, parameters));
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
if (DreamDroid.featurePostRequest())
conn.setRequestMethod("POST");
if (conn.getResponseCode() != 200) {
if (conn.getResponseCode() == 405 && !mIsLoopProtected) {
// Method not allowed, the target device either can't handle
// POST or GET requests (old device or Anti-Hijack enabled)
DreamDroid.setFeaturePostRequest(!DreamDroid.featurePostRequest());
conn.disconnect();
mIsLoopProtected = true;
return fetchPageContent(uri, parameters);
}
mIsLoopProtected = false;
mErrorText = conn.getResponseMessage();
mError = true;
return false;
}
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int read = 0;
int bufSize = 512;
byte[] buffer = new byte[bufSize];
while ((read = bis.read(buffer)) != -1) {
baf.append(buffer, 0, read);
}
mBytes = baf.toByteArray();
return true;
} catch (MalformedURLException e) {
mError = true;
mErrorText = e.toString();
} catch (IOException e) {
mError = true;
mErrorText = e.toString();
} catch (Exception e) {
mError = true;
mErrorText = e.toString();
} finally {
if (conn != null)
conn.disconnect();
if (mError)
Log.e(LOG_TAG, mErrorText);
}
return false;
}
| public boolean fetchPageContent(String uri, List<NameValuePair> parameters) {
// Set login, ssl, port, host etc;
applyConfig();
mErrorText = "";
mError = false;
mBytes = new byte[0];
if (!uri.startsWith("/")) {
uri = "/".concat(uri);
}
HttpURLConnection conn = null;
try {
URL url = new URL(buildUrl(uri, parameters));
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
if (DreamDroid.featurePostRequest())
conn.setRequestMethod("POST");
if (conn.getResponseCode() != 200) {
if (conn.getResponseCode() == 405 && !mIsLoopProtected) {
// Method not allowed, the target device either can't handle
// POST or GET requests (old device or Anti-Hijack enabled)
DreamDroid.setFeaturePostRequest(!DreamDroid.featurePostRequest());
conn.disconnect();
mIsLoopProtected = true;
return fetchPageContent(uri, parameters);
}
mIsLoopProtected = false;
mErrorText = conn.getResponseMessage();
mError = true;
return false;
}
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int read = 0;
int bufSize = 512;
byte[] buffer = new byte[bufSize];
while ((read = bis.read(buffer)) != -1) {
baf.append(buffer, 0, read);
}
mBytes = baf.toByteArray();
return true;
} catch (MalformedURLException e) {
mError = true;
mErrorText = e.toString();
} catch (IOException e) {
mError = true;
mErrorText = e.toString();
} catch (Exception e) {
mError = true;
mErrorText = e.toString();
} finally {
if (conn != null)
conn.disconnect();
if (mError)
if(mErrorText == null)
mErrorText = "Error text is null";
Log.e(LOG_TAG, mErrorText);
}
return false;
}
|
diff --git a/cli/src/main/java/com/vmware/bdd/cli/commands/ClusterCommands.java b/cli/src/main/java/com/vmware/bdd/cli/commands/ClusterCommands.java
index 833158b8..ca899bde 100644
--- a/cli/src/main/java/com/vmware/bdd/cli/commands/ClusterCommands.java
+++ b/cli/src/main/java/com/vmware/bdd/cli/commands/ClusterCommands.java
@@ -1,1180 +1,1180 @@
/*****************************************************************************
* Copyright (c) 2012 VMware, Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.vmware.bdd.cli.commands;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import jline.ConsoleReader;
import org.apache.hadoop.conf.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.hadoop.impala.hive.HiveCommands;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.stereotype.Component;
import com.vmware.bdd.apitypes.Cluster.ClusterType;
import com.vmware.bdd.apitypes.ClusterCreate;
import com.vmware.bdd.apitypes.ClusterRead;
import com.vmware.bdd.apitypes.DistroRead;
import com.vmware.bdd.apitypes.NetworkRead;
import com.vmware.bdd.apitypes.NodeGroupCreate;
import com.vmware.bdd.apitypes.NodeGroupRead;
import com.vmware.bdd.apitypes.NodeRead;
import com.vmware.bdd.cli.rest.CliRestException;
import com.vmware.bdd.cli.rest.ClusterRestClient;
import com.vmware.bdd.cli.rest.DistroRestClient;
import com.vmware.bdd.cli.rest.NetworkRestClient;
import com.vmware.bdd.utils.AppConfigValidationUtils;
import com.vmware.bdd.utils.AppConfigValidationUtils.ValidationType;
import com.vmware.bdd.utils.ValidateResult;
@Component
public class ClusterCommands implements CommandMarker {
@Autowired
private DistroRestClient distroRestClient;
@Autowired
private NetworkRestClient networkRestClient;
@Autowired
private ClusterRestClient restClient;
@Autowired
private Configuration hadoopConfiguration;
@Autowired
private HiveCommands hiveCommands;
private String hiveInfo;
private String targetClusterName;
private boolean alwaysAnswerYes;
//define role of the node group .
private enum NodeGroupRole {
MASTER, WORKER, CLIENT, NONE
}
@CliAvailabilityIndicator({ "cluster help" })
public boolean isCommandAvailable() {
return true;
}
@CliCommand(value = "cluster create", help = "Create a default vhadoop cluster")
public void createCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "distro" }, mandatory = false, help = "Hadoop Distro") final String distro,
@CliOption(key = { "specFile" }, mandatory = false, help = "The spec file name path") final String specFilePath,
@CliOption(key = { "rpNames" }, mandatory = false, help = "Resource Pools for the cluster: use \",\" among names.") final String rpNames,
@CliOption(key = { "dsNames" }, mandatory = false, help = "Datastores for the cluster: use \",\" among names.") final String dsNames,
@CliOption(key = { "networkName" }, mandatory = false, help = "Network Name") final String networkName,
@CliOption(key = { "resume" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to resume cluster creation") final boolean resume,
@CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation,
@CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) {
this.alwaysAnswerYes = alwaysAnswerYes;
//validate the name
if (name.indexOf("-") != -1) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CLUSTER
+ Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE);
return;
}
//process resume
if (resume) {
resumeCreateCluster(name);
return;
}
// build ClusterCreate object
ClusterCreate clusterCreate = new ClusterCreate();
clusterCreate.setName(name);
if (distro != null) {
List<String> distroNames = getDistroNames();
if (validName(distro, distroNames)) {
clusterCreate.setDistro(distro);
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_DISTRO
+ Constants.PARAM_NOT_SUPPORTED + distroNames);
return;
}
}
clusterCreate.setType(Enum.valueOf(ClusterType.class, "HADOOP"));
if (rpNames != null) {
List<String> rpNamesList = CommandsUtils.inputsConvert(rpNames);
if (rpNamesList.isEmpty()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INPUT_RPNAMES_PARAM + Constants.MULTI_INPUTS_CHECK);
return;
} else {
clusterCreate.setRpNames(rpNamesList);
}
}
if (dsNames != null) {
List<String> dsNamesList = CommandsUtils.inputsConvert(dsNames);
if (dsNamesList.isEmpty()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INPUT_DSNAMES_PARAM + Constants.MULTI_INPUTS_CHECK);
return;
} else {
clusterCreate.setDsNames(dsNamesList);
}
}
List<String> warningMsgList = new ArrayList<String>();
try {
if (specFilePath != null) {
ClusterCreate clusterSpec =
CommandsUtils.getObjectByJsonString(ClusterCreate.class, CommandsUtils.dataFromFile(specFilePath));
clusterCreate.setExternalHDFS(clusterSpec.getExternalHDFS());
clusterCreate.setNodeGroups(clusterSpec.getNodeGroups());
clusterCreate.setConfiguration(clusterSpec.getConfiguration());
validateConfiguration(clusterCreate, skipConfigValidation, warningMsgList);
if (!validateHAInfo(clusterCreate.getNodeGroups())){
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CLUSTER_SPEC_HA_ERROR + specFilePath);
return;
}
}
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
return;
}
List<String> networkNames = getNetworkNames();
if (networkNames.isEmpty()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_EXISTED);
return;
} else {
if (networkName != null) {
if (validName(networkName, networkNames)) {
clusterCreate.setNetworkName(networkName);
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_NETWORK_NAME
+ Constants.PARAM_NOT_SUPPORTED + networkNames);
return;
}
} else {
if (networkNames.size() == 1) {
clusterCreate.setNetworkName(networkNames.get(0));
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_NETWORK_NAME
+ Constants.PARAM_NOT_SPECIFIED);
return;
}
}
}
// Validate that the specified file is correct json format and proper value.
if (specFilePath != null) {
if (!validateClusterCreate(clusterCreate)) {
return;
}
}
// rest invocation
try {
if (!showWarningMsg(clusterCreate.getName(), warningMsgList)) {
return;
}
restClient.create(clusterCreate);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_CREAT);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
@CliCommand(value = "cluster list", help = "Get cluster information")
public void getCluster(
@CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name,
@CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) {
// rest invocation
try {
if (name == null) {
ClusterRead[] clusters = restClient.getAll();
if (clusters != null) {
prettyOutputClustersInfo(clusters, detail);
}
} else {
ClusterRead cluster = restClient.get(name);
if (cluster != null) {
prettyOutputClusterInfo(cluster, detail);
}
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster export --spec", help = "Export cluster specification")
public void exportClusterSpec(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "output" }, mandatory = false, help = "The output file name") final String fileName) {
// rest invocation
try {
ClusterCreate cluster = restClient.getSpec(name);
if (cluster != null) {
CommandsUtils.prettyJsonOutput(cluster, fileName);
}
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_EXPORT, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster delete", help = "Delete a cluster")
public void deleteCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name) {
//rest invocation
try {
restClient.delete(name);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESULT_DELETE);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster start", help = "Start a cluster")
public void startCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName,
@CliOption(key = { "nodeGroupName" }, mandatory = false, help = "The node group name") final String nodeGroupName,
@CliOption(key = { "nodeName" }, mandatory = false, help = "The node name") final String nodeName) {
Map<String, String> queryStrings = new HashMap<String, String>();
queryStrings
.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_START);
//rest invocation
try {
if (!validateNodeGroupName(nodeGroupName)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL,
"invalid node group name");
return;
}
if (!validateNodeName(clusterName, nodeGroupName, nodeName)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL,
"invalid node name");
return;
}
String groupName = nodeGroupName;
String fullNodeName = nodeName;
if (nodeName != null) {
if (nodeGroupName == null) {
groupName = extractNodeGroupName(nodeName);
if (groupName == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL,
"missing node group name");
return;
}
} else {
fullNodeName = autoCompleteNodeName(clusterName, nodeGroupName, nodeName);
}
}
String resource = getClusterResourceName(clusterName, groupName, fullNodeName);
if (resource != null) {
restClient.actionOps(resource, clusterName, queryStrings);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_RESULT_START);
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster stop", help = "Stop a cluster")
public void stopCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName,
@CliOption(key = { "nodeGroupName" }, mandatory = false, help = "The node group name") final String nodeGroupName,
@CliOption(key = { "nodeName" }, mandatory = false, help = "The node name") final String nodeName) {
Map<String, String> queryStrings = new HashMap<String, String>();
queryStrings.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_STOP);
//rest invocation
try {
if (!validateNodeGroupName(nodeGroupName)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL,
"invalid node group name");
return;
}
if (!validateNodeName(clusterName, nodeGroupName, nodeName)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL,
"invalid node name");
return;
}
String groupName = nodeGroupName;
String fullNodeName = nodeName;
if (nodeName != null) {
if (nodeGroupName == null) {
groupName = extractNodeGroupName(nodeName);
if (groupName == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL,
"missing node group name");
return;
}
} else {
fullNodeName = autoCompleteNodeName(clusterName, nodeGroupName, nodeName);
}
}
- String resource = getClusterResourceName(clusterName, nodeGroupName, fullNodeName);
+ String resource = getClusterResourceName(clusterName, groupName, fullNodeName);
if (resource != null) {
restClient.actionOps(resource, clusterName, queryStrings);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_RESULT_STOP);
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster resize", help = "Resize a cluster")
public void resizeCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "nodeGroup" }, mandatory = true, help = "The node group name") final String nodeGroup,
@CliOption(key = { "instanceNum" }, mandatory = true, help = "The resized number of instances. It should be larger that existing one") final int instanceNum) {
if (instanceNum > 1) {
try {
restClient.resize(name, nodeGroup, instanceNum);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESULT_RESIZE);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INVALID_VALUE + " instanceNum=" + instanceNum);
}
}
@CliCommand(value = "cluster target", help = "Set or query target cluster to run commands")
public void targetCluster(
@CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name,
@CliOption(key = { "info" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show target information") final boolean info) {
ClusterRead cluster = null;
try {
if (info) {
if (name != null) {
System.out.println("Warning: can't specify option --name and --info at the same time");
return;
}
String fsUrl = hadoopConfiguration.get("fs.default.name");
String jtUrl = hadoopConfiguration.get("mapred.job.tracker");
if ((fsUrl == null || fsUrl.length() == 0) && (jtUrl == null || jtUrl.length() == 0)) {
System.out.println("There is no cluster be targeted now, target cluster first");
return;
}
if(targetClusterName != null && targetClusterName.length() > 0){
System.out.println("Cluster: " + targetClusterName);
}
if (fsUrl != null && fsUrl.length() > 0) {
System.out.println("HDFS url: " + fsUrl);
}
if (jtUrl != null && jtUrl.length() > 0) {
System.out.println("Job Tracker url: " + jtUrl);
}
if (hiveInfo != null && hiveInfo.length() > 0) {
System.out.println("Hive server url: " + hiveInfo);
}
} else {
if (name == null) {
ClusterRead[] clusters = restClient.getAll();
if (clusters != null && clusters.length > 0) {
cluster = clusters[0];
}
} else {
cluster = restClient.get(name);
}
if (cluster == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_TARGET,
Constants.OUTPUT_OP_RESULT_FAIL, "No valid target available");
} else {
targetClusterName = cluster.getName();
for (NodeGroupRead nodeGroup : cluster.getNodeGroups()) {
for (String role : nodeGroup.getRoles()) {
if (role.equals("hadoop_namenode")) {
List<NodeRead> nodes = nodeGroup.getInstances();
if (nodes != null && nodes.size() > 0) {
String nameNodeIP = nodes.get(0).getIp();
setNameNode(nameNodeIP);
} else {
throw new CliRestException("no name node available");
}
}
if (role.equals("hadoop_jobtracker")) {
List<NodeRead> nodes = nodeGroup.getInstances();
if (nodes != null && nodes.size() > 0) {
String jobTrackerIP = nodes.get(0).getIp();
setJobTracker(jobTrackerIP);
} else {
throw new CliRestException("no job tracker available");
}
}
if (role.equals("hive_server")) {
List<NodeRead> nodes = nodeGroup.getInstances();
if (nodes != null && nodes.size() > 0) {
String hiveServerIP = nodes.get(0).getIp();
setHiveServer(hiveServerIP);
} else {
throw new CliRestException("no hive server available");
}
}
}
}
if (cluster.getExternalHDFS() != null && !cluster.getExternalHDFS().isEmpty()) {
setFsURL(cluster.getExternalHDFS());
}
}
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_TARGET,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
private void setNameNode(String nameNodeAddress) {
String hdfsUrl = "webhdfs://" + nameNodeAddress + ":50070";
setFsURL(hdfsUrl);
}
private void setFsURL(String fsURL) {
hadoopConfiguration.set("fs.default.name", fsURL);
}
private void setJobTracker(String jobTrackerAddress) {
String jobTrackerUrl = jobTrackerAddress + ":8021";
hadoopConfiguration.set("mapred.job.tracker", jobTrackerUrl);
}
private void setHiveServer(String hiveServerAddress) {
try {
hiveInfo = hiveCommands.config(hiveServerAddress, 10000, null);
} catch (Exception e) {
throw new CliRestException("faild to set hive server address");
}
}
@CliCommand(value = "cluster config", help = "Config an existing cluster")
public void configCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "specFile" }, mandatory = true, help = "The spec file name path") final String specFilePath,
@CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation,
@CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) {
this.alwaysAnswerYes = alwaysAnswerYes;
//validate the name
if (name.indexOf("-") != -1) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CONFIG,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE);
return;
}
try {
ClusterRead clusterRead = restClient.get(name);
// build ClusterCreate object
ClusterCreate clusterConfig = new ClusterCreate();
clusterConfig.setName(clusterRead.getName());
ClusterCreate clusterSpec =
CommandsUtils.getObjectByJsonString(ClusterCreate.class, CommandsUtils.dataFromFile(specFilePath));
clusterConfig.setNodeGroups(clusterSpec.getNodeGroups());
clusterConfig.setConfiguration(clusterSpec.getConfiguration());
List<String> warningMsgList = new ArrayList<String>();
validateConfiguration(clusterConfig, skipConfigValidation, warningMsgList);
// add a confirm message for running job
warningMsgList.add("Warning: " + Constants.PARAM_CLUSTER_CONFIG_RUNNING_JOB_WARNING);
if (!showWarningMsg(clusterConfig.getName(), warningMsgList)) {
return;
}
restClient.configCluster(clusterConfig);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_CONFIG);
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CONFIG,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
return;
}
}
private String getClusterResourceName(String cluster, String nodeGroup, String node) {
assert cluster != null; // Spring shell guarantees this
if (node != null && nodeGroup == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, cluster,
Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.OUTPUT_OP_NODEGROUP_MISSING);
return null;
}
StringBuilder res = new StringBuilder();
res.append(cluster);
if (nodeGroup != null) {
res.append("/nodegroup/").append(nodeGroup);
if (node != null) {
res.append("/node/").append(node);
}
}
return res.toString();
}
private boolean validateNodeName(String cluster, String group, String node) {
if (node != null) {
String[] parts = node.split("-");
if (parts.length == 1) {
return true;
}
if (parts.length == 3) {
if (!parts[0].equals(cluster)) {
return false;
}
if (group != null && !parts[1].equals(group)) {
return false;
}
return true;
}
return false;
}
return true;
}
private boolean validateNodeGroupName(String group) {
if (group != null) {
return group.indexOf("-") == -1;
}
return true;
}
private String autoCompleteNodeName(String cluster, String group, String node) {
assert cluster != null;
assert group != null;
assert node != null;
if (node.indexOf("-") == -1) {
StringBuilder sb = new StringBuilder();
sb.append(cluster).append("-").append(group).append("-").append(node);
return sb.toString();
}
return node;
}
private String extractNodeGroupName(String node) {
String[] parts = node.split("-");
if (parts.length == 3) {
return parts[1];
}
return null;
}
private void resumeCreateCluster(final String name) {
Map<String, String> queryStrings = new HashMap<String, String>();
queryStrings.put(Constants.QUERY_ACTION_KEY,
Constants.QUERY_ACTION_RESUME);
try {
restClient.actionOps(name, queryStrings);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESULT_RESUME);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESUME, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
private List<String> getNetworkNames() {
List<String> networkNames = new ArrayList<String>(0);
NetworkRead[] networks = networkRestClient.getAll(false);
if (networks != null) {
for (NetworkRead network : networks)
networkNames.add(network.getName());
}
return networkNames;
}
private List<String> getDistroNames() {
List<String> distroNames = new ArrayList<String>(0);
DistroRead[] distros = distroRestClient.getAll();
if (distros != null) {
for (DistroRead distro : distros)
distroNames.add(distro.getName());
}
return distroNames;
}
private boolean validName(String inputName, List<String> validNames) {
for (String name : validNames) {
if (name.equals(inputName)) {
return true;
}
}
return false;
}
private void prettyOutputClusterInfo(ClusterRead cluster, boolean detail) {
//cluster Name
System.out.printf("name: %s, distro: %s, status: %s", cluster.getName(),
cluster.getDistro(), cluster.getStatus());
System.out.println();
if(cluster.getExternalHDFS() != null && !cluster.getExternalHDFS().isEmpty()) {
System.out.printf("external HDFS: %s\n", cluster.getExternalHDFS());
}
LinkedHashMap<String, List<String>> ngColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
List<NodeGroupRead> nodegroups = cluster.getNodeGroups();
if (nodegroups != null) {
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_ROLES, Arrays.asList("getRoles"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_INSTANCE,
Arrays.asList("getInstanceNum"));
ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_CPU,
Arrays.asList("getCpuNum"));
ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_MEM,
Arrays.asList("getMemCapacityMB"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_TYPE,
Arrays.asList("getStorage", "getType"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_SIZE,
Arrays.asList("getStorage", "getSizeGB"));
try {
if (detail) {
LinkedHashMap<String, List<String>> nColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NAME,
Arrays.asList("getName"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_HOST,
Arrays.asList("getHostName"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_IP, Arrays.asList("getIp"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_STATUS,
Arrays.asList("getStatus"));
for (NodeGroupRead nodegroup : nodegroups) {
CommandsUtils.printInTableFormat(
ngColumnNamesWithGetMethodNames,
new NodeGroupRead[] { nodegroup },
Constants.OUTPUT_INDENT);
List<NodeRead> nodes = nodegroup.getInstances();
if (nodes != null) {
System.out.println();
CommandsUtils.printInTableFormat(
nColumnNamesWithGetMethodNames, nodes.toArray(),
new StringBuilder().append(Constants.OUTPUT_INDENT)
.append(Constants.OUTPUT_INDENT).toString());
}
System.out.println();
}
} else
CommandsUtils.printInTableFormat(
ngColumnNamesWithGetMethodNames, nodegroups.toArray(),
Constants.OUTPUT_INDENT);
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
cluster.getName(), Constants.OUTPUT_OP_LIST,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
}
private void prettyOutputClustersInfo(ClusterRead[] clusters, boolean detail) {
for (ClusterRead cluster : clusters) {
prettyOutputClusterInfo(cluster, detail);
System.out.println();
}
}
/**
* Validate nodeGroupCreates member formats and values in the ClusterCreate.
*/
private boolean validateClusterCreate(ClusterCreate clusterCreate) {
// validation status
boolean validated = true;
// show warning message
boolean warning = false;
//role count
int masterCount = 0, workerCount = 0, clientCount = 0;
//Find NodeGroupCreate array from current ClusterCreate instance.
NodeGroupCreate[] nodeGroupCreates = clusterCreate.getNodeGroups();
if (nodeGroupCreates == null || nodeGroupCreates.length == 0) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterCreate.getName(), Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.MULTI_INPUTS_CHECK);
return !validated;
} else {
//used for collecting failed message.
List<String> failedMsgList = new LinkedList<String>();
//find distro roles.
List<String> distroRoles = findDistroRoles(clusterCreate);
if (distroRoles == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterCreate.getName(), Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_NO_DISTRO_AVAILABLE);
return !validated;
}
if (nodeGroupCreates.length < 2 || nodeGroupCreates.length > 4) {
warning = true;
}
// check external HDFS
if (clusterCreate.hasHDFSUrlConfigured() && !clusterCreate.validateHDFSUrl()) {
failedMsgList.add(new StringBuilder()
.append("externalHDFS=")
.append(clusterCreate.getExternalHDFS()).toString());
validated = false;
}
// check placement policies
if (!clusterCreate.validateNodeGroupPlacementPolicies(failedMsgList)) {
validated = false;
}
if (!clusterCreate.validateNodeGroupRoles(failedMsgList)) {
validated = false;
}
for (NodeGroupCreate nodeGroupCreate : nodeGroupCreates) {
// check node group's instanceNum
if (!checkInstanceNum(nodeGroupCreate, failedMsgList)) {
validated = false;
}
// check node group's roles
if (!checkNodeGroupRoles(nodeGroupCreate, distroRoles,
failedMsgList)) {
validated = false;
}
// get node group role .
NodeGroupRole role = getNodeGroupRole(nodeGroupCreate);
switch (role) {
case MASTER:
masterCount++;
if (nodeGroupCreate.getInstanceNum() >= 0
&& nodeGroupCreate.getInstanceNum() != 1) {
validated = false;
collectInstanceNumInvalidateMsg(nodeGroupCreate,
failedMsgList);
}
break;
case WORKER:
workerCount++;
if (nodeGroupCreate.getInstanceNum() == 0) {
validated = false;
collectInstanceNumInvalidateMsg(nodeGroupCreate,
failedMsgList);
} else if (isHAFlag(nodeGroupCreate)) {
warning = true;
}
break;
case CLIENT:
clientCount++;
if (nodeGroupCreate.getInstanceNum() == 0
|| isHAFlag(nodeGroupCreate)) {
warning = true;
}
break;
case NONE:
warning = true;
break;
default:
}
}
if ((masterCount < 1 || masterCount > 2) || (workerCount < 1 || workerCount > 2) ||
clientCount > 1) {
warning = true;
}
if (!validated) {
showFailedMsg(clusterCreate.getName(), failedMsgList);
} else if (warning) {
// If warning is true,show waring message.
showWarningMsg();
// When exist warning message,whether to proceed
if (!isContinue(clusterCreate.getName(),Constants.OUTPUT_OP_CREATE,Constants.PARAM_PROMPT_CONTINUE_MESSAGE)) {
validated = false;
}
}
return validated;
}
}
private boolean isContinue(String clusterName, String operateType, String promptMsg) {
if (this.alwaysAnswerYes) {
return true;
}
boolean continueCreate = true;
boolean continueLoop = true;
String readMsg = "";
try {
ConsoleReader reader = new ConsoleReader();
int k = 0;
while (continueLoop) {
if (k >= 3) {
continueCreate = false;
break;
}
// Prompt continue information
System.out.print(promptMsg);
// Get user's entering
readMsg = reader.readLine();
if (readMsg.trim().equalsIgnoreCase("yes")
|| readMsg.trim().equalsIgnoreCase("y")) {
continueLoop = false;
} else if (readMsg.trim().equalsIgnoreCase("no")
|| readMsg.trim().equalsIgnoreCase("n")) {
continueLoop = false;
continueCreate = false;
} else {
k++;
}
}
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, operateType,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
continueCreate = false;
}
return continueCreate;
}
private NodeGroupRole getNodeGroupRole(NodeGroupCreate nodeGroupCreate) {
//Find roles list from current NodeGroupCreate instance.
List<String> roles = nodeGroupCreate.getRoles();
for (NodeGroupRole role : NodeGroupRole.values()) {
if (matchRole(role, roles)) {
return role;
}
}
return NodeGroupRole.NONE;
}
/**
* Check the roles was introduced, whether matching with system's specialize
* role.
*/
private boolean matchRole(NodeGroupRole role, List<String> roles) {
List<String> matchRoles = new LinkedList<String>();
switch (role) {
case MASTER:
if (roles.size() == 1) {
String r = roles.get(0);
return Constants.ROLE_HADOOP_NAME_NODE.equals(r) ||
Constants.ROLE_HADOOP_JOB_TRACKER.equals(r);
} else if (roles.size() == 2) {
matchRoles.add(Constants.ROLE_HADOOP_NAME_NODE);
matchRoles.add(Constants.ROLE_HADOOP_JOB_TRACKER);
matchRoles.removeAll(roles);
return matchRoles.size() == 0 ? true : false;
}
return false;
case WORKER:
if (roles.size() == 1) {
if (Constants.ROLE_HADOOP_DATANODE.equals(roles.get(0)) ||
Constants.ROLE_HADOOP_TASKTRACKER.equals(roles.get(0))) {
return true;
}
return false;
} else {
matchRoles.add(Constants.ROLE_HADOOP_DATANODE);
matchRoles.add(Constants.ROLE_HADOOP_TASKTRACKER);
matchRoles.removeAll(roles);
return matchRoles.size() == 0 ? true : false;
}
case CLIENT:
if (roles.size() < 1 || roles.size() > 4) {
return false;
} else {
matchRoles.add(Constants.ROLE_HADOOP_CLIENT);
matchRoles.add(Constants.ROLE_HIVE);
matchRoles.add(Constants.ROLE_HIVE_SERVER);
matchRoles.add(Constants.ROLE_PIG);
int diffNum = matchRoles.size() - roles.size();
matchRoles.removeAll(roles);
return roles.contains(Constants.ROLE_HADOOP_CLIENT)
&& (diffNum >= 0) && (diffNum == matchRoles.size()) ? true
: false;
}
}
return false;
}
private void showWarningMsg() {
System.out.println(Constants.PARAM_CLUSTER_WARNING);
}
private boolean checkInstanceNum(NodeGroupCreate nodeGroup,
List<String> failedMsgList) {
boolean validated = true;
if (nodeGroup.getInstanceNum() < 0) {
validated = false;
collectInstanceNumInvalidateMsg(nodeGroup, failedMsgList);
}
return validated;
}
private void collectInstanceNumInvalidateMsg(NodeGroupCreate nodeGroup,
List<String> failedMsgList) {
failedMsgList.add(new StringBuilder().append(nodeGroup.getName())
.append(".").append("instanceNum=")
.append(nodeGroup.getInstanceNum()).toString());
}
private boolean checkNodeGroupRoles(NodeGroupCreate nodeGroup,
List<String> distroRoles, List<String> failedMsgList) {
List<String> roles = nodeGroup.getRoles();
boolean validated = true;
StringBuilder rolesMsg = new StringBuilder();
for (String role : roles) {
if (!distroRoles.contains(role)) {
validated = false;
rolesMsg.append(",").append(role);
}
}
if (!validated) {
rolesMsg.replace(0, 1, "");
failedMsgList.add(new StringBuilder().append(nodeGroup.getName())
.append(".").append("roles=").append("\"")
.append(rolesMsg.toString()).append("\"").toString());
}
return validated;
}
private List<String> findDistroRoles(ClusterCreate clusterCreate) {
DistroRead distroRead = null;
distroRead =
distroRestClient
.get(clusterCreate.getDistro() != null ? clusterCreate
.getDistro() : Constants.DEFAULT_DISTRO);
if (distroRead != null) {
return distroRead.getRoles();
} else {
return null;
}
}
private void showFailedMsg(String name, List<String> failedMsgList) {
//cluster creation failed message.
StringBuilder failedMsg = new StringBuilder();
failedMsg.append(Constants.INVALID_VALUE);
if (failedMsgList.size() > 1) {
failedMsg.append("s");
}
failedMsg.append(" ");
StringBuilder tmpMsg = new StringBuilder();
for (String msg : failedMsgList) {
tmpMsg.append(",").append(msg);
}
tmpMsg.replace(0, 1, "");
failedMsg.append(tmpMsg);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
failedMsg.toString());
}
private void validateConfiguration(ClusterCreate cluster, boolean skipConfigValidation, List<String> warningMsgList) {
// validate blacklist
ValidateResult blackListResult = validateBlackList(cluster);
if (blackListResult != null) {
addBlackListWarning(blackListResult, warningMsgList);
}
if (!skipConfigValidation) {
// validate whitelist
ValidateResult whiteListResult = validateWhiteList(cluster);
addWhiteListWarning(cluster.getName(), whiteListResult, warningMsgList);
} else {
cluster.setValidateConfig(false);
}
}
private ValidateResult validateBlackList(ClusterCreate cluster) {
return validateConfiguration(cluster, ValidationType.BLACK_LIST);
}
private ValidateResult validateWhiteList(ClusterCreate cluster) {
return validateConfiguration(cluster, ValidationType.WHITE_LIST);
}
private ValidateResult validateConfiguration(ClusterCreate cluster, ValidationType validationType) {
ValidateResult validateResult = new ValidateResult();
// validate cluster level Configuration
ValidateResult vr = null;
if (cluster.getConfiguration() != null && !cluster.getConfiguration().isEmpty()) {
vr = AppConfigValidationUtils.validateConfig(validationType, cluster.getConfiguration());
if (vr.getType() != ValidateResult.Type.VALID) {
validateResult.setType(vr.getType());
validateResult.setFailureNames(vr.getFailureNames());
}
}
// validate nodegroup level Configuration
for (NodeGroupCreate nodeGroup : cluster.getNodeGroups()) {
if (nodeGroup.getConfiguration() != null && !nodeGroup.getConfiguration().isEmpty()) {
vr = AppConfigValidationUtils.validateConfig(validationType, nodeGroup.getConfiguration());
if (vr.getType() != ValidateResult.Type.VALID) {
validateResult.setType(vr.getType());
List<String> failureNames = new LinkedList<String>();
failureNames.addAll(validateResult.getFailureNames());
for (String name : vr.getFailureNames()) {
if (!failureNames.contains(name)) {
failureNames.add(name);
}
}
validateResult.setFailureNames(vr.getFailureNames());
}
}
}
return validateResult;
}
private void addWhiteListWarning(final String clusterName, ValidateResult whiteListResult,
List<String> warningMsgList) {
if (whiteListResult.getType() == ValidateResult.Type.WHITE_LIST_INVALID_NAME) {
String warningMsg =
getValidateWarningMsg(whiteListResult.getFailureNames(),
Constants.PARAM_CLUSTER_NOT_IN_WHITE_LIST_WARNING);
if (warningMsgList != null) {
warningMsgList.add(warningMsg);
}
}
}
private void addBlackListWarning(ValidateResult blackListResult, List<String> warningList) {
if (blackListResult.getType() == ValidateResult.Type.NAME_IN_BLACK_LIST) {
String warningMsg =
getValidateWarningMsg(blackListResult.getFailureNames(), Constants.PARAM_CLUSTER_IN_BLACK_LIST_WARNING);
if (warningList != null)
warningList.add(warningMsg);
}
}
private String getValidateWarningMsg(List<String> failureNames, String warningMsg) {
StringBuilder warningMsgBuff = new StringBuilder();
if (failureNames != null && !failureNames.isEmpty()) {
warningMsgBuff.append("Warning: ");
for (String failureName : failureNames) {
warningMsgBuff.append(failureName).append(", ");
}
warningMsgBuff.delete(warningMsgBuff.length() - 2, warningMsgBuff.length());
if (failureNames.size() > 1) {
warningMsgBuff.append(" are ");
} else {
warningMsgBuff.append(" is ");
}
warningMsgBuff.append(warningMsg);
}
return warningMsgBuff.toString();
}
private boolean showWarningMsg(String clusterName, List<String> warningMsgList) {
if (warningMsgList != null && !warningMsgList.isEmpty()) {
for (String message : warningMsgList) {
System.out.println(message);
}
if (!isContinue(clusterName, Constants.OUTPUT_OP_CREATE, Constants.PARAM_PROMPT_CONTINUE_MESSAGE)) {
return false;
}
}
return true;
}
private boolean isHAFlag(NodeGroupCreate nodeGroupCreate) {
return !CommandsUtils.isBlank(nodeGroupCreate.getHaFlag())
&& !nodeGroupCreate.getHaFlag().equalsIgnoreCase("off");
}
private boolean validateHAInfo(NodeGroupCreate[] nodeGroups) {
List<String> haFlagList = Arrays.asList("off","on","ft");
if (nodeGroups != null){
for(NodeGroupCreate group : nodeGroups){
if (!haFlagList.contains(group.getHaFlag().toLowerCase())){
return false;
}
}
}
return true;
}
}
| true | true | public void createCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "distro" }, mandatory = false, help = "Hadoop Distro") final String distro,
@CliOption(key = { "specFile" }, mandatory = false, help = "The spec file name path") final String specFilePath,
@CliOption(key = { "rpNames" }, mandatory = false, help = "Resource Pools for the cluster: use \",\" among names.") final String rpNames,
@CliOption(key = { "dsNames" }, mandatory = false, help = "Datastores for the cluster: use \",\" among names.") final String dsNames,
@CliOption(key = { "networkName" }, mandatory = false, help = "Network Name") final String networkName,
@CliOption(key = { "resume" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to resume cluster creation") final boolean resume,
@CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation,
@CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) {
this.alwaysAnswerYes = alwaysAnswerYes;
//validate the name
if (name.indexOf("-") != -1) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CLUSTER
+ Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE);
return;
}
//process resume
if (resume) {
resumeCreateCluster(name);
return;
}
// build ClusterCreate object
ClusterCreate clusterCreate = new ClusterCreate();
clusterCreate.setName(name);
if (distro != null) {
List<String> distroNames = getDistroNames();
if (validName(distro, distroNames)) {
clusterCreate.setDistro(distro);
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_DISTRO
+ Constants.PARAM_NOT_SUPPORTED + distroNames);
return;
}
}
clusterCreate.setType(Enum.valueOf(ClusterType.class, "HADOOP"));
if (rpNames != null) {
List<String> rpNamesList = CommandsUtils.inputsConvert(rpNames);
if (rpNamesList.isEmpty()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INPUT_RPNAMES_PARAM + Constants.MULTI_INPUTS_CHECK);
return;
} else {
clusterCreate.setRpNames(rpNamesList);
}
}
if (dsNames != null) {
List<String> dsNamesList = CommandsUtils.inputsConvert(dsNames);
if (dsNamesList.isEmpty()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INPUT_DSNAMES_PARAM + Constants.MULTI_INPUTS_CHECK);
return;
} else {
clusterCreate.setDsNames(dsNamesList);
}
}
List<String> warningMsgList = new ArrayList<String>();
try {
if (specFilePath != null) {
ClusterCreate clusterSpec =
CommandsUtils.getObjectByJsonString(ClusterCreate.class, CommandsUtils.dataFromFile(specFilePath));
clusterCreate.setExternalHDFS(clusterSpec.getExternalHDFS());
clusterCreate.setNodeGroups(clusterSpec.getNodeGroups());
clusterCreate.setConfiguration(clusterSpec.getConfiguration());
validateConfiguration(clusterCreate, skipConfigValidation, warningMsgList);
if (!validateHAInfo(clusterCreate.getNodeGroups())){
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CLUSTER_SPEC_HA_ERROR + specFilePath);
return;
}
}
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
return;
}
List<String> networkNames = getNetworkNames();
if (networkNames.isEmpty()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_EXISTED);
return;
} else {
if (networkName != null) {
if (validName(networkName, networkNames)) {
clusterCreate.setNetworkName(networkName);
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_NETWORK_NAME
+ Constants.PARAM_NOT_SUPPORTED + networkNames);
return;
}
} else {
if (networkNames.size() == 1) {
clusterCreate.setNetworkName(networkNames.get(0));
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_NETWORK_NAME
+ Constants.PARAM_NOT_SPECIFIED);
return;
}
}
}
// Validate that the specified file is correct json format and proper value.
if (specFilePath != null) {
if (!validateClusterCreate(clusterCreate)) {
return;
}
}
// rest invocation
try {
if (!showWarningMsg(clusterCreate.getName(), warningMsgList)) {
return;
}
restClient.create(clusterCreate);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_CREAT);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
@CliCommand(value = "cluster list", help = "Get cluster information")
public void getCluster(
@CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name,
@CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) {
// rest invocation
try {
if (name == null) {
ClusterRead[] clusters = restClient.getAll();
if (clusters != null) {
prettyOutputClustersInfo(clusters, detail);
}
} else {
ClusterRead cluster = restClient.get(name);
if (cluster != null) {
prettyOutputClusterInfo(cluster, detail);
}
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster export --spec", help = "Export cluster specification")
public void exportClusterSpec(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "output" }, mandatory = false, help = "The output file name") final String fileName) {
// rest invocation
try {
ClusterCreate cluster = restClient.getSpec(name);
if (cluster != null) {
CommandsUtils.prettyJsonOutput(cluster, fileName);
}
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_EXPORT, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster delete", help = "Delete a cluster")
public void deleteCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name) {
//rest invocation
try {
restClient.delete(name);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESULT_DELETE);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster start", help = "Start a cluster")
public void startCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName,
@CliOption(key = { "nodeGroupName" }, mandatory = false, help = "The node group name") final String nodeGroupName,
@CliOption(key = { "nodeName" }, mandatory = false, help = "The node name") final String nodeName) {
Map<String, String> queryStrings = new HashMap<String, String>();
queryStrings
.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_START);
//rest invocation
try {
if (!validateNodeGroupName(nodeGroupName)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL,
"invalid node group name");
return;
}
if (!validateNodeName(clusterName, nodeGroupName, nodeName)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL,
"invalid node name");
return;
}
String groupName = nodeGroupName;
String fullNodeName = nodeName;
if (nodeName != null) {
if (nodeGroupName == null) {
groupName = extractNodeGroupName(nodeName);
if (groupName == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL,
"missing node group name");
return;
}
} else {
fullNodeName = autoCompleteNodeName(clusterName, nodeGroupName, nodeName);
}
}
String resource = getClusterResourceName(clusterName, groupName, fullNodeName);
if (resource != null) {
restClient.actionOps(resource, clusterName, queryStrings);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_RESULT_START);
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster stop", help = "Stop a cluster")
public void stopCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName,
@CliOption(key = { "nodeGroupName" }, mandatory = false, help = "The node group name") final String nodeGroupName,
@CliOption(key = { "nodeName" }, mandatory = false, help = "The node name") final String nodeName) {
Map<String, String> queryStrings = new HashMap<String, String>();
queryStrings.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_STOP);
//rest invocation
try {
if (!validateNodeGroupName(nodeGroupName)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL,
"invalid node group name");
return;
}
if (!validateNodeName(clusterName, nodeGroupName, nodeName)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL,
"invalid node name");
return;
}
String groupName = nodeGroupName;
String fullNodeName = nodeName;
if (nodeName != null) {
if (nodeGroupName == null) {
groupName = extractNodeGroupName(nodeName);
if (groupName == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL,
"missing node group name");
return;
}
} else {
fullNodeName = autoCompleteNodeName(clusterName, nodeGroupName, nodeName);
}
}
String resource = getClusterResourceName(clusterName, nodeGroupName, fullNodeName);
if (resource != null) {
restClient.actionOps(resource, clusterName, queryStrings);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_RESULT_STOP);
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster resize", help = "Resize a cluster")
public void resizeCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "nodeGroup" }, mandatory = true, help = "The node group name") final String nodeGroup,
@CliOption(key = { "instanceNum" }, mandatory = true, help = "The resized number of instances. It should be larger that existing one") final int instanceNum) {
if (instanceNum > 1) {
try {
restClient.resize(name, nodeGroup, instanceNum);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESULT_RESIZE);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INVALID_VALUE + " instanceNum=" + instanceNum);
}
}
@CliCommand(value = "cluster target", help = "Set or query target cluster to run commands")
public void targetCluster(
@CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name,
@CliOption(key = { "info" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show target information") final boolean info) {
ClusterRead cluster = null;
try {
if (info) {
if (name != null) {
System.out.println("Warning: can't specify option --name and --info at the same time");
return;
}
String fsUrl = hadoopConfiguration.get("fs.default.name");
String jtUrl = hadoopConfiguration.get("mapred.job.tracker");
if ((fsUrl == null || fsUrl.length() == 0) && (jtUrl == null || jtUrl.length() == 0)) {
System.out.println("There is no cluster be targeted now, target cluster first");
return;
}
if(targetClusterName != null && targetClusterName.length() > 0){
System.out.println("Cluster: " + targetClusterName);
}
if (fsUrl != null && fsUrl.length() > 0) {
System.out.println("HDFS url: " + fsUrl);
}
if (jtUrl != null && jtUrl.length() > 0) {
System.out.println("Job Tracker url: " + jtUrl);
}
if (hiveInfo != null && hiveInfo.length() > 0) {
System.out.println("Hive server url: " + hiveInfo);
}
} else {
if (name == null) {
ClusterRead[] clusters = restClient.getAll();
if (clusters != null && clusters.length > 0) {
cluster = clusters[0];
}
} else {
cluster = restClient.get(name);
}
if (cluster == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_TARGET,
Constants.OUTPUT_OP_RESULT_FAIL, "No valid target available");
} else {
targetClusterName = cluster.getName();
for (NodeGroupRead nodeGroup : cluster.getNodeGroups()) {
for (String role : nodeGroup.getRoles()) {
if (role.equals("hadoop_namenode")) {
List<NodeRead> nodes = nodeGroup.getInstances();
if (nodes != null && nodes.size() > 0) {
String nameNodeIP = nodes.get(0).getIp();
setNameNode(nameNodeIP);
} else {
throw new CliRestException("no name node available");
}
}
if (role.equals("hadoop_jobtracker")) {
List<NodeRead> nodes = nodeGroup.getInstances();
if (nodes != null && nodes.size() > 0) {
String jobTrackerIP = nodes.get(0).getIp();
setJobTracker(jobTrackerIP);
} else {
throw new CliRestException("no job tracker available");
}
}
if (role.equals("hive_server")) {
List<NodeRead> nodes = nodeGroup.getInstances();
if (nodes != null && nodes.size() > 0) {
String hiveServerIP = nodes.get(0).getIp();
setHiveServer(hiveServerIP);
} else {
throw new CliRestException("no hive server available");
}
}
}
}
if (cluster.getExternalHDFS() != null && !cluster.getExternalHDFS().isEmpty()) {
setFsURL(cluster.getExternalHDFS());
}
}
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_TARGET,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
private void setNameNode(String nameNodeAddress) {
String hdfsUrl = "webhdfs://" + nameNodeAddress + ":50070";
setFsURL(hdfsUrl);
}
private void setFsURL(String fsURL) {
hadoopConfiguration.set("fs.default.name", fsURL);
}
private void setJobTracker(String jobTrackerAddress) {
String jobTrackerUrl = jobTrackerAddress + ":8021";
hadoopConfiguration.set("mapred.job.tracker", jobTrackerUrl);
}
private void setHiveServer(String hiveServerAddress) {
try {
hiveInfo = hiveCommands.config(hiveServerAddress, 10000, null);
} catch (Exception e) {
throw new CliRestException("faild to set hive server address");
}
}
@CliCommand(value = "cluster config", help = "Config an existing cluster")
public void configCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "specFile" }, mandatory = true, help = "The spec file name path") final String specFilePath,
@CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation,
@CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) {
this.alwaysAnswerYes = alwaysAnswerYes;
//validate the name
if (name.indexOf("-") != -1) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CONFIG,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE);
return;
}
try {
ClusterRead clusterRead = restClient.get(name);
// build ClusterCreate object
ClusterCreate clusterConfig = new ClusterCreate();
clusterConfig.setName(clusterRead.getName());
ClusterCreate clusterSpec =
CommandsUtils.getObjectByJsonString(ClusterCreate.class, CommandsUtils.dataFromFile(specFilePath));
clusterConfig.setNodeGroups(clusterSpec.getNodeGroups());
clusterConfig.setConfiguration(clusterSpec.getConfiguration());
List<String> warningMsgList = new ArrayList<String>();
validateConfiguration(clusterConfig, skipConfigValidation, warningMsgList);
// add a confirm message for running job
warningMsgList.add("Warning: " + Constants.PARAM_CLUSTER_CONFIG_RUNNING_JOB_WARNING);
if (!showWarningMsg(clusterConfig.getName(), warningMsgList)) {
return;
}
restClient.configCluster(clusterConfig);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_CONFIG);
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CONFIG,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
return;
}
}
private String getClusterResourceName(String cluster, String nodeGroup, String node) {
assert cluster != null; // Spring shell guarantees this
if (node != null && nodeGroup == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, cluster,
Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.OUTPUT_OP_NODEGROUP_MISSING);
return null;
}
StringBuilder res = new StringBuilder();
res.append(cluster);
if (nodeGroup != null) {
res.append("/nodegroup/").append(nodeGroup);
if (node != null) {
res.append("/node/").append(node);
}
}
return res.toString();
}
private boolean validateNodeName(String cluster, String group, String node) {
if (node != null) {
String[] parts = node.split("-");
if (parts.length == 1) {
return true;
}
if (parts.length == 3) {
if (!parts[0].equals(cluster)) {
return false;
}
if (group != null && !parts[1].equals(group)) {
return false;
}
return true;
}
return false;
}
return true;
}
private boolean validateNodeGroupName(String group) {
if (group != null) {
return group.indexOf("-") == -1;
}
return true;
}
private String autoCompleteNodeName(String cluster, String group, String node) {
assert cluster != null;
assert group != null;
assert node != null;
if (node.indexOf("-") == -1) {
StringBuilder sb = new StringBuilder();
sb.append(cluster).append("-").append(group).append("-").append(node);
return sb.toString();
}
return node;
}
private String extractNodeGroupName(String node) {
String[] parts = node.split("-");
if (parts.length == 3) {
return parts[1];
}
return null;
}
private void resumeCreateCluster(final String name) {
Map<String, String> queryStrings = new HashMap<String, String>();
queryStrings.put(Constants.QUERY_ACTION_KEY,
Constants.QUERY_ACTION_RESUME);
try {
restClient.actionOps(name, queryStrings);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESULT_RESUME);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESUME, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
private List<String> getNetworkNames() {
List<String> networkNames = new ArrayList<String>(0);
NetworkRead[] networks = networkRestClient.getAll(false);
if (networks != null) {
for (NetworkRead network : networks)
networkNames.add(network.getName());
}
return networkNames;
}
private List<String> getDistroNames() {
List<String> distroNames = new ArrayList<String>(0);
DistroRead[] distros = distroRestClient.getAll();
if (distros != null) {
for (DistroRead distro : distros)
distroNames.add(distro.getName());
}
return distroNames;
}
private boolean validName(String inputName, List<String> validNames) {
for (String name : validNames) {
if (name.equals(inputName)) {
return true;
}
}
return false;
}
private void prettyOutputClusterInfo(ClusterRead cluster, boolean detail) {
//cluster Name
System.out.printf("name: %s, distro: %s, status: %s", cluster.getName(),
cluster.getDistro(), cluster.getStatus());
System.out.println();
if(cluster.getExternalHDFS() != null && !cluster.getExternalHDFS().isEmpty()) {
System.out.printf("external HDFS: %s\n", cluster.getExternalHDFS());
}
LinkedHashMap<String, List<String>> ngColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
List<NodeGroupRead> nodegroups = cluster.getNodeGroups();
if (nodegroups != null) {
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_ROLES, Arrays.asList("getRoles"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_INSTANCE,
Arrays.asList("getInstanceNum"));
ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_CPU,
Arrays.asList("getCpuNum"));
ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_MEM,
Arrays.asList("getMemCapacityMB"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_TYPE,
Arrays.asList("getStorage", "getType"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_SIZE,
Arrays.asList("getStorage", "getSizeGB"));
try {
if (detail) {
LinkedHashMap<String, List<String>> nColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NAME,
Arrays.asList("getName"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_HOST,
Arrays.asList("getHostName"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_IP, Arrays.asList("getIp"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_STATUS,
Arrays.asList("getStatus"));
for (NodeGroupRead nodegroup : nodegroups) {
CommandsUtils.printInTableFormat(
ngColumnNamesWithGetMethodNames,
new NodeGroupRead[] { nodegroup },
Constants.OUTPUT_INDENT);
List<NodeRead> nodes = nodegroup.getInstances();
if (nodes != null) {
System.out.println();
CommandsUtils.printInTableFormat(
nColumnNamesWithGetMethodNames, nodes.toArray(),
new StringBuilder().append(Constants.OUTPUT_INDENT)
.append(Constants.OUTPUT_INDENT).toString());
}
System.out.println();
}
} else
CommandsUtils.printInTableFormat(
ngColumnNamesWithGetMethodNames, nodegroups.toArray(),
Constants.OUTPUT_INDENT);
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
cluster.getName(), Constants.OUTPUT_OP_LIST,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
}
private void prettyOutputClustersInfo(ClusterRead[] clusters, boolean detail) {
for (ClusterRead cluster : clusters) {
prettyOutputClusterInfo(cluster, detail);
System.out.println();
}
}
/**
* Validate nodeGroupCreates member formats and values in the ClusterCreate.
*/
private boolean validateClusterCreate(ClusterCreate clusterCreate) {
// validation status
boolean validated = true;
// show warning message
boolean warning = false;
//role count
int masterCount = 0, workerCount = 0, clientCount = 0;
//Find NodeGroupCreate array from current ClusterCreate instance.
NodeGroupCreate[] nodeGroupCreates = clusterCreate.getNodeGroups();
if (nodeGroupCreates == null || nodeGroupCreates.length == 0) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterCreate.getName(), Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.MULTI_INPUTS_CHECK);
return !validated;
} else {
//used for collecting failed message.
List<String> failedMsgList = new LinkedList<String>();
//find distro roles.
List<String> distroRoles = findDistroRoles(clusterCreate);
if (distroRoles == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterCreate.getName(), Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_NO_DISTRO_AVAILABLE);
return !validated;
}
if (nodeGroupCreates.length < 2 || nodeGroupCreates.length > 4) {
warning = true;
}
// check external HDFS
if (clusterCreate.hasHDFSUrlConfigured() && !clusterCreate.validateHDFSUrl()) {
failedMsgList.add(new StringBuilder()
.append("externalHDFS=")
.append(clusterCreate.getExternalHDFS()).toString());
validated = false;
}
// check placement policies
if (!clusterCreate.validateNodeGroupPlacementPolicies(failedMsgList)) {
validated = false;
}
if (!clusterCreate.validateNodeGroupRoles(failedMsgList)) {
validated = false;
}
for (NodeGroupCreate nodeGroupCreate : nodeGroupCreates) {
// check node group's instanceNum
if (!checkInstanceNum(nodeGroupCreate, failedMsgList)) {
validated = false;
}
// check node group's roles
if (!checkNodeGroupRoles(nodeGroupCreate, distroRoles,
failedMsgList)) {
validated = false;
}
// get node group role .
NodeGroupRole role = getNodeGroupRole(nodeGroupCreate);
switch (role) {
case MASTER:
masterCount++;
if (nodeGroupCreate.getInstanceNum() >= 0
&& nodeGroupCreate.getInstanceNum() != 1) {
validated = false;
collectInstanceNumInvalidateMsg(nodeGroupCreate,
failedMsgList);
}
break;
case WORKER:
workerCount++;
if (nodeGroupCreate.getInstanceNum() == 0) {
validated = false;
collectInstanceNumInvalidateMsg(nodeGroupCreate,
failedMsgList);
} else if (isHAFlag(nodeGroupCreate)) {
warning = true;
}
break;
case CLIENT:
clientCount++;
if (nodeGroupCreate.getInstanceNum() == 0
|| isHAFlag(nodeGroupCreate)) {
warning = true;
}
break;
case NONE:
warning = true;
break;
default:
}
}
if ((masterCount < 1 || masterCount > 2) || (workerCount < 1 || workerCount > 2) ||
clientCount > 1) {
warning = true;
}
if (!validated) {
showFailedMsg(clusterCreate.getName(), failedMsgList);
} else if (warning) {
// If warning is true,show waring message.
showWarningMsg();
// When exist warning message,whether to proceed
if (!isContinue(clusterCreate.getName(),Constants.OUTPUT_OP_CREATE,Constants.PARAM_PROMPT_CONTINUE_MESSAGE)) {
validated = false;
}
}
return validated;
}
}
private boolean isContinue(String clusterName, String operateType, String promptMsg) {
if (this.alwaysAnswerYes) {
return true;
}
boolean continueCreate = true;
boolean continueLoop = true;
String readMsg = "";
try {
ConsoleReader reader = new ConsoleReader();
int k = 0;
while (continueLoop) {
if (k >= 3) {
continueCreate = false;
break;
}
// Prompt continue information
System.out.print(promptMsg);
// Get user's entering
readMsg = reader.readLine();
if (readMsg.trim().equalsIgnoreCase("yes")
|| readMsg.trim().equalsIgnoreCase("y")) {
continueLoop = false;
} else if (readMsg.trim().equalsIgnoreCase("no")
|| readMsg.trim().equalsIgnoreCase("n")) {
continueLoop = false;
continueCreate = false;
} else {
k++;
}
}
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, operateType,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
continueCreate = false;
}
return continueCreate;
}
private NodeGroupRole getNodeGroupRole(NodeGroupCreate nodeGroupCreate) {
//Find roles list from current NodeGroupCreate instance.
List<String> roles = nodeGroupCreate.getRoles();
for (NodeGroupRole role : NodeGroupRole.values()) {
if (matchRole(role, roles)) {
return role;
}
}
return NodeGroupRole.NONE;
}
/**
* Check the roles was introduced, whether matching with system's specialize
* role.
*/
private boolean matchRole(NodeGroupRole role, List<String> roles) {
List<String> matchRoles = new LinkedList<String>();
switch (role) {
case MASTER:
if (roles.size() == 1) {
String r = roles.get(0);
return Constants.ROLE_HADOOP_NAME_NODE.equals(r) ||
Constants.ROLE_HADOOP_JOB_TRACKER.equals(r);
} else if (roles.size() == 2) {
matchRoles.add(Constants.ROLE_HADOOP_NAME_NODE);
matchRoles.add(Constants.ROLE_HADOOP_JOB_TRACKER);
matchRoles.removeAll(roles);
return matchRoles.size() == 0 ? true : false;
}
return false;
case WORKER:
if (roles.size() == 1) {
if (Constants.ROLE_HADOOP_DATANODE.equals(roles.get(0)) ||
Constants.ROLE_HADOOP_TASKTRACKER.equals(roles.get(0))) {
return true;
}
return false;
} else {
matchRoles.add(Constants.ROLE_HADOOP_DATANODE);
matchRoles.add(Constants.ROLE_HADOOP_TASKTRACKER);
matchRoles.removeAll(roles);
return matchRoles.size() == 0 ? true : false;
}
case CLIENT:
if (roles.size() < 1 || roles.size() > 4) {
return false;
} else {
matchRoles.add(Constants.ROLE_HADOOP_CLIENT);
matchRoles.add(Constants.ROLE_HIVE);
matchRoles.add(Constants.ROLE_HIVE_SERVER);
matchRoles.add(Constants.ROLE_PIG);
int diffNum = matchRoles.size() - roles.size();
matchRoles.removeAll(roles);
return roles.contains(Constants.ROLE_HADOOP_CLIENT)
&& (diffNum >= 0) && (diffNum == matchRoles.size()) ? true
: false;
}
}
return false;
}
private void showWarningMsg() {
System.out.println(Constants.PARAM_CLUSTER_WARNING);
}
private boolean checkInstanceNum(NodeGroupCreate nodeGroup,
List<String> failedMsgList) {
boolean validated = true;
if (nodeGroup.getInstanceNum() < 0) {
validated = false;
collectInstanceNumInvalidateMsg(nodeGroup, failedMsgList);
}
return validated;
}
private void collectInstanceNumInvalidateMsg(NodeGroupCreate nodeGroup,
List<String> failedMsgList) {
failedMsgList.add(new StringBuilder().append(nodeGroup.getName())
.append(".").append("instanceNum=")
.append(nodeGroup.getInstanceNum()).toString());
}
private boolean checkNodeGroupRoles(NodeGroupCreate nodeGroup,
List<String> distroRoles, List<String> failedMsgList) {
List<String> roles = nodeGroup.getRoles();
boolean validated = true;
StringBuilder rolesMsg = new StringBuilder();
for (String role : roles) {
if (!distroRoles.contains(role)) {
validated = false;
rolesMsg.append(",").append(role);
}
}
if (!validated) {
rolesMsg.replace(0, 1, "");
failedMsgList.add(new StringBuilder().append(nodeGroup.getName())
.append(".").append("roles=").append("\"")
.append(rolesMsg.toString()).append("\"").toString());
}
return validated;
}
private List<String> findDistroRoles(ClusterCreate clusterCreate) {
DistroRead distroRead = null;
distroRead =
distroRestClient
.get(clusterCreate.getDistro() != null ? clusterCreate
.getDistro() : Constants.DEFAULT_DISTRO);
if (distroRead != null) {
return distroRead.getRoles();
} else {
return null;
}
}
private void showFailedMsg(String name, List<String> failedMsgList) {
//cluster creation failed message.
StringBuilder failedMsg = new StringBuilder();
failedMsg.append(Constants.INVALID_VALUE);
if (failedMsgList.size() > 1) {
failedMsg.append("s");
}
failedMsg.append(" ");
StringBuilder tmpMsg = new StringBuilder();
for (String msg : failedMsgList) {
tmpMsg.append(",").append(msg);
}
tmpMsg.replace(0, 1, "");
failedMsg.append(tmpMsg);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
failedMsg.toString());
}
private void validateConfiguration(ClusterCreate cluster, boolean skipConfigValidation, List<String> warningMsgList) {
// validate blacklist
ValidateResult blackListResult = validateBlackList(cluster);
if (blackListResult != null) {
addBlackListWarning(blackListResult, warningMsgList);
}
if (!skipConfigValidation) {
// validate whitelist
ValidateResult whiteListResult = validateWhiteList(cluster);
addWhiteListWarning(cluster.getName(), whiteListResult, warningMsgList);
} else {
cluster.setValidateConfig(false);
}
}
private ValidateResult validateBlackList(ClusterCreate cluster) {
return validateConfiguration(cluster, ValidationType.BLACK_LIST);
}
private ValidateResult validateWhiteList(ClusterCreate cluster) {
return validateConfiguration(cluster, ValidationType.WHITE_LIST);
}
private ValidateResult validateConfiguration(ClusterCreate cluster, ValidationType validationType) {
ValidateResult validateResult = new ValidateResult();
// validate cluster level Configuration
ValidateResult vr = null;
if (cluster.getConfiguration() != null && !cluster.getConfiguration().isEmpty()) {
vr = AppConfigValidationUtils.validateConfig(validationType, cluster.getConfiguration());
if (vr.getType() != ValidateResult.Type.VALID) {
validateResult.setType(vr.getType());
validateResult.setFailureNames(vr.getFailureNames());
}
}
// validate nodegroup level Configuration
for (NodeGroupCreate nodeGroup : cluster.getNodeGroups()) {
if (nodeGroup.getConfiguration() != null && !nodeGroup.getConfiguration().isEmpty()) {
vr = AppConfigValidationUtils.validateConfig(validationType, nodeGroup.getConfiguration());
if (vr.getType() != ValidateResult.Type.VALID) {
validateResult.setType(vr.getType());
List<String> failureNames = new LinkedList<String>();
failureNames.addAll(validateResult.getFailureNames());
for (String name : vr.getFailureNames()) {
if (!failureNames.contains(name)) {
failureNames.add(name);
}
}
validateResult.setFailureNames(vr.getFailureNames());
}
}
}
return validateResult;
}
private void addWhiteListWarning(final String clusterName, ValidateResult whiteListResult,
List<String> warningMsgList) {
if (whiteListResult.getType() == ValidateResult.Type.WHITE_LIST_INVALID_NAME) {
String warningMsg =
getValidateWarningMsg(whiteListResult.getFailureNames(),
Constants.PARAM_CLUSTER_NOT_IN_WHITE_LIST_WARNING);
if (warningMsgList != null) {
warningMsgList.add(warningMsg);
}
}
}
private void addBlackListWarning(ValidateResult blackListResult, List<String> warningList) {
if (blackListResult.getType() == ValidateResult.Type.NAME_IN_BLACK_LIST) {
String warningMsg =
getValidateWarningMsg(blackListResult.getFailureNames(), Constants.PARAM_CLUSTER_IN_BLACK_LIST_WARNING);
if (warningList != null)
warningList.add(warningMsg);
}
}
private String getValidateWarningMsg(List<String> failureNames, String warningMsg) {
StringBuilder warningMsgBuff = new StringBuilder();
if (failureNames != null && !failureNames.isEmpty()) {
warningMsgBuff.append("Warning: ");
for (String failureName : failureNames) {
warningMsgBuff.append(failureName).append(", ");
}
warningMsgBuff.delete(warningMsgBuff.length() - 2, warningMsgBuff.length());
if (failureNames.size() > 1) {
warningMsgBuff.append(" are ");
} else {
warningMsgBuff.append(" is ");
}
warningMsgBuff.append(warningMsg);
}
return warningMsgBuff.toString();
}
private boolean showWarningMsg(String clusterName, List<String> warningMsgList) {
if (warningMsgList != null && !warningMsgList.isEmpty()) {
for (String message : warningMsgList) {
System.out.println(message);
}
if (!isContinue(clusterName, Constants.OUTPUT_OP_CREATE, Constants.PARAM_PROMPT_CONTINUE_MESSAGE)) {
return false;
}
}
return true;
}
private boolean isHAFlag(NodeGroupCreate nodeGroupCreate) {
return !CommandsUtils.isBlank(nodeGroupCreate.getHaFlag())
&& !nodeGroupCreate.getHaFlag().equalsIgnoreCase("off");
}
private boolean validateHAInfo(NodeGroupCreate[] nodeGroups) {
List<String> haFlagList = Arrays.asList("off","on","ft");
if (nodeGroups != null){
for(NodeGroupCreate group : nodeGroups){
if (!haFlagList.contains(group.getHaFlag().toLowerCase())){
return false;
}
}
}
return true;
}
}
| public void createCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "distro" }, mandatory = false, help = "Hadoop Distro") final String distro,
@CliOption(key = { "specFile" }, mandatory = false, help = "The spec file name path") final String specFilePath,
@CliOption(key = { "rpNames" }, mandatory = false, help = "Resource Pools for the cluster: use \",\" among names.") final String rpNames,
@CliOption(key = { "dsNames" }, mandatory = false, help = "Datastores for the cluster: use \",\" among names.") final String dsNames,
@CliOption(key = { "networkName" }, mandatory = false, help = "Network Name") final String networkName,
@CliOption(key = { "resume" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to resume cluster creation") final boolean resume,
@CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation,
@CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) {
this.alwaysAnswerYes = alwaysAnswerYes;
//validate the name
if (name.indexOf("-") != -1) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CLUSTER
+ Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE);
return;
}
//process resume
if (resume) {
resumeCreateCluster(name);
return;
}
// build ClusterCreate object
ClusterCreate clusterCreate = new ClusterCreate();
clusterCreate.setName(name);
if (distro != null) {
List<String> distroNames = getDistroNames();
if (validName(distro, distroNames)) {
clusterCreate.setDistro(distro);
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_DISTRO
+ Constants.PARAM_NOT_SUPPORTED + distroNames);
return;
}
}
clusterCreate.setType(Enum.valueOf(ClusterType.class, "HADOOP"));
if (rpNames != null) {
List<String> rpNamesList = CommandsUtils.inputsConvert(rpNames);
if (rpNamesList.isEmpty()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INPUT_RPNAMES_PARAM + Constants.MULTI_INPUTS_CHECK);
return;
} else {
clusterCreate.setRpNames(rpNamesList);
}
}
if (dsNames != null) {
List<String> dsNamesList = CommandsUtils.inputsConvert(dsNames);
if (dsNamesList.isEmpty()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INPUT_DSNAMES_PARAM + Constants.MULTI_INPUTS_CHECK);
return;
} else {
clusterCreate.setDsNames(dsNamesList);
}
}
List<String> warningMsgList = new ArrayList<String>();
try {
if (specFilePath != null) {
ClusterCreate clusterSpec =
CommandsUtils.getObjectByJsonString(ClusterCreate.class, CommandsUtils.dataFromFile(specFilePath));
clusterCreate.setExternalHDFS(clusterSpec.getExternalHDFS());
clusterCreate.setNodeGroups(clusterSpec.getNodeGroups());
clusterCreate.setConfiguration(clusterSpec.getConfiguration());
validateConfiguration(clusterCreate, skipConfigValidation, warningMsgList);
if (!validateHAInfo(clusterCreate.getNodeGroups())){
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CLUSTER_SPEC_HA_ERROR + specFilePath);
return;
}
}
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
return;
}
List<String> networkNames = getNetworkNames();
if (networkNames.isEmpty()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_EXISTED);
return;
} else {
if (networkName != null) {
if (validName(networkName, networkNames)) {
clusterCreate.setNetworkName(networkName);
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_NETWORK_NAME
+ Constants.PARAM_NOT_SUPPORTED + networkNames);
return;
}
} else {
if (networkNames.size() == 1) {
clusterCreate.setNetworkName(networkNames.get(0));
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_NETWORK_NAME
+ Constants.PARAM_NOT_SPECIFIED);
return;
}
}
}
// Validate that the specified file is correct json format and proper value.
if (specFilePath != null) {
if (!validateClusterCreate(clusterCreate)) {
return;
}
}
// rest invocation
try {
if (!showWarningMsg(clusterCreate.getName(), warningMsgList)) {
return;
}
restClient.create(clusterCreate);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_CREAT);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
@CliCommand(value = "cluster list", help = "Get cluster information")
public void getCluster(
@CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name,
@CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) {
// rest invocation
try {
if (name == null) {
ClusterRead[] clusters = restClient.getAll();
if (clusters != null) {
prettyOutputClustersInfo(clusters, detail);
}
} else {
ClusterRead cluster = restClient.get(name);
if (cluster != null) {
prettyOutputClusterInfo(cluster, detail);
}
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster export --spec", help = "Export cluster specification")
public void exportClusterSpec(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "output" }, mandatory = false, help = "The output file name") final String fileName) {
// rest invocation
try {
ClusterCreate cluster = restClient.getSpec(name);
if (cluster != null) {
CommandsUtils.prettyJsonOutput(cluster, fileName);
}
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_EXPORT, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster delete", help = "Delete a cluster")
public void deleteCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name) {
//rest invocation
try {
restClient.delete(name);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESULT_DELETE);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster start", help = "Start a cluster")
public void startCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName,
@CliOption(key = { "nodeGroupName" }, mandatory = false, help = "The node group name") final String nodeGroupName,
@CliOption(key = { "nodeName" }, mandatory = false, help = "The node name") final String nodeName) {
Map<String, String> queryStrings = new HashMap<String, String>();
queryStrings
.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_START);
//rest invocation
try {
if (!validateNodeGroupName(nodeGroupName)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL,
"invalid node group name");
return;
}
if (!validateNodeName(clusterName, nodeGroupName, nodeName)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL,
"invalid node name");
return;
}
String groupName = nodeGroupName;
String fullNodeName = nodeName;
if (nodeName != null) {
if (nodeGroupName == null) {
groupName = extractNodeGroupName(nodeName);
if (groupName == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL,
"missing node group name");
return;
}
} else {
fullNodeName = autoCompleteNodeName(clusterName, nodeGroupName, nodeName);
}
}
String resource = getClusterResourceName(clusterName, groupName, fullNodeName);
if (resource != null) {
restClient.actionOps(resource, clusterName, queryStrings);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_RESULT_START);
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster stop", help = "Stop a cluster")
public void stopCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName,
@CliOption(key = { "nodeGroupName" }, mandatory = false, help = "The node group name") final String nodeGroupName,
@CliOption(key = { "nodeName" }, mandatory = false, help = "The node name") final String nodeName) {
Map<String, String> queryStrings = new HashMap<String, String>();
queryStrings.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_STOP);
//rest invocation
try {
if (!validateNodeGroupName(nodeGroupName)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL,
"invalid node group name");
return;
}
if (!validateNodeName(clusterName, nodeGroupName, nodeName)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL,
"invalid node name");
return;
}
String groupName = nodeGroupName;
String fullNodeName = nodeName;
if (nodeName != null) {
if (nodeGroupName == null) {
groupName = extractNodeGroupName(nodeName);
if (groupName == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL,
"missing node group name");
return;
}
} else {
fullNodeName = autoCompleteNodeName(clusterName, nodeGroupName, nodeName);
}
}
String resource = getClusterResourceName(clusterName, groupName, fullNodeName);
if (resource != null) {
restClient.actionOps(resource, clusterName, queryStrings);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_RESULT_STOP);
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster resize", help = "Resize a cluster")
public void resizeCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "nodeGroup" }, mandatory = true, help = "The node group name") final String nodeGroup,
@CliOption(key = { "instanceNum" }, mandatory = true, help = "The resized number of instances. It should be larger that existing one") final int instanceNum) {
if (instanceNum > 1) {
try {
restClient.resize(name, nodeGroup, instanceNum);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESULT_RESIZE);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INVALID_VALUE + " instanceNum=" + instanceNum);
}
}
@CliCommand(value = "cluster target", help = "Set or query target cluster to run commands")
public void targetCluster(
@CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name,
@CliOption(key = { "info" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show target information") final boolean info) {
ClusterRead cluster = null;
try {
if (info) {
if (name != null) {
System.out.println("Warning: can't specify option --name and --info at the same time");
return;
}
String fsUrl = hadoopConfiguration.get("fs.default.name");
String jtUrl = hadoopConfiguration.get("mapred.job.tracker");
if ((fsUrl == null || fsUrl.length() == 0) && (jtUrl == null || jtUrl.length() == 0)) {
System.out.println("There is no cluster be targeted now, target cluster first");
return;
}
if(targetClusterName != null && targetClusterName.length() > 0){
System.out.println("Cluster: " + targetClusterName);
}
if (fsUrl != null && fsUrl.length() > 0) {
System.out.println("HDFS url: " + fsUrl);
}
if (jtUrl != null && jtUrl.length() > 0) {
System.out.println("Job Tracker url: " + jtUrl);
}
if (hiveInfo != null && hiveInfo.length() > 0) {
System.out.println("Hive server url: " + hiveInfo);
}
} else {
if (name == null) {
ClusterRead[] clusters = restClient.getAll();
if (clusters != null && clusters.length > 0) {
cluster = clusters[0];
}
} else {
cluster = restClient.get(name);
}
if (cluster == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_TARGET,
Constants.OUTPUT_OP_RESULT_FAIL, "No valid target available");
} else {
targetClusterName = cluster.getName();
for (NodeGroupRead nodeGroup : cluster.getNodeGroups()) {
for (String role : nodeGroup.getRoles()) {
if (role.equals("hadoop_namenode")) {
List<NodeRead> nodes = nodeGroup.getInstances();
if (nodes != null && nodes.size() > 0) {
String nameNodeIP = nodes.get(0).getIp();
setNameNode(nameNodeIP);
} else {
throw new CliRestException("no name node available");
}
}
if (role.equals("hadoop_jobtracker")) {
List<NodeRead> nodes = nodeGroup.getInstances();
if (nodes != null && nodes.size() > 0) {
String jobTrackerIP = nodes.get(0).getIp();
setJobTracker(jobTrackerIP);
} else {
throw new CliRestException("no job tracker available");
}
}
if (role.equals("hive_server")) {
List<NodeRead> nodes = nodeGroup.getInstances();
if (nodes != null && nodes.size() > 0) {
String hiveServerIP = nodes.get(0).getIp();
setHiveServer(hiveServerIP);
} else {
throw new CliRestException("no hive server available");
}
}
}
}
if (cluster.getExternalHDFS() != null && !cluster.getExternalHDFS().isEmpty()) {
setFsURL(cluster.getExternalHDFS());
}
}
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_TARGET,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
private void setNameNode(String nameNodeAddress) {
String hdfsUrl = "webhdfs://" + nameNodeAddress + ":50070";
setFsURL(hdfsUrl);
}
private void setFsURL(String fsURL) {
hadoopConfiguration.set("fs.default.name", fsURL);
}
private void setJobTracker(String jobTrackerAddress) {
String jobTrackerUrl = jobTrackerAddress + ":8021";
hadoopConfiguration.set("mapred.job.tracker", jobTrackerUrl);
}
private void setHiveServer(String hiveServerAddress) {
try {
hiveInfo = hiveCommands.config(hiveServerAddress, 10000, null);
} catch (Exception e) {
throw new CliRestException("faild to set hive server address");
}
}
@CliCommand(value = "cluster config", help = "Config an existing cluster")
public void configCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "specFile" }, mandatory = true, help = "The spec file name path") final String specFilePath,
@CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation,
@CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) {
this.alwaysAnswerYes = alwaysAnswerYes;
//validate the name
if (name.indexOf("-") != -1) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CONFIG,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE);
return;
}
try {
ClusterRead clusterRead = restClient.get(name);
// build ClusterCreate object
ClusterCreate clusterConfig = new ClusterCreate();
clusterConfig.setName(clusterRead.getName());
ClusterCreate clusterSpec =
CommandsUtils.getObjectByJsonString(ClusterCreate.class, CommandsUtils.dataFromFile(specFilePath));
clusterConfig.setNodeGroups(clusterSpec.getNodeGroups());
clusterConfig.setConfiguration(clusterSpec.getConfiguration());
List<String> warningMsgList = new ArrayList<String>();
validateConfiguration(clusterConfig, skipConfigValidation, warningMsgList);
// add a confirm message for running job
warningMsgList.add("Warning: " + Constants.PARAM_CLUSTER_CONFIG_RUNNING_JOB_WARNING);
if (!showWarningMsg(clusterConfig.getName(), warningMsgList)) {
return;
}
restClient.configCluster(clusterConfig);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_CONFIG);
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CONFIG,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
return;
}
}
private String getClusterResourceName(String cluster, String nodeGroup, String node) {
assert cluster != null; // Spring shell guarantees this
if (node != null && nodeGroup == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, cluster,
Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.OUTPUT_OP_NODEGROUP_MISSING);
return null;
}
StringBuilder res = new StringBuilder();
res.append(cluster);
if (nodeGroup != null) {
res.append("/nodegroup/").append(nodeGroup);
if (node != null) {
res.append("/node/").append(node);
}
}
return res.toString();
}
private boolean validateNodeName(String cluster, String group, String node) {
if (node != null) {
String[] parts = node.split("-");
if (parts.length == 1) {
return true;
}
if (parts.length == 3) {
if (!parts[0].equals(cluster)) {
return false;
}
if (group != null && !parts[1].equals(group)) {
return false;
}
return true;
}
return false;
}
return true;
}
private boolean validateNodeGroupName(String group) {
if (group != null) {
return group.indexOf("-") == -1;
}
return true;
}
private String autoCompleteNodeName(String cluster, String group, String node) {
assert cluster != null;
assert group != null;
assert node != null;
if (node.indexOf("-") == -1) {
StringBuilder sb = new StringBuilder();
sb.append(cluster).append("-").append(group).append("-").append(node);
return sb.toString();
}
return node;
}
private String extractNodeGroupName(String node) {
String[] parts = node.split("-");
if (parts.length == 3) {
return parts[1];
}
return null;
}
private void resumeCreateCluster(final String name) {
Map<String, String> queryStrings = new HashMap<String, String>();
queryStrings.put(Constants.QUERY_ACTION_KEY,
Constants.QUERY_ACTION_RESUME);
try {
restClient.actionOps(name, queryStrings);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESULT_RESUME);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESUME, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
private List<String> getNetworkNames() {
List<String> networkNames = new ArrayList<String>(0);
NetworkRead[] networks = networkRestClient.getAll(false);
if (networks != null) {
for (NetworkRead network : networks)
networkNames.add(network.getName());
}
return networkNames;
}
private List<String> getDistroNames() {
List<String> distroNames = new ArrayList<String>(0);
DistroRead[] distros = distroRestClient.getAll();
if (distros != null) {
for (DistroRead distro : distros)
distroNames.add(distro.getName());
}
return distroNames;
}
private boolean validName(String inputName, List<String> validNames) {
for (String name : validNames) {
if (name.equals(inputName)) {
return true;
}
}
return false;
}
private void prettyOutputClusterInfo(ClusterRead cluster, boolean detail) {
//cluster Name
System.out.printf("name: %s, distro: %s, status: %s", cluster.getName(),
cluster.getDistro(), cluster.getStatus());
System.out.println();
if(cluster.getExternalHDFS() != null && !cluster.getExternalHDFS().isEmpty()) {
System.out.printf("external HDFS: %s\n", cluster.getExternalHDFS());
}
LinkedHashMap<String, List<String>> ngColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
List<NodeGroupRead> nodegroups = cluster.getNodeGroups();
if (nodegroups != null) {
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_ROLES, Arrays.asList("getRoles"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_INSTANCE,
Arrays.asList("getInstanceNum"));
ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_CPU,
Arrays.asList("getCpuNum"));
ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_MEM,
Arrays.asList("getMemCapacityMB"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_TYPE,
Arrays.asList("getStorage", "getType"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_SIZE,
Arrays.asList("getStorage", "getSizeGB"));
try {
if (detail) {
LinkedHashMap<String, List<String>> nColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NAME,
Arrays.asList("getName"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_HOST,
Arrays.asList("getHostName"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_IP, Arrays.asList("getIp"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_STATUS,
Arrays.asList("getStatus"));
for (NodeGroupRead nodegroup : nodegroups) {
CommandsUtils.printInTableFormat(
ngColumnNamesWithGetMethodNames,
new NodeGroupRead[] { nodegroup },
Constants.OUTPUT_INDENT);
List<NodeRead> nodes = nodegroup.getInstances();
if (nodes != null) {
System.out.println();
CommandsUtils.printInTableFormat(
nColumnNamesWithGetMethodNames, nodes.toArray(),
new StringBuilder().append(Constants.OUTPUT_INDENT)
.append(Constants.OUTPUT_INDENT).toString());
}
System.out.println();
}
} else
CommandsUtils.printInTableFormat(
ngColumnNamesWithGetMethodNames, nodegroups.toArray(),
Constants.OUTPUT_INDENT);
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
cluster.getName(), Constants.OUTPUT_OP_LIST,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
}
private void prettyOutputClustersInfo(ClusterRead[] clusters, boolean detail) {
for (ClusterRead cluster : clusters) {
prettyOutputClusterInfo(cluster, detail);
System.out.println();
}
}
/**
* Validate nodeGroupCreates member formats and values in the ClusterCreate.
*/
private boolean validateClusterCreate(ClusterCreate clusterCreate) {
// validation status
boolean validated = true;
// show warning message
boolean warning = false;
//role count
int masterCount = 0, workerCount = 0, clientCount = 0;
//Find NodeGroupCreate array from current ClusterCreate instance.
NodeGroupCreate[] nodeGroupCreates = clusterCreate.getNodeGroups();
if (nodeGroupCreates == null || nodeGroupCreates.length == 0) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterCreate.getName(), Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.MULTI_INPUTS_CHECK);
return !validated;
} else {
//used for collecting failed message.
List<String> failedMsgList = new LinkedList<String>();
//find distro roles.
List<String> distroRoles = findDistroRoles(clusterCreate);
if (distroRoles == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterCreate.getName(), Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_NO_DISTRO_AVAILABLE);
return !validated;
}
if (nodeGroupCreates.length < 2 || nodeGroupCreates.length > 4) {
warning = true;
}
// check external HDFS
if (clusterCreate.hasHDFSUrlConfigured() && !clusterCreate.validateHDFSUrl()) {
failedMsgList.add(new StringBuilder()
.append("externalHDFS=")
.append(clusterCreate.getExternalHDFS()).toString());
validated = false;
}
// check placement policies
if (!clusterCreate.validateNodeGroupPlacementPolicies(failedMsgList)) {
validated = false;
}
if (!clusterCreate.validateNodeGroupRoles(failedMsgList)) {
validated = false;
}
for (NodeGroupCreate nodeGroupCreate : nodeGroupCreates) {
// check node group's instanceNum
if (!checkInstanceNum(nodeGroupCreate, failedMsgList)) {
validated = false;
}
// check node group's roles
if (!checkNodeGroupRoles(nodeGroupCreate, distroRoles,
failedMsgList)) {
validated = false;
}
// get node group role .
NodeGroupRole role = getNodeGroupRole(nodeGroupCreate);
switch (role) {
case MASTER:
masterCount++;
if (nodeGroupCreate.getInstanceNum() >= 0
&& nodeGroupCreate.getInstanceNum() != 1) {
validated = false;
collectInstanceNumInvalidateMsg(nodeGroupCreate,
failedMsgList);
}
break;
case WORKER:
workerCount++;
if (nodeGroupCreate.getInstanceNum() == 0) {
validated = false;
collectInstanceNumInvalidateMsg(nodeGroupCreate,
failedMsgList);
} else if (isHAFlag(nodeGroupCreate)) {
warning = true;
}
break;
case CLIENT:
clientCount++;
if (nodeGroupCreate.getInstanceNum() == 0
|| isHAFlag(nodeGroupCreate)) {
warning = true;
}
break;
case NONE:
warning = true;
break;
default:
}
}
if ((masterCount < 1 || masterCount > 2) || (workerCount < 1 || workerCount > 2) ||
clientCount > 1) {
warning = true;
}
if (!validated) {
showFailedMsg(clusterCreate.getName(), failedMsgList);
} else if (warning) {
// If warning is true,show waring message.
showWarningMsg();
// When exist warning message,whether to proceed
if (!isContinue(clusterCreate.getName(),Constants.OUTPUT_OP_CREATE,Constants.PARAM_PROMPT_CONTINUE_MESSAGE)) {
validated = false;
}
}
return validated;
}
}
private boolean isContinue(String clusterName, String operateType, String promptMsg) {
if (this.alwaysAnswerYes) {
return true;
}
boolean continueCreate = true;
boolean continueLoop = true;
String readMsg = "";
try {
ConsoleReader reader = new ConsoleReader();
int k = 0;
while (continueLoop) {
if (k >= 3) {
continueCreate = false;
break;
}
// Prompt continue information
System.out.print(promptMsg);
// Get user's entering
readMsg = reader.readLine();
if (readMsg.trim().equalsIgnoreCase("yes")
|| readMsg.trim().equalsIgnoreCase("y")) {
continueLoop = false;
} else if (readMsg.trim().equalsIgnoreCase("no")
|| readMsg.trim().equalsIgnoreCase("n")) {
continueLoop = false;
continueCreate = false;
} else {
k++;
}
}
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, operateType,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
continueCreate = false;
}
return continueCreate;
}
private NodeGroupRole getNodeGroupRole(NodeGroupCreate nodeGroupCreate) {
//Find roles list from current NodeGroupCreate instance.
List<String> roles = nodeGroupCreate.getRoles();
for (NodeGroupRole role : NodeGroupRole.values()) {
if (matchRole(role, roles)) {
return role;
}
}
return NodeGroupRole.NONE;
}
/**
* Check the roles was introduced, whether matching with system's specialize
* role.
*/
private boolean matchRole(NodeGroupRole role, List<String> roles) {
List<String> matchRoles = new LinkedList<String>();
switch (role) {
case MASTER:
if (roles.size() == 1) {
String r = roles.get(0);
return Constants.ROLE_HADOOP_NAME_NODE.equals(r) ||
Constants.ROLE_HADOOP_JOB_TRACKER.equals(r);
} else if (roles.size() == 2) {
matchRoles.add(Constants.ROLE_HADOOP_NAME_NODE);
matchRoles.add(Constants.ROLE_HADOOP_JOB_TRACKER);
matchRoles.removeAll(roles);
return matchRoles.size() == 0 ? true : false;
}
return false;
case WORKER:
if (roles.size() == 1) {
if (Constants.ROLE_HADOOP_DATANODE.equals(roles.get(0)) ||
Constants.ROLE_HADOOP_TASKTRACKER.equals(roles.get(0))) {
return true;
}
return false;
} else {
matchRoles.add(Constants.ROLE_HADOOP_DATANODE);
matchRoles.add(Constants.ROLE_HADOOP_TASKTRACKER);
matchRoles.removeAll(roles);
return matchRoles.size() == 0 ? true : false;
}
case CLIENT:
if (roles.size() < 1 || roles.size() > 4) {
return false;
} else {
matchRoles.add(Constants.ROLE_HADOOP_CLIENT);
matchRoles.add(Constants.ROLE_HIVE);
matchRoles.add(Constants.ROLE_HIVE_SERVER);
matchRoles.add(Constants.ROLE_PIG);
int diffNum = matchRoles.size() - roles.size();
matchRoles.removeAll(roles);
return roles.contains(Constants.ROLE_HADOOP_CLIENT)
&& (diffNum >= 0) && (diffNum == matchRoles.size()) ? true
: false;
}
}
return false;
}
private void showWarningMsg() {
System.out.println(Constants.PARAM_CLUSTER_WARNING);
}
private boolean checkInstanceNum(NodeGroupCreate nodeGroup,
List<String> failedMsgList) {
boolean validated = true;
if (nodeGroup.getInstanceNum() < 0) {
validated = false;
collectInstanceNumInvalidateMsg(nodeGroup, failedMsgList);
}
return validated;
}
private void collectInstanceNumInvalidateMsg(NodeGroupCreate nodeGroup,
List<String> failedMsgList) {
failedMsgList.add(new StringBuilder().append(nodeGroup.getName())
.append(".").append("instanceNum=")
.append(nodeGroup.getInstanceNum()).toString());
}
private boolean checkNodeGroupRoles(NodeGroupCreate nodeGroup,
List<String> distroRoles, List<String> failedMsgList) {
List<String> roles = nodeGroup.getRoles();
boolean validated = true;
StringBuilder rolesMsg = new StringBuilder();
for (String role : roles) {
if (!distroRoles.contains(role)) {
validated = false;
rolesMsg.append(",").append(role);
}
}
if (!validated) {
rolesMsg.replace(0, 1, "");
failedMsgList.add(new StringBuilder().append(nodeGroup.getName())
.append(".").append("roles=").append("\"")
.append(rolesMsg.toString()).append("\"").toString());
}
return validated;
}
private List<String> findDistroRoles(ClusterCreate clusterCreate) {
DistroRead distroRead = null;
distroRead =
distroRestClient
.get(clusterCreate.getDistro() != null ? clusterCreate
.getDistro() : Constants.DEFAULT_DISTRO);
if (distroRead != null) {
return distroRead.getRoles();
} else {
return null;
}
}
private void showFailedMsg(String name, List<String> failedMsgList) {
//cluster creation failed message.
StringBuilder failedMsg = new StringBuilder();
failedMsg.append(Constants.INVALID_VALUE);
if (failedMsgList.size() > 1) {
failedMsg.append("s");
}
failedMsg.append(" ");
StringBuilder tmpMsg = new StringBuilder();
for (String msg : failedMsgList) {
tmpMsg.append(",").append(msg);
}
tmpMsg.replace(0, 1, "");
failedMsg.append(tmpMsg);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
failedMsg.toString());
}
private void validateConfiguration(ClusterCreate cluster, boolean skipConfigValidation, List<String> warningMsgList) {
// validate blacklist
ValidateResult blackListResult = validateBlackList(cluster);
if (blackListResult != null) {
addBlackListWarning(blackListResult, warningMsgList);
}
if (!skipConfigValidation) {
// validate whitelist
ValidateResult whiteListResult = validateWhiteList(cluster);
addWhiteListWarning(cluster.getName(), whiteListResult, warningMsgList);
} else {
cluster.setValidateConfig(false);
}
}
private ValidateResult validateBlackList(ClusterCreate cluster) {
return validateConfiguration(cluster, ValidationType.BLACK_LIST);
}
private ValidateResult validateWhiteList(ClusterCreate cluster) {
return validateConfiguration(cluster, ValidationType.WHITE_LIST);
}
private ValidateResult validateConfiguration(ClusterCreate cluster, ValidationType validationType) {
ValidateResult validateResult = new ValidateResult();
// validate cluster level Configuration
ValidateResult vr = null;
if (cluster.getConfiguration() != null && !cluster.getConfiguration().isEmpty()) {
vr = AppConfigValidationUtils.validateConfig(validationType, cluster.getConfiguration());
if (vr.getType() != ValidateResult.Type.VALID) {
validateResult.setType(vr.getType());
validateResult.setFailureNames(vr.getFailureNames());
}
}
// validate nodegroup level Configuration
for (NodeGroupCreate nodeGroup : cluster.getNodeGroups()) {
if (nodeGroup.getConfiguration() != null && !nodeGroup.getConfiguration().isEmpty()) {
vr = AppConfigValidationUtils.validateConfig(validationType, nodeGroup.getConfiguration());
if (vr.getType() != ValidateResult.Type.VALID) {
validateResult.setType(vr.getType());
List<String> failureNames = new LinkedList<String>();
failureNames.addAll(validateResult.getFailureNames());
for (String name : vr.getFailureNames()) {
if (!failureNames.contains(name)) {
failureNames.add(name);
}
}
validateResult.setFailureNames(vr.getFailureNames());
}
}
}
return validateResult;
}
private void addWhiteListWarning(final String clusterName, ValidateResult whiteListResult,
List<String> warningMsgList) {
if (whiteListResult.getType() == ValidateResult.Type.WHITE_LIST_INVALID_NAME) {
String warningMsg =
getValidateWarningMsg(whiteListResult.getFailureNames(),
Constants.PARAM_CLUSTER_NOT_IN_WHITE_LIST_WARNING);
if (warningMsgList != null) {
warningMsgList.add(warningMsg);
}
}
}
private void addBlackListWarning(ValidateResult blackListResult, List<String> warningList) {
if (blackListResult.getType() == ValidateResult.Type.NAME_IN_BLACK_LIST) {
String warningMsg =
getValidateWarningMsg(blackListResult.getFailureNames(), Constants.PARAM_CLUSTER_IN_BLACK_LIST_WARNING);
if (warningList != null)
warningList.add(warningMsg);
}
}
private String getValidateWarningMsg(List<String> failureNames, String warningMsg) {
StringBuilder warningMsgBuff = new StringBuilder();
if (failureNames != null && !failureNames.isEmpty()) {
warningMsgBuff.append("Warning: ");
for (String failureName : failureNames) {
warningMsgBuff.append(failureName).append(", ");
}
warningMsgBuff.delete(warningMsgBuff.length() - 2, warningMsgBuff.length());
if (failureNames.size() > 1) {
warningMsgBuff.append(" are ");
} else {
warningMsgBuff.append(" is ");
}
warningMsgBuff.append(warningMsg);
}
return warningMsgBuff.toString();
}
private boolean showWarningMsg(String clusterName, List<String> warningMsgList) {
if (warningMsgList != null && !warningMsgList.isEmpty()) {
for (String message : warningMsgList) {
System.out.println(message);
}
if (!isContinue(clusterName, Constants.OUTPUT_OP_CREATE, Constants.PARAM_PROMPT_CONTINUE_MESSAGE)) {
return false;
}
}
return true;
}
private boolean isHAFlag(NodeGroupCreate nodeGroupCreate) {
return !CommandsUtils.isBlank(nodeGroupCreate.getHaFlag())
&& !nodeGroupCreate.getHaFlag().equalsIgnoreCase("off");
}
private boolean validateHAInfo(NodeGroupCreate[] nodeGroups) {
List<String> haFlagList = Arrays.asList("off","on","ft");
if (nodeGroups != null){
for(NodeGroupCreate group : nodeGroups){
if (!haFlagList.contains(group.getHaFlag().toLowerCase())){
return false;
}
}
}
return true;
}
}
|
diff --git a/utgb-shell/src/main/java/org/utgenome/shell/ScreenShot.java b/utgb-shell/src/main/java/org/utgenome/shell/ScreenShot.java
index 4dd25bbe..e24a8b2f 100755
--- a/utgb-shell/src/main/java/org/utgenome/shell/ScreenShot.java
+++ b/utgb-shell/src/main/java/org/utgenome/shell/ScreenShot.java
@@ -1,285 +1,287 @@
/*--------------------------------------------------------------------------
* Copyright 2011 utgenome.org
*
* 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.
*--------------------------------------------------------------------------*/
//--------------------------------------
// utgb-shell Project
//
// ScreenShot.java
// Since: 2011/01/06
//
// $URL$
// $Author$
//--------------------------------------
package org.utgenome.shell;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.LinearGradientPaint;
import java.awt.RenderingHints;
import java.awt.geom.GeneralPath;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import org.utgenome.graphics.GenomeWindow;
import org.utgenome.graphics.ReadCanvas;
import org.utgenome.graphics.ReadCanvas.DrawStyle;
import org.utgenome.gwt.utgb.client.bio.ChrLoc;
import org.utgenome.gwt.utgb.client.bio.GenomeDB;
import org.utgenome.gwt.utgb.client.bio.OnGenome;
import org.utgenome.gwt.utgb.client.bio.ReadQueryConfig;
import org.utgenome.gwt.utgb.client.view.TrackDisplay;
import org.utgenome.gwt.utgb.client.view.TrackDisplay.DB;
import org.utgenome.gwt.utgb.client.view.TrackDisplay.Track;
import org.utgenome.gwt.utgb.server.app.ReadView;
import org.xerial.lens.SilkLens;
import org.xerial.util.ObjectHandler;
import org.xerial.util.log.Logger;
import org.xerial.util.opt.Argument;
import org.xerial.util.opt.Option;
/**
* screenshot commant to take a image data of the read view
*
* @author leo
*
*/
public class ScreenShot extends UTGBShellCommand {
private static Logger _logger = Logger.getLogger(ScreenShot.class);
@Option(symbol = "i", longName = "input", description = "read file to query (BAM/BED, etc.)")
private String readFile;
@Option(symbol = "o", longName = "output", description = "output PNG file path")
private String outFile;
@Option(longName = "outdir", description = "output folder. default is the current directory")
private File outputFolder;
@Option(symbol = "q", description = "query file in Silk format -region(chr, start, end)")
private File queryFile;
@Option(longName = "pixelwidth", description = "pixel width. default=1000")
private int pixelWidth = 1000;
@Option(symbol = "t", description = "track display defintion file (.silk)")
private File viewFile;
@Option(symbol = "b", description = "background color in #FFFFFF format. default= transparent")
private String backgroundColor;
@Argument(index = 0, name = "query")
private String query;
@Override
public void execute(String[] args) throws Exception {
if (query == null && queryFile == null)
throw new UTGBShellException("No query is given.");
if (outputFolder != null) {
if (!outputFolder.exists()) {
_logger.info("create dir: " + outputFolder);
outputFolder.mkdirs();
}
}
if (readFile == null && viewFile == null) {
throw new UTGBShellException("No read file (-f) or view file (--view) is specified");
}
if (query != null) {
ChrLoc loc = RegionQueryExpr.parse(query);
createPNG(viewFile, loc);
return;
}
if (queryFile != null) {
SilkLens.findFromSilk(new BufferedReader(new FileReader(queryFile)), "region", ChrLoc.class, new ObjectHandler<ChrLoc>() {
public void init() throws Exception {
_logger.info("reading " + queryFile);
}
public void handle(ChrLoc loc) throws Exception {
createPNG(viewFile, loc);
}
public void finish() throws Exception {
_logger.info("finished reading " + queryFile);
}
});
return;
}
throw new UTGBShellException("No query is given");
}
public BufferedImage createReadAlignmentImage(ChrLoc loc, String dbPath) {
GenomeDB db = new GenomeDB(dbPath, "");
ReadQueryConfig config = new ReadQueryConfig();
config.pixelWidth = pixelWidth;
config.maxmumNumberOfReadsToDisplay = Integer.MAX_VALUE;
List<OnGenome> readSet = ReadView.overlapQuery(null, db, loc, config);
// draw graphics
ReadCanvas canvas = new ReadCanvas(pixelWidth, 1, new GenomeWindow(loc.start, loc.end));
DrawStyle style = canvas.getStyle();
if (!dbPath.endsWith(".bam")) {
style.geneHeight = 10;
style.geneMargin = 2;
style.showLabels = true;
canvas.setStyle(style);
}
canvas.draw(readSet);
return canvas.getBufferedImage();
}
public String replaceVariable(String path, ChrLoc loc) {
path = path.replaceAll("%chr", loc.chr);
return path;
}
void createPNG(File viewFile, ChrLoc loc) throws Exception {
_logger.info(String.format("query: %s", loc));
TrackDisplay display;
if (viewFile == null) {
display = new TrackDisplay();
Track t = new Track();
t.name = "";
t.db = new DB();
t.db.path = readFile;
display.track.add(t);
}
else
display = SilkLens.loadSilk(TrackDisplay.class, viewFile.toURI().toURL());
String maxWidthText = null;
List<BufferedImage> trackImage = new ArrayList<BufferedImage>();
for (Track track : display.track) {
DB db = track.db;
if (db == null || db.path == null) {
continue;
}
if (maxWidthText == null)
maxWidthText = track.name;
else if (track.name != null && track.name.length() > maxWidthText.length()) {
maxWidthText = track.name;
}
trackImage.add(createReadAlignmentImage(loc, replaceVariable(db.path, loc)));
}
Font f = new Font("Arial", Font.PLAIN, 1);
f = f.deriveFont(10f);
int maxTextWidth = 30;
+ int textHeight = 10;
{
BufferedImage tmp = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) tmp.getGraphics();
g.setFont(f);
maxTextWidth = g.getFontMetrics().stringWidth(maxWidthText);
+ textHeight = g.getFontMetrics().getHeight();
}
// Compute the canvas height
+ final int minTrackHeight = textHeight;
int pixelHeight = 0;
for (BufferedImage each : trackImage)
- pixelHeight += each.getHeight();
+ pixelHeight += Math.max(each.getHeight(), 10);
// Prepare a large canvas
BufferedImage image = new BufferedImage(maxTextWidth + pixelWidth, pixelHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) image.getGraphics();
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setFont(f);
// background
if (backgroundColor != null) {
if (!backgroundColor.startsWith("#"))
backgroundColor = "#" + backgroundColor;
Color bg = Color.decode(backgroundColor);
g.setColor(bg);
g.fillRect(0, 0, image.getWidth(), image.getHeight());
}
// Paste track images
int yOffset = 0;
int yMargin = 1;
int index = 0;
FontMetrics fs = g.getFontMetrics();
- int textHeight = fs.getHeight();
int xOffset = maxTextWidth + 10;
for (BufferedImage each : trackImage) {
Track t = display.track.get(index);
int h = each.getHeight();
int w = each.getWidth();
_logger.debug(String.format("w:%d, h:%d", w, h));
g.drawImage(each, xOffset, yOffset, xOffset + w, yOffset + h, 0, 0, w, h, null);
- if (h < 10)
- h = 10;
+ if (h < minTrackHeight)
+ h = minTrackHeight;
GeneralPath box = new GeneralPath();
box.moveTo(0, yOffset);
box.lineTo(xOffset - 3, yOffset);
box.lineTo(xOffset, textHeight / 2.0 + yOffset);
box.lineTo(xOffset - 3, textHeight + yOffset);
box.lineTo(0, textHeight + yOffset);
box.closePath();
LinearGradientPaint lg = new LinearGradientPaint(0, yOffset, 0, yOffset + textHeight, new float[] { 0, 0.5f, 1.0f }, new Color[] {
Color.decode("#66CCFF"), Color.decode("#3366CC"), Color.decode("#006699") });
g.setPaint(lg);
g.fill(box);
g.setColor(Color.white);
g.drawString(t.name, 0, yOffset + textHeight - 2f);
yOffset += h + yMargin;
index++;
}
// output the graphics as pa PNG file
File outPNG = new File(outputFolder, outFile == null ? String.format("region-%s-%d-%d.png", loc.chr, loc.start, loc.end) : outFile);
_logger.info("output " + outPNG);
ImageIO.write(image, "PNG", outPNG);
}
@Override
public String name() {
return "screenshot";
}
@Override
public String getOneLinerDescription() {
return "take the screenshot of the specified region";
}
}
| false | true | void createPNG(File viewFile, ChrLoc loc) throws Exception {
_logger.info(String.format("query: %s", loc));
TrackDisplay display;
if (viewFile == null) {
display = new TrackDisplay();
Track t = new Track();
t.name = "";
t.db = new DB();
t.db.path = readFile;
display.track.add(t);
}
else
display = SilkLens.loadSilk(TrackDisplay.class, viewFile.toURI().toURL());
String maxWidthText = null;
List<BufferedImage> trackImage = new ArrayList<BufferedImage>();
for (Track track : display.track) {
DB db = track.db;
if (db == null || db.path == null) {
continue;
}
if (maxWidthText == null)
maxWidthText = track.name;
else if (track.name != null && track.name.length() > maxWidthText.length()) {
maxWidthText = track.name;
}
trackImage.add(createReadAlignmentImage(loc, replaceVariable(db.path, loc)));
}
Font f = new Font("Arial", Font.PLAIN, 1);
f = f.deriveFont(10f);
int maxTextWidth = 30;
{
BufferedImage tmp = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) tmp.getGraphics();
g.setFont(f);
maxTextWidth = g.getFontMetrics().stringWidth(maxWidthText);
}
// Compute the canvas height
int pixelHeight = 0;
for (BufferedImage each : trackImage)
pixelHeight += each.getHeight();
// Prepare a large canvas
BufferedImage image = new BufferedImage(maxTextWidth + pixelWidth, pixelHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) image.getGraphics();
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setFont(f);
// background
if (backgroundColor != null) {
if (!backgroundColor.startsWith("#"))
backgroundColor = "#" + backgroundColor;
Color bg = Color.decode(backgroundColor);
g.setColor(bg);
g.fillRect(0, 0, image.getWidth(), image.getHeight());
}
// Paste track images
int yOffset = 0;
int yMargin = 1;
int index = 0;
FontMetrics fs = g.getFontMetrics();
int textHeight = fs.getHeight();
int xOffset = maxTextWidth + 10;
for (BufferedImage each : trackImage) {
Track t = display.track.get(index);
int h = each.getHeight();
int w = each.getWidth();
_logger.debug(String.format("w:%d, h:%d", w, h));
g.drawImage(each, xOffset, yOffset, xOffset + w, yOffset + h, 0, 0, w, h, null);
if (h < 10)
h = 10;
GeneralPath box = new GeneralPath();
box.moveTo(0, yOffset);
box.lineTo(xOffset - 3, yOffset);
box.lineTo(xOffset, textHeight / 2.0 + yOffset);
box.lineTo(xOffset - 3, textHeight + yOffset);
box.lineTo(0, textHeight + yOffset);
box.closePath();
LinearGradientPaint lg = new LinearGradientPaint(0, yOffset, 0, yOffset + textHeight, new float[] { 0, 0.5f, 1.0f }, new Color[] {
Color.decode("#66CCFF"), Color.decode("#3366CC"), Color.decode("#006699") });
g.setPaint(lg);
g.fill(box);
g.setColor(Color.white);
g.drawString(t.name, 0, yOffset + textHeight - 2f);
yOffset += h + yMargin;
index++;
}
// output the graphics as pa PNG file
File outPNG = new File(outputFolder, outFile == null ? String.format("region-%s-%d-%d.png", loc.chr, loc.start, loc.end) : outFile);
_logger.info("output " + outPNG);
ImageIO.write(image, "PNG", outPNG);
}
| void createPNG(File viewFile, ChrLoc loc) throws Exception {
_logger.info(String.format("query: %s", loc));
TrackDisplay display;
if (viewFile == null) {
display = new TrackDisplay();
Track t = new Track();
t.name = "";
t.db = new DB();
t.db.path = readFile;
display.track.add(t);
}
else
display = SilkLens.loadSilk(TrackDisplay.class, viewFile.toURI().toURL());
String maxWidthText = null;
List<BufferedImage> trackImage = new ArrayList<BufferedImage>();
for (Track track : display.track) {
DB db = track.db;
if (db == null || db.path == null) {
continue;
}
if (maxWidthText == null)
maxWidthText = track.name;
else if (track.name != null && track.name.length() > maxWidthText.length()) {
maxWidthText = track.name;
}
trackImage.add(createReadAlignmentImage(loc, replaceVariable(db.path, loc)));
}
Font f = new Font("Arial", Font.PLAIN, 1);
f = f.deriveFont(10f);
int maxTextWidth = 30;
int textHeight = 10;
{
BufferedImage tmp = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) tmp.getGraphics();
g.setFont(f);
maxTextWidth = g.getFontMetrics().stringWidth(maxWidthText);
textHeight = g.getFontMetrics().getHeight();
}
// Compute the canvas height
final int minTrackHeight = textHeight;
int pixelHeight = 0;
for (BufferedImage each : trackImage)
pixelHeight += Math.max(each.getHeight(), 10);
// Prepare a large canvas
BufferedImage image = new BufferedImage(maxTextWidth + pixelWidth, pixelHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) image.getGraphics();
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setFont(f);
// background
if (backgroundColor != null) {
if (!backgroundColor.startsWith("#"))
backgroundColor = "#" + backgroundColor;
Color bg = Color.decode(backgroundColor);
g.setColor(bg);
g.fillRect(0, 0, image.getWidth(), image.getHeight());
}
// Paste track images
int yOffset = 0;
int yMargin = 1;
int index = 0;
FontMetrics fs = g.getFontMetrics();
int xOffset = maxTextWidth + 10;
for (BufferedImage each : trackImage) {
Track t = display.track.get(index);
int h = each.getHeight();
int w = each.getWidth();
_logger.debug(String.format("w:%d, h:%d", w, h));
g.drawImage(each, xOffset, yOffset, xOffset + w, yOffset + h, 0, 0, w, h, null);
if (h < minTrackHeight)
h = minTrackHeight;
GeneralPath box = new GeneralPath();
box.moveTo(0, yOffset);
box.lineTo(xOffset - 3, yOffset);
box.lineTo(xOffset, textHeight / 2.0 + yOffset);
box.lineTo(xOffset - 3, textHeight + yOffset);
box.lineTo(0, textHeight + yOffset);
box.closePath();
LinearGradientPaint lg = new LinearGradientPaint(0, yOffset, 0, yOffset + textHeight, new float[] { 0, 0.5f, 1.0f }, new Color[] {
Color.decode("#66CCFF"), Color.decode("#3366CC"), Color.decode("#006699") });
g.setPaint(lg);
g.fill(box);
g.setColor(Color.white);
g.drawString(t.name, 0, yOffset + textHeight - 2f);
yOffset += h + yMargin;
index++;
}
// output the graphics as pa PNG file
File outPNG = new File(outputFolder, outFile == null ? String.format("region-%s-%d-%d.png", loc.chr, loc.start, loc.end) : outFile);
_logger.info("output " + outPNG);
ImageIO.write(image, "PNG", outPNG);
}
|
diff --git a/sample/src/com/twotoasters/android/horizontalimagescroller/sample/MainActivity.java b/sample/src/com/twotoasters/android/horizontalimagescroller/sample/MainActivity.java
index 9f0f026..0d5e95d 100644
--- a/sample/src/com/twotoasters/android/horizontalimagescroller/sample/MainActivity.java
+++ b/sample/src/com/twotoasters/android/horizontalimagescroller/sample/MainActivity.java
@@ -1,317 +1,316 @@
/*
Copyright 2012 Two Toasters, LLC
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.twotoasters.android.horizontalimagescroller.sample;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;
import com.twotoasters.android.horizontalimagescroller.image.ImageToLoad;
import com.twotoasters.android.horizontalimagescroller.image.ImageToLoadDrawableResource;
import com.twotoasters.android.horizontalimagescroller.image.ImageToLoadUrl;
import com.twotoasters.android.horizontalimagescroller.widget.HorizontalImageScroller;
import com.twotoasters.android.horizontalimagescroller.widget.HorizontalImageScrollerAdapter;
import com.twotoasters.android.horizontalimagescroller.widget.SelectionToggleOnItemClickListener;
public class MainActivity extends Activity {
/*
* there are multiple HorizontalImageScroller widgets in this activity, and there are some
* cases where we want to perform the same operations on all of them. if your activity only
* has one instance, keeping a reference is probably not necessary (but may be convenient)
*/
private List<HorizontalImageScroller> _horizontalImageScrollers;
// String key for persisting the scrollX position in Bundle objects
private static final String KEY_SCROLL_XES = "scrollXes";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_horizontalImageScrollers = new ArrayList<HorizontalImageScroller>();
/*
* this is a convenience to map our ImageToLoad objects by name of toaster, making it easy
* to reference toasters by name. your app probably doesn't need to use this pattern,
- * but since this app is "programmer art" with no format design process, this object made
- * it easy to change the design direction without too detracting too much from my quality
- * of life.
+ * but since this app is "programmer art" with no formal design process, this lessened the
+ * impact on my quality of life when changing the design.
*/
ToasterImageToLoadHolder toasters = new ToasterImageToLoadHolder();
/*
* demonstrate onItemClick handling. Use the adapter's getItem() method to find the backing
* object for the clicked item. Tap a toaster where this listener is set to see a Toast
* with the name of the Toaster.
*/
OnItemClickListener onItemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ToasterToLoad toaster = (ToasterToLoad)((HorizontalImageScroller)parent).getAdapter().getItem(position);
Toast.makeText(MainActivity.this, toaster.getName(), Toast.LENGTH_SHORT).show();
}
};
// android toasters
ArrayList<ImageToLoad> androidToasters = new ArrayList<ImageToLoad>();
androidToasters.add(toasters.BRIAN);
androidToasters.add(toasters.CARLTON);
androidToasters.add(toasters.JEREMY);
androidToasters.add(toasters.PAT);
_setupToasterScroller(androidToasters, R.id.scroller_androids, onItemClickListener); // more on this method later
// ios toasters
ArrayList<ImageToLoad> iosToasters = new ArrayList<ImageToLoad>();
iosToasters.add(toasters.DIRK);
iosToasters.add(toasters.DUNCAN);
iosToasters.add(toasters.GEOFF);
iosToasters.add(toasters.KEVIN);
iosToasters.add(toasters.JOSH);
iosToasters.add(toasters.SCOTT);
_setupToasterScroller(iosToasters, R.id.scroller_ioesses, onItemClickListener); // isn't it nice when code is reusable?
// biz dev toasters
ArrayList<ImageToLoad> bizDevToasters = new ArrayList<ImageToLoad>();
bizDevToasters.add(toasters.RACHIT);
bizDevToasters.add(toasters.SIMON);
_setupToasterScroller(bizDevToasters, R.id.scroller_bizdevs, onItemClickListener);
// pm toasters
ArrayList<ImageToLoad> pmToasters = new ArrayList<ImageToLoad>();
pmToasters.add(toasters.KAYLA);
pmToasters.add(toasters.MATT);
_setupToasterScroller(pmToasters, R.id.scroller_pms, onItemClickListener);
// designer toasters
ArrayList<ImageToLoad> designerToasters = new ArrayList<ImageToLoad>();
designerToasters.add(toasters.ADIT);
designerToasters.add(toasters.DUSTIN);
_setupToasterScroller(designerToasters, R.id.scroller_designers, onItemClickListener);
// all toasters
ArrayList<ImageToLoad> allToasters = new ArrayList<ImageToLoad>();
allToasters.addAll(androidToasters);
allToasters.addAll(iosToasters);
allToasters.addAll(bizDevToasters);
allToasters.addAll(pmToasters);
allToasters.addAll(designerToasters);
HorizontalImageScroller scroller = (HorizontalImageScroller)findViewById(R.id.scroller_all_toasters);
// AllToasters...Adapter provides some additional functionality... keep reading
HorizontalImageScrollerAdapter adapter = new AllToastersHorizontalImageScrollerAdapter(this, allToasters);
scroller.setAdapter(adapter);
/*
* use our handy dandy SelectionToggleOnItemClickListener. It toggles the selection state
* of the clicked item
*/
scroller.setOnItemClickListener(new SelectionToggleOnItemClickListener());
/*
* if onCreate() has been called with a non-null savedInstanceState, then we're recreating
* the activity following a device configuration change (such as the user rotated the
* device). here we restore the scroll position of each HorizontalImageScroller widget.
* if you don't mind losing the scroll position, you don't *have* to do this, but don't
* blame me if your users rage-quit over it.
*/
if(savedInstanceState != null) {
// restore the scroll position of each scroller
int[] scrollXes = savedInstanceState.getIntArray(KEY_SCROLL_XES);
for(int i = 0; i < scrollXes.length; i++) {
_horizontalImageScrollers.get(i).scrollTo(scrollXes[i]);
}
}
}
/*
* since most of the toaster scrollers have the exact same behavior and appearance (except
* for the toasters on display), here we make the setup process reusable.
*/
private void _setupToasterScroller(ArrayList<ImageToLoad> imagesToLoad, int scrollerResourceId, OnItemClickListener onItemClickListener) {
HorizontalImageScroller scroller = (HorizontalImageScroller)findViewById(scrollerResourceId);
HorizontalImageScrollerAdapter adapter = new HorizontalImageScrollerAdapter(MainActivity.this, imagesToLoad);
adapter.setLoadingImageResourceId(R.drawable.generic_toaster);
adapter.setImageSize((int) getResources().getDimension(R.dimen.image_size));
adapter.setDefaultImageFailedToLoadResourceId(R.drawable.generic_toaster);
scroller.setAdapter(adapter);
scroller.setOnItemClickListener(onItemClickListener);
_horizontalImageScrollers.add(scroller);
}
private String getGravatarUrl(String hash) {
StringBuilder builder = new StringBuilder("http://www.gravatar.com/avatar/");
builder.append(hash)
.append(".jpg?size=200")
.append("&rating=g")
.append("&default=404");
return builder.toString();
}
@Override
protected void onPause() {
super.onPause();
/*
* when your activity pauses, your activity will release its layout, and in turn the
* ImageView objects. however, the HorizontalImageScrollerAdapter may have passed
* references to some of those objects into the ImageCacheManager, which might still
* be hanging onto them. if you don't unbind them, they won't be garbage collected.
* if you only have one HorizontalImageScroller (and no need for a list), you can
* get its adapter, and call its unbindImageViews() directly.
* HorizontalImageScroller.unbindImageViews(List<HorizontalImageScroller> scrollers) is
* just for convenience if you have multiple scrollers.
*/
HorizontalImageScroller.unbindImageViews(_horizontalImageScrollers);
}
/*
* map the ToasterToLoad* objects to the name of the toaster for easy reference. again, you
* probably don't need to use this pattern in your app. i figure a hard-coded multiple
* hard-coded lists sharing the same images is a bit of a contrived use-case.
*/
private class ToasterImageToLoadHolder {
ImageToLoad ADIT = new ToasterToLoadDrawableResource(R.drawable.adit, "Adit Shukla");
ImageToLoad BRIAN = new ToasterToLoadDrawableResource(R.drawable.brian, "Brian Dupuis");
ImageToLoad CARLTON = new ToasterToLoadDrawableResource(R.drawable.carlton, "Carlton Whitehead");
ImageToLoad JEREMY = new ToasterToLoadDrawableResource(R.drawable.jeremy, "Jeremy Ellison");
ImageToLoad PAT = new ToasterToLoadDrawableResource(R.drawable.pat, "Pat Fives");
ImageToLoad DIRK = new ToasterToLoadDrawableResource(R.drawable.dirk, "Dirk Smith");
ImageToLoad DUNCAN = new ToasterToLoadDrawableResource(R.drawable.duncan, "Duncan Lewis");
ImageToLoad GEOFF = new ToasterToLoadDrawableResource(R.drawable.geoff, "Geoff Mackey");
ImageToLoad KEVIN = new ToasterToLoadUrl(getGravatarUrl("070948597b3f5b4f1a98cc01e3e3da8a"), "Kevin Conner");
ImageToLoad JOSH = new ToasterToLoadDrawableResource(R.drawable.josh, "Josh Johnson");
ImageToLoad SCOTT = new ToasterToLoadDrawableResource(R.drawable.scott, "Scott Penrose");
ImageToLoad RACHIT = new ToasterToLoadDrawableResource(R.drawable.rachit, "Rachit Shukla");
ImageToLoad SIMON = new ToasterToLoadUrl(getGravatarUrl("86752d9f14430042c1aad0054081249c"), "Simon Kirk");
ImageToLoad MATT = new ToasterToLoadUrl(getGravatarUrl("efb9d67132359d3a8cbc3cefd1169eb4"), "Matt Raimundo");
ImageToLoad KAYLA = new ToasterToLoadUrl(getGravatarUrl("20580e80650dcf07167e9c8779371e16"), "Kayla Bourgeois");
ImageToLoad DUSTIN = new ToasterToLoadUrl(getGravatarUrl("266f809f5baf5421098c93e73520ad42"), "Dustin Rhodes");
}
/*
* make it easy to get the toaster's name on the Toaster...Url/Drawable subclasses
*/
private interface ToasterToLoad {
public String getName();
}
/*
* extend the ImageToLoadUrl class with the name of a toaster
*/
private class ToasterToLoadUrl extends ImageToLoadUrl implements ToasterToLoad {
private String _name;
public ToasterToLoadUrl(String url, String name) {
super(url);
_name = name;
/*
* ImageToLoadUrl objects won't have their images cached by default. in this case,
* we always want ToasterToLoadUrl to have their images cached, so we set that here.
* there is also a public setter you can use if you want more nuanced control in your
* app. one more piece is required for this to work, though. in your manifest, make
* sure you have the following uses-permission tags:
* INTERNET
* WRITE_EXTERNAL_STORAGE
*/
_canCacheFile = true;
}
public String getName() {
return _name;
}
}
/*
* extend the ImageToLoadDrawableResource with the name of a toaster
*/
private class ToasterToLoadDrawableResource extends ImageToLoadDrawableResource implements ToasterToLoad {
private String _name;
public ToasterToLoadDrawableResource(int drawableResourceId, String name) {
super(drawableResourceId);
_name = name;
}
public String getName() {
return _name;
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// store the scroll position of each scroller
// (so they can be restored after device configuration change)
int[] scrollXes = new int[_horizontalImageScrollers.size()];
for(HorizontalImageScroller scroller : _horizontalImageScrollers) {
// deters the wrath of your users
scrollXes[_horizontalImageScrollers.indexOf(scroller)] = scroller.getCurrentX();
}
outState.putIntArray(KEY_SCROLL_XES, scrollXes);
}
/*
* custom adapter with a custom layout that shows the name of the toaster as a caption, and
* provides selection state
*/
private class AllToastersHorizontalImageScrollerAdapter extends HorizontalImageScrollerAdapter {
public AllToastersHorizontalImageScrollerAdapter(Context context, List<ImageToLoad> images) {
super(context, images);
_showImageFrame = true;
_highlightActive = true;
// substitute our custom layout
_imageLayoutResourceId = R.layout.alltoasters_horizontal_image_scroller_item;
_imageSize = (int) getResources().getDimension(R.dimen.image_size);
_loadingImageResourceId = R.drawable.generic_toaster;
_defaultImageFailedToLoadResourceId = R.drawable.generic_toaster;
_frameColor = getResources().getColor(R.color.light_grey);
_frameOffColor = getResources().getColor(android.R.color.transparent);
/*
* if you specify a custom layout, you MUST also specify the _imageIdInLayout and
* _innerWrapperIdInLayout. since we're using a custom layout, keep in mind that
* although the id of the image appears to be the same as the one in the stock layout
* at first glance, the sample app is a different "project", so its R class is a
* different package, and the underlying integer id will almost surely differ.
*/
_imageIdInLayout = R.id.image;
_innerWrapperIdInLayout = R.id.inner_wrapper;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// the parent getView() method does most of the hard work
View view = super.getView(position, convertView, parent);
// set the caption to the name of the toaster
TextView textView = (TextView) view.findViewById(R.id.name);
textView.setText(((ToasterToLoad) getItem(position)).getName());
return view;
}
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_horizontalImageScrollers = new ArrayList<HorizontalImageScroller>();
/*
* this is a convenience to map our ImageToLoad objects by name of toaster, making it easy
* to reference toasters by name. your app probably doesn't need to use this pattern,
* but since this app is "programmer art" with no format design process, this object made
* it easy to change the design direction without too detracting too much from my quality
* of life.
*/
ToasterImageToLoadHolder toasters = new ToasterImageToLoadHolder();
/*
* demonstrate onItemClick handling. Use the adapter's getItem() method to find the backing
* object for the clicked item. Tap a toaster where this listener is set to see a Toast
* with the name of the Toaster.
*/
OnItemClickListener onItemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ToasterToLoad toaster = (ToasterToLoad)((HorizontalImageScroller)parent).getAdapter().getItem(position);
Toast.makeText(MainActivity.this, toaster.getName(), Toast.LENGTH_SHORT).show();
}
};
// android toasters
ArrayList<ImageToLoad> androidToasters = new ArrayList<ImageToLoad>();
androidToasters.add(toasters.BRIAN);
androidToasters.add(toasters.CARLTON);
androidToasters.add(toasters.JEREMY);
androidToasters.add(toasters.PAT);
_setupToasterScroller(androidToasters, R.id.scroller_androids, onItemClickListener); // more on this method later
// ios toasters
ArrayList<ImageToLoad> iosToasters = new ArrayList<ImageToLoad>();
iosToasters.add(toasters.DIRK);
iosToasters.add(toasters.DUNCAN);
iosToasters.add(toasters.GEOFF);
iosToasters.add(toasters.KEVIN);
iosToasters.add(toasters.JOSH);
iosToasters.add(toasters.SCOTT);
_setupToasterScroller(iosToasters, R.id.scroller_ioesses, onItemClickListener); // isn't it nice when code is reusable?
// biz dev toasters
ArrayList<ImageToLoad> bizDevToasters = new ArrayList<ImageToLoad>();
bizDevToasters.add(toasters.RACHIT);
bizDevToasters.add(toasters.SIMON);
_setupToasterScroller(bizDevToasters, R.id.scroller_bizdevs, onItemClickListener);
// pm toasters
ArrayList<ImageToLoad> pmToasters = new ArrayList<ImageToLoad>();
pmToasters.add(toasters.KAYLA);
pmToasters.add(toasters.MATT);
_setupToasterScroller(pmToasters, R.id.scroller_pms, onItemClickListener);
// designer toasters
ArrayList<ImageToLoad> designerToasters = new ArrayList<ImageToLoad>();
designerToasters.add(toasters.ADIT);
designerToasters.add(toasters.DUSTIN);
_setupToasterScroller(designerToasters, R.id.scroller_designers, onItemClickListener);
// all toasters
ArrayList<ImageToLoad> allToasters = new ArrayList<ImageToLoad>();
allToasters.addAll(androidToasters);
allToasters.addAll(iosToasters);
allToasters.addAll(bizDevToasters);
allToasters.addAll(pmToasters);
allToasters.addAll(designerToasters);
HorizontalImageScroller scroller = (HorizontalImageScroller)findViewById(R.id.scroller_all_toasters);
// AllToasters...Adapter provides some additional functionality... keep reading
HorizontalImageScrollerAdapter adapter = new AllToastersHorizontalImageScrollerAdapter(this, allToasters);
scroller.setAdapter(adapter);
/*
* use our handy dandy SelectionToggleOnItemClickListener. It toggles the selection state
* of the clicked item
*/
scroller.setOnItemClickListener(new SelectionToggleOnItemClickListener());
/*
* if onCreate() has been called with a non-null savedInstanceState, then we're recreating
* the activity following a device configuration change (such as the user rotated the
* device). here we restore the scroll position of each HorizontalImageScroller widget.
* if you don't mind losing the scroll position, you don't *have* to do this, but don't
* blame me if your users rage-quit over it.
*/
if(savedInstanceState != null) {
// restore the scroll position of each scroller
int[] scrollXes = savedInstanceState.getIntArray(KEY_SCROLL_XES);
for(int i = 0; i < scrollXes.length; i++) {
_horizontalImageScrollers.get(i).scrollTo(scrollXes[i]);
}
}
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_horizontalImageScrollers = new ArrayList<HorizontalImageScroller>();
/*
* this is a convenience to map our ImageToLoad objects by name of toaster, making it easy
* to reference toasters by name. your app probably doesn't need to use this pattern,
* but since this app is "programmer art" with no formal design process, this lessened the
* impact on my quality of life when changing the design.
*/
ToasterImageToLoadHolder toasters = new ToasterImageToLoadHolder();
/*
* demonstrate onItemClick handling. Use the adapter's getItem() method to find the backing
* object for the clicked item. Tap a toaster where this listener is set to see a Toast
* with the name of the Toaster.
*/
OnItemClickListener onItemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ToasterToLoad toaster = (ToasterToLoad)((HorizontalImageScroller)parent).getAdapter().getItem(position);
Toast.makeText(MainActivity.this, toaster.getName(), Toast.LENGTH_SHORT).show();
}
};
// android toasters
ArrayList<ImageToLoad> androidToasters = new ArrayList<ImageToLoad>();
androidToasters.add(toasters.BRIAN);
androidToasters.add(toasters.CARLTON);
androidToasters.add(toasters.JEREMY);
androidToasters.add(toasters.PAT);
_setupToasterScroller(androidToasters, R.id.scroller_androids, onItemClickListener); // more on this method later
// ios toasters
ArrayList<ImageToLoad> iosToasters = new ArrayList<ImageToLoad>();
iosToasters.add(toasters.DIRK);
iosToasters.add(toasters.DUNCAN);
iosToasters.add(toasters.GEOFF);
iosToasters.add(toasters.KEVIN);
iosToasters.add(toasters.JOSH);
iosToasters.add(toasters.SCOTT);
_setupToasterScroller(iosToasters, R.id.scroller_ioesses, onItemClickListener); // isn't it nice when code is reusable?
// biz dev toasters
ArrayList<ImageToLoad> bizDevToasters = new ArrayList<ImageToLoad>();
bizDevToasters.add(toasters.RACHIT);
bizDevToasters.add(toasters.SIMON);
_setupToasterScroller(bizDevToasters, R.id.scroller_bizdevs, onItemClickListener);
// pm toasters
ArrayList<ImageToLoad> pmToasters = new ArrayList<ImageToLoad>();
pmToasters.add(toasters.KAYLA);
pmToasters.add(toasters.MATT);
_setupToasterScroller(pmToasters, R.id.scroller_pms, onItemClickListener);
// designer toasters
ArrayList<ImageToLoad> designerToasters = new ArrayList<ImageToLoad>();
designerToasters.add(toasters.ADIT);
designerToasters.add(toasters.DUSTIN);
_setupToasterScroller(designerToasters, R.id.scroller_designers, onItemClickListener);
// all toasters
ArrayList<ImageToLoad> allToasters = new ArrayList<ImageToLoad>();
allToasters.addAll(androidToasters);
allToasters.addAll(iosToasters);
allToasters.addAll(bizDevToasters);
allToasters.addAll(pmToasters);
allToasters.addAll(designerToasters);
HorizontalImageScroller scroller = (HorizontalImageScroller)findViewById(R.id.scroller_all_toasters);
// AllToasters...Adapter provides some additional functionality... keep reading
HorizontalImageScrollerAdapter adapter = new AllToastersHorizontalImageScrollerAdapter(this, allToasters);
scroller.setAdapter(adapter);
/*
* use our handy dandy SelectionToggleOnItemClickListener. It toggles the selection state
* of the clicked item
*/
scroller.setOnItemClickListener(new SelectionToggleOnItemClickListener());
/*
* if onCreate() has been called with a non-null savedInstanceState, then we're recreating
* the activity following a device configuration change (such as the user rotated the
* device). here we restore the scroll position of each HorizontalImageScroller widget.
* if you don't mind losing the scroll position, you don't *have* to do this, but don't
* blame me if your users rage-quit over it.
*/
if(savedInstanceState != null) {
// restore the scroll position of each scroller
int[] scrollXes = savedInstanceState.getIntArray(KEY_SCROLL_XES);
for(int i = 0; i < scrollXes.length; i++) {
_horizontalImageScrollers.get(i).scrollTo(scrollXes[i]);
}
}
}
|
diff --git a/mes-plugins/mes-plugins-assignment-to-shift/src/main/java/com/qcadoo/mes/assignmentToShift/print/xls/AssignmentToShiftXlsService.java b/mes-plugins/mes-plugins-assignment-to-shift/src/main/java/com/qcadoo/mes/assignmentToShift/print/xls/AssignmentToShiftXlsService.java
index 85e41e5485..b20f7ef44f 100644
--- a/mes-plugins/mes-plugins-assignment-to-shift/src/main/java/com/qcadoo/mes/assignmentToShift/print/xls/AssignmentToShiftXlsService.java
+++ b/mes-plugins/mes-plugins-assignment-to-shift/src/main/java/com/qcadoo/mes/assignmentToShift/print/xls/AssignmentToShiftXlsService.java
@@ -1,283 +1,284 @@
/**
* ***************************************************************************
* Copyright (c) 2010 Qcadoo Limited
* Project: Qcadoo MES
* Version: 1.2.0
*
* This file is part of Qcadoo.
*
* Qcadoo 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, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* ***************************************************************************
*/
package com.qcadoo.mes.assignmentToShift.print.xls;
import static com.qcadoo.mes.assignmentToShift.constants.AssignmentToShiftFields.SHIFT;
import static com.qcadoo.mes.assignmentToShift.constants.AssignmentToShiftReportConstants.COLUMN_HEADER_AUTHOR;
import static com.qcadoo.mes.assignmentToShift.constants.AssignmentToShiftReportConstants.COLUMN_HEADER_DAY;
import static com.qcadoo.mes.assignmentToShift.constants.AssignmentToShiftReportConstants.COLUMN_HEADER_OCCUPATIONTYPE;
import static com.qcadoo.mes.assignmentToShift.constants.AssignmentToShiftReportConstants.COLUMN_HEADER_SHIFT;
import static com.qcadoo.mes.assignmentToShift.constants.AssignmentToShiftReportConstants.COLUMN_HEADER_UPDATE_DATE;
import static com.qcadoo.mes.assignmentToShift.constants.AssignmentToShiftReportConstants.TITLE;
import static com.qcadoo.mes.assignmentToShift.constants.AssignmentToShiftReportFields.CREATE_USER;
import static com.qcadoo.mes.assignmentToShift.constants.AssignmentToShiftReportFields.UPDATE_DATE;
import static com.qcadoo.mes.basic.constants.ShiftFields.NAME;
import static com.qcadoo.mes.productionLines.constants.ProductionLineFields.NUMBER;
import static com.qcadoo.mes.productionLines.constants.ProductionLineFields.PLACE;
import static com.qcadoo.model.constants.DictionaryItemFields.TECHNICAL_CODE;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qcadoo.localization.api.TranslationService;
import com.qcadoo.mes.assignmentToShift.constants.OccupationType;
import com.qcadoo.mes.productionLines.constants.ProductionLineFields;
import com.qcadoo.model.api.DataDefinitionService;
import com.qcadoo.model.api.Entity;
import com.qcadoo.model.api.search.SearchRestrictions;
import com.qcadoo.model.constants.QcadooModelConstants;
import com.qcadoo.report.api.xls.XlsDocumentService;
@Service
public class AssignmentToShiftXlsService extends XlsDocumentService {
@Autowired
private TranslationService translationService;
@Autowired
private AssignmentToShiftXlsHelper assignmentToShiftXlsHelper;
@Autowired
private AssignmentToShiftXlsStyleHelper assignmentToShiftXlsStyleHelper;
@Autowired
private DataDefinitionService dataDefinitionService;
@Override
public String getReportTitle(final Locale locale) {
return translationService.translate(TITLE, locale);
}
@Override
protected void addHeader(final HSSFSheet sheet, final Locale locale, final Entity entity) {
createHeaderForAuthor(sheet, locale, entity);
createHeaderForAssignmentToShift(sheet, locale, entity);
}
private void createHeaderForAuthor(final HSSFSheet sheet, final Locale locale, final Entity entity) {
HSSFRow headerAuthorLine = sheet.createRow(1);
String shift = translationService.translate(COLUMN_HEADER_SHIFT, locale) + " "
+ entity.getBelongsToField(SHIFT).getStringField(NAME);
String user = translationService.translate(COLUMN_HEADER_AUTHOR, locale) + " " + entity.getField(CREATE_USER).toString();
String date = translationService.translate(COLUMN_HEADER_UPDATE_DATE, locale) + " "
+ DateFormat.getDateInstance().format(entity.getField(UPDATE_DATE));
HSSFCell cellAuthorLine0 = headerAuthorLine.createCell(0);
cellAuthorLine0.setCellValue(shift);
HSSFCell cellAuthorLine3 = headerAuthorLine.createCell(3);
cellAuthorLine3.setCellValue(date);
HSSFCell cellAuthorLine6 = headerAuthorLine.createCell(6);
cellAuthorLine6.setCellValue(user);
headerAuthorLine.setHeightInPoints(30);
assignmentToShiftXlsStyleHelper.addMarginsAndStylesForAuthor(sheet, 1,
assignmentToShiftXlsHelper.getNumberOfDaysBetweenGivenDates(entity));
}
private void createHeaderForAssignmentToShift(final HSSFSheet sheet, final Locale locale, final Entity entity) {
List<DateTime> days = assignmentToShiftXlsHelper.getDaysBetweenGivenDates(entity);
if (days != null) {
HSSFRow headerAssignmentToShift = sheet.createRow(3);
String occupationType = translationService.translate(COLUMN_HEADER_OCCUPATIONTYPE, locale);
HSSFCell cell0 = headerAssignmentToShift.createCell(0);
cell0.setCellValue(occupationType);
int columnNumber = 1;
for (DateTime day : days) {
HSSFCell cellDay = headerAssignmentToShift.createCell(columnNumber);
cellDay.setCellValue(translationService.translate(COLUMN_HEADER_DAY, locale,
DateFormat.getDateInstance().format(new Date(day.getMillis()))));
columnNumber += 3;
}
headerAssignmentToShift.setHeightInPoints(14);
assignmentToShiftXlsStyleHelper.addMarginsAndStylesForAssignmentToShift(sheet, 3,
assignmentToShiftXlsHelper.getNumberOfDaysBetweenGivenDates(entity));
}
}
@Override
protected void addSeries(final HSSFSheet sheet, final Entity entity) {
List<DateTime> days = assignmentToShiftXlsHelper.getDaysBetweenGivenDates(entity);
if (days != null) {
int rowNum = 4;
List<Entity> occupationTypesWithoutTechnicalCode = getOccupationTypeDictionaryWithoutTechnicalCode();
List<Entity> productionlines = assignmentToShiftXlsHelper.getProductionLines();
if (!productionlines.isEmpty()) {
fillColumnWithStaffForWorkOnLine(sheet, rowNum, entity, days, productionlines,
getDictionaryItemWithProductionOnLine());
rowNum += productionlines.size();
}
for (Entity dictionaryItem : occupationTypesWithoutTechnicalCode) {
fillColumnWithStaffForOtherTypes(sheet, rowNum, entity, days, dictionaryItem);
rowNum++;
}
fillColumnWithStaffForOtherTypes(sheet, rowNum, entity, days, getDictionaryItemWithOtherCase());
sheet.autoSizeColumn(0);
}
}
private void fillColumnWithStaffForWorkOnLine(final HSSFSheet sheet, int rowNum, final Entity assignmentToShiftReport,
final List<DateTime> days, final List<Entity> productionLines, final Entity dictionaryItem) {
if ((assignmentToShiftReport != null) && (days != null) && (productionLines != null)) {
for (Entity productionLine : productionLines) {
HSSFRow row = sheet.createRow(rowNum);
String productionLineValue = null;
if (productionLine.getStringField(PLACE) == null) {
productionLineValue = productionLine.getStringField(NUMBER);
} else {
productionLineValue = productionLine.getStringField(NUMBER) + "-"
+ productionLine.getStringField(ProductionLineFields.PLACE);
}
row.createCell(0).setCellValue(productionLineValue);
if (assignmentToShiftXlsHelper.getProductionLinesWithStaff(productionLine).isEmpty()) {
assignmentToShiftXlsStyleHelper.addMarginsAndStylesForSeries(sheet, rowNum,
assignmentToShiftXlsHelper.getNumberOfDaysBetweenGivenDates(assignmentToShiftReport));
+ rowNum++;
continue;
}
int columnNumber = 1;
int maxLength = 0;
for (DateTime day : days) {
Entity assignmentToShift = assignmentToShiftXlsHelper.getAssignmentToShift(
assignmentToShiftReport.getBelongsToField(SHIFT), day.toDate());
if (assignmentToShift == null) {
columnNumber += 3;
continue;
}
List<Entity> staffs = assignmentToShiftXlsHelper.getStaffsList(assignmentToShift,
dictionaryItem.getStringField(NAME), productionLine);
if (staffs.isEmpty()) {
columnNumber += 3;
continue;
}
String staffsValue = assignmentToShiftXlsHelper.getListOfWorkers(staffs);
row.createCell(columnNumber).setCellValue(staffsValue);
if (maxLength < staffsValue.length()) {
maxLength = staffsValue.length();
}
row.setHeightInPoints(assignmentToShiftXlsStyleHelper.getHeightForRow(maxLength, 22, 14));
columnNumber += 3;
}
assignmentToShiftXlsStyleHelper.addMarginsAndStylesForSeries(sheet, rowNum,
assignmentToShiftXlsHelper.getNumberOfDaysBetweenGivenDates(assignmentToShiftReport));
rowNum++;
}
}
}
private void fillColumnWithStaffForOtherTypes(final HSSFSheet sheet, final int rowNum, final Entity assignmentToShiftReport,
final List<DateTime> days, final Entity occupationType) {
if ((assignmentToShiftReport != null) && (days != null) && (occupationType != null)) {
HSSFRow row = sheet.createRow(rowNum);
String occupationTypeValue = occupationType.getStringField(NAME);
row.createCell(0).setCellValue(occupationTypeValue);
int columnNumber = 1;
int maxLength = 0;
for (DateTime day : days) {
Entity assignmentToShift = assignmentToShiftXlsHelper.getAssignmentToShift(
assignmentToShiftReport.getBelongsToField(SHIFT), day.toDate());
if (assignmentToShift == null) {
columnNumber += 3;
continue;
}
List<Entity> staffs = assignmentToShiftXlsHelper.getStaffsList(assignmentToShift,
occupationType.getStringField(NAME), null);
String staffsValue = null;
if (OccupationType.OTHER_CASE.getStringValue().equals(occupationType.getStringField(TECHNICAL_CODE))) {
staffsValue = assignmentToShiftXlsHelper.getListOfWorkersWithOtherCases(staffs);
} else {
staffsValue = assignmentToShiftXlsHelper.getListOfWorkers(staffs);
}
row.createCell(columnNumber).setCellValue(staffsValue);
if (maxLength < staffsValue.length()) {
maxLength = staffsValue.length();
}
row.setHeightInPoints(assignmentToShiftXlsStyleHelper.getHeightForRow(maxLength, 22, 14));
columnNumber += 3;
}
assignmentToShiftXlsStyleHelper.addMarginsAndStylesForSeries(sheet, rowNum,
assignmentToShiftXlsHelper.getNumberOfDaysBetweenGivenDates(assignmentToShiftReport));
}
}
private List<Entity> getOccupationTypeDictionaryWithoutTechnicalCode() {
Entity occupationTypeDictionary = dataDefinitionService
.get(QcadooModelConstants.PLUGIN_IDENTIFIER, QcadooModelConstants.MODEL_DICTIONARY).find()
.add(SearchRestrictions.eq(NAME, "occupationType")).uniqueResult();
return dataDefinitionService.get(QcadooModelConstants.PLUGIN_IDENTIFIER, QcadooModelConstants.MODEL_DICTIONARY_ITEM)
.find().add(SearchRestrictions.belongsTo("dictionary", occupationTypeDictionary))
.add(SearchRestrictions.isNull("technicalCode")).list().getEntities();
}
private Entity getDictionaryItemWithProductionOnLine() {
Entity occupationTypeDictionary = dataDefinitionService
.get(QcadooModelConstants.PLUGIN_IDENTIFIER, QcadooModelConstants.MODEL_DICTIONARY).find()
.add(SearchRestrictions.eq(NAME, "occupationType")).uniqueResult();
return dataDefinitionService.get(QcadooModelConstants.PLUGIN_IDENTIFIER, QcadooModelConstants.MODEL_DICTIONARY_ITEM)
.find().add(SearchRestrictions.belongsTo("dictionary", occupationTypeDictionary))
.add(SearchRestrictions.eq("technicalCode", OccupationType.WORK_ON_LINE.getStringValue())).uniqueResult();
}
private Entity getDictionaryItemWithOtherCase() {
Entity occupationTypeDictionary = dataDefinitionService
.get(QcadooModelConstants.PLUGIN_IDENTIFIER, QcadooModelConstants.MODEL_DICTIONARY).find()
.add(SearchRestrictions.eq(NAME, "occupationType")).uniqueResult();
return dataDefinitionService.get(QcadooModelConstants.PLUGIN_IDENTIFIER, QcadooModelConstants.MODEL_DICTIONARY_ITEM)
.find().add(SearchRestrictions.belongsTo("dictionary", occupationTypeDictionary))
.add(SearchRestrictions.eq("technicalCode", OccupationType.OTHER_CASE.getStringValue())).uniqueResult();
}
}
| true | true | private void fillColumnWithStaffForWorkOnLine(final HSSFSheet sheet, int rowNum, final Entity assignmentToShiftReport,
final List<DateTime> days, final List<Entity> productionLines, final Entity dictionaryItem) {
if ((assignmentToShiftReport != null) && (days != null) && (productionLines != null)) {
for (Entity productionLine : productionLines) {
HSSFRow row = sheet.createRow(rowNum);
String productionLineValue = null;
if (productionLine.getStringField(PLACE) == null) {
productionLineValue = productionLine.getStringField(NUMBER);
} else {
productionLineValue = productionLine.getStringField(NUMBER) + "-"
+ productionLine.getStringField(ProductionLineFields.PLACE);
}
row.createCell(0).setCellValue(productionLineValue);
if (assignmentToShiftXlsHelper.getProductionLinesWithStaff(productionLine).isEmpty()) {
assignmentToShiftXlsStyleHelper.addMarginsAndStylesForSeries(sheet, rowNum,
assignmentToShiftXlsHelper.getNumberOfDaysBetweenGivenDates(assignmentToShiftReport));
continue;
}
int columnNumber = 1;
int maxLength = 0;
for (DateTime day : days) {
Entity assignmentToShift = assignmentToShiftXlsHelper.getAssignmentToShift(
assignmentToShiftReport.getBelongsToField(SHIFT), day.toDate());
if (assignmentToShift == null) {
columnNumber += 3;
continue;
}
List<Entity> staffs = assignmentToShiftXlsHelper.getStaffsList(assignmentToShift,
dictionaryItem.getStringField(NAME), productionLine);
if (staffs.isEmpty()) {
columnNumber += 3;
continue;
}
String staffsValue = assignmentToShiftXlsHelper.getListOfWorkers(staffs);
row.createCell(columnNumber).setCellValue(staffsValue);
if (maxLength < staffsValue.length()) {
maxLength = staffsValue.length();
}
row.setHeightInPoints(assignmentToShiftXlsStyleHelper.getHeightForRow(maxLength, 22, 14));
columnNumber += 3;
}
assignmentToShiftXlsStyleHelper.addMarginsAndStylesForSeries(sheet, rowNum,
assignmentToShiftXlsHelper.getNumberOfDaysBetweenGivenDates(assignmentToShiftReport));
rowNum++;
}
}
}
| private void fillColumnWithStaffForWorkOnLine(final HSSFSheet sheet, int rowNum, final Entity assignmentToShiftReport,
final List<DateTime> days, final List<Entity> productionLines, final Entity dictionaryItem) {
if ((assignmentToShiftReport != null) && (days != null) && (productionLines != null)) {
for (Entity productionLine : productionLines) {
HSSFRow row = sheet.createRow(rowNum);
String productionLineValue = null;
if (productionLine.getStringField(PLACE) == null) {
productionLineValue = productionLine.getStringField(NUMBER);
} else {
productionLineValue = productionLine.getStringField(NUMBER) + "-"
+ productionLine.getStringField(ProductionLineFields.PLACE);
}
row.createCell(0).setCellValue(productionLineValue);
if (assignmentToShiftXlsHelper.getProductionLinesWithStaff(productionLine).isEmpty()) {
assignmentToShiftXlsStyleHelper.addMarginsAndStylesForSeries(sheet, rowNum,
assignmentToShiftXlsHelper.getNumberOfDaysBetweenGivenDates(assignmentToShiftReport));
rowNum++;
continue;
}
int columnNumber = 1;
int maxLength = 0;
for (DateTime day : days) {
Entity assignmentToShift = assignmentToShiftXlsHelper.getAssignmentToShift(
assignmentToShiftReport.getBelongsToField(SHIFT), day.toDate());
if (assignmentToShift == null) {
columnNumber += 3;
continue;
}
List<Entity> staffs = assignmentToShiftXlsHelper.getStaffsList(assignmentToShift,
dictionaryItem.getStringField(NAME), productionLine);
if (staffs.isEmpty()) {
columnNumber += 3;
continue;
}
String staffsValue = assignmentToShiftXlsHelper.getListOfWorkers(staffs);
row.createCell(columnNumber).setCellValue(staffsValue);
if (maxLength < staffsValue.length()) {
maxLength = staffsValue.length();
}
row.setHeightInPoints(assignmentToShiftXlsStyleHelper.getHeightForRow(maxLength, 22, 14));
columnNumber += 3;
}
assignmentToShiftXlsStyleHelper.addMarginsAndStylesForSeries(sheet, rowNum,
assignmentToShiftXlsHelper.getNumberOfDaysBetweenGivenDates(assignmentToShiftReport));
rowNum++;
}
}
}
|
diff --git a/org.emftext.sdk/src/org/emftext/sdk/codegen/generators/ManifestGenerator.java b/org.emftext.sdk/src/org/emftext/sdk/codegen/generators/ManifestGenerator.java
index 9ac1260c6..458c0e51a 100644
--- a/org.emftext.sdk/src/org/emftext/sdk/codegen/generators/ManifestGenerator.java
+++ b/org.emftext.sdk/src/org/emftext/sdk/codegen/generators/ManifestGenerator.java
@@ -1,123 +1,123 @@
/*******************************************************************************
* Copyright (c) 2006-2009
* Software Technology Group, Dresden University of Technology
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option) any
* later version. This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* See the GNU Lesser General Public License for more details. You should have
* received a copy of the GNU Lesser General Public License along with this
* program; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA
*
* Contributors:
* Software Technology Group - TU Dresden, Germany
* - initial API and implementation
******************************************************************************/
package org.emftext.sdk.codegen.generators;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.codegen.ecore.genmodel.GenModel;
import org.emftext.sdk.codegen.GenerationContext;
import org.emftext.sdk.codegen.GenerationProblem;
import org.emftext.sdk.codegen.IGenerator;
import org.emftext.sdk.codegen.composites.ManifestComposite;
import org.emftext.sdk.codegen.composites.StringComposite;
import org.emftext.sdk.concretesyntax.ConcreteSyntax;
import org.emftext.sdk.concretesyntax.Import;
/**
* A generator that creates the manifest file for the resource
* plug-in.
*/
public class ManifestGenerator implements IGenerator {
private final GenerationContext context;
private final boolean generateTestAction;
public ManifestGenerator(GenerationContext context, boolean generateTestAction) {
this.context = context;
this.generateTestAction = generateTestAction;
}
public boolean generate(PrintWriter out) {
out.write(getManifestContent());
out.flush();
return true;
}
/**
* Generates the contents of the MANIFEST.MF file for the plug-in.
*
* @param cSyntax
* Concrete syntax model.
* @param packageName
* Name of the Java package.
* @param resourcePackage
*
* @return generated content
*/
private String getManifestContent() {
StringComposite sc = new ManifestComposite();
ConcreteSyntax concreteSyntax = context.getConcreteSyntax();
String projectName = context.getPluginName();
sc.add("Manifest-Version: 1.0");
sc.add("Bundle-ManifestVersion: 2");
sc.add("Bundle-Name: EMFText Parser Plugin: " + concreteSyntax.getName());
sc.add("Bundle-SymbolicName: " + projectName + ";singleton:=true");
sc.add("Bundle-Version: 1.0.0");
- sc.add("Bundle-Vendor: Software Engineering Group - TU Dresden Germany");
+ sc.add("Bundle-Vendor: Software Technology Group - TU Dresden Germany");
sc.add("Require-Bundle: org.eclipse.core.runtime,");
sc.add(" org.eclipse.emf.ecore,");
List<String> importedPlugins = new ArrayList<String>();
String modelPluginID = concreteSyntax.getPackage().getGenModel().getModelPluginID();
importedPlugins.add(modelPluginID);
sc.add(" " + modelPluginID + ",");
if (generateTestAction) {
sc.add(" org.emftext.sdk.ui,");
}
for (Import aImport : concreteSyntax.getImports()) {
GenModel genModel = aImport.getPackage().getGenModel();
String pluginID = genModel.getModelPluginID();
if (!importedPlugins.contains(pluginID)) {
sc.add(" " + pluginID + ",");
sc.add(" " + context.getPluginName(aImport.getConcreteSyntax()) + ",");
importedPlugins.add(pluginID);
}
}
sc.add(" org.eclipse.jface,");
sc.add(" org.eclipse.ui,");
sc.add(" org.emftext.runtime,");
sc.add(" org.emftext.runtime.ui");
sc.add("Bundle-ActivationPolicy: lazy");
sc.add("Bundle-RequiredExecutionEnvironment: J2SE-1.5");
// export the generated packages
if (context.getResolverClasses().size() > 0) {
sc.add("Export-Package: " + projectName + ",");
sc.add(" " + context.getResolverPackageName());
} else {
sc.add("Export-Package: " + projectName);
}
return sc.toString();
}
public Collection<GenerationProblem> getCollectedErrors() {
return Collections.emptyList();
}
public Collection<GenerationProblem> getCollectedProblems() {
return Collections.emptyList();
}
}
| true | true | private String getManifestContent() {
StringComposite sc = new ManifestComposite();
ConcreteSyntax concreteSyntax = context.getConcreteSyntax();
String projectName = context.getPluginName();
sc.add("Manifest-Version: 1.0");
sc.add("Bundle-ManifestVersion: 2");
sc.add("Bundle-Name: EMFText Parser Plugin: " + concreteSyntax.getName());
sc.add("Bundle-SymbolicName: " + projectName + ";singleton:=true");
sc.add("Bundle-Version: 1.0.0");
sc.add("Bundle-Vendor: Software Engineering Group - TU Dresden Germany");
sc.add("Require-Bundle: org.eclipse.core.runtime,");
sc.add(" org.eclipse.emf.ecore,");
List<String> importedPlugins = new ArrayList<String>();
String modelPluginID = concreteSyntax.getPackage().getGenModel().getModelPluginID();
importedPlugins.add(modelPluginID);
sc.add(" " + modelPluginID + ",");
if (generateTestAction) {
sc.add(" org.emftext.sdk.ui,");
}
for (Import aImport : concreteSyntax.getImports()) {
GenModel genModel = aImport.getPackage().getGenModel();
String pluginID = genModel.getModelPluginID();
if (!importedPlugins.contains(pluginID)) {
sc.add(" " + pluginID + ",");
sc.add(" " + context.getPluginName(aImport.getConcreteSyntax()) + ",");
importedPlugins.add(pluginID);
}
}
sc.add(" org.eclipse.jface,");
sc.add(" org.eclipse.ui,");
sc.add(" org.emftext.runtime,");
sc.add(" org.emftext.runtime.ui");
sc.add("Bundle-ActivationPolicy: lazy");
sc.add("Bundle-RequiredExecutionEnvironment: J2SE-1.5");
// export the generated packages
if (context.getResolverClasses().size() > 0) {
sc.add("Export-Package: " + projectName + ",");
sc.add(" " + context.getResolverPackageName());
} else {
sc.add("Export-Package: " + projectName);
}
return sc.toString();
}
| private String getManifestContent() {
StringComposite sc = new ManifestComposite();
ConcreteSyntax concreteSyntax = context.getConcreteSyntax();
String projectName = context.getPluginName();
sc.add("Manifest-Version: 1.0");
sc.add("Bundle-ManifestVersion: 2");
sc.add("Bundle-Name: EMFText Parser Plugin: " + concreteSyntax.getName());
sc.add("Bundle-SymbolicName: " + projectName + ";singleton:=true");
sc.add("Bundle-Version: 1.0.0");
sc.add("Bundle-Vendor: Software Technology Group - TU Dresden Germany");
sc.add("Require-Bundle: org.eclipse.core.runtime,");
sc.add(" org.eclipse.emf.ecore,");
List<String> importedPlugins = new ArrayList<String>();
String modelPluginID = concreteSyntax.getPackage().getGenModel().getModelPluginID();
importedPlugins.add(modelPluginID);
sc.add(" " + modelPluginID + ",");
if (generateTestAction) {
sc.add(" org.emftext.sdk.ui,");
}
for (Import aImport : concreteSyntax.getImports()) {
GenModel genModel = aImport.getPackage().getGenModel();
String pluginID = genModel.getModelPluginID();
if (!importedPlugins.contains(pluginID)) {
sc.add(" " + pluginID + ",");
sc.add(" " + context.getPluginName(aImport.getConcreteSyntax()) + ",");
importedPlugins.add(pluginID);
}
}
sc.add(" org.eclipse.jface,");
sc.add(" org.eclipse.ui,");
sc.add(" org.emftext.runtime,");
sc.add(" org.emftext.runtime.ui");
sc.add("Bundle-ActivationPolicy: lazy");
sc.add("Bundle-RequiredExecutionEnvironment: J2SE-1.5");
// export the generated packages
if (context.getResolverClasses().size() > 0) {
sc.add("Export-Package: " + projectName + ",");
sc.add(" " + context.getResolverPackageName());
} else {
sc.add("Export-Package: " + projectName);
}
return sc.toString();
}
|
diff --git a/org.eclipse.scout.rt.ui.swt/src/org/eclipse/scout/rt/ui/swt/AbstractSwtEnvironment.java b/org.eclipse.scout.rt.ui.swt/src/org/eclipse/scout/rt/ui/swt/AbstractSwtEnvironment.java
index d3c5bb9318..34bd742201 100644
--- a/org.eclipse.scout.rt.ui.swt/src/org/eclipse/scout/rt/ui/swt/AbstractSwtEnvironment.java
+++ b/org.eclipse.scout.rt.ui.swt/src/org/eclipse/scout/rt/ui/swt/AbstractSwtEnvironment.java
@@ -1,1661 +1,1661 @@
/*******************************************************************************
* Copyright (c) 2010 BSI Business Systems Integration AG.
* 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:
* BSI Business Systems Integration AG - initial API and implementation
******************************************************************************/
package org.eclipse.scout.rt.ui.swt;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.scout.commons.CompareUtility;
import org.eclipse.scout.commons.EventListenerList;
import org.eclipse.scout.commons.HTMLUtility;
import org.eclipse.scout.commons.HTMLUtility.DefaultFont;
import org.eclipse.scout.commons.StringUtility;
import org.eclipse.scout.commons.beans.AbstractPropertyObserver;
import org.eclipse.scout.commons.exception.IProcessingStatus;
import org.eclipse.scout.commons.exception.ProcessingException;
import org.eclipse.scout.commons.holders.Holder;
import org.eclipse.scout.commons.holders.IHolder;
import org.eclipse.scout.commons.job.JobEx;
import org.eclipse.scout.commons.logger.IScoutLogger;
import org.eclipse.scout.commons.logger.ScoutLogManager;
import org.eclipse.scout.rt.client.ClientAsyncJob;
import org.eclipse.scout.rt.client.ClientSyncJob;
import org.eclipse.scout.rt.client.IClientSession;
import org.eclipse.scout.rt.client.busy.IBusyManagerService;
import org.eclipse.scout.rt.client.services.common.exceptionhandler.ErrorHandler;
import org.eclipse.scout.rt.client.services.common.session.IClientSessionRegistryService;
import org.eclipse.scout.rt.client.ui.action.keystroke.IKeyStroke;
import org.eclipse.scout.rt.client.ui.basic.filechooser.IFileChooser;
import org.eclipse.scout.rt.client.ui.desktop.DesktopEvent;
import org.eclipse.scout.rt.client.ui.desktop.DesktopListener;
import org.eclipse.scout.rt.client.ui.desktop.IDesktop;
import org.eclipse.scout.rt.client.ui.form.FormEvent;
import org.eclipse.scout.rt.client.ui.form.IForm;
import org.eclipse.scout.rt.client.ui.form.fields.IFormField;
import org.eclipse.scout.rt.client.ui.form.fields.htmlfield.IHtmlField;
import org.eclipse.scout.rt.client.ui.messagebox.IMessageBox;
import org.eclipse.scout.rt.client.ui.wizard.IWizard;
import org.eclipse.scout.rt.shared.data.basic.FontSpec;
import org.eclipse.scout.rt.shared.ui.UiDeviceType;
import org.eclipse.scout.rt.shared.ui.UiLayer;
import org.eclipse.scout.rt.shared.ui.UserAgent;
import org.eclipse.scout.rt.ui.swt.basic.WidgetPrinter;
import org.eclipse.scout.rt.ui.swt.busy.SwtBusyHandler;
import org.eclipse.scout.rt.ui.swt.concurrency.SwtScoutSynchronizer;
import org.eclipse.scout.rt.ui.swt.form.ISwtScoutForm;
import org.eclipse.scout.rt.ui.swt.form.SwtScoutForm;
import org.eclipse.scout.rt.ui.swt.form.fields.ISwtScoutFormField;
import org.eclipse.scout.rt.ui.swt.keystroke.ISwtKeyStroke;
import org.eclipse.scout.rt.ui.swt.keystroke.ISwtKeyStrokeFilter;
import org.eclipse.scout.rt.ui.swt.keystroke.KeyStrokeManager;
import org.eclipse.scout.rt.ui.swt.util.ColorFactory;
import org.eclipse.scout.rt.ui.swt.util.FontRegistry;
import org.eclipse.scout.rt.ui.swt.util.ScoutFormToolkit;
import org.eclipse.scout.rt.ui.swt.util.SwtIconLocator;
import org.eclipse.scout.rt.ui.swt.util.SwtUtility;
import org.eclipse.scout.rt.ui.swt.window.ISwtScoutPart;
import org.eclipse.scout.rt.ui.swt.window.SwtScoutPartEvent;
import org.eclipse.scout.rt.ui.swt.window.SwtScoutPartListener;
import org.eclipse.scout.rt.ui.swt.window.desktop.editor.AbstractScoutEditorPart;
import org.eclipse.scout.rt.ui.swt.window.desktop.editor.ScoutFormEditorInput;
import org.eclipse.scout.rt.ui.swt.window.desktop.tray.ISwtScoutTray;
import org.eclipse.scout.rt.ui.swt.window.desktop.tray.SwtScoutTray;
import org.eclipse.scout.rt.ui.swt.window.desktop.view.AbstractScoutView;
import org.eclipse.scout.rt.ui.swt.window.dialog.SwtScoutDialog;
import org.eclipse.scout.rt.ui.swt.window.filechooser.SwtScoutFileChooser;
import org.eclipse.scout.rt.ui.swt.window.messagebox.SwtScoutMessageBoxDialog;
import org.eclipse.scout.rt.ui.swt.window.popup.SwtScoutPopup;
import org.eclipse.scout.service.SERVICES;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolTip;
import org.eclipse.swt.widgets.TrayItem;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IPerspectiveDescriptor;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchListener;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PerspectiveAdapter;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.views.IViewDescriptor;
import org.osgi.framework.Bundle;
import org.osgi.framework.Version;
/**
* <h3>SwtEnvironment</h3> ...
*
* @since 1.0.0 06.03.2008
*/
public abstract class AbstractSwtEnvironment extends AbstractPropertyObserver implements ISwtEnvironment {
private static IScoutLogger LOG = ScoutLogManager.getLogger(AbstractSwtEnvironment.class);
private final Bundle m_applicationBundle;
private final String m_perspectiveId;
private final Class<? extends IClientSession> m_clientSessionClass;
private IClientSession m_clientSession;
private int m_status;
private SwtScoutSynchronizer m_synchronizer;
private final Object m_immediateSwtJobsLock = new Object();
private final List<Runnable> m_immediateSwtJobs = new ArrayList<Runnable>();
private Clipboard m_clipboard;
private ColorFactory m_colorFactory;
private FontRegistry m_fontRegistry;
private SwtIconLocator m_iconLocator;
private ISwtScoutTray m_trayComposite;
private List<ISwtKeyStroke> m_desktopKeyStrokes;
private KeyStrokeManager m_keyStrokeManager;
private Control m_popupOwner;
private Rectangle m_popupOwnerBounds;
private ScoutFormToolkit m_formToolkit;
private FormFieldFactory m_formFieldFactory;
private PropertyChangeSupport m_propertySupport;
private boolean m_startDesktopCalled;
private boolean m_activateDesktopCalled;
private EventListenerList m_environmentListeners;
private HashMap<String, String> m_scoutPartIdToUiPartId;
private HashMap<IForm, ISwtScoutPart> m_openForms;
private P_ScoutDesktopListener m_scoutDesktopListener;
private P_ScoutDesktopPropertyListener m_desktopPropertyListener;
private P_PerspectiveListener m_perspectiveListener;
public AbstractSwtEnvironment(Bundle applicationBundle, String perspectiveId, Class<? extends IClientSession> clientSessionClass) {
m_applicationBundle = applicationBundle;
m_perspectiveId = perspectiveId;
m_clientSessionClass = clientSessionClass;
//
m_environmentListeners = new EventListenerList();
m_scoutPartIdToUiPartId = new HashMap<String, String>();
m_openForms = new HashMap<IForm, ISwtScoutPart>();
m_propertySupport = new PropertyChangeSupport(this);
m_status = SwtEnvironmentEvent.INACTIVE;
m_desktopKeyStrokes = new ArrayList<ISwtKeyStroke>();
m_startDesktopCalled = false;
}
public Bundle getApplicationBundle() {
return m_applicationBundle;
}
private void stopScout() throws CoreException {
try {
if (m_desktopKeyStrokes != null) {
for (ISwtKeyStroke swtKeyStroke : m_desktopKeyStrokes) {
removeGlobalKeyStroke(swtKeyStroke);
}
m_desktopKeyStrokes.clear();
}
if (m_iconLocator != null) {
m_iconLocator.dispose();
m_iconLocator = null;
}
if (m_colorFactory != null) {
m_colorFactory.dispose();
m_colorFactory = null;
}
m_keyStrokeManager = null;
if (m_fontRegistry != null) {
m_fontRegistry.dispose();
m_fontRegistry = null;
}
if (m_formToolkit != null) {
m_formToolkit.dispose();
m_formToolkit = null;
}
detachScoutListeners();
detachSWTListeners();
if (m_synchronizer != null) {
m_synchronizer = null;
}
m_clientSession = null;
m_status = SwtEnvironmentEvent.STOPPED;
fireEnvironmentChanged(new SwtEnvironmentEvent(this, SwtEnvironmentEvent.STOPPED));
setStartDesktopCalled(false);
}
finally {
if (m_status != SwtEnvironmentEvent.STOPPED) {
m_status = SwtEnvironmentEvent.STARTED;
fireEnvironmentChanged(new SwtEnvironmentEvent(this, SwtEnvironmentEvent.STARTED));
}
}
}
/**
* @param scoutPartLocation
* the location id defined in {@link IForm} or additional.
* @param uiPartId
* the id of the {@link IViewPart} registered in the plugin.xml as a
* view extension.
*/
@Override
public void registerPart(String scoutPartLocation, String uiPartId) {
m_scoutPartIdToUiPartId.put(scoutPartLocation, uiPartId);
}
@Override
public void unregisterPart(String scoutPartLocation) {
m_scoutPartIdToUiPartId.remove(scoutPartLocation);
}
@Override
public final String[] getAllPartIds() {
HashSet<String> partIds = new HashSet<String>(m_scoutPartIdToUiPartId.values());
return partIds.toArray(new String[partIds.size()]);
}
@Override
public final String getSwtPartIdForScoutPartId(String scoutPartLocation) {
return m_scoutPartIdToUiPartId.get(scoutPartLocation);
}
@Override
public final String getScoutPartIdForSwtPartId(String partId) {
if (partId == null) {
return "";
}
for (Entry<String, String> entry : m_scoutPartIdToUiPartId.entrySet()) {
if (entry.getValue().equals(partId)) {
return entry.getKey();
}
}
return "";
}
public IViewPart findViewPart(String viewId) {
if (viewId != null) {
IViewDescriptor viewRef = PlatformUI.getWorkbench().getViewRegistry().find(viewId);
if (viewRef != null && !viewRef.getAllowMultiple()) {
return PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(viewId);
}
}
return null;
}
@Override
public AbstractScoutView getViewPart(String viewId) {
if (viewId != null) {
String secondaryId = null;
IViewDescriptor viewRef = PlatformUI.getWorkbench().getViewRegistry().find(viewId);
if (viewRef.getAllowMultiple()) {
secondaryId = "" + System.currentTimeMillis();
}
try {
IViewPart view = null;
if (secondaryId == null) {
view = findViewPart(viewId);
if (view == null) {
view = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(viewId);
}
}
else {
view = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(viewId, secondaryId, IWorkbenchPage.VIEW_ACTIVATE);
}
if (!(view instanceof AbstractScoutView)) {
LOG.warn("views used in scout's enviromnent must be extensions of AbstractScoutView");
}
else {
return (AbstractScoutView) view;
}
}
catch (PartInitException e) {
LOG.error("could not inizialize view", e);
}
}
return null;
}
@Override
public AbstractScoutEditorPart getEditorPart(IEditorInput editorInput, String editorId) {
if (editorInput != null && editorId != null) {
try {
IEditorPart editor = null;
editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findEditor(editorInput);
if (editor == null) {
editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().openEditor(editorInput, editorId);
}
if (!(editor instanceof AbstractScoutEditorPart)) {
LOG.warn("editors used in scout's enviromnent must be extensions of AbstractScoutEditorPart");
}
else {
return (AbstractScoutEditorPart) editor;
}
}
catch (PartInitException e) {
LOG.error("could not inizialize editor", e);
}
}
return null;
}
@Override
public boolean isInitialized() {
return m_status == SwtEnvironmentEvent.STARTED;
}
@Override
public final void ensureInitialized() {
if (m_status == SwtEnvironmentEvent.INACTIVE
|| m_status == SwtEnvironmentEvent.STOPPED) {
try {
init();
}
catch (CoreException e) {
LOG.error("could not initialize Environment", e);
}
}
}
private synchronized void init() throws CoreException {
if (m_status == SwtEnvironmentEvent.STARTING
|| m_status == SwtEnvironmentEvent.STARTED
|| m_status == SwtEnvironmentEvent.STOPPING) {
return;
}
m_status = SwtEnvironmentEvent.INACTIVE;
// must be called in display thread
if (Thread.currentThread() != getDisplay().getThread()) {
throw new IllegalStateException("must be called in display thread");
}
// workbench must exist
if (PlatformUI.getWorkbench().getActiveWorkbenchWindow() == null) {
throw new IllegalStateException("workbench must be active");
}
try {
m_status = SwtEnvironmentEvent.STARTING;
m_clipboard = new Clipboard(getDisplay());
fireEnvironmentChanged(new SwtEnvironmentEvent(this, m_status));
IClientSession tempClientSession = createAndStartClientSession();
if (!tempClientSession.isActive()) {
showClientSessionLoadError(tempClientSession.getLoadError());
LOG.error("ClientSession is not active, there must be a problem with loading or starting");
m_status = SwtEnvironmentEvent.INACTIVE;
return;
}
else {
m_clientSession = tempClientSession;
}
SwtUtility.setNlsTextsOnDisplay(getDisplay(), m_clientSession.getTexts());
if (m_synchronizer == null) {
m_synchronizer = new SwtScoutSynchronizer(this);
}
//
m_iconLocator = createIconLocator();
m_colorFactory = new ColorFactory(getDisplay());
m_keyStrokeManager = new KeyStrokeManager(this);
m_fontRegistry = new FontRegistry(getDisplay());
attachScoutListeners();
attachSWTListeners();
IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
if (activePage != null) {
IPerspectiveDescriptor activePerspective = activePage.getPerspective();
if (activePerspective != null) {
String perspectiveId = activePerspective.getId();
if (handlePerspectiveOpened(perspectiveId)) {
handlePerspectiveActivated(perspectiveId);
}
}
}
// desktop keystokes
for (IKeyStroke scoutKeyStroke : getClientSession().getDesktop().getKeyStrokes()) {
ISwtKeyStroke[] swtStrokes = SwtUtility.getKeyStrokes(scoutKeyStroke, this);
for (ISwtKeyStroke swtStroke : swtStrokes) {
m_desktopKeyStrokes.add(swtStroke);
addGlobalKeyStroke(swtStroke);
}
}
// environment shutdownhook
PlatformUI.getWorkbench().addWorkbenchListener(new IWorkbenchListener() {
@Override
public boolean preShutdown(IWorkbench workbench, boolean forced) {
return true;
}
@Override
public void postShutdown(IWorkbench workbench) {
Runnable t = new Runnable() {
@Override
public void run() {
getScoutDesktop().getUIFacade().fireGuiDetached();
getScoutDesktop().getUIFacade().fireDesktopClosingFromUI();
}
};
JobEx job = invokeScoutLater(t, 0);
if (job != null) {
try {
job.join(600000);
}
catch (InterruptedException e) {
//nop
}
}
}
});
// notify ui available
Runnable job = new Runnable() {
@Override
public void run() {
getScoutDesktop().getUIFacade().fireDesktopOpenedFromUI();
}
};
invokeScoutLater(job, 0);
m_status = SwtEnvironmentEvent.STARTED;
fireEnvironmentChanged(new SwtEnvironmentEvent(this, m_status));
attachBusyHandler();
}
finally {
if (m_status == SwtEnvironmentEvent.STARTING) {
m_status = SwtEnvironmentEvent.STOPPED;
fireEnvironmentChanged(new SwtEnvironmentEvent(this, m_status));
}
}
}
/**
* Creates and starts a new client session. <br/>
* This is done in a separate thread to make sure that no client code is
* running in the ui thread.
*/
private IClientSession createAndStartClientSession() {
final IHolder<IClientSession> holder = new Holder<IClientSession>(IClientSession.class);
JobEx job = new JobEx("Creating and starting client session") {
@Override
protected IStatus run(IProgressMonitor monitor) {
holder.setValue(SERVICES.getService(IClientSessionRegistryService.class).newClientSession(m_clientSessionClass, initUserAgent()));
return Status.OK_STATUS;
}
};
job.schedule();
try {
job.join();
}
catch (InterruptedException e) {
LOG.error("Client session startup interrupted.", e);
}
return holder.getValue();
}
protected UserAgent initUserAgent() {
return UserAgent.create(UiLayer.SWT, UiDeviceType.DESKTOP);
}
protected SwtBusyHandler attachBusyHandler() {
IBusyManagerService service = SERVICES.getService(IBusyManagerService.class);
if (service == null) {
return null;
}
SwtBusyHandler handler = createBusyHandler();
getDisplay().addListener(SWT.Dispose, new P_BusyHandlerDisposeListener(service));
service.register(getClientSession(), handler);
return handler;
}
private class P_BusyHandlerDisposeListener implements Listener {
private IBusyManagerService m_busyManagerService;
public P_BusyHandlerDisposeListener(IBusyManagerService busyManagerService) {
m_busyManagerService = busyManagerService;
}
@Override
public void handleEvent(Event event) {
m_busyManagerService.unregister(getClientSession());
}
}
protected SwtBusyHandler createBusyHandler() {
return new SwtBusyHandler(getClientSession(), this);
}
protected void showClientSessionLoadError(Throwable error) {
ErrorHandler handler = new ErrorHandler(error);
MessageBox mbox = new MessageBox(getParentShellIgnoringPopups(SWT.SYSTEM_MODAL | SWT.APPLICATION_MODAL | SWT.MODELESS), SWT.OK);
mbox.setText("" + handler.getTitle());
mbox.setMessage(StringUtility.join("\n\n", handler.getText(), handler.getDetail()));
mbox.open();
}
// hide ScoutViews with no Forms
private class P_HideScoutViews implements Runnable {
@Override
public void run() {
IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
if (activePage != null) {
for (IViewReference viewReference : activePage.getViewReferences()) {
IViewPart view = viewReference.getView(false);
if (view != null && view instanceof AbstractScoutView) {
if (((AbstractScoutView) view).getForm() == null) {
activePage.hideView(viewReference);
}
}
else if (m_scoutPartIdToUiPartId.containsValue(viewReference.getId())) {
activePage.hideView(viewReference);
}
}
}
}
}
private void fireGuiAttachedFromUI() {
if (getScoutDesktop() != null) {
getScoutDesktop().getUIFacade().fireGuiAttached();
}
getDisplay().asyncExec(new P_HideScoutViews());
}
private void fireGuiDetachedFromUI() {
if (getScoutDesktop() != null) {
getScoutDesktop().getUIFacade().fireGuiDetached();
}
}
private void fireDesktopActivatedFromUI() {
if (getScoutDesktop() != null) {
getScoutDesktop().ensureViewStackVisible();
}
}
@Override
public String styleHtmlText(ISwtScoutFormField<?> uiComposite, String rawHtml) {
String cleanHtml = rawHtml;
if (cleanHtml == null) {
cleanHtml = "";
}
if (uiComposite.getScoutObject() instanceof IHtmlField) {
IHtmlField htmlField = (IHtmlField) uiComposite.getScoutObject();
if (htmlField.isHtmlEditor()) {
/*
* In HTML editor mode, the HTML is not styled except that an empty HTML skeleton is created in case the given HTML is empty.
* In general no extra styling should be applied because the HTML installed in the editor should be the very same as
* provided. Otherwise, if the user did some modifications in the HTML source and reloads the HTML in the editor anew,
* unwanted auto-corrections would be applied.
*/
if (!StringUtility.hasText(cleanHtml)) {
cleanHtml = "<html><head></head><body></body></html>";
}
}
else {
/*
* Because @{link SwtScoutHtmlField} is file based, it is crucial to set the content-type and charset appropriately.
* Also, the CSS needs not to be cleaned as the native browser is used.
*/
cleanHtml = HTMLUtility.cleanupHtml(cleanHtml, true, false, createDefaultFontSettings(uiComposite.getSwtField()));
}
}
return cleanHtml;
}
/**
* Get SWT specific default font settings
*/
protected DefaultFont createDefaultFontSettings(Control control) {
DefaultFont defaultFont = new DefaultFont();
defaultFont.setSize(8);
defaultFont.setSizeUnit("pt");
defaultFont.setForegroundColor(0x000000);
defaultFont.setFamilies(new String[]{"sans-serif"});
if (control != null) {
FontData[] fontData = control.getFont().getFontData();
if (fontData != null && fontData.length > 0) {
int height = fontData[0].getHeight();
if (height > 0) {
defaultFont.setSize(height);
}
String fontFamily = fontData[0].getName();
if (StringUtility.hasText(fontFamily)) {
defaultFont.setFamilies(new String[]{fontFamily, "sans-serif"});
}
}
Color color = control.getForeground();
if (color != null) {
defaultFont.setForegroundColor(color.getRed() * 0x10000 + color.getGreen() * 0x100 + color.getBlue());
}
}
return defaultFont;
}
@SuppressWarnings("deprecation")
@Override
public boolean isBusy() {
//replaced by SwtBusyHandler
return false;
}
@SuppressWarnings("deprecation")
@Override
public void setBusyFromSwt(boolean b) {
//replaced by SwtBusyHandler
}
@Override
public void setClipboardText(String text) {
m_clipboard.setContents(new Object[]{text}, new Transfer[]{TextTransfer.getInstance()});
}
@Override
public void addPropertyChangeListener(PropertyChangeListener listener) {
m_propertySupport.addPropertyChangeListener(listener);
}
@Override
public void removePropertyChangeListener(PropertyChangeListener listener) {
m_propertySupport.removePropertyChangeListener(listener);
}
@Override
public final void addEnvironmentListener(ISwtEnvironmentListener listener) {
m_environmentListeners.add(ISwtEnvironmentListener.class, listener);
}
@Override
public final void removeEnvironmentListener(ISwtEnvironmentListener listener) {
m_environmentListeners.remove(ISwtEnvironmentListener.class, listener);
}
private void fireEnvironmentChanged(SwtEnvironmentEvent event) {
for (ISwtEnvironmentListener l : m_environmentListeners.getListeners(ISwtEnvironmentListener.class)) {
l.environmentChanged(event);
}
}
// icon handling
@Override
public Image getIcon(String name) {
return m_iconLocator.getIcon(name);
}
@Override
public ImageDescriptor getImageDescriptor(String iconId) {
return m_iconLocator.getImageDescriptor(iconId);
}
// key stoke handling
@Override
public void addGlobalKeyStroke(ISwtKeyStroke stroke) {
m_keyStrokeManager.addGlobalKeyStroke(stroke);
}
@Override
public boolean removeGlobalKeyStroke(ISwtKeyStroke stroke) {
return m_keyStrokeManager.removeGlobalKeyStroke(stroke);
}
@Override
public void addKeyStroke(Widget widget, ISwtKeyStroke stoke) {
m_keyStrokeManager.addKeyStroke(widget, stoke);
}
@Override
public boolean removeKeyStroke(Widget widget, ISwtKeyStroke stoke) {
return m_keyStrokeManager.removeKeyStroke(widget, stoke);
}
@Override
public void addKeyStrokeFilter(Widget c, ISwtKeyStrokeFilter filter) {
m_keyStrokeManager.addKeyStrokeFilter(c, filter);
}
@Override
public boolean removeKeyStrokeFilter(Widget c, ISwtKeyStrokeFilter filter) {
return m_keyStrokeManager.removeKeyStrokeFilter(c, filter);
}
// color handling
@Override
public Color getColor(String scoutColor) {
return m_colorFactory.getColor(scoutColor);
}
@Override
public Color getColor(RGB rgb) {
return m_colorFactory.getColor(rgb);
}
// font handling
@Override
public Font getFont(FontSpec scoutFont, Font templateFont) {
return m_fontRegistry.getFont(scoutFont, templateFont);
}
@Override
public Font getFont(Font templateFont, String newName, Integer newStyle, Integer newSize) {
return m_fontRegistry.getFont(templateFont, newName, newStyle, newSize);
}
// form toolkit handling
@Override
public ScoutFormToolkit getFormToolkit() {
if (m_formToolkit == null) {
m_formToolkit = createScoutFormToolkit(getDisplay());
}
return m_formToolkit;
}
// desktop handling
@Override
public final IDesktop getScoutDesktop() {
if (m_clientSession != null) {
return m_clientSession.getDesktop();
}
else {
return null;
}
}
protected void attachScoutListeners() {
if (m_scoutDesktopListener == null) {
m_scoutDesktopListener = new P_ScoutDesktopListener();
getScoutDesktop().addDesktopListener(m_scoutDesktopListener);
}
if (m_desktopPropertyListener == null) {
m_desktopPropertyListener = new P_ScoutDesktopPropertyListener();
getScoutDesktop().addPropertyChangeListener(m_desktopPropertyListener);
}
}
protected void detachScoutListeners() {
IDesktop desktop = getScoutDesktop();
if (desktop != null) {
if (m_scoutDesktopListener != null) {
desktop.removeDesktopListener(m_scoutDesktopListener);
m_scoutDesktopListener = null;
}
if (m_desktopPropertyListener != null) {
desktop.removePropertyChangeListener(m_desktopPropertyListener);
m_desktopPropertyListener = null;
}
}
}
protected void attachSWTListeners() {
if (m_perspectiveListener == null) {
m_perspectiveListener = new P_PerspectiveListener();
PlatformUI.getWorkbench().getActiveWorkbenchWindow().addPerspectiveListener(m_perspectiveListener);
}
}
protected void detachSWTListeners() {
if (m_perspectiveListener != null && PlatformUI.getWorkbench().getActiveWorkbenchWindow() != null) {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().removePerspectiveListener(m_perspectiveListener);
m_perspectiveListener = null;
}
}
protected void applyScoutState() {
IDesktop desktop = getScoutDesktop();
// load state of internal frames and dialogs
for (IForm form : desktop.getViewStack()) {
if (form.isAutoAddRemoveOnDesktop()) {
showStandaloneForm(form);
}
}
//tray icon
if (desktop.isTrayVisible()) {
m_trayComposite = createTray(desktop);
}
// dialogs
IForm[] dialogs = desktop.getDialogStack();
for (IForm dialog : dialogs) {
// showDialogFromScout(dialogs[i]);
showStandaloneForm(dialog);
}
IMessageBox[] messageBoxes = desktop.getMessageBoxStack();
for (IMessageBox messageBoxe : messageBoxes) {
showMessageBoxFromScout(messageBoxe);
}
}
public IFormField findFocusOwnerField() {
Control comp = getDisplay().getFocusControl();
while (comp != null) {
Object o = comp.getData(ISwtScoutFormField.CLIENT_PROPERTY_SCOUT_OBJECT);
if (o instanceof IFormField) {
return (IFormField) o;
}
// next
comp = comp.getParent();
}
return null;
}
@Override
public void showFileChooserFromScout(IFileChooser fileChooser) {
SwtScoutFileChooser sfc = new SwtScoutFileChooser(getParentShellIgnoringPopups(SWT.SYSTEM_MODAL | SWT.APPLICATION_MODAL | SWT.MODELESS), fileChooser, this);
sfc.showFileChooser();
}
@Override
public void showMessageBoxFromScout(IMessageBox messageBox) {
SwtScoutMessageBoxDialog box = new SwtScoutMessageBoxDialog(getParentShellIgnoringPopups(SWT.SYSTEM_MODAL | SWT.APPLICATION_MODAL | SWT.MODELESS), messageBox, this);
box.open();
}
@Override
public void ensureStandaloneFormVisible(IForm form) {
ISwtScoutPart part = m_openForms.get(form);
if (part != null) {
part.activate();
}
}
private Map<String, List<IForm>> openLater = new HashMap<String, List<IForm>>();
@Override
public void showStandaloneForm(final IForm form) {
if (form == null) {
return;
}
ISwtScoutPart part = m_openForms.get(form);
if (part != null) {
return;
}
switch (form.getDisplayHint()) {
case IForm.DISPLAY_HINT_DIALOG: {
int dialogStyle = SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | (form.isModal() ? SWT.APPLICATION_MODAL : SWT.MODELESS | SWT.MIN);
Shell parentShell;
if (form.isModal()) {
parentShell = getParentShellIgnoringPopups(SWT.SYSTEM_MODAL | SWT.APPLICATION_MODAL | SWT.MODELESS);
}
else {
- parentShell = getParentShellIgnoringPopups(0);
+ parentShell = getParentShellIgnoringPopups(SWT.MODELESS);
}
SwtScoutDialog dialog = createSwtScoutDialog(parentShell, dialogStyle);
try {
m_openForms.put(form, dialog);
dialog.showForm(form);
part = dialog;
}
catch (ProcessingException e) {
LOG.error(e.getMessage(), e);
}
break;
}
case IForm.DISPLAY_HINT_POPUP_DIALOG: {
int dialogStyle = SWT.RESIZE | (form.isModal() ? SWT.APPLICATION_MODAL : SWT.MODELESS);
Shell parentShell;
if (form.isModal()) {
parentShell = getParentShellIgnoringPopups(SWT.SYSTEM_MODAL | SWT.APPLICATION_MODAL | SWT.MODELESS);
}
else {
parentShell = getParentShellIgnoringPopups(0);
}
SwtScoutDialog popupDialog = createSwtScoutPopupDialog(parentShell, dialogStyle);
if (popupDialog == null) {
LOG.error("showing popup for " + form + ", but there is neither a focus owner nor the property 'ISwtEnvironment.getPopupOwner()'");
return;
}
try {
m_openForms.put(form, popupDialog);
popupDialog.showForm(form);
part = popupDialog;
}
catch (Throwable t) {
LOG.error(t.getMessage(), t);
}
break;
}
case IForm.DISPLAY_HINT_VIEW: {
String scoutViewId = form.getDisplayViewId();
if (scoutViewId == null) {
LOG.error("The property displayViewId must not be null if the property displayHint is set to IForm.DISPLAY_HINT_VIEW.");
return;
}
String uiViewId = getSwtPartIdForScoutPartId(scoutViewId);
if (uiViewId == null) {
LOG.warn("no view defined for scoutViewId: " + form.getDisplayViewId());
return;
}
IViewPart existingView = findViewPart(uiViewId);
String formPerspectiveId = form.getPerspectiveId();
if (formPerspectiveId == null) {
formPerspectiveId = "";
}
IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
//open form if formPerspectiveId is empty
// OR if currentPerspectiveId equals perspecitveId set on form
if (StringUtility.hasText(formPerspectiveId)
&& existingView == null
&& activePage != null
&& CompareUtility.notEquals(activePage.getPerspective().getId(), formPerspectiveId)) {
synchronized (openLater) {
if (!openLater.containsKey(formPerspectiveId) || !openLater.get(formPerspectiveId).contains(form)) {
if (openLater.get(formPerspectiveId) == null) {
openLater.put(formPerspectiveId, new ArrayList<IForm>());
}
openLater.get(formPerspectiveId).add(form);
}
}
return;
}
//Check if an editor or a view should be opened.
//An editor is opened if the scoutViewId starts with IForm.EDITOR_ID or IWizard.EDITOR_ID.
//Compared to equals the check with startsWith enables the possibility to link different editors with the forms.
if (scoutViewId.startsWith(IForm.EDITOR_ID) || scoutViewId.startsWith(IWizard.EDITOR_ID)) {
if (activePage != null) {
ScoutFormEditorInput editorInput = new ScoutFormEditorInput(form, this);
part = getEditorPart(editorInput, uiViewId);
m_openForms.put(form, part);
}
}
else {
AbstractScoutView viewPart = getViewPart(uiViewId);
try {
viewPart.showForm(form);
part = viewPart;
m_openForms.put(form, viewPart);
}
catch (ProcessingException e) {
LOG.error(e.getMessage(), e);
}
}
break;
}
case IForm.DISPLAY_HINT_POPUP_WINDOW: {
SwtScoutPopup popupWindow = createSwtScoutPopupWindow();
if (popupWindow == null) {
LOG.error("showing popup for " + form + ", but there is neither a focus owner nor the property 'ISwtEnvironment.getPopupOwner()'");
return;
}
try {
m_openForms.put(form, popupWindow);
popupWindow.showForm(form);
part = popupWindow;
}
catch (Throwable e1) {
LOG.error("Failed opening popup for " + form, e1);
try {
popupWindow.showForm(form);
}
catch (Throwable t) {
LOG.error(t.getMessage(), t);
}
}
break;
}
}
}
protected SwtScoutDialog createSwtScoutDialog(Shell shell, int dialogStyle) {
return new SwtScoutDialog(shell, this, dialogStyle);
}
protected SwtScoutDialog createSwtScoutPopupDialog(Shell shell, int dialogStyle) {
Control owner = getPopupOwner();
if (owner == null) {
owner = getDisplay().getFocusControl();
}
if (owner == null) {
return null;
}
Rectangle ownerBounds = getPopupOwnerBounds();
if (ownerBounds == null) {
ownerBounds = owner.getBounds();
Point pDisp = owner.toDisplay(0, 0);
ownerBounds.x = pDisp.x;
ownerBounds.y = pDisp.y;
}
SwtScoutDialog dialog = new SwtScoutDialog(shell, this, dialogStyle);
dialog.setInitialLocation(new Point(ownerBounds.x, ownerBounds.y + ownerBounds.height));
return dialog;
}
protected SwtScoutPopup createSwtScoutPopupWindow() {
Control owner = getPopupOwner();
if (owner == null) {
owner = getDisplay().getFocusControl();
}
if (owner == null) {
return null;
}
Rectangle ownerBounds = getPopupOwnerBounds();
if (ownerBounds == null) {
ownerBounds = owner.getBounds();
Point pDisp = owner.toDisplay(0, 0);
ownerBounds.x = pDisp.x;
ownerBounds.y = pDisp.y;
}
final SwtScoutPopup popup = new SwtScoutPopup(this, owner, ownerBounds, SWT.RESIZE);
popup.setMaxHeightHint(280);
popup.addSwtScoutPartListener(new SwtScoutPartListener() {
@Override
public void partChanged(SwtScoutPartEvent e) {
switch (e.getType()) {
case SwtScoutPartEvent.TYPE_CLOSED: {
popup.closePart();
break;
}
case SwtScoutPartEvent.TYPE_CLOSING: {
popup.closePart();
break;
}
}
}
});
//close popup when PARENT shell is activated or closed
owner.getShell().addShellListener(new ShellAdapter() {
@Override
public void shellClosed(ShellEvent e) {
//auto-detach
((Shell) e.getSource()).removeShellListener(this);
popup.closePart();
}
@Override
public void shellActivated(ShellEvent e) {
//auto-detach
((Shell) e.getSource()).removeShellListener(this);
popup.closePart();
}
});
return popup;
}
@Override
public Control getPopupOwner() {
return m_popupOwner;
}
@Override
public Rectangle getPopupOwnerBounds() {
return m_popupOwnerBounds != null ? new Rectangle(m_popupOwnerBounds.x, m_popupOwnerBounds.y, m_popupOwnerBounds.width, m_popupOwnerBounds.height) : null;
}
@Override
public void setPopupOwner(Control owner, Rectangle ownerBounds) {
m_popupOwner = owner;
m_popupOwnerBounds = ownerBounds;
}
@Override
public void hideStandaloneForm(IForm form) {
if (form == null) {
return;
}
ISwtScoutPart part = m_openForms.remove(form);
if (part != null && part.getForm().equals(form)) {
try {
part.closePart();
}
catch (ProcessingException e) {
LOG.warn("could not close part.", e);
}
}
}
protected void handleDesktopPropertyChanged(String propertyName, Object oldVal, Object newValue) {
if (IDesktop.PROP_STATUS.equals(propertyName)) {
setStatusFromScout();
}
}
protected void setStatusFromScout() {
if (getScoutDesktop() != null) {
IProcessingStatus newValue = getScoutDesktop().getStatus();
//when a tray item is available, use it, otherwise set status on views/dialogs
TrayItem trayItem = null;
if (getTrayComposite() != null) {
trayItem = getTrayComposite().getSwtTrayItem();
}
if (trayItem != null) {
String s = newValue != null ? newValue.getMessage() : null;
if (newValue != null && s != null) {
int iconId;
switch (newValue.getSeverity()) {
case IProcessingStatus.WARNING: {
iconId = SWT.ICON_WARNING;
break;
}
case IProcessingStatus.FATAL:
case IProcessingStatus.ERROR: {
iconId = SWT.ICON_ERROR;
break;
}
case IProcessingStatus.CANCEL: {
//Necessary for backward compatibility to Eclipse 3.4 needed for Lotus Notes 8.5.2
Version frameworkVersion = new Version(Activator.getDefault().getBundle().getBundleContext().getProperty("osgi.framework.version"));
if (frameworkVersion.getMajor() == 3
&& frameworkVersion.getMinor() <= 4) {
iconId = SWT.ICON_INFORMATION;
}
else {
iconId = 1 << 8;//SWT.ICON_CANCEL
}
break;
}
default: {
iconId = SWT.ICON_INFORMATION;
break;
}
}
ToolTip tip = new ToolTip(getParentShellIgnoringPopups(SWT.MODELESS), SWT.BALLOON | iconId);
tip.setMessage(s);
trayItem.setToolTip(tip);
tip.setVisible(true);
}
else {
ToolTip tip = new ToolTip(getParentShellIgnoringPopups(SWT.MODELESS), SWT.NONE);
trayItem.setToolTip(tip);
tip.setVisible(true);
}
}
else {
String message = null;
if (newValue != null) {
message = newValue.getMessage();
}
setStatusLineMessage(null, message);
}
}
}
@Override
public void setStatusLineMessage(Image image, String message) {
for (ISwtScoutPart part : m_openForms.values()) {
part.setStatusLineMessage(image, message);
}
}
@Override
public Collection<ISwtScoutPart> getOpenFormParts() {
return new ArrayList<ISwtScoutPart>(m_openForms.values());
}
private class P_ScoutDesktopPropertyListener implements PropertyChangeListener {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
Runnable job = new Runnable() {
@Override
public void run() {
handleDesktopPropertyChanged(evt.getPropertyName(), evt.getOldValue(), evt.getNewValue());
}
};
invokeSwtLater(job);
}
} // end class P_ScoutDesktopPropertyListener
private class P_ScoutDesktopListener implements DesktopListener {
@Override
public void desktopChanged(final DesktopEvent e) {
switch (e.getType()) {
case DesktopEvent.TYPE_FORM_ADDED: {
Runnable t = new Runnable() {
@Override
public void run() {
showStandaloneForm(e.getForm());
}
};
invokeSwtLater(t);
break;
}
case DesktopEvent.TYPE_FORM_REMOVED: {
Runnable t = new Runnable() {
@Override
public void run() {
hideStandaloneForm(e.getForm());
}
};
invokeSwtLater(t);
break;
}
case DesktopEvent.TYPE_FORM_ENSURE_VISIBLE: {
Runnable t = new Runnable() {
@Override
public void run() {
ensureStandaloneFormVisible(e.getForm());
}
};
invokeSwtLater(t);
break;
}
case DesktopEvent.TYPE_MESSAGE_BOX_ADDED: {
Runnable t = new Runnable() {
@Override
public void run() {
showMessageBoxFromScout(e.getMessageBox());
}
};
invokeSwtLater(t);
break;
}
case DesktopEvent.TYPE_FILE_CHOOSER_ADDED: {
Runnable t = new Runnable() {
@Override
public void run() {
showFileChooserFromScout(e.getFileChooser());
}
};
invokeSwtLater(t);
break;
}
case DesktopEvent.TYPE_DESKTOP_CLOSED: {
Runnable t = new Runnable() {
@Override
public void run() {
try {
stopScout();
}
catch (CoreException ex) {
LOG.error("desktop closed", ex);
}
}
};
invokeSwtLater(t);
break;
}
case DesktopEvent.TYPE_PRINT: {
Runnable t = new Runnable() {
@Override
public void run() {
handleScoutPrintInSwt(e);
}
};
invokeSwtLater(t);
break;
}
case DesktopEvent.TYPE_FIND_FOCUS_OWNER: {
final Object lock = new Object();
Runnable t = new Runnable() {
@Override
public void run() {
try {
IFormField f = findFocusOwnerField();
if (f != null) {
e.setFocusedField(f);
}
}
finally {
synchronized (lock) {
lock.notifyAll();
}
}
}
};
synchronized (lock) {
invokeSwtLater(t);
try {
lock.wait(2000L);
}
catch (InterruptedException e1) {
//nop
}
}
break;
}
}
}
}
@Override
public void postImmediateSwtJob(Runnable r) {
synchronized (m_immediateSwtJobsLock) {
m_immediateSwtJobs.add(r);
}
}
@Override
public void dispatchImmediateSwtJobs() {
List<Runnable> list;
synchronized (m_immediateSwtJobsLock) {
list = new ArrayList<Runnable>(m_immediateSwtJobs);
m_immediateSwtJobs.clear();
}
for (Runnable r : list) {
try {
r.run();
}
catch (Throwable t) {
LOG.warn("running " + r, t);
}
}
}
@Override
public JobEx invokeScoutLater(Runnable job, long cancelTimeout) {
synchronized (m_immediateSwtJobsLock) {
m_immediateSwtJobs.clear();
}
if (m_synchronizer != null) {
return m_synchronizer.invokeScoutLater(job, cancelTimeout);
}
else {
LOG.warn("synchronizer is null; clientSession did not start");
return null;
}
}
@Override
public void invokeSwtLater(Runnable job) {
if (m_synchronizer != null) {
m_synchronizer.invokeSwtLater(job);
}
else {
LOG.warn("synchronizer is null; clientSession did not start");
}
}
@Override
public Display getDisplay() {
if (PlatformUI.isWorkbenchRunning()) {
return PlatformUI.getWorkbench().getDisplay();
}
else {
LOG.warn("Workbench is not yet started, accessing the display is unusual: " + new Exception().getStackTrace()[1]);
Display display = Display.getCurrent();
if (display == null) {
display = Display.getDefault();
}
return display;
}
}
/**
* {@inheritDoc}
*/
@Override
public Shell getParentShellIgnoringPopups(int modalities) {
return SwtUtility.getParentShellIgnoringPopups(getDisplay(), modalities);
}
@Override
public IClientSession getClientSession() {
return m_clientSession;
}
// GUI FACTORY
protected SwtIconLocator createIconLocator() {
return new SwtIconLocator(getClientSession().getIconLocator());
}
protected ScoutFormToolkit createScoutFormToolkit(Display display) {
return new ScoutFormToolkit(new FormToolkit(display) {
@Override
public Form createForm(Composite parent) {
Form f = super.createForm(parent);
decorateFormHeading(f);
return f;
}
});
}
@Override
public ISwtScoutTray getTrayComposite() {
return m_trayComposite;
}
protected ISwtScoutTray createTray(IDesktop desktop) {
SwtScoutTray ui = new SwtScoutTray();
ui.createField(null, desktop, this);
return ui;
}
@Override
public ISwtScoutForm createForm(Composite parent, IForm scoutForm) {
SwtScoutForm uiForm = new SwtScoutForm();
uiForm.createField(parent, scoutForm, this);
return uiForm;
}
@Override
public ISwtScoutFormField createFormField(Composite parent, IFormField model) {
if (m_formFieldFactory == null) {
m_formFieldFactory = new FormFieldFactory(m_applicationBundle);
}
ISwtScoutFormField<IFormField> uiField = m_formFieldFactory.createFormField(parent, model, this);
return uiField;
}
@Override
public void checkThread() {
if (!(getDisplay().getThread() == Thread.currentThread())) {
throw new IllegalStateException("Must be called in swt thread");
}
}
private class P_PerspectiveListener extends PerspectiveAdapter {
@Override
public void perspectiveActivated(IWorkbenchPage page, IPerspectiveDescriptor perspective) {
String perspectiveId = perspective.getId();
if (handlePerspectiveOpened(perspectiveId)) {
handlePerspectiveActivated(perspectiveId);
}
}
@Override
public void perspectiveDeactivated(IWorkbenchPage page, IPerspectiveDescriptor perspective) {
// global keystrokes are bound to a perspective so it is necessary to disable the global keystrokes
if (m_perspectiveId.equals(perspective.getId())) {
m_keyStrokeManager.setGlobalKeyStrokesActivated(false);
}
}
@Override
public void perspectiveClosed(IWorkbenchPage page, IPerspectiveDescriptor perspective) {
handlePerspectiveClosed(perspective.getId());
}
@Override
public void perspectiveChanged(IWorkbenchPage page, IPerspectiveDescriptor perspective, String changeId) {
String perspectiveId = perspective.getId();
//If perspective is resetted make sure that scout views are open
if (IWorkbenchPage.CHANGE_RESET.equals(changeId)) {
handlePerspectiveClosed(perspectiveId);
}
else if (IWorkbenchPage.CHANGE_RESET_COMPLETE.equals(changeId)) {
if (handlePerspectiveOpened(perspectiveId)) {
handlePerspectiveActivated(perspectiveId);
}
}
}
}
private synchronized boolean handlePerspectiveOpened(String perspectiveId) {
if (m_perspectiveId.equals(perspectiveId)) {
//make sure that the desktop is only started once
if (!isStartDesktopCalled()) {
final P_PerspecitveOpenedJob j = new P_PerspecitveOpenedJob(getDesktopOpenedTaskText(), getClientSession());
j.schedule();
setStartDesktopCalled(true);
}
m_keyStrokeManager.setGlobalKeyStrokesActivated(true);
return isStartDesktopCalled();
}
return false;
}
private synchronized boolean handlePerspectiveActivated(String perspectiveId) {
if (openLater.containsKey(perspectiveId)) {
List<IForm> list;
synchronized (openLater) {
list = openLater.remove(perspectiveId);
}
for (IForm form : list) {
showStandaloneForm(form);
}
setActivateDesktopCalled(CompareUtility.notEquals(m_perspectiveId, perspectiveId));
}
if (m_perspectiveId.equals(perspectiveId) && isStartDesktopCalled()) {
//make sure that the desktop is only started once
if (!isActivateDesktopCalled()) {
final P_PerspectiveActivatedJob j = new P_PerspectiveActivatedJob(getDesktopOpenedTaskText(), getClientSession());
j.schedule();
setActivateDesktopCalled(true);
}
m_keyStrokeManager.setGlobalKeyStrokesActivated(true);
return isActivateDesktopCalled();
}
return false;
}
private synchronized boolean handlePerspectiveClosed(String perspectiveId) {
boolean called = false;
// make sure that the desktop is only started once
if (m_perspectiveId.equals(perspectiveId)) {
final P_PerspectiveClosedJob j = new P_PerspectiveClosedJob(getDesktopClosedTaskText(), getClientSession());
j.schedule();
called = true;
setStartDesktopCalled(false);
setActivateDesktopCalled(false);
//global keystrokes are bound to a perspective so it is necessary to disable the global keystrokes
m_keyStrokeManager.setGlobalKeyStrokesActivated(false);
}
return called;
}
protected void handleScoutPrintInSwt(DesktopEvent e) {
final WidgetPrinter wp = new WidgetPrinter(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());//getParentShellIgnoringPopups(SWT.SYSTEM_MODAL | SWT.APPLICATION_MODAL | SWT.MODELESS));
try {
wp.print(e.getPrintDevice(), e.getPrintParameters());
}
catch (Throwable ex) {
LOG.error(null, ex);
}
finally {
Runnable r = new Runnable() {
@Override
public void run() {
getScoutDesktop().getUIFacade().fireDesktopPrintedFromUI(wp.getOutputFile());
}
};
invokeScoutLater(r, 0);
}
}
protected String getDesktopOpenedTaskText() {
return SwtUtility.getNlsText(Display.getCurrent(), "ScoutStarting");
}
protected String getDesktopClosedTaskText() {
return SwtUtility.getNlsText(Display.getCurrent(), "ScoutStoping");
}
private final class P_PerspecitveOpenedJob extends ClientAsyncJob {
public P_PerspecitveOpenedJob(String name, IClientSession session) {
super(name, session);
}
@Override
protected void runVoid(IProgressMonitor monitor) throws Throwable {
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
applyScoutState();
}
});
ClientSyncJob clienSyncJob = new ClientSyncJob(getDesktopOpenedTaskText(), super.getClientSession()) {
@Override
protected void runVoid(IProgressMonitor syncMonitor) throws Throwable {
fireGuiAttachedFromUI();
}
};
clienSyncJob.schedule();
}
}
private final class P_PerspectiveActivatedJob extends ClientAsyncJob {
public P_PerspectiveActivatedJob(String name, IClientSession session) {
super(name, session);
}
@Override
protected void runVoid(IProgressMonitor monitor) throws Throwable {
ClientSyncJob clienSyncJob = new ClientSyncJob(getDesktopOpenedTaskText(), super.getClientSession()) {
@Override
protected void runVoid(IProgressMonitor syncMonitor) throws Throwable {
fireDesktopActivatedFromUI();
}
};
clienSyncJob.schedule();
}
}
private final class P_PerspectiveClosedJob extends ClientAsyncJob {
public P_PerspectiveClosedJob(String name, IClientSession session) {
super(name, session);
}
@Override
protected void runVoid(IProgressMonitor monitor) throws Throwable {
ClientSyncJob clienSyncJob = new ClientSyncJob(getDesktopOpenedTaskText(), super.getClientSession()) {
@Override
protected void runVoid(IProgressMonitor syncMonitor) throws Throwable {
fireGuiDetachedFromUI();
}
};
clienSyncJob.schedule();
}
}
private boolean isStartDesktopCalled() {
return m_startDesktopCalled;
}
private void setStartDesktopCalled(boolean startDesktopCalled) {
m_startDesktopCalled = startDesktopCalled;
}
private boolean isActivateDesktopCalled() {
return m_activateDesktopCalled;
}
private void setActivateDesktopCalled(boolean activateDesktopCalled) {
m_activateDesktopCalled = activateDesktopCalled;
}
@Override
public String getPerspectiveId() {
return m_perspectiveId;
}
@SuppressWarnings("deprecation")
@Override
public FormEvent[] fetchPendingPrintEvents(IForm form) {
return new FormEvent[0];
}
}
| true | true | public void showStandaloneForm(final IForm form) {
if (form == null) {
return;
}
ISwtScoutPart part = m_openForms.get(form);
if (part != null) {
return;
}
switch (form.getDisplayHint()) {
case IForm.DISPLAY_HINT_DIALOG: {
int dialogStyle = SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | (form.isModal() ? SWT.APPLICATION_MODAL : SWT.MODELESS | SWT.MIN);
Shell parentShell;
if (form.isModal()) {
parentShell = getParentShellIgnoringPopups(SWT.SYSTEM_MODAL | SWT.APPLICATION_MODAL | SWT.MODELESS);
}
else {
parentShell = getParentShellIgnoringPopups(0);
}
SwtScoutDialog dialog = createSwtScoutDialog(parentShell, dialogStyle);
try {
m_openForms.put(form, dialog);
dialog.showForm(form);
part = dialog;
}
catch (ProcessingException e) {
LOG.error(e.getMessage(), e);
}
break;
}
case IForm.DISPLAY_HINT_POPUP_DIALOG: {
int dialogStyle = SWT.RESIZE | (form.isModal() ? SWT.APPLICATION_MODAL : SWT.MODELESS);
Shell parentShell;
if (form.isModal()) {
parentShell = getParentShellIgnoringPopups(SWT.SYSTEM_MODAL | SWT.APPLICATION_MODAL | SWT.MODELESS);
}
else {
parentShell = getParentShellIgnoringPopups(0);
}
SwtScoutDialog popupDialog = createSwtScoutPopupDialog(parentShell, dialogStyle);
if (popupDialog == null) {
LOG.error("showing popup for " + form + ", but there is neither a focus owner nor the property 'ISwtEnvironment.getPopupOwner()'");
return;
}
try {
m_openForms.put(form, popupDialog);
popupDialog.showForm(form);
part = popupDialog;
}
catch (Throwable t) {
LOG.error(t.getMessage(), t);
}
break;
}
case IForm.DISPLAY_HINT_VIEW: {
String scoutViewId = form.getDisplayViewId();
if (scoutViewId == null) {
LOG.error("The property displayViewId must not be null if the property displayHint is set to IForm.DISPLAY_HINT_VIEW.");
return;
}
String uiViewId = getSwtPartIdForScoutPartId(scoutViewId);
if (uiViewId == null) {
LOG.warn("no view defined for scoutViewId: " + form.getDisplayViewId());
return;
}
IViewPart existingView = findViewPart(uiViewId);
String formPerspectiveId = form.getPerspectiveId();
if (formPerspectiveId == null) {
formPerspectiveId = "";
}
IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
//open form if formPerspectiveId is empty
// OR if currentPerspectiveId equals perspecitveId set on form
if (StringUtility.hasText(formPerspectiveId)
&& existingView == null
&& activePage != null
&& CompareUtility.notEquals(activePage.getPerspective().getId(), formPerspectiveId)) {
synchronized (openLater) {
if (!openLater.containsKey(formPerspectiveId) || !openLater.get(formPerspectiveId).contains(form)) {
if (openLater.get(formPerspectiveId) == null) {
openLater.put(formPerspectiveId, new ArrayList<IForm>());
}
openLater.get(formPerspectiveId).add(form);
}
}
return;
}
//Check if an editor or a view should be opened.
//An editor is opened if the scoutViewId starts with IForm.EDITOR_ID or IWizard.EDITOR_ID.
//Compared to equals the check with startsWith enables the possibility to link different editors with the forms.
if (scoutViewId.startsWith(IForm.EDITOR_ID) || scoutViewId.startsWith(IWizard.EDITOR_ID)) {
if (activePage != null) {
ScoutFormEditorInput editorInput = new ScoutFormEditorInput(form, this);
part = getEditorPart(editorInput, uiViewId);
m_openForms.put(form, part);
}
}
else {
AbstractScoutView viewPart = getViewPart(uiViewId);
try {
viewPart.showForm(form);
part = viewPart;
m_openForms.put(form, viewPart);
}
catch (ProcessingException e) {
LOG.error(e.getMessage(), e);
}
}
break;
}
case IForm.DISPLAY_HINT_POPUP_WINDOW: {
SwtScoutPopup popupWindow = createSwtScoutPopupWindow();
if (popupWindow == null) {
LOG.error("showing popup for " + form + ", but there is neither a focus owner nor the property 'ISwtEnvironment.getPopupOwner()'");
return;
}
try {
m_openForms.put(form, popupWindow);
popupWindow.showForm(form);
part = popupWindow;
}
catch (Throwable e1) {
LOG.error("Failed opening popup for " + form, e1);
try {
popupWindow.showForm(form);
}
catch (Throwable t) {
LOG.error(t.getMessage(), t);
}
}
break;
}
}
}
| public void showStandaloneForm(final IForm form) {
if (form == null) {
return;
}
ISwtScoutPart part = m_openForms.get(form);
if (part != null) {
return;
}
switch (form.getDisplayHint()) {
case IForm.DISPLAY_HINT_DIALOG: {
int dialogStyle = SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | (form.isModal() ? SWT.APPLICATION_MODAL : SWT.MODELESS | SWT.MIN);
Shell parentShell;
if (form.isModal()) {
parentShell = getParentShellIgnoringPopups(SWT.SYSTEM_MODAL | SWT.APPLICATION_MODAL | SWT.MODELESS);
}
else {
parentShell = getParentShellIgnoringPopups(SWT.MODELESS);
}
SwtScoutDialog dialog = createSwtScoutDialog(parentShell, dialogStyle);
try {
m_openForms.put(form, dialog);
dialog.showForm(form);
part = dialog;
}
catch (ProcessingException e) {
LOG.error(e.getMessage(), e);
}
break;
}
case IForm.DISPLAY_HINT_POPUP_DIALOG: {
int dialogStyle = SWT.RESIZE | (form.isModal() ? SWT.APPLICATION_MODAL : SWT.MODELESS);
Shell parentShell;
if (form.isModal()) {
parentShell = getParentShellIgnoringPopups(SWT.SYSTEM_MODAL | SWT.APPLICATION_MODAL | SWT.MODELESS);
}
else {
parentShell = getParentShellIgnoringPopups(0);
}
SwtScoutDialog popupDialog = createSwtScoutPopupDialog(parentShell, dialogStyle);
if (popupDialog == null) {
LOG.error("showing popup for " + form + ", but there is neither a focus owner nor the property 'ISwtEnvironment.getPopupOwner()'");
return;
}
try {
m_openForms.put(form, popupDialog);
popupDialog.showForm(form);
part = popupDialog;
}
catch (Throwable t) {
LOG.error(t.getMessage(), t);
}
break;
}
case IForm.DISPLAY_HINT_VIEW: {
String scoutViewId = form.getDisplayViewId();
if (scoutViewId == null) {
LOG.error("The property displayViewId must not be null if the property displayHint is set to IForm.DISPLAY_HINT_VIEW.");
return;
}
String uiViewId = getSwtPartIdForScoutPartId(scoutViewId);
if (uiViewId == null) {
LOG.warn("no view defined for scoutViewId: " + form.getDisplayViewId());
return;
}
IViewPart existingView = findViewPart(uiViewId);
String formPerspectiveId = form.getPerspectiveId();
if (formPerspectiveId == null) {
formPerspectiveId = "";
}
IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
//open form if formPerspectiveId is empty
// OR if currentPerspectiveId equals perspecitveId set on form
if (StringUtility.hasText(formPerspectiveId)
&& existingView == null
&& activePage != null
&& CompareUtility.notEquals(activePage.getPerspective().getId(), formPerspectiveId)) {
synchronized (openLater) {
if (!openLater.containsKey(formPerspectiveId) || !openLater.get(formPerspectiveId).contains(form)) {
if (openLater.get(formPerspectiveId) == null) {
openLater.put(formPerspectiveId, new ArrayList<IForm>());
}
openLater.get(formPerspectiveId).add(form);
}
}
return;
}
//Check if an editor or a view should be opened.
//An editor is opened if the scoutViewId starts with IForm.EDITOR_ID or IWizard.EDITOR_ID.
//Compared to equals the check with startsWith enables the possibility to link different editors with the forms.
if (scoutViewId.startsWith(IForm.EDITOR_ID) || scoutViewId.startsWith(IWizard.EDITOR_ID)) {
if (activePage != null) {
ScoutFormEditorInput editorInput = new ScoutFormEditorInput(form, this);
part = getEditorPart(editorInput, uiViewId);
m_openForms.put(form, part);
}
}
else {
AbstractScoutView viewPart = getViewPart(uiViewId);
try {
viewPart.showForm(form);
part = viewPart;
m_openForms.put(form, viewPart);
}
catch (ProcessingException e) {
LOG.error(e.getMessage(), e);
}
}
break;
}
case IForm.DISPLAY_HINT_POPUP_WINDOW: {
SwtScoutPopup popupWindow = createSwtScoutPopupWindow();
if (popupWindow == null) {
LOG.error("showing popup for " + form + ", but there is neither a focus owner nor the property 'ISwtEnvironment.getPopupOwner()'");
return;
}
try {
m_openForms.put(form, popupWindow);
popupWindow.showForm(form);
part = popupWindow;
}
catch (Throwable e1) {
LOG.error("Failed opening popup for " + form, e1);
try {
popupWindow.showForm(form);
}
catch (Throwable t) {
LOG.error(t.getMessage(), t);
}
}
break;
}
}
}
|
diff --git a/src/com/secpro/platform/log/Activator.java b/src/com/secpro/platform/log/Activator.java
index 7418a56..622337d 100644
--- a/src/com/secpro/platform/log/Activator.java
+++ b/src/com/secpro/platform/log/Activator.java
@@ -1,84 +1,84 @@
package com.secpro.platform.log;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import com.secpro.platform.log.utils.PlatformLogger;
/**
* @author Martin Bai. Logging bundle just provide logging function for other
* bundle. May 31, 2012
*/
public class Activator implements BundleActivator {
private static PlatformLogger _logger = PlatformLogger.getLogger(Activator.class);
private static BundleContext context;
public final static String LOGGING_CONFIGURATION_PATH = "loggingConfigurationPath";
public final static String DEFAULT_LOGGING_CONFIGURATION_PATH = "configuration/logging.xml";
static BundleContext getContext() {
return context;
}
/*
* (non-Javadoc)
*
* @see
* org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext
* )
*/
public void start(BundleContext bundleContext) throws Exception {
Activator.context = bundleContext;
initConfigurationForLogging(getLoggingConfigurationPath());
_logger.info("Logging bundle is ready ^");
}
/*
* (non-Javadoc)
*
* @see
* org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext bundleContext) throws Exception {
Activator.context = null;
}
/**
* @param logConfigruationPath
* @throws Exception
* read and set the logging configuration from starting
* parameter
*/
private void initConfigurationForLogging(String logConfigruationPath) throws Exception {
if (logConfigruationPath == null || logConfigruationPath.trim().equals("")) {
- throw new Exception("invaild logging configuration path.");
+ throw new Exception("invalid logging configuration path.");
}
try {
LoggerContext logContext = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(logContext);
logContext.reset();
configurator.doConfigure(logConfigruationPath);
} catch (JoranException je) {
je.printStackTrace();
throw je;
}
}
/**
* Gets the file path.
*
* @return
*/
public String getLoggingConfigurationPath() {
String path = System.getProperty(LOGGING_CONFIGURATION_PATH);
if (path == null || path.trim().length() == 0) {
path = DEFAULT_LOGGING_CONFIGURATION_PATH;
}
return path;
}
}
| true | true | private void initConfigurationForLogging(String logConfigruationPath) throws Exception {
if (logConfigruationPath == null || logConfigruationPath.trim().equals("")) {
throw new Exception("invaild logging configuration path.");
}
try {
LoggerContext logContext = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(logContext);
logContext.reset();
configurator.doConfigure(logConfigruationPath);
} catch (JoranException je) {
je.printStackTrace();
throw je;
}
}
| private void initConfigurationForLogging(String logConfigruationPath) throws Exception {
if (logConfigruationPath == null || logConfigruationPath.trim().equals("")) {
throw new Exception("invalid logging configuration path.");
}
try {
LoggerContext logContext = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(logContext);
logContext.reset();
configurator.doConfigure(logConfigruationPath);
} catch (JoranException je) {
je.printStackTrace();
throw je;
}
}
|
diff --git a/lenskit-core/src/main/java/org/grouplens/lenskit/core/LenskitRecommenderEngineFactory.java b/lenskit-core/src/main/java/org/grouplens/lenskit/core/LenskitRecommenderEngineFactory.java
index 9583660c4..32cc8d83b 100644
--- a/lenskit-core/src/main/java/org/grouplens/lenskit/core/LenskitRecommenderEngineFactory.java
+++ b/lenskit-core/src/main/java/org/grouplens/lenskit/core/LenskitRecommenderEngineFactory.java
@@ -1,332 +1,332 @@
/*
* LensKit, an open source recommender systems toolkit.
* Copyright 2010-2012 Regents of the University of Minnesota and contributors
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.grouplens.lenskit.core;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import org.grouplens.grapht.*;
import org.grouplens.grapht.graph.Edge;
import org.grouplens.grapht.graph.Graph;
import org.grouplens.grapht.graph.Node;
import org.grouplens.grapht.solver.DefaultDesireBindingFunction;
import org.grouplens.grapht.solver.DependencySolver;
import org.grouplens.grapht.solver.SolverException;
import org.grouplens.grapht.spi.*;
import org.grouplens.lenskit.*;
import org.grouplens.lenskit.data.dao.DAOFactory;
import org.grouplens.lenskit.data.dao.DataAccessObject;
import javax.annotation.Nullable;
import java.lang.annotation.Annotation;
import java.util.*;
import static org.grouplens.grapht.BindingFunctionBuilder.RuleSet;
/**
* {@link RecommenderEngineFactory} that builds a LenskitRecommenderEngine.
* <p>
* This class is final for copying safety. This decision can be revisited.
* </p>
*
* @author Michael Ekstrand <[email protected]>
* @compat Public
*/
public final class LenskitRecommenderEngineFactory implements RecommenderEngineFactory, Context {
private static final Class<?>[] INITIAL_ROOTS = {
RatingPredictor.class,
ItemScorer.class,
GlobalItemScorer.class,
ItemRecommender.class,
GlobalItemRecommender.class
};
private final BindingFunctionBuilder config;
private final DAOFactory factory;
private final Set<Class<?>> roots;
public LenskitRecommenderEngineFactory() {
this((DAOFactory) null);
}
public LenskitRecommenderEngineFactory(@Nullable DAOFactory factory) {
this.factory = factory;
config = new BindingFunctionBuilder();
roots = new HashSet<Class<?>>();
Collections.addAll(roots, INITIAL_ROOTS);
}
private LenskitRecommenderEngineFactory(LenskitRecommenderEngineFactory engineFactory) {
factory = engineFactory.factory;
config = engineFactory.config.clone();
roots = new HashSet<Class<?>>(engineFactory.roots);
}
/**
* Add the specified component type as a root component. This forces it (and its
* dependencies) to be resolved, and makes it available from the resulting
* recommenders.
*
* @param componentType The type of component to add as a root (typically an interface).
* @see LenskitRecommender#get(Class)
*/
public void addRoot(Class<?> componentType) {
roots.add(componentType);
}
@Override
public <T> Binding<T> bind(Class<T> type) {
return config.getRootContext().bind(type);
}
@Override
public void bind(Class<? extends Annotation> param, Object value) {
config.getRootContext().bind(param, value);
}
public <T> Binding<T> bind(Class<? extends Annotation> qualifier, Class<T> type) {
return bind(type).withQualifier(qualifier);
}
@Override
public Context in(Class<?> type) {
return config.getRootContext().in(type);
}
@Override
public Context in(Class<? extends Annotation> qualifier, Class<?> type) {
return config.getRootContext().in(qualifier, type);
}
@Override
public Context in(Annotation qualifier, Class<?> type) {
return config.getRootContext().in(qualifier, type);
}
public Context in(String name, Class<?> type) {
// REVIEW: Do we want to keep this method? Do we want to add it to Grapht?
return config.getRootContext().in(Names.named(name), type);
}
/**
* Groovy-compatible alias for {@link #in(Class)}.
*/
@SuppressWarnings("unused")
public Context within(Class<?> type) {
return in(type);
}
/**
* Groovy-compatible alias for {@link #in(Class, Class)}.
*/
public Context within(Class<? extends Annotation> qualifier, Class<?> type) {
return in(qualifier, type);
}
/**
* Groovy-compatible alias for {@link #in(String, Class)}.
*/
public Context within(String name, Class<?> type) {
return in(name, type);
}
@Override
public LenskitRecommenderEngineFactory clone() {
return new LenskitRecommenderEngineFactory(this);
}
@Override
public LenskitRecommenderEngine create() {
if (factory == null) {
throw new IllegalStateException("create() called with no DAOFactory");
}
DataAccessObject dao = factory.snapshot();
try {
return create(dao);
} finally {
dao.close();
}
}
private void resolve(Class<?> type, DependencySolver solver) {
try {
solver.resolve(config.getSPI().desire(null, type, true));
} catch (SolverException e) {
throw new InjectionException(type, null, e);
}
}
public LenskitRecommenderEngine create(DataAccessObject dao) {
BindingFunctionBuilder config = this.config.clone();
config.getRootContext().bind(DataAccessObject.class).to(dao);
DependencySolver solver = new DependencySolver(
Arrays.asList(config.build(RuleSet.EXPLICIT),
config.build(RuleSet.INTERMEDIATE_TYPES),
config.build(RuleSet.SUPER_TYPES),
new DefaultDesireBindingFunction(config.getSPI())),
100);
// Resolve all required types to complete a Recommender
for (Class<?> root : roots) {
resolve(root, solver);
}
// At this point the graph contains the dependency state to build a
// recommender with the current DAO. Any extra bind rules don't matter
// because they could not have created any Nodes.
Graph original = solver.getGraph();
- // Get the set of shareable instances.
+ // Get the set of shareable nodes
Set<Node> shared = getShareableNodes(original);
// Instantiate and replace shareable nodes
Graph modified = original.clone();
Set<Node> sharedInstances = instantiate(modified, shared);
// Remove transient edges and orphaned subgraphs
Set<Node> transientTargets = removeTransientEdges(modified, sharedInstances);
removeOrphanSubgraphs(modified, transientTargets);
// Find the DAO node
Node daoNode = GraphtUtils.findDAONode(modified);
Node daoPlaceholder = null;
if (daoNode != null) {
// replace it with a null satisfaction
CachedSatisfaction daoLbl = daoNode.getLabel();
assert daoLbl != null;
Class<?> type = daoLbl.getSatisfaction().getErasedType();
Satisfaction sat = config.getSPI().satisfyWithNull(type);
daoPlaceholder = new Node(sat, CachePolicy.MEMOIZE);
modified.replaceNode(daoNode, daoPlaceholder);
}
return new LenskitRecommenderEngine(factory, modified, daoPlaceholder,
config.getSPI());
}
/**
* Prune the graph, returning the set of nodes for shareable objects
* (objects that will be replaced with instance satisfactions in the
* final graph).
*
* @param graph The graph to analyze. The graph is not modified.
* @return The set of root nodes - nodes that need to be instantiated and
* removed. These nodes are in topologically sorted order.
*/
private LinkedHashSet<Node> getShareableNodes(Graph graph) {
LinkedHashSet<Node> shared = new LinkedHashSet<Node>();
List<Node> nodes = graph.sort(graph.getNode(null));
for (Node node : nodes) {
if (!GraphtUtils.isShareable(node)) {
continue;
}
// see if we depend on any non-shared nodes
// since nodes are sorted, all shared nodes will have been seen
Set<Edge> intransient = GraphtUtils.removeTransient(graph.getOutgoingEdges(node));
boolean isShared =
Iterables.all(Iterables.transform(intransient, GraphtUtils.edgeTail()),
Predicates.in(shared));
if (isShared) {
shared.add(node);
}
}
return shared;
}
/**
* Instantiate the shared objects in a graph. This instantiates all shared objects,
* and replaces their nodes with nodes wrapping instance satisfactions.
*
* @param graph The complete configuration graph. This graph will be modified.
* @param toReplace The shared nodes to replace.
* @return The new instance nodes, in iteration order from {@code toReplace}.
*/
private LinkedHashSet<Node> instantiate(Graph graph, Set<Node> toReplace) {
InjectSPI spi = config.getSPI();
StaticInjector injector = new StaticInjector(spi, graph);
LinkedHashSet<Node> replacements = new LinkedHashSet<Node>();
for (Node node : toReplace) {
Object obj = injector.instantiate(node);
CachedSatisfaction label = node.getLabel();
assert label != null;
Satisfaction instanceSat;
if (obj == null) {
instanceSat = spi.satisfyWithNull(label.getSatisfaction().getErasedType());
} else {
instanceSat = spi.satisfy(obj);
}
Node repl = new Node(instanceSat, label.getCachePolicy());
graph.replaceNode(node, repl);
}
return replacements;
}
/**
* Remove transient edges from a graph.
*
* @param graph The graph to remove transient edges from.
* @param nodes The nodes whose outgoing transient edges should be removed.
* @return The set of tail nodes of removed edges.
*/
private Set<Node> removeTransientEdges(Graph graph, Set<Node> nodes) {
Set<Node> targets = new HashSet<Node>();
Set<Node> seen = new HashSet<Node>();
Queue<Node> work = new LinkedList<Node>();
work.addAll(nodes);
seen.addAll(nodes);
while (!work.isEmpty()) {
Node node = work.remove();
for (Edge e : graph.getOutgoingEdges(node)) {
Node nbr = e.getTail();
// remove transient edges, traverse non-transient ones
Desire desire = e.getDesire();
assert desire != null;
if (GraphtUtils.desireIsTransient(desire)) {
graph.removeEdge(e);
targets.add(nbr);
} else if (!seen.contains(nbr)) {
seen.add(nbr);
work.add(nbr);
}
}
}
return targets;
}
private void removeOrphanSubgraphs(Graph graph, Collection<Node> candidates) {
Queue<Node> removeQueue = new LinkedList<Node>(candidates);
while (!removeQueue.isEmpty()) {
Node candidate = removeQueue.poll();
Set<Edge> incoming = graph.getIncomingEdges(candidate); // null if candidate got re-added
if (incoming != null && incoming.isEmpty()) {
// No other node depends on this node, so we can remove it,
// we must also flag its dependencies as removal candidates
for (Edge e : graph.getOutgoingEdges(candidate)) {
removeQueue.add(e.getTail());
}
graph.removeNode(candidate);
}
}
}
}
| true | true | public LenskitRecommenderEngine create(DataAccessObject dao) {
BindingFunctionBuilder config = this.config.clone();
config.getRootContext().bind(DataAccessObject.class).to(dao);
DependencySolver solver = new DependencySolver(
Arrays.asList(config.build(RuleSet.EXPLICIT),
config.build(RuleSet.INTERMEDIATE_TYPES),
config.build(RuleSet.SUPER_TYPES),
new DefaultDesireBindingFunction(config.getSPI())),
100);
// Resolve all required types to complete a Recommender
for (Class<?> root : roots) {
resolve(root, solver);
}
// At this point the graph contains the dependency state to build a
// recommender with the current DAO. Any extra bind rules don't matter
// because they could not have created any Nodes.
Graph original = solver.getGraph();
// Get the set of shareable instances.
Set<Node> shared = getShareableNodes(original);
// Instantiate and replace shareable nodes
Graph modified = original.clone();
Set<Node> sharedInstances = instantiate(modified, shared);
// Remove transient edges and orphaned subgraphs
Set<Node> transientTargets = removeTransientEdges(modified, sharedInstances);
removeOrphanSubgraphs(modified, transientTargets);
// Find the DAO node
Node daoNode = GraphtUtils.findDAONode(modified);
Node daoPlaceholder = null;
if (daoNode != null) {
// replace it with a null satisfaction
CachedSatisfaction daoLbl = daoNode.getLabel();
assert daoLbl != null;
Class<?> type = daoLbl.getSatisfaction().getErasedType();
Satisfaction sat = config.getSPI().satisfyWithNull(type);
daoPlaceholder = new Node(sat, CachePolicy.MEMOIZE);
modified.replaceNode(daoNode, daoPlaceholder);
}
return new LenskitRecommenderEngine(factory, modified, daoPlaceholder,
config.getSPI());
}
| public LenskitRecommenderEngine create(DataAccessObject dao) {
BindingFunctionBuilder config = this.config.clone();
config.getRootContext().bind(DataAccessObject.class).to(dao);
DependencySolver solver = new DependencySolver(
Arrays.asList(config.build(RuleSet.EXPLICIT),
config.build(RuleSet.INTERMEDIATE_TYPES),
config.build(RuleSet.SUPER_TYPES),
new DefaultDesireBindingFunction(config.getSPI())),
100);
// Resolve all required types to complete a Recommender
for (Class<?> root : roots) {
resolve(root, solver);
}
// At this point the graph contains the dependency state to build a
// recommender with the current DAO. Any extra bind rules don't matter
// because they could not have created any Nodes.
Graph original = solver.getGraph();
// Get the set of shareable nodes
Set<Node> shared = getShareableNodes(original);
// Instantiate and replace shareable nodes
Graph modified = original.clone();
Set<Node> sharedInstances = instantiate(modified, shared);
// Remove transient edges and orphaned subgraphs
Set<Node> transientTargets = removeTransientEdges(modified, sharedInstances);
removeOrphanSubgraphs(modified, transientTargets);
// Find the DAO node
Node daoNode = GraphtUtils.findDAONode(modified);
Node daoPlaceholder = null;
if (daoNode != null) {
// replace it with a null satisfaction
CachedSatisfaction daoLbl = daoNode.getLabel();
assert daoLbl != null;
Class<?> type = daoLbl.getSatisfaction().getErasedType();
Satisfaction sat = config.getSPI().satisfyWithNull(type);
daoPlaceholder = new Node(sat, CachePolicy.MEMOIZE);
modified.replaceNode(daoNode, daoPlaceholder);
}
return new LenskitRecommenderEngine(factory, modified, daoPlaceholder,
config.getSPI());
}
|
diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/TextField.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/TextField.java
index f4b3b6b8e..36a95b840 100644
--- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/TextField.java
+++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/TextField.java
@@ -1,815 +1,815 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.scenes.scene2d.ui;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.BitmapFont.TextBounds;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Clipboard;
import com.badlogic.gdx.utils.FloatArray;
import com.badlogic.gdx.utils.TimeUtils;
import com.badlogic.gdx.utils.Timer;
import com.badlogic.gdx.utils.Timer.Task;
/** A single-line text input field.
* <p>
* The preferred height of a text field is the height of the {@link TextFieldStyle#font} and {@link TextFieldStyle#background}.
* The preferred width of a text field is 150, a relatively arbitrary size.
* <p>
* The text field will copy the currently selected text when ctrl+c is pressed, and paste any text in the clipboard when ctrl+v is
* pressed. Clipboard functionality is provided via the {@link Clipboard} interface. Currently there are two standard
* implementations, one for the desktop and one for Android. The Android clipboard is a stub, as copy & pasting on Android is not
* supported yet.
* <p>
* The text field allows you to specify an {@link OnscreenKeyboard} for displaying a softkeyboard and piping all key events
* generated by the keyboard to the text field. There are two standard implementations, one for the desktop and one for Android.
* The desktop keyboard is a stub, as a softkeyboard is not needed on the desktop. The Android {@link OnscreenKeyboard}
* implementation will bring up the default IME.
* @author mzechner
* @author Nathan Sweet */
public class TextField extends Widget {
static private final char BACKSPACE = 8;
static private final char ENTER_DESKTOP = '\r';
static private final char ENTER_ANDROID = '\n';
static private final char TAB = '\t';
static private final char DELETE = 127;
static private final char BULLET = 149;
TextFieldStyle style;
String text, messageText;
private CharSequence displayText;
int cursor;
private Clipboard clipboard;
TextFieldListener listener;
TextFieldFilter filter;
OnscreenKeyboard keyboard = new DefaultOnscreenKeyboard();
boolean focusTraversal = true;
private boolean passwordMode;
private StringBuilder passwordBuffer;
private final Rectangle fieldBounds = new Rectangle();
private final TextBounds textBounds = new TextBounds();
private final Rectangle scissor = new Rectangle();
float renderOffset, textOffset;
private int visibleTextStart, visibleTextEnd;
private final FloatArray glyphAdvances = new FloatArray();
final FloatArray glyphPositions = new FloatArray();
boolean cursorOn = true;
private float blinkTime = 0.32f;
long lastBlink;
boolean hasSelection;
int selectionStart;
private float selectionX, selectionWidth;
private char passwordCharacter = BULLET;
InputListener inputListener;
KeyRepeatTask keyRepeatTask = new KeyRepeatTask();
float keyRepeatInitialTime = 0.4f;
float keyRepeatTime = 0.1f;
boolean rightAligned;
public TextField (String text, Skin skin) {
this(text, skin.get(TextFieldStyle.class));
}
public TextField (String text, Skin skin, String styleName) {
this(text, skin.get(styleName, TextFieldStyle.class));
}
public TextField (String text, TextFieldStyle style) {
setStyle(style);
this.clipboard = Gdx.app.getClipboard();
setText(text);
setWidth(getPrefWidth());
setHeight(getPrefHeight());
initialize();
}
private void initialize () {
addListener(inputListener = new ClickListener() {
public void clicked (InputEvent event, float x, float y) {
if (getTapCount() > 1) setSelection(0, text.length());
}
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
if (!super.touchDown(event, x, y, pointer, button)) return false;
if (pointer == 0 && button != 0) return false;
Stage stage = getStage();
keyboard.show(true);
clearSelection();
setCursorPosition(x);
selectionStart = cursor;
if (stage != null) stage.setKeyboardFocus(TextField.this);
return true;
}
public void touchDragged (InputEvent event, float x, float y, int pointer) {
super.touchDragged(event, x, y, pointer);
lastBlink = 0;
cursorOn = false;
setCursorPosition(x);
hasSelection = true;
}
private void setCursorPosition (float x) {
lastBlink = 0;
cursorOn = false;
- x -= renderOffset;
+ x -= renderOffset + textOffset;
for (int i = 0; i < glyphPositions.size; i++) {
if (glyphPositions.items[i] > x) {
cursor = Math.max(0, i - 1);
return;
}
}
cursor = Math.max(0, glyphPositions.size - 1);
}
public boolean keyDown (InputEvent event, int keycode) {
final BitmapFont font = style.font;
lastBlink = 0;
cursorOn = false;
Stage stage = getStage();
if (stage != null && stage.getKeyboardFocus() == TextField.this) {
boolean repeat = false;
boolean ctrl = Gdx.input.isKeyPressed(Keys.CONTROL_LEFT) || Gdx.input.isKeyPressed(Keys.CONTROL_RIGHT);
if (ctrl) {
// paste
if (keycode == Keys.V) {
paste();
return true;
}
// copy
if (keycode == Keys.C || keycode == Keys.INSERT) {
copy();
return true;
}
// cut
if (keycode == Keys.X || keycode == Keys.DEL) {
cut();
return true;
}
}
if (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT)) {
// paste
if (keycode == Keys.INSERT) paste();
// cut
if (keycode == Keys.FORWARD_DEL) {
if (hasSelection) {
copy();
delete();
}
}
// selection
if (keycode == Keys.LEFT) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
while (--cursor > 0 && ctrl) {
char c = text.charAt(cursor);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
repeat = true;
}
if (keycode == Keys.RIGHT) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
int length = text.length();
while (++cursor < length && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
repeat = true;
}
if (keycode == Keys.HOME) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
cursor = 0;
}
if (keycode == Keys.END) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
cursor = text.length();
}
cursor = Math.max(0, cursor);
cursor = Math.min(text.length(), cursor);
} else {
// cursor movement or other keys (kill selection)
if (keycode == Keys.LEFT) {
while (cursor-- > 1 && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
clearSelection();
repeat = true;
}
if (keycode == Keys.RIGHT) {
int length = text.length();
while (++cursor < length && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
clearSelection();
repeat = true;
}
if (keycode == Keys.HOME) {
cursor = 0;
clearSelection();
}
if (keycode == Keys.END) {
cursor = text.length();
clearSelection();
}
cursor = Math.max(0, cursor);
cursor = Math.min(text.length(), cursor);
}
if (repeat && (!keyRepeatTask.isScheduled() || keyRepeatTask.keycode != keycode)) {
keyRepeatTask.keycode = keycode;
keyRepeatTask.cancel();
Timer.schedule(keyRepeatTask, keyRepeatInitialTime, keyRepeatTime);
}
return true;
}
return false;
}
public boolean keyUp (InputEvent event, int keycode) {
keyRepeatTask.cancel();
return true;
}
public boolean keyTyped (InputEvent event, char character) {
final BitmapFont font = style.font;
Stage stage = getStage();
if (stage != null && stage.getKeyboardFocus() == TextField.this) {
if (character == BACKSPACE && (cursor > 0 || hasSelection)) {
if (!hasSelection) {
text = text.substring(0, cursor - 1) + text.substring(cursor);
updateDisplayText();
cursor--;
renderOffset = 0;
} else {
delete();
}
}
if (character == DELETE) {
if (cursor < text.length() || hasSelection) {
if (!hasSelection) {
text = text.substring(0, cursor) + text.substring(cursor + 1);
updateDisplayText();
} else {
delete();
}
}
return true;
}
if (character != ENTER_DESKTOP && character != ENTER_ANDROID) {
if (filter != null && !filter.acceptChar(TextField.this, character)) return true;
}
if ((character == TAB || character == ENTER_ANDROID) && focusTraversal)
next(Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT));
if (font.containsCharacter(character)) {
if (!hasSelection) {
text = text.substring(0, cursor) + character + text.substring(cursor, text.length());
updateDisplayText();
cursor++;
} else {
int minIndex = Math.min(cursor, selectionStart);
int maxIndex = Math.max(cursor, selectionStart);
text = (minIndex > 0 ? text.substring(0, minIndex) : "")
+ (maxIndex < text.length() ? text.substring(maxIndex, text.length()) : "");
cursor = minIndex;
text = text.substring(0, cursor) + character + text.substring(cursor, text.length());
updateDisplayText();
cursor++;
clearSelection();
}
}
if (listener != null) listener.keyTyped(TextField.this, character);
return true;
} else
return false;
}
});
}
public void setStyle (TextFieldStyle style) {
if (style == null) throw new IllegalArgumentException("style cannot be null.");
this.style = style;
invalidateHierarchy();
}
public void setPasswordCharacter (char passwordCharacter) {
this.passwordCharacter = passwordCharacter;
}
/** Returns the text field's style. Modifying the returned style may not have an effect until {@link #setStyle(TextFieldStyle)}
* is called. */
public TextFieldStyle getStyle () {
return style;
}
private void calculateOffsets () {
float visibleWidth = getWidth();
if (style.background != null) visibleWidth -= style.background.getLeftWidth() + style.background.getRightWidth();
// Check if the cursor has gone out the left or right side of the visible area and adjust renderoffset.
float position = glyphPositions.get(cursor);
float distance = position - Math.abs(renderOffset);
if (distance <= 0) {
if (cursor > 0)
renderOffset = -glyphPositions.get(cursor - 1);
else
renderOffset = 0;
} else if (distance > visibleWidth) {
renderOffset -= distance - visibleWidth;
}
// calculate first visible char based on render offset
visibleTextStart = 0;
textOffset = 0;
float start = Math.abs(renderOffset);
int len = glyphPositions.size;
float startPos = 0;
for (int i = 0; i < len; i++) {
if (glyphPositions.items[i] >= start) {
visibleTextStart = i;
startPos = glyphPositions.items[i];
textOffset = startPos - start;
break;
}
}
// calculate last visible char based on visible width and render offset
visibleTextEnd = Math.min(displayText.length(), cursor + 1);
for (; visibleTextEnd <= displayText.length(); visibleTextEnd++) {
if (glyphPositions.items[visibleTextEnd] - startPos > visibleWidth) break;
}
visibleTextEnd = Math.max(0, visibleTextEnd - 1);
// calculate selection x position and width
if (hasSelection) {
int minIndex = Math.min(cursor, selectionStart);
int maxIndex = Math.max(cursor, selectionStart);
float minX = Math.max(glyphPositions.get(minIndex), startPos);
float maxX = Math.min(glyphPositions.get(maxIndex), glyphPositions.get(visibleTextEnd));
selectionX = minX;
selectionWidth = maxX - minX;
}
if (rightAligned) {
textOffset = visibleWidth - (glyphPositions.items[visibleTextEnd] - startPos);
if (hasSelection) selectionX += textOffset;
}
}
@Override
public void draw (SpriteBatch batch, float parentAlpha) {
final BitmapFont font = style.font;
final Color fontColor = style.fontColor;
final Drawable selection = style.selection;
final Drawable cursorPatch = style.cursor;
final Drawable background = style.background;
Color color = getColor();
float x = getX();
float y = getY();
float width = getWidth();
float height = getHeight();
float textY = textBounds.height / 2 + font.getDescent();
batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
float bgLeftWidth = 0;
if (background != null) {
background.draw(batch, x, y, width, height);
bgLeftWidth = background.getLeftWidth();
float bottom = background.getBottomHeight();
textY = (int)(textY + (height - background.getTopHeight() - bottom) / 2 + bottom);
} else
textY = (int)(textY + height / 2);
calculateOffsets();
Stage stage = getStage();
boolean focused = stage != null && stage.getKeyboardFocus() == this;
if (focused && hasSelection && selection != null) {
selection.draw(batch, x + selectionX + bgLeftWidth + renderOffset, y + textY - textBounds.height - font.getDescent(),
selectionWidth, textBounds.height + font.getDescent() / 2);
}
if (displayText.length() == 0) {
if (!focused && messageText != null) {
if (style.messageFontColor != null) {
font.setColor(style.messageFontColor.r, style.messageFontColor.g, style.messageFontColor.b,
style.messageFontColor.a * parentAlpha);
} else
font.setColor(0.7f, 0.7f, 0.7f, parentAlpha);
BitmapFont messageFont = style.messageFont != null ? style.messageFont : font;
font.draw(batch, messageText, x + bgLeftWidth, y + textY);
}
} else {
font.setColor(fontColor.r, fontColor.g, fontColor.b, fontColor.a * parentAlpha);
font.draw(batch, displayText, x + bgLeftWidth + textOffset, y + textY, visibleTextStart, visibleTextEnd);
}
if (focused) {
blink();
if (cursorOn && cursorPatch != null) {
cursorPatch.draw(batch, x + bgLeftWidth + textOffset + glyphPositions.get(cursor)
- glyphPositions.items[visibleTextStart] - 1, y + textY - textBounds.height - font.getDescent(),
cursorPatch.getMinWidth(), textBounds.height + font.getDescent() / 2);
}
}
}
void updateDisplayText () {
if (passwordMode && style.font.containsCharacter(passwordCharacter)) {
if (passwordBuffer == null) passwordBuffer = new StringBuilder(text.length());
if (passwordBuffer.length() > text.length()) //
passwordBuffer.setLength(text.length());
else {
for (int i = passwordBuffer.length(), n = text.length(); i < n; i++)
passwordBuffer.append(passwordCharacter);
}
displayText = passwordBuffer;
} else
displayText = text;
style.font.computeGlyphAdvancesAndPositions(displayText, glyphAdvances, glyphPositions);
if (selectionStart > text.length()) selectionStart = text.length();
}
private void blink () {
long time = TimeUtils.nanoTime();
if ((time - lastBlink) / 1000000000.0f > blinkTime) {
cursorOn = !cursorOn;
lastBlink = time;
}
}
/** Copies the contents of this TextField to the {@link Clipboard} implementation set on this TextField. */
public void copy () {
if (hasSelection) {
int minIndex = Math.min(cursor, selectionStart);
int maxIndex = Math.max(cursor, selectionStart);
clipboard.setContents(text.substring(minIndex, maxIndex));
}
}
/** Copies the selected contents of this TextField to the {@link Clipboard} implementation set on this TextField, then removes
* it. */
public void cut () {
if (hasSelection) {
copy();
delete();
}
}
/** Pastes the content of the {@link Clipboard} implementation set on this Textfield to this TextField. */
void paste () {
String content = clipboard.getContents();
if (content != null) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < content.length(); i++) {
char c = content.charAt(i);
if (style.font.containsCharacter(c)) builder.append(c);
}
content = builder.toString();
if (!hasSelection) {
text = text.substring(0, cursor) + content + text.substring(cursor, text.length());
updateDisplayText();
cursor += content.length();
} else {
int minIndex = Math.min(cursor, selectionStart);
int maxIndex = Math.max(cursor, selectionStart);
text = (minIndex > 0 ? text.substring(0, minIndex) : "")
+ (maxIndex < text.length() ? text.substring(maxIndex, text.length()) : "");
cursor = minIndex;
text = text.substring(0, cursor) + content + text.substring(cursor, text.length());
updateDisplayText();
cursor = minIndex + content.length();
clearSelection();
}
}
}
void delete () {
int minIndex = Math.min(cursor, selectionStart);
int maxIndex = Math.max(cursor, selectionStart);
text = (minIndex > 0 ? text.substring(0, minIndex) : "")
+ (maxIndex < text.length() ? text.substring(maxIndex, text.length()) : "");
updateDisplayText();
cursor = minIndex;
clearSelection();
}
/** Focuses the next TextField. If none is found, the keyboard is hidden. Does nothing if the text field is not in a stage.
* @param up If true, the TextField with the same or next smallest y coordinate is found, else the next highest. */
public void next (boolean up) {
Stage stage = getStage();
if (stage == null) return;
getParent().localToStageCoordinates(Vector2.tmp.set(getX(), getY()));
TextField textField = findNextTextField(stage.getActors(), null, Vector2.tmp2, Vector2.tmp, up);
if (textField == null) { // Try to wrap around.
if (up)
Vector2.tmp.set(Float.MIN_VALUE, Float.MIN_VALUE);
else
Vector2.tmp.set(Float.MAX_VALUE, Float.MAX_VALUE);
textField = findNextTextField(getStage().getActors(), null, Vector2.tmp2, Vector2.tmp, up);
}
if (textField != null)
stage.setKeyboardFocus(textField);
else
Gdx.input.setOnscreenKeyboardVisible(false);
}
private TextField findNextTextField (Array<Actor> actors, TextField best, Vector2 bestCoords, Vector2 currentCoords, boolean up) {
for (int i = 0, n = actors.size; i < n; i++) {
Actor actor = actors.get(i);
if (actor == this) continue;
if (actor instanceof TextField) {
Vector2 actorCoords = actor.getParent().localToStageCoordinates(Vector2.tmp3.set(actor.getX(), actor.getY()));
if ((actorCoords.y < currentCoords.y || (actorCoords.y == currentCoords.y && actorCoords.x > currentCoords.x)) ^ up) {
if (best == null
|| (actorCoords.y > bestCoords.y || (actorCoords.y == bestCoords.y && actorCoords.x < bestCoords.x)) ^ up) {
best = (TextField)actor;
bestCoords.set(actorCoords);
}
}
}
if (actor instanceof Group) best = findNextTextField(((Group)actor).getChildren(), best, bestCoords, currentCoords, up);
}
return best;
}
/** @param listener May be null. */
public void setTextFieldListener (TextFieldListener listener) {
this.listener = listener;
}
/** @param filter May be null. */
public void setTextFieldFilter (TextFieldFilter filter) {
this.filter = filter;
}
/** If true (the default), tab/shift+tab will move to the next text field. */
public void setFocusTraversal (boolean focusTraversal) {
this.focusTraversal = focusTraversal;
}
/** @return May be null. */
public String getMessageText () {
return messageText;
}
/** Sets the text that will be drawn in the text field if no text has been entered.
* @parma messageText May be null. */
public void setMessageText (String messageText) {
this.messageText = messageText;
}
public void setText (String text) {
if (text == null) throw new IllegalArgumentException("text cannot be null.");
BitmapFont font = style.font;
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (font.containsCharacter(c)) buffer.append(c);
}
this.text = buffer.toString();
updateDisplayText();
cursor = 0;
clearSelection();
textBounds.set(font.getBounds(displayText));
textBounds.height -= font.getDescent() * 2;
font.computeGlyphAdvancesAndPositions(displayText, glyphAdvances, glyphPositions);
}
/** @return Never null, might be an empty string. */
public String getText () {
return text;
}
/** Sets the selected text. */
public void setSelection (int selectionStart, int selectionEnd) {
if (selectionStart < 0) throw new IllegalArgumentException("selectionStart must be >= 0");
if (selectionEnd < 0) throw new IllegalArgumentException("selectionEnd must be >= 0");
selectionStart = Math.min(text.length(), selectionStart);
selectionEnd = Math.min(text.length(), selectionEnd);
if (selectionEnd == selectionStart) {
clearSelection();
return;
}
if (selectionEnd < selectionStart) {
int temp = selectionEnd;
selectionEnd = selectionStart;
selectionStart = temp;
}
hasSelection = true;
this.selectionStart = selectionStart;
cursor = selectionEnd;
}
public void selectAll () {
setSelection(0, text.length());
}
public void clearSelection () {
hasSelection = false;
}
/** Sets the cursor position and clears any selection. */
public void setCursorPosition (int cursorPosition) {
if (cursorPosition < 0) throw new IllegalArgumentException("cursorPosition must be >= 0");
clearSelection();
cursor = Math.min(cursorPosition, text.length());
}
public int getCursorPosition () {
return cursor;
}
/** Default is an instance of {@link DefaultOnscreenKeyboard}. */
public OnscreenKeyboard getOnscreenKeyboard () {
return keyboard;
}
public void setOnscreenKeyboard (OnscreenKeyboard keyboard) {
this.keyboard = keyboard;
}
public void setClipboard (Clipboard clipboard) {
this.clipboard = clipboard;
}
public float getPrefWidth () {
return 150;
}
public float getPrefHeight () {
float prefHeight = textBounds.height;
if (style.background != null) {
prefHeight = Math.max(prefHeight + style.background.getBottomHeight() + style.background.getTopHeight(),
style.background.getMinHeight());
}
return prefHeight;
}
public void setRightAligned (boolean rightAligned) {
this.rightAligned = rightAligned;
}
/** If true, the text in this text field will be shown as bullet characters. The font must have character 149 or this will have
* no affect. */
public void setPasswordMode (boolean passwordMode) {
this.passwordMode = passwordMode;
}
public void setBlinkTime (float blinkTime) {
this.blinkTime = blinkTime;
}
class KeyRepeatTask extends Task {
int keycode;
public void run () {
inputListener.keyDown(null, keycode);
}
}
/** Interface for listening to typed characters.
* @author mzechner */
static public interface TextFieldListener {
public void keyTyped (TextField textField, char key);
}
/** Interface for filtering characters entered into the text field.
* @author mzechner */
static public interface TextFieldFilter {
/** @param textField
* @param key
* @return whether to accept the character */
public boolean acceptChar (TextField textField, char key);
static public class DigitsOnlyFilter implements TextFieldFilter {
@Override
public boolean acceptChar (TextField textField, char key) {
return Character.isDigit(key);
}
}
}
/** An interface for onscreen keyboards. Can invoke the default keyboard or render your own keyboard!
* @author mzechner */
static public interface OnscreenKeyboard {
public void show (boolean visible);
}
/** The default {@link OnscreenKeyboard} used by all {@link TextField} instances. Just uses
* {@link Input#setOnscreenKeyboardVisible(boolean)} as appropriate. Might overlap your actual rendering, so use with care!
* @author mzechner */
static public class DefaultOnscreenKeyboard implements OnscreenKeyboard {
@Override
public void show (boolean visible) {
Gdx.input.setOnscreenKeyboardVisible(visible);
}
}
/** The style for a text field, see {@link TextField}.
* @author mzechner
* @author Nathan Sweet */
static public class TextFieldStyle {
public BitmapFont font;
public Color fontColor;
/** Optional. */
public Drawable background, cursor, selection;
/** Optional. */
public BitmapFont messageFont;
/** Optional. */
public Color messageFontColor;
public TextFieldStyle () {
}
public TextFieldStyle (BitmapFont font, Color fontColor, Drawable cursor, Drawable selection, Drawable background) {
this.background = background;
this.cursor = cursor;
this.font = font;
this.fontColor = fontColor;
this.selection = selection;
}
public TextFieldStyle (TextFieldStyle style) {
this.messageFont = style.messageFont;
if (style.messageFontColor != null) this.messageFontColor = new Color(style.messageFontColor);
this.background = style.background;
this.cursor = style.cursor;
this.font = style.font;
if (style.fontColor != null) this.fontColor = new Color(style.fontColor);
this.selection = style.selection;
}
}
}
| true | true | private void initialize () {
addListener(inputListener = new ClickListener() {
public void clicked (InputEvent event, float x, float y) {
if (getTapCount() > 1) setSelection(0, text.length());
}
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
if (!super.touchDown(event, x, y, pointer, button)) return false;
if (pointer == 0 && button != 0) return false;
Stage stage = getStage();
keyboard.show(true);
clearSelection();
setCursorPosition(x);
selectionStart = cursor;
if (stage != null) stage.setKeyboardFocus(TextField.this);
return true;
}
public void touchDragged (InputEvent event, float x, float y, int pointer) {
super.touchDragged(event, x, y, pointer);
lastBlink = 0;
cursorOn = false;
setCursorPosition(x);
hasSelection = true;
}
private void setCursorPosition (float x) {
lastBlink = 0;
cursorOn = false;
x -= renderOffset;
for (int i = 0; i < glyphPositions.size; i++) {
if (glyphPositions.items[i] > x) {
cursor = Math.max(0, i - 1);
return;
}
}
cursor = Math.max(0, glyphPositions.size - 1);
}
public boolean keyDown (InputEvent event, int keycode) {
final BitmapFont font = style.font;
lastBlink = 0;
cursorOn = false;
Stage stage = getStage();
if (stage != null && stage.getKeyboardFocus() == TextField.this) {
boolean repeat = false;
boolean ctrl = Gdx.input.isKeyPressed(Keys.CONTROL_LEFT) || Gdx.input.isKeyPressed(Keys.CONTROL_RIGHT);
if (ctrl) {
// paste
if (keycode == Keys.V) {
paste();
return true;
}
// copy
if (keycode == Keys.C || keycode == Keys.INSERT) {
copy();
return true;
}
// cut
if (keycode == Keys.X || keycode == Keys.DEL) {
cut();
return true;
}
}
if (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT)) {
// paste
if (keycode == Keys.INSERT) paste();
// cut
if (keycode == Keys.FORWARD_DEL) {
if (hasSelection) {
copy();
delete();
}
}
// selection
if (keycode == Keys.LEFT) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
while (--cursor > 0 && ctrl) {
char c = text.charAt(cursor);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
repeat = true;
}
if (keycode == Keys.RIGHT) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
int length = text.length();
while (++cursor < length && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
repeat = true;
}
if (keycode == Keys.HOME) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
cursor = 0;
}
if (keycode == Keys.END) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
cursor = text.length();
}
cursor = Math.max(0, cursor);
cursor = Math.min(text.length(), cursor);
} else {
// cursor movement or other keys (kill selection)
if (keycode == Keys.LEFT) {
while (cursor-- > 1 && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
clearSelection();
repeat = true;
}
if (keycode == Keys.RIGHT) {
int length = text.length();
while (++cursor < length && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
clearSelection();
repeat = true;
}
if (keycode == Keys.HOME) {
cursor = 0;
clearSelection();
}
if (keycode == Keys.END) {
cursor = text.length();
clearSelection();
}
cursor = Math.max(0, cursor);
cursor = Math.min(text.length(), cursor);
}
if (repeat && (!keyRepeatTask.isScheduled() || keyRepeatTask.keycode != keycode)) {
keyRepeatTask.keycode = keycode;
keyRepeatTask.cancel();
Timer.schedule(keyRepeatTask, keyRepeatInitialTime, keyRepeatTime);
}
return true;
}
return false;
}
public boolean keyUp (InputEvent event, int keycode) {
keyRepeatTask.cancel();
return true;
}
public boolean keyTyped (InputEvent event, char character) {
final BitmapFont font = style.font;
Stage stage = getStage();
if (stage != null && stage.getKeyboardFocus() == TextField.this) {
if (character == BACKSPACE && (cursor > 0 || hasSelection)) {
if (!hasSelection) {
text = text.substring(0, cursor - 1) + text.substring(cursor);
updateDisplayText();
cursor--;
renderOffset = 0;
} else {
delete();
}
}
if (character == DELETE) {
if (cursor < text.length() || hasSelection) {
if (!hasSelection) {
text = text.substring(0, cursor) + text.substring(cursor + 1);
updateDisplayText();
} else {
delete();
}
}
return true;
}
if (character != ENTER_DESKTOP && character != ENTER_ANDROID) {
if (filter != null && !filter.acceptChar(TextField.this, character)) return true;
}
if ((character == TAB || character == ENTER_ANDROID) && focusTraversal)
next(Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT));
if (font.containsCharacter(character)) {
if (!hasSelection) {
text = text.substring(0, cursor) + character + text.substring(cursor, text.length());
updateDisplayText();
cursor++;
} else {
int minIndex = Math.min(cursor, selectionStart);
int maxIndex = Math.max(cursor, selectionStart);
text = (minIndex > 0 ? text.substring(0, minIndex) : "")
+ (maxIndex < text.length() ? text.substring(maxIndex, text.length()) : "");
cursor = minIndex;
text = text.substring(0, cursor) + character + text.substring(cursor, text.length());
updateDisplayText();
cursor++;
clearSelection();
}
}
if (listener != null) listener.keyTyped(TextField.this, character);
return true;
} else
return false;
}
});
}
| private void initialize () {
addListener(inputListener = new ClickListener() {
public void clicked (InputEvent event, float x, float y) {
if (getTapCount() > 1) setSelection(0, text.length());
}
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
if (!super.touchDown(event, x, y, pointer, button)) return false;
if (pointer == 0 && button != 0) return false;
Stage stage = getStage();
keyboard.show(true);
clearSelection();
setCursorPosition(x);
selectionStart = cursor;
if (stage != null) stage.setKeyboardFocus(TextField.this);
return true;
}
public void touchDragged (InputEvent event, float x, float y, int pointer) {
super.touchDragged(event, x, y, pointer);
lastBlink = 0;
cursorOn = false;
setCursorPosition(x);
hasSelection = true;
}
private void setCursorPosition (float x) {
lastBlink = 0;
cursorOn = false;
x -= renderOffset + textOffset;
for (int i = 0; i < glyphPositions.size; i++) {
if (glyphPositions.items[i] > x) {
cursor = Math.max(0, i - 1);
return;
}
}
cursor = Math.max(0, glyphPositions.size - 1);
}
public boolean keyDown (InputEvent event, int keycode) {
final BitmapFont font = style.font;
lastBlink = 0;
cursorOn = false;
Stage stage = getStage();
if (stage != null && stage.getKeyboardFocus() == TextField.this) {
boolean repeat = false;
boolean ctrl = Gdx.input.isKeyPressed(Keys.CONTROL_LEFT) || Gdx.input.isKeyPressed(Keys.CONTROL_RIGHT);
if (ctrl) {
// paste
if (keycode == Keys.V) {
paste();
return true;
}
// copy
if (keycode == Keys.C || keycode == Keys.INSERT) {
copy();
return true;
}
// cut
if (keycode == Keys.X || keycode == Keys.DEL) {
cut();
return true;
}
}
if (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT)) {
// paste
if (keycode == Keys.INSERT) paste();
// cut
if (keycode == Keys.FORWARD_DEL) {
if (hasSelection) {
copy();
delete();
}
}
// selection
if (keycode == Keys.LEFT) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
while (--cursor > 0 && ctrl) {
char c = text.charAt(cursor);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
repeat = true;
}
if (keycode == Keys.RIGHT) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
int length = text.length();
while (++cursor < length && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
repeat = true;
}
if (keycode == Keys.HOME) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
cursor = 0;
}
if (keycode == Keys.END) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
cursor = text.length();
}
cursor = Math.max(0, cursor);
cursor = Math.min(text.length(), cursor);
} else {
// cursor movement or other keys (kill selection)
if (keycode == Keys.LEFT) {
while (cursor-- > 1 && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
clearSelection();
repeat = true;
}
if (keycode == Keys.RIGHT) {
int length = text.length();
while (++cursor < length && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
clearSelection();
repeat = true;
}
if (keycode == Keys.HOME) {
cursor = 0;
clearSelection();
}
if (keycode == Keys.END) {
cursor = text.length();
clearSelection();
}
cursor = Math.max(0, cursor);
cursor = Math.min(text.length(), cursor);
}
if (repeat && (!keyRepeatTask.isScheduled() || keyRepeatTask.keycode != keycode)) {
keyRepeatTask.keycode = keycode;
keyRepeatTask.cancel();
Timer.schedule(keyRepeatTask, keyRepeatInitialTime, keyRepeatTime);
}
return true;
}
return false;
}
public boolean keyUp (InputEvent event, int keycode) {
keyRepeatTask.cancel();
return true;
}
public boolean keyTyped (InputEvent event, char character) {
final BitmapFont font = style.font;
Stage stage = getStage();
if (stage != null && stage.getKeyboardFocus() == TextField.this) {
if (character == BACKSPACE && (cursor > 0 || hasSelection)) {
if (!hasSelection) {
text = text.substring(0, cursor - 1) + text.substring(cursor);
updateDisplayText();
cursor--;
renderOffset = 0;
} else {
delete();
}
}
if (character == DELETE) {
if (cursor < text.length() || hasSelection) {
if (!hasSelection) {
text = text.substring(0, cursor) + text.substring(cursor + 1);
updateDisplayText();
} else {
delete();
}
}
return true;
}
if (character != ENTER_DESKTOP && character != ENTER_ANDROID) {
if (filter != null && !filter.acceptChar(TextField.this, character)) return true;
}
if ((character == TAB || character == ENTER_ANDROID) && focusTraversal)
next(Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT));
if (font.containsCharacter(character)) {
if (!hasSelection) {
text = text.substring(0, cursor) + character + text.substring(cursor, text.length());
updateDisplayText();
cursor++;
} else {
int minIndex = Math.min(cursor, selectionStart);
int maxIndex = Math.max(cursor, selectionStart);
text = (minIndex > 0 ? text.substring(0, minIndex) : "")
+ (maxIndex < text.length() ? text.substring(maxIndex, text.length()) : "");
cursor = minIndex;
text = text.substring(0, cursor) + character + text.substring(cursor, text.length());
updateDisplayText();
cursor++;
clearSelection();
}
}
if (listener != null) listener.keyTyped(TextField.this, character);
return true;
} else
return false;
}
});
}
|
diff --git a/asterix-external-data/src/main/java/edu/uci/ics/asterix/external/dataset/adapter/NCFileSystemAdapter.java b/asterix-external-data/src/main/java/edu/uci/ics/asterix/external/dataset/adapter/NCFileSystemAdapter.java
index ae9b412e..ef39d454 100644
--- a/asterix-external-data/src/main/java/edu/uci/ics/asterix/external/dataset/adapter/NCFileSystemAdapter.java
+++ b/asterix-external-data/src/main/java/edu/uci/ics/asterix/external/dataset/adapter/NCFileSystemAdapter.java
@@ -1,111 +1,115 @@
/*
* Copyright 2009-2012 by The Regents of the University of California
* 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 from
*
* 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 edu.uci.ics.asterix.external.dataset.adapter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import edu.uci.ics.asterix.common.exceptions.AsterixException;
import edu.uci.ics.asterix.om.types.IAType;
import edu.uci.ics.hyracks.algebricks.common.constraints.AlgebricksAbsolutePartitionConstraint;
import edu.uci.ics.hyracks.algebricks.common.constraints.AlgebricksPartitionConstraint;
import edu.uci.ics.hyracks.api.context.IHyracksTaskContext;
import edu.uci.ics.hyracks.api.io.FileReference;
import edu.uci.ics.hyracks.dataflow.std.file.FileSplit;
/**
* Factory class for creating an instance of NCFileSystemAdapter. An
* NCFileSystemAdapter reads external data residing on the local file system of
* an NC.
*/
public class NCFileSystemAdapter extends FileSystemBasedAdapter {
private static final long serialVersionUID = 1L;
private FileSplit[] fileSplits;
public NCFileSystemAdapter(IAType atype) {
super(atype);
}
@Override
public void configure(Map<String, String> arguments) throws Exception {
this.configuration = arguments;
String[] splits = arguments.get(KEY_PATH).split(",");
configureFileSplits(splits);
configureFormat();
}
@Override
public void initialize(IHyracksTaskContext ctx) throws Exception {
this.ctx = ctx;
}
@Override
public AdapterType getAdapterType() {
return AdapterType.READ;
}
- private void configureFileSplits(String[] splits) {
+ private void configureFileSplits(String[] splits) throws AsterixException {
if (fileSplits == null) {
fileSplits = new FileSplit[splits.length];
String nodeName;
String nodeLocalPath;
int count = 0;
String trimmedValue;
for (String splitPath : splits) {
trimmedValue = splitPath.trim();
+ if (!trimmedValue.contains("://")) {
+ throw new AsterixException("Invalid path: " + splitPath
+ + "\nUsage- path=\"Host://Absolute File Path\"");
+ }
nodeName = trimmedValue.split(":")[0];
nodeLocalPath = trimmedValue.split("://")[1];
FileSplit fileSplit = new FileSplit(nodeName, new FileReference(new File(nodeLocalPath)));
fileSplits[count++] = fileSplit;
}
}
}
private void configurePartitionConstraint() throws AsterixException {
String[] locs = new String[fileSplits.length];
String location;
for (int i = 0; i < fileSplits.length; i++) {
location = getNodeResolver().resolveNode(fileSplits[i].getNodeName());
locs[i] = location;
}
partitionConstraint = new AlgebricksAbsolutePartitionConstraint(locs);
}
@Override
public InputStream getInputStream(int partition) throws IOException {
FileSplit split = fileSplits[partition];
File inputFile = split.getLocalFile().getFile();
InputStream in;
try {
in = new FileInputStream(inputFile);
return in;
} catch (FileNotFoundException e) {
throw new IOException(e);
}
}
@Override
public AlgebricksPartitionConstraint getPartitionConstraint() throws Exception {
if (partitionConstraint == null) {
configurePartitionConstraint();
}
return partitionConstraint;
}
}
| false | true | private void configureFileSplits(String[] splits) {
if (fileSplits == null) {
fileSplits = new FileSplit[splits.length];
String nodeName;
String nodeLocalPath;
int count = 0;
String trimmedValue;
for (String splitPath : splits) {
trimmedValue = splitPath.trim();
nodeName = trimmedValue.split(":")[0];
nodeLocalPath = trimmedValue.split("://")[1];
FileSplit fileSplit = new FileSplit(nodeName, new FileReference(new File(nodeLocalPath)));
fileSplits[count++] = fileSplit;
}
}
}
| private void configureFileSplits(String[] splits) throws AsterixException {
if (fileSplits == null) {
fileSplits = new FileSplit[splits.length];
String nodeName;
String nodeLocalPath;
int count = 0;
String trimmedValue;
for (String splitPath : splits) {
trimmedValue = splitPath.trim();
if (!trimmedValue.contains("://")) {
throw new AsterixException("Invalid path: " + splitPath
+ "\nUsage- path=\"Host://Absolute File Path\"");
}
nodeName = trimmedValue.split(":")[0];
nodeLocalPath = trimmedValue.split("://")[1];
FileSplit fileSplit = new FileSplit(nodeName, new FileReference(new File(nodeLocalPath)));
fileSplits[count++] = fileSplit;
}
}
}
|
diff --git a/src/com/android/settings/wifi/WifiDialog.java b/src/com/android/settings/wifi/WifiDialog.java
index f86482620..f980d0c30 100644
--- a/src/com/android/settings/wifi/WifiDialog.java
+++ b/src/com/android/settings/wifi/WifiDialog.java
@@ -1,95 +1,95 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.wifi;
import com.android.settings.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
class WifiDialog extends AlertDialog implements WifiConfigUiBase {
static final int BUTTON_SUBMIT = DialogInterface.BUTTON_POSITIVE;
static final int BUTTON_FORGET = DialogInterface.BUTTON_NEUTRAL;
private final boolean mEdit;
private final DialogInterface.OnClickListener mListener;
private final AccessPoint mAccessPoint;
private View mView;
private WifiConfigController mController;
public WifiDialog(Context context, DialogInterface.OnClickListener listener,
AccessPoint accessPoint, boolean edit) {
- super(context);
+ super(context, R.style.Theme_WifiDialog);
mEdit = edit;
mListener = listener;
mAccessPoint = accessPoint;
}
@Override
public WifiConfigController getController() {
return mController;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
mView = getLayoutInflater().inflate(R.layout.wifi_dialog, null);
setView(mView);
setInverseBackgroundForced(true);
mController = new WifiConfigController(this, mView, mAccessPoint, mEdit);
super.onCreate(savedInstanceState);
}
@Override
public boolean isEdit() {
return mEdit;
}
@Override
public Button getSubmitButton() {
return getButton(BUTTON_SUBMIT);
}
@Override
public Button getForgetButton() {
return getButton(BUTTON_FORGET);
}
@Override
public Button getCancelButton() {
return getButton(BUTTON_NEGATIVE);
}
@Override
public void setSubmitButton(CharSequence text) {
setButton(BUTTON_SUBMIT, text, mListener);
}
@Override
public void setForgetButton(CharSequence text) {
setButton(BUTTON_FORGET, text, mListener);
}
@Override
public void setCancelButton(CharSequence text) {
setButton(BUTTON_NEGATIVE, text, mListener);
}
}
| true | true | public WifiDialog(Context context, DialogInterface.OnClickListener listener,
AccessPoint accessPoint, boolean edit) {
super(context);
mEdit = edit;
mListener = listener;
mAccessPoint = accessPoint;
}
| public WifiDialog(Context context, DialogInterface.OnClickListener listener,
AccessPoint accessPoint, boolean edit) {
super(context, R.style.Theme_WifiDialog);
mEdit = edit;
mListener = listener;
mAccessPoint = accessPoint;
}
|
diff --git a/src/main/java/org/primefaces/component/calendar/CalendarRenderer.java b/src/main/java/org/primefaces/component/calendar/CalendarRenderer.java
index 001b98811..2eceab585 100644
--- a/src/main/java/org/primefaces/component/calendar/CalendarRenderer.java
+++ b/src/main/java/org/primefaces/component/calendar/CalendarRenderer.java
@@ -1,231 +1,231 @@
/*
* Copyright 2009-2011 Prime Technology.
*
* 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.primefaces.component.calendar;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import org.primefaces.event.DateSelectEvent;
import org.primefaces.renderkit.InputRenderer;
import org.primefaces.util.ComponentUtils;
public class CalendarRenderer extends InputRenderer {
@Override
public void decode(FacesContext context, UIComponent component) {
Calendar calendar = (Calendar) component;
if(calendar.isDisabled() || calendar.isReadonly()) {
return;
}
decodeBehaviors(context, calendar);
String param = calendar.getClientId(context) + "_input";
String submittedValue = context.getExternalContext().getRequestParameterMap().get(param);
if(submittedValue != null) {
calendar.setSubmittedValue(submittedValue);
}
}
@Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
Calendar calendar = (Calendar) component;
String value = CalendarUtils.getValueAsString(context, calendar);
encodeMarkup(context, calendar, value);
encodeScript(context, calendar, value);
}
protected void encodeMarkup(FacesContext context, Calendar calendar, String value) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String clientId = calendar.getClientId(context);
String inputId = clientId + "_input";
boolean popup = calendar.isPopup();
writer.startElement("span", calendar);
writer.writeAttribute("id", clientId, null);
if(calendar.getStyle() != null) writer.writeAttribute("style", calendar.getStyle(), null);
if(calendar.getStyleClass() != null) writer.writeAttribute("class", calendar.getStyleClass(), null);
//inline container
if(!popup) {
writer.startElement("div", null);
writer.writeAttribute("id", clientId + "_inline", null);
writer.endElement("div");
}
//input
String type = popup ? "text" : "hidden";
writer.startElement("input", null);
writer.writeAttribute("id", inputId, null);
writer.writeAttribute("name", inputId, null);
writer.writeAttribute("type", type, null);
if(!isValueBlank(value)) {
writer.writeAttribute("value", value, null);
}
if(popup) {
String inputStyleClass = calendar.getInputStyleClass();
inputStyleClass = inputStyleClass == null ? Calendar.INPUT_STYLE_CLASS : Calendar.INPUT_STYLE_CLASS + " " + inputStyleClass;
writer.writeAttribute("class", inputStyleClass, null);
if(calendar.getInputStyle() != null) writer.writeAttribute("style", calendar.getInputStyle(), null);
if(calendar.isReadOnlyInputText()) writer.writeAttribute("readonly", "readonly", null);
if(calendar.isDisabled()) writer.writeAttribute("disabled", "disabled", null);
renderPassThruAttributes(context, calendar, Calendar.INPUT_TEXT_ATTRS);
}
writer.endElement("input");
writer.endElement("span");
}
protected void encodeScript(FacesContext context, Calendar calendar, String value) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String clientId = calendar.getClientId(context);
writer.startElement("script", null);
writer.writeAttribute("type", "text/javascript", null);
writer.write("jQuery(function(){");
writer.write(calendar.resolveWidgetVar() + " = new PrimeFaces.widget.Calendar('" + clientId + "', {");
writer.write("popup:" + calendar.isPopup());
writer.write(",locale:'" + calendar.calculateLocale(context).toString() + "'");
if(!isValueBlank(value)) writer.write(",defaultDate:'" + value + "'");
- if(calendar.getPattern() != null) writer.write(",dateFormat:'" + CalendarUtils.convertPattern(calendar.getPattern()) + "'");
+ if(calendar.getPattern() != null) writer.write(",pattern:'" + CalendarUtils.convertPattern(calendar.getPattern()) + "'");
if(calendar.getPages() != 1) writer.write(",numberOfMonths:" + calendar.getPages());
if(calendar.getMindate() != null) writer.write(",minDate:'" + CalendarUtils.getDateAsString(calendar, calendar.getMindate()) + "'");
if(calendar.getMaxdate() != null) writer.write(",maxDate:'" + CalendarUtils.getDateAsString(calendar, calendar.getMaxdate()) + "'");
if(calendar.isShowButtonPanel()) writer.write(",showButtonPanel:true");
if(calendar.isShowWeek()) writer.write(",showWeek:true");
if(calendar.isDisabled()) writer.write(",disabled:true");
if(calendar.getYearRange() != null) writer.write(",yearRange:'" + calendar.getYearRange() + "'");
if(calendar.isNavigator()) {
writer.write(",changeMonth:true");
writer.write(",changeYear:true");
}
if(calendar.getEffect() != null) {
writer.write(",showAnim:'" + calendar.getEffect() + "'");
writer.write(",duration:'" + calendar.getEffectDuration() + "'");
}
String showOn = calendar.getShowOn();
if(!showOn.equalsIgnoreCase("focus")) {
String iconSrc = calendar.getPopupIcon() != null ? getResourceURL(context, calendar.getPopupIcon()) : getResourceRequestPath(context, Calendar.POPUP_ICON);
writer.write(",showOn:'" + showOn + "'");
writer.write(",buttonImage:'" + iconSrc + "'");
writer.write(",buttonImageOnly:" + calendar.isPopupIconOnly());
}
if(calendar.isShowOtherMonths()) {
writer.write(",showOtherMonths:true");
writer.write(",selectOtherMonths:" + calendar.isSelectOtherMonths());
}
if(calendar.getSelectListener() != null) {
writer.write(",hasSelectListener:true");
String onSelectProcess = calendar.getOnSelectProcess();
onSelectProcess = onSelectProcess == null ? clientId : ComponentUtils.findClientIds(context, calendar, onSelectProcess);
writer.write(",onSelectProcess:'" + onSelectProcess + "'");
if(calendar.getOnSelectUpdate() != null) {
writer.write(",onSelectUpdate:'" + ComponentUtils.findClientIds(context, calendar, calendar.getOnSelectUpdate()) + "'");
}
}
//time
if(calendar.hasTime()) {
writer.write(",timeOnly:" + calendar.isTimeOnly());
//step
writer.write(",stepHour:" + calendar.getStepHour());
writer.write(",stepMinute:" + calendar.getStepMinute());
writer.write(",stepSecond:" + calendar.getStepSecond());
//minmax
writer.write(",hourMin:" + calendar.getMinHour());
writer.write(",hourMax:" + calendar.getMaxHour());
writer.write(",minuteMin:" + calendar.getMinMinute());
writer.write(",minuteMax:" + calendar.getMaxMinute());
writer.write(",secondMin:" + calendar.getMinSecond());
writer.write(",secondMax:" + calendar.getMaxSecond());
}
encodeClientBehaviors(context, calendar);
writer.write("});});");
writer.endElement("script");
}
@Override
public Object getConvertedValue(FacesContext context, UIComponent component, Object value) throws ConverterException {
Calendar calendar = (Calendar) component;
String submittedValue = (String) value;
Converter converter = calendar.getConverter();
if(isValueBlank(submittedValue)) {
return null;
}
//Delegate to user supplied converter if defined
if(converter != null) {
return converter.getAsObject(context, calendar, submittedValue);
}
//Use built-in converter
try {
Date convertedValue;
Locale locale = calendar.calculateLocale(context);
SimpleDateFormat format = new SimpleDateFormat(calendar.getPattern(), locale);
format.setTimeZone(calendar.calculateTimeZone());
convertedValue = format.parse(submittedValue);
if(calendar.isInstantSelection()) {
calendar.queueEvent(new DateSelectEvent(calendar, convertedValue));
}
return convertedValue;
} catch (ParseException e) {
throw new ConverterException(e);
}
}
}
| true | true | protected void encodeScript(FacesContext context, Calendar calendar, String value) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String clientId = calendar.getClientId(context);
writer.startElement("script", null);
writer.writeAttribute("type", "text/javascript", null);
writer.write("jQuery(function(){");
writer.write(calendar.resolveWidgetVar() + " = new PrimeFaces.widget.Calendar('" + clientId + "', {");
writer.write("popup:" + calendar.isPopup());
writer.write(",locale:'" + calendar.calculateLocale(context).toString() + "'");
if(!isValueBlank(value)) writer.write(",defaultDate:'" + value + "'");
if(calendar.getPattern() != null) writer.write(",dateFormat:'" + CalendarUtils.convertPattern(calendar.getPattern()) + "'");
if(calendar.getPages() != 1) writer.write(",numberOfMonths:" + calendar.getPages());
if(calendar.getMindate() != null) writer.write(",minDate:'" + CalendarUtils.getDateAsString(calendar, calendar.getMindate()) + "'");
if(calendar.getMaxdate() != null) writer.write(",maxDate:'" + CalendarUtils.getDateAsString(calendar, calendar.getMaxdate()) + "'");
if(calendar.isShowButtonPanel()) writer.write(",showButtonPanel:true");
if(calendar.isShowWeek()) writer.write(",showWeek:true");
if(calendar.isDisabled()) writer.write(",disabled:true");
if(calendar.getYearRange() != null) writer.write(",yearRange:'" + calendar.getYearRange() + "'");
if(calendar.isNavigator()) {
writer.write(",changeMonth:true");
writer.write(",changeYear:true");
}
if(calendar.getEffect() != null) {
writer.write(",showAnim:'" + calendar.getEffect() + "'");
writer.write(",duration:'" + calendar.getEffectDuration() + "'");
}
String showOn = calendar.getShowOn();
if(!showOn.equalsIgnoreCase("focus")) {
String iconSrc = calendar.getPopupIcon() != null ? getResourceURL(context, calendar.getPopupIcon()) : getResourceRequestPath(context, Calendar.POPUP_ICON);
writer.write(",showOn:'" + showOn + "'");
writer.write(",buttonImage:'" + iconSrc + "'");
writer.write(",buttonImageOnly:" + calendar.isPopupIconOnly());
}
if(calendar.isShowOtherMonths()) {
writer.write(",showOtherMonths:true");
writer.write(",selectOtherMonths:" + calendar.isSelectOtherMonths());
}
if(calendar.getSelectListener() != null) {
writer.write(",hasSelectListener:true");
String onSelectProcess = calendar.getOnSelectProcess();
onSelectProcess = onSelectProcess == null ? clientId : ComponentUtils.findClientIds(context, calendar, onSelectProcess);
writer.write(",onSelectProcess:'" + onSelectProcess + "'");
if(calendar.getOnSelectUpdate() != null) {
writer.write(",onSelectUpdate:'" + ComponentUtils.findClientIds(context, calendar, calendar.getOnSelectUpdate()) + "'");
}
}
//time
if(calendar.hasTime()) {
writer.write(",timeOnly:" + calendar.isTimeOnly());
//step
writer.write(",stepHour:" + calendar.getStepHour());
writer.write(",stepMinute:" + calendar.getStepMinute());
writer.write(",stepSecond:" + calendar.getStepSecond());
//minmax
writer.write(",hourMin:" + calendar.getMinHour());
writer.write(",hourMax:" + calendar.getMaxHour());
writer.write(",minuteMin:" + calendar.getMinMinute());
writer.write(",minuteMax:" + calendar.getMaxMinute());
writer.write(",secondMin:" + calendar.getMinSecond());
writer.write(",secondMax:" + calendar.getMaxSecond());
}
encodeClientBehaviors(context, calendar);
writer.write("});});");
writer.endElement("script");
}
| protected void encodeScript(FacesContext context, Calendar calendar, String value) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String clientId = calendar.getClientId(context);
writer.startElement("script", null);
writer.writeAttribute("type", "text/javascript", null);
writer.write("jQuery(function(){");
writer.write(calendar.resolveWidgetVar() + " = new PrimeFaces.widget.Calendar('" + clientId + "', {");
writer.write("popup:" + calendar.isPopup());
writer.write(",locale:'" + calendar.calculateLocale(context).toString() + "'");
if(!isValueBlank(value)) writer.write(",defaultDate:'" + value + "'");
if(calendar.getPattern() != null) writer.write(",pattern:'" + CalendarUtils.convertPattern(calendar.getPattern()) + "'");
if(calendar.getPages() != 1) writer.write(",numberOfMonths:" + calendar.getPages());
if(calendar.getMindate() != null) writer.write(",minDate:'" + CalendarUtils.getDateAsString(calendar, calendar.getMindate()) + "'");
if(calendar.getMaxdate() != null) writer.write(",maxDate:'" + CalendarUtils.getDateAsString(calendar, calendar.getMaxdate()) + "'");
if(calendar.isShowButtonPanel()) writer.write(",showButtonPanel:true");
if(calendar.isShowWeek()) writer.write(",showWeek:true");
if(calendar.isDisabled()) writer.write(",disabled:true");
if(calendar.getYearRange() != null) writer.write(",yearRange:'" + calendar.getYearRange() + "'");
if(calendar.isNavigator()) {
writer.write(",changeMonth:true");
writer.write(",changeYear:true");
}
if(calendar.getEffect() != null) {
writer.write(",showAnim:'" + calendar.getEffect() + "'");
writer.write(",duration:'" + calendar.getEffectDuration() + "'");
}
String showOn = calendar.getShowOn();
if(!showOn.equalsIgnoreCase("focus")) {
String iconSrc = calendar.getPopupIcon() != null ? getResourceURL(context, calendar.getPopupIcon()) : getResourceRequestPath(context, Calendar.POPUP_ICON);
writer.write(",showOn:'" + showOn + "'");
writer.write(",buttonImage:'" + iconSrc + "'");
writer.write(",buttonImageOnly:" + calendar.isPopupIconOnly());
}
if(calendar.isShowOtherMonths()) {
writer.write(",showOtherMonths:true");
writer.write(",selectOtherMonths:" + calendar.isSelectOtherMonths());
}
if(calendar.getSelectListener() != null) {
writer.write(",hasSelectListener:true");
String onSelectProcess = calendar.getOnSelectProcess();
onSelectProcess = onSelectProcess == null ? clientId : ComponentUtils.findClientIds(context, calendar, onSelectProcess);
writer.write(",onSelectProcess:'" + onSelectProcess + "'");
if(calendar.getOnSelectUpdate() != null) {
writer.write(",onSelectUpdate:'" + ComponentUtils.findClientIds(context, calendar, calendar.getOnSelectUpdate()) + "'");
}
}
//time
if(calendar.hasTime()) {
writer.write(",timeOnly:" + calendar.isTimeOnly());
//step
writer.write(",stepHour:" + calendar.getStepHour());
writer.write(",stepMinute:" + calendar.getStepMinute());
writer.write(",stepSecond:" + calendar.getStepSecond());
//minmax
writer.write(",hourMin:" + calendar.getMinHour());
writer.write(",hourMax:" + calendar.getMaxHour());
writer.write(",minuteMin:" + calendar.getMinMinute());
writer.write(",minuteMax:" + calendar.getMaxMinute());
writer.write(",secondMin:" + calendar.getMinSecond());
writer.write(",secondMax:" + calendar.getMaxSecond());
}
encodeClientBehaviors(context, calendar);
writer.write("});});");
writer.endElement("script");
}
|
diff --git a/src/api/org/openmrs/util/OpenmrsConstants.java b/src/api/org/openmrs/util/OpenmrsConstants.java
index e627d1d2..e93c0b37 100644
--- a/src/api/org/openmrs/util/OpenmrsConstants.java
+++ b/src/api/org/openmrs/util/OpenmrsConstants.java
@@ -1,1153 +1,1151 @@
/**
* 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.util;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Vector;
import org.openmrs.GlobalProperty;
import org.openmrs.Privilege;
import org.openmrs.api.ConceptService;
import org.openmrs.module.ModuleConstants;
import org.openmrs.module.ModuleFactory;
import org.openmrs.patient.impl.LuhnIdentifierValidator;
import org.openmrs.scheduler.SchedulerConstants;
/**
* Constants used in OpenMRS. Contents built from build properties (version, version_short, and
* expected_database). Some are set at runtime (database, database version). This file should
* contain all privilege names and global property names. Those strings added to the static CORE_*
* methods will be written to the database at startup if they don't exist yet.
*/
public final class OpenmrsConstants {
//private static Log log = LogFactory.getLog(OpenmrsConstants.class);
/**
* This is the hard coded primary key of the order type for DRUG. This has to be done because
* some logic in the API acts on this order type
*/
public static final int ORDERTYPE_DRUG = 2;
/**
* This is the hard coded primary key of the concept class for DRUG. This has to be done because
* some logic in the API acts on this concept class
*/
public static final int CONCEPT_CLASS_DRUG = 3;
/**
* hack alert: During an ant build, the openmrs api jar manifest file is loaded with these
* values. When constructing the OpenmrsConstants class file, the api jar is read and the values
* are copied in as constants
*/
private static final Package THIS_PACKAGE = OpenmrsConstants.class.getPackage();
public static final String OPENMRS_VERSION = THIS_PACKAGE.getSpecificationVendor();
public static final String OPENMRS_VERSION_SHORT = THIS_PACKAGE.getSpecificationVersion();
/**
* See {@link DatabaseUpdater#updatesRequired()} to see what changesets in the
* liquibase-update-to-latest.xml file in the openmrs api jar file need to be run to bring the
* db up to date with what the api requires.
*
* @deprecated the database doesn't have just one main version now that we are using liquibase.
*/
public static final String DATABASE_VERSION_EXPECTED = THIS_PACKAGE.getImplementationVersion();
public static String DATABASE_NAME = "openmrs";
public static String DATABASE_BUSINESS_NAME = "openmrs";
/**
* See {@link DatabaseUpdater#updatesRequired()} to see what changesets in the
* liquibase-update-to-latest.xml file in the openmrs api jar file need to be run to bring the
* db up to date with what the api requires.
*
* @deprecated the database doesn't have just one main version now that we are using liquibase.
*/
public static String DATABASE_VERSION = null;
/**
* Set true from runtime configuration to obscure patients for system demonstrations
*/
public static boolean OBSCURE_PATIENTS = false;
public static String OBSCURE_PATIENTS_GIVEN_NAME = "Demo";
public static String OBSCURE_PATIENTS_MIDDLE_NAME = null;
public static String OBSCURE_PATIENTS_FAMILY_NAME = "Person";
public static final String REGEX_LARGE = "[!\"#\\$%&'\\(\\)\\*,+-\\./:;<=>\\?@\\[\\\\\\\\\\]^_`{\\|}~]";
public static final String REGEX_SMALL = "[!\"#\\$%&'\\(\\)\\*,\\./:;<=>\\?@\\[\\\\\\\\\\]^_`{\\|}~]";
public static final Integer CIVIL_STATUS_CONCEPT_ID = 1054;
/**
* The directory that will store filesystem data about openmrs like module omods, generated data
* exports, etc. This shouldn't be accessed directory, the
* OpenmrsUtil.getApplicationDataDirectory() should be used. This should be null here. This
* constant will hold the value of the user's runtime property for the
* application_data_directory and is set programmatically at startup. This value is set in the
* openmrs startup method If this is null, the getApplicationDataDirectory() uses some OS
* heuristics to determine where to put an app data dir.
*
* @see #APPLICATION_DATA_DIRECTORY_RUNTIME_PROPERTY
* @see OpenmrsUtil.getApplicationDataDirectory()
* @see OpenmrsUtil.startup(java.util.Properties);
*/
public static String APPLICATION_DATA_DIRECTORY = null;
/**
* The name of the runtime property that a user can set that will specify where openmrs's
* application directory is
*
* @see #APPLICATION_DATA_DIRECTORY
*/
public static String APPLICATION_DATA_DIRECTORY_RUNTIME_PROPERTY = "application_data_directory";
/**
* The name of the runtime property that a user can set that will specify whether the database
* is automatically updated on startup
*/
public static String AUTO_UPDATE_DATABASE_RUNTIME_PROPERTY = "auto_update_database";
/**
* These words are ignored in concept and patient searches
*
* @return
*/
public static final Collection<String> STOP_WORDS() {
List<String> stopWords = new Vector<String>();
stopWords.add("A");
stopWords.add("AND");
stopWords.add("AT");
stopWords.add("BUT");
stopWords.add("BY");
stopWords.add("FOR");
stopWords.add("HAS");
stopWords.add("OF");
stopWords.add("THE");
stopWords.add("TO");
return stopWords;
}
/**
* A gender character to gender name map TODO issues with localization. How should this be
* handled?
*
* @return
*/
public static final Map<String, String> GENDER() {
Map<String, String> genders = new LinkedHashMap<String, String>();
genders.put("M", "Male");
genders.put("F", "Female");
return genders;
}
// Baked in Privileges:
public static final String PRIV_VIEW_CONCEPTS = "View Concepts";
public static final String PRIV_MANAGE_CONCEPTS = "Manage Concepts";
public static final String PRIV_PURGE_CONCEPTS = "Purge Concepts";
public static final String PRIV_VIEW_CONCEPT_PROPOSALS = "View Concept Proposals";
public static final String PRIV_ADD_CONCEPT_PROPOSALS = "Add Concept Proposals";
public static final String PRIV_EDIT_CONCEPT_PROPOSALS = "Edit Concept Proposals";
public static final String PRIV_DELETE_CONCEPT_PROPOSALS = "Delete Concept Proposals";
public static final String PRIV_PURGE_CONCEPT_PROPOSALS = "Purge Concept Proposals";
public static final String PRIV_VIEW_USERS = "View Users";
public static final String PRIV_ADD_USERS = "Add Users";
public static final String PRIV_EDIT_USERS = "Edit Users";
public static final String PRIV_DELETE_USERS = "Delete Users";
public static final String PRIV_PURGE_USERS = "Purge Users";
public static final String PRIV_EDIT_USER_PASSWORDS = "Edit User Passwords";
public static final String PRIV_VIEW_ENCOUNTERS = "View Encounters";
public static final String PRIV_ADD_ENCOUNTERS = "Add Encounters";
public static final String PRIV_EDIT_ENCOUNTERS = "Edit Encounters";
public static final String PRIV_DELETE_ENCOUNTERS = "Delete Encounters";
public static final String PRIV_PURGE_ENCOUNTERS = "Purge Encounters";
public static final String PRIV_VIEW_ENCOUNTER_TYPES = "View Encounter Types";
public static final String PRIV_MANAGE_ENCOUNTER_TYPES = "Manage Encounter Types";
public static final String PRIV_PURGE_ENCOUNTER_TYPES = "Purge Encounter Types";
public static final String PRIV_VIEW_LOCATIONS = "View Locations";
public static final String PRIV_MANAGE_LOCATIONS = "Manage Locations";
public static final String PRIV_PURGE_LOCATIONS = "Purge Locations";
public static final String PRIV_MANAGE_LOCATION_TAGS = "Manage Location Tags";
public static final String PRIV_PURGE_LOCATION_TAGS = "Purge Location Tags";
public static final String PRIV_VIEW_OBS = "View Observations";
public static final String PRIV_ADD_OBS = "Add Observations";
public static final String PRIV_EDIT_OBS = "Edit Observations";
public static final String PRIV_DELETE_OBS = "Delete Observations";
public static final String PRIV_PURGE_OBS = "Purge Observations";
@Deprecated
public static final String PRIV_VIEW_MIME_TYPES = "View Mime Types";
@Deprecated
public static final String PRIV_PURGE_MIME_TYPES = "Purge Mime Types";
public static final String PRIV_VIEW_PATIENTS = "View Patients";
public static final String PRIV_ADD_PATIENTS = "Add Patients";
public static final String PRIV_EDIT_PATIENTS = "Edit Patients";
public static final String PRIV_DELETE_PATIENTS = "Delete Patients";
public static final String PRIV_PURGE_PATIENTS = "Purge Patients";
public static final String PRIV_VIEW_PATIENT_IDENTIFIERS = "View Patient Identifiers";
public static final String PRIV_ADD_PATIENT_IDENTIFIERS = "Add Patient Identifiers";
public static final String PRIV_EDIT_PATIENT_IDENTIFIERS = "Edit Patient Identifiers";
public static final String PRIV_DELETE_PATIENT_IDENTIFIERS = "Delete Patient Identifiers";
public static final String PRIV_PURGE_PATIENT_IDENTIFIERS = "Purge Patient Identifiers";
public static final String PRIV_VIEW_PATIENT_COHORTS = "View Patient Cohorts";
public static final String PRIV_ADD_COHORTS = "Add Cohorts";
public static final String PRIV_EDIT_COHORTS = "Edit Cohorts";
public static final String PRIV_DELETE_COHORTS = "Delete Cohorts";
public static final String PRIV_PURGE_COHORTS = "Purge Cohorts";
public static final String PRIV_VIEW_ORDERS = "View Orders";
public static final String PRIV_ADD_ORDERS = "Add Orders";
public static final String PRIV_EDIT_ORDERS = "Edit Orders";
public static final String PRIV_DELETE_ORDERS = "Delete Orders";
public static final String PRIV_PURGE_ORDERS = "Purge Orders";
public static final String PRIV_VIEW_FORMS = "View Forms";
public static final String PRIV_MANAGE_FORMS = "Manage Forms";
public static final String PRIV_PURGE_FORMS = "Purge Forms";
public static final String PRIV_VIEW_REPORTS = "View Reports";
public static final String PRIV_ADD_REPORTS = "Add Reports";
public static final String PRIV_EDIT_REPORTS = "Edit Reports";
public static final String PRIV_DELETE_REPORTS = "Delete Reports";
public static final String PRIV_RUN_REPORTS = "Run Reports";
public static final String PRIV_VIEW_REPORT_OBJECTS = "View Report Objects";
public static final String PRIV_ADD_REPORT_OBJECTS = "Add Report Objects";
public static final String PRIV_EDIT_REPORT_OBJECTS = "Edit Report Objects";
public static final String PRIV_DELETE_REPORT_OBJECTS = "Delete Report Objects";
public static final String PRIV_MANAGE_IDENTIFIER_TYPES = "Manage Identifier Types";
public static final String PRIV_VIEW_IDENTIFIER_TYPES = "View Identifier Types";
public static final String PRIV_PURGE_IDENTIFIER_TYPES = "Purge Identifier Types";
@Deprecated
public static final String PRIV_MANAGE_MIME_TYPES = "Manage Mime Types";
public static final String PRIV_VIEW_CONCEPT_CLASSES = "View Concept Classes";
public static final String PRIV_MANAGE_CONCEPT_CLASSES = "Manage Concept Classes";
public static final String PRIV_PURGE_CONCEPT_CLASSES = "Purge Concept Classes";
public static final String PRIV_VIEW_CONCEPT_DATATYPES = "View Concept Datatypes";
public static final String PRIV_MANAGE_CONCEPT_DATATYPES = "Manage Concept Datatypes";
public static final String PRIV_PURGE_CONCEPT_DATATYPES = "Purge Concept Datatypes";
public static final String PRIV_VIEW_PRIVILEGES = "View Privileges";
public static final String PRIV_MANAGE_PRIVILEGES = "Manage Privileges";
public static final String PRIV_PURGE_PRIVILEGES = "Purge Privileges";
public static final String PRIV_VIEW_ROLES = "View Roles";
public static final String PRIV_MANAGE_ROLES = "Manage Roles";
public static final String PRIV_PURGE_ROLES = "Purge Roles";
public static final String PRIV_VIEW_FIELD_TYPES = "View Field Types";
public static final String PRIV_MANAGE_FIELD_TYPES = "Manage Field Types";
public static final String PRIV_PURGE_FIELD_TYPES = "Purge Field Types";
public static final String PRIV_VIEW_ORDER_TYPES = "View Order Types";
public static final String PRIV_MANAGE_ORDER_TYPES = "Manage Order Types";
public static final String PRIV_PURGE_ORDER_TYPES = "Purge Order Types";
public static final String PRIV_VIEW_RELATIONSHIP_TYPES = "View Relationship Types";
public static final String PRIV_MANAGE_RELATIONSHIP_TYPES = "Manage Relationship Types";
public static final String PRIV_PURGE_RELATIONSHIP_TYPES = "Purge Relationship Types";
public static final String PRIV_MANAGE_ALERTS = "Manage Alerts";
public static final String PRIV_MANAGE_CONCEPT_SOURCES = "Manage Concept Sources";
public static final String PRIV_VIEW_CONCEPT_SOURCES = "View Concept Sources";
public static final String PRIV_PURGE_CONCEPT_SOURCES = "Purge Concept Sources";
public static final String PRIV_VIEW_NAVIGATION_MENU = "View Navigation Menu";
public static final String PRIV_VIEW_ADMIN_FUNCTIONS = "View Administration Functions";
public static final String PRIV_VIEW_UNPUBLISHED_FORMS = "View Unpublished Forms";
public static final String PRIV_VIEW_PROGRAMS = "View Programs";
public static final String PRIV_MANAGE_PROGRAMS = "Manage Programs";
public static final String PRIV_VIEW_PATIENT_PROGRAMS = "View Patient Programs";
public static final String PRIV_ADD_PATIENT_PROGRAMS = "Add Patient Programs";
public static final String PRIV_EDIT_PATIENT_PROGRAMS = "Edit Patient Programs";
public static final String PRIV_DELETE_PATIENT_PROGRAMS = "Delete Patient Programs";
public static final String PRIV_PURGE_PATIENT_PROGRAMS = "Add Patient Programs";
public static final String PRIV_DASHBOARD_OVERVIEW = "Patient Dashboard - View Overview Section";
public static final String PRIV_DASHBOARD_REGIMEN = "Patient Dashboard - View Regimen Section";
public static final String PRIV_DASHBOARD_ENCOUNTERS = "Patient Dashboard - View Encounters Section";
public static final String PRIV_DASHBOARD_DEMOGRAPHICS = "Patient Dashboard - View Demographics Section";
public static final String PRIV_DASHBOARD_GRAPHS = "Patient Dashboard - View Graphs Section";
public static final String PRIV_DASHBOARD_FORMS = "Patient Dashboard - View Forms Section";
public static final String PRIV_DASHBOARD_SUMMARY = "Patient Dashboard - View Patient Summary";
public static final String PRIV_VIEW_GLOBAL_PROPERTIES = "View Global Properties";
public static final String PRIV_MANAGE_GLOBAL_PROPERTIES = "Manage Global Properties";
public static final String PRIV_PURGE_GLOBAL_PROPERTIES = "Purge Global Properties";
public static final String PRIV_MANAGE_MODULES = "Manage Modules";
public static final String PRIV_MANAGE_SCHEDULER = "Manage Scheduler";
public static final String PRIV_VIEW_PERSON_ATTRIBUTE_TYPES = "View Person Attribute Types";
public static final String PRIV_MANAGE_PERSON_ATTRIBUTE_TYPES = "Manage Person Attribute Types";
public static final String PRIV_PURGE_PERSON_ATTRIBUTE_TYPES = "Purge Person Attribute Types";
public static final String PRIV_VIEW_PERSONS = "View People";
public static final String PRIV_ADD_PERSONS = "Add People";
public static final String PRIV_EDIT_PERSONS = "Edit People";
public static final String PRIV_DELETE_PERSONS = "Delete People";
public static final String PRIV_PURGE_PERSONS = "Purge People";
/**
* @deprecated replacing with ADD/EDIT/DELETE privileges
*/
public static final String PRIV_MANAGE_RELATIONSHIPS = "Manage Relationships";
public static final String PRIV_VIEW_RELATIONSHIPS = "View Relationships";
public static final String PRIV_ADD_RELATIONSHIPS = "Add Relationships";
public static final String PRIV_EDIT_RELATIONSHIPS = "Edit Relationships";
public static final String PRIV_DELETE_RELATIONSHIPS = "Delete Relationships";
public static final String PRIV_PURGE_RELATIONSHIPS = "Purge Relationships";
public static final String PRIV_VIEW_DATAENTRY_STATS = "View Data Entry Statistics";
public static final String PRIV_VIEW_DATABASE_CHANGES = "View Database Changes";
/**
* Cached list of core privileges
*/
private static Map<String, String> CORE_PRIVILEGES = null;
/**
* These are the privileges that are required by OpenMRS. Upon startup, if any of these
* privileges do not exist in the database, they are inserted. These privileges are not allowed
* to be deleted. They are marked as 'locked' in the administration screens.
*
* @return privileges core to the system
*/
public static final Map<String, String> CORE_PRIVILEGES() {
// if we don't have a cache, create one
if (CORE_PRIVILEGES == null) {
CORE_PRIVILEGES = new HashMap<String, String>();
CORE_PRIVILEGES.put(PRIV_VIEW_PROGRAMS, "Able to view patient programs");
CORE_PRIVILEGES.put(PRIV_MANAGE_PROGRAMS, "Able to add/view/delete patient programs");
CORE_PRIVILEGES.put(PRIV_VIEW_PATIENT_PROGRAMS, "Able to see which programs that patients are in");
CORE_PRIVILEGES.put(PRIV_ADD_PATIENT_PROGRAMS, "Able to add patients to programs");
CORE_PRIVILEGES.put(PRIV_EDIT_PATIENT_PROGRAMS, "Able to edit patients in programs");
CORE_PRIVILEGES.put(PRIV_DELETE_PATIENT_PROGRAMS, "Able to delete patients from programs");
CORE_PRIVILEGES.put(PRIV_VIEW_UNPUBLISHED_FORMS, "Able to view and fill out unpublished forms");
CORE_PRIVILEGES.put(PRIV_VIEW_CONCEPTS, "Able to view concept entries");
CORE_PRIVILEGES.put(PRIV_MANAGE_CONCEPTS, "Able to add/edit/delete concept entries");
CORE_PRIVILEGES.put(PRIV_VIEW_CONCEPT_PROPOSALS, "Able to view concept proposals to the system");
CORE_PRIVILEGES.put(PRIV_ADD_CONCEPT_PROPOSALS, "Able to add concept proposals to the system");
CORE_PRIVILEGES.put(PRIV_EDIT_CONCEPT_PROPOSALS, "Able to edit concept proposals in the system");
CORE_PRIVILEGES.put(PRIV_DELETE_CONCEPT_PROPOSALS, "Able to delete concept proposals from the system");
CORE_PRIVILEGES.put(PRIV_VIEW_USERS, "Able to view users in OpenMRS");
CORE_PRIVILEGES.put(PRIV_ADD_USERS, "Able to add users to OpenMRS");
CORE_PRIVILEGES.put(PRIV_EDIT_USERS, "Able to edit users in OpenMRS");
CORE_PRIVILEGES.put(PRIV_DELETE_USERS, "Able to delete users in OpenMRS");
CORE_PRIVILEGES.put(PRIV_EDIT_USER_PASSWORDS, "Able to change the passwords of users in OpenMRS");
CORE_PRIVILEGES.put(PRIV_VIEW_ENCOUNTERS, "Able to view patient encounters");
CORE_PRIVILEGES.put(PRIV_ADD_ENCOUNTERS, "Able to add patient encounters");
CORE_PRIVILEGES.put(PRIV_EDIT_ENCOUNTERS, "Able to edit patient encounters");
CORE_PRIVILEGES.put(PRIV_DELETE_ENCOUNTERS, "Able to delete patient encounters");
CORE_PRIVILEGES.put(PRIV_VIEW_OBS, "Able to view patient observations");
CORE_PRIVILEGES.put(PRIV_ADD_OBS, "Able to add patient observations");
CORE_PRIVILEGES.put(PRIV_EDIT_OBS, "Able to edit patient observations");
CORE_PRIVILEGES.put(PRIV_DELETE_OBS, "Able to delete patient observations");
CORE_PRIVILEGES.put(PRIV_VIEW_PATIENTS, "Able to view patients");
CORE_PRIVILEGES.put(PRIV_ADD_PATIENTS, "Able to add patients");
CORE_PRIVILEGES.put(PRIV_EDIT_PATIENTS, "Able to edit patients");
CORE_PRIVILEGES.put(PRIV_DELETE_PATIENTS, "Able to delete patients");
CORE_PRIVILEGES.put(PRIV_VIEW_PATIENT_IDENTIFIERS, "Able to view patient identifiers");
CORE_PRIVILEGES.put(PRIV_ADD_PATIENT_IDENTIFIERS, "Able to add patient identifiers");
CORE_PRIVILEGES.put(PRIV_EDIT_PATIENT_IDENTIFIERS, "Able to edit patient identifiers");
CORE_PRIVILEGES.put(PRIV_DELETE_PATIENT_IDENTIFIERS, "Able to delete patient identifiers");
CORE_PRIVILEGES.put(PRIV_VIEW_PATIENT_COHORTS, "Able to view patient cohorts");
CORE_PRIVILEGES.put(PRIV_ADD_COHORTS, "Able to add a cohort to the system");
CORE_PRIVILEGES.put(PRIV_EDIT_COHORTS, "Able to add a cohort to the system");
CORE_PRIVILEGES.put(PRIV_DELETE_COHORTS, "Able to add a cohort to the system");
CORE_PRIVILEGES.put(PRIV_VIEW_ORDERS, "Able to view orders");
CORE_PRIVILEGES.put(PRIV_ADD_ORDERS, "Able to add orders");
CORE_PRIVILEGES.put(PRIV_EDIT_ORDERS, "Able to edit orders");
CORE_PRIVILEGES.put(PRIV_DELETE_ORDERS, "Able to delete orders");
CORE_PRIVILEGES.put(PRIV_VIEW_FORMS, "Able to view forms");
CORE_PRIVILEGES.put(PRIV_MANAGE_FORMS, "Able to add/edit/delete forms");
CORE_PRIVILEGES.put(PRIV_VIEW_REPORTS, "Able to view reports");
CORE_PRIVILEGES.put(PRIV_ADD_REPORTS, "Able to add reports");
CORE_PRIVILEGES.put(PRIV_EDIT_REPORTS, "Able to edit reports");
CORE_PRIVILEGES.put(PRIV_DELETE_REPORTS, "Able to delete reports");
CORE_PRIVILEGES.put(PRIV_RUN_REPORTS, "Able to run reports");
CORE_PRIVILEGES.put(PRIV_VIEW_REPORT_OBJECTS, "Able to view report objects");
CORE_PRIVILEGES.put(PRIV_ADD_REPORT_OBJECTS, "Able to add report objects");
CORE_PRIVILEGES.put(PRIV_EDIT_REPORT_OBJECTS, "Able to edit report objects");
CORE_PRIVILEGES.put(PRIV_DELETE_REPORT_OBJECTS, "Able to delete report objects");
CORE_PRIVILEGES.put(PRIV_VIEW_IDENTIFIER_TYPES, "Able to view patient identifier types");
CORE_PRIVILEGES.put(PRIV_MANAGE_RELATIONSHIPS, "Able to add/edit/delete relationships");
CORE_PRIVILEGES.put(PRIV_MANAGE_IDENTIFIER_TYPES, "Able to add/edit/delete patient identifier types");
CORE_PRIVILEGES.put(PRIV_VIEW_LOCATIONS, "Able to view locations");
CORE_PRIVILEGES.put(PRIV_MANAGE_LOCATIONS, "Able to add/edit/delete locations");
CORE_PRIVILEGES.put(PRIV_MANAGE_LOCATION_TAGS, "Able to add/edit/delete location tags");
CORE_PRIVILEGES.put(PRIV_VIEW_CONCEPT_CLASSES, "Able to view concept classes");
CORE_PRIVILEGES.put(PRIV_MANAGE_CONCEPT_CLASSES, "Able to add/edit/retire concept classes");
CORE_PRIVILEGES.put(PRIV_VIEW_CONCEPT_DATATYPES, "Able to view concept datatypes");
CORE_PRIVILEGES.put(PRIV_MANAGE_CONCEPT_DATATYPES, "Able to add/edit/retire concept datatypes");
CORE_PRIVILEGES.put(PRIV_VIEW_ENCOUNTER_TYPES, "Able to view encounter types");
CORE_PRIVILEGES.put(PRIV_MANAGE_ENCOUNTER_TYPES, "Able to add/edit/delete encounter types");
CORE_PRIVILEGES.put(PRIV_VIEW_PRIVILEGES, "Able to view user privileges");
CORE_PRIVILEGES.put(PRIV_MANAGE_PRIVILEGES, "Able to add/edit/delete privileges");
CORE_PRIVILEGES.put(PRIV_VIEW_FIELD_TYPES, "Able to view field types");
CORE_PRIVILEGES.put(PRIV_MANAGE_FIELD_TYPES, "Able to add/edit/retire field types");
CORE_PRIVILEGES.put(PRIV_PURGE_FIELD_TYPES, "Able to purge field types");
CORE_PRIVILEGES.put(PRIV_MANAGE_ORDER_TYPES, "Able to add/edit/retire order types");
CORE_PRIVILEGES.put(PRIV_VIEW_ORDER_TYPES, "Able to view order types");
CORE_PRIVILEGES.put(PRIV_VIEW_RELATIONSHIP_TYPES, "Able to view relationship types");
CORE_PRIVILEGES.put(PRIV_MANAGE_RELATIONSHIP_TYPES, "Able to add/edit/retire relationship types");
CORE_PRIVILEGES.put(PRIV_MANAGE_ALERTS, "Able to add/edit/delete user alerts");
CORE_PRIVILEGES.put(PRIV_MANAGE_CONCEPT_SOURCES, "Able to add/edit/delete concept sources");
CORE_PRIVILEGES.put(PRIV_VIEW_CONCEPT_SOURCES, "Able to view concept sources");
CORE_PRIVILEGES.put(PRIV_VIEW_ROLES, "Able to view user roles");
CORE_PRIVILEGES.put(PRIV_MANAGE_ROLES, "Able to add/edit/delete user roles");
CORE_PRIVILEGES.put(PRIV_VIEW_NAVIGATION_MENU,
"Able to view the navigation menu (Home, View Patients, Dictionary, Administration, My Profile)");
CORE_PRIVILEGES.put(PRIV_VIEW_ADMIN_FUNCTIONS, "Able to view the 'Administration' link in the navigation bar");
CORE_PRIVILEGES.put(PRIV_DASHBOARD_OVERVIEW, "Able to view the 'Overview' tab on the patient dashboard");
CORE_PRIVILEGES.put(PRIV_DASHBOARD_REGIMEN, "Able to view the 'Regimen' tab on the patient dashboard");
CORE_PRIVILEGES.put(PRIV_DASHBOARD_ENCOUNTERS, "Able to view the 'Encounters' tab on the patient dashboard");
CORE_PRIVILEGES.put(PRIV_DASHBOARD_DEMOGRAPHICS, "Able to view the 'Demographics' tab on the patient dashboard");
CORE_PRIVILEGES.put(PRIV_DASHBOARD_GRAPHS, "Able to view the 'Graphs' tab on the patient dashboard");
CORE_PRIVILEGES.put(PRIV_DASHBOARD_FORMS, "Able to view the 'Forms' tab on the patient dashboard");
CORE_PRIVILEGES.put(PRIV_DASHBOARD_SUMMARY, "Able to view the 'Summary' tab on the patient dashboard");
CORE_PRIVILEGES.put(PRIV_VIEW_GLOBAL_PROPERTIES, "Able to view global properties on the administration screen");
CORE_PRIVILEGES.put(PRIV_MANAGE_GLOBAL_PROPERTIES, "Able to add/edit global properties");
CORE_PRIVILEGES.put(PRIV_MANAGE_MODULES, "Able to add/remove modules to the system");
CORE_PRIVILEGES.put(PRIV_MANAGE_SCHEDULER, "Able to add/edit/remove scheduled tasks");
CORE_PRIVILEGES.put(PRIV_VIEW_PERSON_ATTRIBUTE_TYPES, "Able to view person attribute types");
CORE_PRIVILEGES.put(PRIV_MANAGE_PERSON_ATTRIBUTE_TYPES, "Able to add/edit/delete person attribute types");
CORE_PRIVILEGES.put(PRIV_VIEW_PERSONS, "Able to view person objects");
CORE_PRIVILEGES.put(PRIV_ADD_PERSONS, "Able to add person objects");
CORE_PRIVILEGES.put(PRIV_EDIT_PERSONS, "Able to edit person objects");
CORE_PRIVILEGES.put(PRIV_DELETE_PERSONS, "Able to delete objects");
CORE_PRIVILEGES.put(PRIV_VIEW_RELATIONSHIPS, "Able to view relationships");
CORE_PRIVILEGES.put(PRIV_ADD_RELATIONSHIPS, "Able to add relationships");
CORE_PRIVILEGES.put(PRIV_EDIT_RELATIONSHIPS, "Able to edit relationships");
CORE_PRIVILEGES.put(PRIV_DELETE_RELATIONSHIPS, "Able to delete relationships");
CORE_PRIVILEGES.put(PRIV_VIEW_DATAENTRY_STATS, "Able to view data entry statistics from the admin screen");
CORE_PRIVILEGES.put(PRIV_VIEW_DATABASE_CHANGES, "Able to view database changes from the admin screen");
}
// always add the module core privileges back on
for (Privilege privilege : ModuleFactory.getPrivileges()) {
CORE_PRIVILEGES.put(privilege.getPrivilege(), privilege.getDescription());
}
return CORE_PRIVILEGES;
}
// Baked in Roles:
public static final String SUPERUSER_ROLE = "System Developer";
public static final String ANONYMOUS_ROLE = "Anonymous";
public static final String AUTHENTICATED_ROLE = "Authenticated";
public static final String PROVIDER_ROLE = "Provider";
/**
* All roles returned by this method are inserted into the database if they do not exist
* already. These roles are also forbidden to be deleted from the administration screens.
*
* @return roles that are core to the system
*/
public static final Map<String, String> CORE_ROLES() {
Map<String, String> roles = new HashMap<String, String>();
roles
.put(SUPERUSER_ROLE,
"Assigned to developers of OpenMRS. Gives additional access to change fundamental structure of the database model.");
roles.put(ANONYMOUS_ROLE, "Privileges for non-authenticated users.");
roles.put(AUTHENTICATED_ROLE, "Privileges gained once authentication has been established.");
roles.put(PROVIDER_ROLE, "All users with the 'Provider' role will appear as options in the default Infopath ");
return roles;
}
/**
* These roles are given to a user automatically and cannot be assigned
*
* @return
*/
public static final Collection<String> AUTO_ROLES() {
List<String> roles = new Vector<String>();
roles.add(ANONYMOUS_ROLE);
roles.add(AUTHENTICATED_ROLE);
return roles;
}
public static final String GLOBAL_PROPERTY_CONCEPTS_LOCKED = "concepts.locked";
public static final String GLOBAL_PROPERTY_PATIENT_LISTING_ATTRIBUTES = "patient.listingAttributeTypes";
public static final String GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES = "patient.viewingAttributeTypes";
public static final String GLOBAL_PROPERTY_PATIENT_HEADER_ATTRIBUTES = "patient.headerAttributeTypes";
public static final String GLOBAL_PROPERTY_USER_LISTING_ATTRIBUTES = "user.listingAttributeTypes";
public static final String GLOBAL_PROPERTY_USER_VIEWING_ATTRIBUTES = "user.viewingAttributeTypes";
public static final String GLOBAL_PROPERTY_USER_HEADER_ATTRIBUTES = "user.headerAttributeTypes";
public static final String GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX = "patient.identifierRegex";
public static final String GLOBAL_PROPERTY_PATIENT_IDENTIFIER_PREFIX = "patient.identifierPrefix";
public static final String GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SUFFIX = "patient.identifierSuffix";
public static final String GLOBAL_PROPERTY_PATIENT_SEARCH_MAX_RESULTS = "patient.searchMaxResults";
public static final String GLOBAL_PROPERTY_GZIP_ENABLED = "gzip.enabled";
public static final String GLOBAL_PROPERTY_MEDICAL_RECORD_OBSERVATIONS = "concept.medicalRecordObservations";
public static final String GLOBAL_PROPERTY_REPORT_XML_MACROS = "report.xmlMacros";
public static final String GLOBAL_PROPERTY_STANDARD_DRUG_REGIMENS = "dashboard.regimen.standardRegimens";
public static final String GLOBAL_PROPERTY_DEFAULT_PATIENT_IDENTIFIER_VALIDATOR = "patient.defaultPatientIdentifierValidator";
public static final String GLOBAL_PROPERTY_PATIENT_IDENTIFIER_IMPORTANT_TYPES = "patient_identifier.importantTypes";
public static final String GLOBAL_PROPERTY_ENCOUNTER_FORM_OBS_SORT_ORDER = "encounterForm.obsSortOrder";
public static final String GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST = "locale.allowed.list";
public static final String GLOBAL_PROPERTY_IMPLEMENTATION_ID = "implementation_id";
public static final String GLOBAL_PROPERTY_NEWPATIENTFORM_RELATIONSHIPS = "newPatientForm.relationships";
public static final String GLOBAL_PROPERTY_COMPLEX_OBS_DIR = "obs.complex_obs_dir";
public static final String GLOBAL_PROPERTY_MIN_SEARCH_CHARACTERS = "minSearchCharacters";
/**
* These properties (and default values) are set if not found in the database when OpenMRS is
* started if they do not exist yet
*
* @return
*/
public static final List<GlobalProperty> CORE_GLOBAL_PROPERTIES() {
List<GlobalProperty> props = new Vector<GlobalProperty>();
props.add(new GlobalProperty("use_patient_attribute.healthCenter", "false",
"Indicates whether or not the 'health center' attribute is shown when viewing/searching for patients"));
props.add(new GlobalProperty("use_patient_attribute.mothersName", "false",
"Indicates whether or not mother's name is able to be added/viewed for a patient"));
props.add(new GlobalProperty("new_patient_form.showRelationships", "false",
"true/false whether or not to show the relationship editor on the addPatient.htm screen"));
props.add(new GlobalProperty("dashboard.overview.showConcepts", "",
"Comma delimited list of concepts ids to show on the patient dashboard overview tab"));
props
.add(new GlobalProperty("dashboard.encounters.viewWhere", "newWindow",
"Defines how the 'View Encounter' link should act. Known values: 'sameWindow', 'newWindow', 'oneNewWindow'"));
props.add(new GlobalProperty("dashboard.encounters.showEmptyFields", "true",
"true/false whether or not to show empty fields on the 'View Encounter' window"));
props
.add(new GlobalProperty(
"dashboard.encounters.usePages",
"smart",
"true/false/smart on how to show the pages on the 'View Encounter' window. 'smart' means that if > 50% of the fields have page numbers defined, show data in pages"));
props.add(new GlobalProperty("dashboard.encounters.showViewLink", "true",
"true/false whether or not to show the 'View Encounter' link on the patient dashboard"));
props.add(new GlobalProperty("dashboard.encounters.showEditLink", "true",
"true/false whether or not to show the 'Edit Encounter' link on the patient dashboard"));
props.add(new GlobalProperty("dashboard.relationships.show_types", "",
"Types of relationships separated by commas. Doctor/Patient,Parent/Child"));
props
.add(new GlobalProperty(
"dashboard.regimen.displayDrugSetIds",
"ANTIRETROVIRAL DRUGS,TUBERCULOSIS TREATMENT DRUGS",
"Drug sets that appear on the Patient Dashboard Regimen tab. Comma separated list of name of concepts that are defined as drug sets."));
String standardRegimens = "<list>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>"
+ " <drugId>2</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>" + " </drugComponents>"
+ " <displayName>3TC + d4T(30) + NVP (Triomune-30)</displayName>"
+ " <codeName>standardTri30</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>"
+ " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>"
+ " <drugId>3</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>" + " </drugComponents>"
+ " <displayName>3TC + d4T(40) + NVP (Triomune-40)</displayName>"
+ " <codeName>standardTri40</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>"
+ " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>"
+ " <drugId>39</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>22</drugId>"
+ " <dose>200</dose>" + " <units>mg</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + NVP</displayName>"
+ " <codeName>standardAztNvp</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>"
+ " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>"
+ " <drugSuggestion reference=\"../../../regimenSuggestion[3]/drugComponents/drugSuggestion\"/>"
+ " <drugSuggestion>" + " <drugId>11</drugId>" + " <dose>600</dose>"
+ " <units>mg</units>" + " <frequency>1/day x 7 days/week</frequency>"
+ " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>"
+ " <displayName>AZT + 3TC + EFV(600)</displayName>" + " <codeName>standardAztEfv</codeName>"
+ " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>"
+ " <drugComponents>" + " <drugSuggestion>" + " <drugId>5</drugId>"
+ " <dose>30</dose>" + " <units>mg</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>42</drugId>"
+ " <dose>150</dose>" + " <units>mg</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>"
+ " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>"
+ " </drugComponents>" + " <displayName>d4T(30) + 3TC + EFV(600)</displayName>"
+ " <codeName>standardD4t30Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>"
+ " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>"
+ " <drugId>6</drugId>" + " <dose>40</dose>" + " <units>mg</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>"
+ " <drugSuggestion reference=\"../../../regimenSuggestion[5]/drugComponents/drugSuggestion[2]\"/>"
+ " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>"
+ " </drugComponents>" + " <displayName>d4T(40) + 3TC + EFV(600)</displayName>"
+ " <codeName>standardD4t40Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>"
+ " </regimenSuggestion>" + "</list>";
props.add(new GlobalProperty(GLOBAL_PROPERTY_STANDARD_DRUG_REGIMENS, standardRegimens,
"XML description of standard drug regimens, to be shown as shortcuts on the dashboard regimen entry tab"));
props.add(new GlobalProperty("concept.weight", "5089", "Concept id of the concept defining the WEIGHT concept"));
props.add(new GlobalProperty("concept.height", "5090", "Concept id of the concept defining the HEIGHT concept"));
- props
- .add(new GlobalProperty("concept.cd4_count", "5497",
- "Concept id of the concept defining the CD4 count concept"));
+ props.add(new GlobalProperty("concept.cd4_count", "5497", "Concept id of the concept defining the CD4 count concept"));
props.add(new GlobalProperty("concept.causeOfDeath", "5002",
"Concept id of the concept defining the CAUSE OF DEATH concept"));
props.add(new GlobalProperty("concept.none", "1107", "Concept id of the concept defining the NONE concept"));
props.add(new GlobalProperty("concept.otherNonCoded", "5622",
"Concept id of the concept defining the OTHER NON-CODED concept"));
props.add(new GlobalProperty("concept.patientDied", "1742",
- "Concept id of the concept defining the PATIEND DIED concept"));
+ "Concept id of the concept defining the PATIENT DIED concept"));
props.add(new GlobalProperty("concept.reasonExitedCare", "1811",
"Concept id of the concept defining the REASON EXITED CARE concept"));
props.add(new GlobalProperty("concept.reasonOrderStopped", "1812",
"Concept id of the concept defining the REASON ORDER STOPPED concept"));
props.add(new GlobalProperty("mail.transport_protocol", "smtp",
"Transport protocol for the messaging engine. Valid values: smtp"));
props.add(new GlobalProperty("mail.smtp_host", "localhost", "SMTP host name"));
props.add(new GlobalProperty("mail.smtp_port", "25", "SMTP port"));
props.add(new GlobalProperty("mail.from", "[email protected]", "Email address to use as the default from address"));
props.add(new GlobalProperty("mail.debug", "false",
"true/false whether to print debugging information during mailing"));
props.add(new GlobalProperty("mail.smtp_auth", "false", "true/false whether the smtp host requires authentication"));
props.add(new GlobalProperty("mail.user", "test", "Username of the SMTP user (if smtp_auth is enabled)"));
props.add(new GlobalProperty("mail.password", "test", "Password for the SMTP user (if smtp_auth is enabled)"));
props.add(new GlobalProperty("mail.default_content_type", "text/plain",
"Content type to append to the mail messages"));
props.add(new GlobalProperty(ModuleConstants.REPOSITORY_FOLDER_PROPERTY,
ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT, "Name of the folder in which to store the modules"));
props
.add(new GlobalProperty("layout.address.format", "general",
"Format in which to display the person addresses. Valid values are general, kenya, rwanda, usa, and lesotho"));
props.add(new GlobalProperty("layout.name.format", "short",
"Format in which to display the person names. Valid values are short, long"));
// TODO should be changed to text defaults and constants should be removed
props.add(new GlobalProperty("scheduler.username", SchedulerConstants.SCHEDULER_DEFAULT_USERNAME,
"Username for the OpenMRS user that will perform the scheduler activities"));
props.add(new GlobalProperty("scheduler.password", SchedulerConstants.SCHEDULER_DEFAULT_PASSWORD,
"Password for the OpenMRS user that will perform the scheduler activities"));
props.add(new GlobalProperty(GLOBAL_PROPERTY_CONCEPTS_LOCKED, "false",
"true/false whether or not concepts can be edited in this database."));
props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_LISTING_ATTRIBUTES, "",
"A comma delimited list of PersonAttributeType names that should be displayed for patients in _lists_"));
props
.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES, "",
"A comma delimited list of PersonAttributeType names that should be displayed for patients when _viewing individually_"));
props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_HEADER_ATTRIBUTES, "",
"A comma delimited list of PersonAttributeType names that will be shown on the patient dashboard"));
props.add(new GlobalProperty(GLOBAL_PROPERTY_USER_LISTING_ATTRIBUTES, "",
"A comma delimited list of PersonAttributeType names that should be displayed for users in _lists_"));
props
.add(new GlobalProperty(GLOBAL_PROPERTY_USER_VIEWING_ATTRIBUTES, "",
"A comma delimited list of PersonAttributeType names that should be displayed for users when _viewing individually_"));
props
.add(new GlobalProperty(GLOBAL_PROPERTY_USER_HEADER_ATTRIBUTES, "",
"A comma delimited list of PersonAttributeType names that will be shown on the user dashboard. (not used in v1.5)"));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX,
"^0*@SEARCH@([A-Z]+-[0-9])?$",
"A MySQL regular expression for the patient identifier search strings. The @SEARCH@ string is replaced at runtime with the user's search string. An empty regex will cause a simply 'like' sql search to be used"));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_PATIENT_IDENTIFIER_PREFIX,
"",
"This property is only used if "
+ GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX
+ " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty."));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SUFFIX,
"%",
"This property is only used if "
+ GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX
+ " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty."));
props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_SEARCH_MAX_RESULTS, "1000",
"The maximum number of results returned by patient searches"));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_GZIP_ENABLED,
"false",
"Set to 'true' to turn on OpenMRS's gzip filter, and have the webapp compress data before sending it to any client that supports it. Generally use this if you are running Tomcat standalone. If you are running Tomcat behind Apache, then you'd want to use Apache to do gzip compression."));
props
.add(new GlobalProperty(GLOBAL_PROPERTY_REPORT_XML_MACROS, "",
"Macros that will be applied to Report Schema XMLs when they are interpreted. This should be java.util.properties format."));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_MEDICAL_RECORD_OBSERVATIONS,
"1238",
"The concept id of the MEDICAL_RECORD_OBSERVATIONS concept. This concept_id is presumed to be the generic grouping (obr) concept in hl7 messages. An obs_group row is not created for this concept."));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_LOG_LEVEL,
LOG_LEVEL_INFO,
"log level used by the logger 'org.openmrs'. This value will override the log4j.xml value. Valid values are trace, debug, info, warn, error or fatal"));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_DEFAULT_PATIENT_IDENTIFIER_VALIDATOR,
LUHN_IDENTIFIER_VALIDATOR,
"This property sets the default patient identifier validator. The default validator is only used in a handful of (mostly legacy) instances. For example, it's used to generate the isValidCheckDigit calculated column and to append the string \"(default)\" to the name of the default validator on the editPatientIdentifierType form."));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_PATIENT_IDENTIFIER_IMPORTANT_TYPES,
"",
"A comma delimited list of PatientIdentifier names : PatientIdentifier locations that will be displayed on the patient dashboard. E.g.: TRACnet ID:Rwanda,ELDID:Kenya"));
props.add(new GlobalProperty(GLOBAL_PROPERTY_COMPLEX_OBS_DIR, "complex_obs",
"Default directory for storing complex obs."));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_ENCOUNTER_FORM_OBS_SORT_ORDER,
"number",
"The sort order for the obs listed on the encounter edit form. 'number' sorts on the associated numbering from the form schema. 'weight' sorts on the order displayed in the form schema."));
props.add(new GlobalProperty(GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en, es, fr, it, pt",
"Comma delimited list of locales allowed for use on system"));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_NEWPATIENTFORM_RELATIONSHIPS,
"",
"Comma separated list of the RelationshipTypes to show on the new/short patient form. The list is defined like '3a, 4b, 7a'. The number is the RelationshipTypeId and the 'a' vs 'b' part is which side of the relationship is filled in by the user."));
props.add(new GlobalProperty(GLOBAL_PROPERTY_MIN_SEARCH_CHARACTERS, "3",
"Number of characters user must input before searching is started."));
for (GlobalProperty gp : ModuleFactory.getGlobalProperties()) {
props.add(gp);
}
return props;
}
// ConceptProposal proposed concept identifier keyword
public static final String PROPOSED_CONCEPT_IDENTIFIER = "PROPOSED";
// ConceptProposal states
public static final String CONCEPT_PROPOSAL_UNMAPPED = "UNMAPPED";
public static final String CONCEPT_PROPOSAL_CONCEPT = "CONCEPT";
public static final String CONCEPT_PROPOSAL_SYNONYM = "SYNONYM";
public static final String CONCEPT_PROPOSAL_REJECT = "REJECT";
public static final Collection<String> CONCEPT_PROPOSAL_STATES() {
Collection<String> states = new Vector<String>();
states.add(CONCEPT_PROPOSAL_UNMAPPED);
states.add(CONCEPT_PROPOSAL_CONCEPT);
states.add(CONCEPT_PROPOSAL_SYNONYM);
states.add(CONCEPT_PROPOSAL_REJECT);
return states;
}
public static Locale SPANISH_LANGUAGE = new Locale("es");
public static Locale PORTUGUESE_LANGUAGE = new Locale("pt");
public static Locale ITALIAN_LANGUAGE = new Locale("it");
/**
* @return Collection of locales available to openmrs
* @deprecated
*/
public static final Collection<Locale> OPENMRS_LOCALES() {
List<Locale> languages = new Vector<Locale>();
languages.add(Locale.US);
languages.add(Locale.UK);
languages.add(Locale.FRENCH);
languages.add(SPANISH_LANGUAGE);
languages.add(PORTUGUESE_LANGUAGE);
languages.add(ITALIAN_LANGUAGE);
return languages;
}
public static final Locale GLOBAL_DEFAULT_LOCALE = Locale.US;
/**
* @return Collection of locales that the concept dictionary should be aware of
* @see ConceptService#getLocalesOfConceptNames()
* @deprecated
*/
public static final Collection<Locale> OPENMRS_CONCEPT_LOCALES() {
List<Locale> languages = new Vector<Locale>();
languages.add(Locale.ENGLISH);
languages.add(Locale.FRENCH);
languages.add(SPANISH_LANGUAGE);
languages.add(PORTUGUESE_LANGUAGE);
languages.add(ITALIAN_LANGUAGE);
return languages;
}
private static Map<String, String> OPENMRS_LOCALE_DATE_PATTERNS = null;
/**
* This method is necessary until SimpleDateFormat(SHORT, java.util.locale) returns a pattern
* with a four digit year <locale.toString().toLowerCase(), pattern>
*
* @return Mapping of Locales to locale specific date pattern
*/
public static final Map<String, String> OPENMRS_LOCALE_DATE_PATTERNS() {
if (OPENMRS_LOCALE_DATE_PATTERNS == null) {
Map<String, String> patterns = new HashMap<String, String>();
patterns.put(Locale.US.toString().toLowerCase(), "MM/dd/yyyy");
patterns.put(Locale.UK.toString().toLowerCase(), "dd/MM/yyyy");
patterns.put(Locale.FRENCH.toString().toLowerCase(), "dd/MM/yyyy");
patterns.put(Locale.GERMAN.toString().toLowerCase(), "MM.dd.yyyy");
patterns.put(SPANISH_LANGUAGE.toString().toLowerCase(), "dd/MM/yyyy");
patterns.put(PORTUGUESE_LANGUAGE.toString().toLowerCase(), "dd/MM/yyyy");
patterns.put(ITALIAN_LANGUAGE.toString().toLowerCase(), "dd/MM/yyyy");
OPENMRS_LOCALE_DATE_PATTERNS = patterns;
}
return OPENMRS_LOCALE_DATE_PATTERNS;
}
/*
* User property names
*/
public static final String USER_PROPERTY_CHANGE_PASSWORD = "forcePassword";
public static final String USER_PROPERTY_DEFAULT_LOCALE = "defaultLocale";
public static final String USER_PROPERTY_DEFAULT_LOCATION = "defaultLocation";
public static final String USER_PROPERTY_SHOW_RETIRED = "showRetired";
public static final String USER_PROPERTY_SHOW_VERBOSE = "showVerbose";
public static final String USER_PROPERTY_NOTIFICATION = "notification";
public static final String USER_PROPERTY_NOTIFICATION_ADDRESS = "notificationAddress";
public static final String USER_PROPERTY_NOTIFICATION_FORMAT = "notificationFormat"; // text/plain, text/html
/**
* Name of the user_property that stores the number of unsuccessful login attempts this user has
* made
*/
public static final String USER_PROPERTY_LOGIN_ATTEMPTS = "loginAttempts";
/**
* Name of the user_property that stores the time the user was locked out due to too many login
* attempts
*/
public static final String USER_PROPERTY_LOCKOUT_TIMESTAMP = "lockoutTimestamp";
/**
* A user property name. The value should be a comma-separated ordered list of fully qualified
* locales within which the user is a proficient speaker. The list should be ordered from the
* most to the least proficiency. Example:
* <code>proficientLocales = en_US, en_GB, en, fr_RW</code>
*/
public static final String USER_PROPERTY_PROFICIENT_LOCALES = "proficientLocales";
/**
* Report object properties
*/
public static final String REPORT_OBJECT_TYPE_PATIENTFILTER = "Patient Filter";
public static final String REPORT_OBJECT_TYPE_PATIENTSEARCH = "Patient Search";
public static final String REPORT_OBJECT_TYPE_PATIENTDATAPRODUCER = "Patient Data Producer";
// Used for differences between windows/linux upload capabilities)
// Used for determining where to find runtime properties
public static final String OPERATING_SYSTEM_KEY = "os.name";
public static final String OPERATING_SYSTEM = System.getProperty(OPERATING_SYSTEM_KEY);
public static final String OPERATING_SYSTEM_WINDOWS_XP = "Windows XP";
public static final String OPERATING_SYSTEM_WINDOWS_VISTA = "Windows Vista";
public static final String OPERATING_SYSTEM_LINUX = "Linux";
public static final String OPERATING_SYSTEM_SUNOS = "SunOS";
public static final String OPERATING_SYSTEM_FREEBSD = "FreeBSD";
public static final String OPERATING_SYSTEM_OSX = "Mac OS X";
/**
* URL to the concept source id verification server
*/
public static final String IMPLEMENTATION_ID_REMOTE_CONNECTION_URL = "http://resources.openmrs.org/tools/implementationid";
/**
* Shortcut booleans used to make some OS specific checks more generic; note the *nix flavored
* check is missing some less obvious choices
*/
public static final boolean UNIX_BASED_OPERATING_SYSTEM = (OPERATING_SYSTEM.indexOf(OPERATING_SYSTEM_LINUX) > -1
|| OPERATING_SYSTEM.indexOf(OPERATING_SYSTEM_SUNOS) > -1
|| OPERATING_SYSTEM.indexOf(OPERATING_SYSTEM_FREEBSD) > -1 || OPERATING_SYSTEM.indexOf(OPERATING_SYSTEM_OSX) > -1);
public static final boolean WINDOWS_BASED_OPERATING_SYSTEM = OPERATING_SYSTEM.indexOf("Windows") > -1;
public static final boolean WINDOWS_VISTA_OPERATING_SYSTEM = OPERATING_SYSTEM.equals(OPERATING_SYSTEM_WINDOWS_VISTA);
/**
* Marker put into the serialization session map to tell @Replace methods whether or not to do
* just the very basic serialization
*/
public static final String SHORT_SERIALIZATION = "isShortSerialization";
// Global property key for global logger level
public static final String GLOBAL_PROPERTY_LOG_LEVEL = "log.level.openmrs";
// Global logger category
public static final String LOG_CLASS_DEFAULT = "org.openmrs";
// Log levels
public static final String LOG_LEVEL_TRACE = "trace";
public static final String LOG_LEVEL_DEBUG = "debug";
public static final String LOG_LEVEL_INFO = "info";
public static final String LOG_LEVEL_WARN = "warn";
public static final String LOG_LEVEL_ERROR = "error";
public static final String LOG_LEVEL_FATAL = "fatal";
/**
* These enumerations should be used in ObsService and PersonService getters to help determine
* which type of object to restrict on
*
* @see org.openmrs.api.ObsService
* @see org.openmrs.api.PersonService
*/
public static enum PERSON_TYPE {
PERSON, PATIENT, USER
}
//Patient Identifier Validators
public static final String LUHN_IDENTIFIER_VALIDATOR = LuhnIdentifierValidator.class.getName();
// ComplexObsHandler views
public static final String RAW_VIEW = "RAW_VIEW";
public static final String TEXT_VIEW = "TEXT_VIEW";
}
| false | true | public static final List<GlobalProperty> CORE_GLOBAL_PROPERTIES() {
List<GlobalProperty> props = new Vector<GlobalProperty>();
props.add(new GlobalProperty("use_patient_attribute.healthCenter", "false",
"Indicates whether or not the 'health center' attribute is shown when viewing/searching for patients"));
props.add(new GlobalProperty("use_patient_attribute.mothersName", "false",
"Indicates whether or not mother's name is able to be added/viewed for a patient"));
props.add(new GlobalProperty("new_patient_form.showRelationships", "false",
"true/false whether or not to show the relationship editor on the addPatient.htm screen"));
props.add(new GlobalProperty("dashboard.overview.showConcepts", "",
"Comma delimited list of concepts ids to show on the patient dashboard overview tab"));
props
.add(new GlobalProperty("dashboard.encounters.viewWhere", "newWindow",
"Defines how the 'View Encounter' link should act. Known values: 'sameWindow', 'newWindow', 'oneNewWindow'"));
props.add(new GlobalProperty("dashboard.encounters.showEmptyFields", "true",
"true/false whether or not to show empty fields on the 'View Encounter' window"));
props
.add(new GlobalProperty(
"dashboard.encounters.usePages",
"smart",
"true/false/smart on how to show the pages on the 'View Encounter' window. 'smart' means that if > 50% of the fields have page numbers defined, show data in pages"));
props.add(new GlobalProperty("dashboard.encounters.showViewLink", "true",
"true/false whether or not to show the 'View Encounter' link on the patient dashboard"));
props.add(new GlobalProperty("dashboard.encounters.showEditLink", "true",
"true/false whether or not to show the 'Edit Encounter' link on the patient dashboard"));
props.add(new GlobalProperty("dashboard.relationships.show_types", "",
"Types of relationships separated by commas. Doctor/Patient,Parent/Child"));
props
.add(new GlobalProperty(
"dashboard.regimen.displayDrugSetIds",
"ANTIRETROVIRAL DRUGS,TUBERCULOSIS TREATMENT DRUGS",
"Drug sets that appear on the Patient Dashboard Regimen tab. Comma separated list of name of concepts that are defined as drug sets."));
String standardRegimens = "<list>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>"
+ " <drugId>2</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>" + " </drugComponents>"
+ " <displayName>3TC + d4T(30) + NVP (Triomune-30)</displayName>"
+ " <codeName>standardTri30</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>"
+ " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>"
+ " <drugId>3</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>" + " </drugComponents>"
+ " <displayName>3TC + d4T(40) + NVP (Triomune-40)</displayName>"
+ " <codeName>standardTri40</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>"
+ " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>"
+ " <drugId>39</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>22</drugId>"
+ " <dose>200</dose>" + " <units>mg</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + NVP</displayName>"
+ " <codeName>standardAztNvp</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>"
+ " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>"
+ " <drugSuggestion reference=\"../../../regimenSuggestion[3]/drugComponents/drugSuggestion\"/>"
+ " <drugSuggestion>" + " <drugId>11</drugId>" + " <dose>600</dose>"
+ " <units>mg</units>" + " <frequency>1/day x 7 days/week</frequency>"
+ " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>"
+ " <displayName>AZT + 3TC + EFV(600)</displayName>" + " <codeName>standardAztEfv</codeName>"
+ " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>"
+ " <drugComponents>" + " <drugSuggestion>" + " <drugId>5</drugId>"
+ " <dose>30</dose>" + " <units>mg</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>42</drugId>"
+ " <dose>150</dose>" + " <units>mg</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>"
+ " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>"
+ " </drugComponents>" + " <displayName>d4T(30) + 3TC + EFV(600)</displayName>"
+ " <codeName>standardD4t30Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>"
+ " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>"
+ " <drugId>6</drugId>" + " <dose>40</dose>" + " <units>mg</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>"
+ " <drugSuggestion reference=\"../../../regimenSuggestion[5]/drugComponents/drugSuggestion[2]\"/>"
+ " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>"
+ " </drugComponents>" + " <displayName>d4T(40) + 3TC + EFV(600)</displayName>"
+ " <codeName>standardD4t40Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>"
+ " </regimenSuggestion>" + "</list>";
props.add(new GlobalProperty(GLOBAL_PROPERTY_STANDARD_DRUG_REGIMENS, standardRegimens,
"XML description of standard drug regimens, to be shown as shortcuts on the dashboard regimen entry tab"));
props.add(new GlobalProperty("concept.weight", "5089", "Concept id of the concept defining the WEIGHT concept"));
props.add(new GlobalProperty("concept.height", "5090", "Concept id of the concept defining the HEIGHT concept"));
props
.add(new GlobalProperty("concept.cd4_count", "5497",
"Concept id of the concept defining the CD4 count concept"));
props.add(new GlobalProperty("concept.causeOfDeath", "5002",
"Concept id of the concept defining the CAUSE OF DEATH concept"));
props.add(new GlobalProperty("concept.none", "1107", "Concept id of the concept defining the NONE concept"));
props.add(new GlobalProperty("concept.otherNonCoded", "5622",
"Concept id of the concept defining the OTHER NON-CODED concept"));
props.add(new GlobalProperty("concept.patientDied", "1742",
"Concept id of the concept defining the PATIEND DIED concept"));
props.add(new GlobalProperty("concept.reasonExitedCare", "1811",
"Concept id of the concept defining the REASON EXITED CARE concept"));
props.add(new GlobalProperty("concept.reasonOrderStopped", "1812",
"Concept id of the concept defining the REASON ORDER STOPPED concept"));
props.add(new GlobalProperty("mail.transport_protocol", "smtp",
"Transport protocol for the messaging engine. Valid values: smtp"));
props.add(new GlobalProperty("mail.smtp_host", "localhost", "SMTP host name"));
props.add(new GlobalProperty("mail.smtp_port", "25", "SMTP port"));
props.add(new GlobalProperty("mail.from", "[email protected]", "Email address to use as the default from address"));
props.add(new GlobalProperty("mail.debug", "false",
"true/false whether to print debugging information during mailing"));
props.add(new GlobalProperty("mail.smtp_auth", "false", "true/false whether the smtp host requires authentication"));
props.add(new GlobalProperty("mail.user", "test", "Username of the SMTP user (if smtp_auth is enabled)"));
props.add(new GlobalProperty("mail.password", "test", "Password for the SMTP user (if smtp_auth is enabled)"));
props.add(new GlobalProperty("mail.default_content_type", "text/plain",
"Content type to append to the mail messages"));
props.add(new GlobalProperty(ModuleConstants.REPOSITORY_FOLDER_PROPERTY,
ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT, "Name of the folder in which to store the modules"));
props
.add(new GlobalProperty("layout.address.format", "general",
"Format in which to display the person addresses. Valid values are general, kenya, rwanda, usa, and lesotho"));
props.add(new GlobalProperty("layout.name.format", "short",
"Format in which to display the person names. Valid values are short, long"));
// TODO should be changed to text defaults and constants should be removed
props.add(new GlobalProperty("scheduler.username", SchedulerConstants.SCHEDULER_DEFAULT_USERNAME,
"Username for the OpenMRS user that will perform the scheduler activities"));
props.add(new GlobalProperty("scheduler.password", SchedulerConstants.SCHEDULER_DEFAULT_PASSWORD,
"Password for the OpenMRS user that will perform the scheduler activities"));
props.add(new GlobalProperty(GLOBAL_PROPERTY_CONCEPTS_LOCKED, "false",
"true/false whether or not concepts can be edited in this database."));
props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_LISTING_ATTRIBUTES, "",
"A comma delimited list of PersonAttributeType names that should be displayed for patients in _lists_"));
props
.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES, "",
"A comma delimited list of PersonAttributeType names that should be displayed for patients when _viewing individually_"));
props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_HEADER_ATTRIBUTES, "",
"A comma delimited list of PersonAttributeType names that will be shown on the patient dashboard"));
props.add(new GlobalProperty(GLOBAL_PROPERTY_USER_LISTING_ATTRIBUTES, "",
"A comma delimited list of PersonAttributeType names that should be displayed for users in _lists_"));
props
.add(new GlobalProperty(GLOBAL_PROPERTY_USER_VIEWING_ATTRIBUTES, "",
"A comma delimited list of PersonAttributeType names that should be displayed for users when _viewing individually_"));
props
.add(new GlobalProperty(GLOBAL_PROPERTY_USER_HEADER_ATTRIBUTES, "",
"A comma delimited list of PersonAttributeType names that will be shown on the user dashboard. (not used in v1.5)"));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX,
"^0*@SEARCH@([A-Z]+-[0-9])?$",
"A MySQL regular expression for the patient identifier search strings. The @SEARCH@ string is replaced at runtime with the user's search string. An empty regex will cause a simply 'like' sql search to be used"));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_PATIENT_IDENTIFIER_PREFIX,
"",
"This property is only used if "
+ GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX
+ " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty."));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SUFFIX,
"%",
"This property is only used if "
+ GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX
+ " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty."));
props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_SEARCH_MAX_RESULTS, "1000",
"The maximum number of results returned by patient searches"));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_GZIP_ENABLED,
"false",
"Set to 'true' to turn on OpenMRS's gzip filter, and have the webapp compress data before sending it to any client that supports it. Generally use this if you are running Tomcat standalone. If you are running Tomcat behind Apache, then you'd want to use Apache to do gzip compression."));
props
.add(new GlobalProperty(GLOBAL_PROPERTY_REPORT_XML_MACROS, "",
"Macros that will be applied to Report Schema XMLs when they are interpreted. This should be java.util.properties format."));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_MEDICAL_RECORD_OBSERVATIONS,
"1238",
"The concept id of the MEDICAL_RECORD_OBSERVATIONS concept. This concept_id is presumed to be the generic grouping (obr) concept in hl7 messages. An obs_group row is not created for this concept."));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_LOG_LEVEL,
LOG_LEVEL_INFO,
"log level used by the logger 'org.openmrs'. This value will override the log4j.xml value. Valid values are trace, debug, info, warn, error or fatal"));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_DEFAULT_PATIENT_IDENTIFIER_VALIDATOR,
LUHN_IDENTIFIER_VALIDATOR,
"This property sets the default patient identifier validator. The default validator is only used in a handful of (mostly legacy) instances. For example, it's used to generate the isValidCheckDigit calculated column and to append the string \"(default)\" to the name of the default validator on the editPatientIdentifierType form."));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_PATIENT_IDENTIFIER_IMPORTANT_TYPES,
"",
"A comma delimited list of PatientIdentifier names : PatientIdentifier locations that will be displayed on the patient dashboard. E.g.: TRACnet ID:Rwanda,ELDID:Kenya"));
props.add(new GlobalProperty(GLOBAL_PROPERTY_COMPLEX_OBS_DIR, "complex_obs",
"Default directory for storing complex obs."));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_ENCOUNTER_FORM_OBS_SORT_ORDER,
"number",
"The sort order for the obs listed on the encounter edit form. 'number' sorts on the associated numbering from the form schema. 'weight' sorts on the order displayed in the form schema."));
props.add(new GlobalProperty(GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en, es, fr, it, pt",
"Comma delimited list of locales allowed for use on system"));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_NEWPATIENTFORM_RELATIONSHIPS,
"",
"Comma separated list of the RelationshipTypes to show on the new/short patient form. The list is defined like '3a, 4b, 7a'. The number is the RelationshipTypeId and the 'a' vs 'b' part is which side of the relationship is filled in by the user."));
props.add(new GlobalProperty(GLOBAL_PROPERTY_MIN_SEARCH_CHARACTERS, "3",
"Number of characters user must input before searching is started."));
for (GlobalProperty gp : ModuleFactory.getGlobalProperties()) {
props.add(gp);
}
return props;
}
| public static final List<GlobalProperty> CORE_GLOBAL_PROPERTIES() {
List<GlobalProperty> props = new Vector<GlobalProperty>();
props.add(new GlobalProperty("use_patient_attribute.healthCenter", "false",
"Indicates whether or not the 'health center' attribute is shown when viewing/searching for patients"));
props.add(new GlobalProperty("use_patient_attribute.mothersName", "false",
"Indicates whether or not mother's name is able to be added/viewed for a patient"));
props.add(new GlobalProperty("new_patient_form.showRelationships", "false",
"true/false whether or not to show the relationship editor on the addPatient.htm screen"));
props.add(new GlobalProperty("dashboard.overview.showConcepts", "",
"Comma delimited list of concepts ids to show on the patient dashboard overview tab"));
props
.add(new GlobalProperty("dashboard.encounters.viewWhere", "newWindow",
"Defines how the 'View Encounter' link should act. Known values: 'sameWindow', 'newWindow', 'oneNewWindow'"));
props.add(new GlobalProperty("dashboard.encounters.showEmptyFields", "true",
"true/false whether or not to show empty fields on the 'View Encounter' window"));
props
.add(new GlobalProperty(
"dashboard.encounters.usePages",
"smart",
"true/false/smart on how to show the pages on the 'View Encounter' window. 'smart' means that if > 50% of the fields have page numbers defined, show data in pages"));
props.add(new GlobalProperty("dashboard.encounters.showViewLink", "true",
"true/false whether or not to show the 'View Encounter' link on the patient dashboard"));
props.add(new GlobalProperty("dashboard.encounters.showEditLink", "true",
"true/false whether or not to show the 'Edit Encounter' link on the patient dashboard"));
props.add(new GlobalProperty("dashboard.relationships.show_types", "",
"Types of relationships separated by commas. Doctor/Patient,Parent/Child"));
props
.add(new GlobalProperty(
"dashboard.regimen.displayDrugSetIds",
"ANTIRETROVIRAL DRUGS,TUBERCULOSIS TREATMENT DRUGS",
"Drug sets that appear on the Patient Dashboard Regimen tab. Comma separated list of name of concepts that are defined as drug sets."));
String standardRegimens = "<list>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>"
+ " <drugId>2</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>" + " </drugComponents>"
+ " <displayName>3TC + d4T(30) + NVP (Triomune-30)</displayName>"
+ " <codeName>standardTri30</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>"
+ " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>"
+ " <drugId>3</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>" + " </drugComponents>"
+ " <displayName>3TC + d4T(40) + NVP (Triomune-40)</displayName>"
+ " <codeName>standardTri40</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>"
+ " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>"
+ " <drugId>39</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>22</drugId>"
+ " <dose>200</dose>" + " <units>mg</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + NVP</displayName>"
+ " <codeName>standardAztNvp</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>"
+ " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>"
+ " <drugSuggestion reference=\"../../../regimenSuggestion[3]/drugComponents/drugSuggestion\"/>"
+ " <drugSuggestion>" + " <drugId>11</drugId>" + " <dose>600</dose>"
+ " <units>mg</units>" + " <frequency>1/day x 7 days/week</frequency>"
+ " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>"
+ " <displayName>AZT + 3TC + EFV(600)</displayName>" + " <codeName>standardAztEfv</codeName>"
+ " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>"
+ " <drugComponents>" + " <drugSuggestion>" + " <drugId>5</drugId>"
+ " <dose>30</dose>" + " <units>mg</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>42</drugId>"
+ " <dose>150</dose>" + " <units>mg</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>"
+ " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>"
+ " </drugComponents>" + " <displayName>d4T(30) + 3TC + EFV(600)</displayName>"
+ " <codeName>standardD4t30Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>"
+ " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>"
+ " <drugId>6</drugId>" + " <dose>40</dose>" + " <units>mg</units>"
+ " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>"
+ " </drugSuggestion>"
+ " <drugSuggestion reference=\"../../../regimenSuggestion[5]/drugComponents/drugSuggestion[2]\"/>"
+ " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>"
+ " </drugComponents>" + " <displayName>d4T(40) + 3TC + EFV(600)</displayName>"
+ " <codeName>standardD4t40Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>"
+ " </regimenSuggestion>" + "</list>";
props.add(new GlobalProperty(GLOBAL_PROPERTY_STANDARD_DRUG_REGIMENS, standardRegimens,
"XML description of standard drug regimens, to be shown as shortcuts on the dashboard regimen entry tab"));
props.add(new GlobalProperty("concept.weight", "5089", "Concept id of the concept defining the WEIGHT concept"));
props.add(new GlobalProperty("concept.height", "5090", "Concept id of the concept defining the HEIGHT concept"));
props.add(new GlobalProperty("concept.cd4_count", "5497", "Concept id of the concept defining the CD4 count concept"));
props.add(new GlobalProperty("concept.causeOfDeath", "5002",
"Concept id of the concept defining the CAUSE OF DEATH concept"));
props.add(new GlobalProperty("concept.none", "1107", "Concept id of the concept defining the NONE concept"));
props.add(new GlobalProperty("concept.otherNonCoded", "5622",
"Concept id of the concept defining the OTHER NON-CODED concept"));
props.add(new GlobalProperty("concept.patientDied", "1742",
"Concept id of the concept defining the PATIENT DIED concept"));
props.add(new GlobalProperty("concept.reasonExitedCare", "1811",
"Concept id of the concept defining the REASON EXITED CARE concept"));
props.add(new GlobalProperty("concept.reasonOrderStopped", "1812",
"Concept id of the concept defining the REASON ORDER STOPPED concept"));
props.add(new GlobalProperty("mail.transport_protocol", "smtp",
"Transport protocol for the messaging engine. Valid values: smtp"));
props.add(new GlobalProperty("mail.smtp_host", "localhost", "SMTP host name"));
props.add(new GlobalProperty("mail.smtp_port", "25", "SMTP port"));
props.add(new GlobalProperty("mail.from", "[email protected]", "Email address to use as the default from address"));
props.add(new GlobalProperty("mail.debug", "false",
"true/false whether to print debugging information during mailing"));
props.add(new GlobalProperty("mail.smtp_auth", "false", "true/false whether the smtp host requires authentication"));
props.add(new GlobalProperty("mail.user", "test", "Username of the SMTP user (if smtp_auth is enabled)"));
props.add(new GlobalProperty("mail.password", "test", "Password for the SMTP user (if smtp_auth is enabled)"));
props.add(new GlobalProperty("mail.default_content_type", "text/plain",
"Content type to append to the mail messages"));
props.add(new GlobalProperty(ModuleConstants.REPOSITORY_FOLDER_PROPERTY,
ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT, "Name of the folder in which to store the modules"));
props
.add(new GlobalProperty("layout.address.format", "general",
"Format in which to display the person addresses. Valid values are general, kenya, rwanda, usa, and lesotho"));
props.add(new GlobalProperty("layout.name.format", "short",
"Format in which to display the person names. Valid values are short, long"));
// TODO should be changed to text defaults and constants should be removed
props.add(new GlobalProperty("scheduler.username", SchedulerConstants.SCHEDULER_DEFAULT_USERNAME,
"Username for the OpenMRS user that will perform the scheduler activities"));
props.add(new GlobalProperty("scheduler.password", SchedulerConstants.SCHEDULER_DEFAULT_PASSWORD,
"Password for the OpenMRS user that will perform the scheduler activities"));
props.add(new GlobalProperty(GLOBAL_PROPERTY_CONCEPTS_LOCKED, "false",
"true/false whether or not concepts can be edited in this database."));
props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_LISTING_ATTRIBUTES, "",
"A comma delimited list of PersonAttributeType names that should be displayed for patients in _lists_"));
props
.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES, "",
"A comma delimited list of PersonAttributeType names that should be displayed for patients when _viewing individually_"));
props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_HEADER_ATTRIBUTES, "",
"A comma delimited list of PersonAttributeType names that will be shown on the patient dashboard"));
props.add(new GlobalProperty(GLOBAL_PROPERTY_USER_LISTING_ATTRIBUTES, "",
"A comma delimited list of PersonAttributeType names that should be displayed for users in _lists_"));
props
.add(new GlobalProperty(GLOBAL_PROPERTY_USER_VIEWING_ATTRIBUTES, "",
"A comma delimited list of PersonAttributeType names that should be displayed for users when _viewing individually_"));
props
.add(new GlobalProperty(GLOBAL_PROPERTY_USER_HEADER_ATTRIBUTES, "",
"A comma delimited list of PersonAttributeType names that will be shown on the user dashboard. (not used in v1.5)"));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX,
"^0*@SEARCH@([A-Z]+-[0-9])?$",
"A MySQL regular expression for the patient identifier search strings. The @SEARCH@ string is replaced at runtime with the user's search string. An empty regex will cause a simply 'like' sql search to be used"));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_PATIENT_IDENTIFIER_PREFIX,
"",
"This property is only used if "
+ GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX
+ " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty."));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SUFFIX,
"%",
"This property is only used if "
+ GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX
+ " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty."));
props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_SEARCH_MAX_RESULTS, "1000",
"The maximum number of results returned by patient searches"));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_GZIP_ENABLED,
"false",
"Set to 'true' to turn on OpenMRS's gzip filter, and have the webapp compress data before sending it to any client that supports it. Generally use this if you are running Tomcat standalone. If you are running Tomcat behind Apache, then you'd want to use Apache to do gzip compression."));
props
.add(new GlobalProperty(GLOBAL_PROPERTY_REPORT_XML_MACROS, "",
"Macros that will be applied to Report Schema XMLs when they are interpreted. This should be java.util.properties format."));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_MEDICAL_RECORD_OBSERVATIONS,
"1238",
"The concept id of the MEDICAL_RECORD_OBSERVATIONS concept. This concept_id is presumed to be the generic grouping (obr) concept in hl7 messages. An obs_group row is not created for this concept."));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_LOG_LEVEL,
LOG_LEVEL_INFO,
"log level used by the logger 'org.openmrs'. This value will override the log4j.xml value. Valid values are trace, debug, info, warn, error or fatal"));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_DEFAULT_PATIENT_IDENTIFIER_VALIDATOR,
LUHN_IDENTIFIER_VALIDATOR,
"This property sets the default patient identifier validator. The default validator is only used in a handful of (mostly legacy) instances. For example, it's used to generate the isValidCheckDigit calculated column and to append the string \"(default)\" to the name of the default validator on the editPatientIdentifierType form."));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_PATIENT_IDENTIFIER_IMPORTANT_TYPES,
"",
"A comma delimited list of PatientIdentifier names : PatientIdentifier locations that will be displayed on the patient dashboard. E.g.: TRACnet ID:Rwanda,ELDID:Kenya"));
props.add(new GlobalProperty(GLOBAL_PROPERTY_COMPLEX_OBS_DIR, "complex_obs",
"Default directory for storing complex obs."));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_ENCOUNTER_FORM_OBS_SORT_ORDER,
"number",
"The sort order for the obs listed on the encounter edit form. 'number' sorts on the associated numbering from the form schema. 'weight' sorts on the order displayed in the form schema."));
props.add(new GlobalProperty(GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en, es, fr, it, pt",
"Comma delimited list of locales allowed for use on system"));
props
.add(new GlobalProperty(
GLOBAL_PROPERTY_NEWPATIENTFORM_RELATIONSHIPS,
"",
"Comma separated list of the RelationshipTypes to show on the new/short patient form. The list is defined like '3a, 4b, 7a'. The number is the RelationshipTypeId and the 'a' vs 'b' part is which side of the relationship is filled in by the user."));
props.add(new GlobalProperty(GLOBAL_PROPERTY_MIN_SEARCH_CHARACTERS, "3",
"Number of characters user must input before searching is started."));
for (GlobalProperty gp : ModuleFactory.getGlobalProperties()) {
props.add(gp);
}
return props;
}
|
diff --git a/src/sphinx4/edu/cmu/sphinx/util/props/PropertySheet.java b/src/sphinx4/edu/cmu/sphinx/util/props/PropertySheet.java
index 3114c72a..b55b757f 100644
--- a/src/sphinx4/edu/cmu/sphinx/util/props/PropertySheet.java
+++ b/src/sphinx4/edu/cmu/sphinx/util/props/PropertySheet.java
@@ -1,715 +1,720 @@
package edu.cmu.sphinx.util.props;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A property sheet which defines a collection of properties for a single component in the system.
*
* @author Holger Brandl
*/
public class PropertySheet implements Cloneable {
public enum PropertyType {
INT, DOUBLE, BOOL, COMP, STRING, COMPLIST
}
private Map<String, S4PropWrapper> registeredProperties = new HashMap<String, S4PropWrapper>();
private Map<String, Object> propValues = new HashMap<String, Object>();
/**
* Maps the names of the component properties to their (possibly unresolved) values.
* <p/>
* Example: <code>frontend</code> to <code>${myFrontEnd}</code>
*/
private Map<String, Object> rawProps = new HashMap<String, Object>();
private ConfigurationManager cm;
private Configurable owner;
private final Class<? extends Configurable> ownerClass;
private String instanceName;
public PropertySheet(Configurable configurable, String name, RawPropertyData rpd, ConfigurationManager ConfigurationManager) {
this(configurable.getClass(), name, ConfigurationManager, rpd);
owner = configurable;
}
public PropertySheet(Class<? extends Configurable> confClass, String name, ConfigurationManager cm, RawPropertyData rpd) {
ownerClass = confClass;
this.cm = cm;
this.instanceName = name;
processAnnotations(this, confClass);
// now apply all xml properties
Map<String, Object> flatProps = rpd.flatten(cm).getProperties();
rawProps = new HashMap<String, Object>(rpd.getProperties());
for (String propName : rawProps.keySet())
propValues.put(propName, flatProps.get(propName));
}
/**
* Registers a new property which type and default value are defined by the given sphinx property.
*
* @param propName The name of the property to be registered.
* @param property The property annoation masked by a proxy.
*/
private void registerProperty(String propName, S4PropWrapper property) {
assert property != null && propName != null;
registeredProperties.put(propName, property);
propValues.put(propName, null);
rawProps.put(propName, null);
}
/** Returns the property names <code>name</code> which is still wrapped into the annotation instance. */
public S4PropWrapper getProperty(String name, Class propertyClass) throws PropertyException {
if (!propValues.containsKey(name))
throw new InternalConfigurationException(getInstanceName(), name,
"Unknown property '" + name + "' ! Make sure that you've annotated it.");
S4PropWrapper s4PropWrapper = registeredProperties.get(name);
try {
propertyClass.cast(s4PropWrapper.getAnnotation());
} catch (ClassCastException e) {
throw new InternalConfigurationException(e, getInstanceName(), name, name + " is not an annotated sphinx property of '" + getConfigurableClass().getName() + "' !");
}
return s4PropWrapper;
}
/**
* Gets the value associated with this name
*
* @param name the name
* @return the value
*/
public String getString(String name) throws PropertyException {
S4PropWrapper s4PropWrapper = getProperty(name, S4String.class);
S4String s4String = ((S4String) s4PropWrapper.getAnnotation());
if (propValues.get(name) == null) {
boolean isDefDefined = !s4String.defaultValue().equals(S4String.NOT_DEFINED);
if (s4String.mandatory()) {
if (!isDefDefined)
throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!");
}
// else if(!isDefDefined)
// throw new InternalConfigurationException(getInstanceName(), name, "no default value for non-mandatory property");
propValues.put(name, isDefDefined ? s4String.defaultValue() : null);
}
String propValue = (String) propValues.get(name);
//check range
List<String> range = Arrays.asList(s4String.range());
if (!range.isEmpty() && !range.contains(propValue))
throw new InternalConfigurationException(getInstanceName(), name, " is not in range (" + range + ")");
return propValue;
}
/**
* Gets the value associated with this name
*
* @param name the name
* @return the value
* @throws edu.cmu.sphinx.util.props.PropertyException
* if the named property is not of this type
*/
public int getInt(String name) throws PropertyException {
S4PropWrapper s4PropWrapper = getProperty(name, S4Integer.class);
S4Integer s4Integer = (S4Integer) s4PropWrapper.getAnnotation();
if (propValues.get(name) == null) {
boolean isDefDefined = !(s4Integer.defaultValue() == S4Integer.NOT_DEFINED);
if (s4Integer.mandatory()) {
if (!isDefDefined)
throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!");
} else if (!isDefDefined)
throw new InternalConfigurationException(getInstanceName(), name, "no default value for non-mandatory property");
propValues.put(name, s4Integer.defaultValue());
}
Object propObject = propValues.get(name);
Integer propValue = propObject instanceof Integer ? (Integer) propObject : Integer.decode((String) propObject);
int[] range = s4Integer.range();
if (range.length != 2)
throw new InternalConfigurationException(getInstanceName(), name, range + " is not of expected range type, which is {minValue, maxValue)");
if (propValue < range[0] || propValue > range[1])
throw new InternalConfigurationException(getInstanceName(), name, " is not in range (" + range + ")");
return propValue;
}
/**
* Gets the value associated with this name
*
* @param name the name
* @return the value
* @throws edu.cmu.sphinx.util.props.PropertyException
* if the named property is not of this type
*/
public float getFloat(String name) throws PropertyException {
return ((Double) getDouble(name)).floatValue();
}
/**
* Gets the value associated with this name
*
* @param name the name
* @return the value
* @throws edu.cmu.sphinx.util.props.PropertyException
* if the named property is not of this type
*/
public double getDouble(String name) throws PropertyException {
S4PropWrapper s4PropWrapper = getProperty(name, S4Double.class);
S4Double s4Double = (S4Double) s4PropWrapper.getAnnotation();
if (propValues.get(name) == null) {
boolean isDefDefined = !(s4Double.defaultValue() == S4Double.NOT_DEFINED);
if (s4Double.mandatory()) {
if (!isDefDefined)
throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!");
} else if (!isDefDefined)
throw new InternalConfigurationException(getInstanceName(), name, "no default value for non-mandatory property");
propValues.put(name, s4Double.defaultValue());
}
Object propObject = propValues.get(name);
Double propValue = propObject instanceof Double ? (Double) propObject : Double.valueOf((String) propObject);
double[] range = s4Double.range();
if (range.length != 2)
throw new InternalConfigurationException(getInstanceName(), name, range + " is not of expected range type, which is {minValue, maxValue)");
if (propValue < range[0] || propValue > range[1])
throw new InternalConfigurationException(getInstanceName(), name, " is not in range (" + range + ")");
return propValue;
}
/**
* Gets the value associated with this name
*
* @param name the name
* @return the value
* @throws edu.cmu.sphinx.util.props.PropertyException
* if the named property is not of this type
*/
public Boolean getBoolean(String name) throws PropertyException {
S4PropWrapper s4PropWrapper = getProperty(name, S4Boolean.class);
S4Boolean s4Boolean = (S4Boolean) s4PropWrapper.getAnnotation();
if (propValues.get(name) == null && !s4Boolean.isNotDefined())
propValues.put(name, s4Boolean.defaultValue());
Object propValue = propValues.get(name);
if (propValue instanceof String)
propValue = Boolean.valueOf((String) propValue);
return (Boolean) propValue;
}
/**
* Gets a component associated with the given parameter name
*
* @param name the parameter name
* @return the component associated with the name
* @throws edu.cmu.sphinx.util.props.PropertyException
* if the component does not exist or is of the wrong type.
*/
public Configurable getComponent(String name) throws PropertyException {
S4PropWrapper s4PropWrapper = getProperty(name, S4Component.class);
S4Component s4Component = (S4Component) s4PropWrapper.getAnnotation();
Class expectedType = s4Component.type();
if (propValues.get(name) == null || propValues.get(name) instanceof String) {
Configurable configurable = null;
try {
if (propValues.get(name) != null) {
PropertySheet ps = cm.getPropertySheet((String) propValues.get(name));
if (ps != null)
configurable = ps.getOwner();
}
if (configurable != null && !expectedType.isInstance(configurable))
throw new InternalConfigurationException(getInstanceName(), name, "mismatch between annoation and component type");
if (configurable == null) {
Class<? extends Configurable> defClass;
if (propValues.get(name) != null)
defClass = (Class<? extends Configurable>) Class.forName((String) propValues.get(name));
else
defClass = s4Component.defaultClass();
if (defClass.equals(Configurable.class) && s4Component.mandatory()) {
throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!");
} else {
- if (Modifier.isAbstract(defClass.getModifiers()))
+ if (Modifier.isAbstract(defClass.getModifiers()) && s4Component.mandatory())
throw new InternalConfigurationException(getInstanceName(), name, defClass.getName() + " is abstract!");
// because we're forced to use the default type, assert that it is set
- if (defClass.equals(Configurable.class))
- throw new InternalConfigurationException(getInstanceName(), name, instanceName + ": no default class defined for " + name);
+ if (defClass.equals(Configurable.class)) {
+ if (s4Component.mandatory()) {
+ throw new InternalConfigurationException(getInstanceName(), name, instanceName + ": no default class defined for " + name);
+ } else {
+ return null;
+ }
+ }
configurable = ConfigurationManager.getInstance(defClass);
assert configurable != null;
}
}
} catch (ClassNotFoundException e) {
throw new PropertyException(e);
}
propValues.put(name, configurable);
}
return (Configurable) propValues.get(name);
}
/** Returns the class of of a registered component property without instantiating it. */
public Class<? extends Configurable> getComponentClass(String propName) {
Class<? extends Configurable> defClass = null;
if (propValues.get(propName) != null)
try {
defClass = (Class<? extends Configurable>) Class.forName((String) propValues.get(propName));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
else {
S4Component comAnno = (S4Component) registeredProperties.get(propName).getAnnotation();
defClass = comAnno.defaultClass();
if (comAnno.mandatory())
defClass = null;
}
return defClass;
}
/**
* Gets a list of components associated with the given parameter name
*
* @param name the parameter name
* @return the component associated with the name
* @throws edu.cmu.sphinx.util.props.PropertyException
* if the component does not exist or is of the wrong type.
*/
public List<? extends Configurable> getComponentList(String name) throws InternalConfigurationException {
getProperty(name, S4ComponentList.class);
List components = (List) propValues.get(name);
assert registeredProperties.get(name).getAnnotation() instanceof S4ComponentList;
S4ComponentList annoation = (S4ComponentList) registeredProperties.get(name).getAnnotation();
// no componets names are available and no comp-list was yet loaded
// therefore load the default list of components from the annoation
if (components == null) {
List<Class<? extends Configurable>> defClasses = Arrays.asList(annoation.defaultList());
// if (annoation.mandatory() && defClasses.isEmpty())
// throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!");
components = new ArrayList();
for (Class<? extends Configurable> defClass : defClasses) {
components.add(ConfigurationManager.getInstance(defClass));
}
propValues.put(name, components);
}
if (!components.isEmpty() && !(components.get(0) instanceof Configurable)) {
List<Configurable> list = new ArrayList<Configurable>();
for (Object componentName : components) {
Configurable configurable = cm.lookup((String) componentName);
assert configurable != null;
list.add(configurable);
}
propValues.put(name, list);
}
return (List<? extends Configurable>) propValues.get(name);
}
public String getInstanceName() {
return instanceName;
}
public void setInstanceName(String newInstanceName) {
this.instanceName = newInstanceName;
}
/** Returns true if the owner of this property sheet is already instanciated. */
public boolean isInstanciated() {
return !(owner == null);
}
/**
* Returns the owner of this property sheet. In most cases this will be the configurable instance which was
* instrumented by this property sheet.
*/
public synchronized Configurable getOwner() {
try {
if (!isInstanciated()) {
owner = ownerClass.newInstance();
owner.newProperties(this);
}
} catch (IllegalAccessException e) {
throw new InternalConfigurationException(e, getInstanceName(), null, "Can't access class " + ownerClass);
} catch (InstantiationException e) {
throw new InternalConfigurationException(e, getInstanceName(), null, "Can't instantiate class " + ownerClass);
}
return owner;
}
/** Returns the class of the owner configurable of this property sheet. */
public Class<? extends Configurable> getConfigurableClass() {
return ownerClass;
}
/**
* Sets the given property to the given name
*
* @param name the simple property name
*/
public void setString(String name, String value) throws PropertyException {
// ensure that there is such a property
assert registeredProperties.keySet().contains(name) : "'" + name + "' is not a registered compontent";
Proxy annotation = registeredProperties.get(name).getAnnotation();
assert annotation instanceof S4String;
applyConfigurationChange(name, value, value);
}
/**
* Sets the given property to the given name
*
* @param name the simple property name
* @param value the value for the property
*/
public void setInt(String name, int value) throws PropertyException {
// ensure that there is such a property
assert registeredProperties.keySet().contains(name) : "'" + name + "' is not a registered compontent";
Proxy annotation = registeredProperties.get(name).getAnnotation();
assert annotation instanceof S4Integer;
applyConfigurationChange(name, value, value);
}
/**
* Sets the given property to the given name
*
* @param name the simple property name
* @param value the value for the property
*/
public void setDouble(String name, double value) throws PropertyException {
// ensure that there is such a property
assert registeredProperties.keySet().contains(name) : "'" + name + "' is not a registered compontent";
Proxy annotation = registeredProperties.get(name).getAnnotation();
assert annotation instanceof S4Double;
applyConfigurationChange(name, value, value);
}
/**
* Sets the given property to the given name
*
* @param name the simple property name
* @param value the value for the property
*/
public void setBoolean(String name, Boolean value) throws PropertyException {
// ensure that there is such a property
assert registeredProperties.keySet().contains(name) : "'" + name + "' is not a registered compontent";
Proxy annotation = registeredProperties.get(name).getAnnotation();
assert annotation instanceof S4Boolean;
applyConfigurationChange(name, value, value);
}
/**
* Sets the given property to the given name
*
* @param name the simple property name
* @param cmName the name of the configurable within the configuration manager (required for serialization only)
* @param value the value for the property
*/
public void setComponent(String name, String cmName, Configurable value) throws PropertyException {
// ensure that there is such a property
assert registeredProperties.keySet().contains(name) : "'" + name + "' is not a registered compontent";
Proxy annotation = registeredProperties.get(name).getAnnotation();
assert annotation instanceof S4Component;
applyConfigurationChange(name, cmName, value);
}
/**
* Sets the given property to the given name
*
* @param name the simple property name
* @param valueNames the list of names of the configurables within the configuration manager (required for
* serialization only)
* @param value the value for the property
*/
public void setComponentList(String name, List<String> valueNames, List<Configurable> value) throws PropertyException {
// ensure that there is such a property
assert registeredProperties.keySet().contains(name) : "'" + name + "' is not a registered compontent";
Proxy annotation = registeredProperties.get(name).getAnnotation();
assert annotation instanceof S4ComponentList;
// assert valueNames.size() == value.size();
rawProps.put(name, valueNames);
propValues.put(name, value);
applyConfigurationChange(name, valueNames, value);
}
private void applyConfigurationChange(String propName, Object cmName, Object value) throws PropertyException {
rawProps.put(propName, cmName);
propValues.put(propName, value);
if (getInstanceName() != null)
cm.fireConfChanged(getInstanceName(), propName);
if (owner != null)
owner.newProperties(this);
}
/**
* Sets the raw property to the given name
*
* @param key the simple property name
* @param val the value for the property
*/
public void setRaw(String key, Object val) {
rawProps.put(key, val);
}
/**
* Gets the raw value associated with this name
*
* @param name the name
* @return the value as an object (it could be a String or a String[] depending upon the property type)
*/
public Object getRaw(String name) {
return rawProps.get(name);
}
/**
* Gets the raw value associated with this name, no global symbol replacement is performed.
*
* @param name the name
* @return the value as an object (it could be a String or a String[] depending upon the property type)
*/
public Object getRawNoReplacement(String name) {
return rawProps.get(name);
}
/** Returns the type of the given property. */
public PropertyType getType(String propName) {
Proxy annotation = registeredProperties.get(propName).getAnnotation();
if (annotation instanceof S4Component)
return PropertyType.COMP;
else if (annotation instanceof S4ComponentList)
return PropertyType.COMPLIST;
else if (annotation instanceof S4Integer)
return PropertyType.INT;
else if (annotation instanceof S4Double)
return PropertyType.DOUBLE;
else if (annotation instanceof S4Boolean)
return PropertyType.BOOL;
else if (annotation instanceof S4String)
return PropertyType.STRING;
else
throw new RuntimeException("Unknown property type");
}
/**
* Gets the owning property manager
*
* @return the property manager
*/
ConfigurationManager getPropertyManager() {
return cm;
}
/**
* Returns a logger to use for this configurable component. The logger can be configured with the property:
* 'logLevel' - The default logLevel value is defined (within the xml configuration file by the global property
* 'defaultLogLevel' (which defaults to WARNING).
* <p/>
* implementation note: the logger became configured within the constructor of the parenting configuration manager.
*
* @return the logger for this component
* @throws edu.cmu.sphinx.util.props.PropertyException
* if an error occurs
*/
public Logger getLogger() {
Logger logger;
if (instanceName != null) {
logger = Logger.getLogger(ownerClass.getName() + "." + instanceName);
} else
logger = Logger.getLogger(ownerClass.getName());
// if there's a logLevel set for component apply to the logger
if (rawProps.get("logLevel") != null)
logger.setLevel(Level.parse((String) rawProps.get("logLevel")));
return logger;
}
/** Returns the names of registered properties of this PropertySheet object. */
public Collection<String> getRegisteredProperties() {
return Collections.unmodifiableCollection(registeredProperties.keySet());
}
public void setCM(ConfigurationManager cm) {
this.cm = cm;
}
/**
* Returns true if two property sheet define the same object in terms of configuration. The owner (and the parent
* configuration manager) are not expected to be the same.
*/
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof PropertySheet))
return false;
PropertySheet ps = (PropertySheet) obj;
if (!rawProps.keySet().equals(ps.rawProps.keySet()))
return false;
// maybe we could test a little bit more here. suggestions?
return true;
}
protected Object clone() throws CloneNotSupportedException {
PropertySheet ps = (PropertySheet) super.clone();
ps.registeredProperties = new HashMap<String, S4PropWrapper>(this.registeredProperties);
ps.propValues = new HashMap<String, Object>(this.propValues);
ps.rawProps = new HashMap<String, Object>(this.rawProps);
// make deep copy of raw-lists
for (String regProp : ps.getRegisteredProperties()) {
if (getType(regProp).equals(PropertyType.COMPLIST)) {
ps.rawProps.put(regProp, new ArrayList<String>((Collection<? extends String>) rawProps.get(regProp)));
ps.propValues.put(regProp, null);
}
}
ps.cm = cm;
ps.owner = null;
ps.instanceName = this.instanceName;
return ps;
}
/**
* use annotation based class parsing to detect the configurable properties of a <code>Configurable</code>-class
*
* @param propertySheet of type PropertySheet
* @param configurable of type Class<? extends Configurable>
*/
public static void processAnnotations(PropertySheet propertySheet, Class<? extends Configurable> configurable) {
Field[] classFields = configurable.getFields();
for (Field field : classFields) {
Annotation[] annotations = field.getAnnotations();
for (Annotation annotation : annotations) {
Annotation[] superAnnotations = annotation.annotationType().getAnnotations();
for (Annotation superAnnotation : superAnnotations) {
if (superAnnotation instanceof S4Property) {
int fieldModifiers = field.getModifiers();
assert Modifier.isStatic(fieldModifiers) : "property fields are assumed to be static";
assert Modifier.isPublic(fieldModifiers) : "property fields are assumed to be public";
assert field.getType().equals(String.class) : "properties fields are assumed to be instances of java.lang.String";
try {
String propertyName = (String) field.get(null);
propertySheet.registerProperty(propertyName, new S4PropWrapper((Proxy) annotation));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
}
}
| false | true | public Configurable getComponent(String name) throws PropertyException {
S4PropWrapper s4PropWrapper = getProperty(name, S4Component.class);
S4Component s4Component = (S4Component) s4PropWrapper.getAnnotation();
Class expectedType = s4Component.type();
if (propValues.get(name) == null || propValues.get(name) instanceof String) {
Configurable configurable = null;
try {
if (propValues.get(name) != null) {
PropertySheet ps = cm.getPropertySheet((String) propValues.get(name));
if (ps != null)
configurable = ps.getOwner();
}
if (configurable != null && !expectedType.isInstance(configurable))
throw new InternalConfigurationException(getInstanceName(), name, "mismatch between annoation and component type");
if (configurable == null) {
Class<? extends Configurable> defClass;
if (propValues.get(name) != null)
defClass = (Class<? extends Configurable>) Class.forName((String) propValues.get(name));
else
defClass = s4Component.defaultClass();
if (defClass.equals(Configurable.class) && s4Component.mandatory()) {
throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!");
} else {
if (Modifier.isAbstract(defClass.getModifiers()))
throw new InternalConfigurationException(getInstanceName(), name, defClass.getName() + " is abstract!");
// because we're forced to use the default type, assert that it is set
if (defClass.equals(Configurable.class))
throw new InternalConfigurationException(getInstanceName(), name, instanceName + ": no default class defined for " + name);
configurable = ConfigurationManager.getInstance(defClass);
assert configurable != null;
}
}
} catch (ClassNotFoundException e) {
throw new PropertyException(e);
}
propValues.put(name, configurable);
}
return (Configurable) propValues.get(name);
}
| public Configurable getComponent(String name) throws PropertyException {
S4PropWrapper s4PropWrapper = getProperty(name, S4Component.class);
S4Component s4Component = (S4Component) s4PropWrapper.getAnnotation();
Class expectedType = s4Component.type();
if (propValues.get(name) == null || propValues.get(name) instanceof String) {
Configurable configurable = null;
try {
if (propValues.get(name) != null) {
PropertySheet ps = cm.getPropertySheet((String) propValues.get(name));
if (ps != null)
configurable = ps.getOwner();
}
if (configurable != null && !expectedType.isInstance(configurable))
throw new InternalConfigurationException(getInstanceName(), name, "mismatch between annoation and component type");
if (configurable == null) {
Class<? extends Configurable> defClass;
if (propValues.get(name) != null)
defClass = (Class<? extends Configurable>) Class.forName((String) propValues.get(name));
else
defClass = s4Component.defaultClass();
if (defClass.equals(Configurable.class) && s4Component.mandatory()) {
throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!");
} else {
if (Modifier.isAbstract(defClass.getModifiers()) && s4Component.mandatory())
throw new InternalConfigurationException(getInstanceName(), name, defClass.getName() + " is abstract!");
// because we're forced to use the default type, assert that it is set
if (defClass.equals(Configurable.class)) {
if (s4Component.mandatory()) {
throw new InternalConfigurationException(getInstanceName(), name, instanceName + ": no default class defined for " + name);
} else {
return null;
}
}
configurable = ConfigurationManager.getInstance(defClass);
assert configurable != null;
}
}
} catch (ClassNotFoundException e) {
throw new PropertyException(e);
}
propValues.put(name, configurable);
}
return (Configurable) propValues.get(name);
}
|
diff --git a/src/minecraft/org/getspout/spout/packet/PacketWidgetRemove.java b/src/minecraft/org/getspout/spout/packet/PacketWidgetRemove.java
index 5dcf5012..c1763c29 100644
--- a/src/minecraft/org/getspout/spout/packet/PacketWidgetRemove.java
+++ b/src/minecraft/org/getspout/spout/packet/PacketWidgetRemove.java
@@ -1,106 +1,105 @@
/*
* This file is part of Spoutcraft (http://wiki.getspout.org/).
*
* Spoutcraft is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Spoutcraft is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.getspout.spout.packet;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.UUID;
import org.getspout.spout.client.SpoutClient;
import org.spoutcraft.spoutcraftapi.gui.InGameHUD;
import org.spoutcraft.spoutcraftapi.gui.PopupScreen;
import org.spoutcraft.spoutcraftapi.gui.Screen;
import org.spoutcraft.spoutcraftapi.gui.Widget;
import org.spoutcraft.spoutcraftapi.gui.WidgetType;
public class PacketWidgetRemove implements SpoutPacket {
protected Widget widget;
protected UUID screen;
public PacketWidgetRemove() {
}
public PacketWidgetRemove(Widget widget, UUID screen) {
this.widget = widget;
this.screen = screen;
}
public int getNumBytes() {
return widget.getNumBytes() + 20;
}
public void readData(DataInputStream input) throws IOException {
int id = input.readInt();
long msb = input.readLong();
long lsb = input.readLong();
screen = new UUID(msb, lsb);
WidgetType widgetType = WidgetType.getWidgetFromId(id);
if (widgetType != null) {
try {
widget = widgetType.getWidgetClass().newInstance();
widget.readData(input);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public void writeData(DataOutputStream output) throws IOException {
output.writeInt(widget.getType().getId());
output.writeLong(screen.getMostSignificantBits());
output.writeLong(screen.getLeastSignificantBits());
widget.writeData(output);
}
public void run(int playerId) {
InGameHUD mainScreen = SpoutClient.getInstance().getActivePlayer().getMainScreen();
PopupScreen popup = mainScreen.getActivePopup();
- Screen overlay = null;
- if(SpoutClient.getHandle().currentScreen != null) {
- overlay = SpoutClient.getHandle().currentScreen.getScreen();
- }
+ Screen overlay = null;
+ if(SpoutClient.getHandle().currentScreen != null) {
+ overlay = SpoutClient.getHandle().currentScreen.getScreen();
+ }
//Determine if this is a popup screen and if we need to update it
if (widget instanceof PopupScreen && popup.getId().equals(widget.getId())) {
// Determine if this is a popup screen and if we need to update it
mainScreen.closePopup();
} else if (widget.getScreen() != null) {
// Otherwise just remove it from the display
widget.getScreen().removeWidget(widget);
}
- //Determine if this is a widget on the overlay screen
- else if (overlay != null && screen.equals(overlay.getId()))
- {
- overlay.removeWidget(widget);
- }
+ //Determine if this is a widget on the overlay screen
+ else if (overlay != null && screen.equals(overlay.getId())) {
+ overlay.removeWidget(widget);
+ }
}
public PacketType getPacketType() {
return PacketType.PacketWidgetRemove;
}
public int getVersion() {
return 0;
}
public void failure(int playerId) {
}
}
| false | true | public void run(int playerId) {
InGameHUD mainScreen = SpoutClient.getInstance().getActivePlayer().getMainScreen();
PopupScreen popup = mainScreen.getActivePopup();
Screen overlay = null;
if(SpoutClient.getHandle().currentScreen != null) {
overlay = SpoutClient.getHandle().currentScreen.getScreen();
}
//Determine if this is a popup screen and if we need to update it
if (widget instanceof PopupScreen && popup.getId().equals(widget.getId())) {
// Determine if this is a popup screen and if we need to update it
mainScreen.closePopup();
} else if (widget.getScreen() != null) {
// Otherwise just remove it from the display
widget.getScreen().removeWidget(widget);
}
//Determine if this is a widget on the overlay screen
else if (overlay != null && screen.equals(overlay.getId()))
{
overlay.removeWidget(widget);
}
}
| public void run(int playerId) {
InGameHUD mainScreen = SpoutClient.getInstance().getActivePlayer().getMainScreen();
PopupScreen popup = mainScreen.getActivePopup();
Screen overlay = null;
if(SpoutClient.getHandle().currentScreen != null) {
overlay = SpoutClient.getHandle().currentScreen.getScreen();
}
//Determine if this is a popup screen and if we need to update it
if (widget instanceof PopupScreen && popup.getId().equals(widget.getId())) {
// Determine if this is a popup screen and if we need to update it
mainScreen.closePopup();
} else if (widget.getScreen() != null) {
// Otherwise just remove it from the display
widget.getScreen().removeWidget(widget);
}
//Determine if this is a widget on the overlay screen
else if (overlay != null && screen.equals(overlay.getId())) {
overlay.removeWidget(widget);
}
}
|
diff --git a/GAE/src/org/waterforpeople/mapping/portal/client/widgets/component/SurveySelectionDialog.java b/GAE/src/org/waterforpeople/mapping/portal/client/widgets/component/SurveySelectionDialog.java
index 386893836..ec85af4cd 100644
--- a/GAE/src/org/waterforpeople/mapping/portal/client/widgets/component/SurveySelectionDialog.java
+++ b/GAE/src/org/waterforpeople/mapping/portal/client/widgets/component/SurveySelectionDialog.java
@@ -1,130 +1,130 @@
package org.waterforpeople.mapping.portal.client.widgets.component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.waterforpeople.mapping.app.gwt.client.util.TextConstants;
import org.waterforpeople.mapping.portal.client.widgets.component.SurveySelectionWidget.Orientation;
import org.waterforpeople.mapping.portal.client.widgets.component.SurveySelectionWidget.SelectionMode;
import org.waterforpeople.mapping.portal.client.widgets.component.SurveySelectionWidget.TerminalType;
import com.gallatinsystems.framework.gwt.util.client.CompletionListener;
import com.gallatinsystems.framework.gwt.util.client.ViewUtil;
import com.gallatinsystems.framework.gwt.util.client.WidgetDialog;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* Dialog box that allows selection of a survey
*
* @author Christopher Fagiani
*
*/
public class SurveySelectionDialog extends WidgetDialog implements ClickHandler {
private static TextConstants TEXT_CONSTANTS = GWT
.create(TextConstants.class);
public static final String SURVEY_KEY = "survey";
public static final String LANG_KEY = "lang";
private SurveySelectionWidget selector;
private Widget additionalControls;
private Button okButton;
private Button cancelButton;
private Label messageLabel;
private ListBox languageBox;
public SurveySelectionDialog(CompletionListener listener,
boolean allowMultiple, Widget additionalControls,
boolean useLangSelection) {
super(TEXT_CONSTANTS.selectSurvey(), null, true, listener);
this.additionalControls = additionalControls;
Panel panel = new VerticalPanel();
messageLabel = new Label();
Panel buttonPanel = new HorizontalPanel();
selector = new SurveySelectionWidget(Orientation.HORIZONTAL,
TerminalType.SURVEY, allowMultiple ? SelectionMode.MULTI
: SelectionMode.SINGLE);
panel.add(selector);
if (additionalControls != null) {
panel.add(additionalControls);
}
if (useLangSelection) {
languageBox = new ListBox(false);
String locale = com.google.gwt.i18n.client.LocaleInfo
.getCurrentLocale().getLocaleName();
languageBox.addItem(TEXT_CONSTANTS.english(), "en");
languageBox.addItem(TEXT_CONSTANTS.french(), "fr");
- languageBox.addItem(TEXT_CONSTANTS.spanish(), "sp");
+ languageBox.addItem(TEXT_CONSTANTS.spanish(), "es");
languageBox.addItem(TEXT_CONSTANTS.kinyarwanda(), "rw");
if ("en".equalsIgnoreCase(locale)) {
languageBox.setSelectedIndex(0);
} else if ("fr".equalsIgnoreCase(locale)) {
languageBox.setSelectedIndex(1);
} else if ("sp".equalsIgnoreCase(locale)) {
languageBox.setSelectedIndex(2);
} else if ("rw".equalsIgnoreCase(locale)) {
languageBox.setSelectedIndex(3);
} else {
languageBox.setSelectedIndex(0);
}
panel.add(ViewUtil.formFieldPair(TEXT_CONSTANTS.language(),
languageBox, ViewUtil.DEFAULT_INPUT_LABEL_CSS));
}
panel.add(messageLabel);
messageLabel.setVisible(false);
okButton = new Button(TEXT_CONSTANTS.ok());
okButton.addClickHandler(this);
cancelButton = new Button(TEXT_CONSTANTS.cancel());
cancelButton.addClickHandler(this);
buttonPanel.add(okButton);
buttonPanel.add(cancelButton);
panel.add(buttonPanel);
setContentWidget(panel);
}
public Widget getAdditionalControls() {
return additionalControls;
}
public SurveySelectionDialog(CompletionListener listener,
boolean allowMultiple) {
this(listener, allowMultiple, null, false);
}
public SurveySelectionDialog(CompletionListener listener) {
this(listener, true);
}
@Override
public void onClick(ClickEvent event) {
if (event.getSource() == cancelButton) {
hide(true);
} else if (event.getSource() == okButton) {
if (selector.getSelectedSurveyIds() == null
|| selector.getSelectedSurveyIds().size() == 0) {
messageLabel.setText(TEXT_CONSTANTS.selectSurveyFirst());
messageLabel.setVisible(true);
} else {
hide(true);
Map<String, Object> payload = new HashMap<String, Object>();
List<Long> ids = selector.getSelectedSurveyIds();
payload.put(SURVEY_KEY, ids.get(0));
if (languageBox != null) {
payload.put(LANG_KEY,
ViewUtil.getListBoxSelection(languageBox, false));
}
notifyListener(true, payload);
}
}
}
}
| true | true | public SurveySelectionDialog(CompletionListener listener,
boolean allowMultiple, Widget additionalControls,
boolean useLangSelection) {
super(TEXT_CONSTANTS.selectSurvey(), null, true, listener);
this.additionalControls = additionalControls;
Panel panel = new VerticalPanel();
messageLabel = new Label();
Panel buttonPanel = new HorizontalPanel();
selector = new SurveySelectionWidget(Orientation.HORIZONTAL,
TerminalType.SURVEY, allowMultiple ? SelectionMode.MULTI
: SelectionMode.SINGLE);
panel.add(selector);
if (additionalControls != null) {
panel.add(additionalControls);
}
if (useLangSelection) {
languageBox = new ListBox(false);
String locale = com.google.gwt.i18n.client.LocaleInfo
.getCurrentLocale().getLocaleName();
languageBox.addItem(TEXT_CONSTANTS.english(), "en");
languageBox.addItem(TEXT_CONSTANTS.french(), "fr");
languageBox.addItem(TEXT_CONSTANTS.spanish(), "sp");
languageBox.addItem(TEXT_CONSTANTS.kinyarwanda(), "rw");
if ("en".equalsIgnoreCase(locale)) {
languageBox.setSelectedIndex(0);
} else if ("fr".equalsIgnoreCase(locale)) {
languageBox.setSelectedIndex(1);
} else if ("sp".equalsIgnoreCase(locale)) {
languageBox.setSelectedIndex(2);
} else if ("rw".equalsIgnoreCase(locale)) {
languageBox.setSelectedIndex(3);
} else {
languageBox.setSelectedIndex(0);
}
panel.add(ViewUtil.formFieldPair(TEXT_CONSTANTS.language(),
languageBox, ViewUtil.DEFAULT_INPUT_LABEL_CSS));
}
panel.add(messageLabel);
messageLabel.setVisible(false);
okButton = new Button(TEXT_CONSTANTS.ok());
okButton.addClickHandler(this);
cancelButton = new Button(TEXT_CONSTANTS.cancel());
cancelButton.addClickHandler(this);
buttonPanel.add(okButton);
buttonPanel.add(cancelButton);
panel.add(buttonPanel);
setContentWidget(panel);
}
| public SurveySelectionDialog(CompletionListener listener,
boolean allowMultiple, Widget additionalControls,
boolean useLangSelection) {
super(TEXT_CONSTANTS.selectSurvey(), null, true, listener);
this.additionalControls = additionalControls;
Panel panel = new VerticalPanel();
messageLabel = new Label();
Panel buttonPanel = new HorizontalPanel();
selector = new SurveySelectionWidget(Orientation.HORIZONTAL,
TerminalType.SURVEY, allowMultiple ? SelectionMode.MULTI
: SelectionMode.SINGLE);
panel.add(selector);
if (additionalControls != null) {
panel.add(additionalControls);
}
if (useLangSelection) {
languageBox = new ListBox(false);
String locale = com.google.gwt.i18n.client.LocaleInfo
.getCurrentLocale().getLocaleName();
languageBox.addItem(TEXT_CONSTANTS.english(), "en");
languageBox.addItem(TEXT_CONSTANTS.french(), "fr");
languageBox.addItem(TEXT_CONSTANTS.spanish(), "es");
languageBox.addItem(TEXT_CONSTANTS.kinyarwanda(), "rw");
if ("en".equalsIgnoreCase(locale)) {
languageBox.setSelectedIndex(0);
} else if ("fr".equalsIgnoreCase(locale)) {
languageBox.setSelectedIndex(1);
} else if ("sp".equalsIgnoreCase(locale)) {
languageBox.setSelectedIndex(2);
} else if ("rw".equalsIgnoreCase(locale)) {
languageBox.setSelectedIndex(3);
} else {
languageBox.setSelectedIndex(0);
}
panel.add(ViewUtil.formFieldPair(TEXT_CONSTANTS.language(),
languageBox, ViewUtil.DEFAULT_INPUT_LABEL_CSS));
}
panel.add(messageLabel);
messageLabel.setVisible(false);
okButton = new Button(TEXT_CONSTANTS.ok());
okButton.addClickHandler(this);
cancelButton = new Button(TEXT_CONSTANTS.cancel());
cancelButton.addClickHandler(this);
buttonPanel.add(okButton);
buttonPanel.add(cancelButton);
panel.add(buttonPanel);
setContentWidget(panel);
}
|
diff --git a/org.springsource.ide.eclipse.commons.core/src/org/springsource/ide/eclipse/commons/core/preferences/StsProperties.java b/org.springsource.ide.eclipse.commons.core/src/org/springsource/ide/eclipse/commons/core/preferences/StsProperties.java
index c2beff21..45e772d1 100644
--- a/org.springsource.ide.eclipse.commons.core/src/org/springsource/ide/eclipse/commons/core/preferences/StsProperties.java
+++ b/org.springsource.ide.eclipse.commons.core/src/org/springsource/ide/eclipse/commons/core/preferences/StsProperties.java
@@ -1,202 +1,202 @@
/*******************************************************************************
* Copyright (c) 2012 - 2013 GoPivotal, Inc.
* 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:
* GoPivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.preferences;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;
import org.eclipse.core.runtime.IProduct;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.springsource.ide.eclipse.commons.core.HttpUtil;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
/**
* An instance of this class provides a mechanism to retrieve String properties.
* This is similar to a Java system properties. However it has support for reading these
* properties from a fixed url. This allows us to change the properties after release.
* <p>
* Properties in this class can come from 3 different sources, listed here in
* decreasing order of priority:
*
* 1) Java System properties (set via -Dmy.prop.name=value) in STS.ini
* (properties set this way override anything else).
* 2) loaded from fixed url
* 3) default values hard-coded in this class.
* (used only if property was not set via either 1 or 2).
*
* @since 3.4.M1
*
* @author Kris De Volder
*/
public class StsProperties {
private static final String PROPERTIES_URL_PROPERTY = "sts.properties.url";
/**
* The properties url is normally defined as a property on the active product {@link IProduct}).
* See the product plugin i.e. 'org.springsource.sts' and 'org.springsource.ggts' for toolsuite-distribution repo.
* <p>
* If STS or GGTS is installed from update site then product may actually be STS or GGTS. In that case
* the 'no_product.properties' url will be used.
*/
private static final String NO_PRODUCT_PROPERTIES = "http://dist.springsource.com/release/STS/discovery/no_product.properties";
//Note: there is also a class called 'ResourceProvider'.. which reads various properties
// from eclipse extension points. This is different because the STSProperties themselves
// are read from an external url.
//The ResourceProvider only allows properties to defined by extensions contained in plugins
// installed into the Ecliple platform.
/**
* This class is a singleton. This holds the instance once created.
*/
private static StsProperties instance = null;
public static StsProperties getInstance(IProgressMonitor mon) {
if (instance==null) {
StsProperties newInstance = new StsProperties(determineUrl(), mon);
instance = newInstance;
}
return instance;
}
private final Properties props;
private StsProperties(String url, IProgressMonitor mon) {
props = createProperties();
if (url!=null) {
try {
InputStream content = HttpUtil.stream(new URI(url), mon);
if (content != null) {
try {
props.load(content);
} finally {
content.close();
}
}
} catch (Throwable e) {
//Catch and log all exceptions. This should never fail to initialise *something* usable.
CorePlugin.warn("Couldn't read sts properties from '"+url+"' internal default values will be used");
}
}
}
/**
* Determines the URL from where the properties file shall be read.
*/
private static String determineUrl() {
//Allow easy overriding by setting a system property:
String url = System.getProperty(PROPERTIES_URL_PROPERTY);
if (url==null) {
IProduct product = Platform.getProduct();
if (product!=null) {
url = product.getProperty(PROPERTIES_URL_PROPERTY);
}
}
if (url==null) {
url = NO_PRODUCT_PROPERTIES;
}
return url;
}
protected Properties createProperties() {
Properties props = new Properties();
// Default properties (guarantees certain properties have a value no
// matter what).
props.put("spring.site.url", "http://springsource.org");
props.put("spring.initializr.form.url", "http://start.springframework.io/");
props.put("spring.initializr.download.url", "http://start.springframework.io/starter.zip");
//Urls used in the dashboard. For each XXX.url=... property, if
// - XXX.url.label is defined that label will be used for the corresponding
// dashboard tab instead of the html page title (title tends to be too long).
// - XXX.url.external is defined that url will always be openened in an external browser.
//Switch to enable new dash
props.put("sts.new.dashboard.enabled", "false");
//Points to where the content for the dash is. If a platform url it will be interpreted as a directory to be
// copied and 'instantiated' by substituting StsProperties. If a non-platform url then it will
// passed directly to the browser without further processing.
// This default value points to a bundled STS dashboard welcome page.
props.put("dashboard.welcome.url", "platform:/plugin/org.springsource.ide.eclipse.commons.gettingstarted/resources/welcome");
//Forum:
props.put("sts.forum.url", "http://forum.springsource.org/forumdisplay.php?32-SpringSource-Tool-Suite");
props.put("sts.forum.url.label", "Forum");
props.put("sts.forum.url.external", "true");
//Tracker:
props.put("sts.tracker.url", "https://issuetracker.springsource.com/browse/STS");
props.put("sts.tracker.url.label", "Issues");
props.put("sts.tracker.url.external", "true");
//Docs
props.put("spring.docs.url", "http://www.springsource.org/documentation");
props.put("spring.docs.url.label", "Spring Docs");
props.put("spring.docs.url.external", "true");
//Blog
props.put("spring.blog.url", "http://blog.springsource.org");
props.put("spring.blog.url.label", "Blog");
props.put("spring.blog.url.external", "true");
//Guides
props.put("spring.guides.url", "http://www.springsource.org/get-started");
props.put("spring.guides.url.label", "Guides");
props.put("spring.guides.url.external", "true");
//future value: "${spring.site.url}/guides"
//New and Noteworthy
props.put("sts.nan.url", "http://static.springsource.org/sts/nan/latest/NewAndNoteworthy.html");
- props.put("spring.guides.url.external", "true");
+ //props.put("sts.nan.url.external", "true");
return props;
}
/**
* Procudes names of properties that have explicitly been set, either from properties file
* or by the explicitly provided defaults. More precisely this does not return
* properties simply inherited from Java system properties.
*/
public Collection<String> getExplicitProperties() {
ArrayList<String> keys = new ArrayList<String>();
for (Object string : props.keySet()) {
if (string instanceof String) {
keys.add((String) string);
}
}
return keys;
}
public String get(String key) {
String value = System.getProperty(key);
if (value == null) {
value = props.getProperty(key);
}
return value;
}
public boolean get(String key, boolean deflt) {
String value = get(key);
if (value!=null) {
return Boolean.valueOf(value);
}
return deflt;
}
}
| true | true | protected Properties createProperties() {
Properties props = new Properties();
// Default properties (guarantees certain properties have a value no
// matter what).
props.put("spring.site.url", "http://springsource.org");
props.put("spring.initializr.form.url", "http://start.springframework.io/");
props.put("spring.initializr.download.url", "http://start.springframework.io/starter.zip");
//Urls used in the dashboard. For each XXX.url=... property, if
// - XXX.url.label is defined that label will be used for the corresponding
// dashboard tab instead of the html page title (title tends to be too long).
// - XXX.url.external is defined that url will always be openened in an external browser.
//Switch to enable new dash
props.put("sts.new.dashboard.enabled", "false");
//Points to where the content for the dash is. If a platform url it will be interpreted as a directory to be
// copied and 'instantiated' by substituting StsProperties. If a non-platform url then it will
// passed directly to the browser without further processing.
// This default value points to a bundled STS dashboard welcome page.
props.put("dashboard.welcome.url", "platform:/plugin/org.springsource.ide.eclipse.commons.gettingstarted/resources/welcome");
//Forum:
props.put("sts.forum.url", "http://forum.springsource.org/forumdisplay.php?32-SpringSource-Tool-Suite");
props.put("sts.forum.url.label", "Forum");
props.put("sts.forum.url.external", "true");
//Tracker:
props.put("sts.tracker.url", "https://issuetracker.springsource.com/browse/STS");
props.put("sts.tracker.url.label", "Issues");
props.put("sts.tracker.url.external", "true");
//Docs
props.put("spring.docs.url", "http://www.springsource.org/documentation");
props.put("spring.docs.url.label", "Spring Docs");
props.put("spring.docs.url.external", "true");
//Blog
props.put("spring.blog.url", "http://blog.springsource.org");
props.put("spring.blog.url.label", "Blog");
props.put("spring.blog.url.external", "true");
//Guides
props.put("spring.guides.url", "http://www.springsource.org/get-started");
props.put("spring.guides.url.label", "Guides");
props.put("spring.guides.url.external", "true");
//future value: "${spring.site.url}/guides"
//New and Noteworthy
props.put("sts.nan.url", "http://static.springsource.org/sts/nan/latest/NewAndNoteworthy.html");
props.put("spring.guides.url.external", "true");
return props;
}
| protected Properties createProperties() {
Properties props = new Properties();
// Default properties (guarantees certain properties have a value no
// matter what).
props.put("spring.site.url", "http://springsource.org");
props.put("spring.initializr.form.url", "http://start.springframework.io/");
props.put("spring.initializr.download.url", "http://start.springframework.io/starter.zip");
//Urls used in the dashboard. For each XXX.url=... property, if
// - XXX.url.label is defined that label will be used for the corresponding
// dashboard tab instead of the html page title (title tends to be too long).
// - XXX.url.external is defined that url will always be openened in an external browser.
//Switch to enable new dash
props.put("sts.new.dashboard.enabled", "false");
//Points to where the content for the dash is. If a platform url it will be interpreted as a directory to be
// copied and 'instantiated' by substituting StsProperties. If a non-platform url then it will
// passed directly to the browser without further processing.
// This default value points to a bundled STS dashboard welcome page.
props.put("dashboard.welcome.url", "platform:/plugin/org.springsource.ide.eclipse.commons.gettingstarted/resources/welcome");
//Forum:
props.put("sts.forum.url", "http://forum.springsource.org/forumdisplay.php?32-SpringSource-Tool-Suite");
props.put("sts.forum.url.label", "Forum");
props.put("sts.forum.url.external", "true");
//Tracker:
props.put("sts.tracker.url", "https://issuetracker.springsource.com/browse/STS");
props.put("sts.tracker.url.label", "Issues");
props.put("sts.tracker.url.external", "true");
//Docs
props.put("spring.docs.url", "http://www.springsource.org/documentation");
props.put("spring.docs.url.label", "Spring Docs");
props.put("spring.docs.url.external", "true");
//Blog
props.put("spring.blog.url", "http://blog.springsource.org");
props.put("spring.blog.url.label", "Blog");
props.put("spring.blog.url.external", "true");
//Guides
props.put("spring.guides.url", "http://www.springsource.org/get-started");
props.put("spring.guides.url.label", "Guides");
props.put("spring.guides.url.external", "true");
//future value: "${spring.site.url}/guides"
//New and Noteworthy
props.put("sts.nan.url", "http://static.springsource.org/sts/nan/latest/NewAndNoteworthy.html");
//props.put("sts.nan.url.external", "true");
return props;
}
|
diff --git a/model/org/eclipse/cdt/internal/core/model/Binary.java b/model/org/eclipse/cdt/internal/core/model/Binary.java
index d0fed86f4..bfda27a9c 100644
--- a/model/org/eclipse/cdt/internal/core/model/Binary.java
+++ b/model/org/eclipse/cdt/internal/core/model/Binary.java
@@ -1,557 +1,557 @@
/*******************************************************************************
* Copyright (c) 2000, 2010 QNX Software Systems 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:
* QNX Software Systems - Initial API and implementation
* Markus Schorn (Wind River Systems)
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.core.model;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.CCorePreferenceConstants;
import org.eclipse.cdt.core.ISourceFinder;
import org.eclipse.cdt.core.ISymbolReader;
import org.eclipse.cdt.core.IBinaryParser.IBinaryExecutable;
import org.eclipse.cdt.core.IBinaryParser.IBinaryFile;
import org.eclipse.cdt.core.IBinaryParser.IBinaryObject;
import org.eclipse.cdt.core.IBinaryParser.IBinaryShared;
import org.eclipse.cdt.core.IBinaryParser.ISymbol;
import org.eclipse.cdt.core.model.BinaryFilePresentation;
import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.IBinary;
import org.eclipse.cdt.core.model.IBuffer;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.internal.core.resources.ResourceLookup;
import org.eclipse.cdt.internal.core.util.MementoTokenizer;
import org.eclipse.core.filesystem.URIUtil;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
public class Binary extends Openable implements IBinary {
private int fBinType;
private String hasDebug;
private String cpu;
private String[] needed;
private long longData;
private long longText;
private long longBSS;
private String endian;
private String soname;
private long fLastModification;
private IBinaryObject binaryObject;
private boolean showInBinaryContainer;
public Binary(ICElement parent, IFile file, IBinaryObject bin) {
super(parent, file, ICElement.C_BINARY);
binaryObject = bin;
showInBinaryContainer= determineShowInBinaryContainer(bin);
}
private boolean determineShowInBinaryContainer(IBinaryObject bin) {
BinaryFilePresentation presentation= (BinaryFilePresentation) bin.getAdapter(BinaryFilePresentation.class);
if (presentation != null) {
return presentation.showInBinaryContainer();
}
return BinaryFilePresentation.showInBinaryContainer(bin);
}
public Binary(ICElement parent, IPath path, IBinaryObject bin) {
super (parent, path, ICElement.C_BINARY);
binaryObject = bin;
showInBinaryContainer= determineShowInBinaryContainer(bin);
}
public boolean isSharedLib() {
return getType() == IBinaryFile.SHARED;
}
public boolean isExecutable() {
return getType() == IBinaryFile.EXECUTABLE;
}
public boolean isObject() {
return getType() == IBinaryFile.OBJECT;
}
public boolean isCore() {
return getType() == IBinaryFile.CORE;
}
public boolean hasDebug() {
if (isObject() || isExecutable() || isSharedLib()) {
if (hasDebug == null || hasChanged()) {
IBinaryObject obj = getBinaryObject();
if (obj != null) {
hasDebug = new Boolean(obj.hasDebug()).toString();
}
}
}
return Boolean.valueOf(hasDebug).booleanValue();
}
public String getCPU() {
if (isObject() || isExecutable() || isSharedLib() || isCore()) {
if (cpu == null || hasChanged()) {
IBinaryObject obj = getBinaryObject();
cpu = obj.getCPU();
}
}
return (cpu == null ? "" : cpu); //$NON-NLS-1$
}
public String[] getNeededSharedLibs() {
if (isExecutable() || isSharedLib()) {
if (needed == null || hasChanged()) {
IBinaryObject obj = getBinaryObject();
if (obj instanceof IBinaryExecutable) {
needed = ((IBinaryExecutable)obj).getNeededSharedLibs();
}
}
}
return (needed == null ? new String[0] : needed);
}
public long getText() {
if (isObject() || isExecutable() || isSharedLib()) {
if (longText == -1 || hasChanged()) {
IBinaryObject obj = getBinaryObject();
if (obj != null) {
longText = obj.getText();
}
}
}
return longText;
}
public long getData() {
if (isObject() || isExecutable() || isSharedLib()) {
if (longData == -1 || hasChanged()) {
IBinaryObject obj = getBinaryObject();
if (obj != null) {
longData = obj.getData();
}
}
}
return longData;
}
public long getBSS() {
if (isObject() || isExecutable() || isSharedLib()) {
if (longBSS == -1 || hasChanged()) {
IBinaryObject obj = getBinaryObject();
if (obj != null) {
longBSS = obj.getBSS();
}
}
}
return longBSS;
}
public String getSoname() {
if (isSharedLib()) {
if (soname == null || hasChanged()) {
IBinaryObject obj = getBinaryObject();
if (obj instanceof IBinaryShared) {
soname = ((IBinaryShared)obj).getSoName();
}
}
}
return (soname == null ? "" : soname); //$NON-NLS-1$
}
public boolean isLittleEndian() {
if (isObject() || isExecutable() || isSharedLib() || isCore()) {
if (endian == null || hasChanged()) {
IBinaryObject obj = getBinaryObject();
if (obj != null) {
endian = new Boolean(obj.isLittleEndian()).toString();
}
}
}
return Boolean.valueOf(endian).booleanValue();
}
protected IBinaryObject getBinaryObject() {
return binaryObject;
}
/* (non-Javadoc)
* @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
*/
@SuppressWarnings("rawtypes")
@Override
public Object getAdapter(Class adapter) {
if (IBinaryObject.class.equals(adapter)) {
return getBinaryObject();
}
return super.getAdapter(adapter);
}
protected int getType() {
IBinaryObject obj = getBinaryObject();
if (obj != null && (fBinType == 0 || hasChanged())) {
fBinType = obj.getType();
}
return fBinType;
}
@Override
protected boolean hasChanged() {
long modification = getModificationStamp();
boolean changed = modification != fLastModification;
fLastModification = modification;
if (changed) {
hasDebug = null;
needed = null;
cpu = null;
endian = null;
longBSS = -1;
longData = -1;
longText = -1;
soname = null;
}
return changed;
}
protected long getModificationStamp() {
IResource res = getResource();
if (res != null) {
return res.getModificationStamp();
}
return 0;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.model.ICElement#isReadOnly()
*/
@Override
public boolean isReadOnly() {
return true;
}
@Override
public CElementInfo createElementInfo() {
return new BinaryInfo(this);
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.model.Openable#buildStructure(org.eclipse.cdt.internal.core.model.OpenableInfo, org.eclipse.core.runtime.IProgressMonitor, java.util.Map, org.eclipse.core.resources.IResource)
*/
@Override
protected boolean buildStructure(OpenableInfo info, IProgressMonitor pm, Map<ICElement, CElementInfo> newElements, IResource underlyingResource)
throws CModelException {
return computeChildren(info, underlyingResource);
}
boolean computeChildren(OpenableInfo info, IResource res) throws CModelException {
boolean ok = false;
if (isObject() || isExecutable() || isSharedLib()) {
Map<IPath, BinaryModule> hash = new HashMap<IPath, BinaryModule>();
IBinaryObject obj = getBinaryObject();
if (obj != null) {
// First check if we can get the list of source
// files used to build the binary from the symbol
// information. if not, fall back on information from the binary parser.
boolean showSourceFiles = CCorePlugin.getDefault().getPluginPreferences().getBoolean( CCorePreferenceConstants.SHOW_SOURCE_FILES_IN_BINARIES );
if (!showSourceFiles ||
!addSourceFiles(info, obj, hash))
{
ISymbol[] symbols = obj.getSymbols();
for (ISymbol symbol : symbols) {
switch (symbol.getType()) {
case ISymbol.FUNCTION :
addFunction(info, symbol, hash);
break;
case ISymbol.VARIABLE :
addVariable(info, symbol, hash);
break;
}
}
}
ok = true;
}
}
return ok;
}
private boolean addSourceFiles(OpenableInfo info, IBinaryObject obj,
Map<IPath, BinaryModule> hash) throws CModelException {
// Try to get the list of source files used to build the binary from the
// symbol information.
ISymbolReader symbolreader = (ISymbolReader)obj.getAdapter(ISymbolReader.class);
if (symbolreader == null)
return false;
String[] sourceFiles = symbolreader.getSourceFiles();
if (sourceFiles != null && sourceFiles.length > 0) {
ISourceFinder srcFinder = (ISourceFinder) getAdapter(ISourceFinder.class);
try {
for (String filename : sourceFiles) {
// Find the file locally
if (srcFinder != null) {
String localPath = srcFinder.toLocalPath(filename);
if (localPath != null) {
filename = localPath;
}
}
// Be careful how you use this File object. If filename is a relative path, the resulting File
// object will apply the relative path to the working directory, which is not what we want.
// Stay away from methods that return or use the absolute path of the object. Note that
// File.isAbsolute() returns false when the object was constructed with a relative path.
File file = new File(filename);
// Create a translation unit for this file and add it as a child of the binary
String id = CoreModel.getRegistedContentTypeId(getCProject().getProject(), file.getName());
if (id == null) {
// Don't add files we can't get an ID for.
continue;
}
// See if this source file is already in the project.
// We check this to determine if we should create a TranslationUnit or ExternalTranslationUnit
IFile wkspFile = null;
if (file.isAbsolute()) {
IFile[] filesInWP = ResourceLookup.findFilesForLocation(new Path(filename));
for (IFile element : filesInWP) {
if (element.isAccessible()) {
wkspFile = element;
break;
}
}
}
TranslationUnit tu;
if (wkspFile != null)
tu = new TranslationUnit(this, wkspFile, id);
else {
// If we have an absolute path (for the host file system), then use an IPath to create the
// ExternalTranslationUnit, as that is the more accurate way to specify the file. If it's
// not, then use the path specification we got from the debug information. We want to
// avoid, e.g., converting a UNIX path to a Windows one when debugging a UNIX-built binary
// on Windows. The opportunity to remap source paths was taken above, when we called
// ISourceFinder. If a mapping didn't occur, we want to preserve whatever the debug
// information told us. See bugzilla 297781
if (file.isAbsolute()) {
tu = new ExternalTranslationUnit(this, Path.fromOSString(filename), id);
}
else {
- tu = new ExternalTranslationUnit(this, URIUtil.toURI(filename), id);
+ tu = new ExternalTranslationUnit(this, URIUtil.toURI(filename, true), id);
}
}
if (! info.includesChild(tu))
info.addChild(tu);
}
return true;
}
finally {
if (srcFinder != null) {
srcFinder.dispose();
}
}
}
return false;
}
private void addFunction(OpenableInfo info, ISymbol symbol, Map<IPath, BinaryModule> hash) throws CModelException {
IPath filename= symbol.getFilename();
BinaryFunction function = null;
if (filename != null && !filename.isEmpty()) {
BinaryModule module = null;
if (hash.containsKey(filename)) {
module = hash.get(filename);
} else {
// A special container we do not want the file to be parse.
module = new BinaryModule(this, filename);
hash.put(filename, module);
info.addChild(module);
}
function = new BinaryFunction(module, symbol.getName(), symbol.getAddress());
function.setLines(symbol.getStartLine(), symbol.getEndLine());
module.addChild(function);
} else {
//function = new Function(parent, symbol.getName());
function = new BinaryFunction(this, symbol.getName(), symbol.getAddress());
function.setLines(symbol.getStartLine(), symbol.getEndLine());
info.addChild(function);
}
// if (function != null) {
// if (!external) {
// function.getFunctionInfo().setAccessControl(IConstants.AccStatic);
// }
// }
}
private void addVariable(OpenableInfo info, ISymbol symbol, Map<IPath, BinaryModule> hash) throws CModelException {
IPath filename= symbol.getFilename();
BinaryVariable variable = null;
if (filename != null && !filename.isEmpty()) {
BinaryModule module = null;
if (hash.containsKey(filename)) {
module = hash.get(filename);
} else {
module = new BinaryModule(this, filename);
hash.put(filename, module);
info.addChild(module);
}
variable = new BinaryVariable(module, symbol.getName(), symbol.getAddress());
variable.setLines(symbol.getStartLine(), symbol.getEndLine());
module.addChild(variable);
} else {
variable = new BinaryVariable(this, symbol.getName(), symbol.getAddress());
variable.setLines(symbol.getStartLine(), symbol.getEndLine());
info.addChild(variable);
}
//if (variable != null) {
// if (!external) {
// variable.getVariableInfo().setAccessControl(IConstants.AccStatic);
// }
//}
}
/**
* @see org.eclipse.cdt.core.model.IOpenable#getBuffer()
*
* overridden from default as we do not need to create our children to provider a buffer since the buffer just contains
* IBinaryOject contents which is not model specific.
*/
@Override
public IBuffer getBuffer() throws CModelException {
if (hasBuffer()) {
IBuffer buffer = getBufferManager().getBuffer(this);
if (buffer == null) {
// try to (re)open a buffer
buffer = openBuffer(null);
}
return buffer;
}
return null;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.model.Openable#openBuffer(org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
protected IBuffer openBuffer(IProgressMonitor pm) throws CModelException {
// create buffer - translation units only use default buffer factory
BufferManager bufManager = getBufferManager();
IBuffer buffer = getBufferFactory().createBuffer(this);
if (buffer == null)
return null;
// set the buffer source
if (buffer.getCharacters() == null){
IBinaryObject bin = getBinaryObject();
if (bin != null) {
StringBuffer sb = new StringBuffer();
try {
BufferedReader stream = new BufferedReader(new InputStreamReader(bin.getContents()));
char[] buf = new char[512];
int len;
while ((len = stream.read(buf, 0, buf.length)) != -1) {
sb.append(buf, 0, len);
}
} catch (IOException e) {
// nothint.
}
buffer.setContents(sb.toString());
} else {
IResource file = this.getResource();
if (file != null && file.getType() == IResource.FILE) {
buffer.setContents(Util.getResourceContentsAsCharArray((IFile)file));
}
}
}
// add buffer to buffer cache
bufManager.addBuffer(buffer);
// listen to buffer changes
buffer.addBufferChangedListener(this);
return buffer;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.model.Openable#hasBuffer()
*/
@Override
protected boolean hasBuffer() {
return true;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.model.ICElement#exists()
*/
@Override
public boolean exists() {
IResource res = getResource();
if (res != null)
return res.exists();
return super.exists();
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.model.CElement#closing(java.lang.Object)
*/
@Override
protected void closing(Object info) throws CModelException {
ICProject cproject = getCProject();
CProjectInfo pinfo = (CProjectInfo)CModelManager.getDefault().peekAtInfo(cproject);
if (pinfo != null && pinfo.vBin != null) {
pinfo.vBin.removeChild(this);
}
super.closing(info);
}
public boolean showInBinaryContainer() {
return showInBinaryContainer;
}
@Override
public ICElement getHandleFromMemento(String token, MementoTokenizer memento) {
return null;
}
@Override
public String getHandleMemento() {
return null;
}
@Override
protected char getHandleMementoDelimiter() {
Assert.isTrue(false, "Should not be called"); //$NON-NLS-1$
return 0;
}
}
| true | true | private boolean addSourceFiles(OpenableInfo info, IBinaryObject obj,
Map<IPath, BinaryModule> hash) throws CModelException {
// Try to get the list of source files used to build the binary from the
// symbol information.
ISymbolReader symbolreader = (ISymbolReader)obj.getAdapter(ISymbolReader.class);
if (symbolreader == null)
return false;
String[] sourceFiles = symbolreader.getSourceFiles();
if (sourceFiles != null && sourceFiles.length > 0) {
ISourceFinder srcFinder = (ISourceFinder) getAdapter(ISourceFinder.class);
try {
for (String filename : sourceFiles) {
// Find the file locally
if (srcFinder != null) {
String localPath = srcFinder.toLocalPath(filename);
if (localPath != null) {
filename = localPath;
}
}
// Be careful how you use this File object. If filename is a relative path, the resulting File
// object will apply the relative path to the working directory, which is not what we want.
// Stay away from methods that return or use the absolute path of the object. Note that
// File.isAbsolute() returns false when the object was constructed with a relative path.
File file = new File(filename);
// Create a translation unit for this file and add it as a child of the binary
String id = CoreModel.getRegistedContentTypeId(getCProject().getProject(), file.getName());
if (id == null) {
// Don't add files we can't get an ID for.
continue;
}
// See if this source file is already in the project.
// We check this to determine if we should create a TranslationUnit or ExternalTranslationUnit
IFile wkspFile = null;
if (file.isAbsolute()) {
IFile[] filesInWP = ResourceLookup.findFilesForLocation(new Path(filename));
for (IFile element : filesInWP) {
if (element.isAccessible()) {
wkspFile = element;
break;
}
}
}
TranslationUnit tu;
if (wkspFile != null)
tu = new TranslationUnit(this, wkspFile, id);
else {
// If we have an absolute path (for the host file system), then use an IPath to create the
// ExternalTranslationUnit, as that is the more accurate way to specify the file. If it's
// not, then use the path specification we got from the debug information. We want to
// avoid, e.g., converting a UNIX path to a Windows one when debugging a UNIX-built binary
// on Windows. The opportunity to remap source paths was taken above, when we called
// ISourceFinder. If a mapping didn't occur, we want to preserve whatever the debug
// information told us. See bugzilla 297781
if (file.isAbsolute()) {
tu = new ExternalTranslationUnit(this, Path.fromOSString(filename), id);
}
else {
tu = new ExternalTranslationUnit(this, URIUtil.toURI(filename), id);
}
}
if (! info.includesChild(tu))
info.addChild(tu);
}
return true;
}
finally {
if (srcFinder != null) {
srcFinder.dispose();
}
}
}
return false;
}
| private boolean addSourceFiles(OpenableInfo info, IBinaryObject obj,
Map<IPath, BinaryModule> hash) throws CModelException {
// Try to get the list of source files used to build the binary from the
// symbol information.
ISymbolReader symbolreader = (ISymbolReader)obj.getAdapter(ISymbolReader.class);
if (symbolreader == null)
return false;
String[] sourceFiles = symbolreader.getSourceFiles();
if (sourceFiles != null && sourceFiles.length > 0) {
ISourceFinder srcFinder = (ISourceFinder) getAdapter(ISourceFinder.class);
try {
for (String filename : sourceFiles) {
// Find the file locally
if (srcFinder != null) {
String localPath = srcFinder.toLocalPath(filename);
if (localPath != null) {
filename = localPath;
}
}
// Be careful how you use this File object. If filename is a relative path, the resulting File
// object will apply the relative path to the working directory, which is not what we want.
// Stay away from methods that return or use the absolute path of the object. Note that
// File.isAbsolute() returns false when the object was constructed with a relative path.
File file = new File(filename);
// Create a translation unit for this file and add it as a child of the binary
String id = CoreModel.getRegistedContentTypeId(getCProject().getProject(), file.getName());
if (id == null) {
// Don't add files we can't get an ID for.
continue;
}
// See if this source file is already in the project.
// We check this to determine if we should create a TranslationUnit or ExternalTranslationUnit
IFile wkspFile = null;
if (file.isAbsolute()) {
IFile[] filesInWP = ResourceLookup.findFilesForLocation(new Path(filename));
for (IFile element : filesInWP) {
if (element.isAccessible()) {
wkspFile = element;
break;
}
}
}
TranslationUnit tu;
if (wkspFile != null)
tu = new TranslationUnit(this, wkspFile, id);
else {
// If we have an absolute path (for the host file system), then use an IPath to create the
// ExternalTranslationUnit, as that is the more accurate way to specify the file. If it's
// not, then use the path specification we got from the debug information. We want to
// avoid, e.g., converting a UNIX path to a Windows one when debugging a UNIX-built binary
// on Windows. The opportunity to remap source paths was taken above, when we called
// ISourceFinder. If a mapping didn't occur, we want to preserve whatever the debug
// information told us. See bugzilla 297781
if (file.isAbsolute()) {
tu = new ExternalTranslationUnit(this, Path.fromOSString(filename), id);
}
else {
tu = new ExternalTranslationUnit(this, URIUtil.toURI(filename, true), id);
}
}
if (! info.includesChild(tu))
info.addChild(tu);
}
return true;
}
finally {
if (srcFinder != null) {
srcFinder.dispose();
}
}
}
return false;
}
|
diff --git a/AppServer_Java/src/com/google/appengine/api/users/dev/LoginCookieUtils.java b/AppServer_Java/src/com/google/appengine/api/users/dev/LoginCookieUtils.java
index bc0fc715b..83a9ec6eb 100644
--- a/AppServer_Java/src/com/google/appengine/api/users/dev/LoginCookieUtils.java
+++ b/AppServer_Java/src/com/google/appengine/api/users/dev/LoginCookieUtils.java
@@ -1,240 +1,240 @@
package com.google.appengine.api.users.dev;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/*
* AppScale -- added two imports
*/
import java.util.logging.Logger;
import java.util.logging.Level;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public final class LoginCookieUtils
{
public static final String COOKIE_PATH = "/";
public static final String COOKIE_NAME = "dev_appserver_login";
private static final int COOKIE_AGE = -1;
private final static String SHA = "SHA";
private final static String MD5 = "MD5";
private static final String EMAIL_PREPEND = "1";
private static final String APPLICATION_ID_PROPERTY = "APPLICATION_ID";
private static final String COOKIE_SECRET_PROPERTY = "COOKIE_SECRET";
/*
* AppScale -- added next two final variables
*/
private static final Logger logger = Logger.getLogger(LoginCookieUtils.class.getName());
// used for parsing cookie
private static final String hextab = "0123456789abcdef";
/*
* AppScale -- replaced method body -- should not be called b/c
* AppDashboard handles this now, this method is not called
* so adding Exception to catch when it is
*/
public static Cookie createCookie( String email, boolean isAdmin )
{
if (true) throw new UnsupportedOperationException("Unexpected code path: createCookie(String,boolean) in LoginCookieUtils.");
String userId = encodeEmailAsUserId(email);
Cookie cookie = new Cookie("dev_appserver_login", email + ":" + isAdmin + ":" + userId);
cookie.setPath(COOKIE_PATH);
cookie.setMaxAge(COOKIE_AGE);
logger.warning("Creating cookie by original jetty server, should be done by AppDashboard");
logger.warning("Cookie is: " + cookie.toString());
return cookie;
}
/*
* AppScale -- replaced method body this method should not be called b/c
* AppDashboard handles this now Chandra says: but it is called when a
* login route is requested when cookie is null (so throw exception on an
* attemp to remove a valid cookie) If these are not the semantics we want,
* then replace this method so that it is correct.
*/
public static void removeCookie( HttpServletRequest req, HttpServletResponse resp )
{
Cookie cookie = findCookie(req);
if (cookie != null)
{
if (true) throw new UnsupportedOperationException("Unexpected code path: removeCookie(String,boolean) in LoginCookieUtils.");
cookie.setPath("/");
cookie.setMaxAge(0);
resp.addCookie(cookie);
logger.warning("Revoking cookie by original jetty server, should be done by AppDashboard");
logger.warning("Cookie is: " + cookie.toString());
}
else
{
logger.info("DevAppServer/jetty server LoginCookieUtils removeCookie on null cookie (as expected)");
}
}
public static AppScaleCookieData getCookieData( HttpServletRequest req )
{
Cookie cookie = findCookie(req);
if (cookie == null)
{
return null;
}
return parseCookie(cookie);
}
public static String encodeEmailAsUserId( String email )
{
try
{
MessageDigest md5 = MessageDigest.getInstance(MD5);
md5.update(email.toLowerCase().getBytes());
StringBuilder builder = new StringBuilder();
builder.append(EMAIL_PREPEND);
for (byte b : md5.digest())
{
builder.append(String.format("%02d", new Object[] { Integer.valueOf(b & 0xFF) }));
}
return builder.toString().substring(0, 20);
}
catch (NoSuchAlgorithmException ex)
{
}
return "";
}
/*
* AppScale - replaced method
*/
private static AppScaleCookieData parseCookie( Cookie cookie )
{
String value = cookie.getValue();
// replace chars
value = value.replace("%3A", ":");
value = value.replace("%40", "@");
value = value.replace("%2C", ",");
String[] parts = value.split(":");
if (parts.length < 4)
{
logger.log(Level.SEVERE, "Invalid cookie");
return new AppScaleCookieData("", false, "", false);
}
String email = parts[0];
String nickname = parts[1];
boolean admin = false;
String adminList[] = parts[2].split(",");
String curApp = System.getProperty(APPLICATION_ID_PROPERTY);
if (curApp == null)
{
logger.log(Level.FINE, "Current app is not set when placing cookie!");
}
else
{
for (int i = 0; i < adminList.length; i++)
{
if (adminList[i].equals(curApp))
{
// logger.log(Level.FINE, "set admin to true");
admin = true;
}
}
}
String hsh = parts[3];
boolean valid_cookie = true;
String cookie_secret = System.getProperty(COOKIE_SECRET_PROPERTY);
if (cookie_secret == "")
{
return new AppScaleCookieData("", false, "", false);
}
if (email.equals(""))
{
nickname = "";
admin = false;
}
else
{
try
{
MessageDigest sha = MessageDigest.getInstance(SHA);
sha.update((email + nickname + parts[2] + cookie_secret).getBytes());
StringBuilder builder = new StringBuilder();
// padding 0
for (byte b : sha.digest())
{
byte tmphigh = (byte)(b >> 4);
tmphigh = (byte)(tmphigh & 0xf);
builder.append(hextab.charAt(tmphigh));
byte tmplow = (byte)(b & 0xf);
builder.append(hextab.charAt(tmplow));
}
String vhsh = builder.toString();
if (!vhsh.equals(hsh))
{
valid_cookie = false;
- }
- else
- {
+ email = "";
+ admin = false;
+ nickname = "";
}
}
catch (NoSuchAlgorithmException e)
{
logger.log(Level.SEVERE, "Decoding cookie failed");
return new AppScaleCookieData("", false, "", false);
}
}
return new AppScaleCookieData(email, admin, nickname, valid_cookie);
}
private static Cookie findCookie( HttpServletRequest req )
{
Cookie[] cookies = req.getCookies();
if (cookies != null)
{
for (Cookie cookie : cookies)
{
if (cookie.getName().equals("dev_appserver_login"))
{
return cookie;
}
}
}
return null;
}
public static final class AppScaleCookieData
{
private final String email;
private final boolean isAdmin;
private final String nickname;
private final boolean valid;
public AppScaleCookieData( String email, boolean isAdmin, String nickname, boolean isValid )
{
this.email = email;
this.isAdmin = isAdmin;
this.nickname = nickname;
this.valid = isValid;
}
public String getEmail()
{
return this.email;
}
public boolean isAdmin()
{
return this.isAdmin;
}
public String getUserId()
{
return this.nickname;
}
public boolean isValid()
{
return this.valid;
}
}
}
| true | true | private static AppScaleCookieData parseCookie( Cookie cookie )
{
String value = cookie.getValue();
// replace chars
value = value.replace("%3A", ":");
value = value.replace("%40", "@");
value = value.replace("%2C", ",");
String[] parts = value.split(":");
if (parts.length < 4)
{
logger.log(Level.SEVERE, "Invalid cookie");
return new AppScaleCookieData("", false, "", false);
}
String email = parts[0];
String nickname = parts[1];
boolean admin = false;
String adminList[] = parts[2].split(",");
String curApp = System.getProperty(APPLICATION_ID_PROPERTY);
if (curApp == null)
{
logger.log(Level.FINE, "Current app is not set when placing cookie!");
}
else
{
for (int i = 0; i < adminList.length; i++)
{
if (adminList[i].equals(curApp))
{
// logger.log(Level.FINE, "set admin to true");
admin = true;
}
}
}
String hsh = parts[3];
boolean valid_cookie = true;
String cookie_secret = System.getProperty(COOKIE_SECRET_PROPERTY);
if (cookie_secret == "")
{
return new AppScaleCookieData("", false, "", false);
}
if (email.equals(""))
{
nickname = "";
admin = false;
}
else
{
try
{
MessageDigest sha = MessageDigest.getInstance(SHA);
sha.update((email + nickname + parts[2] + cookie_secret).getBytes());
StringBuilder builder = new StringBuilder();
// padding 0
for (byte b : sha.digest())
{
byte tmphigh = (byte)(b >> 4);
tmphigh = (byte)(tmphigh & 0xf);
builder.append(hextab.charAt(tmphigh));
byte tmplow = (byte)(b & 0xf);
builder.append(hextab.charAt(tmplow));
}
String vhsh = builder.toString();
if (!vhsh.equals(hsh))
{
valid_cookie = false;
}
else
{
}
}
catch (NoSuchAlgorithmException e)
{
logger.log(Level.SEVERE, "Decoding cookie failed");
return new AppScaleCookieData("", false, "", false);
}
}
return new AppScaleCookieData(email, admin, nickname, valid_cookie);
}
| private static AppScaleCookieData parseCookie( Cookie cookie )
{
String value = cookie.getValue();
// replace chars
value = value.replace("%3A", ":");
value = value.replace("%40", "@");
value = value.replace("%2C", ",");
String[] parts = value.split(":");
if (parts.length < 4)
{
logger.log(Level.SEVERE, "Invalid cookie");
return new AppScaleCookieData("", false, "", false);
}
String email = parts[0];
String nickname = parts[1];
boolean admin = false;
String adminList[] = parts[2].split(",");
String curApp = System.getProperty(APPLICATION_ID_PROPERTY);
if (curApp == null)
{
logger.log(Level.FINE, "Current app is not set when placing cookie!");
}
else
{
for (int i = 0; i < adminList.length; i++)
{
if (adminList[i].equals(curApp))
{
// logger.log(Level.FINE, "set admin to true");
admin = true;
}
}
}
String hsh = parts[3];
boolean valid_cookie = true;
String cookie_secret = System.getProperty(COOKIE_SECRET_PROPERTY);
if (cookie_secret == "")
{
return new AppScaleCookieData("", false, "", false);
}
if (email.equals(""))
{
nickname = "";
admin = false;
}
else
{
try
{
MessageDigest sha = MessageDigest.getInstance(SHA);
sha.update((email + nickname + parts[2] + cookie_secret).getBytes());
StringBuilder builder = new StringBuilder();
// padding 0
for (byte b : sha.digest())
{
byte tmphigh = (byte)(b >> 4);
tmphigh = (byte)(tmphigh & 0xf);
builder.append(hextab.charAt(tmphigh));
byte tmplow = (byte)(b & 0xf);
builder.append(hextab.charAt(tmplow));
}
String vhsh = builder.toString();
if (!vhsh.equals(hsh))
{
valid_cookie = false;
email = "";
admin = false;
nickname = "";
}
}
catch (NoSuchAlgorithmException e)
{
logger.log(Level.SEVERE, "Decoding cookie failed");
return new AppScaleCookieData("", false, "", false);
}
}
return new AppScaleCookieData(email, admin, nickname, valid_cookie);
}
|
diff --git a/src/com/moupress/app/ui/UIMgr.java b/src/com/moupress/app/ui/UIMgr.java
index d21f312..b1a8bce 100644
--- a/src/com/moupress/app/ui/UIMgr.java
+++ b/src/com/moupress/app/ui/UIMgr.java
@@ -1,660 +1,661 @@
package com.moupress.app.ui;
import java.util.ArrayList;
import java.util.Calendar;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;
import kankan.wheel.widget.adapters.NumericWheelAdapter;
import android.app.Activity;
import android.app.AlarmManager;
import android.content.Context;
import android.gesture.GestureOverlayView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;
import com.moupress.app.ui.SlideButton.OnChangeListener;
import com.moupress.app.ui.SlideButton.SlideButton;
import com.moupress.app.ui.SlideButton.TextSlideButtonAdapter;
import com.moupress.app.ui.SlideButton.SlideButtonAdapter;
import com.moupress.app.Const;
import com.moupress.app.R;
import com.moupress.app.util.DbHelper;
public class UIMgr {
Activity activity;
public UIMgr(Activity activity) {
this.activity = activity;
initAlarmSettings();
initUI();
initSoonzeControls();
}
/**
* Initialize all UIs
*/
private void initUI() {
this.initHomeUI();
this.initSnoozeUI();
this.initAlarmTimeUI();
this.initAlarmSoundUI();
this.initToolbarUI();
this.initMainContainer();
}
// =======================Home UI==============================================
public ListView hsListView;
private AlarmListViewAdapter hsListAdapter;
private String[] hsDisplayTxt = { "Rain 10C", "No Alarm Set", "Gesture" };
private int[] hsDisplayIcon = { R.drawable.world, R.drawable.clock,
R.drawable.disc };
private boolean[] hsSelected = { false, false, false };
/**
* Initilise home screen.
*/
private void initHomeUI() {
hsListView = (ListView) activity.findViewById(R.id.hslistview);
hsListAdapter = new AlarmListViewAdapter(hsDisplayTxt, hsDisplayIcon, hsSelected);
hsListView.setAdapter(hsListAdapter);
hsListView.setOnItemClickListener(optionListOnItemClickListener);
}
// =======================Snooze UI==============================================
public ListView snoozeListView;
private AlarmListViewAdapter snoozeAdapter;
private String[] snoozeDisplayTxt = { "Gesture", "Flip", "Swing" };
private int[] snoozeDisplayIcon = { R.drawable.disc, R.drawable.disc,R.drawable.disc };
private boolean[] snoozeSelected = { true, true, true };
/**
* Initialize snooze screen
*/
private void initSnoozeUI() {
snoozeListView = (ListView) activity.findViewById(R.id.snoozelistview);
snoozeAdapter = new AlarmListViewAdapter(snoozeDisplayTxt,snoozeDisplayIcon, snoozeSelected);
snoozeListView.setAdapter(snoozeAdapter);
snoozeListView.setOnItemClickListener(optionListOnItemClickListener);
}
// =======================Alarm Time UI==============================================
public ListView alarmListView;
private AlarmListViewAdapter alarmAdapter;
private WheelView hours;
private WheelView minutes;
private WheelView amOrpm;
private Button btnUpdateTimeOk;
private Button btnUpdateTimeCancel;
private String[] alarmDisplayTxt = { "8:00 am", "9:00 am", "10:00 am" };
private int[] alarmDisplayIcon = { R.drawable.clock, R.drawable.clock,R.drawable.clock };
private boolean[] alarmSelected = { false, false, false };
private static int ALARM_POSITION = 0;
private String[] AMPM = { "am", "pm" };
private boolean bSettingAlarmTimeDisableFlip;
private NewsAlarmSlidingUpPanel timeSlidingUpPanel;
private static final String[] weekdays = new String[]{"S","M","T","W","T","F","S"};
private boolean[] daySelected = new boolean[]{false,false,false,false,false,false,false};
private SlideButtonAdapter viewAdapter;
private SlideButton slideBtn;
/**
* Initialize Alarm Time Screen
*/
private void initAlarmTimeUI() {
alarmListView = (ListView) activity.findViewById(R.id.alarmlistview);
alarmAdapter = new AlarmListViewAdapter(alarmDisplayTxt,alarmDisplayIcon, alarmSelected);
alarmListView.setAdapter(alarmAdapter);
alarmListView.setOnItemClickListener(optionListOnItemClickListener);
alarmListView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
ALARM_POSITION = position;
buttonBarSlidingUpPanel.toggle();
// timeSlidingUpPanel.toggle();
return true;
}
});
btnUpdateTimeOk = (Button) activity.findViewById(R.id.timeaddok);
btnUpdateTimeCancel = (Button) activity.findViewById(R.id.timeaddcancel);
btnUpdateTimeOk.setOnClickListener(alarmWheelButtonListener);
btnUpdateTimeCancel.setOnClickListener(alarmWheelButtonListener);
timeSlidingUpPanel = (NewsAlarmSlidingUpPanel) activity.findViewById(R.id.timeupdatepanel);
timeSlidingUpPanel.setOpen(false);
timeSlidingUpPanel
.setPanelSlidingListener(new NewsAlarmSlidingUpPanel.PanelSlidingListener() {
@Override
public void onSlidingUpEnd() {
}
@Override
public void onSlidingDownEnd() {
bSettingAlarmTimeDisableFlip = false;
buttonBarSlidingUpPanel.toggle();
}
});
bSettingAlarmTimeDisableFlip = false;
hours = (WheelView) activity.findViewById(R.id.wheelhour);
minutes = (WheelView) activity.findViewById(R.id.wheelminute);
amOrpm = (WheelView) activity.findViewById(R.id.wheelsecond);
hours.setViewAdapter(new NumericWheelAdapter(activity, 0, 12));
hours.setCurrentItem(6);
minutes.setViewAdapter(new NumericWheelAdapter(activity, 0, 59, "%02d"));
minutes.setCurrentItem(30);
amOrpm.setViewAdapter(new ArrayWheelAdapter<String>(activity, AMPM));
slideBtn =(SlideButton) activity.findViewById(R.id.slideBtn);
slideBtn.setOnChangedListener(new OnChangeListener()
{
public void OnChanged(int i,boolean direction,View v) {
if(direction == true)
{
((TextView)v).setTextColor(activity.getResources().getColor(R.color.royal_blue));
daySelected[i]=true;
}
else
{
((TextView)v).setTextColor(activity.getResources().getColor(R.color.black));
daySelected[i]=false;
}
}
@Override
public void OnSelected(int i, View v, int mode) {
if(mode == 0)
{
if(daySelected[i]==true)
{
daySelected[i]= false;
((TextView)v).setTextColor(activity.getResources().getColor(R.color.black));
}
else
{
daySelected[i]= true;
((TextView)v).setTextColor(activity.getResources().getColor(R.color.royal_blue));
}
}
else if(mode == 1)
{
daySelected[i]= true;
((TextView)v).setTextColor(activity.getResources().getColor(R.color.royal_blue));
}
else if (mode == 2)
{
daySelected[i]= false;
((TextView)v).setTextColor(activity.getResources().getColor(R.color.black));
}
}
});
viewAdapter = new TextSlideButtonAdapter(weekdays, activity);
slideBtn.setViewAdapter(viewAdapter);
bSettingAlarmTimeDisableFlip = false;
+ NewsAlarmDigiClock weekday = (NewsAlarmDigiClock) activity.findViewById(R.id.weekday);
//System.out.println("Weekday "+weekday.getWeekDayRank());
slideBtn.setSlidePosition(weekday.getWeekDayRank()-1);
bSettingAlarmTimeDisableFlip = false;
}
// =======================Alarm Sound UI==============================================
public ListView soundListView;
private AlarmListViewAdapter soundAdapter;
private String[] soundDisplayTxt = { "BBC", "933", "My Events" };
private int[] soundDisplayIcon = { R.drawable.radio, R.drawable.radio,R.drawable.radio };
private boolean[] soundSelected = { false, false, true };
private static final int BBC_OR_933 = 1;
/**
* Initialize Alarm Sound Screen
*/
private void initAlarmSoundUI() {
soundListView = (ListView) activity.findViewById(R.id.soundlistview);
soundAdapter = new AlarmListViewAdapter(soundDisplayTxt,soundDisplayIcon, soundSelected);
soundListView.setAdapter(soundAdapter);
soundListView.setOnItemClickListener(optionListOnItemClickListener);
}
public boolean[] getSoundSelected() {return soundSelected;}
// ==============Alarm Toolbar UI==============================================
public Button btnHome;
public Button btnSoonze;
public Button btnAlarm;
public Button btnSound;
private NewsAlarmSlidingUpPanel buttonBarSlidingUpPanel;
/**
* Initialize Toolbar UI
*/
private void initToolbarUI() {
btnHome = (Button) activity.findViewById(R.id.homebtn);
btnHome.setOnClickListener(toolbarButtonListener);
btnSoonze = (Button) activity.findViewById(R.id.snoozebtn);
btnSoonze.setOnClickListener(toolbarButtonListener);
btnAlarm = (Button) activity.findViewById(R.id.alarmbtn);
btnAlarm.setOnClickListener(toolbarButtonListener);
btnSound = (Button) activity.findViewById(R.id.soundbtn);
btnSound.setOnClickListener(toolbarButtonListener);
buttonBarSlidingUpPanel = (NewsAlarmSlidingUpPanel) activity.findViewById(R.id.removeItemPanel);
buttonBarSlidingUpPanel.setOpen(true);
buttonBarSlidingUpPanel
.setPanelSlidingListener(new NewsAlarmSlidingUpPanel.PanelSlidingListener() {
@Override
public void onSlidingUpEnd() {
}
@Override
public void onSlidingDownEnd() {
bSettingAlarmTimeDisableFlip = true;
timeSlidingUpPanel.toggle();
}
});
alarmInfoViewSlipper = (ViewFlipper) activity.findViewById(R.id.optionflipper);
}
//================Main Container==========================================
public LinearLayout llMainContainer = null;
/**
* Register the main container with onTouchlistener
*/
private void initMainContainer() {
llMainContainer = (LinearLayout)this.activity.findViewById(R.id.mainContainer);
llMainContainer.setOnTouchListener(new View.OnTouchListener() {
float XStart = 0;
float XEnd = 0;
int toDisplayChildId = 0;
static final int EFFECTIVE_MOVEMENT = 50;
@Override
public boolean onTouch(View v, MotionEvent event)
{
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
//System.out.println("Action Down On Touch!! "+event.getX()+" "+event.getY()+" Action "+event.getAction());
XStart = XEnd = event.getX();
return true;
case MotionEvent.ACTION_MOVE:
//System.out.println("Action Move On Touch!! "+event.getY()+" Action "+event.getAction());
XEnd = event.getX();
return true;
case MotionEvent.ACTION_UP:
if(XEnd > XStart + EFFECTIVE_MOVEMENT)
{
System.out.println("from left: " + XStart + "to right: " + XEnd + " Page: "+ alarmInfoViewSlipper.getDisplayedChild());
toDisplayChildId = alarmInfoViewSlipper.getDisplayedChild();
if(toDisplayChildId != 0)
// flipperListView(3);
// else
flipperListView(toDisplayChildId - 1);
}
else if(XEnd < XStart - EFFECTIVE_MOVEMENT){
System.out.println("from right: " + XStart + "to left: " + XEnd);
toDisplayChildId = alarmInfoViewSlipper.getDisplayedChild();
if(toDisplayChildId != 3)
// flipperListView(0);
// else
flipperListView(toDisplayChildId + 1);
}
XEnd = XStart = 0;
return true;
case MotionEvent.ACTION_CANCEL:
return true;
default:
//System.out.println("Touch Event : " + event.getAction());
return true;
}
}
});
}
//All Listener Events===================================
public GestureOverlayView gesturesView;
public ViewFlipper alarmInfoViewSlipper;
private OnListViewItemChangeListener onListViewItemChangeListener;
/**
* Initialize Display alarm time text
*/
private void initAlarmSettings() {
DbHelper helper = new DbHelper(this.activity);
Calendar cal = Calendar.getInstance();
int hours, mins;
int nextAlarmPosition = -1;
long nextAlarm = 0;
// alarm Time
for (int i = 0; i < alarmDisplayTxt.length; i++) {
alarmSelected[i] = helper.GetBool(Const.ISALARMSET
+ Integer.toString(i));
hours = helper.GetInt(Const.Hours + Integer.toString(i));
mins = helper.GetInt(Const.Mins + Integer.toString(i));
cal.setTimeInMillis(System.currentTimeMillis());
if (hours != Const.DefNum && mins != Const.DefNum) {
cal.set(Calendar.HOUR_OF_DAY, hours);
cal.set(Calendar.MINUTE, mins);
}
hours = cal.get(Calendar.HOUR);
mins = cal.get(Calendar.MINUTE);
switch (cal.get(Calendar.AM_PM)) {
case Calendar.AM:
alarmDisplayTxt[i] = Integer.toString(hours) + ":"
+ String.format("%02d", mins) + " " + this.AMPM[0];
break;
case Calendar.PM:
alarmDisplayTxt[i] = Integer.toString(hours) + ":"
+ String.format("%02d", mins) + " " + this.AMPM[1];
break;
default:
break;
}
if (alarmSelected[i]) {
long tmp = cal.getTimeInMillis();
if (tmp > System.currentTimeMillis())
tmp += AlarmManager.INTERVAL_DAY;
if (nextAlarm != 0) {
if (nextAlarm > tmp) {
nextAlarm = tmp;
nextAlarmPosition = i;
}
} else {
nextAlarm = tmp;
nextAlarmPosition = i;
}
}
}
if (nextAlarmPosition != -1) {
hsDisplayTxt[1] = alarmDisplayTxt[nextAlarmPosition];
}
}
/**
* List view Item click
*/
AdapterView.OnItemClickListener optionListOnItemClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
switch (parent.getId()) {
case R.id.snoozelistview:
toggleSelectListItem(snoozeAdapter, snoozeSelected, position);
// Call back function for Snooze Mode selected/unselected
onListViewItemChangeListener.onSnoozeModeSelected(position,
snoozeSelected[position]);
break;
case R.id.soundlistview:
if (position <= BBC_OR_933 && soundSelected[position] == false && soundSelected[1 - position] == true) {
// make BBC and 993 broadcasting mutual exclusive
toggleSelectListItem(soundAdapter, soundSelected, 1 - position);
}
toggleSelectListItem(soundAdapter, soundSelected, position);
// Call back function for Alarm Sound selected/unselected
onListViewItemChangeListener.onAlarmSoundSelected(position,
soundSelected[position]);
break;
case R.id.alarmlistview:
toggleSelectListItem(alarmAdapter, alarmSelected, position);
// Call back function for alarm time selected/unselected
onListViewItemChangeListener.onAlarmTimeSelected(position,
alarmSelected[position]);
break;
case R.id.hslistview:
hsListViewClicked(position);
}
}
};
/**
* Alarm Wheel's Setting Button Click
*/
Button.OnClickListener alarmWheelButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.timeaddok:
alarmAdapter.updateTxtArrayList("" + hours.getCurrentItem()
+ ":" + String.format("%02d", minutes.getCurrentItem())
+ " " + (amOrpm.getCurrentItem() == 0 ? "am" : "pm"),
ALARM_POSITION);
timeSlidingUpPanel.toggle();
// Call Back function on Alarm Time Change
int hours24 = amOrpm.getCurrentItem() == 0 ? hours
.getCurrentItem() : hours.getCurrentItem() + 12;
onListViewItemChangeListener.onAlarmTimeChanged(ALARM_POSITION,
alarmSelected[ALARM_POSITION], hours24,
minutes.getCurrentItem(), 0, 0, daySelected);
//Get Weekdays selected
System.out.println("Days Selected" + daySelected[0]);
break;
case R.id.timeaddcancel:
timeSlidingUpPanel.toggle();
break;
}
;
}
};
/**
* Toolbar button listener
*/
Button.OnClickListener toolbarButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.homebtn:
flipperListView(Const.SCREENS.HomeUI.ordinal());
break;
case R.id.snoozebtn:
flipperListView(Const.SCREENS.SnoozeUI.ordinal());
break;
case R.id.alarmbtn:
flipperListView(Const.SCREENS.AlarmTimeUI.ordinal());
break;
case R.id.soundbtn:
flipperListView(Const.SCREENS.AlarmSoundUI.ordinal());
break;
default:// no match
System.out.println("btn is from nowhere.");
}
}
};
private void toggleSelectListItem(AlarmListViewAdapter listAdapter,boolean[] chked, int pos) {
chked[pos] = !chked[pos];
listAdapter.invertSelect(pos);
listAdapter.notifyDataSetChanged();
}
/**
* Home Screen List Item Click Response
*
* @param position
*/
private void hsListViewClicked(int position) {
switch (position) {
case 0:
// display weather info
break;
case 1:
flipperListView(Const.SCREENS.AlarmTimeUI.ordinal());
break;
case 2:
flipperListView(Const.SCREENS.AlarmSoundUI.ordinal());
break;
}
}
/**
* common adapter used in all listview
*
* @author Saya
*
*/
private class AlarmListViewAdapter extends BaseAdapter {
private ArrayList<NewsAlarmListItem> optionArrayList;
private LayoutInflater viewInflator;
public AlarmListViewAdapter(String[] displayStrings, int[] displayInts,boolean[] displayChecked) {
viewInflator = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
optionArrayList = new ArrayList<NewsAlarmListItem>();
loadArrayList(displayStrings, displayInts, displayChecked);
// txtisplays = displayStrings;
// icons = displayInts;
}
public void loadArrayList(String[] displayStrings, int[] displayInts,
boolean[] displayChecked) {
for (int i = 0; i < displayStrings.length; i++) {
addToArrayList(displayStrings[i], displayInts[i],displayChecked[i]);
}
}
public void addToArrayList(String displayString, int displayInt,
boolean displayChk) {
optionArrayList.add(new NewsAlarmListItem(displayInt,displayString, displayChk));
}
public void updateTxtArrayList(String displayString, int position) {
if (displayString.length() == 0) {
optionArrayList.get(position).setOptionTxt(Const.NON_WEATHER_MSG);
} else
optionArrayList.get(position).setOptionTxt(displayString);
this.notifyDataSetChanged();
}
@Override
public int getCount() {
return optionArrayList.size();
}
@Override
public Object getItem(int position) {
return optionArrayList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = viewInflator.inflate(R.layout.home_screen_item,null);
}
ImageView imgView = (ImageView) convertView.findViewById(R.id.alarmitemicon);
imgView.setImageResource(optionArrayList.get(position).getOptionIcon());
TextView textView = (TextView) convertView.findViewById(R.id.alarmitemtxt);
textView.setText(optionArrayList.get(position).getOptionTxt());
ImageView chkImgView = (ImageView) convertView.findViewById(R.id.checked);
chkImgView.setImageResource(R.drawable.checkbtn);
if (optionArrayList.get(position).isOptionSelected()) {
chkImgView.setVisibility(View.VISIBLE);
} else {
chkImgView.setVisibility(View.INVISIBLE);
}
return convertView;
}
public void invertSelect(int position) {
optionArrayList.get(position).setOptionSelected(!optionArrayList.get(position).isOptionSelected());
}
}
/**
* UI Flipper Animation
* When user is setting alarm time using timeSlidingUpPanel, disable flip
*
* @param toDisplayedChild
*/
private void flipperListView(int toDisplayedChild) {
if (!bSettingAlarmTimeDisableFlip) {
if (alarmInfoViewSlipper.getDisplayedChild() > toDisplayedChild) {
alarmInfoViewSlipper.setInAnimation(activity, R.anim.slidein);
alarmInfoViewSlipper.setOutAnimation(activity, R.anim.slideout);
alarmInfoViewSlipper.setDisplayedChild(toDisplayedChild);
} else if (alarmInfoViewSlipper.getDisplayedChild() < toDisplayedChild) {
alarmInfoViewSlipper.setInAnimation(activity,R.anim.slideinfromright);
alarmInfoViewSlipper.setOutAnimation(activity,R.anim.slideouttoleft);
alarmInfoViewSlipper.setDisplayedChild(toDisplayedChild);
}
buttonBarSlidingUpPanel.setVisibility(View.VISIBLE);
}
}
private void initSoonzeControls() {
gesturesView = (GestureOverlayView) activity.findViewById(R.id.gestures);
}
// =============================Consumed from otherClasses=============================================
public void registerListViewItemChangeListener(OnListViewItemChangeListener onListViewItemChangeListener) {
this.onListViewItemChangeListener = onListViewItemChangeListener;
}
public void updateHomeWeatherText(String displayString) {
hsListAdapter.updateTxtArrayList(displayString, 0);
}
/**
* temp solution
*/
public void showSnoozeView() {
flipperListView(4);
buttonBarSlidingUpPanel.setVisibility(View.INVISIBLE);
}
public void updateHomeAlarmText() {
initAlarmSettings();
hsListAdapter.updateTxtArrayList(hsDisplayTxt[1], 1);
}
}
| true | true | private void initAlarmTimeUI() {
alarmListView = (ListView) activity.findViewById(R.id.alarmlistview);
alarmAdapter = new AlarmListViewAdapter(alarmDisplayTxt,alarmDisplayIcon, alarmSelected);
alarmListView.setAdapter(alarmAdapter);
alarmListView.setOnItemClickListener(optionListOnItemClickListener);
alarmListView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
ALARM_POSITION = position;
buttonBarSlidingUpPanel.toggle();
// timeSlidingUpPanel.toggle();
return true;
}
});
btnUpdateTimeOk = (Button) activity.findViewById(R.id.timeaddok);
btnUpdateTimeCancel = (Button) activity.findViewById(R.id.timeaddcancel);
btnUpdateTimeOk.setOnClickListener(alarmWheelButtonListener);
btnUpdateTimeCancel.setOnClickListener(alarmWheelButtonListener);
timeSlidingUpPanel = (NewsAlarmSlidingUpPanel) activity.findViewById(R.id.timeupdatepanel);
timeSlidingUpPanel.setOpen(false);
timeSlidingUpPanel
.setPanelSlidingListener(new NewsAlarmSlidingUpPanel.PanelSlidingListener() {
@Override
public void onSlidingUpEnd() {
}
@Override
public void onSlidingDownEnd() {
bSettingAlarmTimeDisableFlip = false;
buttonBarSlidingUpPanel.toggle();
}
});
bSettingAlarmTimeDisableFlip = false;
hours = (WheelView) activity.findViewById(R.id.wheelhour);
minutes = (WheelView) activity.findViewById(R.id.wheelminute);
amOrpm = (WheelView) activity.findViewById(R.id.wheelsecond);
hours.setViewAdapter(new NumericWheelAdapter(activity, 0, 12));
hours.setCurrentItem(6);
minutes.setViewAdapter(new NumericWheelAdapter(activity, 0, 59, "%02d"));
minutes.setCurrentItem(30);
amOrpm.setViewAdapter(new ArrayWheelAdapter<String>(activity, AMPM));
slideBtn =(SlideButton) activity.findViewById(R.id.slideBtn);
slideBtn.setOnChangedListener(new OnChangeListener()
{
public void OnChanged(int i,boolean direction,View v) {
if(direction == true)
{
((TextView)v).setTextColor(activity.getResources().getColor(R.color.royal_blue));
daySelected[i]=true;
}
else
{
((TextView)v).setTextColor(activity.getResources().getColor(R.color.black));
daySelected[i]=false;
}
}
@Override
public void OnSelected(int i, View v, int mode) {
if(mode == 0)
{
if(daySelected[i]==true)
{
daySelected[i]= false;
((TextView)v).setTextColor(activity.getResources().getColor(R.color.black));
}
else
{
daySelected[i]= true;
((TextView)v).setTextColor(activity.getResources().getColor(R.color.royal_blue));
}
}
else if(mode == 1)
{
daySelected[i]= true;
((TextView)v).setTextColor(activity.getResources().getColor(R.color.royal_blue));
}
else if (mode == 2)
{
daySelected[i]= false;
((TextView)v).setTextColor(activity.getResources().getColor(R.color.black));
}
}
});
viewAdapter = new TextSlideButtonAdapter(weekdays, activity);
slideBtn.setViewAdapter(viewAdapter);
bSettingAlarmTimeDisableFlip = false;
//System.out.println("Weekday "+weekday.getWeekDayRank());
slideBtn.setSlidePosition(weekday.getWeekDayRank()-1);
bSettingAlarmTimeDisableFlip = false;
}
| private void initAlarmTimeUI() {
alarmListView = (ListView) activity.findViewById(R.id.alarmlistview);
alarmAdapter = new AlarmListViewAdapter(alarmDisplayTxt,alarmDisplayIcon, alarmSelected);
alarmListView.setAdapter(alarmAdapter);
alarmListView.setOnItemClickListener(optionListOnItemClickListener);
alarmListView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
ALARM_POSITION = position;
buttonBarSlidingUpPanel.toggle();
// timeSlidingUpPanel.toggle();
return true;
}
});
btnUpdateTimeOk = (Button) activity.findViewById(R.id.timeaddok);
btnUpdateTimeCancel = (Button) activity.findViewById(R.id.timeaddcancel);
btnUpdateTimeOk.setOnClickListener(alarmWheelButtonListener);
btnUpdateTimeCancel.setOnClickListener(alarmWheelButtonListener);
timeSlidingUpPanel = (NewsAlarmSlidingUpPanel) activity.findViewById(R.id.timeupdatepanel);
timeSlidingUpPanel.setOpen(false);
timeSlidingUpPanel
.setPanelSlidingListener(new NewsAlarmSlidingUpPanel.PanelSlidingListener() {
@Override
public void onSlidingUpEnd() {
}
@Override
public void onSlidingDownEnd() {
bSettingAlarmTimeDisableFlip = false;
buttonBarSlidingUpPanel.toggle();
}
});
bSettingAlarmTimeDisableFlip = false;
hours = (WheelView) activity.findViewById(R.id.wheelhour);
minutes = (WheelView) activity.findViewById(R.id.wheelminute);
amOrpm = (WheelView) activity.findViewById(R.id.wheelsecond);
hours.setViewAdapter(new NumericWheelAdapter(activity, 0, 12));
hours.setCurrentItem(6);
minutes.setViewAdapter(new NumericWheelAdapter(activity, 0, 59, "%02d"));
minutes.setCurrentItem(30);
amOrpm.setViewAdapter(new ArrayWheelAdapter<String>(activity, AMPM));
slideBtn =(SlideButton) activity.findViewById(R.id.slideBtn);
slideBtn.setOnChangedListener(new OnChangeListener()
{
public void OnChanged(int i,boolean direction,View v) {
if(direction == true)
{
((TextView)v).setTextColor(activity.getResources().getColor(R.color.royal_blue));
daySelected[i]=true;
}
else
{
((TextView)v).setTextColor(activity.getResources().getColor(R.color.black));
daySelected[i]=false;
}
}
@Override
public void OnSelected(int i, View v, int mode) {
if(mode == 0)
{
if(daySelected[i]==true)
{
daySelected[i]= false;
((TextView)v).setTextColor(activity.getResources().getColor(R.color.black));
}
else
{
daySelected[i]= true;
((TextView)v).setTextColor(activity.getResources().getColor(R.color.royal_blue));
}
}
else if(mode == 1)
{
daySelected[i]= true;
((TextView)v).setTextColor(activity.getResources().getColor(R.color.royal_blue));
}
else if (mode == 2)
{
daySelected[i]= false;
((TextView)v).setTextColor(activity.getResources().getColor(R.color.black));
}
}
});
viewAdapter = new TextSlideButtonAdapter(weekdays, activity);
slideBtn.setViewAdapter(viewAdapter);
bSettingAlarmTimeDisableFlip = false;
NewsAlarmDigiClock weekday = (NewsAlarmDigiClock) activity.findViewById(R.id.weekday);
//System.out.println("Weekday "+weekday.getWeekDayRank());
slideBtn.setSlidePosition(weekday.getWeekDayRank()-1);
bSettingAlarmTimeDisableFlip = false;
}
|
diff --git a/src/com/redhat/ceylon/compiler/tools/CeyloncTool.java b/src/com/redhat/ceylon/compiler/tools/CeyloncTool.java
index 331490c00..cd38a387a 100644
--- a/src/com/redhat/ceylon/compiler/tools/CeyloncTool.java
+++ b/src/com/redhat/ceylon/compiler/tools/CeyloncTool.java
@@ -1,100 +1,101 @@
/*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*/
package com.redhat.ceylon.compiler.tools;
import java.io.PrintWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.Locale;
import javax.lang.model.SourceVersion;
import javax.tools.DiagnosticListener;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import com.redhat.ceylon.compiler.launcher.Main;
import com.sun.source.util.JavacTask;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.JavacFileManager;
import com.sun.tools.javac.util.Log;
public class CeyloncTool extends JavacTool implements JavaCompiler {
@Override
public JavacFileManager getStandardFileManager(DiagnosticListener<? super JavaFileObject> diagnosticListener, Locale locale, Charset charset) {
Context context = new Context();
if (diagnosticListener != null)
context.put(DiagnosticListener.class, diagnosticListener);
CeylonLog.preRegister(context);
return new CeyloncFileManager(context, true, charset);
}
@Override
public JavacTask getTask(Writer out, JavaFileManager fileManager, DiagnosticListener<? super JavaFileObject> diagnosticListener, Iterable<String> options, Iterable<String> classes, Iterable<? extends JavaFileObject> compilationUnits) {
final String kindMsg = "All compilation units must be of SOURCE kind";
if (options != null)
for (String option : options)
option.getClass(); // null check
if (classes != null) {
for (String cls : classes)
- if (!SourceVersion.isName(cls)) // implicit null check
+ if (!SourceVersion.isName(cls) // implicit null check
+ && !"default".equals(cls)) // FIX for ceylon because default is not a valid name for Java
throw new IllegalArgumentException("Not a valid class name: " + cls);
}
if (compilationUnits != null) {
for (JavaFileObject cu : compilationUnits) {
if (cu.getKind() != JavaFileObject.Kind.SOURCE) // implicit null
// check
throw new IllegalArgumentException(kindMsg);
}
}
if (fileManager == null)
fileManager = getStandardFileManager(diagnosticListener, null, null);
Context context = ((CeyloncFileManager) fileManager).getContext();
if (diagnosticListener != null && context.get(DiagnosticListener.class) == null)
context.put(DiagnosticListener.class, diagnosticListener);
if (context.get(Log.outKey) == null) {
if (out == null)
context.put(Log.outKey, new PrintWriter(System.err, true));
else
context.put(Log.outKey, new PrintWriter(out, true));
}
context.put(JavaFileManager.class, fileManager);
processOptions(context, fileManager, options);
- Main compiler = new Main("javacTask", context.get(Log.outKey));
+ Main compiler = new Main("ceyloncTask", context.get(Log.outKey));
return new CeyloncTaskImpl(this, compiler, options, context, classes, compilationUnits);
}
}
| false | true | public JavacTask getTask(Writer out, JavaFileManager fileManager, DiagnosticListener<? super JavaFileObject> diagnosticListener, Iterable<String> options, Iterable<String> classes, Iterable<? extends JavaFileObject> compilationUnits) {
final String kindMsg = "All compilation units must be of SOURCE kind";
if (options != null)
for (String option : options)
option.getClass(); // null check
if (classes != null) {
for (String cls : classes)
if (!SourceVersion.isName(cls)) // implicit null check
throw new IllegalArgumentException("Not a valid class name: " + cls);
}
if (compilationUnits != null) {
for (JavaFileObject cu : compilationUnits) {
if (cu.getKind() != JavaFileObject.Kind.SOURCE) // implicit null
// check
throw new IllegalArgumentException(kindMsg);
}
}
if (fileManager == null)
fileManager = getStandardFileManager(diagnosticListener, null, null);
Context context = ((CeyloncFileManager) fileManager).getContext();
if (diagnosticListener != null && context.get(DiagnosticListener.class) == null)
context.put(DiagnosticListener.class, diagnosticListener);
if (context.get(Log.outKey) == null) {
if (out == null)
context.put(Log.outKey, new PrintWriter(System.err, true));
else
context.put(Log.outKey, new PrintWriter(out, true));
}
context.put(JavaFileManager.class, fileManager);
processOptions(context, fileManager, options);
Main compiler = new Main("javacTask", context.get(Log.outKey));
return new CeyloncTaskImpl(this, compiler, options, context, classes, compilationUnits);
}
| public JavacTask getTask(Writer out, JavaFileManager fileManager, DiagnosticListener<? super JavaFileObject> diagnosticListener, Iterable<String> options, Iterable<String> classes, Iterable<? extends JavaFileObject> compilationUnits) {
final String kindMsg = "All compilation units must be of SOURCE kind";
if (options != null)
for (String option : options)
option.getClass(); // null check
if (classes != null) {
for (String cls : classes)
if (!SourceVersion.isName(cls) // implicit null check
&& !"default".equals(cls)) // FIX for ceylon because default is not a valid name for Java
throw new IllegalArgumentException("Not a valid class name: " + cls);
}
if (compilationUnits != null) {
for (JavaFileObject cu : compilationUnits) {
if (cu.getKind() != JavaFileObject.Kind.SOURCE) // implicit null
// check
throw new IllegalArgumentException(kindMsg);
}
}
if (fileManager == null)
fileManager = getStandardFileManager(diagnosticListener, null, null);
Context context = ((CeyloncFileManager) fileManager).getContext();
if (diagnosticListener != null && context.get(DiagnosticListener.class) == null)
context.put(DiagnosticListener.class, diagnosticListener);
if (context.get(Log.outKey) == null) {
if (out == null)
context.put(Log.outKey, new PrintWriter(System.err, true));
else
context.put(Log.outKey, new PrintWriter(out, true));
}
context.put(JavaFileManager.class, fileManager);
processOptions(context, fileManager, options);
Main compiler = new Main("ceyloncTask", context.get(Log.outKey));
return new CeyloncTaskImpl(this, compiler, options, context, classes, compilationUnits);
}
|
diff --git a/src/balle/world/processing/AbstractWorldProcessor.java b/src/balle/world/processing/AbstractWorldProcessor.java
index 038c78e..b78c043 100644
--- a/src/balle/world/processing/AbstractWorldProcessor.java
+++ b/src/balle/world/processing/AbstractWorldProcessor.java
@@ -1,61 +1,61 @@
package balle.world.processing;
import balle.world.AbstractWorld;
import balle.world.Snapshot;
/**
* A class that is supposed to be a base class for any class that needs to
* process world snapshots.
*
* It defines a basic interface one could use to do this.
*
* @author s0909773
*
*/
public abstract class AbstractWorldProcessor extends Thread {
private Snapshot snapshot;
private Snapshot prevSnapshot;
private final AbstractWorld world;
public AbstractWorldProcessor(AbstractWorld world) {
super();
this.world = world;
}
@Override
public final void run() {
snapshot = null;
while (true) {
Snapshot newSnapshot = world.getSnapshot();
if ((newSnapshot != null) && (!newSnapshot.equals(prevSnapshot))) {
- actionOnStep();
+ actionOnChange();
prevSnapshot = snapshot;
snapshot = newSnapshot;
}
- actionOnChange();
+ actionOnStep();
}
}
/**
* Return the latest snapshot
*
* @return snapshot
*/
protected final Snapshot getSnapshot() {
return snapshot;
}
/**
* This function is a step counter for the vision input. It is increased
* every time a new snapshot of the world is received.
*/
protected abstract void actionOnStep();
/**
* This function will run when a snapshot that is different from the
* previous one was received.
*/
protected abstract void actionOnChange();
}
| false | true | public final void run() {
snapshot = null;
while (true) {
Snapshot newSnapshot = world.getSnapshot();
if ((newSnapshot != null) && (!newSnapshot.equals(prevSnapshot))) {
actionOnStep();
prevSnapshot = snapshot;
snapshot = newSnapshot;
}
actionOnChange();
}
}
| public final void run() {
snapshot = null;
while (true) {
Snapshot newSnapshot = world.getSnapshot();
if ((newSnapshot != null) && (!newSnapshot.equals(prevSnapshot))) {
actionOnChange();
prevSnapshot = snapshot;
snapshot = newSnapshot;
}
actionOnStep();
}
}
|
diff --git a/linkid-sdk-saml2/src/test/java/test/unit/net/link/safeonline/sdk/auth/saml2/AuthnRequestFactoryTest.java b/linkid-sdk-saml2/src/test/java/test/unit/net/link/safeonline/sdk/auth/saml2/AuthnRequestFactoryTest.java
index 47e7a84bd..1ad240d13 100644
--- a/linkid-sdk-saml2/src/test/java/test/unit/net/link/safeonline/sdk/auth/saml2/AuthnRequestFactoryTest.java
+++ b/linkid-sdk-saml2/src/test/java/test/unit/net/link/safeonline/sdk/auth/saml2/AuthnRequestFactoryTest.java
@@ -1,238 +1,238 @@
/*
* SafeOnline project.
*
* Copyright 2006-2007 Lin.k N.V. All rights reserved.
* Lin.k N.V. proprietary/confidential. Use is subject to license terms.
*/
package test.unit.net.link.safeonline.sdk.auth.saml2;
import static org.junit.Assert.*;
import com.google.common.collect.Maps;
import com.lyndir.lhunath.opal.system.logging.Logger;
import com.lyndir.lhunath.opal.system.logging.exception.InternalInconsistencyException;
import java.io.Serializable;
import java.security.KeyPair;
import java.security.cert.X509Certificate;
import java.util.*;
import net.link.safeonline.sdk.api.payment.*;
import net.link.safeonline.sdk.api.payment.Currency;
import net.link.safeonline.sdk.auth.protocol.saml2.AuthnRequestFactory;
import net.link.safeonline.sdk.auth.protocol.saml2.LinkIDSaml2Utils;
import net.link.safeonline.sdk.auth.protocol.saml2.devicecontext.DeviceContext;
import net.link.safeonline.sdk.auth.protocol.saml2.paymentcontext.PaymentContext;
import net.link.safeonline.sdk.auth.protocol.saml2.subjectattributes.SubjectAttributes;
import net.link.util.common.CertificateChain;
import net.link.util.common.DomUtils;
import net.link.util.saml.Saml2Utils;
import net.link.util.saml.SamlUtils;
import net.link.util.test.pkix.PkiTestUtils;
import net.link.util.test.web.DomTestUtils;
import org.joda.time.DateTime;
import org.junit.Test;
import org.opensaml.common.xml.SAMLConstants;
import org.opensaml.saml2.core.Attribute;
import org.opensaml.saml2.core.AuthnRequest;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.security.keyinfo.KeyInfoHelper;
import org.w3c.dom.Document;
/**
* Unit test for authentication request factory.
*
* @author fcorneli
*/
public class AuthnRequestFactoryTest {
private static final Logger logger = Logger.get( AuthnRequestFactoryTest.class );
@Test
public void createAuthnRequest()
throws Exception {
// Setup Data
String applicationName = "test-application-id";
KeyPair keyPair = PkiTestUtils.generateKeyPair();
String assertionConsumerServiceURL = "http://test.assertion.consumer.service";
String destinationURL = "https://test.idp.com/entry";
String device = "device";
String session = "test-session-info";
// Test
long begin = System.currentTimeMillis();
Set<String> devices = Collections.singleton( device );
AuthnRequest samlAuthnRequest = AuthnRequestFactory.createAuthnRequest( applicationName, null, null, assertionConsumerServiceURL, destinationURL,
devices, false, session, null, null, null );
String samlAuthnRequestToken = DomUtils.domToString( SamlUtils.sign( samlAuthnRequest, keyPair, null ) );
logger.dbg( DomUtils.domToString( SamlUtils.marshall( samlAuthnRequest ) ) );
long end = System.currentTimeMillis();
// Verify
assertNotNull( samlAuthnRequest );
logger.dbg( "duration: %d ms", end - begin );
logger.dbg( "result message: %s", samlAuthnRequest );
Document resultDocument = DomTestUtils.parseDocument( samlAuthnRequestToken );
AuthnRequest resultAuthnRequest = LinkIDSaml2Utils.unmarshall( resultDocument.getDocumentElement() );
assertNotNull( resultAuthnRequest );
assertNotNull( resultAuthnRequest.getSignature() );
assertNotNull( resultAuthnRequest.getIssuer() );
assertEquals( applicationName, resultAuthnRequest.getIssuer().getValue() );
assertNotNull( resultAuthnRequest.getAssertionConsumerServiceURL() );
assertEquals( assertionConsumerServiceURL, resultAuthnRequest.getAssertionConsumerServiceURL() );
assertNotNull( resultAuthnRequest.getProtocolBinding() );
assertEquals( SAMLConstants.SAML2_POST_BINDING_URI, resultAuthnRequest.getProtocolBinding() );
assertNotNull( resultAuthnRequest.getDestination() );
assertEquals( destinationURL, resultAuthnRequest.getDestination() );
assertNotNull( resultAuthnRequest.getNameIDPolicy() );
assertNotNull( resultAuthnRequest.getNameIDPolicy().getAllowCreate() );
assertTrue( resultAuthnRequest.getNameIDPolicy().getAllowCreate() );
// verify signature
Saml2Utils.validateSignature( resultAuthnRequest.getSignature(), null, null );
}
@Test
public void createAuthnRequestWithCertificateChain()
throws Exception {
// Setup Data
String applicationName = "test-application-id";
String assertionConsumerServiceURL = "http://test.assertion.consumer.service";
String destinationURL = "https://test.idp.com/entry";
String device = "device";
String session = "test-session-info";
KeyPair rootKeyPair = PkiTestUtils.generateKeyPair();
X509Certificate rootCertificate = PkiTestUtils.generateSelfSignedCertificate( rootKeyPair, "CN=Root" );
KeyPair keyPair = PkiTestUtils.generateKeyPair();
DateTime notBefore = new DateTime();
DateTime notAfter = notBefore.plusYears( 1 );
X509Certificate certificate = PkiTestUtils.generateCertificate( keyPair.getPublic(), "CN=Test", rootKeyPair.getPrivate(), rootCertificate, notBefore,
notAfter, null, true, false, false, null );
CertificateChain certificateChain = new CertificateChain( rootCertificate, certificate );
// Test
long begin = System.currentTimeMillis();
Set<String> devices = Collections.singleton( device );
AuthnRequest samlAuthnRequest = AuthnRequestFactory.createAuthnRequest( applicationName, null, null, assertionConsumerServiceURL, destinationURL,
devices, false, session, null, null, null );
String samlAuthnRequestToken = DomUtils.domToString( SamlUtils.sign( samlAuthnRequest, keyPair, certificateChain ) );
long end = System.currentTimeMillis();
// Verify
assertNotNull( samlAuthnRequest );
logger.dbg( "duration: %d ms", end - begin );
logger.dbg( "result message: %s", samlAuthnRequest );
Document resultDocument = DomTestUtils.parseDocument( samlAuthnRequestToken );
AuthnRequest resultAuthnRequest = LinkIDSaml2Utils.unmarshall( resultDocument.getDocumentElement() );
// verify signature
assertNotNull( resultAuthnRequest.getSignature() );
assertNotNull( resultAuthnRequest.getSignature().getKeyInfo() );
CertificateChain resultCertificateChain = new CertificateChain( KeyInfoHelper.getCertificates( resultAuthnRequest.getSignature().getKeyInfo() ) );
assertEquals( 2, resultCertificateChain.getOrderedCertificateChain().size() );
assertEquals( rootCertificate, resultCertificateChain.getRootCertificate() );
assertEquals( certificate, resultCertificateChain.getIdentityCertificate() );
Saml2Utils.validateSignature( resultAuthnRequest.getSignature(), null, null );
}
@Test
public void createAuthnRequestWithDeviceContextAndSubjectAttributesAndPaymentContext()
throws Exception {
// Setup Data
String applicationName = "test-application-id";
String assertionConsumerServiceURL = "http://test.assertion.consumer.service";
String destinationURL = "https://test.idp.com/entry";
String device = "device";
String session = "test-session-info";
KeyPair keyPair = PkiTestUtils.generateKeyPair();
// Setup device context map
Map<String, String> deviceContextMap = Maps.newHashMap();
deviceContextMap.put( "devicecontext1", UUID.randomUUID().toString() );
deviceContextMap.put( "devicecontext2", UUID.randomUUID().toString() );
// Setup subject attributes map
Map<String, List<Serializable>> subjectAttributesMap = Maps.newHashMap();
String testAttributeString = "test.attribute.string";
String testAttributeBoolean = "test.attribute.boolean";
String testAttributeDate = "test.attribute.date";
subjectAttributesMap.put( testAttributeString, Arrays.<Serializable>asList( "value1", "value2", "value3" ) );
subjectAttributesMap.put( testAttributeBoolean, Arrays.<Serializable>asList( true ) );
subjectAttributesMap.put( testAttributeDate, Arrays.<Serializable>asList( new Date(), new Date() ) );
// Setup Payment context
PaymentContextDO paymentContext = new PaymentContextDO( 50, Currency.EUR );
// Test
long begin = System.currentTimeMillis();
Set<String> devices = Collections.singleton( device );
AuthnRequest samlAuthnRequest = AuthnRequestFactory.createAuthnRequest( applicationName, null, null, assertionConsumerServiceURL, destinationURL,
devices, false, session, deviceContextMap, subjectAttributesMap, paymentContext );
String samlAuthnRequestToken = DomUtils.domToString( SamlUtils.sign( samlAuthnRequest, keyPair, null ) );
long end = System.currentTimeMillis();
// Verify
assertNotNull( samlAuthnRequest );
logger.dbg( "duration: %d ms", end - begin );
logger.dbg( "result message: %s", samlAuthnRequest );
Document resultDocument = DomTestUtils.parseDocument( samlAuthnRequestToken );
AuthnRequest resultAuthnRequest = LinkIDSaml2Utils.unmarshall( resultDocument.getDocumentElement() );
// verify signature
assertNotNull( resultAuthnRequest.getSignature() );
assertNotNull( resultAuthnRequest.getSignature().getKeyInfo() );
Saml2Utils.validateSignature( resultAuthnRequest.getSignature(), null, null );
// validate device context map
List<XMLObject> deviceContexts = resultAuthnRequest.getExtensions().getUnknownXMLObjects( DeviceContext.DEFAULT_ELEMENT_NAME );
assertNotNull( deviceContexts );
assertEquals( 1, deviceContexts.size() );
DeviceContext deviceContext = (DeviceContext) deviceContexts.get( 0 );
assertEquals( 2, deviceContext.getAttributes().size() );
// validate subject attributes map
List<XMLObject> saList = resultAuthnRequest.getExtensions().getUnknownXMLObjects( SubjectAttributes.DEFAULT_ELEMENT_NAME );
assertNotNull( saList );
assertEquals( 1, saList.size() );
SubjectAttributes subjectAttributes = (SubjectAttributes) saList.get( 0 );
assertEquals( 3, subjectAttributes.getAttributes().size() );
for (Attribute attribute : subjectAttributes.getAttributes()) {
if (attribute.getName().equals( testAttributeString )) {
assertEquals( 3, attribute.getAttributeValues().size() );
} else if (attribute.getName().equals( testAttributeBoolean )) {
assertEquals( 1, attribute.getAttributeValues().size() );
} else if (attribute.getName().equals( testAttributeDate )) {
assertEquals( 2, attribute.getAttributeValues().size() );
} else {
throw new InternalInconsistencyException( String.format( "Unexpected attribute in SubjectAttributesExtension: %s", attribute.getName() ) );
}
}
// validate payment context map
List<XMLObject> paymentContexts = resultAuthnRequest.getExtensions().getUnknownXMLObjects( PaymentContext.DEFAULT_ELEMENT_NAME );
assertNotNull( paymentContexts );
assertEquals( 1, paymentContexts.size() );
PaymentContext paymentContextMap = (PaymentContext) paymentContexts.get( 0 );
- assertEquals( 4, paymentContextMap.getAttributes().size() );
+ assertEquals( 5, paymentContextMap.getAttributes().size() );
}
}
| true | true | public void createAuthnRequestWithDeviceContextAndSubjectAttributesAndPaymentContext()
throws Exception {
// Setup Data
String applicationName = "test-application-id";
String assertionConsumerServiceURL = "http://test.assertion.consumer.service";
String destinationURL = "https://test.idp.com/entry";
String device = "device";
String session = "test-session-info";
KeyPair keyPair = PkiTestUtils.generateKeyPair();
// Setup device context map
Map<String, String> deviceContextMap = Maps.newHashMap();
deviceContextMap.put( "devicecontext1", UUID.randomUUID().toString() );
deviceContextMap.put( "devicecontext2", UUID.randomUUID().toString() );
// Setup subject attributes map
Map<String, List<Serializable>> subjectAttributesMap = Maps.newHashMap();
String testAttributeString = "test.attribute.string";
String testAttributeBoolean = "test.attribute.boolean";
String testAttributeDate = "test.attribute.date";
subjectAttributesMap.put( testAttributeString, Arrays.<Serializable>asList( "value1", "value2", "value3" ) );
subjectAttributesMap.put( testAttributeBoolean, Arrays.<Serializable>asList( true ) );
subjectAttributesMap.put( testAttributeDate, Arrays.<Serializable>asList( new Date(), new Date() ) );
// Setup Payment context
PaymentContextDO paymentContext = new PaymentContextDO( 50, Currency.EUR );
// Test
long begin = System.currentTimeMillis();
Set<String> devices = Collections.singleton( device );
AuthnRequest samlAuthnRequest = AuthnRequestFactory.createAuthnRequest( applicationName, null, null, assertionConsumerServiceURL, destinationURL,
devices, false, session, deviceContextMap, subjectAttributesMap, paymentContext );
String samlAuthnRequestToken = DomUtils.domToString( SamlUtils.sign( samlAuthnRequest, keyPair, null ) );
long end = System.currentTimeMillis();
// Verify
assertNotNull( samlAuthnRequest );
logger.dbg( "duration: %d ms", end - begin );
logger.dbg( "result message: %s", samlAuthnRequest );
Document resultDocument = DomTestUtils.parseDocument( samlAuthnRequestToken );
AuthnRequest resultAuthnRequest = LinkIDSaml2Utils.unmarshall( resultDocument.getDocumentElement() );
// verify signature
assertNotNull( resultAuthnRequest.getSignature() );
assertNotNull( resultAuthnRequest.getSignature().getKeyInfo() );
Saml2Utils.validateSignature( resultAuthnRequest.getSignature(), null, null );
// validate device context map
List<XMLObject> deviceContexts = resultAuthnRequest.getExtensions().getUnknownXMLObjects( DeviceContext.DEFAULT_ELEMENT_NAME );
assertNotNull( deviceContexts );
assertEquals( 1, deviceContexts.size() );
DeviceContext deviceContext = (DeviceContext) deviceContexts.get( 0 );
assertEquals( 2, deviceContext.getAttributes().size() );
// validate subject attributes map
List<XMLObject> saList = resultAuthnRequest.getExtensions().getUnknownXMLObjects( SubjectAttributes.DEFAULT_ELEMENT_NAME );
assertNotNull( saList );
assertEquals( 1, saList.size() );
SubjectAttributes subjectAttributes = (SubjectAttributes) saList.get( 0 );
assertEquals( 3, subjectAttributes.getAttributes().size() );
for (Attribute attribute : subjectAttributes.getAttributes()) {
if (attribute.getName().equals( testAttributeString )) {
assertEquals( 3, attribute.getAttributeValues().size() );
} else if (attribute.getName().equals( testAttributeBoolean )) {
assertEquals( 1, attribute.getAttributeValues().size() );
} else if (attribute.getName().equals( testAttributeDate )) {
assertEquals( 2, attribute.getAttributeValues().size() );
} else {
throw new InternalInconsistencyException( String.format( "Unexpected attribute in SubjectAttributesExtension: %s", attribute.getName() ) );
}
}
// validate payment context map
List<XMLObject> paymentContexts = resultAuthnRequest.getExtensions().getUnknownXMLObjects( PaymentContext.DEFAULT_ELEMENT_NAME );
assertNotNull( paymentContexts );
assertEquals( 1, paymentContexts.size() );
PaymentContext paymentContextMap = (PaymentContext) paymentContexts.get( 0 );
assertEquals( 4, paymentContextMap.getAttributes().size() );
}
| public void createAuthnRequestWithDeviceContextAndSubjectAttributesAndPaymentContext()
throws Exception {
// Setup Data
String applicationName = "test-application-id";
String assertionConsumerServiceURL = "http://test.assertion.consumer.service";
String destinationURL = "https://test.idp.com/entry";
String device = "device";
String session = "test-session-info";
KeyPair keyPair = PkiTestUtils.generateKeyPair();
// Setup device context map
Map<String, String> deviceContextMap = Maps.newHashMap();
deviceContextMap.put( "devicecontext1", UUID.randomUUID().toString() );
deviceContextMap.put( "devicecontext2", UUID.randomUUID().toString() );
// Setup subject attributes map
Map<String, List<Serializable>> subjectAttributesMap = Maps.newHashMap();
String testAttributeString = "test.attribute.string";
String testAttributeBoolean = "test.attribute.boolean";
String testAttributeDate = "test.attribute.date";
subjectAttributesMap.put( testAttributeString, Arrays.<Serializable>asList( "value1", "value2", "value3" ) );
subjectAttributesMap.put( testAttributeBoolean, Arrays.<Serializable>asList( true ) );
subjectAttributesMap.put( testAttributeDate, Arrays.<Serializable>asList( new Date(), new Date() ) );
// Setup Payment context
PaymentContextDO paymentContext = new PaymentContextDO( 50, Currency.EUR );
// Test
long begin = System.currentTimeMillis();
Set<String> devices = Collections.singleton( device );
AuthnRequest samlAuthnRequest = AuthnRequestFactory.createAuthnRequest( applicationName, null, null, assertionConsumerServiceURL, destinationURL,
devices, false, session, deviceContextMap, subjectAttributesMap, paymentContext );
String samlAuthnRequestToken = DomUtils.domToString( SamlUtils.sign( samlAuthnRequest, keyPair, null ) );
long end = System.currentTimeMillis();
// Verify
assertNotNull( samlAuthnRequest );
logger.dbg( "duration: %d ms", end - begin );
logger.dbg( "result message: %s", samlAuthnRequest );
Document resultDocument = DomTestUtils.parseDocument( samlAuthnRequestToken );
AuthnRequest resultAuthnRequest = LinkIDSaml2Utils.unmarshall( resultDocument.getDocumentElement() );
// verify signature
assertNotNull( resultAuthnRequest.getSignature() );
assertNotNull( resultAuthnRequest.getSignature().getKeyInfo() );
Saml2Utils.validateSignature( resultAuthnRequest.getSignature(), null, null );
// validate device context map
List<XMLObject> deviceContexts = resultAuthnRequest.getExtensions().getUnknownXMLObjects( DeviceContext.DEFAULT_ELEMENT_NAME );
assertNotNull( deviceContexts );
assertEquals( 1, deviceContexts.size() );
DeviceContext deviceContext = (DeviceContext) deviceContexts.get( 0 );
assertEquals( 2, deviceContext.getAttributes().size() );
// validate subject attributes map
List<XMLObject> saList = resultAuthnRequest.getExtensions().getUnknownXMLObjects( SubjectAttributes.DEFAULT_ELEMENT_NAME );
assertNotNull( saList );
assertEquals( 1, saList.size() );
SubjectAttributes subjectAttributes = (SubjectAttributes) saList.get( 0 );
assertEquals( 3, subjectAttributes.getAttributes().size() );
for (Attribute attribute : subjectAttributes.getAttributes()) {
if (attribute.getName().equals( testAttributeString )) {
assertEquals( 3, attribute.getAttributeValues().size() );
} else if (attribute.getName().equals( testAttributeBoolean )) {
assertEquals( 1, attribute.getAttributeValues().size() );
} else if (attribute.getName().equals( testAttributeDate )) {
assertEquals( 2, attribute.getAttributeValues().size() );
} else {
throw new InternalInconsistencyException( String.format( "Unexpected attribute in SubjectAttributesExtension: %s", attribute.getName() ) );
}
}
// validate payment context map
List<XMLObject> paymentContexts = resultAuthnRequest.getExtensions().getUnknownXMLObjects( PaymentContext.DEFAULT_ELEMENT_NAME );
assertNotNull( paymentContexts );
assertEquals( 1, paymentContexts.size() );
PaymentContext paymentContextMap = (PaymentContext) paymentContexts.get( 0 );
assertEquals( 5, paymentContextMap.getAttributes().size() );
}
|
diff --git a/src/com/forgenz/mobmanager/listeners/commands/MMCommandCount.java b/src/com/forgenz/mobmanager/listeners/commands/MMCommandCount.java
index 7e470d6..d00d0a3 100644
--- a/src/com/forgenz/mobmanager/listeners/commands/MMCommandCount.java
+++ b/src/com/forgenz/mobmanager/listeners/commands/MMCommandCount.java
@@ -1,187 +1,187 @@
/*
* Copyright 2013 Michael McKnight. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and contributors and should not be interpreted as representing official policies,
* either expressed or implied, of anybody else.
*/
package com.forgenz.mobmanager.listeners.commands;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.forgenz.mobmanager.MobType;
import com.forgenz.mobmanager.P;
import com.forgenz.mobmanager.world.MMChunk;
import com.forgenz.mobmanager.world.MMCoord;
import com.forgenz.mobmanager.world.MMWorld;
class MMCommandCount extends MMCommand
{
MMCommandCount()
{
super(Pattern.compile("count", Pattern.CASE_INSENSITIVE),
Pattern.compile("^.*$", Pattern.CASE_INSENSITIVE),
0, 1);
}
@Override
public void run(CommandSender sender, String maincmd, String[] args)
{
if (sender instanceof Player && !sender.hasPermission("mobmanager.count"))
{
sender.sendMessage(ChatColor.DARK_RED + "You do not have permission to use /mm count");
return;
}
if (!super.validArgs(sender, maincmd, args))
return;
Collection<MMWorld> worldList;
if (args.length > 1)
{
MMWorld world = P.worlds.get(args[1]);
if (world == null)
{
sender.sendMessage("The world '" + args[1] + "' does not exist or is inactive");
return;
}
worldList = new ArrayList<MMWorld>();
worldList.add(world);
}
else
{
worldList = P.worlds.values();
}
if (worldList.size() == 0)
{
sender.sendMessage("[MobManger] No worlds were found");
}
int totalMonsters = 0;
int totalAnimals = 0;
int totalWaterAnimals = 0;
int totalAmbient = 0;
int totalVillagers = 0;
int totalMaxMonsters = 0;
int totalMaxAnimals = 0;
int totalMaxWaterAnimals = 0;
int totalMaxAmbient = 0;
int totalMaxVillagers = 0;
int totalWorlds = 0;
int totalChunks = 0;
for (final MMWorld world : worldList)
{
world.updateMobCounts();
int numPlayers = 0;
for (final Entry<MMCoord, MMChunk> chunk : world.getChunks())
numPlayers += chunk.getValue().getNumPlayers();
sender.sendMessage(String.format("%1$sWorld:%2$s%3$s, %1$sChunks:%2$s%4$d, %1$sPlayers:%2$s%5$d",
ChatColor.DARK_GREEN, ChatColor.AQUA, world.getWorld().getName(), world.getChunks().size(), numPlayers));
sender.sendMessage(String.format("%1$sM:%2$s%4$d%3$s/%2$s%5$d, %1$sA:%2$s%6$d%3$s/%2$s%7$d, %1$sW:%2$s%8$d%3$s/%2$s%9$d, %1$sAm:%2$s%10$d%3$s/%2$s%11$d, %1$sV:%2$s%12$d%3$s/%2$s%13$d",
ChatColor.GREEN, ChatColor.AQUA, ChatColor.YELLOW,
world.getMobCount(MobType.MONSTER), world.maxMobs(MobType.MONSTER),
world.getMobCount(MobType.ANIMAL), world.maxMobs(MobType.ANIMAL),
world.getMobCount(MobType.WATER_ANIMAL), world.maxMobs(MobType.WATER_ANIMAL),
world.getMobCount(MobType.AMBIENT), world.maxMobs(MobType.AMBIENT),
world.getMobCount(MobType.VILLAGER), world.maxMobs(MobType.VILLAGER)));
if (args.length == 1)
{
totalMonsters += world.getMobCount(MobType.MONSTER);
totalAnimals += world.getMobCount(MobType.ANIMAL);
totalWaterAnimals += world.getMobCount(MobType.WATER_ANIMAL);
totalAmbient += world.getMobCount(MobType.AMBIENT);
totalVillagers += world.getMobCount(MobType.VILLAGER);
totalMaxMonsters += world.maxMobs(MobType.MONSTER);
totalMaxAnimals += world.maxMobs(MobType.ANIMAL);
totalMaxWaterAnimals += world.maxMobs(MobType.WATER_ANIMAL);
totalMaxAmbient += world.maxMobs(MobType.AMBIENT);
- totalMaxVillagers += world.getMobCount(MobType.VILLAGER);
+ totalMaxVillagers += world.maxMobs(MobType.VILLAGER);
++totalWorlds;
totalChunks += world.getChunks().size();
}
}
if (args.length == 1)
{
int totalMobs = totalMonsters + totalAnimals + totalWaterAnimals + totalAmbient + totalVillagers;
int totalMaxMobs = totalMaxMonsters + totalMaxAnimals + totalMaxWaterAnimals + totalMaxAmbient + totalMaxVillagers;
sender.sendMessage(String.format("%1$sTotals - Worlds:%2$s%3$d, %1$sChunks:%2$s%4$d, %1$sPlayers:%2$s%5$d",
ChatColor.GREEN, ChatColor.AQUA,
totalWorlds,
totalChunks,
P.p.getServer().getOnlinePlayers().length));
sender.sendMessage(String.format("%1$sM:%2$s%4$d%3$s/%2$s%5$d, %1$sA:%2$s%6$d%3$s/%2$s%7$d, %1$sW:%2$s%8$d%3$s/%2$s%9$d, %1$sAm:%2$s%10$d%3$s/%2$s%11$d, %1$sV:%2$s%12$d%3$s/%2$s%13$d %1$sT:%2$s%14$d%3$s/%2$s%15$d",
ChatColor.GREEN, ChatColor.AQUA, ChatColor.YELLOW,
totalMonsters, totalMaxMonsters,
totalAnimals, totalMaxAnimals,
totalWaterAnimals, totalMaxWaterAnimals,
totalAmbient, totalMaxAmbient,
totalVillagers, totalMaxVillagers,
totalMobs, totalMaxMobs));
}
}
@Override
public String getUsage()
{
return "%s/%s %s %s[World]";
}
@Override
public String getDescription()
{
return "Displays a list of mob counts for each type of mob along with limits";
}
@Override
public String getAliases()
{
return "count";
}
}
| true | true | public void run(CommandSender sender, String maincmd, String[] args)
{
if (sender instanceof Player && !sender.hasPermission("mobmanager.count"))
{
sender.sendMessage(ChatColor.DARK_RED + "You do not have permission to use /mm count");
return;
}
if (!super.validArgs(sender, maincmd, args))
return;
Collection<MMWorld> worldList;
if (args.length > 1)
{
MMWorld world = P.worlds.get(args[1]);
if (world == null)
{
sender.sendMessage("The world '" + args[1] + "' does not exist or is inactive");
return;
}
worldList = new ArrayList<MMWorld>();
worldList.add(world);
}
else
{
worldList = P.worlds.values();
}
if (worldList.size() == 0)
{
sender.sendMessage("[MobManger] No worlds were found");
}
int totalMonsters = 0;
int totalAnimals = 0;
int totalWaterAnimals = 0;
int totalAmbient = 0;
int totalVillagers = 0;
int totalMaxMonsters = 0;
int totalMaxAnimals = 0;
int totalMaxWaterAnimals = 0;
int totalMaxAmbient = 0;
int totalMaxVillagers = 0;
int totalWorlds = 0;
int totalChunks = 0;
for (final MMWorld world : worldList)
{
world.updateMobCounts();
int numPlayers = 0;
for (final Entry<MMCoord, MMChunk> chunk : world.getChunks())
numPlayers += chunk.getValue().getNumPlayers();
sender.sendMessage(String.format("%1$sWorld:%2$s%3$s, %1$sChunks:%2$s%4$d, %1$sPlayers:%2$s%5$d",
ChatColor.DARK_GREEN, ChatColor.AQUA, world.getWorld().getName(), world.getChunks().size(), numPlayers));
sender.sendMessage(String.format("%1$sM:%2$s%4$d%3$s/%2$s%5$d, %1$sA:%2$s%6$d%3$s/%2$s%7$d, %1$sW:%2$s%8$d%3$s/%2$s%9$d, %1$sAm:%2$s%10$d%3$s/%2$s%11$d, %1$sV:%2$s%12$d%3$s/%2$s%13$d",
ChatColor.GREEN, ChatColor.AQUA, ChatColor.YELLOW,
world.getMobCount(MobType.MONSTER), world.maxMobs(MobType.MONSTER),
world.getMobCount(MobType.ANIMAL), world.maxMobs(MobType.ANIMAL),
world.getMobCount(MobType.WATER_ANIMAL), world.maxMobs(MobType.WATER_ANIMAL),
world.getMobCount(MobType.AMBIENT), world.maxMobs(MobType.AMBIENT),
world.getMobCount(MobType.VILLAGER), world.maxMobs(MobType.VILLAGER)));
if (args.length == 1)
{
totalMonsters += world.getMobCount(MobType.MONSTER);
totalAnimals += world.getMobCount(MobType.ANIMAL);
totalWaterAnimals += world.getMobCount(MobType.WATER_ANIMAL);
totalAmbient += world.getMobCount(MobType.AMBIENT);
totalVillagers += world.getMobCount(MobType.VILLAGER);
totalMaxMonsters += world.maxMobs(MobType.MONSTER);
totalMaxAnimals += world.maxMobs(MobType.ANIMAL);
totalMaxWaterAnimals += world.maxMobs(MobType.WATER_ANIMAL);
totalMaxAmbient += world.maxMobs(MobType.AMBIENT);
totalMaxVillagers += world.getMobCount(MobType.VILLAGER);
++totalWorlds;
totalChunks += world.getChunks().size();
}
}
if (args.length == 1)
{
int totalMobs = totalMonsters + totalAnimals + totalWaterAnimals + totalAmbient + totalVillagers;
int totalMaxMobs = totalMaxMonsters + totalMaxAnimals + totalMaxWaterAnimals + totalMaxAmbient + totalMaxVillagers;
sender.sendMessage(String.format("%1$sTotals - Worlds:%2$s%3$d, %1$sChunks:%2$s%4$d, %1$sPlayers:%2$s%5$d",
ChatColor.GREEN, ChatColor.AQUA,
totalWorlds,
totalChunks,
P.p.getServer().getOnlinePlayers().length));
sender.sendMessage(String.format("%1$sM:%2$s%4$d%3$s/%2$s%5$d, %1$sA:%2$s%6$d%3$s/%2$s%7$d, %1$sW:%2$s%8$d%3$s/%2$s%9$d, %1$sAm:%2$s%10$d%3$s/%2$s%11$d, %1$sV:%2$s%12$d%3$s/%2$s%13$d %1$sT:%2$s%14$d%3$s/%2$s%15$d",
ChatColor.GREEN, ChatColor.AQUA, ChatColor.YELLOW,
totalMonsters, totalMaxMonsters,
totalAnimals, totalMaxAnimals,
totalWaterAnimals, totalMaxWaterAnimals,
totalAmbient, totalMaxAmbient,
totalVillagers, totalMaxVillagers,
totalMobs, totalMaxMobs));
}
}
| public void run(CommandSender sender, String maincmd, String[] args)
{
if (sender instanceof Player && !sender.hasPermission("mobmanager.count"))
{
sender.sendMessage(ChatColor.DARK_RED + "You do not have permission to use /mm count");
return;
}
if (!super.validArgs(sender, maincmd, args))
return;
Collection<MMWorld> worldList;
if (args.length > 1)
{
MMWorld world = P.worlds.get(args[1]);
if (world == null)
{
sender.sendMessage("The world '" + args[1] + "' does not exist or is inactive");
return;
}
worldList = new ArrayList<MMWorld>();
worldList.add(world);
}
else
{
worldList = P.worlds.values();
}
if (worldList.size() == 0)
{
sender.sendMessage("[MobManger] No worlds were found");
}
int totalMonsters = 0;
int totalAnimals = 0;
int totalWaterAnimals = 0;
int totalAmbient = 0;
int totalVillagers = 0;
int totalMaxMonsters = 0;
int totalMaxAnimals = 0;
int totalMaxWaterAnimals = 0;
int totalMaxAmbient = 0;
int totalMaxVillagers = 0;
int totalWorlds = 0;
int totalChunks = 0;
for (final MMWorld world : worldList)
{
world.updateMobCounts();
int numPlayers = 0;
for (final Entry<MMCoord, MMChunk> chunk : world.getChunks())
numPlayers += chunk.getValue().getNumPlayers();
sender.sendMessage(String.format("%1$sWorld:%2$s%3$s, %1$sChunks:%2$s%4$d, %1$sPlayers:%2$s%5$d",
ChatColor.DARK_GREEN, ChatColor.AQUA, world.getWorld().getName(), world.getChunks().size(), numPlayers));
sender.sendMessage(String.format("%1$sM:%2$s%4$d%3$s/%2$s%5$d, %1$sA:%2$s%6$d%3$s/%2$s%7$d, %1$sW:%2$s%8$d%3$s/%2$s%9$d, %1$sAm:%2$s%10$d%3$s/%2$s%11$d, %1$sV:%2$s%12$d%3$s/%2$s%13$d",
ChatColor.GREEN, ChatColor.AQUA, ChatColor.YELLOW,
world.getMobCount(MobType.MONSTER), world.maxMobs(MobType.MONSTER),
world.getMobCount(MobType.ANIMAL), world.maxMobs(MobType.ANIMAL),
world.getMobCount(MobType.WATER_ANIMAL), world.maxMobs(MobType.WATER_ANIMAL),
world.getMobCount(MobType.AMBIENT), world.maxMobs(MobType.AMBIENT),
world.getMobCount(MobType.VILLAGER), world.maxMobs(MobType.VILLAGER)));
if (args.length == 1)
{
totalMonsters += world.getMobCount(MobType.MONSTER);
totalAnimals += world.getMobCount(MobType.ANIMAL);
totalWaterAnimals += world.getMobCount(MobType.WATER_ANIMAL);
totalAmbient += world.getMobCount(MobType.AMBIENT);
totalVillagers += world.getMobCount(MobType.VILLAGER);
totalMaxMonsters += world.maxMobs(MobType.MONSTER);
totalMaxAnimals += world.maxMobs(MobType.ANIMAL);
totalMaxWaterAnimals += world.maxMobs(MobType.WATER_ANIMAL);
totalMaxAmbient += world.maxMobs(MobType.AMBIENT);
totalMaxVillagers += world.maxMobs(MobType.VILLAGER);
++totalWorlds;
totalChunks += world.getChunks().size();
}
}
if (args.length == 1)
{
int totalMobs = totalMonsters + totalAnimals + totalWaterAnimals + totalAmbient + totalVillagers;
int totalMaxMobs = totalMaxMonsters + totalMaxAnimals + totalMaxWaterAnimals + totalMaxAmbient + totalMaxVillagers;
sender.sendMessage(String.format("%1$sTotals - Worlds:%2$s%3$d, %1$sChunks:%2$s%4$d, %1$sPlayers:%2$s%5$d",
ChatColor.GREEN, ChatColor.AQUA,
totalWorlds,
totalChunks,
P.p.getServer().getOnlinePlayers().length));
sender.sendMessage(String.format("%1$sM:%2$s%4$d%3$s/%2$s%5$d, %1$sA:%2$s%6$d%3$s/%2$s%7$d, %1$sW:%2$s%8$d%3$s/%2$s%9$d, %1$sAm:%2$s%10$d%3$s/%2$s%11$d, %1$sV:%2$s%12$d%3$s/%2$s%13$d %1$sT:%2$s%14$d%3$s/%2$s%15$d",
ChatColor.GREEN, ChatColor.AQUA, ChatColor.YELLOW,
totalMonsters, totalMaxMonsters,
totalAnimals, totalMaxAnimals,
totalWaterAnimals, totalMaxWaterAnimals,
totalAmbient, totalMaxAmbient,
totalVillagers, totalMaxVillagers,
totalMobs, totalMaxMobs));
}
}
|
diff --git a/src/SRMA.java b/src/SRMA.java
index b884c2d..2c607fc 100644
--- a/src/SRMA.java
+++ b/src/SRMA.java
@@ -1,403 +1,403 @@
/*
* LICENSE to be determined
*/
package srma;
import srma.Align;
import net.sf.samtools.*;
import net.sf.samtools.util.*;
import net.sf.picard.cmdline.*;
import net.sf.picard.io.IoUtil;
import net.sf.picard.reference.*;
//import java.lang.Runtime;
import java.io.*;
import java.util.*;
/* Documentation:
* - allow if MINIMUM_ALLELE_FREQUENCY or MINIMUM_ALLELE_COVERAGE
* - requires a ".dict" file for the FASTA
* */
public class SRMA extends CommandLineProgram {
@Usage (programVersion="0.0.1")
public final String USAGE = getStandardUsagePreamble() + "Short read micro assembler.";
@Option(shortName=StandardOptionDefinitions.INPUT_SHORT_NAME, doc="The input SAM or BAM file.")
public File INPUT=null;
@Option(shortName=StandardOptionDefinitions.OUTPUT_SHORT_NAME, doc="The output SAM or BAM file.", optional=true)
public File OUTPUT=null;
@Option(shortName=StandardOptionDefinitions.REFERENCE_SHORT_NAME, doc="The reference FASTA file.")
public File REFERENCE=null;
@Option(doc="The alignment offset.", optional=true)
public int OFFSET=20;
@Option(doc="The minimum allele frequency for the conensus.", optional=true)
public double MINIMUM_ALLELE_FREQUENCY=0.0;
@Option(doc="The minimum haploid coverage for the consensus.", optional=true)
public int MINIMUM_ALLELE_COVERAGE=0;
@Option(doc="The file containing ranges to examine.", optional=true)
public File RANGES=null;
@Option(doc="A range to examine.", optional=true)
public String RANGE=null;
private long startTime;
private long endTime;
private final static int SRMA_OUTPUT_CTR = 100;
private int maxOutputStringLength = 0;
ReferenceSequenceFile referenceSequenceFile = null;
private ReferenceSequence referenceSequence = null;
private SAMSequenceDictionary referenceDictionary = null;
private LinkedList<SAMRecord> toProcessSAMRecordList = null;
private LinkedList<Node> toProcesSAMRecordNodeList = null;
private PriorityQueue<SAMRecord> toOutputSAMRecordPriorityQueue = null;
private SAMFileReader in = null;
private SAMFileHeader header = null;
private SAMFileWriter out = null;
private Graph graph = null;
private CloseableIterator<SAMRecord> recordIter = null;
// for RANGES
private boolean useRanges = false;
// for inputting within RANGES
private Ranges inputRanges = null;
private Iterator<Range> inputRangesIterator = null;
private Range inputRange = null;
// for outputting within RANGES
private Ranges outputRanges = null;
private Iterator<Range> outputRangesIterator = null;
private Range outputRange = null;
public static void main(final String[] args) {
new SRMA().instanceMain(args);
}
/*
* Current assumptions:
* - can fit entire partial order graph in memory
* */
protected int doWork()
{
int ctr=0;
int prevReferenceIndex=-1, prevAlignmentStart=-1;
try {
// this is annoying
QUIET = true;
this.startTime = System.nanoTime();
// Check input files
IoUtil.assertFileIsReadable(INPUT);
IoUtil.assertFileIsReadable(REFERENCE);
// Initialize basic input/output files
this.toProcessSAMRecordList = new LinkedList<SAMRecord>();
this.toProcesSAMRecordNodeList = new LinkedList<Node>();
this.toOutputSAMRecordPriorityQueue = new PriorityQueue(40, new SAMRecordCoordinateComparator());
this.in = new SAMFileReader(INPUT, true);
this.header = this.in.getFileHeader();
if(null == OUTPUT) { // to STDOUT as a SAM
this.out = new SAMFileWriterFactory().makeSAMWriter(this.header, true, System.out);
}
else { // to BAM file
this.out = new SAMFileWriterFactory().makeSAMOrBAMWriter(this.header, true, OUTPUT);
}
// Get references
ReferenceSequenceFileFactory referenceSequenceFileFactory = new ReferenceSequenceFileFactory();
this.referenceSequenceFile = referenceSequenceFileFactory.getReferenceSequenceFile(REFERENCE);
this.referenceDictionary = this.referenceSequenceFile.getSequenceDictionary();
if(null == this.referenceDictionary) {
// Try manually
String dictionaryName = new String(REFERENCE.getAbsolutePath());
dictionaryName += ".dict";
final File dictionary = new File(dictionaryName);
if (dictionary.exists()) {
IoUtil.assertFileIsReadable(dictionary);
final SAMTextHeaderCodec codec = new SAMTextHeaderCodec();
final SAMFileHeader header = codec.decode(new AsciiLineReader(new FileInputStream(dictionary)),
dictionary.toString());
if (header.getSequenceDictionary() != null && header.getSequenceDictionary().size() > 0) {
this.referenceDictionary = header.getSequenceDictionary();
}
}
else {
throw new Exception("Could not open sequence dictionary file: " + dictionaryName);
}
}
// Get ranges
if(null == RANGES && null == RANGE) {
this.useRanges = false;
// initialize SAM iter
this.recordIter = this.in.iterator();
this.referenceSequence = this.referenceSequenceFile.nextSequence();
}
else if(null != RANGES && null != RANGE) {
throw new Exception("RANGES and RANGE were both specified.\n");
}
else {
this.useRanges = true;
if(null != RANGES) {
IoUtil.assertFileIsReadable(RANGES);
this.inputRanges = new Ranges(RANGES, this.referenceDictionary, OFFSET);
this.outputRanges = new Ranges(RANGES, this.referenceDictionary);
}
else {
this.inputRanges = new Ranges(RANGE, this.referenceDictionary, OFFSET);
this.outputRanges = new Ranges(RANGE, this.referenceDictionary);
}
this.inputRangesIterator = this.inputRanges.iterator();
this.outputRangesIterator = this.outputRanges.iterator();
if(!this.inputRangesIterator.hasNext()) {
return 0;
}
this.inputRange = this.inputRangesIterator.next();
do {
this.referenceSequence = this.referenceSequenceFile.nextSequence();
} while(null != this.referenceSequence && this.referenceSequence.getContigIndex() < this.inputRange.referenceIndex);
if(null == this.referenceSequence) {
throw new Exception("Premature EOF in the reference sequence");
}
else if(this.referenceSequence.getContigIndex() != this.inputRange.referenceIndex) {
throw new Exception("Could not find the reference sequence");
}
this.recordIter = this.in.query(this.referenceDictionary.getSequence(this.inputRange.referenceIndex).getSequenceName(),
this.inputRange.startPosition,
this.inputRange.endPosition,
false);
this.outputRange = this.outputRangesIterator.next();
}
// Initialize graph
this.graph = new Graph(this.header);
SAMRecord rec = this.getNextSAMRecord();
while(null != rec) {
if(!rec.getReadUnmappedFlag()) { // only mapped reads
Node recNode = null;
// Make sure that it is sorted
if(rec.getReferenceIndex() < prevReferenceIndex || (rec.getReferenceIndex() == prevReferenceIndex && rec.getAlignmentStart() < prevAlignmentStart)) {
throw new Exception("SAM/BAM file is not co-ordinate sorted.");
}
prevReferenceIndex = rec.getReferenceIndex();
prevAlignmentStart = rec.getAlignmentStart();
// Add only if it is from the same contig
if(this.graph.contig != rec.getReferenceIndex()+1) {
// Process the rest of the reads
ctr = this.processList(ctr, false, false);
}
// Add to the graph
try {
recNode = this.graph.addSAMRecord(rec, this.referenceSequence);
} catch (Graph.GraphException e) {
if(Graph.GraphException.NOT_IMPLEMENTED != e.type) {
throw e;
}
}
if(this.useRanges) {
// Partition by the alignment start
if(this.recordAlignmentStartContained(rec)) { // only add if it will be outputted
this.toProcessSAMRecordList.add(rec);
this.toProcesSAMRecordNodeList.add(recNode);
}
}
else {
this.toProcessSAMRecordList.add(rec);
this.toProcesSAMRecordNodeList.add(recNode);
}
// Process the available reads
ctr = this.processList(ctr, true, false);
}
else {
// TODO
// Print this out somehow in some order somewhere
}
// get new record
rec = this.getNextSAMRecord();
}
// Process the rest of the reads
ctr = this.processList(ctr, true, true);
// Close input/output files
this.in.close();
this.out.close();
this.endTime = System.nanoTime();
// to end it all
System.err.println("");
System.err.println("SRMA complete");
// Memory
double totalMemory = (double)Runtime.getRuntime().totalMemory();
double totalMemoryLog2 = Math.log(totalMemory) / ((double)Math.log(2.0));
if(totalMemoryLog2 < 10) {
System.err.println("Total memory usage: " + (int)totalMemory + "B");
}
else if(totalMemoryLog2 < 20) {
System.err.println("Total memory usage: " + (totalMemory / Math.pow(2, 10)) + "KB");
}
else if(totalMemoryLog2 < 30) {
System.err.println("Total memory usage: " + (totalMemory / Math.pow(2, 20)) + "MB");
}
else {
System.err.println("Total memory usage: " + (totalMemory / Math.pow(2, 30)) + "GB");
}
// Run time
long seconds = (this.endTime - this.startTime) / 1000000000;
long hours = seconds / 3600; seconds -= hours * 3600;
- long minutes = seconds / 60; seconds -= minutes* 3600;
+ long minutes = seconds / 60; seconds -= minutes* 60;
System.err.print("Total execution time: " + hours + "h : " + minutes + "m : " + seconds + "s");
System.err.println("");
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
return 0;
}
private SAMRecord getNextSAMRecord()
throws Exception
{
if(this.recordIter.hasNext()) {
return this.recordIter.next();
}
else if(this.useRanges) {
do {
if(this.inputRangesIterator.hasNext()) {
// close previous iterator
this.recordIter.close();
// get new range
this.inputRange = this.inputRangesIterator.next();
// seek in the SAM file
this.recordIter = this.in.query(this.referenceDictionary.getSequence(this.inputRange.referenceIndex).getSequenceName(),
this.inputRange.startPosition,
this.inputRange.endPosition,
false);
}
else {
this.recordIter.close();
return null;
}
} while(false == this.recordIter.hasNext());
while(null != this.referenceSequence && this.referenceSequence.getContigIndex() < this.inputRange.referenceIndex) {
this.referenceSequence = this.referenceSequenceFile.nextSequence();
}
if(null == this.referenceSequence) {
throw new Exception("Premature EOF in the reference sequence");
}
else if(this.referenceSequence.getContigIndex() != this.inputRange.referenceIndex) {
throw new Exception("Could not find the reference sequence");
}
return this.recordIter.next();
}
else {
this.recordIter.close();
return null;
}
}
private void outputProgress(SAMRecord rec, int ctr)
{
if(0 == (ctr % SRMA_OUTPUT_CTR) || ctr < 0) {
// TODO: enforce column width ?
String outputString = new String("ctr:" + ctr + " AL:" + rec.getAlignmentStart() + ":" + rec.getAlignmentEnd() + ":" + rec.toString());
int outputStringLength = outputString.length();
if(this.maxOutputStringLength < outputStringLength) {
this.maxOutputStringLength = outputStringLength;
}
System.err.print("\r" + outputString);
int i;
for(i=outputStringLength;i < this.maxOutputStringLength;i++) { // pad with blanks
System.err.print(" ");
}
}
}
private int processList(int ctr, boolean prune, boolean finish)
throws Exception
{
SAMRecord curSAMRecord = null;
// Process alignments
while(0 < this.toProcessSAMRecordList.size() && ((!finish && this.toProcessSAMRecordList.getFirst().getAlignmentEnd() + this.OFFSET < this.toProcessSAMRecordList.getLast().getAlignmentStart()) || finish)) {
curSAMRecord = this.toProcessSAMRecordList.removeFirst();
Node curSAMRecordNode = this.toProcesSAMRecordNodeList.removeFirst();
if(prune) {
this.graph.prune(curSAMRecord.getReferenceIndex(), curSAMRecord.getAlignmentStart(), this.OFFSET);
}
this.outputProgress(curSAMRecord, ctr);
ctr++;
// Align - this will overwrite/change the alignment
curSAMRecord = Align.align(this.graph,
curSAMRecord,
curSAMRecordNode,
this.referenceSequence,
OFFSET,
MINIMUM_ALLELE_FREQUENCY,
MINIMUM_ALLELE_COVERAGE);
// Add to a heap/priority-queue to assure output is sorted
this.toOutputSAMRecordPriorityQueue.add(curSAMRecord);
}
if(finish && null != curSAMRecord) {
this.outputProgress(curSAMRecord, ctr);
}
// Output alignments
while(0 < this.toOutputSAMRecordPriorityQueue.size()) {
curSAMRecord = this.toOutputSAMRecordPriorityQueue.peek();
if(finish || curSAMRecord.getAlignmentStart() < graph.position_start) { // other alignments will not be less than
this.out.addAlignment(this.toOutputSAMRecordPriorityQueue.poll());
}
else { // other alignments could be less than
break;
}
}
return ctr;
}
private boolean recordAlignmentStartContained(SAMRecord rec)
{
int recAlignmentStart = -1;
if(null == this.outputRange) { // no more ranges
return false;
}
recAlignmentStart = rec.getAlignmentStart();
while(this.outputRange.endPosition < recAlignmentStart) { // find a new range
if(!this.outputRangesIterator.hasNext()) { // no more ranges
this.outputRange = null;
return false;
}
this.outputRange = this.outputRangesIterator.next();
}
if(recAlignmentStart < this.outputRange.startPosition) { // before range
// not within range
return false;
}
else {
// must be within range
return true;
}
}
}
| true | true | protected int doWork()
{
int ctr=0;
int prevReferenceIndex=-1, prevAlignmentStart=-1;
try {
// this is annoying
QUIET = true;
this.startTime = System.nanoTime();
// Check input files
IoUtil.assertFileIsReadable(INPUT);
IoUtil.assertFileIsReadable(REFERENCE);
// Initialize basic input/output files
this.toProcessSAMRecordList = new LinkedList<SAMRecord>();
this.toProcesSAMRecordNodeList = new LinkedList<Node>();
this.toOutputSAMRecordPriorityQueue = new PriorityQueue(40, new SAMRecordCoordinateComparator());
this.in = new SAMFileReader(INPUT, true);
this.header = this.in.getFileHeader();
if(null == OUTPUT) { // to STDOUT as a SAM
this.out = new SAMFileWriterFactory().makeSAMWriter(this.header, true, System.out);
}
else { // to BAM file
this.out = new SAMFileWriterFactory().makeSAMOrBAMWriter(this.header, true, OUTPUT);
}
// Get references
ReferenceSequenceFileFactory referenceSequenceFileFactory = new ReferenceSequenceFileFactory();
this.referenceSequenceFile = referenceSequenceFileFactory.getReferenceSequenceFile(REFERENCE);
this.referenceDictionary = this.referenceSequenceFile.getSequenceDictionary();
if(null == this.referenceDictionary) {
// Try manually
String dictionaryName = new String(REFERENCE.getAbsolutePath());
dictionaryName += ".dict";
final File dictionary = new File(dictionaryName);
if (dictionary.exists()) {
IoUtil.assertFileIsReadable(dictionary);
final SAMTextHeaderCodec codec = new SAMTextHeaderCodec();
final SAMFileHeader header = codec.decode(new AsciiLineReader(new FileInputStream(dictionary)),
dictionary.toString());
if (header.getSequenceDictionary() != null && header.getSequenceDictionary().size() > 0) {
this.referenceDictionary = header.getSequenceDictionary();
}
}
else {
throw new Exception("Could not open sequence dictionary file: " + dictionaryName);
}
}
// Get ranges
if(null == RANGES && null == RANGE) {
this.useRanges = false;
// initialize SAM iter
this.recordIter = this.in.iterator();
this.referenceSequence = this.referenceSequenceFile.nextSequence();
}
else if(null != RANGES && null != RANGE) {
throw new Exception("RANGES and RANGE were both specified.\n");
}
else {
this.useRanges = true;
if(null != RANGES) {
IoUtil.assertFileIsReadable(RANGES);
this.inputRanges = new Ranges(RANGES, this.referenceDictionary, OFFSET);
this.outputRanges = new Ranges(RANGES, this.referenceDictionary);
}
else {
this.inputRanges = new Ranges(RANGE, this.referenceDictionary, OFFSET);
this.outputRanges = new Ranges(RANGE, this.referenceDictionary);
}
this.inputRangesIterator = this.inputRanges.iterator();
this.outputRangesIterator = this.outputRanges.iterator();
if(!this.inputRangesIterator.hasNext()) {
return 0;
}
this.inputRange = this.inputRangesIterator.next();
do {
this.referenceSequence = this.referenceSequenceFile.nextSequence();
} while(null != this.referenceSequence && this.referenceSequence.getContigIndex() < this.inputRange.referenceIndex);
if(null == this.referenceSequence) {
throw new Exception("Premature EOF in the reference sequence");
}
else if(this.referenceSequence.getContigIndex() != this.inputRange.referenceIndex) {
throw new Exception("Could not find the reference sequence");
}
this.recordIter = this.in.query(this.referenceDictionary.getSequence(this.inputRange.referenceIndex).getSequenceName(),
this.inputRange.startPosition,
this.inputRange.endPosition,
false);
this.outputRange = this.outputRangesIterator.next();
}
// Initialize graph
this.graph = new Graph(this.header);
SAMRecord rec = this.getNextSAMRecord();
while(null != rec) {
if(!rec.getReadUnmappedFlag()) { // only mapped reads
Node recNode = null;
// Make sure that it is sorted
if(rec.getReferenceIndex() < prevReferenceIndex || (rec.getReferenceIndex() == prevReferenceIndex && rec.getAlignmentStart() < prevAlignmentStart)) {
throw new Exception("SAM/BAM file is not co-ordinate sorted.");
}
prevReferenceIndex = rec.getReferenceIndex();
prevAlignmentStart = rec.getAlignmentStart();
// Add only if it is from the same contig
if(this.graph.contig != rec.getReferenceIndex()+1) {
// Process the rest of the reads
ctr = this.processList(ctr, false, false);
}
// Add to the graph
try {
recNode = this.graph.addSAMRecord(rec, this.referenceSequence);
} catch (Graph.GraphException e) {
if(Graph.GraphException.NOT_IMPLEMENTED != e.type) {
throw e;
}
}
if(this.useRanges) {
// Partition by the alignment start
if(this.recordAlignmentStartContained(rec)) { // only add if it will be outputted
this.toProcessSAMRecordList.add(rec);
this.toProcesSAMRecordNodeList.add(recNode);
}
}
else {
this.toProcessSAMRecordList.add(rec);
this.toProcesSAMRecordNodeList.add(recNode);
}
// Process the available reads
ctr = this.processList(ctr, true, false);
}
else {
// TODO
// Print this out somehow in some order somewhere
}
// get new record
rec = this.getNextSAMRecord();
}
// Process the rest of the reads
ctr = this.processList(ctr, true, true);
// Close input/output files
this.in.close();
this.out.close();
this.endTime = System.nanoTime();
// to end it all
System.err.println("");
System.err.println("SRMA complete");
// Memory
double totalMemory = (double)Runtime.getRuntime().totalMemory();
double totalMemoryLog2 = Math.log(totalMemory) / ((double)Math.log(2.0));
if(totalMemoryLog2 < 10) {
System.err.println("Total memory usage: " + (int)totalMemory + "B");
}
else if(totalMemoryLog2 < 20) {
System.err.println("Total memory usage: " + (totalMemory / Math.pow(2, 10)) + "KB");
}
else if(totalMemoryLog2 < 30) {
System.err.println("Total memory usage: " + (totalMemory / Math.pow(2, 20)) + "MB");
}
else {
System.err.println("Total memory usage: " + (totalMemory / Math.pow(2, 30)) + "GB");
}
// Run time
long seconds = (this.endTime - this.startTime) / 1000000000;
long hours = seconds / 3600; seconds -= hours * 3600;
long minutes = seconds / 60; seconds -= minutes* 3600;
System.err.print("Total execution time: " + hours + "h : " + minutes + "m : " + seconds + "s");
System.err.println("");
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
return 0;
}
| protected int doWork()
{
int ctr=0;
int prevReferenceIndex=-1, prevAlignmentStart=-1;
try {
// this is annoying
QUIET = true;
this.startTime = System.nanoTime();
// Check input files
IoUtil.assertFileIsReadable(INPUT);
IoUtil.assertFileIsReadable(REFERENCE);
// Initialize basic input/output files
this.toProcessSAMRecordList = new LinkedList<SAMRecord>();
this.toProcesSAMRecordNodeList = new LinkedList<Node>();
this.toOutputSAMRecordPriorityQueue = new PriorityQueue(40, new SAMRecordCoordinateComparator());
this.in = new SAMFileReader(INPUT, true);
this.header = this.in.getFileHeader();
if(null == OUTPUT) { // to STDOUT as a SAM
this.out = new SAMFileWriterFactory().makeSAMWriter(this.header, true, System.out);
}
else { // to BAM file
this.out = new SAMFileWriterFactory().makeSAMOrBAMWriter(this.header, true, OUTPUT);
}
// Get references
ReferenceSequenceFileFactory referenceSequenceFileFactory = new ReferenceSequenceFileFactory();
this.referenceSequenceFile = referenceSequenceFileFactory.getReferenceSequenceFile(REFERENCE);
this.referenceDictionary = this.referenceSequenceFile.getSequenceDictionary();
if(null == this.referenceDictionary) {
// Try manually
String dictionaryName = new String(REFERENCE.getAbsolutePath());
dictionaryName += ".dict";
final File dictionary = new File(dictionaryName);
if (dictionary.exists()) {
IoUtil.assertFileIsReadable(dictionary);
final SAMTextHeaderCodec codec = new SAMTextHeaderCodec();
final SAMFileHeader header = codec.decode(new AsciiLineReader(new FileInputStream(dictionary)),
dictionary.toString());
if (header.getSequenceDictionary() != null && header.getSequenceDictionary().size() > 0) {
this.referenceDictionary = header.getSequenceDictionary();
}
}
else {
throw new Exception("Could not open sequence dictionary file: " + dictionaryName);
}
}
// Get ranges
if(null == RANGES && null == RANGE) {
this.useRanges = false;
// initialize SAM iter
this.recordIter = this.in.iterator();
this.referenceSequence = this.referenceSequenceFile.nextSequence();
}
else if(null != RANGES && null != RANGE) {
throw new Exception("RANGES and RANGE were both specified.\n");
}
else {
this.useRanges = true;
if(null != RANGES) {
IoUtil.assertFileIsReadable(RANGES);
this.inputRanges = new Ranges(RANGES, this.referenceDictionary, OFFSET);
this.outputRanges = new Ranges(RANGES, this.referenceDictionary);
}
else {
this.inputRanges = new Ranges(RANGE, this.referenceDictionary, OFFSET);
this.outputRanges = new Ranges(RANGE, this.referenceDictionary);
}
this.inputRangesIterator = this.inputRanges.iterator();
this.outputRangesIterator = this.outputRanges.iterator();
if(!this.inputRangesIterator.hasNext()) {
return 0;
}
this.inputRange = this.inputRangesIterator.next();
do {
this.referenceSequence = this.referenceSequenceFile.nextSequence();
} while(null != this.referenceSequence && this.referenceSequence.getContigIndex() < this.inputRange.referenceIndex);
if(null == this.referenceSequence) {
throw new Exception("Premature EOF in the reference sequence");
}
else if(this.referenceSequence.getContigIndex() != this.inputRange.referenceIndex) {
throw new Exception("Could not find the reference sequence");
}
this.recordIter = this.in.query(this.referenceDictionary.getSequence(this.inputRange.referenceIndex).getSequenceName(),
this.inputRange.startPosition,
this.inputRange.endPosition,
false);
this.outputRange = this.outputRangesIterator.next();
}
// Initialize graph
this.graph = new Graph(this.header);
SAMRecord rec = this.getNextSAMRecord();
while(null != rec) {
if(!rec.getReadUnmappedFlag()) { // only mapped reads
Node recNode = null;
// Make sure that it is sorted
if(rec.getReferenceIndex() < prevReferenceIndex || (rec.getReferenceIndex() == prevReferenceIndex && rec.getAlignmentStart() < prevAlignmentStart)) {
throw new Exception("SAM/BAM file is not co-ordinate sorted.");
}
prevReferenceIndex = rec.getReferenceIndex();
prevAlignmentStart = rec.getAlignmentStart();
// Add only if it is from the same contig
if(this.graph.contig != rec.getReferenceIndex()+1) {
// Process the rest of the reads
ctr = this.processList(ctr, false, false);
}
// Add to the graph
try {
recNode = this.graph.addSAMRecord(rec, this.referenceSequence);
} catch (Graph.GraphException e) {
if(Graph.GraphException.NOT_IMPLEMENTED != e.type) {
throw e;
}
}
if(this.useRanges) {
// Partition by the alignment start
if(this.recordAlignmentStartContained(rec)) { // only add if it will be outputted
this.toProcessSAMRecordList.add(rec);
this.toProcesSAMRecordNodeList.add(recNode);
}
}
else {
this.toProcessSAMRecordList.add(rec);
this.toProcesSAMRecordNodeList.add(recNode);
}
// Process the available reads
ctr = this.processList(ctr, true, false);
}
else {
// TODO
// Print this out somehow in some order somewhere
}
// get new record
rec = this.getNextSAMRecord();
}
// Process the rest of the reads
ctr = this.processList(ctr, true, true);
// Close input/output files
this.in.close();
this.out.close();
this.endTime = System.nanoTime();
// to end it all
System.err.println("");
System.err.println("SRMA complete");
// Memory
double totalMemory = (double)Runtime.getRuntime().totalMemory();
double totalMemoryLog2 = Math.log(totalMemory) / ((double)Math.log(2.0));
if(totalMemoryLog2 < 10) {
System.err.println("Total memory usage: " + (int)totalMemory + "B");
}
else if(totalMemoryLog2 < 20) {
System.err.println("Total memory usage: " + (totalMemory / Math.pow(2, 10)) + "KB");
}
else if(totalMemoryLog2 < 30) {
System.err.println("Total memory usage: " + (totalMemory / Math.pow(2, 20)) + "MB");
}
else {
System.err.println("Total memory usage: " + (totalMemory / Math.pow(2, 30)) + "GB");
}
// Run time
long seconds = (this.endTime - this.startTime) / 1000000000;
long hours = seconds / 3600; seconds -= hours * 3600;
long minutes = seconds / 60; seconds -= minutes* 60;
System.err.print("Total execution time: " + hours + "h : " + minutes + "m : " + seconds + "s");
System.err.println("");
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
return 0;
}
|
diff --git a/src/test/java/com/leokom/chess/WinBoardTest.java b/src/test/java/com/leokom/chess/WinBoardTest.java
index 425489b9..413247cf 100644
--- a/src/test/java/com/leokom/chess/WinBoardTest.java
+++ b/src/test/java/com/leokom/chess/WinBoardTest.java
@@ -1,16 +1,16 @@
package com.leokom.chess;
import org.junit.Test;
import static org.junit.Assert.fail;
/**
* Author: Leonid
* Date-time: 19.08.12 18:16
*/
public class WinBoardTest {
@Test
public void firstTest() {
- fail( "Checking if JUnit works fine" );
+ fail( "any message" );
}
}
| true | true | public void firstTest() {
fail( "Checking if JUnit works fine" );
}
| public void firstTest() {
fail( "any message" );
}
|
diff --git a/BusTours/src/org/gitorious/scrapfilbleu/android/MapViewActivity.java b/BusTours/src/org/gitorious/scrapfilbleu/android/MapViewActivity.java
index 904a8cd..f2bafc5 100644
--- a/BusTours/src/org/gitorious/scrapfilbleu/android/MapViewActivity.java
+++ b/BusTours/src/org/gitorious/scrapfilbleu/android/MapViewActivity.java
@@ -1,42 +1,42 @@
/* vim: set ts=4 sw=4 et: */
package org.gitorious.scrapfilbleu.android;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.os.Bundle;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.slf4j.LoggerFactory;
public class MapViewActivity extends Activity
{
private MapView osmMap;
private GeoPoint geoPointTours;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview);
- this.geoPointTours = new GeoPoint(47.3883 * 1000000, 0.7276 * 1000000);
+ this.geoPointTours = new GeoPoint((int)(47.3883*1e6), (int)(0.7276*1e6));
osmMap = (MapView)findViewById(R.id.map);
osmMap.setTileSource(TileSourceFactory.MAPNIK);
osmMap.setBuiltInZoomControls(true);
osmMap.setMultiTouchControls(true);
osmMap.getController().setZoom(16);
osmMap.getController().setCenter(this.geoPointTours);
}
}
| true | true | public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview);
this.geoPointTours = new GeoPoint(47.3883 * 1000000, 0.7276 * 1000000);
osmMap = (MapView)findViewById(R.id.map);
osmMap.setTileSource(TileSourceFactory.MAPNIK);
osmMap.setBuiltInZoomControls(true);
osmMap.setMultiTouchControls(true);
osmMap.getController().setZoom(16);
osmMap.getController().setCenter(this.geoPointTours);
}
| public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview);
this.geoPointTours = new GeoPoint((int)(47.3883*1e6), (int)(0.7276*1e6));
osmMap = (MapView)findViewById(R.id.map);
osmMap.setTileSource(TileSourceFactory.MAPNIK);
osmMap.setBuiltInZoomControls(true);
osmMap.setMultiTouchControls(true);
osmMap.getController().setZoom(16);
osmMap.getController().setCenter(this.geoPointTours);
}
|
diff --git a/nuxeo-webengine-client/src/main/java/org/nuxeo/ecm/client/atompub/AtomPubConnector.java b/nuxeo-webengine-client/src/main/java/org/nuxeo/ecm/client/atompub/AtomPubConnector.java
index c516f595..96ae7aed 100644
--- a/nuxeo-webengine-client/src/main/java/org/nuxeo/ecm/client/atompub/AtomPubConnector.java
+++ b/nuxeo-webengine-client/src/main/java/org/nuxeo/ecm/client/atompub/AtomPubConnector.java
@@ -1,137 +1,141 @@
/*
* (C) Copyright 2006-2008 Nuxeo SAS (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* 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.
*
* Contributors:
* matic
*/
package org.nuxeo.ecm.client.atompub;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import org.apache.abdera.Abdera;
import org.apache.abdera.ext.cmis.CmisExtensionFactory;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.Feed;
import org.apache.abdera.model.Service;
import org.apache.abdera.model.Workspace;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.nuxeo.ecm.client.CannotConnectToServerException;
import org.nuxeo.ecm.client.Command;
import org.nuxeo.ecm.client.Connector;
import org.nuxeo.ecm.client.ContentManager;
import org.nuxeo.ecm.client.DocumentFeed;
import org.nuxeo.ecm.client.QueryEntry;
import org.nuxeo.ecm.client.Repository;
import org.nuxeo.ecm.client.abdera.DocumentFeedAdapter;
import org.nuxeo.ecm.client.abdera.QueryEntryTransformer;
import org.nuxeo.ecm.client.abdera.RepositoryAdapter;
import org.nuxeo.ecm.client.commands.AbstractCommand;
import org.nuxeo.ecm.client.commands.GetDocumentFeedCommand;
import org.nuxeo.ecm.client.commands.GetQueriesCommand;
import org.nuxeo.ecm.client.commands.RefreshDocumentFeedCommand;
import org.nuxeo.ecm.client.commands.RepositoriesCommand;
/**
* @author matic
*
*/
public class AtomPubConnector implements Connector {
protected HttpClient httpClient;
protected Abdera abdera;
public void init(ContentManager contentManager) {
this.contentManager = contentManager;
this.httpClient = new HttpClient();
this.abdera = Abdera.getInstance();
this.abdera.getConfiguration().addExtensionFactory(
new CmisExtensionFactory());
}
protected ContentManager contentManager;
@SuppressWarnings("unchecked")
public <T> T invoke(Command<T> command)
throws CannotConnectToServerException {
if (command instanceof RepositoriesCommand) {
return (T) doInvoke((RepositoriesCommand) command);
} else if (command instanceof GetQueriesCommand) {
return (T) doInvoke((GetQueriesCommand) command);
} else if (command instanceof RefreshDocumentFeedCommand) {
return (T) doInvoke((RefreshDocumentFeedCommand) command);
}
throw new UnsupportedOperationException("not yet");
}
protected <T extends Element> T doGet(AbstractCommand<?> command)
throws CannotConnectToServerException {
URL baseURL = contentManager.getBaseURL();
String url = command.formatURL(baseURL);
GetMethod method = new GetMethod(url);
InputStream bodyStream = null;
+ String serverTag = command.getServerTag();
+ if (serverTag != null) {
+ method.setRequestHeader(new Header("If-Range",serverTag));
+ }
try {
httpClient.executeMethod(method);
bodyStream = method.getResponseBodyAsStream();
} catch (Exception e) {
throw CannotConnectToServerException.wrap("Cannot connect to "
+ url, e);
}
Header header = method.getResponseHeader("ETag");
if (header != null) {
command.setServerTag(header.getValue());
}
Document<T> document = abdera.getParser().parse(bodyStream);
return document.getRoot();
}
protected List<QueryEntry> doInvoke(GetQueriesCommand command)
throws CannotConnectToServerException {
Feed atomFeed = this.doGet(command);
return QueryEntryTransformer.transformEntries(atomFeed.getEntries(), contentManager);
}
protected Repository[] doInvoke(RepositoriesCommand command)
throws CannotConnectToServerException {
Service atomService = this.doGet(command);
List<Workspace> atomWorkspaces = atomService.getWorkspaces();
Repository[] repositories = new RepositoryAdapter[atomWorkspaces.size()];
int index = 0;
for (Workspace atomWorkspace : atomWorkspaces) {
repositories[index++] = new RepositoryAdapter(contentManager,
atomWorkspace);
}
return repositories;
}
protected DocumentFeed doInvoke(GetDocumentFeedCommand command) throws CannotConnectToServerException {
Feed atomFeed = this.doGet(command);
return new DocumentFeedAdapter(contentManager,atomFeed,command.getServerTag());
}
private DocumentFeed doInvoke(RefreshDocumentFeedCommand command) throws CannotConnectToServerException {
Feed atomFeed = this.doGet(command);
return new DocumentFeedAdapter(contentManager,atomFeed,command.getServerTag());
}
}
| true | true | protected <T extends Element> T doGet(AbstractCommand<?> command)
throws CannotConnectToServerException {
URL baseURL = contentManager.getBaseURL();
String url = command.formatURL(baseURL);
GetMethod method = new GetMethod(url);
InputStream bodyStream = null;
try {
httpClient.executeMethod(method);
bodyStream = method.getResponseBodyAsStream();
} catch (Exception e) {
throw CannotConnectToServerException.wrap("Cannot connect to "
+ url, e);
}
Header header = method.getResponseHeader("ETag");
if (header != null) {
command.setServerTag(header.getValue());
}
Document<T> document = abdera.getParser().parse(bodyStream);
return document.getRoot();
}
| protected <T extends Element> T doGet(AbstractCommand<?> command)
throws CannotConnectToServerException {
URL baseURL = contentManager.getBaseURL();
String url = command.formatURL(baseURL);
GetMethod method = new GetMethod(url);
InputStream bodyStream = null;
String serverTag = command.getServerTag();
if (serverTag != null) {
method.setRequestHeader(new Header("If-Range",serverTag));
}
try {
httpClient.executeMethod(method);
bodyStream = method.getResponseBodyAsStream();
} catch (Exception e) {
throw CannotConnectToServerException.wrap("Cannot connect to "
+ url, e);
}
Header header = method.getResponseHeader("ETag");
if (header != null) {
command.setServerTag(header.getValue());
}
Document<T> document = abdera.getParser().parse(bodyStream);
return document.getRoot();
}
|
diff --git a/src/java/com/threerings/getdown/data/Application.java b/src/java/com/threerings/getdown/data/Application.java
index 7fbbdef..ac4dbc7 100644
--- a/src/java/com/threerings/getdown/data/Application.java
+++ b/src/java/com/threerings/getdown/data/Application.java
@@ -1,1026 +1,1026 @@
//
// $Id$
//
// Getdown - application installer, patcher and launcher
// Copyright (C) 2004-2006 Three Rings Design, Inc.
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the: Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
package com.threerings.getdown.data;
import java.awt.Color;
import java.awt.Rectangle;
import javax.swing.JApplet;
import java.lang.reflect.Method;
import java.security.AllPermission;
import java.security.CodeSource;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.samskivert.io.StreamUtil;
import com.samskivert.text.MessageUtil;
import com.samskivert.util.RunAnywhere;
import com.samskivert.util.StringUtil;
import org.apache.commons.io.CopyUtils;
import com.threerings.getdown.Log;
import com.threerings.getdown.util.ConfigUtil;
import com.threerings.getdown.util.LaunchUtil;
import com.threerings.getdown.util.MetaProgressObserver;
import com.threerings.getdown.util.ProgressObserver;
/**
* Parses and provide access to the information contained in the
* <code>getdown.txt</code> configuration file.
*/
public class Application
{
/** The name of our configuration file. */
public static final String CONFIG_FILE = "getdown.txt";
/** The name of our target version file. */
public static final String VERSION_FILE = "version.txt";
/** System properties that are prefixed with this string will be
* passed through to our application (minus this prefix). */
public static final String PROP_PASSTHROUGH_PREFIX = "app.";
/** Used to communicate information about the UI displayed when
* updating the application. */
public static class UpdateInterface
{
/** The human readable name of this application. */
public String name;
/** The path (relative to the appdir) to the background image. */
public String backgroundImage;
/** The path (relative to the appdir) to the progress bar image. */
public String progressImage;
/** The dimensions of the progress bar. */
public Rectangle progress = new Rectangle(5, 5, 300, 15);
/** The color of the progress text. */
public Color progressText = Color.black;
/** The color of the progress bar. */
public Color progressBar = new Color(0x6699CC);
/** The dimensions of the status display. */
public Rectangle status = new Rectangle(5, 25, 500, 100);
/** The color of the status text. */
public Color statusText = Color.black;
/** The color of the text shadow. */
public Color textShadow;
/** Where to point the user for help with install errors. */
public String installError;
/** Generates a string representation of this instance. */
public String toString ()
{
return "[name=" + name + ", bg=" + backgroundImage +
", pi=" + progressImage + ", prect=" + progress +
", pt=" + progressText + ", pb=" + progressBar +
", srect=" + status + ", st=" + statusText +
", shadow=" + textShadow + ", err=" + installError + "]";
}
}
/** Used by {@link #verifyMetadata} to communicate status in
* circumstances where it needs to take network actions. */
public static interface StatusDisplay
{
/** Requests that the specified status message be displayed. */
public void updateStatus (String message);
}
/**
* Creates an application instance which records the location of the
* <code>getdown.txt</code> configuration file from the supplied
* application directory.
*
* @param appid usually null but a string identifier if a secondary
* application is desired to be launched. That application will use *
* <code>appid.class</code> and <code>appid.apparg</code> to configure
* itself but all other parameters will be the same as the primary
* application.
*/
public Application (File appdir, String appid)
{
_appdir = appdir;
_appid = appid;
_config = getLocalPath(CONFIG_FILE);
}
/**
* Indicates whether or not we support downloading of our resources using
* the Bittorrent protocol.
*/
public boolean getUseTorrent ()
{
return _useTorrent;
}
/**
* Returns a resource that refers to the application configuration
* file itself.
*/
public Resource getConfigResource ()
{
try {
return createResource(CONFIG_FILE, false);
} catch (Exception e) {
throw new RuntimeException("Invalid appbase '" + _vappbase + "'.");
}
}
/**
* Returns a list of the code {@link Resource} objects used by this
* application.
*/
public List<Resource> getCodeResources ()
{
return _codes;
}
/**
* Returns a list of the non-code {@link Resource} objects used by
* this application.
*/
public List<Resource> getResources ()
{
return _resources;
}
/**
* Returns a list of all the {@link Resource} objects used by
* this application.
*/
public List<Resource> getAllResources ()
{
List<Resource> allResources = new ArrayList<Resource>();
allResources.addAll(getCodeResources());
allResources.addAll(getActiveResources());
return allResources;
}
/**
* Returns a list of all auxiliary resource groups defined by the
* application. An auxiliary resource group is a collection of resource
* files that are not downloaded unless a group token file is present in
* the application directory.
*/
public List<String> getAuxGroups ()
{
return _auxgroups;
}
/**
* Returns true if the specified auxgroup has been "activated", false if
* not. Non-activated groups should be ignored, activated groups should be
* downloaded and patched along with the main resources.
*/
public boolean isAuxGroupActive (String auxgroup)
{
Boolean active = _auxactive.get(auxgroup);
if (active == null) {
// TODO: compare the contents with the MD5 hash of the auxgroup
// name and the client's machine ident
active = getLocalPath(auxgroup + ".dat").exists();
_auxactive.put(auxgroup, active);
}
return active;
}
/**
* Returns a list of the non-code {@link Resource} objects included in the
* specified auxiliary resource group. If the group does not exist or has
* no resources, an empty list will be returned.
*/
public List<Resource> getResources (String group)
{
ArrayList<Resource> auxrsrcs = _auxrsrcs.get(group);
return (auxrsrcs == null) ? new ArrayList<Resource>() : auxrsrcs;
}
/**
* Returns all non-code resources and all resources from active auxiliary
* resource groups.
*/
public List<Resource> getActiveResources ()
{
ArrayList<Resource> rsrcs = new ArrayList<Resource>();
rsrcs.addAll(getResources());
for (String auxgroup : getAuxGroups()) {
if (isAuxGroupActive(auxgroup)) {
rsrcs.addAll(getResources(auxgroup));
}
}
return rsrcs;
}
/**
* Returns a resource that can be used to download a patch file that
* will bring this application from its current version to the target
* version.
*
* @param auxgroup the auxiliary resource group for which a patch resource
* is desired or null for the main application patch resource.
*/
public Resource getPatchResource (String auxgroup)
{
if (_targetVersion <= _version) {
Log.warning("Requested patch resource for up-to-date or " +
"non-versioned application [cvers=" + _version +
", tvers=" + _targetVersion + "].");
return null;
}
String infix = (auxgroup == null) ? "" : ("-" + auxgroup);
String pfile = "patch" + infix + _version + ".dat";
try {
URL remote = new URL(createVAppBase(_targetVersion), pfile);
return new Resource(pfile, remote, getLocalPath(pfile), false);
} catch (Exception e) {
Log.warning("Failed to create patch resource path [pfile=" + pfile +
", appbase=" + _appbase + ", tvers=" + _targetVersion +
", error=" + e + "].");
return null;
}
}
/**
* Returns a resource that can be used to download an archive containing
* all files belonging to the application.
*/
public Resource getFullResource ()
{
String file = "full";
try {
URL remote = new URL(createVAppBase(_targetVersion), file);
return new Resource(file, remote, getLocalPath(file), false);
} catch (Exception e) {
Log.warning("Failed to create full resource path [file=" + file +
", appbase=" + _appbase + ", tvers=" + _targetVersion +
", error=" + e + "].");
return null;
}
}
/**
* Instructs the application to parse its <code>getdown.txt</code>
* configuration and prepare itself for operation. The application
* base URL will be parsed first so that if there are errors
* discovered later, the caller can use the application base to
* download a new <code>config.txt</code> file and try again.
*
* @return a configured UpdateInterface instance that will be used to
* configure the update UI.
*
* @exception IOException thrown if there is an error reading the file
* or an error encountered during its parsing.
*/
public UpdateInterface init (boolean checkPlatform)
throws IOException
{
// parse our configuration file
HashMap<String,Object> cdata = null;
try {
cdata = ConfigUtil.parseConfig(_config, checkPlatform);
} catch (FileNotFoundException fnfe) {
// thanks to funny windows bullshit, we have to do this backup
// file fiddling in case we got screwed while updating our
// very critical getdown config file
File cbackup = getLocalPath(CONFIG_FILE + "_old");
if (cbackup.exists()) {
cdata = ConfigUtil.parseConfig(cbackup, checkPlatform);
} else {
throw fnfe;
}
}
// first determine our application base, this way if anything goes
// wrong later in the process, our caller can use the appbase to
// download a new configuration file
_appbase = (String)cdata.get("appbase");
if (_appbase == null) {
throw new IOException("m.missing_appbase");
}
// make sure there's a trailing slash
if (!_appbase.endsWith("/")) {
_appbase = _appbase + "/";
}
// extract our version information
String vstr = (String)cdata.get("version");
if (vstr != null) {
try {
_version = Long.parseLong(vstr);
} catch (Exception e) {
String err = MessageUtil.tcompose("m.invalid_version", vstr);
throw (IOException) new IOException(err).initCause(e);
}
}
// if we are a versioned deployment, create a versioned appbase
try {
if (_version < 0) {
_vappbase = new URL(_appbase);
} else {
_vappbase = createVAppBase(_version);
}
} catch (MalformedURLException mue) {
String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
throw (IOException) new IOException(err).initCause(mue);
}
String prefix = (_appid == null) ? "" : (_appid + ".");
// determine our application class name
_class = (String)cdata.get(prefix + "class");
if (_class == null) {
throw new IOException("m.missing_class");
}
// clear our arrays as we may be reinitializing
_codes.clear();
_resources.clear();
_auxgroups.clear();
_auxrsrcs.clear();
_jvmargs.clear();
_appargs.clear();
// parse our code resources
if (ConfigUtil.getMultiValue(cdata, "code") == null) {
throw new IOException("m.missing_code");
}
parseResources(cdata, "code", false, _codes);
// parse our non-code resources
parseResources(cdata, "resource", false, _resources);
parseResources(cdata, "uresource", true, _resources);
// parse our auxiliary resource groups
for (String auxgroup : parseList(cdata, "auxgroups")) {
ArrayList<Resource> rsrcs = new ArrayList<Resource>();
parseResources(cdata, auxgroup + ".resource", false, rsrcs);
parseResources(cdata, auxgroup + ".uresource", true, rsrcs);
_auxrsrcs.put(auxgroup, rsrcs);
_auxgroups.add(auxgroup);
}
// transfer our JVM arguments
String[] jvmargs = ConfigUtil.getMultiValue(cdata, "jvmarg");
if (jvmargs != null) {
for (int ii = 0; ii < jvmargs.length; ii++) {
_jvmargs.add(jvmargs[ii]);
}
}
// transfer our application arguments
String[] appargs = ConfigUtil.getMultiValue(cdata, prefix + "apparg");
if (appargs != null) {
for (int ii = 0; ii < appargs.length; ii++) {
_appargs.add(appargs[ii]);
}
}
// look for custom arguments
File file = getLocalPath("extra.txt");
if (file.exists()) {
try {
List<String[]> args = ConfigUtil.parsePairs(file, false);
for (Iterator<String[]> iter = args.iterator();
iter.hasNext();) {
String[] pair = iter.next();
_jvmargs.add(pair[0] + "=" + pair[1]);
}
} catch (Throwable t) {
Log.warning("Failed to parse '" + file + "': " + t);
}
}
// determine whether or not we should be using bit torrent
- _useTorrent = Boolean.parseBoolean((String)cdata.get("torrent"));
+ _useTorrent = (cdata.get("torrent") != null);
// look for a debug.txt file which causes us to run in java.exe on
// Windows so that we can obtain a thread dump of the running JVM
_windebug = getLocalPath("debug.txt").exists();
// parse and return our application config
UpdateInterface ui = new UpdateInterface();
_name = ui.name = (String)cdata.get("ui.name");
ui.progress = parseRect(cdata, "ui.progress", ui.progress);
ui.progressText = parseColor(
cdata, "ui.progress_text", ui.progressText);
ui.progressBar = parseColor(
cdata, "ui.progress_bar", ui.progressBar);
ui.status = parseRect(cdata, "ui.status", ui.status);
ui.statusText = parseColor(cdata, "ui.status_text", ui.statusText);
ui.textShadow = parseColor(cdata, "ui.text_shadow", ui.textShadow);
ui.backgroundImage = (String)cdata.get("ui.background_image");
if (ui.backgroundImage == null) { // support legacy format
ui.backgroundImage = (String)cdata.get("ui.background");
}
ui.progressImage = (String)cdata.get("ui.progress_image");
// On an installation error, where do we point the user.
ui.installError = (String)cdata.get("ui.install_error");
if (ui.installError == null) {
ui.installError = "m.default_install_error";
} else {
ui.installError = MessageUtil.taint(ui.installError);
}
return ui;
}
/**
* Returns a URL from which the specified path can be fetched. Our
* application base URL is properly versioned and combined with the
* supplied path.
*/
public URL getRemoteURL (String path)
throws MalformedURLException
{
return new URL(_vappbase, path);
}
/**
* Returns the local path to the specified resource.
*/
public File getLocalPath (String path)
{
return new File(_appdir, path);
}
/**
* Attempts to redownload the <code>getdown.txt</code> file based on
* information parsed from a previous call to {@link #init}.
*/
public void attemptRecovery (StatusDisplay status)
throws IOException
{
status.updateStatus("m.updating_metadata");
downloadControlFile(CONFIG_FILE);
}
/**
* Downloads and replaces the <code>getdown.txt</code> and
* <code>digest.txt</code> files with those for the target version of
* our application.
*/
public void updateMetadata ()
throws IOException
{
try {
// update our versioned application base with the target version
_vappbase = createVAppBase(_targetVersion);
} catch (MalformedURLException mue) {
String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
throw (IOException) new IOException(err).initCause(mue);
}
// now re-download our control files; we download the digest first
// so that if it fails, our config file will still reference the
// old version and re-running the updater will start the whole
// process over again
downloadControlFile(Digest.DIGEST_FILE);
downloadControlFile(CONFIG_FILE);
}
/**
* Invokes the process associated with this application definition.
*/
public Process createProcess ()
throws IOException
{
// create our classpath
StringBuilder cpbuf = new StringBuilder();
for (Iterator<Resource> iter = _codes.iterator(); iter.hasNext(); ) {
if (cpbuf.length() > 0) {
cpbuf.append(File.pathSeparator);
}
Resource rsrc = iter.next();
cpbuf.append(rsrc.getLocal().getAbsolutePath());
}
ArrayList<String> args = new ArrayList<String>();
// reconstruct the path to the JVM
args.add(LaunchUtil.getJVMPath(_windebug));
// add the classpath arguments
args.add("-classpath");
args.add(cpbuf.toString());
// we love our Mac users, so we do nice things to preserve our
// application identity
if (RunAnywhere.isMacOS()) {
args.add("-Xdock:icon=" + _appdir.getAbsolutePath() +
"/../desktop.icns");
args.add("-Xdock:name=" + _name);
}
// pass along our proxy settings
String proxyHost;
if ((proxyHost = System.getProperty("http.proxyHost")) != null) {
args.add("-Dhttp.proxyHost=" + proxyHost);
args.add("-Dhttp.proxyPort=" +
System.getProperty("http.proxyPort"));
}
// pass along any pass-through arguments
for (Map.Entry entry : System.getProperties().entrySet()) {
String key = (String)entry.getKey();
if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
args.add("-D" + key + "=" + entry.getValue());
}
}
// add the JVM arguments
for (Iterator<String> iter = _jvmargs.iterator(); iter.hasNext(); ) {
args.add(processArg(iter.next()));
}
// add the application class name
args.add(_class);
// finally add the application arguments
for (Iterator<String> iter = _appargs.iterator(); iter.hasNext(); ) {
args.add(processArg(iter.next()));
}
String[] sargs = new String[args.size()];
args.toArray(sargs);
Log.info("Running " + StringUtil.join(sargs, "\n "));
return Runtime.getRuntime().exec(sargs, null);
}
/**
* Runs this application directly in the current VM.
*/
public void invokeDirect (JApplet applet)
{
// create a custom class loader
ArrayList<URL> jars = new ArrayList<URL>();
for (Resource rsrc : _codes) {
try {
jars.add(
new URL("file", "", rsrc.getLocal().getAbsolutePath()));
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
URLClassLoader loader = new URLClassLoader(
jars.toArray(new URL[jars.size()]),
ClassLoader.getSystemClassLoader()) {
protected PermissionCollection getPermissions (CodeSource code) {
Permissions perms = new Permissions();
perms.add(new AllPermission());
return perms;
}
};
// configure any system properties that we can
for (String jvmarg : _jvmargs) {
if (jvmarg.startsWith("-D")) {
jvmarg = processArg(jvmarg.substring(2));
int eqidx = jvmarg.indexOf("=");
if (eqidx == -1) {
Log.warning("Bogus system property: '" + jvmarg + "'?");
} else {
System.setProperty(jvmarg.substring(0, eqidx),
jvmarg.substring(eqidx+1));
}
}
}
// pass along any pass-through arguments
for (Map.Entry entry : System.getProperties().entrySet()) {
String key = (String)entry.getKey();
if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
System.setProperty(key, (String)entry.getValue());
}
}
// make a note that we're running in "applet" mode
System.setProperty("applet", "true");
try {
Class<?> appclass = loader.loadClass(_class);
String[] args = _appargs.toArray(new String[_appargs.size()]);
Method main;
try {
// first see if the class has a special applet-aware main
main = appclass.getMethod(
"main", JApplet.class, SA_PROTO.getClass());
main.invoke(null, new Object[] { applet, args });
} catch (NoSuchMethodException nsme) {
main = appclass.getMethod("main", SA_PROTO.getClass());
main.invoke(null, new Object[] { args });
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
/** Replaces the application directory and version in any argument. */
protected String processArg (String arg)
{
arg = StringUtil.replace(arg, "%APPDIR%", _appdir.getAbsolutePath());
arg = StringUtil.replace(arg, "%VERSION%", String.valueOf(_version));
return arg;
}
/**
* Loads the <code>digest.txt</code> file and verifies the contents of
* both that file and the <code>getdown.text</code> file. Then it
* loads the <code>version.txt</code> and decides whether or not the
* application needs to be updated or whether we can proceed to
* verification and execution.
*
* @return true if the application needs to be updated, false if it is
* up to date and can be verified and executed.
*
* @exception IOException thrown if we encounter an unrecoverable
* error while verifying the metadata.
*/
public boolean verifyMetadata (StatusDisplay status)
throws IOException
{
Log.info("Verifying application: " + _vappbase);
Log.info("Version: " + _version);
Log.info("Class: " + _class);
// Log.info("Code: " +
// StringUtil.toString(getCodeResources().iterator()));
// Log.info("Resources: " +
// StringUtil.toString(getActiveResources().iterator()));
// Log.info("JVM Args: " + StringUtil.toString(_jvmargs.iterator()));
// Log.info("App Args: " + StringUtil.toString(_appargs.iterator()));
// create our digester which will read in the contents of the
// digest file and validate itself
try {
_digest = new Digest(_appdir);
} catch (IOException ioe) {
Log.info("Failed to load digest: " + ioe.getMessage() + ". " +
"Attempting recovery...");
}
// if we have no version, then we are running in unversioned mode
// so we need to download our digest.txt file on every invocation
if (_version == -1) {
// make a note of the old meta-digest, if this changes we need
// to revalidate all of our resources as one or more of them
// have also changed
String olddig = (_digest == null) ? "" : _digest.getMetaDigest();
try {
status.updateStatus("m.checking");
downloadControlFile(Digest.DIGEST_FILE);
_digest = new Digest(_appdir);
if (!olddig.equals(_digest.getMetaDigest())) {
Log.info("Unversioned digest changed. Revalidating...");
status.updateStatus("m.validating");
clearValidationMarkers();
}
} catch (IOException ioe) {
Log.warning("Failed to refresh non-versioned digest: " +
ioe.getMessage() + ". Proceeding...");
}
}
// regardless of whether we're versioned, if we failed to read the
// digest from disk, try to redownload the digest file and give it
// another good college try; this time we allow exceptions to
// propagate up to the caller as there is nothing else we can do
if (_digest == null) {
status.updateStatus("m.updating_metadata");
downloadControlFile(Digest.DIGEST_FILE);
_digest = new Digest(_appdir);
}
// now verify the contents of our main config file
Resource crsrc = getConfigResource();
if (!_digest.validateResource(crsrc, null)) {
status.updateStatus("m.updating_metadata");
// attempt to redownload both of our metadata files; again we
// pass errors up to our caller because there's nothing we can
// do to automatically recover
downloadControlFile(CONFIG_FILE);
downloadControlFile(Digest.DIGEST_FILE);
_digest = new Digest(_appdir);
// revalidate everything if we end up downloading new metadata
clearValidationMarkers();
// if the new copy validates, reinitialize ourselves;
// otherwise report baffling hoseage
if (_digest.validateResource(crsrc, null)) {
init(true);
} else {
Log.warning(CONFIG_FILE + " failed to validate even after " +
"redownloading. Blindly forging onward.");
}
}
// start by assuming we are happy with our version
_targetVersion = _version;
// if we are a versioned application, read in the contents of the
// version.txt file
if (_version != -1) {
File vfile = getLocalPath(VERSION_FILE);
FileInputStream fin = null;
try {
fin = new FileInputStream(vfile);
BufferedReader bin = new BufferedReader(
new InputStreamReader(fin));
String vstr = bin.readLine();
if (!StringUtil.isBlank(vstr)) {
_targetVersion = Long.parseLong(vstr);
}
} catch (Exception e) {
Log.info("Unable to read version file: " + e.getMessage());
} finally {
StreamUtil.close(fin);
}
}
// finally let the caller know if we need an update
return _version != _targetVersion;
}
/**
* Verifies the code and media resources associated with this
* application. A list of resources that do not exist or fail the
* verification process will be returned. If all resources are ready
* to go, null will be returned and the application is considered
* ready to run.
*/
public List<Resource> verifyResources (ProgressObserver obs)
{
List<Resource> rsrcs = getAllResources();
List<Resource> failures = new ArrayList<Resource>();
// total up the file size of the resources to validate
long totalSize = 0L;
for (Resource rsrc : rsrcs) {
totalSize += rsrc.getLocal().length();
}
MetaProgressObserver mpobs = new MetaProgressObserver(obs, totalSize);
for (Resource rsrc : rsrcs) {
mpobs.startElement(rsrc.getLocal().length());
if (rsrc.isMarkedValid()) {
mpobs.progress(100);
continue;
}
try {
if (_digest.validateResource(rsrc, mpobs)) {
// unpack this resource if appropriate
if (!rsrc.shouldUnpack() || rsrc.unpack()) {
// finally note that this resource is kosher
rsrc.markAsValid();
continue;
}
Log.info("Failure unpacking resource [rsrc=" + rsrc + "].");
}
} catch (Exception e) {
Log.info("Failure validating resource [rsrc=" + rsrc +
", error=" + e + "]. Requesting redownload...");
} finally {
mpobs.progress(100);
}
failures.add(rsrc);
}
return (failures.size() == 0) ? null : failures;
}
/**
* Clears all validation marker files.
*/
public void clearValidationMarkers ()
{
clearValidationMarkers(getAllResources().iterator());
}
/**
* Creates a versioned application base URL for the specified version.
*/
protected URL createVAppBase (long version)
throws MalformedURLException
{
return new URL(
StringUtil.replace(_appbase, "%VERSION%", "" + version));
}
/** Clears all validation marker files for the resources in the
* supplied iterator. */
protected void clearValidationMarkers (Iterator<Resource> iter)
{
while (iter.hasNext()) {
iter.next().clearMarker();
}
}
/**
* Downloads a new copy of the specified control file and, if the
* download is successful, moves it over the old file on the
* filesystem.
*/
protected void downloadControlFile (String path)
throws IOException
{
File target = getLocalPath(path + "_new");
URL targetURL = null;
try {
targetURL = getRemoteURL(path);
} catch (Exception e) {
Log.warning("Requested to download invalid control file " +
"[appbase=" + _vappbase + ", path=" + path +
", error=" + e + "].");
String msg = "Invalid path '" + path + "'.";
throw (IOException) new IOException(msg).initCause(e);
}
Log.info("Attempting to refetch '" + path + "' from '" +
targetURL + "'.");
// stream the URL into our temporary file
InputStream fin = null;
FileOutputStream fout = null;
try {
fin = targetURL.openStream();
fout = new FileOutputStream(target);
CopyUtils.copy(fin, fout);
} finally {
StreamUtil.close(fin);
StreamUtil.close(fout);
}
// Windows is a wonderful operating system, it won't let you
// rename a file overtop of another one; thus to avoid running the
// risk of getting royally fucked, we have to do this complicated
// backup bullshit; this way if the shit hits the fan before we
// get the new copy into place, we should be able to read from the
// backup copy; yay!
File original = getLocalPath(path);
if (RunAnywhere.isWindows() && original.exists()) {
File backup = getLocalPath(path + "_old");
if (backup.exists() && !backup.delete()) {
Log.warning("Failed to delete " + backup + ".");
}
if (!original.renameTo(backup)) {
Log.warning("Failed to move " + original + " to backup. " +
"We will likely fail to replace it with " +
target + ".");
}
}
// now attempt to replace the current file with the new one
if (!target.renameTo(original)) {
throw new IOException(
"Failed to rename(" + target + ", " + original + ")");
}
}
/** Helper function for creating {@link Resource} instances. */
protected Resource createResource (String path, boolean unpack)
throws MalformedURLException
{
return new Resource(
path, getRemoteURL(path), getLocalPath(path), unpack);
}
/** Used to parse resources with the specfied name. */
protected void parseResources (
HashMap<String,Object> cdata, String name, boolean unpack,
ArrayList<Resource> list)
{
String[] rsrcs = ConfigUtil.getMultiValue(cdata, name);
if (rsrcs == null) {
return;
}
for (String rsrc : rsrcs) {
try {
list.add(createResource(rsrc, unpack));
} catch (Exception e) {
Log.warning("Invalid resource '" + rsrc + "'. " + e);
}
}
}
/** Used to parse rectangle specifications from the config file. */
protected Rectangle parseRect (
HashMap<String,Object> cdata, String name, Rectangle def)
{
String value = (String)cdata.get(name);
if (!StringUtil.isBlank(value)) {
int[] v = StringUtil.parseIntArray(value);
if (v != null && v.length == 4) {
return new Rectangle(v[0], v[1], v[2], v[3]);
} else {
Log.warning("Ignoring invalid '" + name + "' config '" +
value + "'.");
}
}
return def;
}
/** Used to parse color specifications from the config file. */
protected Color parseColor (
HashMap<String,Object> cdata, String name, Color def)
{
String value = (String)cdata.get(name);
if (!StringUtil.isBlank(value)) {
try {
return new Color(Integer.parseInt(value, 16));
} catch (Exception e) {
Log.warning("Ignoring invalid '" + name + "' config '" +
value + "'.");
}
}
return def;
}
/** Parses a list of strings from the config file. */
protected String[] parseList (HashMap<String,Object> cdata, String name)
{
String value = (String)cdata.get(name);
return (value == null) ? new String[0] :
StringUtil.parseStringArray(value);
}
protected File _appdir;
protected String _appid;
protected File _config;
protected Digest _digest;
protected long _version = -1;
protected long _targetVersion = -1;
protected String _appbase;
protected URL _vappbase;
protected String _class;
protected String _name;
protected boolean _windebug;
protected boolean _useTorrent = false;
protected ArrayList<Resource> _codes = new ArrayList<Resource>();
protected ArrayList<Resource> _resources = new ArrayList<Resource>();
protected ArrayList<String> _auxgroups = new ArrayList<String>();
protected HashMap<String,ArrayList<Resource>> _auxrsrcs =
new HashMap<String,ArrayList<Resource>>();
protected HashMap<String,Boolean> _auxactive =
new HashMap<String,Boolean>();
protected ArrayList<String> _jvmargs = new ArrayList<String>();
protected ArrayList<String> _appargs = new ArrayList<String>();
protected static final String[] SA_PROTO = new String[0];
}
| true | true | public UpdateInterface init (boolean checkPlatform)
throws IOException
{
// parse our configuration file
HashMap<String,Object> cdata = null;
try {
cdata = ConfigUtil.parseConfig(_config, checkPlatform);
} catch (FileNotFoundException fnfe) {
// thanks to funny windows bullshit, we have to do this backup
// file fiddling in case we got screwed while updating our
// very critical getdown config file
File cbackup = getLocalPath(CONFIG_FILE + "_old");
if (cbackup.exists()) {
cdata = ConfigUtil.parseConfig(cbackup, checkPlatform);
} else {
throw fnfe;
}
}
// first determine our application base, this way if anything goes
// wrong later in the process, our caller can use the appbase to
// download a new configuration file
_appbase = (String)cdata.get("appbase");
if (_appbase == null) {
throw new IOException("m.missing_appbase");
}
// make sure there's a trailing slash
if (!_appbase.endsWith("/")) {
_appbase = _appbase + "/";
}
// extract our version information
String vstr = (String)cdata.get("version");
if (vstr != null) {
try {
_version = Long.parseLong(vstr);
} catch (Exception e) {
String err = MessageUtil.tcompose("m.invalid_version", vstr);
throw (IOException) new IOException(err).initCause(e);
}
}
// if we are a versioned deployment, create a versioned appbase
try {
if (_version < 0) {
_vappbase = new URL(_appbase);
} else {
_vappbase = createVAppBase(_version);
}
} catch (MalformedURLException mue) {
String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
throw (IOException) new IOException(err).initCause(mue);
}
String prefix = (_appid == null) ? "" : (_appid + ".");
// determine our application class name
_class = (String)cdata.get(prefix + "class");
if (_class == null) {
throw new IOException("m.missing_class");
}
// clear our arrays as we may be reinitializing
_codes.clear();
_resources.clear();
_auxgroups.clear();
_auxrsrcs.clear();
_jvmargs.clear();
_appargs.clear();
// parse our code resources
if (ConfigUtil.getMultiValue(cdata, "code") == null) {
throw new IOException("m.missing_code");
}
parseResources(cdata, "code", false, _codes);
// parse our non-code resources
parseResources(cdata, "resource", false, _resources);
parseResources(cdata, "uresource", true, _resources);
// parse our auxiliary resource groups
for (String auxgroup : parseList(cdata, "auxgroups")) {
ArrayList<Resource> rsrcs = new ArrayList<Resource>();
parseResources(cdata, auxgroup + ".resource", false, rsrcs);
parseResources(cdata, auxgroup + ".uresource", true, rsrcs);
_auxrsrcs.put(auxgroup, rsrcs);
_auxgroups.add(auxgroup);
}
// transfer our JVM arguments
String[] jvmargs = ConfigUtil.getMultiValue(cdata, "jvmarg");
if (jvmargs != null) {
for (int ii = 0; ii < jvmargs.length; ii++) {
_jvmargs.add(jvmargs[ii]);
}
}
// transfer our application arguments
String[] appargs = ConfigUtil.getMultiValue(cdata, prefix + "apparg");
if (appargs != null) {
for (int ii = 0; ii < appargs.length; ii++) {
_appargs.add(appargs[ii]);
}
}
// look for custom arguments
File file = getLocalPath("extra.txt");
if (file.exists()) {
try {
List<String[]> args = ConfigUtil.parsePairs(file, false);
for (Iterator<String[]> iter = args.iterator();
iter.hasNext();) {
String[] pair = iter.next();
_jvmargs.add(pair[0] + "=" + pair[1]);
}
} catch (Throwable t) {
Log.warning("Failed to parse '" + file + "': " + t);
}
}
// determine whether or not we should be using bit torrent
_useTorrent = Boolean.parseBoolean((String)cdata.get("torrent"));
// look for a debug.txt file which causes us to run in java.exe on
// Windows so that we can obtain a thread dump of the running JVM
_windebug = getLocalPath("debug.txt").exists();
// parse and return our application config
UpdateInterface ui = new UpdateInterface();
_name = ui.name = (String)cdata.get("ui.name");
ui.progress = parseRect(cdata, "ui.progress", ui.progress);
ui.progressText = parseColor(
cdata, "ui.progress_text", ui.progressText);
ui.progressBar = parseColor(
cdata, "ui.progress_bar", ui.progressBar);
ui.status = parseRect(cdata, "ui.status", ui.status);
ui.statusText = parseColor(cdata, "ui.status_text", ui.statusText);
ui.textShadow = parseColor(cdata, "ui.text_shadow", ui.textShadow);
ui.backgroundImage = (String)cdata.get("ui.background_image");
if (ui.backgroundImage == null) { // support legacy format
ui.backgroundImage = (String)cdata.get("ui.background");
}
ui.progressImage = (String)cdata.get("ui.progress_image");
// On an installation error, where do we point the user.
ui.installError = (String)cdata.get("ui.install_error");
if (ui.installError == null) {
ui.installError = "m.default_install_error";
} else {
ui.installError = MessageUtil.taint(ui.installError);
}
return ui;
}
| public UpdateInterface init (boolean checkPlatform)
throws IOException
{
// parse our configuration file
HashMap<String,Object> cdata = null;
try {
cdata = ConfigUtil.parseConfig(_config, checkPlatform);
} catch (FileNotFoundException fnfe) {
// thanks to funny windows bullshit, we have to do this backup
// file fiddling in case we got screwed while updating our
// very critical getdown config file
File cbackup = getLocalPath(CONFIG_FILE + "_old");
if (cbackup.exists()) {
cdata = ConfigUtil.parseConfig(cbackup, checkPlatform);
} else {
throw fnfe;
}
}
// first determine our application base, this way if anything goes
// wrong later in the process, our caller can use the appbase to
// download a new configuration file
_appbase = (String)cdata.get("appbase");
if (_appbase == null) {
throw new IOException("m.missing_appbase");
}
// make sure there's a trailing slash
if (!_appbase.endsWith("/")) {
_appbase = _appbase + "/";
}
// extract our version information
String vstr = (String)cdata.get("version");
if (vstr != null) {
try {
_version = Long.parseLong(vstr);
} catch (Exception e) {
String err = MessageUtil.tcompose("m.invalid_version", vstr);
throw (IOException) new IOException(err).initCause(e);
}
}
// if we are a versioned deployment, create a versioned appbase
try {
if (_version < 0) {
_vappbase = new URL(_appbase);
} else {
_vappbase = createVAppBase(_version);
}
} catch (MalformedURLException mue) {
String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
throw (IOException) new IOException(err).initCause(mue);
}
String prefix = (_appid == null) ? "" : (_appid + ".");
// determine our application class name
_class = (String)cdata.get(prefix + "class");
if (_class == null) {
throw new IOException("m.missing_class");
}
// clear our arrays as we may be reinitializing
_codes.clear();
_resources.clear();
_auxgroups.clear();
_auxrsrcs.clear();
_jvmargs.clear();
_appargs.clear();
// parse our code resources
if (ConfigUtil.getMultiValue(cdata, "code") == null) {
throw new IOException("m.missing_code");
}
parseResources(cdata, "code", false, _codes);
// parse our non-code resources
parseResources(cdata, "resource", false, _resources);
parseResources(cdata, "uresource", true, _resources);
// parse our auxiliary resource groups
for (String auxgroup : parseList(cdata, "auxgroups")) {
ArrayList<Resource> rsrcs = new ArrayList<Resource>();
parseResources(cdata, auxgroup + ".resource", false, rsrcs);
parseResources(cdata, auxgroup + ".uresource", true, rsrcs);
_auxrsrcs.put(auxgroup, rsrcs);
_auxgroups.add(auxgroup);
}
// transfer our JVM arguments
String[] jvmargs = ConfigUtil.getMultiValue(cdata, "jvmarg");
if (jvmargs != null) {
for (int ii = 0; ii < jvmargs.length; ii++) {
_jvmargs.add(jvmargs[ii]);
}
}
// transfer our application arguments
String[] appargs = ConfigUtil.getMultiValue(cdata, prefix + "apparg");
if (appargs != null) {
for (int ii = 0; ii < appargs.length; ii++) {
_appargs.add(appargs[ii]);
}
}
// look for custom arguments
File file = getLocalPath("extra.txt");
if (file.exists()) {
try {
List<String[]> args = ConfigUtil.parsePairs(file, false);
for (Iterator<String[]> iter = args.iterator();
iter.hasNext();) {
String[] pair = iter.next();
_jvmargs.add(pair[0] + "=" + pair[1]);
}
} catch (Throwable t) {
Log.warning("Failed to parse '" + file + "': " + t);
}
}
// determine whether or not we should be using bit torrent
_useTorrent = (cdata.get("torrent") != null);
// look for a debug.txt file which causes us to run in java.exe on
// Windows so that we can obtain a thread dump of the running JVM
_windebug = getLocalPath("debug.txt").exists();
// parse and return our application config
UpdateInterface ui = new UpdateInterface();
_name = ui.name = (String)cdata.get("ui.name");
ui.progress = parseRect(cdata, "ui.progress", ui.progress);
ui.progressText = parseColor(
cdata, "ui.progress_text", ui.progressText);
ui.progressBar = parseColor(
cdata, "ui.progress_bar", ui.progressBar);
ui.status = parseRect(cdata, "ui.status", ui.status);
ui.statusText = parseColor(cdata, "ui.status_text", ui.statusText);
ui.textShadow = parseColor(cdata, "ui.text_shadow", ui.textShadow);
ui.backgroundImage = (String)cdata.get("ui.background_image");
if (ui.backgroundImage == null) { // support legacy format
ui.backgroundImage = (String)cdata.get("ui.background");
}
ui.progressImage = (String)cdata.get("ui.progress_image");
// On an installation error, where do we point the user.
ui.installError = (String)cdata.get("ui.install_error");
if (ui.installError == null) {
ui.installError = "m.default_install_error";
} else {
ui.installError = MessageUtil.taint(ui.installError);
}
return ui;
}
|
diff --git a/src/com/googlecode/jspcompressor/compressor/JspCompressor.java b/src/com/googlecode/jspcompressor/compressor/JspCompressor.java
index 1a4fd7e..fd672a1 100644
--- a/src/com/googlecode/jspcompressor/compressor/JspCompressor.java
+++ b/src/com/googlecode/jspcompressor/compressor/JspCompressor.java
@@ -1,813 +1,813 @@
package com.googlecode.jspcompressor.compressor;
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.yahoo.platform.yui.compressor.CssCompressor;
import com.yahoo.platform.yui.compressor.JavaScriptCompressor;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.lang.Math;
/**
* Class that compresses given HTML source by removing comments, extra spaces and
* line breaks while preserving content within <pre>, <textarea>, <script>
* and <style> tags. Can optionally compress content inside <script>
* or <style> tags using
* <a href="http://developer.yahoo.com/yui/compressor/">Yahoo YUI Compressor</a>
* library.
*
* @author <a href="mailto:[email protected]">Sergiy Kovalchuk</a>
*/
public class JspCompressor implements Compressor {
private boolean enabled = true;
private int total = 0;
private int failed = 0;
//default settings
private boolean removeComments = true;
private boolean removeJspComments = true;
private boolean removeMultiSpaces = true;
private boolean skipCommentsWithStrutsForm = false;
//optional settings
private boolean removeIntertagSpaces = false;
private boolean removeQuotes = false;
private boolean compressJavaScript = false;
private boolean compressCss = false;
private boolean debugMode = false;
private boolean failOnError = false;
//YUICompressor settings
private boolean yuiJsNoMunge = false;
private boolean yuiJsPreserveAllSemiColons = false;
private boolean yuiJsDisableOptimizations = false;
private int yuiJsLineBreak = -1;
private int yuiCssLineBreak = -1;
//temp replacements for preserved blocks
private static final String tempPreBlock = "%%%COMPRESS~PRE~#%%%";
private static final String tempTextAreaBlock = "%%%COMPRESS~TEXTAREA~#%%%";
private static final String tempScriptBlock = "%%%COMPRESS~SCRIPT~#%%%";
private static final String tempStyleBlock = "%%%COMPRESS~STYLE~#%%%";
private static final String tempJSPBlock = "%%%COMPRESS~JSP~#%%%";
private static final String tempJSPAssignBlock = "%%%COMPRESS~JSPASSIGN~#%%%";
private static final String tempStrutsFormCommentBlock = "%%%COMPRESS~STRUTSFORMCOMMENT~#%%%";
private static final String tempJavaScriptBlock = "___COMPRESSJAVASCRIPTJSP_#___";
private static final String tempJavaScriptJSPELBlock = "___COMPRESSJAVASCRIPTJSPEL_#___";
private static final String tempJSTagBlock = "___COMPRESSJAVASCRIPTTAG_#___";
//compiled regex patterns
// The commentStrutsFormHack pattern purposely excludes any comment with <html:form> in it due to a work around
// for a struts 1.0 bug that we use.
private static final Pattern commentMarkersInScript = Pattern.compile("(<!--)(.*?)(\\/\\/[ \\t]*-->)", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern commentStrutsFormCommentPattern = Pattern.compile("<!--[^\\[].*?html:form[^>]*?>.*?-->", Pattern.CASE_INSENSITIVE);
private static final Pattern commentPattern = Pattern.compile("<!--[^\\[].*?-->", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern jspCommentPattern = Pattern.compile("<%--.+?--%>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern intertagPattern = Pattern.compile(">[ \\t\\n\\r]+?<", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern multispacePattern = Pattern.compile("\\s{2,}", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern prePattern = Pattern.compile("<pre[^>]*?>.*?</pre>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern taPattern = Pattern.compile("<textarea[^>]*?>.*?</textarea>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern tagquotePattern = Pattern.compile("\\s*=\\s*([\"'])([a-z0-9-_]+?)\\1(?=[^<]*?>)", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern scriptPattern = Pattern.compile("<script[^>]*?>.*?</script>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern stylePattern = Pattern.compile("<style[^>]*?>.*?</style>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern scriptPatternNonEmpty = Pattern.compile("<script[^>]*?>(.+?)</script>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern stylePatternNonEmpty = Pattern.compile("<style[^>]*?>(.+?)</style>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
/*
* Ok, I know this is retarded, but I am specifically looking for custom tags that are namespaced, which I know we use in our code.
* I'm assuming this would be true for all JSP programming, but I'm not sure.
*/
private static final Pattern jsTagPattern = Pattern.compile("(<[a-z0-9]+?:[a-z0-9]+?[^>]*?>|</[a-z0-9]+?:[a-z0-9]+?[^>]*?>)", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
// JSP and js block patterns used to strip leading and trailing space, as well as empty lines.
private static final Pattern jspAssignPattern = Pattern.compile("<%=.*?%>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern jspPattern = Pattern.compile("<%[^-=@].*?%>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern jspELPattern = Pattern.compile("\\$\\{.*?\\}", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern jsLeadingSpacePattern = Pattern.compile("^[ \\t]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
private static final Pattern jsTrailingSpacePattern = Pattern.compile("[ \\t]+$", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
private static final Pattern jsEmptyLinePattern = Pattern.compile("^$\\n", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
private static final Pattern jspAllPattern = Pattern.compile("<%[^-@].*?%>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern tempPrePattern = Pattern.compile("%%%COMPRESS~PRE~(\\d+?)%%%", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern tempTextAreaPattern = Pattern.compile("%%%COMPRESS~TEXTAREA~(\\d+?)%%%", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern tempScriptPattern = Pattern.compile("%%%COMPRESS~SCRIPT~(\\d+?)%%%", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern tempStylePattern = Pattern.compile("%%%COMPRESS~STYLE~(\\d+?)%%%", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern tempJSPPattern = Pattern.compile("%%%COMPRESS~JSP~(\\d+?)%%%", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern tempJSPAssignPattern = Pattern.compile("%%%COMPRESS~JSPASSIGN~(\\d+?)%%%", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern tempStrutsFormCommentPattern = Pattern.compile("%%%COMPRESS~STRUTSFORMCOMMENT~(\\d+?)%%%", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern tempJavaScriptJSPPattern = Pattern.compile("___COMPRESSJAVASCRIPTJSP_(\\d+?)___", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern tempJavaScriptJSPELPattern = Pattern.compile("___COMPRESSJAVASCRIPTJSPEL_(\\d+?)___", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
private static final Pattern tempJSTagPattern = Pattern.compile("___COMPRESSJAVASCRIPTTAG_(\\d+?)___", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
/**
* The main method that compresses given HTML source and returns compressed result.
*
* @param html HTML content to compress
* @return compressed content.
* @throws Exception
*/
public String compress(String html) throws Exception {
if(!enabled || html == null || html.length() == 0) {
return html;
}
//preserved block containers
List<String> preBlocks = new ArrayList<String>();
List<String> taBlocks = new ArrayList<String>();
List<String> scriptBlocks = new ArrayList<String>();
List<String> styleBlocks = new ArrayList<String>();
List<String> jspBlocks = new ArrayList<String>();
List<String> jspAssignBlocks = new ArrayList<String>();
List<String> strutsFormCommentBlocks = new ArrayList<String>();
//preserve blocks
html = preserveBlocks(html, preBlocks, taBlocks, scriptBlocks, styleBlocks, jspBlocks, jspAssignBlocks, strutsFormCommentBlocks);
//process pure html
html = processHtml(html);
//process preserved blocks
processScriptBlocks(scriptBlocks);
processStyleBlocks(styleBlocks);
processJSPBlocks(jspBlocks);
//put blocks back
html = returnBlocks(html, preBlocks, taBlocks, scriptBlocks, styleBlocks, jspBlocks, jspAssignBlocks, strutsFormCommentBlocks);
return html.trim();
}
private String preserveBlocks(String html, Pattern thePattern, String tempBlock, List<String> theBlocks) {
Matcher matcher = null;
StringBuffer sb = null;
int index = 0;
matcher = thePattern.matcher(html);
sb = new StringBuffer();
while(matcher.find()) {
theBlocks.add(matcher.group(0));
matcher.appendReplacement(sb, tempBlock.replaceFirst("#", Integer.toString(index++)));
}
matcher.appendTail(sb);
return(sb.toString());
}
private String returnBlocks(String html, Pattern thePattern, List<String> theBlocks) {
Matcher matcher = thePattern.matcher(html);
StringBuffer sb = new StringBuffer();
while(matcher.find()) {
matcher.appendReplacement(sb, Matcher.quoteReplacement(theBlocks.get(Integer.parseInt(matcher.group(1)))));
}
matcher.appendTail(sb);
return(sb.toString());
}
private String preserveBlocks(String html,
List<String> preBlocks,
List<String> taBlocks,
List<String> scriptBlocks,
List<String> styleBlocks,
List<String>jspBlocks,
List<String>jspAssignBlocks,
List<String> strutsFormCommentBlocks) {
// preserve JSP variable references
html = preserveBlocks(html, scriptPattern, tempScriptBlock, scriptBlocks);
html = preserveBlocks(html, jspAssignPattern, tempJSPAssignBlock, jspAssignBlocks);
html = preserveBlocks(html, jspPattern, tempJSPBlock, jspBlocks);
html = preserveBlocks(html, prePattern, tempPreBlock, preBlocks);
html = preserveBlocks(html, stylePattern, tempStyleBlock, styleBlocks);
html = preserveBlocks(html, taPattern, tempTextAreaBlock, taBlocks);
if (skipCommentsWithStrutsForm) {
html = preserveBlocks(html, commentStrutsFormCommentPattern, tempStrutsFormCommentBlock, strutsFormCommentBlocks);
}
return(html);
}
private String returnBlocks(String html,
List<String> preBlocks,
List<String> taBlocks,
List<String> scriptBlocks,
List<String> styleBlocks,
List<String> jspBlocks,
List<String> jspAssignBlocks,
List<String> strutsFormCommentBlocks) {
html = returnBlocks(html, tempStrutsFormCommentPattern, strutsFormCommentBlocks);
html = returnBlocks(html, tempTextAreaPattern, taBlocks);
html = returnBlocks(html, tempStylePattern, styleBlocks);
html = returnBlocks(html, tempScriptPattern, scriptBlocks);
html = returnBlocks(html, tempPrePattern, preBlocks);
html = returnBlocks(html, tempJSPPattern, jspBlocks);
html = returnBlocks(html, tempJSPAssignPattern, jspAssignBlocks);
html = returnBlocks(html, tempScriptPattern, scriptBlocks);
//remove inter-tag spaces
if(removeIntertagSpaces) {
html = intertagPattern.matcher(html).replaceAll("><");
}
return(html);
}
private String processHtml(String html) {
// remove comments and JSP comments, if specified.
if(this.removeComments) {
html = commentPattern.matcher(html).replaceAll("");
}
if (this.removeJspComments) {
html = jspCommentPattern.matcher(html).replaceAll("");
}
//remove inter-tag spaces
if(removeIntertagSpaces) {
html = intertagPattern.matcher(html).replaceAll("><");
}
//remove multi whitespace characters
if(removeMultiSpaces) {
html = multispacePattern.matcher(html).replaceAll(" ");
}
//remove quotes from tag attributes
if(removeQuotes) {
html = tagquotePattern.matcher(html).replaceAll("=$2");
}
return html;
}
private void processScriptBlocks(List<String> scriptBlocks) throws Exception {
List<String> jspBlocks = new ArrayList<String>();
List<String> jspELBlocks = new ArrayList<String>();
int originalSourceLength = 0,
compressionRatio = 0;
for(int i = 0; i < scriptBlocks.size(); i++) {
String scriptBlock = scriptBlocks.get(i);
originalSourceLength = scriptBlock.length();
// Remove any JSP comments that might be in the javascript for security reasons
// (developer only comments, etc)
scriptBlock = jspCommentPattern.matcher(scriptBlock).replaceAll("");
// remove any comment markers you might find in Javascript code (<!-- //-->)
scriptBlock = commentMarkersInScript.matcher(scriptBlock).replaceAll("$2");
// yes, HTML comments are sometimes found in Javascript.
scriptBlock = commentPattern.matcher(scriptBlock).replaceAll("");
scriptBlock = preserveBlocks(scriptBlock, jspAllPattern, tempJavaScriptBlock, jspBlocks);
scriptBlock = preserveBlocks(scriptBlock, jspELPattern, tempJavaScriptJSPELBlock, jspELBlocks);
if (!compressJavaScript) {
scriptBlock = trimEmptySpace(scriptBlock);
} else {
scriptBlock = compressJavaScript(scriptBlock);
}
scriptBlock = returnBlocks(scriptBlock, tempJavaScriptJSPPattern, jspBlocks);
scriptBlock = returnBlocks(scriptBlock, tempJavaScriptJSPELPattern, jspELBlocks);
// Calculate compresion ratio achieved.
compressionRatio = compressionRatio(originalSourceLength, scriptBlock.length());
if (debugMode) {
System.out.println("Returning " + scriptBlock);
System.out.println("\nOriginal Size: " + originalSourceLength + ", reduced to " + scriptBlock.length() + " (" + Integer.toString(compressionRatio) + "%)");
} else {
//System.out.println(Integer.toString(originalSourceLength) + "|" + Integer.toString(scriptBlock.length()) + "|" + Integer.toString(compressionRatio) + "%");
}
scriptBlocks.set(i, scriptBlock);
- // clear jsp blocks collection for the next iteration.
+ // clear jsp blocks collection for the next iteration.
jspBlocks.clear();
- jspELBlocks.clear();
+ jspELBlocks.clear();
}
}
/*
* Calculate compression ratio
*/
private int compressionRatio(int originalSourceLength, int newLength) {
return((int) Math.abs(((((double) newLength - (double) originalSourceLength) / (double) originalSourceLength) * 100.00)));
}
private String trimEmptySpace(String scriptBlock) {
if (scriptBlock != null && scriptBlock.length() > 0) {
scriptBlock = jsLeadingSpacePattern.matcher(scriptBlock).replaceAll("");
scriptBlock = jsTrailingSpacePattern.matcher(scriptBlock).replaceAll("");
scriptBlock = jsEmptyLinePattern.matcher(scriptBlock).replaceAll("");
}
return(scriptBlock);
}
private void processJSPBlocks(List<String> theBlocks) {
for(int i = 0; i < theBlocks.size(); i++) {
String theBlock = theBlocks.get(i);
// Remove any JSP comments that might be in the javascript for security reasons
// (developer only comments, etc)
theBlock = jspCommentPattern.matcher(theBlock).replaceAll("");
theBlock = trimEmptySpace(theBlock);
theBlocks.set(i, theBlock);
}
}
private void processStyleBlocks(List<String> styleBlocks) throws Exception {
if(compressCss) {
for(int i = 0; i < styleBlocks.size(); i++) {
styleBlocks.set(i, compressCssStyles(styleBlocks.get(i)));
}
}
}
private String compressJavaScript(String source) throws Exception {
StringWriter result = new StringWriter();
String originalSource = new String(source);
String scriptBlock = null;
total++;
source = commentMarkersInScript.matcher(source).replaceAll("");
//check if block is not empty
Matcher scriptMatcher = scriptPatternNonEmpty.matcher(source);
if(scriptMatcher.find()) {
//call YUICompressor
try {
List<String> tagBlocks = new ArrayList<String>();
scriptBlock = scriptMatcher.group(1);
scriptBlock = preserveBlocks(scriptBlock, jsTagPattern, tempJSTagBlock, tagBlocks);
if (debugMode) {
int v = 0;
for (String q : tagBlocks) {
System.out.println(Integer.toString(v) + ": " + q);
v++;
}
System.out.println("Compressing: " + scriptBlock);
}
JavaScriptCompressor compressor = new JavaScriptCompressor(new StringReader(scriptBlock), null);
compressor.compress(result, yuiJsLineBreak, !yuiJsNoMunge, false, yuiJsPreserveAllSemiColons, yuiJsDisableOptimizations);
scriptBlock = returnBlocks(result.toString(), tempJSTagPattern, tagBlocks);
} catch (Exception e) {
failed++;
if (failOnError) {
throw new Exception("Returning " + scriptBlock);
}
return(trimEmptySpace(originalSource));
}
return (new StringBuilder(source.substring(0, scriptMatcher.start(1))).append(scriptBlock.toString()).append(source.substring(scriptMatcher.end(1)))).toString();
} else {
return source;
}
}
private String compressCssStyles(String source) throws Exception {
// check if block is not empty
Matcher styleMatcher = stylePatternNonEmpty.matcher(source);
if(styleMatcher.find()) {
// call YUICompressor
StringWriter result = new StringWriter();
CssCompressor compressor = new CssCompressor(new StringReader(styleMatcher.group(1)));
compressor.compress(result, yuiCssLineBreak);
if (debugMode) {
int originalSize = styleMatcher.group(1).length();
int newSize = result.toString().length();
System.out.println("Compressed inline CSS - original size was " + Integer.toString(originalSize) + " bytes, new size is " + Integer.toString(newSize) + " bytes - (" + compressionRatio(originalSize, newSize) + "% reduction)");
}
return (new StringBuilder(source.substring(0, styleMatcher.start(1))).append(result.toString()).append(source.substring(styleMatcher.end(1)))).toString();
} else {
return source;
}
}
/**
* Returns <code>true</code> if JavaScript compression is enabled.
*
* @return current state of JavaScript compression.
*/
public boolean isCompressJavaScript() {
return compressJavaScript;
}
/**
* Enables JavaScript compression within <script> tags using
* <a href="http://developer.yahoo.com/yui/compressor/">Yahoo YUI Compressor</a>
* if set to <code>true</code>. Default is <code>false</code> for performance reasons.
*
* <p><b>Note:</b> Compressing JavaScript is not recommended if pages are
* compressed dynamically on-the-fly because of performance impact.
* You should consider putting JavaScript into a separate file and
* compressing it using standalone YUICompressor for example.</p>
*
* @param compressJavaScript set <code>true</code> to enable JavaScript compression.
* Default is <code>false</code>
*
* @see <a href="http://developer.yahoo.com/yui/compressor/">Yahoo YUI Compressor</a>
*
*/
public void setCompressJavaScript(boolean compressJavaScript) {
this.compressJavaScript = compressJavaScript;
}
/**
* Returns <code>true</code> if CSS compression is enabled.
*
* @return current state of CSS compression.
*/
public boolean isCompressCss() {
return compressCss;
}
/**
* Enables CSS compression within <style> tags using
* <a href="http://developer.yahoo.com/yui/compressor/">Yahoo YUI Compressor</a>
* if set to <code>true</code>. Default is <code>false</code> for performance reasons.
*
* <p><b>Note:</b> Compressing CSS is not recommended if pages are
* compressed dynamically on-the-fly because of performance impact.
* You should consider putting CSS into a separate file and
* compressing it using standalone YUICompressor for example.</p>
*
* @param compressCss set <code>true</code> to enable CSS compression.
* Default is <code>false</code>
*
* @see <a href="http://developer.yahoo.com/yui/compressor/">Yahoo YUI Compressor</a>
*
*/
public void setCompressCss(boolean compressCss) {
this.compressCss = compressCss;
}
/**
* Returns <code>true</code> if Yahoo YUI Compressor
* will only minify javascript without obfuscating local symbols.
* This corresponds to <code>--nomunge</code> command line option.
*
* @return <code>nomunge</code> parameter value used for JavaScript compression.
*
* @see <a href="http://developer.yahoo.com/yui/compressor/">Yahoo YUI Compressor</a>
*/
public boolean isYuiJsNoMunge() {
return yuiJsNoMunge;
}
/**
* Tells Yahoo YUI Compressor to only minify javascript without obfuscating
* local symbols. This corresponds to <code>--nomunge</code> command line option.
* This option has effect only if JavaScript compression is enabled.
* Default is <code>false</code>.
*
* @param yuiJsNoMunge set <code>true<code> to enable <code>nomunge</code> mode
*
* @see <a href="http://developer.yahoo.com/yui/compressor/">Yahoo YUI Compressor</a>
*/
public void setYuiJsNoMunge(boolean yuiJsNoMunge) {
this.yuiJsNoMunge = yuiJsNoMunge;
}
/**
* Returns <code>true</code> if Yahoo YUI Compressor
* will preserve unnecessary semicolons during JavaScript compression.
* This corresponds to <code>--preserve-semi</code> command line option.
*
* @return <code>preserve-semi</code> parameter value used for JavaScript compression.
*
* @see <a href="http://developer.yahoo.com/yui/compressor/">Yahoo YUI Compressor</a>
*/
public boolean isYuiJsPreserveAllSemiColons() {
return yuiJsPreserveAllSemiColons;
}
/**
* Tells Yahoo YUI Compressor to preserve unnecessary semicolons
* during JavaScript compression. This corresponds to
* <code>--preserve-semi</code> command line option.
* This option has effect only if JavaScript compression is enabled.
* Default is <code>false</code>.
*
* @param yuiJsPreserveAllSemiColons set <code>true<code> to enable <code>preserve-semi</code> mode
*
* @see <a href="http://developer.yahoo.com/yui/compressor/">Yahoo YUI Compressor</a>
*/
public void setYuiJsPreserveAllSemiColons(boolean yuiJsPreserveAllSemiColons) {
this.yuiJsPreserveAllSemiColons = yuiJsPreserveAllSemiColons;
}
/**
* Returns <code>true</code> if Yahoo YUI Compressor
* will disable all the built-in micro optimizations during JavaScript compression.
* This corresponds to <code>--disable-optimizations</code> command line option.
*
* @return <code>disable-optimizations</code> parameter value used for JavaScript compression.
*
* @see <a href="http://developer.yahoo.com/yui/compressor/">Yahoo YUI Compressor</a>
*/
public boolean isYuiJsDisableOptimizations() {
return yuiJsDisableOptimizations;
}
/**
* Tells Yahoo YUI Compressor to disable all the built-in micro optimizations
* during JavaScript compression. This corresponds to
* <code>--disable-optimizations</code> command line option.
* This option has effect only if JavaScript compression is enabled.
* Default is <code>false</code>.
*
* @param yuiJsDisableOptimizations set <code>true<code> to enable
* <code>disable-optimizations</code> mode
*
* @see <a href="http://developer.yahoo.com/yui/compressor/">Yahoo YUI Compressor</a>
*/
public void setYuiJsDisableOptimizations(boolean yuiJsDisableOptimizations) {
this.yuiJsDisableOptimizations = yuiJsDisableOptimizations;
}
/**
* Returns number of symbols per line Yahoo YUI Compressor
* will use during JavaScript compression.
* This corresponds to <code>--line-break</code> command line option.
*
* @return <code>line-break</code> parameter value used for JavaScript compression.
*
* @see <a href="http://developer.yahoo.com/yui/compressor/">Yahoo YUI Compressor</a>
*/
public int getYuiJsLineBreak() {
return yuiJsLineBreak;
}
/**
* Tells Yahoo YUI Compressor to break lines after the specified number of symbols
* during JavaScript compression. This corresponds to
* <code>--line-break</code> command line option.
* This option has effect only if JavaScript compression is enabled.
* Default is <code>-1</code> to disable line breaks.
*
* @param yuiJsLineBreak set number of symbols per line
*
* @see <a href="http://developer.yahoo.com/yui/compressor/">Yahoo YUI Compressor</a>
*/
public void setYuiJsLineBreak(int yuiJsLineBreak) {
this.yuiJsLineBreak = yuiJsLineBreak;
}
/**
* Returns number of symbols per line Yahoo YUI Compressor
* will use during CSS compression.
* This corresponds to <code>--line-break</code> command line option.
*
* @return <code>line-break</code> parameter value used for CSS compression.
*
* @see <a href="http://developer.yahoo.com/yui/compressor/">Yahoo YUI Compressor</a>
*/
public int getYuiCssLineBreak() {
return yuiCssLineBreak;
}
/**
* Tells Yahoo YUI Compressor to break lines after the specified number of symbols
* during CSS compression. This corresponds to
* <code>--line-break</code> command line option.
* This option has effect only if CSS compression is enabled.
* Default is <code>-1</code> to disable line breaks.
*
* @param yuiCssLineBreak set number of symbols per line
*
* @see <a href="http://developer.yahoo.com/yui/compressor/">Yahoo YUI Compressor</a>
*/
public void setYuiCssLineBreak(int yuiCssLineBreak) {
this.yuiCssLineBreak = yuiCssLineBreak;
}
/**
* Returns <code>true</code> if all unnecessary quotes will be removed
* from tag attributes.
*
*/
public boolean isRemoveQuotes() {
return removeQuotes;
}
/**
* If set to <code>true</code> all unnecessary quotes will be removed
* from tag attributes. Default is <code>false</code>.
*
* <p><b>Note:</b> Even though quotes are removed only when it is safe to do so,
* it still might break strict HTML validation. Turn this option on only if
* a page validation is not very important or to squeeze the most out of the compression.
* This option has no performance impact.
*
* @param removeQuotes set <code>true</code> to remove unnecessary quotes from tag attributes
*/
public void setRemoveQuotes(boolean removeQuotes) {
this.removeQuotes = removeQuotes;
}
/**
* Returns <code>true</code> if compression is enabled.
*
* @return <code>true</code> if compression is enabled.
*/
public boolean isEnabled() {
return enabled;
}
/**
* If set to <code>false</code> all compression will be bypassed. Might be useful for testing purposes.
* Default is <code>true</code>.
*
* @param enabled set <code>false</code> to bypass all compression
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
/**
* Returns <code>true</code> if all HTML comments will be removed.
*
* @return <code>true</code> if all HTML comments will be removed
*/
public boolean isRemoveComments() {
return removeComments;
}
/**
* If set to <code>true</code> all HTML comments will be removed.
* Default is <code>true</code>.
*
* @param removeComments set <code>true</code> to remove all HTML comments
*/
public void setRemoveComments(boolean removeComments) {
this.removeComments = removeComments;
}
/**
* Returns <code>true</code> if all HTML comments will be removed.
*
* @return <code>true</code> if all HTML comments will be removed
*/
public boolean isRemoveJspComments() {
return removeJspComments;
}
/**
* If set to <code>true</code> all HTML comments will be removed.
* Default is <code>true</code>.
*
* @param removeComments set <code>true</code> to remove all HTML comments
*/
public void setRemoveJspComments(boolean removeComments) {
this.removeJspComments = removeComments;
}
/**
* Returns <code>true</code> if all multiple whitespace characters will be replaced with single spaces.
*
* @return <code>true</code> if all multiple whitespace characters will be replaced with single spaces.
*/
public boolean isRemoveMultiSpaces() {
return removeMultiSpaces;
}
/**
* If set to <code>true</code> all multiple whitespace characters will be replaced with single spaces.
* Default is <code>true</code>.
*
* @param removeMultiSpaces set <code>true</code> to replace all multiple whitespace characters
* will single spaces.
*/
public void setRemoveMultiSpaces(boolean removeMultiSpaces) {
this.removeMultiSpaces = removeMultiSpaces;
}
/**
* Returns <code>true</code> if all inter-tag whitespace characters will be removed.
*
* @return <code>true</code> if all inter-tag whitespace characters will be removed.
*/
public boolean isRemoveIntertagSpaces() {
return removeIntertagSpaces;
}
/**
* If set to <code>true</code> all inter-tag whitespace characters will be removed.
* Default is <code>false</code>.
*
* <p><b>Note:</b> It is fairly safe to turn this option on unless you
* rely on spaces for page formatting. Even if you do, you can always preserve
* required spaces with <code>&nbsp;</code>. This option has no performance impact.
*
* @param removeIntertagSpaces set <code>true</code> to remove all inter-tag whitespace characters
*/
public void setRemoveIntertagSpaces(boolean removeIntertagSpaces) {
this.removeIntertagSpaces = removeIntertagSpaces;
}
/**
* If set to <code>true</code> comments with the <html:form> opening and closing tags will be skipped
* during comment removal. This is a workaround for a Struts 1.0 bug, in which there were issues
* with this tag that caused other form fields to work improperly. The workaround was to put the
* <html:tag> opening and closing tags in comments which caused the proper structures to (for some reason)
* still be initialized properly, but did not use the tag, and then to use standard for tags around your
* struts controls. Kind of odd, but thats how it works.
*/
public void setSkipStrutsFormComments(boolean leaveComments) {
skipCommentsWithStrutsForm = leaveComments;
}
/**
* If set to <code>true</code> the compressor will display debug messages as it works.
*/
public void setDebugMode(boolean debugMode) {
this.debugMode = debugMode;
}
/**
* Get number of failed blocks of this run.
* @return Number of blocks that have failed Javascript compression
*/
public int getFailed() {
return(failed);
}
/**
* Get total number of javascript blocks processed during this run.
* @return Total number of blocks processed on this run.
*/
public int getTotal() {
return(total);
}
/**
* Set property causing failure on error parsing Javascript. This will throw an exception with the
* offending code as the message, which will stop the build and show the user what block of code was
* being processed when the failure occured.
*
* If this setting is false, all extraneous spaces will be removed from the script block and it will
* be returned from the compressor - so you'll still get compression, just not the full advantage
* of the YUI compressor.
*
*/
public void setFailOnError(boolean failonerror) {
this.failOnError = failonerror;
}
}
| false | true | private void processScriptBlocks(List<String> scriptBlocks) throws Exception {
List<String> jspBlocks = new ArrayList<String>();
List<String> jspELBlocks = new ArrayList<String>();
int originalSourceLength = 0,
compressionRatio = 0;
for(int i = 0; i < scriptBlocks.size(); i++) {
String scriptBlock = scriptBlocks.get(i);
originalSourceLength = scriptBlock.length();
// Remove any JSP comments that might be in the javascript for security reasons
// (developer only comments, etc)
scriptBlock = jspCommentPattern.matcher(scriptBlock).replaceAll("");
// remove any comment markers you might find in Javascript code (<!-- //-->)
scriptBlock = commentMarkersInScript.matcher(scriptBlock).replaceAll("$2");
// yes, HTML comments are sometimes found in Javascript.
scriptBlock = commentPattern.matcher(scriptBlock).replaceAll("");
scriptBlock = preserveBlocks(scriptBlock, jspAllPattern, tempJavaScriptBlock, jspBlocks);
scriptBlock = preserveBlocks(scriptBlock, jspELPattern, tempJavaScriptJSPELBlock, jspELBlocks);
if (!compressJavaScript) {
scriptBlock = trimEmptySpace(scriptBlock);
} else {
scriptBlock = compressJavaScript(scriptBlock);
}
scriptBlock = returnBlocks(scriptBlock, tempJavaScriptJSPPattern, jspBlocks);
scriptBlock = returnBlocks(scriptBlock, tempJavaScriptJSPELPattern, jspELBlocks);
// Calculate compresion ratio achieved.
compressionRatio = compressionRatio(originalSourceLength, scriptBlock.length());
if (debugMode) {
System.out.println("Returning " + scriptBlock);
System.out.println("\nOriginal Size: " + originalSourceLength + ", reduced to " + scriptBlock.length() + " (" + Integer.toString(compressionRatio) + "%)");
} else {
//System.out.println(Integer.toString(originalSourceLength) + "|" + Integer.toString(scriptBlock.length()) + "|" + Integer.toString(compressionRatio) + "%");
}
scriptBlocks.set(i, scriptBlock);
// clear jsp blocks collection for the next iteration.
jspBlocks.clear();
jspELBlocks.clear();
}
}
| private void processScriptBlocks(List<String> scriptBlocks) throws Exception {
List<String> jspBlocks = new ArrayList<String>();
List<String> jspELBlocks = new ArrayList<String>();
int originalSourceLength = 0,
compressionRatio = 0;
for(int i = 0; i < scriptBlocks.size(); i++) {
String scriptBlock = scriptBlocks.get(i);
originalSourceLength = scriptBlock.length();
// Remove any JSP comments that might be in the javascript for security reasons
// (developer only comments, etc)
scriptBlock = jspCommentPattern.matcher(scriptBlock).replaceAll("");
// remove any comment markers you might find in Javascript code (<!-- //-->)
scriptBlock = commentMarkersInScript.matcher(scriptBlock).replaceAll("$2");
// yes, HTML comments are sometimes found in Javascript.
scriptBlock = commentPattern.matcher(scriptBlock).replaceAll("");
scriptBlock = preserveBlocks(scriptBlock, jspAllPattern, tempJavaScriptBlock, jspBlocks);
scriptBlock = preserveBlocks(scriptBlock, jspELPattern, tempJavaScriptJSPELBlock, jspELBlocks);
if (!compressJavaScript) {
scriptBlock = trimEmptySpace(scriptBlock);
} else {
scriptBlock = compressJavaScript(scriptBlock);
}
scriptBlock = returnBlocks(scriptBlock, tempJavaScriptJSPPattern, jspBlocks);
scriptBlock = returnBlocks(scriptBlock, tempJavaScriptJSPELPattern, jspELBlocks);
// Calculate compresion ratio achieved.
compressionRatio = compressionRatio(originalSourceLength, scriptBlock.length());
if (debugMode) {
System.out.println("Returning " + scriptBlock);
System.out.println("\nOriginal Size: " + originalSourceLength + ", reduced to " + scriptBlock.length() + " (" + Integer.toString(compressionRatio) + "%)");
} else {
//System.out.println(Integer.toString(originalSourceLength) + "|" + Integer.toString(scriptBlock.length()) + "|" + Integer.toString(compressionRatio) + "%");
}
scriptBlocks.set(i, scriptBlock);
// clear jsp blocks collection for the next iteration.
jspBlocks.clear();
jspELBlocks.clear();
}
}
|
diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/AsyncDataManager.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/AsyncDataManager.java
index 3eb68fd5c..84ed26f2e 100644
--- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/AsyncDataManager.java
+++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/AsyncDataManager.java
@@ -1,563 +1,567 @@
/**
* 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.kaha.impl.async;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
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.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.activemq.kaha.impl.async.DataFileAppender.WriteCommand;
import org.apache.activemq.kaha.impl.async.DataFileAppender.WriteKey;
import org.apache.activemq.thread.Scheduler;
import org.apache.activemq.util.ByteSequence;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Manages DataFiles
*
* @version $Revision: 1.1.1.1 $
*/
public final class AsyncDataManager {
public static final int CONTROL_RECORD_MAX_LENGTH = 1024;
public static final int ITEM_HEAD_RESERVED_SPACE = 21;
// ITEM_HEAD_SPACE = length + type+ reserved space + SOR
public static final int ITEM_HEAD_SPACE = 4 + 1 + ITEM_HEAD_RESERVED_SPACE + 3;
public static final int ITEM_HEAD_OFFSET_TO_SOR = ITEM_HEAD_SPACE - 3;
public static final int ITEM_FOOT_SPACE = 3; // EOR
public static final int ITEM_HEAD_FOOT_SPACE = ITEM_HEAD_SPACE + ITEM_FOOT_SPACE;
public static final byte[] ITEM_HEAD_SOR = new byte[] {'S', 'O', 'R'}; //
public static final byte[] ITEM_HEAD_EOR = new byte[] {'E', 'O', 'R'}; //
public static final byte DATA_ITEM_TYPE = 1;
public static final byte REDO_ITEM_TYPE = 2;
public static final String DEFAULT_DIRECTORY = "data";
public static final String DEFAULT_FILE_PREFIX = "data-";
public static final int DEFAULT_MAX_FILE_LENGTH = 1024 * 1024 * 32;
private static final Log LOG = LogFactory.getLog(AsyncDataManager.class);
protected final Map<WriteKey, WriteCommand> inflightWrites = new ConcurrentHashMap<WriteKey, WriteCommand>();
File directory = new File(DEFAULT_DIRECTORY);
String filePrefix = DEFAULT_FILE_PREFIX;
ControlFile controlFile;
boolean started;
boolean useNio = true;
private int maxFileLength = DEFAULT_MAX_FILE_LENGTH;
private int preferedFileLength = DEFAULT_MAX_FILE_LENGTH - 1024 * 512;
private DataFileAppender appender;
private DataFileAccessorPool accessorPool = new DataFileAccessorPool(this);
private Map<Integer, DataFile> fileMap = new HashMap<Integer, DataFile>();
private DataFile currentWriteFile;
private Location mark;
private final AtomicReference<Location> lastAppendLocation = new AtomicReference<Location>();
private Runnable cleanupTask;
private final AtomicLong storeSize;
public AsyncDataManager(AtomicLong storeSize) {
this.storeSize=storeSize;
}
public AsyncDataManager() {
this(new AtomicLong());
}
@SuppressWarnings("unchecked")
public synchronized void start() throws IOException {
if (started) {
return;
}
started = true;
directory.mkdirs();
synchronized (this) {
controlFile = new ControlFile(new File(directory, filePrefix + "control"), CONTROL_RECORD_MAX_LENGTH);
controlFile.lock();
}
ByteSequence sequence = controlFile.load();
if (sequence != null && sequence.getLength() > 0) {
unmarshallState(sequence);
}
if (useNio) {
appender = new NIODataFileAppender(this);
} else {
appender = new DataFileAppender(this);
}
File[] files = directory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String n) {
return dir.equals(directory) && n.startsWith(filePrefix);
}
});
if (files != null) {
for (int i = 0; i < files.length; i++) {
try {
File file = files[i];
String n = file.getName();
String numStr = n.substring(filePrefix.length(), n.length());
int num = Integer.parseInt(numStr);
DataFile dataFile = new DataFile(file, num, preferedFileLength);
fileMap.put(dataFile.getDataFileId(), dataFile);
storeSize.addAndGet(dataFile.getLength());
} catch (NumberFormatException e) {
// Ignore file that do not match the pattern.
}
}
// Sort the list so that we can link the DataFiles together in the
// right order.
List<DataFile> l = new ArrayList<DataFile>(fileMap.values());
Collections.sort(l);
currentWriteFile = null;
for (DataFile df : l) {
if (currentWriteFile != null) {
currentWriteFile.linkAfter(df);
}
currentWriteFile = df;
}
}
// Need to check the current Write File to see if there was a partial
// write to it.
if (currentWriteFile != null) {
// See if the lastSyncedLocation is valid..
Location l = lastAppendLocation.get();
if (l != null && l.getDataFileId() != currentWriteFile.getDataFileId().intValue()) {
l = null;
}
// If we know the last location that was ok.. then we can skip lots
// of checking
+ try{
l = recoveryCheck(currentWriteFile, l);
lastAppendLocation.set(l);
+ }catch(IOException e){
+ LOG.warn("recovery check failed", e);
+ }
}
storeState(false);
cleanupTask = new Runnable() {
public void run() {
cleanup();
}
};
Scheduler.executePeriodically(cleanupTask, 1000 * 30);
}
private Location recoveryCheck(DataFile dataFile, Location location) throws IOException {
if (location == null) {
location = new Location();
location.setDataFileId(dataFile.getDataFileId());
location.setOffset(0);
}
DataFileAccessor reader = accessorPool.openDataFileAccessor(dataFile);
try {
reader.readLocationDetails(location);
while (reader.readLocationDetailsAndValidate(location)) {
location.setOffset(location.getOffset() + location.getSize());
}
} finally {
accessorPool.closeDataFileAccessor(reader);
}
dataFile.setLength(location.getOffset());
return location;
}
private void unmarshallState(ByteSequence sequence) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(sequence.getData(), sequence.getOffset(), sequence.getLength());
DataInputStream dis = new DataInputStream(bais);
if (dis.readBoolean()) {
mark = new Location();
mark.readExternal(dis);
} else {
mark = null;
}
if (dis.readBoolean()) {
Location l = new Location();
l.readExternal(dis);
lastAppendLocation.set(l);
} else {
lastAppendLocation.set(null);
}
}
private synchronized ByteSequence marshallState() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
if (mark != null) {
dos.writeBoolean(true);
mark.writeExternal(dos);
} else {
dos.writeBoolean(false);
}
Location l = lastAppendLocation.get();
if (l != null) {
dos.writeBoolean(true);
l.writeExternal(dos);
} else {
dos.writeBoolean(false);
}
byte[] bs = baos.toByteArray();
return new ByteSequence(bs, 0, bs.length);
}
synchronized DataFile allocateLocation(Location location) throws IOException {
if (currentWriteFile == null || ((currentWriteFile.getLength() + location.getSize()) > maxFileLength)) {
int nextNum = currentWriteFile != null ? currentWriteFile.getDataFileId().intValue() + 1 : 1;
String fileName = filePrefix + nextNum;
DataFile nextWriteFile = new DataFile(new File(directory, fileName), nextNum, preferedFileLength);
fileMap.put(nextWriteFile.getDataFileId(), nextWriteFile);
if (currentWriteFile != null) {
currentWriteFile.linkAfter(nextWriteFile);
if (currentWriteFile.isUnused()) {
removeDataFile(currentWriteFile);
}
}
currentWriteFile = nextWriteFile;
}
location.setOffset(currentWriteFile.getLength());
location.setDataFileId(currentWriteFile.getDataFileId().intValue());
int size = location.getSize();
currentWriteFile.incrementLength(size);
currentWriteFile.increment();
storeSize.addAndGet(size);
return currentWriteFile;
}
DataFile getDataFile(Location item) throws IOException {
Integer key = Integer.valueOf(item.getDataFileId());
DataFile dataFile = fileMap.get(key);
if (dataFile == null) {
LOG.error("Looking for key " + key + " but not found in fileMap: " + fileMap);
throw new IOException("Could not locate data file " + filePrefix + "-" + item.getDataFileId());
}
return dataFile;
}
private DataFile getNextDataFile(DataFile dataFile) {
return (DataFile)dataFile.getNext();
}
public synchronized void close() throws IOException {
if (!started) {
return;
}
Scheduler.cancel(cleanupTask);
accessorPool.close();
storeState(false);
appender.close();
fileMap.clear();
controlFile.unlock();
controlFile.dispose();
started = false;
}
synchronized void cleanup() {
if (accessorPool != null) {
accessorPool.disposeUnused();
}
}
public synchronized boolean delete() throws IOException {
// Close all open file handles...
appender.close();
accessorPool.close();
boolean result = true;
for (Iterator i = fileMap.values().iterator(); i.hasNext();) {
DataFile dataFile = (DataFile)i.next();
storeSize.addAndGet(-dataFile.getLength());
result &= dataFile.delete();
}
fileMap.clear();
lastAppendLocation.set(null);
mark = null;
currentWriteFile = null;
// reopen open file handles...
accessorPool = new DataFileAccessorPool(this);
if (useNio) {
appender = new NIODataFileAppender(this);
} else {
appender = new DataFileAppender(this);
}
return result;
}
public synchronized void addInterestInFile(int file) throws IOException {
if (file >= 0) {
Integer key = Integer.valueOf(file);
DataFile dataFile = (DataFile)fileMap.get(key);
if (dataFile == null) {
throw new IOException("That data file does not exist");
}
addInterestInFile(dataFile);
}
}
synchronized void addInterestInFile(DataFile dataFile) {
if (dataFile != null) {
dataFile.increment();
}
}
public synchronized void removeInterestInFile(int file) throws IOException {
if (file >= 0) {
Integer key = Integer.valueOf(file);
DataFile dataFile = (DataFile)fileMap.get(key);
removeInterestInFile(dataFile);
}
}
synchronized void removeInterestInFile(DataFile dataFile) throws IOException {
if (dataFile != null) {
if (dataFile.decrement() <= 0) {
removeDataFile(dataFile);
}
}
}
public synchronized void consolidateDataFilesNotIn(Set<Integer> inUse) throws IOException {
// Substract and the difference is the set of files that are no longer
// needed :)
Set<Integer> unUsed = new HashSet<Integer>(fileMap.keySet());
unUsed.removeAll(inUse);
List<DataFile> purgeList = new ArrayList<DataFile>();
for (Integer key : unUsed) {
DataFile dataFile = (DataFile)fileMap.get(key);
purgeList.add(dataFile);
}
for (DataFile dataFile : purgeList) {
removeDataFile(dataFile);
}
}
public synchronized void consolidateDataFiles() throws IOException {
List<DataFile> purgeList = new ArrayList<DataFile>();
for (DataFile dataFile : fileMap.values()) {
if (dataFile.isUnused()) {
purgeList.add(dataFile);
}
}
for (DataFile dataFile : purgeList) {
removeDataFile(dataFile);
}
}
private synchronized void removeDataFile(DataFile dataFile) throws IOException {
// Make sure we don't delete too much data.
if (dataFile == currentWriteFile || mark == null || dataFile.getDataFileId() >= mark.getDataFileId()) {
return;
}
accessorPool.disposeDataFileAccessors(dataFile);
fileMap.remove(dataFile.getDataFileId());
storeSize.addAndGet(-dataFile.getLength());
dataFile.unlink();
boolean result = dataFile.delete();
LOG.debug("discarding data file " + dataFile + (result ? "successful " : "failed"));
}
/**
* @return the maxFileLength
*/
public int getMaxFileLength() {
return maxFileLength;
}
/**
* @param maxFileLength the maxFileLength to set
*/
public void setMaxFileLength(int maxFileLength) {
this.maxFileLength = maxFileLength;
}
public String toString() {
return "DataManager:(" + filePrefix + ")";
}
public synchronized Location getMark() throws IllegalStateException {
return mark;
}
public synchronized Location getNextLocation(Location location) throws IOException, IllegalStateException {
Location cur = null;
while (true) {
if (cur == null) {
if (location == null) {
DataFile head = (DataFile)currentWriteFile.getHeadNode();
cur = new Location();
cur.setDataFileId(head.getDataFileId());
cur.setOffset(0);
// DataFileAccessor reader =
// accessorPool.openDataFileAccessor(head);
// try {
// if( !reader.readLocationDetailsAndValidate(cur) ) {
// return null;
// }
// } finally {
// accessorPool.closeDataFileAccessor(reader);
// }
} else {
// Set to the next offset..
cur = new Location(location);
cur.setOffset(cur.getOffset() + cur.getSize());
}
} else {
cur.setOffset(cur.getOffset() + cur.getSize());
}
DataFile dataFile = getDataFile(cur);
// Did it go into the next file??
if (dataFile.getLength() <= cur.getOffset()) {
dataFile = getNextDataFile(dataFile);
if (dataFile == null) {
return null;
} else {
cur.setDataFileId(dataFile.getDataFileId().intValue());
cur.setOffset(0);
}
}
// Load in location size and type.
DataFileAccessor reader = accessorPool.openDataFileAccessor(dataFile);
try {
reader.readLocationDetails(cur);
} finally {
accessorPool.closeDataFileAccessor(reader);
}
if (cur.getType() == 0) {
return null;
} else if (cur.getType() > 0) {
// Only return user records.
return cur;
}
}
}
public ByteSequence read(Location location) throws IOException, IllegalStateException {
DataFile dataFile = getDataFile(location);
DataFileAccessor reader = accessorPool.openDataFileAccessor(dataFile);
ByteSequence rc = null;
try {
rc = reader.readRecord(location);
} finally {
accessorPool.closeDataFileAccessor(reader);
}
return rc;
}
public void setMark(Location location, boolean sync) throws IOException, IllegalStateException {
synchronized (this) {
mark = location;
}
storeState(sync);
}
private synchronized void storeState(boolean sync) throws IOException {
ByteSequence state = marshallState();
appender.storeItem(state, Location.MARK_TYPE, sync);
controlFile.store(state, sync);
}
public synchronized Location write(ByteSequence data, boolean sync) throws IOException, IllegalStateException {
return appender.storeItem(data, Location.USER_TYPE, sync);
}
public synchronized Location write(ByteSequence data, byte type, boolean sync) throws IOException, IllegalStateException {
return appender.storeItem(data, type, sync);
}
public void update(Location location, ByteSequence data, boolean sync) throws IOException {
DataFile dataFile = getDataFile(location);
DataFileAccessor updater = accessorPool.openDataFileAccessor(dataFile);
try {
updater.updateRecord(location, data, sync);
} finally {
accessorPool.closeDataFileAccessor(updater);
}
}
public File getDirectory() {
return directory;
}
public void setDirectory(File directory) {
this.directory = directory;
}
public String getFilePrefix() {
return filePrefix;
}
public void setFilePrefix(String filePrefix) {
this.filePrefix = filePrefix;
}
public Map<WriteKey, WriteCommand> getInflightWrites() {
return inflightWrites;
}
public Location getLastAppendLocation() {
return lastAppendLocation.get();
}
public void setLastAppendLocation(Location lastSyncedLocation) {
this.lastAppendLocation.set(lastSyncedLocation);
}
}
| false | true | public synchronized void start() throws IOException {
if (started) {
return;
}
started = true;
directory.mkdirs();
synchronized (this) {
controlFile = new ControlFile(new File(directory, filePrefix + "control"), CONTROL_RECORD_MAX_LENGTH);
controlFile.lock();
}
ByteSequence sequence = controlFile.load();
if (sequence != null && sequence.getLength() > 0) {
unmarshallState(sequence);
}
if (useNio) {
appender = new NIODataFileAppender(this);
} else {
appender = new DataFileAppender(this);
}
File[] files = directory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String n) {
return dir.equals(directory) && n.startsWith(filePrefix);
}
});
if (files != null) {
for (int i = 0; i < files.length; i++) {
try {
File file = files[i];
String n = file.getName();
String numStr = n.substring(filePrefix.length(), n.length());
int num = Integer.parseInt(numStr);
DataFile dataFile = new DataFile(file, num, preferedFileLength);
fileMap.put(dataFile.getDataFileId(), dataFile);
storeSize.addAndGet(dataFile.getLength());
} catch (NumberFormatException e) {
// Ignore file that do not match the pattern.
}
}
// Sort the list so that we can link the DataFiles together in the
// right order.
List<DataFile> l = new ArrayList<DataFile>(fileMap.values());
Collections.sort(l);
currentWriteFile = null;
for (DataFile df : l) {
if (currentWriteFile != null) {
currentWriteFile.linkAfter(df);
}
currentWriteFile = df;
}
}
// Need to check the current Write File to see if there was a partial
// write to it.
if (currentWriteFile != null) {
// See if the lastSyncedLocation is valid..
Location l = lastAppendLocation.get();
if (l != null && l.getDataFileId() != currentWriteFile.getDataFileId().intValue()) {
l = null;
}
// If we know the last location that was ok.. then we can skip lots
// of checking
l = recoveryCheck(currentWriteFile, l);
lastAppendLocation.set(l);
}
storeState(false);
cleanupTask = new Runnable() {
public void run() {
cleanup();
}
};
Scheduler.executePeriodically(cleanupTask, 1000 * 30);
}
| public synchronized void start() throws IOException {
if (started) {
return;
}
started = true;
directory.mkdirs();
synchronized (this) {
controlFile = new ControlFile(new File(directory, filePrefix + "control"), CONTROL_RECORD_MAX_LENGTH);
controlFile.lock();
}
ByteSequence sequence = controlFile.load();
if (sequence != null && sequence.getLength() > 0) {
unmarshallState(sequence);
}
if (useNio) {
appender = new NIODataFileAppender(this);
} else {
appender = new DataFileAppender(this);
}
File[] files = directory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String n) {
return dir.equals(directory) && n.startsWith(filePrefix);
}
});
if (files != null) {
for (int i = 0; i < files.length; i++) {
try {
File file = files[i];
String n = file.getName();
String numStr = n.substring(filePrefix.length(), n.length());
int num = Integer.parseInt(numStr);
DataFile dataFile = new DataFile(file, num, preferedFileLength);
fileMap.put(dataFile.getDataFileId(), dataFile);
storeSize.addAndGet(dataFile.getLength());
} catch (NumberFormatException e) {
// Ignore file that do not match the pattern.
}
}
// Sort the list so that we can link the DataFiles together in the
// right order.
List<DataFile> l = new ArrayList<DataFile>(fileMap.values());
Collections.sort(l);
currentWriteFile = null;
for (DataFile df : l) {
if (currentWriteFile != null) {
currentWriteFile.linkAfter(df);
}
currentWriteFile = df;
}
}
// Need to check the current Write File to see if there was a partial
// write to it.
if (currentWriteFile != null) {
// See if the lastSyncedLocation is valid..
Location l = lastAppendLocation.get();
if (l != null && l.getDataFileId() != currentWriteFile.getDataFileId().intValue()) {
l = null;
}
// If we know the last location that was ok.. then we can skip lots
// of checking
try{
l = recoveryCheck(currentWriteFile, l);
lastAppendLocation.set(l);
}catch(IOException e){
LOG.warn("recovery check failed", e);
}
}
storeState(false);
cleanupTask = new Runnable() {
public void run() {
cleanup();
}
};
Scheduler.executePeriodically(cleanupTask, 1000 * 30);
}
|
diff --git a/src/main/java/ch/entwine/weblounge/workbench/WorkbenchService.java b/src/main/java/ch/entwine/weblounge/workbench/WorkbenchService.java
index a01a335d8..dc6113fa3 100644
--- a/src/main/java/ch/entwine/weblounge/workbench/WorkbenchService.java
+++ b/src/main/java/ch/entwine/weblounge/workbench/WorkbenchService.java
@@ -1,415 +1,415 @@
/*
* Weblounge: Web Content Management System
* Copyright (c) 2003 - 2011 The Weblounge Team
* http://entwinemedia.com/weblounge
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package ch.entwine.weblounge.workbench;
import ch.entwine.weblounge.common.content.ResourceURI;
import ch.entwine.weblounge.common.content.SearchQuery;
import ch.entwine.weblounge.common.content.page.Composer;
import ch.entwine.weblounge.common.content.page.Page;
import ch.entwine.weblounge.common.content.page.Pagelet;
import ch.entwine.weblounge.common.content.repository.ContentRepository;
import ch.entwine.weblounge.common.content.repository.ContentRepositoryException;
import ch.entwine.weblounge.common.impl.content.SearchQueryImpl;
import ch.entwine.weblounge.common.impl.testing.MockHttpServletRequest;
import ch.entwine.weblounge.common.impl.testing.MockHttpServletResponse;
import ch.entwine.weblounge.common.impl.url.UrlUtils;
import ch.entwine.weblounge.common.request.WebloungeRequest;
import ch.entwine.weblounge.common.site.Site;
import ch.entwine.weblounge.workbench.suggest.PageSuggestion;
import ch.entwine.weblounge.workbench.suggest.SubjectSuggestion;
import ch.entwine.weblounge.workbench.suggest.UserSuggestion;
import org.apache.commons.io.IOUtils;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Filter;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import org.osgi.util.tracker.ServiceTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
/**
* Implementation of a weblounge workbench. The workbench provides support for
* management applications and the page editor.
*/
public class WorkbenchService {
/** The logging facility */
private static Logger logger = LoggerFactory.getLogger(WorkbenchService.class);
/** The site servlets */
private static Map<String, Servlet> siteServlets = new HashMap<String, Servlet>();
/** The cache service tracker */
private ServiceTracker siteServletTracker = null;
/** Filter expression used to look up site servlets */
private static final String serviceFilter = "(&(objectclass=" + Servlet.class.getName() + ")(" + Site.class.getName().toLowerCase() + "=*))";
/**
* Callback from OSGi declarative services on component startup.
*
* @param ctx
* the component context
*/
void activate(ComponentContext ctx) {
try {
Filter filter = ctx.getBundleContext().createFilter(serviceFilter);
siteServletTracker = new SiteServletTracker(ctx.getBundleContext(), filter);
siteServletTracker.open();
} catch (InvalidSyntaxException e) {
throw new IllegalStateException(e);
}
}
/**
* Callback from OSGi declarative services on component shutdown.
*/
void deactivate() {
if (siteServletTracker != null) {
siteServletTracker.close();
}
}
/**
* Returns a list of users From the given site that are suggested based on
* what is passed in as <code>text</code>. If <code>limit</code> is
*
* @param site
* the site
* @param text
* the starting test
* @param limit
* the maximum number of users to return
* @return the list of suggested users
* @throws IllegalStateException
* if the content repository is not available
* @throws ContentRepositoryException
* if querying fails
*/
public List<UserSuggestion> suggestUsers(Site site, String text, int limit)
throws IllegalStateException {
List<UserSuggestion> users = new ArrayList<UserSuggestion>();
SearchQuery search = new SearchQueryImpl(site);
// search.withUser(text + "*");
// search.withUserFacet();
// Get hold of the site's content repository
ContentRepository contentRepository = site.getContentRepository();
if (contentRepository == null) {
logger.warn("No content repository found for site '{}'", site);
return null;
}
// TODO: implement search
return users;
}
/**
* Returns a list of tags from the given site that are suggested based on what
* is passed in as <code>text</code>. If <code>limit</code> is larger than
* <code>0</code>, then this is the maximum number of facet values returned.
*
* @param site
* the site
* @param text
* the starting test
* @param limit
* the maximum number of tags to return
* @return the list of suggested tags
* @throws IllegalStateException
* if the content repository is not available
* @throws ContentRepositoryException
* if querying fails
*/
public List<SubjectSuggestion> suggestTags(Site site, String text, int limit)
throws IllegalStateException {
List<SubjectSuggestion> tags = new ArrayList<SubjectSuggestion>();
SearchQuery search = new SearchQueryImpl(site);
search.withSubject(text + "*");
search.withSubjectFacet();
// Get hold of the site's content repository
ContentRepository contentRepository = site.getContentRepository();
if (contentRepository == null) {
throw new IllegalStateException("No content repository found for site '" + site + "'");
}
return tags;
}
/**
* Returns a list of pages from the given site that are suggested based on
* what is passed in as <code>text</code>. If <code>limit</code> is
*
* @param site
* the site
* @param text
* the starting test
* @param limit
* the maximum number of pages to return
* @return the list of suggested pages
* @throws IllegalStateException
* if the content repository is not available
* @throws ContentRepositoryException
* if querying fails
*/
public List<PageSuggestion> suggestPages(Site site, String text, int limit)
throws IllegalStateException {
List<PageSuggestion> pages = new ArrayList<PageSuggestion>();
SearchQuery search = new SearchQueryImpl(site);
// search.withPage(text + "*");
// search.withPageFacet();
// TODO: implement search
return pages;
}
/**
* Returns the pagelet editor or <code>null</code> if either one of the page,
* the composer or the is not available.
*
* @param site
* the site
* @param pageURI
* the page uri
* @param composerId
* the composer id
* @param pageletIndex
* the pagelet index
* @return the pagelet editor
* @throws IOException
* if reading the pagelet fails
*/
public PageletEditor getEditor(Site site, ResourceURI pageURI,
String composerId, int pageletIndex) throws IOException {
if (site == null)
throw new IllegalArgumentException("Site must not be null");
if (composerId == null)
throw new IllegalArgumentException("Composer must not be null");
if (pageletIndex < 0)
throw new IllegalArgumentException("Pagelet index must be a positive integer");
// Get hold of the site's content repository
ContentRepository contentRepository = site.getContentRepository();
if (contentRepository == null) {
logger.warn("No content repository found for site '{}'", site);
return null;
}
// Load the page
Page page = null;
try {
page = (Page) contentRepository.get(pageURI);
if (page == null) {
logger.warn("Client requested pagelet editor for non existing page {}", pageURI);
return null;
}
} catch (ContentRepositoryException e) {
logger.error("Error trying to access content repository {}: {}", contentRepository, e);
return null;
}
// Load the composer
Composer composer = page.getComposer(composerId);
if (composer == null) {
logger.warn("Client requested pagelet editor for non existing composer {} on page {}", composerId, pageURI);
return null;
}
// Get the pagelet
- if (composer.getPagelets().length < pageletIndex || composer.size() < pageletIndex) {
+ if (composer.getPagelets().length <= pageletIndex || composer.size() <= pageletIndex) {
logger.warn("Client requested pagelet editor for non existing pagelet on page {}", pageURI);
return null;
}
Pagelet pagelet = composer.getPagelet(pageletIndex);
pagelet = new TrimpathPageletWrapper(pagelet);
PageletEditor pageletEditor = new PageletEditor(pagelet, pageURI, composerId, pageletIndex);
// Load the contents of the renderer url
URL rendererURL = pageletEditor.getRenderer();
if (rendererURL != null) {
String rendererContent = null;
try {
rendererContent = loadContents(rendererURL, site, page, composer, pagelet);
pageletEditor.setRenderer(rendererContent);
} catch (ServletException e) {
logger.warn("Error processing the pagelet renderer at {}: {}", rendererURL, e.getMessage());
}
}
// Load the contents of the editor url
URL editorURL = pageletEditor.getEditorURL();
if (editorURL != null) {
String rendererContent = null;
try {
rendererContent = loadContents(editorURL, site, page, composer, pagelet);
pageletEditor.setEditor(rendererContent);
} catch (ServletException e) {
logger.warn("Error processing the pagelet renderer at {}: {}", editorURL, e.getMessage());
}
}
return pageletEditor;
}
/**
* Asks the site servlet to render the given url using the page, composer and
* pagelet as the rendering environment. If the no servlet is available for
* the given site, the contents are loaded from the url directly.
*
* @param rendererURL
* the renderer url
* @param site
* the site
* @param page
* the page
* @param composer
* the composer
* @param pagelet
* the pagelet
* @return the servlet response, serialized to a string
* @throws IOException
* if the servlet fails to create the response
* @throws ServletException
* if an exception occurs while processing
*/
private String loadContents(URL rendererURL, Site site, Page page,
Composer composer, Pagelet pagelet) throws IOException, ServletException {
Servlet servlet = siteServlets.get(site.getIdentifier());
String httpContextURI = UrlUtils.concat("/weblounge-sites", site.getIdentifier());
int httpContextURILength = httpContextURI.length();
String url = rendererURL.toExternalForm();
int uriInPath = url.indexOf(httpContextURI);
if (uriInPath > 0) {
String pathInfo = url.substring(uriInPath + httpContextURILength);
// Prepare the mock request
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
request.setLocalAddr(site.getURL().toExternalForm());
request.setAttribute(WebloungeRequest.PAGE, page);
request.setAttribute(WebloungeRequest.COMPOSER, composer);
request.setAttribute(WebloungeRequest.PAGELET, pagelet);
request.setPathInfo(pathInfo);
request.setRequestURI(UrlUtils.concat(httpContextURI, pathInfo));
MockHttpServletResponse response = new MockHttpServletResponse();
servlet.service(request, response);
return response.getContentAsString();
} else {
InputStream is = null;
try {
is = rendererURL.openStream();
return IOUtils.toString(is, "utf-8");
} finally {
IOUtils.closeQuietly(is);
}
}
}
/**
* Adds the site servlet to the list of servlets.
*
* @param id
* the site identifier
* @param servlet
* the site servlet
*/
void addSiteServlet(String id, Servlet servlet) {
logger.debug("Site servlet attached to {} workbench", id);
siteServlets.put(id, servlet);
}
/**
* Removes the site servlet from the list of servlets
*
* @param site
* the site identifier
*/
void removeSiteServlet(String id) {
logger.debug("Site servlet detached from {} workbench", id);
siteServlets.remove(id);
}
/**
* Implementation of a <code>ServiceTracker</code> that is tracking instances
* of type {@link Servlet} with an associated <code>site</code> attribute.
*/
private class SiteServletTracker extends ServiceTracker {
/**
* Creates a new servlet tracker that is using the given bundle context to
* look up service instances.
*
* @param ctx
* the bundle context
* @param filter
* the service filter
*/
SiteServletTracker(BundleContext ctx, Filter filter) {
super(ctx, filter, null);
}
/**
* {@inheritDoc}
*
* @see org.osgi.util.tracker.ServiceTracker#addingService(org.osgi.framework.ServiceReference)
*/
@Override
public Object addingService(ServiceReference reference) {
Servlet servlet = (Servlet) super.addingService(reference);
String site = (String) reference.getProperty(Site.class.getName().toLowerCase());
addSiteServlet(site, servlet);
return servlet;
}
/**
* {@inheritDoc}
*
* @see org.osgi.util.tracker.ServiceTracker#removedService(org.osgi.framework.ServiceReference,
* java.lang.Object)
*/
@Override
public void removedService(ServiceReference reference, Object service) {
String site = (String) reference.getProperty("site");
removeSiteServlet(site);
}
}
}
| true | true | public PageletEditor getEditor(Site site, ResourceURI pageURI,
String composerId, int pageletIndex) throws IOException {
if (site == null)
throw new IllegalArgumentException("Site must not be null");
if (composerId == null)
throw new IllegalArgumentException("Composer must not be null");
if (pageletIndex < 0)
throw new IllegalArgumentException("Pagelet index must be a positive integer");
// Get hold of the site's content repository
ContentRepository contentRepository = site.getContentRepository();
if (contentRepository == null) {
logger.warn("No content repository found for site '{}'", site);
return null;
}
// Load the page
Page page = null;
try {
page = (Page) contentRepository.get(pageURI);
if (page == null) {
logger.warn("Client requested pagelet editor for non existing page {}", pageURI);
return null;
}
} catch (ContentRepositoryException e) {
logger.error("Error trying to access content repository {}: {}", contentRepository, e);
return null;
}
// Load the composer
Composer composer = page.getComposer(composerId);
if (composer == null) {
logger.warn("Client requested pagelet editor for non existing composer {} on page {}", composerId, pageURI);
return null;
}
// Get the pagelet
if (composer.getPagelets().length < pageletIndex || composer.size() < pageletIndex) {
logger.warn("Client requested pagelet editor for non existing pagelet on page {}", pageURI);
return null;
}
Pagelet pagelet = composer.getPagelet(pageletIndex);
pagelet = new TrimpathPageletWrapper(pagelet);
PageletEditor pageletEditor = new PageletEditor(pagelet, pageURI, composerId, pageletIndex);
// Load the contents of the renderer url
URL rendererURL = pageletEditor.getRenderer();
if (rendererURL != null) {
String rendererContent = null;
try {
rendererContent = loadContents(rendererURL, site, page, composer, pagelet);
pageletEditor.setRenderer(rendererContent);
} catch (ServletException e) {
logger.warn("Error processing the pagelet renderer at {}: {}", rendererURL, e.getMessage());
}
}
// Load the contents of the editor url
URL editorURL = pageletEditor.getEditorURL();
if (editorURL != null) {
String rendererContent = null;
try {
rendererContent = loadContents(editorURL, site, page, composer, pagelet);
pageletEditor.setEditor(rendererContent);
} catch (ServletException e) {
logger.warn("Error processing the pagelet renderer at {}: {}", editorURL, e.getMessage());
}
}
return pageletEditor;
}
| public PageletEditor getEditor(Site site, ResourceURI pageURI,
String composerId, int pageletIndex) throws IOException {
if (site == null)
throw new IllegalArgumentException("Site must not be null");
if (composerId == null)
throw new IllegalArgumentException("Composer must not be null");
if (pageletIndex < 0)
throw new IllegalArgumentException("Pagelet index must be a positive integer");
// Get hold of the site's content repository
ContentRepository contentRepository = site.getContentRepository();
if (contentRepository == null) {
logger.warn("No content repository found for site '{}'", site);
return null;
}
// Load the page
Page page = null;
try {
page = (Page) contentRepository.get(pageURI);
if (page == null) {
logger.warn("Client requested pagelet editor for non existing page {}", pageURI);
return null;
}
} catch (ContentRepositoryException e) {
logger.error("Error trying to access content repository {}: {}", contentRepository, e);
return null;
}
// Load the composer
Composer composer = page.getComposer(composerId);
if (composer == null) {
logger.warn("Client requested pagelet editor for non existing composer {} on page {}", composerId, pageURI);
return null;
}
// Get the pagelet
if (composer.getPagelets().length <= pageletIndex || composer.size() <= pageletIndex) {
logger.warn("Client requested pagelet editor for non existing pagelet on page {}", pageURI);
return null;
}
Pagelet pagelet = composer.getPagelet(pageletIndex);
pagelet = new TrimpathPageletWrapper(pagelet);
PageletEditor pageletEditor = new PageletEditor(pagelet, pageURI, composerId, pageletIndex);
// Load the contents of the renderer url
URL rendererURL = pageletEditor.getRenderer();
if (rendererURL != null) {
String rendererContent = null;
try {
rendererContent = loadContents(rendererURL, site, page, composer, pagelet);
pageletEditor.setRenderer(rendererContent);
} catch (ServletException e) {
logger.warn("Error processing the pagelet renderer at {}: {}", rendererURL, e.getMessage());
}
}
// Load the contents of the editor url
URL editorURL = pageletEditor.getEditorURL();
if (editorURL != null) {
String rendererContent = null;
try {
rendererContent = loadContents(editorURL, site, page, composer, pagelet);
pageletEditor.setEditor(rendererContent);
} catch (ServletException e) {
logger.warn("Error processing the pagelet renderer at {}: {}", editorURL, e.getMessage());
}
}
return pageletEditor;
}
|
diff --git a/src/java/org/lwjgl/MacOSXSysImplementation.java b/src/java/org/lwjgl/MacOSXSysImplementation.java
index b7084e7d..53f277ae 100644
--- a/src/java/org/lwjgl/MacOSXSysImplementation.java
+++ b/src/java/org/lwjgl/MacOSXSysImplementation.java
@@ -1,96 +1,96 @@
/*
* Copyright (c) 2002-2004 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
/**
* $Id$
*
* @author elias_naur <[email protected]>
* @version $Revision$
*/
class MacOSXSysImplementation extends J2SESysImplementation {
public String[] getNativeLibraryNames() {
/* If we're on 10.4, fine, we'll just try the default library name. For
* earlier versions of Mac OS X, try the legacy library first.
*
* Having a kludge like this is unfortunate, but necessary for the following reasons:
* 1. We need two libraries to support Mac OS X 10.2, 10.3 and 10.4. We could
* cover 10.2, 10.3 and 10.4 with one gcc 3 compiled library, but then we
* loose intel mac support. Instead, we'll distribute two versions of the lwjgl
* native library, the default and a legacy one.
* 2. The default library will be universal ('fat') with both intel and powerpc support
* compiled in. This requires gcc 4, and makes the library unusable on Mac OS X 10.3
* and earlier (actually 10.3.9 has the required gcc 4 libraries, but we'll ignore that).
* We could still choose to load the default library first, and the legacy one later,
* but a bug in the Mac OS X java implementation forces a java program to exit
* if the loaded library has a missing dependency (The correct behaviour is to throw
* an UnsatisfiedLinkError, like on linux and windows).
* 3. If the LWJGL program is launched with an intelligent ClassLoader, this issue can be avoided
* altogether, and the legacy library naming can be avoided too. For example, when
* using webstart, one can supply two nativelib references, one for Mac OS X 10.4
* (the default library), and one for earlier Mac OS X (the legacy library). This is the
* preferred way to deploy the libraries. The legacy naming is for the users that don't want to
- * mess around with libraries and classloaders. They can simply supply make sure that lwjgl.jar
+ * mess around with libraries and classloaders. They can simply make sure that lwjgl.jar
* is in the classpath and that both the default library and the legacy library is in the native
* library path (java.library.path).
*/
if (LWJGLUtil.isMacOSXEqualsOrBetterThan(10, 4))
return super.getNativeLibraryNames();
else
return new String[]{LIBRARY_NAME + "-legacy", LIBRARY_NAME};
}
public boolean openURL(String url) {
try {
Method openURL_method = (Method)AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws Exception {
try {
Class com_apple_eio_FileManager = Class.forName("com.apple.eio.FileManager");
return com_apple_eio_FileManager.getMethod("openURL", new Class[]{String.class});
} catch (Exception e) {
LWJGLUtil.log("Exception occurred while trying to invoke browser: " + e);
return null;
}
}
});
openURL_method.invoke(null, new Object[]{url});
return true;
} catch (Exception e) {
LWJGLUtil.log("Exception occurred while trying to invoke browser: " + e);
return false;
}
}
}
| true | true | public String[] getNativeLibraryNames() {
/* If we're on 10.4, fine, we'll just try the default library name. For
* earlier versions of Mac OS X, try the legacy library first.
*
* Having a kludge like this is unfortunate, but necessary for the following reasons:
* 1. We need two libraries to support Mac OS X 10.2, 10.3 and 10.4. We could
* cover 10.2, 10.3 and 10.4 with one gcc 3 compiled library, but then we
* loose intel mac support. Instead, we'll distribute two versions of the lwjgl
* native library, the default and a legacy one.
* 2. The default library will be universal ('fat') with both intel and powerpc support
* compiled in. This requires gcc 4, and makes the library unusable on Mac OS X 10.3
* and earlier (actually 10.3.9 has the required gcc 4 libraries, but we'll ignore that).
* We could still choose to load the default library first, and the legacy one later,
* but a bug in the Mac OS X java implementation forces a java program to exit
* if the loaded library has a missing dependency (The correct behaviour is to throw
* an UnsatisfiedLinkError, like on linux and windows).
* 3. If the LWJGL program is launched with an intelligent ClassLoader, this issue can be avoided
* altogether, and the legacy library naming can be avoided too. For example, when
* using webstart, one can supply two nativelib references, one for Mac OS X 10.4
* (the default library), and one for earlier Mac OS X (the legacy library). This is the
* preferred way to deploy the libraries. The legacy naming is for the users that don't want to
* mess around with libraries and classloaders. They can simply supply make sure that lwjgl.jar
* is in the classpath and that both the default library and the legacy library is in the native
* library path (java.library.path).
*/
if (LWJGLUtil.isMacOSXEqualsOrBetterThan(10, 4))
return super.getNativeLibraryNames();
else
return new String[]{LIBRARY_NAME + "-legacy", LIBRARY_NAME};
}
| public String[] getNativeLibraryNames() {
/* If we're on 10.4, fine, we'll just try the default library name. For
* earlier versions of Mac OS X, try the legacy library first.
*
* Having a kludge like this is unfortunate, but necessary for the following reasons:
* 1. We need two libraries to support Mac OS X 10.2, 10.3 and 10.4. We could
* cover 10.2, 10.3 and 10.4 with one gcc 3 compiled library, but then we
* loose intel mac support. Instead, we'll distribute two versions of the lwjgl
* native library, the default and a legacy one.
* 2. The default library will be universal ('fat') with both intel and powerpc support
* compiled in. This requires gcc 4, and makes the library unusable on Mac OS X 10.3
* and earlier (actually 10.3.9 has the required gcc 4 libraries, but we'll ignore that).
* We could still choose to load the default library first, and the legacy one later,
* but a bug in the Mac OS X java implementation forces a java program to exit
* if the loaded library has a missing dependency (The correct behaviour is to throw
* an UnsatisfiedLinkError, like on linux and windows).
* 3. If the LWJGL program is launched with an intelligent ClassLoader, this issue can be avoided
* altogether, and the legacy library naming can be avoided too. For example, when
* using webstart, one can supply two nativelib references, one for Mac OS X 10.4
* (the default library), and one for earlier Mac OS X (the legacy library). This is the
* preferred way to deploy the libraries. The legacy naming is for the users that don't want to
* mess around with libraries and classloaders. They can simply make sure that lwjgl.jar
* is in the classpath and that both the default library and the legacy library is in the native
* library path (java.library.path).
*/
if (LWJGLUtil.isMacOSXEqualsOrBetterThan(10, 4))
return super.getNativeLibraryNames();
else
return new String[]{LIBRARY_NAME + "-legacy", LIBRARY_NAME};
}
|
diff --git a/src/InstructionState.java b/src/InstructionState.java
index 3cf1f05..212f5e2 100644
--- a/src/InstructionState.java
+++ b/src/InstructionState.java
@@ -1,118 +1,118 @@
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/**
* A class that implements the state where instructions are displayed
*/
public class InstructionState extends BasicGameState {
/** Instructions Menu */
private Menu instructionsMenu;
/** Instructions state ID */
private int stateID;
/** Starting menu x-position */
private int startingX = 500;
/** Starting menu y-position */
private int startingY = 470;
/** The space between Menu items */
private int spaceBetweenItems = 131;
/** Location of graphic when quit button is selected */
private final String menuSelected = "res/menu/MenuSelected.png";
/** Location of graphic when quit button is unselected */
private final String menuUnselected = "res/menu/MenuUnselected.png";
/** Image object of graphic when quit button is selected */
private Image backUs;
/** Image object of graphic when quit button is selected */
private Image backS;
/** background image */
private Image instructionList;
/** Location of background */
private final String instructions = "res/menu/Instructions.png";
/**
* Sets instruction state ID
* @param stateID
*/
InstructionState(int stateID) {
super();
this.stateID = stateID;
}
/**
* Sets the game container and state based game
* @param gc
* @param sbg
*/
public void init(GameContainer gc, StateBasedGame sbg) {
initMenu(gc, sbg);
}
/**
* Draws the instructions for the game
* @param gc
* @param sbg
* @param g
* @throws SlickException
*/
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(instructionList, 0, 0);
instructionsMenu.render(gc, g);
}
/**
* Update the game container and state based game
* @param gc
* @param sbg
* @param i
* @throws SlickException
*/
@Override
public void update(GameContainer gc, StateBasedGame sbg, int i) throws SlickException {
}
/**
* Gets state ID
* @return
*/
@Override
public int getID() {
return stateID;
}
/**
* Initialized instructions menu with images
* @param gc
* @param sbg
*/
private void initMenu(GameContainer gc, StateBasedGame sbg) {
instructionsMenu = new Menu(startingX, startingY, spaceBetweenItems);
// create images for each button
try {
instructionList = new Image(instructions);
backUs = new Image(menuUnselected);
backS = new Image(menuSelected);
} catch (SlickException ex) {
ex.printStackTrace();
return;
}
- AnimatedButton play = new AnimatedButton(gc, sbg, backUs, backS, startingX, startingY, 0, sbg.getCurrentStateID());
+ AnimatedButton play = new AnimatedButton(gc, sbg, backUs, backS, startingX, startingY, 0, 2);
play.add(new ButtonAction() {
public void perform() {
/*currentState = STATES.PLAY;
sbg.enterState(GauchoRunner.PLAY_STATE_ID);*/
}
}
);
instructionsMenu.addItem(play);
}
}
| true | true | private void initMenu(GameContainer gc, StateBasedGame sbg) {
instructionsMenu = new Menu(startingX, startingY, spaceBetweenItems);
// create images for each button
try {
instructionList = new Image(instructions);
backUs = new Image(menuUnselected);
backS = new Image(menuSelected);
} catch (SlickException ex) {
ex.printStackTrace();
return;
}
AnimatedButton play = new AnimatedButton(gc, sbg, backUs, backS, startingX, startingY, 0, sbg.getCurrentStateID());
play.add(new ButtonAction() {
public void perform() {
/*currentState = STATES.PLAY;
sbg.enterState(GauchoRunner.PLAY_STATE_ID);*/
}
}
);
instructionsMenu.addItem(play);
}
| private void initMenu(GameContainer gc, StateBasedGame sbg) {
instructionsMenu = new Menu(startingX, startingY, spaceBetweenItems);
// create images for each button
try {
instructionList = new Image(instructions);
backUs = new Image(menuUnselected);
backS = new Image(menuSelected);
} catch (SlickException ex) {
ex.printStackTrace();
return;
}
AnimatedButton play = new AnimatedButton(gc, sbg, backUs, backS, startingX, startingY, 0, 2);
play.add(new ButtonAction() {
public void perform() {
/*currentState = STATES.PLAY;
sbg.enterState(GauchoRunner.PLAY_STATE_ID);*/
}
}
);
instructionsMenu.addItem(play);
}
|
diff --git a/org.eclipse.mylyn.discovery.ui/src/org/eclipse/mylyn/internal/discovery/ui/wizards/OverviewToolTip.java b/org.eclipse.mylyn.discovery.ui/src/org/eclipse/mylyn/internal/discovery/ui/wizards/OverviewToolTip.java
index 1920dd33..bba55a97 100644
--- a/org.eclipse.mylyn.discovery.ui/src/org/eclipse/mylyn/internal/discovery/ui/wizards/OverviewToolTip.java
+++ b/org.eclipse.mylyn.discovery.ui/src/org/eclipse/mylyn/internal/discovery/ui/wizards/OverviewToolTip.java
@@ -1,196 +1,197 @@
/*******************************************************************************
* Copyright (c) 2009 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.discovery.ui.wizards;
import java.net.URL;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.resource.ColorRegistry;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.window.ToolTip;
import org.eclipse.mylyn.internal.discovery.core.model.AbstractDiscoverySource;
import org.eclipse.mylyn.internal.discovery.core.model.Overview;
import org.eclipse.mylyn.internal.provisional.commons.ui.GradientToolTip;
import org.eclipse.mylyn.internal.provisional.commons.ui.WorkbenchUtil;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
/**
* @author David Green
*/
class OverviewToolTip extends GradientToolTip {
private static final String COLOR_BLACK = "black"; //$NON-NLS-1$
private final Overview overview;
private final AbstractDiscoverySource source;
private Color colorBlack;
public OverviewToolTip(Control control, AbstractDiscoverySource source, Overview overview) {
super(control, ToolTip.RECREATE, true);
if (source == null) {
throw new IllegalArgumentException();
}
if (overview == null) {
throw new IllegalArgumentException();
}
this.source = source;
this.overview = overview;
setHideOnMouseDown(false); // required for links to work
}
@Override
protected Composite createToolTipArea(Event event, final Composite parent) {
if (colorBlack == null) {
ColorRegistry colorRegistry = JFaceResources.getColorRegistry();
if (!colorRegistry.hasValueFor(COLOR_BLACK)) {
colorRegistry.put(COLOR_BLACK, new RGB(0, 0, 0));
}
colorBlack = colorRegistry.get(COLOR_BLACK);
}
GridLayoutFactory.fillDefaults().applyTo(parent);
Composite container = new Composite(parent, SWT.NULL);
container.setBackground(null);
Image image = null;
if (overview.getScreenshot() != null) {
image = computeImage(source, overview.getScreenshot());
if (image != null) {
final Image fimage = image;
container.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
fimage.dispose();
}
});
}
}
final boolean hasLearnMoreLink = overview.getUrl() != null && overview.getUrl().length() > 0;
final int borderWidth = 1;
final int fixedImageHeight = 240;
final int fixedImageWidth = 320;
final int heightHint = fixedImageHeight + (borderWidth * 2);
final int widthHint = fixedImageWidth;
final int containerWidthHintWithImage = 650;
final int containerWidthHintWithoutImage = 500;
GridDataFactory.fillDefaults().grab(true, true).hint(
image == null ? containerWidthHintWithoutImage : containerWidthHintWithImage, SWT.DEFAULT).applyTo(
container);
GridLayoutFactory.fillDefaults().numColumns(2).margins(5, 5).spacing(3, 0).applyTo(container);
String summary = overview.getSummary();
Composite summaryContainer = new Composite(container, SWT.NULL);
summaryContainer.setBackground(null);
GridLayoutFactory.fillDefaults().applyTo(summaryContainer);
- GridDataFactory gridDataFactory = GridDataFactory.fillDefaults().grab(true, false).span(image == null ? 2 : 1,
- 1);
+ GridDataFactory gridDataFactory = GridDataFactory.fillDefaults()
+ .grab(true, true)
+ .span(image == null ? 2 : 1, 1);
if (image != null) {
gridDataFactory.hint(widthHint, heightHint);
}
gridDataFactory.applyTo(summaryContainer);
Label summaryLabel = new Label(summaryContainer, SWT.WRAP);
summaryLabel.setText(summary);
summaryLabel.setBackground(null);
- GridDataFactory.fillDefaults().grab(true, false).align(SWT.BEGINNING, SWT.BEGINNING).applyTo(summaryLabel);
+ GridDataFactory.fillDefaults().grab(true, true).align(SWT.BEGINNING, SWT.BEGINNING).applyTo(summaryLabel);
if (image != null) {
final Composite imageContainer = new Composite(container, SWT.BORDER);
GridLayoutFactory.fillDefaults().applyTo(imageContainer);
GridDataFactory.fillDefaults().grab(false, false).align(SWT.CENTER, SWT.BEGINNING).hint(
widthHint + (borderWidth * 2), heightHint).applyTo(imageContainer);
Label imageLabel = new Label(imageContainer, SWT.NULL);
GridDataFactory.fillDefaults().hint(widthHint, fixedImageHeight).indent(borderWidth, borderWidth).applyTo(
imageLabel);
imageLabel.setImage(image);
imageLabel.setBackground(null);
imageLabel.setSize(widthHint, fixedImageHeight);
// creates a border
imageContainer.setBackground(colorBlack);
}
if (hasLearnMoreLink) {
Link link = new Link(summaryContainer, SWT.NULL);
GridDataFactory.fillDefaults().grab(false, false).align(SWT.BEGINNING, SWT.CENTER).applyTo(link);
link.setText(Messages.ConnectorDescriptorToolTip_detailsLink);
link.setBackground(null);
link.setToolTipText(NLS.bind(Messages.ConnectorDescriptorToolTip_detailsLink_tooltip, overview.getUrl()));
link.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
WorkbenchUtil.openUrl(overview.getUrl(), IWorkbenchBrowserSupport.AS_EXTERNAL);
}
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
}
if (image == null) {
// prevent overviews with no image from providing unlimited text.
Point optimalSize = summaryContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
if (optimalSize.y > (heightHint + 10)) {
((GridData) summaryContainer.getLayoutData()).heightHint = heightHint;
container.layout(true);
}
}
// hack: cause the tooltip to gain focus so that we can capture the escape key
// this must be done async since the tooltip is not yet visible.
Display.getCurrent().asyncExec(new Runnable() {
public void run() {
if (!parent.isDisposed()) {
parent.setFocus();
}
}
});
return container;
}
private Image computeImage(AbstractDiscoverySource discoverySource, String imagePath) {
URL resource = discoverySource.getResource(imagePath);
if (resource != null) {
ImageDescriptor descriptor = ImageDescriptor.createFromURL(resource);
Image image = descriptor.createImage();
return image;
}
return null;
}
}
| false | true | protected Composite createToolTipArea(Event event, final Composite parent) {
if (colorBlack == null) {
ColorRegistry colorRegistry = JFaceResources.getColorRegistry();
if (!colorRegistry.hasValueFor(COLOR_BLACK)) {
colorRegistry.put(COLOR_BLACK, new RGB(0, 0, 0));
}
colorBlack = colorRegistry.get(COLOR_BLACK);
}
GridLayoutFactory.fillDefaults().applyTo(parent);
Composite container = new Composite(parent, SWT.NULL);
container.setBackground(null);
Image image = null;
if (overview.getScreenshot() != null) {
image = computeImage(source, overview.getScreenshot());
if (image != null) {
final Image fimage = image;
container.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
fimage.dispose();
}
});
}
}
final boolean hasLearnMoreLink = overview.getUrl() != null && overview.getUrl().length() > 0;
final int borderWidth = 1;
final int fixedImageHeight = 240;
final int fixedImageWidth = 320;
final int heightHint = fixedImageHeight + (borderWidth * 2);
final int widthHint = fixedImageWidth;
final int containerWidthHintWithImage = 650;
final int containerWidthHintWithoutImage = 500;
GridDataFactory.fillDefaults().grab(true, true).hint(
image == null ? containerWidthHintWithoutImage : containerWidthHintWithImage, SWT.DEFAULT).applyTo(
container);
GridLayoutFactory.fillDefaults().numColumns(2).margins(5, 5).spacing(3, 0).applyTo(container);
String summary = overview.getSummary();
Composite summaryContainer = new Composite(container, SWT.NULL);
summaryContainer.setBackground(null);
GridLayoutFactory.fillDefaults().applyTo(summaryContainer);
GridDataFactory gridDataFactory = GridDataFactory.fillDefaults().grab(true, false).span(image == null ? 2 : 1,
1);
if (image != null) {
gridDataFactory.hint(widthHint, heightHint);
}
gridDataFactory.applyTo(summaryContainer);
Label summaryLabel = new Label(summaryContainer, SWT.WRAP);
summaryLabel.setText(summary);
summaryLabel.setBackground(null);
GridDataFactory.fillDefaults().grab(true, false).align(SWT.BEGINNING, SWT.BEGINNING).applyTo(summaryLabel);
if (image != null) {
final Composite imageContainer = new Composite(container, SWT.BORDER);
GridLayoutFactory.fillDefaults().applyTo(imageContainer);
GridDataFactory.fillDefaults().grab(false, false).align(SWT.CENTER, SWT.BEGINNING).hint(
widthHint + (borderWidth * 2), heightHint).applyTo(imageContainer);
Label imageLabel = new Label(imageContainer, SWT.NULL);
GridDataFactory.fillDefaults().hint(widthHint, fixedImageHeight).indent(borderWidth, borderWidth).applyTo(
imageLabel);
imageLabel.setImage(image);
imageLabel.setBackground(null);
imageLabel.setSize(widthHint, fixedImageHeight);
// creates a border
imageContainer.setBackground(colorBlack);
}
if (hasLearnMoreLink) {
Link link = new Link(summaryContainer, SWT.NULL);
GridDataFactory.fillDefaults().grab(false, false).align(SWT.BEGINNING, SWT.CENTER).applyTo(link);
link.setText(Messages.ConnectorDescriptorToolTip_detailsLink);
link.setBackground(null);
link.setToolTipText(NLS.bind(Messages.ConnectorDescriptorToolTip_detailsLink_tooltip, overview.getUrl()));
link.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
WorkbenchUtil.openUrl(overview.getUrl(), IWorkbenchBrowserSupport.AS_EXTERNAL);
}
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
}
if (image == null) {
// prevent overviews with no image from providing unlimited text.
Point optimalSize = summaryContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
if (optimalSize.y > (heightHint + 10)) {
((GridData) summaryContainer.getLayoutData()).heightHint = heightHint;
container.layout(true);
}
}
// hack: cause the tooltip to gain focus so that we can capture the escape key
// this must be done async since the tooltip is not yet visible.
Display.getCurrent().asyncExec(new Runnable() {
public void run() {
if (!parent.isDisposed()) {
parent.setFocus();
}
}
});
return container;
}
| protected Composite createToolTipArea(Event event, final Composite parent) {
if (colorBlack == null) {
ColorRegistry colorRegistry = JFaceResources.getColorRegistry();
if (!colorRegistry.hasValueFor(COLOR_BLACK)) {
colorRegistry.put(COLOR_BLACK, new RGB(0, 0, 0));
}
colorBlack = colorRegistry.get(COLOR_BLACK);
}
GridLayoutFactory.fillDefaults().applyTo(parent);
Composite container = new Composite(parent, SWT.NULL);
container.setBackground(null);
Image image = null;
if (overview.getScreenshot() != null) {
image = computeImage(source, overview.getScreenshot());
if (image != null) {
final Image fimage = image;
container.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
fimage.dispose();
}
});
}
}
final boolean hasLearnMoreLink = overview.getUrl() != null && overview.getUrl().length() > 0;
final int borderWidth = 1;
final int fixedImageHeight = 240;
final int fixedImageWidth = 320;
final int heightHint = fixedImageHeight + (borderWidth * 2);
final int widthHint = fixedImageWidth;
final int containerWidthHintWithImage = 650;
final int containerWidthHintWithoutImage = 500;
GridDataFactory.fillDefaults().grab(true, true).hint(
image == null ? containerWidthHintWithoutImage : containerWidthHintWithImage, SWT.DEFAULT).applyTo(
container);
GridLayoutFactory.fillDefaults().numColumns(2).margins(5, 5).spacing(3, 0).applyTo(container);
String summary = overview.getSummary();
Composite summaryContainer = new Composite(container, SWT.NULL);
summaryContainer.setBackground(null);
GridLayoutFactory.fillDefaults().applyTo(summaryContainer);
GridDataFactory gridDataFactory = GridDataFactory.fillDefaults()
.grab(true, true)
.span(image == null ? 2 : 1, 1);
if (image != null) {
gridDataFactory.hint(widthHint, heightHint);
}
gridDataFactory.applyTo(summaryContainer);
Label summaryLabel = new Label(summaryContainer, SWT.WRAP);
summaryLabel.setText(summary);
summaryLabel.setBackground(null);
GridDataFactory.fillDefaults().grab(true, true).align(SWT.BEGINNING, SWT.BEGINNING).applyTo(summaryLabel);
if (image != null) {
final Composite imageContainer = new Composite(container, SWT.BORDER);
GridLayoutFactory.fillDefaults().applyTo(imageContainer);
GridDataFactory.fillDefaults().grab(false, false).align(SWT.CENTER, SWT.BEGINNING).hint(
widthHint + (borderWidth * 2), heightHint).applyTo(imageContainer);
Label imageLabel = new Label(imageContainer, SWT.NULL);
GridDataFactory.fillDefaults().hint(widthHint, fixedImageHeight).indent(borderWidth, borderWidth).applyTo(
imageLabel);
imageLabel.setImage(image);
imageLabel.setBackground(null);
imageLabel.setSize(widthHint, fixedImageHeight);
// creates a border
imageContainer.setBackground(colorBlack);
}
if (hasLearnMoreLink) {
Link link = new Link(summaryContainer, SWT.NULL);
GridDataFactory.fillDefaults().grab(false, false).align(SWT.BEGINNING, SWT.CENTER).applyTo(link);
link.setText(Messages.ConnectorDescriptorToolTip_detailsLink);
link.setBackground(null);
link.setToolTipText(NLS.bind(Messages.ConnectorDescriptorToolTip_detailsLink_tooltip, overview.getUrl()));
link.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
WorkbenchUtil.openUrl(overview.getUrl(), IWorkbenchBrowserSupport.AS_EXTERNAL);
}
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
}
if (image == null) {
// prevent overviews with no image from providing unlimited text.
Point optimalSize = summaryContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
if (optimalSize.y > (heightHint + 10)) {
((GridData) summaryContainer.getLayoutData()).heightHint = heightHint;
container.layout(true);
}
}
// hack: cause the tooltip to gain focus so that we can capture the escape key
// this must be done async since the tooltip is not yet visible.
Display.getCurrent().asyncExec(new Runnable() {
public void run() {
if (!parent.isDisposed()) {
parent.setFocus();
}
}
});
return container;
}
|
diff --git a/src/main/java/com/metaweb/gridworks/operations/RowFlagOperation.java b/src/main/java/com/metaweb/gridworks/operations/RowFlagOperation.java
index 9a05b7a5..c9c425d7 100644
--- a/src/main/java/com/metaweb/gridworks/operations/RowFlagOperation.java
+++ b/src/main/java/com/metaweb/gridworks/operations/RowFlagOperation.java
@@ -1,90 +1,90 @@
package com.metaweb.gridworks.operations;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONWriter;
import com.metaweb.gridworks.browsing.Engine;
import com.metaweb.gridworks.browsing.FilteredRows;
import com.metaweb.gridworks.browsing.RowVisitor;
import com.metaweb.gridworks.history.Change;
import com.metaweb.gridworks.history.HistoryEntry;
import com.metaweb.gridworks.model.AbstractOperation;
import com.metaweb.gridworks.model.Project;
import com.metaweb.gridworks.model.Row;
import com.metaweb.gridworks.model.changes.MassChange;
import com.metaweb.gridworks.model.changes.RowFlagChange;
public class RowFlagOperation extends EngineDependentOperation {
final protected boolean _flagged;
static public AbstractOperation reconstruct(Project project, JSONObject obj) throws Exception {
JSONObject engineConfig = obj.getJSONObject("engineConfig");
boolean flagged = obj.getBoolean("flagged");
return new RowFlagOperation(
engineConfig,
flagged
);
}
public RowFlagOperation(JSONObject engineConfig, boolean flagged) {
super(engineConfig);
_flagged = flagged;
}
public void write(JSONWriter writer, Properties options)
throws JSONException {
writer.object();
writer.key("op"); writer.value(OperationRegistry.s_opClassToName.get(this.getClass()));
writer.key("description"); writer.value(getBriefDescription(null));
writer.key("engineConfig"); writer.value(getEngineConfig());
writer.key("flagged"); writer.value(_flagged);
writer.endObject();
}
protected String getBriefDescription(Project project) {
return (_flagged ? "Flag rows" : "Unflag rows");
}
protected HistoryEntry createHistoryEntry(Project project) throws Exception {
Engine engine = createEngine(project);
List<Change> changes = new ArrayList<Change>(project.rows.size());
FilteredRows filteredRows = engine.getAllFilteredRows(false);
filteredRows.accept(project, createRowVisitor(project, changes));
return new HistoryEntry(
project,
(_flagged ? "Flag" : "Unflag") + " " + changes.size() + " rows",
this,
new MassChange(changes, false)
);
}
protected RowVisitor createRowVisitor(Project project, List<Change> changes) throws Exception {
return new RowVisitor() {
List<Change> changes;
public RowVisitor init(List<Change> changes) {
this.changes = changes;
return this;
}
public boolean visit(Project project, int rowIndex, Row row, boolean includeContextual, boolean includeDependent) {
- if (row.starred != _flagged) {
+ if (row.flagged != _flagged) {
RowFlagChange change = new RowFlagChange(rowIndex, _flagged);
changes.add(change);
}
return false;
}
}.init(changes);
}
}
| true | true | protected RowVisitor createRowVisitor(Project project, List<Change> changes) throws Exception {
return new RowVisitor() {
List<Change> changes;
public RowVisitor init(List<Change> changes) {
this.changes = changes;
return this;
}
public boolean visit(Project project, int rowIndex, Row row, boolean includeContextual, boolean includeDependent) {
if (row.starred != _flagged) {
RowFlagChange change = new RowFlagChange(rowIndex, _flagged);
changes.add(change);
}
return false;
}
}.init(changes);
}
| protected RowVisitor createRowVisitor(Project project, List<Change> changes) throws Exception {
return new RowVisitor() {
List<Change> changes;
public RowVisitor init(List<Change> changes) {
this.changes = changes;
return this;
}
public boolean visit(Project project, int rowIndex, Row row, boolean includeContextual, boolean includeDependent) {
if (row.flagged != _flagged) {
RowFlagChange change = new RowFlagChange(rowIndex, _flagged);
changes.add(change);
}
return false;
}
}.init(changes);
}
|
diff --git a/src/com/application/takeacoffee/RetrieveDataFromServer.java b/src/com/application/takeacoffee/RetrieveDataFromServer.java
index df34cb5..e87a94b 100644
--- a/src/com/application/takeacoffee/RetrieveDataFromServer.java
+++ b/src/com/application/takeacoffee/RetrieveDataFromServer.java
@@ -1,100 +1,100 @@
package com.application.takeacoffee;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.application.commons.Common.ReviewStatusEnum;
import com.google.gson.Gson;
import java.util.ArrayList;
public class RetrieveDataFromServer {
// private final static String TAG ="retrieveDataFromServer";
static ArrayList<CoffeMachine> getCoffeMachineData() {
String JSONData = getData();
ArrayList<CoffeMachine> dataArray = parseData(JSONData);
return dataArray;
}
private static String getData() {
String JSONData = "{'coffe_machine_data' : [{'coffe_machine_id':'STATIC_COFFEMACHINEID_1', 'coffe_machine_name':'Fin Machine','coffe_machine_address':'Main Street - London', 'coffe_machine_reviews' : [] }, {'coffe_machine_id':'STATIC_COFFEMACHINEID_2','coffe_machine_name':'Hey Machine','coffe_machine_address':'Even village - Mexico', 'coffe_machine_reviews' : [{'review_id':'STATIC_REVIEWID_1', 'review_username':'Mike pp', 'review_comment':'this is the comment on machine', 'review_status':'NOT_BAD'}, {'review_id':'STATIC_REVIEWID_2', 'review_username':'Henry d', 'review_comment':'this is the comment on machine cos I want to say thats nothing in front of your problems didnt u agree with me?', 'review_status':'GOOD'}] }] }";
return JSONData;
}
private static ArrayList<CoffeMachine> parseData(String data) {
try {
JSONObject jsonObj = (JSONObject) new JSONObject(data);
JSONArray jsonArray = jsonObj.getJSONArray("coffe_machine_data");
ArrayList<CoffeMachine> dataArray = new ArrayList<CoffeMachine>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject coffeMachineObj = jsonArray.getJSONObject(i);
String name = coffeMachineObj.getString("coffe_machine_name");
String address = coffeMachineObj
.getString("coffe_machine_address");
String coffeMachineId = coffeMachineObj
.getString("coffe_machine_id");
JSONArray reviewsArray = coffeMachineObj
.getJSONArray("coffe_machine_reviews");
ArrayList<Review> reviewsList = new ArrayList<Review>();
for (int j = 0; j < reviewsArray.length(); j++) {
JSONObject reviewObj = reviewsArray.getJSONObject(j);
String reviewId = reviewObj.getString("review_id");
String reviewUsername = reviewObj
.getString("review_username");
String reviewComment = reviewObj
.getString("review_comment");
- int reviewStatus = reviewObj
- .getInt("review_status");
+// int reviewStatus = reviewObj
+ // .getInt("review_status");
reviewsList.add(new Review(reviewId, reviewUsername,
- reviewComment, reviewStatus));
+ reviewComment, ReviewStatusEnum.NOT_BAD));
}
dataArray.add(new CoffeMachine(coffeMachineId, name, address,
reviewsList));
}
return dataArray;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private static String encodeToJSONData(
ArrayList<CoffeMachine> coffeMachineList) {
try {
Gson g = new Gson();
String jsonString = g.toJson(coffeMachineList);
return jsonString;
/* if (coffeMachineList.size() != 0) {
for (int i = 0; i < coffeMachineList.size(); i++) {
CoffeMachine coffeMachineObj = coffeMachineList.get(i);
ArrayList<Review> reviewList = coffeMachineObj
.getReviewList();
if (reviewList.size() != 0) {
for (int j = 0; j < reviewList.size(); j++) {
Review reviewObj = reviewList.get(j);
}
}
}
}*/
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
| false | true | private static ArrayList<CoffeMachine> parseData(String data) {
try {
JSONObject jsonObj = (JSONObject) new JSONObject(data);
JSONArray jsonArray = jsonObj.getJSONArray("coffe_machine_data");
ArrayList<CoffeMachine> dataArray = new ArrayList<CoffeMachine>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject coffeMachineObj = jsonArray.getJSONObject(i);
String name = coffeMachineObj.getString("coffe_machine_name");
String address = coffeMachineObj
.getString("coffe_machine_address");
String coffeMachineId = coffeMachineObj
.getString("coffe_machine_id");
JSONArray reviewsArray = coffeMachineObj
.getJSONArray("coffe_machine_reviews");
ArrayList<Review> reviewsList = new ArrayList<Review>();
for (int j = 0; j < reviewsArray.length(); j++) {
JSONObject reviewObj = reviewsArray.getJSONObject(j);
String reviewId = reviewObj.getString("review_id");
String reviewUsername = reviewObj
.getString("review_username");
String reviewComment = reviewObj
.getString("review_comment");
int reviewStatus = reviewObj
.getInt("review_status");
reviewsList.add(new Review(reviewId, reviewUsername,
reviewComment, reviewStatus));
}
dataArray.add(new CoffeMachine(coffeMachineId, name, address,
reviewsList));
}
return dataArray;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
| private static ArrayList<CoffeMachine> parseData(String data) {
try {
JSONObject jsonObj = (JSONObject) new JSONObject(data);
JSONArray jsonArray = jsonObj.getJSONArray("coffe_machine_data");
ArrayList<CoffeMachine> dataArray = new ArrayList<CoffeMachine>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject coffeMachineObj = jsonArray.getJSONObject(i);
String name = coffeMachineObj.getString("coffe_machine_name");
String address = coffeMachineObj
.getString("coffe_machine_address");
String coffeMachineId = coffeMachineObj
.getString("coffe_machine_id");
JSONArray reviewsArray = coffeMachineObj
.getJSONArray("coffe_machine_reviews");
ArrayList<Review> reviewsList = new ArrayList<Review>();
for (int j = 0; j < reviewsArray.length(); j++) {
JSONObject reviewObj = reviewsArray.getJSONObject(j);
String reviewId = reviewObj.getString("review_id");
String reviewUsername = reviewObj
.getString("review_username");
String reviewComment = reviewObj
.getString("review_comment");
// int reviewStatus = reviewObj
// .getInt("review_status");
reviewsList.add(new Review(reviewId, reviewUsername,
reviewComment, ReviewStatusEnum.NOT_BAD));
}
dataArray.add(new CoffeMachine(coffeMachineId, name, address,
reviewsList));
}
return dataArray;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
|
diff --git a/modules/quercus/src/com/caucho/quercus/lib/MailModule.java b/modules/quercus/src/com/caucho/quercus/lib/MailModule.java
index 8ad02cdfb..cae8518f6 100644
--- a/modules/quercus/src/com/caucho/quercus/lib/MailModule.java
+++ b/modules/quercus/src/com/caucho/quercus/lib/MailModule.java
@@ -1,251 +1,251 @@
/*
* Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.quercus.lib;
import com.caucho.quercus.QuercusModuleException;
import com.caucho.quercus.annotation.Optional;
import com.caucho.quercus.env.Env;
import com.caucho.quercus.env.StringValue;
import com.caucho.quercus.module.AbstractQuercusModule;
import com.caucho.util.CharBuffer;
import com.caucho.util.L10N;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* PHP functions implemented from the mail module
*/
public class MailModule extends AbstractQuercusModule {
private static final Logger log =
Logger.getLogger(MailModule.class.getName());
private static final L10N L = new L10N(MailModule.class);
/**
* Send mail using JavaMail.
*/
public static boolean mail(Env env,
String to,
String subject,
StringValue message,
@Optional String additionalHeaders,
@Optional String additionalParameters)
{
Transport smtp = null;
try {
Properties props = new Properties();
StringValue host = env.getIni("SMTP");
if (host != null && ! host.toString().equals(""))
props.put("mail.smtp.host", host.toString());
- else
+ else if (System.getProperty("mail.smtp.host") != null)
props.put("mail.smtp.host", System.getProperty("mail.smtp.host"));
StringValue port = env.getIni("smtp_port");
if (port != null && ! port.toString().equals(""))
props.put("mail.smtp.port", port.toString());
else if (System.getProperty("mail.smtp.port") != null)
props.put("mail.smtp.port", System.getProperty("mail.smtp.port"));
StringValue user = env.getIni("sendmail_from");
if (user != null && ! user.toString().equals(""))
props.put("mail.from", user.toString());
else if (System.getProperty("mail.from") != null)
props.put("mail.from", System.getProperty("mail.from"));
String username = env.getIniString("smtp_username");
String password = env.getIniString("smtp_password");
if (password != null && ! "".equals(password))
props.put( "mail.smtp.auth", "true");
Session mailSession = Session.getInstance(props, null);
smtp = mailSession.getTransport("smtp");
MimeMessage msg = new MimeMessage(mailSession);
msg.setSubject(subject);
msg.setContent(message.toString(), "text/plain");
ArrayList<Address> addrList;
addrList = addRecipients(msg, Message.RecipientType.TO, to);
if (additionalHeaders != null)
addHeaders(msg, additionalHeaders);
Address []from = msg.getFrom();
if (from == null || from.length == 0) {
log.fine(L.l("mail 'From' not set, setting to Java System property 'user.name'"));
msg.setFrom();
}
msg.saveChanges();
if (addrList.size() == 0)
throw new QuercusModuleException(L.l("mail has no recipients"));
from = msg.getFrom();
log.fine(L.l("sending mail, From: {0}, To: {1}", from[0], to));
if (password != null && ! "".equals(password))
smtp.connect(username, password);
else
smtp.connect();
Address[] addr = new Address[addrList.size()];
addrList.toArray(addr);
smtp.sendMessage(msg, addr);
log.fine("quercus-mail: sent mail to " + to);
return true;
} catch (RuntimeException e) {
log.log(Level.FINER, e.toString(), e);
throw e;
} catch (MessagingException e) {
log.warning(L.l("Quercus[] mail could not send mail to '" + to + "'"
+ "\n" + e.getMessage()));
log.log(Level.FINE, e.toString(), e);
env.warning(e.getMessage());
return false;
} catch (Exception e) {
log.warning(L.l("Quercus[] mail could not send mail to '" + to + "'"
+ "\n" + e.getMessage()));
log.log(Level.FINE, e.toString(), e);
env.warning(e.toString());
return false;
} finally {
try {
if (smtp != null)
smtp.close();
} catch (Exception e) {
log.log(Level.FINER, e.toString(), e);
}
}
}
private static ArrayList<Address> addRecipients(MimeMessage msg,
Message.RecipientType type,
String to)
throws MessagingException
{
String []split = to.split("[ \t,<>]");
ArrayList<Address> addresses = new ArrayList<Address>();
for (int i = 0; i < split.length; i++) {
if (split[i].indexOf('@') > 0) {
Address addr = new InternetAddress(split[i]);
addresses.add(addr);
msg.addRecipient(type, addr);
}
}
return addresses;
}
private static void addHeaders(MimeMessage msg, String headers)
throws MessagingException
{
int i = 0;
int len = headers.length();
CharBuffer buffer = new CharBuffer();
while (i < len) {
char ch;
for (;
i < len && Character.isWhitespace(headers.charAt(i));
i++) {
}
if (len <= i)
return;
buffer.clear();
for (;
i < len && (! Character.isWhitespace(ch = headers.charAt(i))
&& ch != ':');
i++) {
buffer.append((char) ch);
}
for (;
i < len && ((ch = headers.charAt(i)) == ' '
|| ch == '\t'
|| ch == '\f'
|| ch == ':');
i++) {
}
String name = buffer.toString();
buffer.clear();
for (;
i < len
&& ((ch = headers.charAt(i)) != '\r' && ch != '\n');
i++) {
buffer.append((char) ch);
}
String value = buffer.toString();
if ("".equals(value)) {
}
else if (name.equalsIgnoreCase("From")) {
msg.setFrom(new InternetAddress(value));
}
else
msg.addHeader(name, value);
}
}
}
| true | true | public static boolean mail(Env env,
String to,
String subject,
StringValue message,
@Optional String additionalHeaders,
@Optional String additionalParameters)
{
Transport smtp = null;
try {
Properties props = new Properties();
StringValue host = env.getIni("SMTP");
if (host != null && ! host.toString().equals(""))
props.put("mail.smtp.host", host.toString());
else
props.put("mail.smtp.host", System.getProperty("mail.smtp.host"));
StringValue port = env.getIni("smtp_port");
if (port != null && ! port.toString().equals(""))
props.put("mail.smtp.port", port.toString());
else if (System.getProperty("mail.smtp.port") != null)
props.put("mail.smtp.port", System.getProperty("mail.smtp.port"));
StringValue user = env.getIni("sendmail_from");
if (user != null && ! user.toString().equals(""))
props.put("mail.from", user.toString());
else if (System.getProperty("mail.from") != null)
props.put("mail.from", System.getProperty("mail.from"));
String username = env.getIniString("smtp_username");
String password = env.getIniString("smtp_password");
if (password != null && ! "".equals(password))
props.put( "mail.smtp.auth", "true");
Session mailSession = Session.getInstance(props, null);
smtp = mailSession.getTransport("smtp");
MimeMessage msg = new MimeMessage(mailSession);
msg.setSubject(subject);
msg.setContent(message.toString(), "text/plain");
ArrayList<Address> addrList;
addrList = addRecipients(msg, Message.RecipientType.TO, to);
if (additionalHeaders != null)
addHeaders(msg, additionalHeaders);
Address []from = msg.getFrom();
if (from == null || from.length == 0) {
log.fine(L.l("mail 'From' not set, setting to Java System property 'user.name'"));
msg.setFrom();
}
msg.saveChanges();
if (addrList.size() == 0)
throw new QuercusModuleException(L.l("mail has no recipients"));
from = msg.getFrom();
log.fine(L.l("sending mail, From: {0}, To: {1}", from[0], to));
if (password != null && ! "".equals(password))
smtp.connect(username, password);
else
smtp.connect();
Address[] addr = new Address[addrList.size()];
addrList.toArray(addr);
smtp.sendMessage(msg, addr);
log.fine("quercus-mail: sent mail to " + to);
return true;
} catch (RuntimeException e) {
log.log(Level.FINER, e.toString(), e);
throw e;
} catch (MessagingException e) {
log.warning(L.l("Quercus[] mail could not send mail to '" + to + "'"
+ "\n" + e.getMessage()));
log.log(Level.FINE, e.toString(), e);
env.warning(e.getMessage());
return false;
} catch (Exception e) {
log.warning(L.l("Quercus[] mail could not send mail to '" + to + "'"
+ "\n" + e.getMessage()));
log.log(Level.FINE, e.toString(), e);
env.warning(e.toString());
return false;
} finally {
try {
if (smtp != null)
smtp.close();
} catch (Exception e) {
log.log(Level.FINER, e.toString(), e);
}
}
}
| public static boolean mail(Env env,
String to,
String subject,
StringValue message,
@Optional String additionalHeaders,
@Optional String additionalParameters)
{
Transport smtp = null;
try {
Properties props = new Properties();
StringValue host = env.getIni("SMTP");
if (host != null && ! host.toString().equals(""))
props.put("mail.smtp.host", host.toString());
else if (System.getProperty("mail.smtp.host") != null)
props.put("mail.smtp.host", System.getProperty("mail.smtp.host"));
StringValue port = env.getIni("smtp_port");
if (port != null && ! port.toString().equals(""))
props.put("mail.smtp.port", port.toString());
else if (System.getProperty("mail.smtp.port") != null)
props.put("mail.smtp.port", System.getProperty("mail.smtp.port"));
StringValue user = env.getIni("sendmail_from");
if (user != null && ! user.toString().equals(""))
props.put("mail.from", user.toString());
else if (System.getProperty("mail.from") != null)
props.put("mail.from", System.getProperty("mail.from"));
String username = env.getIniString("smtp_username");
String password = env.getIniString("smtp_password");
if (password != null && ! "".equals(password))
props.put( "mail.smtp.auth", "true");
Session mailSession = Session.getInstance(props, null);
smtp = mailSession.getTransport("smtp");
MimeMessage msg = new MimeMessage(mailSession);
msg.setSubject(subject);
msg.setContent(message.toString(), "text/plain");
ArrayList<Address> addrList;
addrList = addRecipients(msg, Message.RecipientType.TO, to);
if (additionalHeaders != null)
addHeaders(msg, additionalHeaders);
Address []from = msg.getFrom();
if (from == null || from.length == 0) {
log.fine(L.l("mail 'From' not set, setting to Java System property 'user.name'"));
msg.setFrom();
}
msg.saveChanges();
if (addrList.size() == 0)
throw new QuercusModuleException(L.l("mail has no recipients"));
from = msg.getFrom();
log.fine(L.l("sending mail, From: {0}, To: {1}", from[0], to));
if (password != null && ! "".equals(password))
smtp.connect(username, password);
else
smtp.connect();
Address[] addr = new Address[addrList.size()];
addrList.toArray(addr);
smtp.sendMessage(msg, addr);
log.fine("quercus-mail: sent mail to " + to);
return true;
} catch (RuntimeException e) {
log.log(Level.FINER, e.toString(), e);
throw e;
} catch (MessagingException e) {
log.warning(L.l("Quercus[] mail could not send mail to '" + to + "'"
+ "\n" + e.getMessage()));
log.log(Level.FINE, e.toString(), e);
env.warning(e.getMessage());
return false;
} catch (Exception e) {
log.warning(L.l("Quercus[] mail could not send mail to '" + to + "'"
+ "\n" + e.getMessage()));
log.log(Level.FINE, e.toString(), e);
env.warning(e.toString());
return false;
} finally {
try {
if (smtp != null)
smtp.close();
} catch (Exception e) {
log.log(Level.FINER, e.toString(), e);
}
}
}
|
diff --git a/search-impl/impl/src/java/org/sakaiproject/search/component/adapter/message/MessageContentProducer.java b/search-impl/impl/src/java/org/sakaiproject/search/component/adapter/message/MessageContentProducer.java
index f268f7ca..b1e122d8 100644
--- a/search-impl/impl/src/java/org/sakaiproject/search/component/adapter/message/MessageContentProducer.java
+++ b/search-impl/impl/src/java/org/sakaiproject/search/component/adapter/message/MessageContentProducer.java
@@ -1,442 +1,442 @@
/**********************************************************************************
* $URL: $
* $Id: $
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
*
* 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.sakaiproject.search.component.adapter.message;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.component.api.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.EntityManager;
import org.sakaiproject.entity.api.EntityProducer;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.event.api.Event;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.message.api.Message;
import org.sakaiproject.message.api.MessageChannel;
import org.sakaiproject.message.api.MessageHeader;
import org.sakaiproject.message.api.MessageService;
import org.sakaiproject.search.api.EntityContentProducer;
import org.sakaiproject.search.api.SearchIndexBuilder;
import org.sakaiproject.search.api.SearchService;
import org.sakaiproject.search.model.SearchBuilderItem;
/**
* @author ieb
*/
public class MessageContentProducer implements EntityContentProducer
{
/**
* debug logger
*/
private static Log log = LogFactory.getLog(MessageContentProducer.class);
// runtime dependency
private String toolName = null;
// runtime dependency
private List addEvents = null;
// runtime dependency
private List removeEvents = null;
// injected dependency
private MessageService messageService = null;
// runtime dependency
private SearchService searchService = null;
// runtime dependency
private SearchIndexBuilder searchIndexBuilder = null;
private EntityManager entityManager = null;
public void init()
{
ComponentManager cm = org.sakaiproject.component.cover.ComponentManager
.getInstance();
searchService = (SearchService) load(cm, SearchService.class.getName());
searchIndexBuilder = (SearchIndexBuilder) load(cm,
SearchIndexBuilder.class.getName());
entityManager = (EntityManager) load(cm, EntityManager.class.getName());
if ("true".equals(ServerConfigurationService
.getString("search.experimental","true")))
{
for (Iterator i = addEvents.iterator(); i.hasNext();)
{
searchService.registerFunction((String) i.next());
}
for (Iterator i = removeEvents.iterator(); i.hasNext();)
{
searchService.registerFunction((String) i.next());
}
searchIndexBuilder.registerEntityContentProducer(this);
}
}
private Object load(ComponentManager cm, String name)
{
Object o = cm.get(name);
if (o == null)
{
log.error("Cant find Spring component named " + name);
}
return o;
}
/**
* {@inheritDoc}
*/
public boolean isContentFromReader(Entity cr)
{
return false;
}
/**
* {@inheritDoc}
*/
public Reader getContentReader(Entity cr)
{
return new StringReader(getContent(cr));
}
/**
* {@inheritDoc}
*/
public String getContent(Entity cr)
{
Reference ref = entityManager.newReference(cr.getReference());
EntityProducer ep = ref.getEntityProducer();
if (ep instanceof MessageService)
{
try
{
MessageService ms = (MessageService) ep;
Message m = ms.getMessage(ref);
MessageHeader mh = m.getHeader();
StringBuffer sb = new StringBuffer();
sb.append("Message Headers\n");
sb.append("From ").append(mh.getFrom().getDisplayName())
.append("\n");
sb.append("Message Body\n");
sb.append(m.getBody()).append("\n");
- log.info("Message Content for "+cr.getReference()+" is "+sb.toString());
+ log.debug("Message Content for "+cr.getReference()+" is "+sb.toString());
return sb.toString();
}
catch (IdUnusedException e)
{
throw new RuntimeException(" Failed to get message content ", e);
}
catch (PermissionException e)
{
throw new RuntimeException(" Failed to get message content ", e);
}
}
throw new RuntimeException(" Not a Message Entity " + cr);
}
/**
* @{inheritDoc}
*/
public String getTitle(Entity cr)
{
Reference ref = entityManager.newReference(cr.getReference());
EntityProducer ep = ref.getEntityProducer();
if (ep instanceof MessageService)
{
try
{
MessageService ms = (MessageService) ep;
Message m = ms.getMessage(ref);
MessageHeader mh = m.getHeader();
return "Message From " + mh.getFrom().getDisplayName();
}
catch (IdUnusedException e)
{
throw new RuntimeException(" Failed to get message content ", e);
}
catch (PermissionException e)
{
throw new RuntimeException(" Failed to get message content ", e);
}
}
throw new RuntimeException(" Not a Message Entity " + cr);
}
/**
* @{inheritDoc}
*/
public String getUrl(Entity entity)
{
return entity.getUrl();
}
/**
* @{inheritDoc}
*/
public boolean matches(Reference ref)
{
EntityProducer ep = ref.getEntityProducer();
if (ep.getClass().equals(messageService.getClass()))
{
return true;
}
return false;
}
/**
* @{inheritDoc}
*/
public List getAllContent()
{
List all = new ArrayList();
List l = messageService.getChannels();
for (Iterator i = l.iterator(); i.hasNext();)
{
try
{
MessageChannel c = (MessageChannel) i.next();
List messages = c.getMessages(null, true);
// WARNING: I think the implementation caches on thread, if this
// is
// a builder
// thread this may not work
for (Iterator mi = messages.iterator(); mi.hasNext();)
{
Message m = (Message) i.next();
all.add(m.getReference());
}
}
catch (Exception ex)
{
}
}
return all;
}
/**
* @{inheritDoc}
*/
public Integer getAction(Event event)
{
String evt = event.getEvent();
if (evt == null) return SearchBuilderItem.ACTION_UNKNOWN;
for (Iterator i = addEvents.iterator(); i.hasNext();)
{
String match = (String) i.next();
if (evt.equals(match))
{
return SearchBuilderItem.ACTION_ADD;
}
}
for (Iterator i = removeEvents.iterator(); i.hasNext();)
{
String match = (String) i.next();
if (evt.equals(match))
{
return SearchBuilderItem.ACTION_DELETE;
}
}
return SearchBuilderItem.ACTION_UNKNOWN;
}
/**
* @{inheritDoc}
*/
public boolean matches(Event event)
{
Reference ref = entityManager.newReference(event.getResource());
return matches(ref);
}
/**
* @{inheritDoc}
*/
public String getTool()
{
return toolName;
}
/**
* @return Returns the addEvents.
*/
public List getAddEvents()
{
return addEvents;
}
/**
* @param addEvents
* The addEvents to set.
*/
public void setAddEvents(List addEvents)
{
this.addEvents = addEvents;
}
/**
* @return Returns the messageService.
*/
public MessageService getMessageService()
{
return messageService;
}
/**
* @param messageService
* The messageService to set.
*/
public void setMessageService(MessageService messageService)
{
this.messageService = messageService;
}
/**
* @return Returns the toolName.
*/
public String getToolName()
{
return toolName;
}
/**
* @param toolName
* The toolName to set.
*/
public void setToolName(String toolName)
{
this.toolName = toolName;
}
/**
* @return Returns the removeEvents.
*/
public List getRemoveEvents()
{
return removeEvents;
}
/**
* @param removeEvents
* The removeEvents to set.
*/
public void setRemoveEvents(List removeEvents)
{
this.removeEvents = removeEvents;
}
public String getSiteId(Reference ref)
{
return ref.getContext();
}
public String getSiteId(String resourceName)
{
return getSiteId(entityManager.newReference(resourceName));
}
public List getSiteContent(String context)
{
List all = new ArrayList();
List l = messageService.getChannelIds(context);
for (Iterator i = l.iterator(); i.hasNext();)
{
String chanellId = (String) i.next();
try
{
MessageChannel c = messageService.getChannel(chanellId);
List messages = c.getMessages(null, true);
// WARNING: I think the implementation caches on thread, if this
// is
// a builder
// thread this may not work
for (Iterator mi = messages.iterator(); mi.hasNext();)
{
Message m = (Message) i.next();
all.add(m.getReference());
}
}
catch (Exception ex)
{
log.debug("Failed to get channel "+chanellId);
}
}
return all;
}
public boolean isForIndex(Reference ref)
{
EntityProducer ep = ref.getEntityProducer();
if (ep instanceof MessageService)
{
try
{
MessageService ms = (MessageService) ep;
Message m = ms.getMessage(ref);
if ( m == null ) {
log.warn("Rejected null message "+ref.getReference());
return false;
}
}
catch (IdUnusedException e)
{
log.warn("Rejected Missing message "+ref.getReference());
return false;
}
catch (PermissionException e)
{
log.warn("Rejected private message "+ref.getReference());
return false;
}
return true;
}
return false;
}
}
| true | true | public String getContent(Entity cr)
{
Reference ref = entityManager.newReference(cr.getReference());
EntityProducer ep = ref.getEntityProducer();
if (ep instanceof MessageService)
{
try
{
MessageService ms = (MessageService) ep;
Message m = ms.getMessage(ref);
MessageHeader mh = m.getHeader();
StringBuffer sb = new StringBuffer();
sb.append("Message Headers\n");
sb.append("From ").append(mh.getFrom().getDisplayName())
.append("\n");
sb.append("Message Body\n");
sb.append(m.getBody()).append("\n");
log.info("Message Content for "+cr.getReference()+" is "+sb.toString());
return sb.toString();
}
catch (IdUnusedException e)
{
throw new RuntimeException(" Failed to get message content ", e);
}
catch (PermissionException e)
{
throw new RuntimeException(" Failed to get message content ", e);
}
}
throw new RuntimeException(" Not a Message Entity " + cr);
}
| public String getContent(Entity cr)
{
Reference ref = entityManager.newReference(cr.getReference());
EntityProducer ep = ref.getEntityProducer();
if (ep instanceof MessageService)
{
try
{
MessageService ms = (MessageService) ep;
Message m = ms.getMessage(ref);
MessageHeader mh = m.getHeader();
StringBuffer sb = new StringBuffer();
sb.append("Message Headers\n");
sb.append("From ").append(mh.getFrom().getDisplayName())
.append("\n");
sb.append("Message Body\n");
sb.append(m.getBody()).append("\n");
log.debug("Message Content for "+cr.getReference()+" is "+sb.toString());
return sb.toString();
}
catch (IdUnusedException e)
{
throw new RuntimeException(" Failed to get message content ", e);
}
catch (PermissionException e)
{
throw new RuntimeException(" Failed to get message content ", e);
}
}
throw new RuntimeException(" Not a Message Entity " + cr);
}
|
diff --git a/src/main/com/giftoftheembalmer/gotefarm/client/RoleAndBadgeEditor.java b/src/main/com/giftoftheembalmer/gotefarm/client/RoleAndBadgeEditor.java
index bcade41..cfaaeb1 100644
--- a/src/main/com/giftoftheembalmer/gotefarm/client/RoleAndBadgeEditor.java
+++ b/src/main/com/giftoftheembalmer/gotefarm/client/RoleAndBadgeEditor.java
@@ -1,77 +1,77 @@
package com.giftoftheembalmer.gotefarm.client;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SimpleCheckBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import java.util.List;
public class RoleAndBadgeEditor extends Composite {
VerticalPanel vpanel = new VerticalPanel();
String flavor1; // e.g., Roles
public RoleAndBadgeEditor(String flavor1) {
this.flavor1 = flavor1;
vpanel.setWidth("100%");
initWidget(vpanel);
setStyleName("RoleAndBadgeEditor");
}
public <A extends BadgeAndRole, B extends ChrBadgeAndRole, C extends BadgeAndRoleClickHandlerFactory>
void update(List<A> roles, B[] chrroles, C clickListener) {
vpanel.clear();
FlexTable flex = new FlexTable();
flex.setWidth("100%");
vpanel.add(new Label(flavor1 + " - Check all that apply"));
int row = 0;
for (final A role : roles) {
final SimpleCheckBox hasrole = new SimpleCheckBox();
flex.setWidget(row, 0, hasrole);
boolean has_role = false;
boolean is_waiting = false;
for (B chrrole : chrroles) {
- if (chrrole.getKey() == role.getKey()) {
+ if (chrrole.getKey().equals(role.getKey())) {
has_role = true;
hasrole.addClickHandler(
clickListener.newClickHandler(flex, row, chrrole)
);
is_waiting = chrrole.isWaiting();
break;
}
}
if (has_role) {
hasrole.setChecked(true);
if (is_waiting) {
flex.setText(row, 2, "pending admin approval");
}
}
else {
hasrole.addClickHandler(clickListener.newClickHandler(
flex, row, new ChrBadgeAndRole() {
public String getKey() { return role.getKey(); }
public String getName() { return role.getName(); }
public String getMessage() { return null; }
public boolean isRestricted() { return role.isRestricted(); }
public boolean isApproved() { return !role.isRestricted(); }
public boolean isWaiting() { return role.isRestricted(); }
}));
}
flex.setText(row, 1, role.getName());
// TODO: Show if request has been denied, show admin message if
// any
++row;
}
vpanel.add(flex);
}
}
| true | true | public <A extends BadgeAndRole, B extends ChrBadgeAndRole, C extends BadgeAndRoleClickHandlerFactory>
void update(List<A> roles, B[] chrroles, C clickListener) {
vpanel.clear();
FlexTable flex = new FlexTable();
flex.setWidth("100%");
vpanel.add(new Label(flavor1 + " - Check all that apply"));
int row = 0;
for (final A role : roles) {
final SimpleCheckBox hasrole = new SimpleCheckBox();
flex.setWidget(row, 0, hasrole);
boolean has_role = false;
boolean is_waiting = false;
for (B chrrole : chrroles) {
if (chrrole.getKey() == role.getKey()) {
has_role = true;
hasrole.addClickHandler(
clickListener.newClickHandler(flex, row, chrrole)
);
is_waiting = chrrole.isWaiting();
break;
}
}
if (has_role) {
hasrole.setChecked(true);
if (is_waiting) {
flex.setText(row, 2, "pending admin approval");
}
}
else {
hasrole.addClickHandler(clickListener.newClickHandler(
flex, row, new ChrBadgeAndRole() {
public String getKey() { return role.getKey(); }
public String getName() { return role.getName(); }
public String getMessage() { return null; }
public boolean isRestricted() { return role.isRestricted(); }
public boolean isApproved() { return !role.isRestricted(); }
public boolean isWaiting() { return role.isRestricted(); }
}));
}
flex.setText(row, 1, role.getName());
// TODO: Show if request has been denied, show admin message if
// any
++row;
}
vpanel.add(flex);
}
| public <A extends BadgeAndRole, B extends ChrBadgeAndRole, C extends BadgeAndRoleClickHandlerFactory>
void update(List<A> roles, B[] chrroles, C clickListener) {
vpanel.clear();
FlexTable flex = new FlexTable();
flex.setWidth("100%");
vpanel.add(new Label(flavor1 + " - Check all that apply"));
int row = 0;
for (final A role : roles) {
final SimpleCheckBox hasrole = new SimpleCheckBox();
flex.setWidget(row, 0, hasrole);
boolean has_role = false;
boolean is_waiting = false;
for (B chrrole : chrroles) {
if (chrrole.getKey().equals(role.getKey())) {
has_role = true;
hasrole.addClickHandler(
clickListener.newClickHandler(flex, row, chrrole)
);
is_waiting = chrrole.isWaiting();
break;
}
}
if (has_role) {
hasrole.setChecked(true);
if (is_waiting) {
flex.setText(row, 2, "pending admin approval");
}
}
else {
hasrole.addClickHandler(clickListener.newClickHandler(
flex, row, new ChrBadgeAndRole() {
public String getKey() { return role.getKey(); }
public String getName() { return role.getName(); }
public String getMessage() { return null; }
public boolean isRestricted() { return role.isRestricted(); }
public boolean isApproved() { return !role.isRestricted(); }
public boolean isWaiting() { return role.isRestricted(); }
}));
}
flex.setText(row, 1, role.getName());
// TODO: Show if request has been denied, show admin message if
// any
++row;
}
vpanel.add(flex);
}
|
diff --git a/OpenSudoku/src/cz/romario/opensudoku/gui/SudokuBoardView.java b/OpenSudoku/src/cz/romario/opensudoku/gui/SudokuBoardView.java
index ebfe2a9..9a96aad 100644
--- a/OpenSudoku/src/cz/romario/opensudoku/gui/SudokuBoardView.java
+++ b/OpenSudoku/src/cz/romario/opensudoku/gui/SudokuBoardView.java
@@ -1,613 +1,613 @@
package cz.romario.opensudoku.gui;
import cz.romario.opensudoku.game.SudokuCell;
import cz.romario.opensudoku.game.SudokuCellCollection;
import cz.romario.opensudoku.game.SudokuGame;
import cz.romario.opensudoku.gui.EditCellDialog.OnNoteEditListener;
import cz.romario.opensudoku.gui.EditCellDialog.OnNumberEditListener;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
/**
* Sudoku board widget.
*
* @author romario
*
*/
public class SudokuBoardView extends View {
public static final int DEFAULT_BOARD_SIZE = 100;
private static final String TAG = "SudokuBoardView";
private float mCellWidth;
private float mCellHeight;
private Paint mLinePaint;
private Paint mNumberPaint;
private Paint mNotePaint;
private int mNumberLeft;
private int mNumberTop;
private Paint mReadonlyPaint;
private Paint mTouchedPaint;
private Paint mSelectedPaint;
private SudokuCell mTouchedCell;
private SudokuCell mSelectedCell;
public boolean mReadonly = false;
private EditCellDialog mEditCellDialog;
private SudokuGame mGame;
private SudokuCellCollection mCells;
private int mScreenOrientation = -1;
private OnCellTapListener mOnCellTapListener;
public SudokuBoardView(Context context) {
super(context);
initWidget();
}
public SudokuBoardView(Context context, AttributeSet attrs) {
super(context, attrs);
initWidget();
}
public void setGame(SudokuGame game) {
mGame = game;
setCells(game.getCells());
}
public void setCells(SudokuCellCollection cells) {
mCells = cells;
if (!mReadonly) {
mSelectedCell = mCells.getCell(0, 0); // first cell will be selected by default
}
invalidate();
}
public SudokuCellCollection getCells() {
return mCells;
}
public SudokuCell getSelectedCell() {
return mSelectedCell;
}
public void setReadOnly(boolean readonly) {
mReadonly = readonly;
}
public boolean getReadOnly() {
return mReadonly;
}
public void setOnCellTapListener(OnCellTapListener l) {
mOnCellTapListener = l;
}
private void initWidget() {
setFocusable(true);
setFocusableInTouchMode(true);
setBackgroundColor(Color.WHITE);
mLinePaint = new Paint();
mLinePaint.setColor(Color.BLACK);
mNumberPaint = new Paint();
mNumberPaint.setColor(Color.BLACK);
mNumberPaint.setAntiAlias(true);
mNotePaint = new Paint();
mNotePaint.setColor(Color.BLACK);
mNotePaint.setAntiAlias(true);
mReadonlyPaint = new Paint();
mReadonlyPaint.setColor(Color.LTGRAY);
mTouchedPaint = new Paint();
mTouchedPaint.setColor(Color.rgb(50, 50, 255));
//touchedPaint.setColor(Color.rgb(100, 255, 100));
mTouchedPaint.setAlpha(100);
mSelectedPaint = new Paint();
mSelectedPaint.setColor(Color.YELLOW);
mSelectedPaint.setAlpha(100);
}
/**
* Ensures that editCellDialog exists and is properly initialized.
*
* @return
*/
private void ensureEditCellDialog() {
if (mEditCellDialog == null) {
if (mScreenOrientation == -1) {
mScreenOrientation = getResources().getConfiguration().orientation;
}
// TODO: EditCellDialog is not ready for landscape
if (mScreenOrientation != Configuration.ORIENTATION_LANDSCAPE) {
mEditCellDialog = new EditCellDialog(getContext());
mEditCellDialog.setOnNumberEditListener(onNumberEditListener);
mEditCellDialog.setOnNoteEditListener(onNoteEditListener);
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Log.d(TAG, "widthMode=" + getMeasureSpecModeString(widthMode));
Log.d(TAG, "widthSize=" + widthSize);
Log.d(TAG, "heightMode=" + getMeasureSpecModeString(heightMode));
Log.d(TAG, "heightSize=" + heightSize);
int width = -1, height = -1;
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
} else {
width = DEFAULT_BOARD_SIZE;
if (widthMode == MeasureSpec.AT_MOST && width > widthSize ) {
width = widthSize;
}
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
} else {
height = DEFAULT_BOARD_SIZE;
if (heightMode == MeasureSpec.AT_MOST && height > heightSize ) {
height = heightSize;
}
}
if (widthMode != MeasureSpec.EXACTLY) {
width = height;
}
if (heightMode != MeasureSpec.EXACTLY) {
height = width;
}
if (widthMode == MeasureSpec.AT_MOST && width > widthSize ) {
width = widthSize;
}
if (heightMode == MeasureSpec.AT_MOST && height > heightSize ) {
height = heightSize;
}
mCellWidth = (width - getPaddingLeft() - getPaddingRight()) / 9.0f;
mCellHeight = (height - getPaddingTop() - getPaddingBottom()) / 9.0f;
setMeasuredDimension(width, height);
mNumberPaint.setTextSize(mCellHeight * 0.75f);
mNotePaint.setTextSize(mCellHeight / 3f);
// compute offsets in each cell to center the rendered number
mNumberLeft = (int) ((mCellWidth - mNumberPaint.measureText("9")) / 2);
mNumberTop = (int) ((mCellHeight - mNumberPaint.getTextSize()) / 2);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// some notes:
// Drawable has its own draw() method that takes your Canvas as an arguement
// int width = getMeasuredWidth();
// int height = getMeasuredHeight();
// TODO: padding?
int width = getWidth() - getPaddingLeft() - getPaddingRight();
int height = getHeight() - getPaddingTop() - getPaddingBottom();
int paddingLeft = getPaddingLeft();
int paddingTop = getPaddingTop();
// draw cells
- float cellLeft, cellTop;
+ int cellLeft, cellTop;
if (mCells != null) {
// TODO: why?
float numberAscent = mNumberPaint.ascent();
float noteAscent = mNotePaint.ascent();
float noteWidth = mCellWidth / 3f;
for (int row=0; row<9; row++) {
for (int col=0; col<9; col++) {
SudokuCell cell = mCells.getCell(row, col);
- cellLeft = (col * mCellWidth) + paddingLeft;
- cellTop = (row * mCellHeight) + paddingTop;
+ cellLeft = Math.round((col * mCellWidth) + paddingLeft);
+ cellTop = Math.round((row * mCellHeight) + paddingTop);
// draw read-only field background
if (!cell.getEditable()) {
canvas.drawRect(
cellLeft, cellTop,
cellLeft + mCellWidth, cellTop + mCellHeight,
mReadonlyPaint);
}
// draw cell Text
int value = cell.getValue();
if (value != 0) {
mNumberPaint.setColor(cell.getInvalid() ? Color.RED : Color.BLACK);
canvas.drawText(new Integer(value).toString(),
cellLeft + mNumberLeft,
- cellTop + mNumberTop - numberAscent,
+ Math.round(cellTop) + mNumberTop - numberAscent,
mNumberPaint);
} else {
// TODO: this is ugly temporary version
if (cell.hasNote()) {
Integer[] numbers = getNoteNumbers(cell.getNote());
int r = 0, c = 0;
if (numbers != null) {
for (Integer number : numbers) {
if (c == 3) {
r++;
c = 0;
}
canvas.drawText(number.toString(), cellLeft + c*noteWidth + 2, cellTop - noteAscent + r*noteWidth - 1, mNotePaint);
c++;
}
}
}
}
}
}
// highlight selected cell
if (!mReadonly && mSelectedCell != null) {
- cellLeft = mSelectedCell.getColumnIndex() * mCellWidth;
- cellTop = mSelectedCell.getRowIndex() * mCellHeight;
+ cellLeft = Math.round(mSelectedCell.getColumnIndex() * mCellWidth);
+ cellTop = Math.round(mSelectedCell.getRowIndex() * mCellHeight);
canvas.drawRect(
cellLeft, cellTop,
cellLeft + mCellWidth, cellTop + mCellHeight,
mSelectedPaint);
}
// visually highlight cell under the finger (to cope with touch screen
// imprecision)
if (mTouchedCell != null) {
- cellLeft = mTouchedCell.getColumnIndex() * mCellWidth;
- cellTop = mTouchedCell.getRowIndex() * mCellHeight;
+ cellLeft = Math.round(mTouchedCell.getColumnIndex() * mCellWidth);
+ cellTop = Math.round(mTouchedCell.getRowIndex() * mCellHeight);
canvas.drawRect(
cellLeft, 0,
cellLeft + mCellWidth, height,
mTouchedPaint);
canvas.drawRect(
0, cellTop,
width, cellTop + mCellHeight,
mTouchedPaint);
}
}
// draw vertical lines
for (int c=0; c <= 9; c++) {
float x = c * mCellWidth;
if (c % 3 == 0) {
canvas.drawRect(x-1, 0, x+1, height, mLinePaint);
} else {
canvas.drawLine(x, 0, x, height, mLinePaint);
}
}
// draw horizontal lines
for (int r=0; r <= 9; r++) {
float y = r * mCellHeight;
if (r % 3 == 0) {
canvas.drawRect(0, y-1, width, y+1, mLinePaint);
} else {
canvas.drawLine(0, y, width, y, mLinePaint);
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!mReadonly) {
int x = (int)event.getX();
int y = (int)event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
mTouchedCell = getCellAtPoint(x, y);
break;
case MotionEvent.ACTION_UP:
mSelectedCell = getCellAtPoint(x, y);
boolean selectNumberShowed = false;
if (mSelectedCell != null) {
if (mOnCellTapListener != null) {
mOnCellTapListener.onCellTap(mSelectedCell);
}
ensureEditCellDialog();
if (mSelectedCell.getEditable() && mEditCellDialog != null) {
mEditCellDialog.updateNumber(mSelectedCell.getValue());
mEditCellDialog.updateNote(getNoteNumbers(mSelectedCell.getNote()));
mEditCellDialog.getDialog().show();
selectNumberShowed = true;
}
}
// If select number dialog wasn't showed, clear touched cell highlight, if dialog
// is visible, highlight will be cleared after dialog is dismissed.
if (!selectNumberShowed) {
mTouchedCell = null;
}
break;
case MotionEvent.ACTION_CANCEL:
mTouchedCell = null;
break;
}
invalidate();
}
return !mReadonly;
}
// TODO: do I really need this?
@Override
public boolean onTrackballEvent(MotionEvent event) {
// Actually, just let these come through as D-pad events.
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (!mReadonly) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_UP:
return moveCellSelection(0, -1);
case KeyEvent.KEYCODE_DPAD_RIGHT:
return moveCellSelection(1, 0);
case KeyEvent.KEYCODE_DPAD_DOWN:
return moveCellSelection(0, 1);
case KeyEvent.KEYCODE_DPAD_LEFT:
return moveCellSelection(-1, 0);
case KeyEvent.KEYCODE_0:
case KeyEvent.KEYCODE_SPACE:
case KeyEvent.KEYCODE_DEL:
// clear value in selected cell
if (mSelectedCell != null) {
setCellValue(mSelectedCell, 0);
moveCellSelectionRight();
}
return true;
}
if (keyCode >= KeyEvent.KEYCODE_1 && keyCode <= KeyEvent.KEYCODE_9) {
// enter request number in cell
int selectedNumber = keyCode - KeyEvent.KEYCODE_0;
setCellValue(mSelectedCell, selectedNumber);
moveCellSelectionRight();
return true;
}
}
return false;
}
/**
* Occurs when user selects number in EditCellDialog.
*/
private OnNumberEditListener onNumberEditListener = new OnNumberEditListener() {
@Override
public boolean onNumberEdit(int number) {
SudokuCell selectedCell = getSelectedCell();
if (number != -1) {
// set cell number selected by user
setCellValue(selectedCell, number);
mTouchedCell = null;
invalidate();
}
return true;
}
};
/**
* Occurs when user edits note in EditCellDialog
*/
private OnNoteEditListener onNoteEditListener = new OnNoteEditListener() {
@Override
public boolean onNoteEdit(Integer[] numbers) {
SudokuCell selectedCell = getSelectedCell();
if (selectedCell != null) {
setCellNote(selectedCell, setNoteNumbers(numbers));
mTouchedCell = null;
invalidate();
}
return true;
}
};
private void setCellValue(SudokuCell cell, int value) {
if (cell.getEditable()) {
if (mGame != null) {
mGame.setCellValue(cell, value);
} else {
cell.setValue(value);
}
}
}
private void setCellNote(SudokuCell cell, String note) {
if (cell.getEditable()) {
if (mGame != null) {
mGame.setCellNote(cell, note);
} else {
cell.setNote(note);
}
}
}
/**
* Moves selected cell by one cell to the right. If edge is reached, selection
* skips on beginning of another line.
*/
private void moveCellSelectionRight() {
if (!moveCellSelection(1, 0)) {
int selRow = mSelectedCell.getRowIndex();
selRow++;
if (!moveCellSelectionTo(selRow, 0)) {
moveCellSelectionTo(0, 0);
}
}
}
/**
* Moves selected by vx cells right and vy cells down. vx and vy can be negative. Returns true,
* if new cell is selected.
*
* @param vx Horizontal offset, by which move selected cell.
* @param vy Vertical offset, by which move selected cell.
*/
private boolean moveCellSelection(int vx, int vy) {
int newRow = 0;
int newCol = 0;
if (mSelectedCell != null) {
newRow = mSelectedCell.getRowIndex() + vy;
newCol = mSelectedCell.getColumnIndex() + vx;
}
return moveCellSelectionTo(newRow, newCol);
}
/**
* Moves selection to the cell given by row and column index.
* @param row Row index of cell which should be selected.
* @param col Columnd index of cell which should be selected.
* @return True, if cell was successfuly selected.
*/
private boolean moveCellSelectionTo(int row, int col) {
if(col >= 0 && col < SudokuCellCollection.SUDOKU_SIZE
&& row >= 0 && row < SudokuCellCollection.SUDOKU_SIZE) {
mSelectedCell = mCells.getCell(row, col);
postInvalidate();
return true;
}
return false;
}
/**
* Get cell at given screen coordinates. Returns null if no cell is found.
* @param x
* @param y
* @return
*/
private SudokuCell getCellAtPoint(int x, int y) {
// TODO: this is not nice, col/row vs x/y
int row = (int) (y / mCellHeight);
int col = (int) (x / mCellWidth);
if(col >= 0 && col < SudokuCellCollection.SUDOKU_SIZE
&& row >= 0 && row < SudokuCellCollection.SUDOKU_SIZE) {
return mCells.getCell(row, col);
} else {
return null;
}
}
/**
* Returns content of note as array of numbers. Note is expected to be
* in format "n,n,n".
*
* @return
*/
private Integer[] getNoteNumbers(String note) {
if (note == null || note.equals(""))
return null;
String[] numberStrings = note.split(",");
Integer[] numbers = new Integer[numberStrings.length];
for (int i=0; i<numberStrings.length; i++) {
numbers[i] = Integer.parseInt(numberStrings[i]);
}
return numbers;
}
/**
* Creates content of note from array of numbers. Note will be stored
* in "n,n,n" format.
*
* TODO: find better name for this method
*
* @param numbers
*/
private String setNoteNumbers(Integer[] numbers) {
StringBuffer sb = new StringBuffer();
for (Integer number : numbers) {
sb.append(number).append(",");
}
return sb.toString();
}
public interface OnCellTapListener
{
/**
* Called when a cell is tapped (by finger).
* @param cell
* @return
*/
void onCellTap(SudokuCell cell);
}
private String getMeasureSpecModeString(int mode) {
String modeString = null;
switch (mode) {
case MeasureSpec.AT_MOST:
modeString = "MeasureSpec.AT_MOST";
break;
case MeasureSpec.EXACTLY:
modeString = "MeasureSpec.EXACTLY";
break;
case MeasureSpec.UNSPECIFIED:
modeString = "MeasureSpec.UNSPECIFIED";
break;
}
if (modeString == null)
modeString = new Integer(mode).toString();
return modeString;
}
}
| false | true | protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// some notes:
// Drawable has its own draw() method that takes your Canvas as an arguement
// int width = getMeasuredWidth();
// int height = getMeasuredHeight();
// TODO: padding?
int width = getWidth() - getPaddingLeft() - getPaddingRight();
int height = getHeight() - getPaddingTop() - getPaddingBottom();
int paddingLeft = getPaddingLeft();
int paddingTop = getPaddingTop();
// draw cells
float cellLeft, cellTop;
if (mCells != null) {
// TODO: why?
float numberAscent = mNumberPaint.ascent();
float noteAscent = mNotePaint.ascent();
float noteWidth = mCellWidth / 3f;
for (int row=0; row<9; row++) {
for (int col=0; col<9; col++) {
SudokuCell cell = mCells.getCell(row, col);
cellLeft = (col * mCellWidth) + paddingLeft;
cellTop = (row * mCellHeight) + paddingTop;
// draw read-only field background
if (!cell.getEditable()) {
canvas.drawRect(
cellLeft, cellTop,
cellLeft + mCellWidth, cellTop + mCellHeight,
mReadonlyPaint);
}
// draw cell Text
int value = cell.getValue();
if (value != 0) {
mNumberPaint.setColor(cell.getInvalid() ? Color.RED : Color.BLACK);
canvas.drawText(new Integer(value).toString(),
cellLeft + mNumberLeft,
cellTop + mNumberTop - numberAscent,
mNumberPaint);
} else {
// TODO: this is ugly temporary version
if (cell.hasNote()) {
Integer[] numbers = getNoteNumbers(cell.getNote());
int r = 0, c = 0;
if (numbers != null) {
for (Integer number : numbers) {
if (c == 3) {
r++;
c = 0;
}
canvas.drawText(number.toString(), cellLeft + c*noteWidth + 2, cellTop - noteAscent + r*noteWidth - 1, mNotePaint);
c++;
}
}
}
}
}
}
// highlight selected cell
if (!mReadonly && mSelectedCell != null) {
cellLeft = mSelectedCell.getColumnIndex() * mCellWidth;
cellTop = mSelectedCell.getRowIndex() * mCellHeight;
canvas.drawRect(
cellLeft, cellTop,
cellLeft + mCellWidth, cellTop + mCellHeight,
mSelectedPaint);
}
// visually highlight cell under the finger (to cope with touch screen
// imprecision)
if (mTouchedCell != null) {
cellLeft = mTouchedCell.getColumnIndex() * mCellWidth;
cellTop = mTouchedCell.getRowIndex() * mCellHeight;
canvas.drawRect(
cellLeft, 0,
cellLeft + mCellWidth, height,
mTouchedPaint);
canvas.drawRect(
0, cellTop,
width, cellTop + mCellHeight,
mTouchedPaint);
}
}
// draw vertical lines
for (int c=0; c <= 9; c++) {
float x = c * mCellWidth;
if (c % 3 == 0) {
canvas.drawRect(x-1, 0, x+1, height, mLinePaint);
} else {
canvas.drawLine(x, 0, x, height, mLinePaint);
}
}
// draw horizontal lines
for (int r=0; r <= 9; r++) {
float y = r * mCellHeight;
if (r % 3 == 0) {
canvas.drawRect(0, y-1, width, y+1, mLinePaint);
} else {
canvas.drawLine(0, y, width, y, mLinePaint);
}
}
}
| protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// some notes:
// Drawable has its own draw() method that takes your Canvas as an arguement
// int width = getMeasuredWidth();
// int height = getMeasuredHeight();
// TODO: padding?
int width = getWidth() - getPaddingLeft() - getPaddingRight();
int height = getHeight() - getPaddingTop() - getPaddingBottom();
int paddingLeft = getPaddingLeft();
int paddingTop = getPaddingTop();
// draw cells
int cellLeft, cellTop;
if (mCells != null) {
// TODO: why?
float numberAscent = mNumberPaint.ascent();
float noteAscent = mNotePaint.ascent();
float noteWidth = mCellWidth / 3f;
for (int row=0; row<9; row++) {
for (int col=0; col<9; col++) {
SudokuCell cell = mCells.getCell(row, col);
cellLeft = Math.round((col * mCellWidth) + paddingLeft);
cellTop = Math.round((row * mCellHeight) + paddingTop);
// draw read-only field background
if (!cell.getEditable()) {
canvas.drawRect(
cellLeft, cellTop,
cellLeft + mCellWidth, cellTop + mCellHeight,
mReadonlyPaint);
}
// draw cell Text
int value = cell.getValue();
if (value != 0) {
mNumberPaint.setColor(cell.getInvalid() ? Color.RED : Color.BLACK);
canvas.drawText(new Integer(value).toString(),
cellLeft + mNumberLeft,
Math.round(cellTop) + mNumberTop - numberAscent,
mNumberPaint);
} else {
// TODO: this is ugly temporary version
if (cell.hasNote()) {
Integer[] numbers = getNoteNumbers(cell.getNote());
int r = 0, c = 0;
if (numbers != null) {
for (Integer number : numbers) {
if (c == 3) {
r++;
c = 0;
}
canvas.drawText(number.toString(), cellLeft + c*noteWidth + 2, cellTop - noteAscent + r*noteWidth - 1, mNotePaint);
c++;
}
}
}
}
}
}
// highlight selected cell
if (!mReadonly && mSelectedCell != null) {
cellLeft = Math.round(mSelectedCell.getColumnIndex() * mCellWidth);
cellTop = Math.round(mSelectedCell.getRowIndex() * mCellHeight);
canvas.drawRect(
cellLeft, cellTop,
cellLeft + mCellWidth, cellTop + mCellHeight,
mSelectedPaint);
}
// visually highlight cell under the finger (to cope with touch screen
// imprecision)
if (mTouchedCell != null) {
cellLeft = Math.round(mTouchedCell.getColumnIndex() * mCellWidth);
cellTop = Math.round(mTouchedCell.getRowIndex() * mCellHeight);
canvas.drawRect(
cellLeft, 0,
cellLeft + mCellWidth, height,
mTouchedPaint);
canvas.drawRect(
0, cellTop,
width, cellTop + mCellHeight,
mTouchedPaint);
}
}
// draw vertical lines
for (int c=0; c <= 9; c++) {
float x = c * mCellWidth;
if (c % 3 == 0) {
canvas.drawRect(x-1, 0, x+1, height, mLinePaint);
} else {
canvas.drawLine(x, 0, x, height, mLinePaint);
}
}
// draw horizontal lines
for (int r=0; r <= 9; r++) {
float y = r * mCellHeight;
if (r % 3 == 0) {
canvas.drawRect(0, y-1, width, y+1, mLinePaint);
} else {
canvas.drawLine(0, y, width, y, mLinePaint);
}
}
}
|
diff --git a/src/main/java/de/cismet/cismap/commons/gui/metasearch/SearchTopic.java b/src/main/java/de/cismet/cismap/commons/gui/metasearch/SearchTopic.java
index dfd1681d..c315fbbd 100644
--- a/src/main/java/de/cismet/cismap/commons/gui/metasearch/SearchTopic.java
+++ b/src/main/java/de/cismet/cismap/commons/gui/metasearch/SearchTopic.java
@@ -1,233 +1,235 @@
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
package de.cismet.cismap.commons.gui.metasearch;
import org.apache.log4j.Logger;
import java.awt.event.ActionEvent;
import java.net.URL;
import java.util.Collection;
import java.util.LinkedHashSet;
import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
/**
* DOCUMENT ME!
*
* @author jweintraut
* @version $Revision$, $Date$
*/
public class SearchTopic extends AbstractAction implements Comparable<SearchTopic> {
//~ Static fields/initializers ---------------------------------------------
private static final Logger LOG = Logger.getLogger(SearchTopic.class);
private static final String PATH_TO_ICONS = "/de/cismet/cismap/commons/gui/metasearch/";
public static final String SELECTED = "selected";
//~ Instance fields --------------------------------------------------------
private Collection<SearchClass> searchClasses;
private String name;
private String description;
private String key;
private String iconName;
private ImageIcon icon;
private boolean selected;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new SearchTopic object.
*
* @param name DOCUMENT ME!
* @param description DOCUMENT ME!
* @param key DOCUMENT ME!
* @param iconName DOCUMENT ME!
* @param selected DOCUMENT ME!
*/
public SearchTopic(final String name,
final String description,
final String key,
final String iconName,
final boolean selected) {
this.name = name;
this.description = description;
this.key = key;
this.iconName = iconName;
this.selected = selected;
searchClasses = new LinkedHashSet<SearchClass>();
final URL urlToIcon = getClass().getResource(PATH_TO_ICONS + this.iconName);
if (urlToIcon != null) {
this.icon = new ImageIcon(urlToIcon);
putValue(SMALL_ICON, this.icon);
+ } else {
+ this.icon = new ImageIcon();
}
putValue(SHORT_DESCRIPTION, this.description);
putValue(ACTION_COMMAND_KEY, this.key);
putValue(NAME, this.name);
putValue(SELECTED_KEY, this.selected);
}
//~ Methods ----------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @param searchClass DOCUMENT ME!
*/
public void insert(final SearchClass searchClass) {
if (searchClass == null) {
return;
}
if (!searchClasses.contains(searchClass)) {
searchClasses.add(searchClass);
} else {
LOG.warn("Search class with domain '" + searchClass.getCidsDomain() + "' and table '"
+ searchClass.getCidsClass() + "' already exists in search topic '" + getName()
+ "'. The search class won't be added twice.");
}
}
@Override
public void actionPerformed(final ActionEvent event) {
if (event.getSource() instanceof AbstractButton) {
final boolean oldValue = selected;
selected = ((AbstractButton)event.getSource()).isSelected();
putValue(SELECTED_KEY, selected);
firePropertyChange(SELECTED, oldValue, selected);
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public String getDescription() {
return description;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public ImageIcon getIcon() {
return icon;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public String getIconName() {
return iconName;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public String getKey() {
return key;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public String getName() {
return name;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public Collection<SearchClass> getSearchClasses() {
return searchClasses;
}
/**
* DOCUMENT ME!
*
* @param selected DOCUMENT ME!
*/
void setSelected(final boolean selected) {
this.selected = selected;
putValue(SELECTED_KEY, this.selected);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isSelected() {
return selected;
}
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof SearchTopic)) {
return false;
}
final SearchTopic other = (SearchTopic)obj;
if ((this.name == null) ? (other.name != null) : (!this.name.equals(other.name))) {
return false;
}
if ((this.description == null) ? (other.description != null) : (!this.description.equals(other.description))) {
return false;
}
if ((this.key == null) ? (other.key != null) : (!this.key.equals(other.key))) {
return false;
}
if ((this.iconName == null) ? (other.iconName != null) : (!this.iconName.equals(other.iconName))) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = (11 * hash) + ((this.name != null) ? this.name.hashCode() : 0);
hash = (11 * hash) + ((this.description != null) ? this.description.hashCode() : 0);
hash = (11 * hash) + ((this.key != null) ? this.key.hashCode() : 0);
hash = (11 * hash) + ((this.iconName != null) ? this.iconName.hashCode() : 0);
return hash;
}
@Override
public int compareTo(final SearchTopic o) {
if (o == null) {
return 1;
}
return name.compareTo(o.name);
}
}
| true | true | public SearchTopic(final String name,
final String description,
final String key,
final String iconName,
final boolean selected) {
this.name = name;
this.description = description;
this.key = key;
this.iconName = iconName;
this.selected = selected;
searchClasses = new LinkedHashSet<SearchClass>();
final URL urlToIcon = getClass().getResource(PATH_TO_ICONS + this.iconName);
if (urlToIcon != null) {
this.icon = new ImageIcon(urlToIcon);
putValue(SMALL_ICON, this.icon);
}
putValue(SHORT_DESCRIPTION, this.description);
putValue(ACTION_COMMAND_KEY, this.key);
putValue(NAME, this.name);
putValue(SELECTED_KEY, this.selected);
}
| public SearchTopic(final String name,
final String description,
final String key,
final String iconName,
final boolean selected) {
this.name = name;
this.description = description;
this.key = key;
this.iconName = iconName;
this.selected = selected;
searchClasses = new LinkedHashSet<SearchClass>();
final URL urlToIcon = getClass().getResource(PATH_TO_ICONS + this.iconName);
if (urlToIcon != null) {
this.icon = new ImageIcon(urlToIcon);
putValue(SMALL_ICON, this.icon);
} else {
this.icon = new ImageIcon();
}
putValue(SHORT_DESCRIPTION, this.description);
putValue(ACTION_COMMAND_KEY, this.key);
putValue(NAME, this.name);
putValue(SELECTED_KEY, this.selected);
}
|
diff --git a/squeal/task/EnterGame.java b/squeal/task/EnterGame.java
index 712b6a1..b54e5ab 100644
--- a/squeal/task/EnterGame.java
+++ b/squeal/task/EnterGame.java
@@ -1,236 +1,236 @@
package squeal.task;
import java.awt.event.KeyEvent;
import java.util.Scanner;
import org.powerbot.concurrent.strategy.Strategy;
import org.powerbot.game.api.methods.Game;
import org.powerbot.game.api.methods.Widgets;
import org.powerbot.game.api.methods.input.Keyboard;
import org.powerbot.game.api.methods.tab.Inventory;
import org.powerbot.game.api.methods.widget.Lobby;
import org.powerbot.game.api.util.Time;
import squeal.Squeal;
public class EnterGame extends Strategy implements Runnable {
private boolean clientDead;
@Override
public void run() {
if(Squeal.isLogoutNeeded()) {
while(Game.isLoggedIn()) {
Game.logout(false);
Time.sleep(1000);
}
Squeal.setLogout(false);
}
clientDead = false;
if(!Lobby.isOpen() || !Lobby.getOpenDialog().isOpen()) {
- while(!Lobby.isOpen() && !clientDead) {
+ while(!Lobby.isOpen() && !clientDead && !Game.isLoggedIn() && Widgets.get(596, 70).isOnScreen()) {
getAccount();
clearDetails();
enterDetails();
attemptLog();
}
} else {
if(clientDead == false) {
while(!Game.isLoggedIn()) {
if(Lobby.enterGame()) {
//Method sometimes fails for some unknown reason.
Time.sleep(3000, 5000);
}
}
if(Widgets.get(1313, 11).isOnScreen()) {
Widgets.get(1313, 2).click(true);
}
if(Inventory.isFull()) {
if(Widgets.get(548, 159).click(true)) {
Time.sleep(100, 200);
if (Game.logout(false)) {
//Method sometimes fails.. The game fails to logout and the script stops for some currently unknown reason.
}
}
}
}
}
}
public void getAccount() {
try {
if(Squeal.anotherAccount()) {
String acc = Squeal.nextAccount();
System.out.println(acc);
Scanner manageAccount = new Scanner(acc);
manageAccount.useDelimiter(":");
String account = manageAccount.next();
System.out.println("Account: " + account);
if(manageAccount.hasNext()) {
String password = manageAccount.next();
Squeal.setPassword(password);
System.out.println("Pass: " + password);
} else {
Squeal.setPassword(Squeal.getGlobalPassword());
System.out.println("Pass: " + Squeal.getCurrentPassword());
}
Squeal.setAccount(account);
} else {
System.out.println("There are not anymore accounts");
Squeal.stopScript();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void clearDetails() {
while(Widgets.get(596, 70).getText().length() > 1) {
Widgets.get(596, 70).click(true);
Keyboard.sendKey((char)KeyEvent.VK_BACK_SPACE);
}
while(Widgets.get(596, 76).getText().length() > 1) {
Widgets.get(596, 76).click(true);
Keyboard.sendKey((char)KeyEvent.VK_BACK_SPACE);
}
}
public void enterDetails() {
if(Widgets.get(596, 70).click(true)) {
Time.sleep(100, 200);
Keyboard.sendText(Squeal.getCurrentAccount(), false);
}
if(Widgets.get(596, 76).click(true)) {
Time.sleep(100, 200);
Keyboard.sendText(Squeal.getCurrentPassword(), false);
}
}
public void attemptLog() {
if(Widgets.get(596, 57).click(true)) {
Time.sleep(3000, 5000);
if(Widgets.get(596, 13).getText().startsWith("Invalid")) {
System.out.println("Bad Login: " + Squeal.getCurrentAccount());
Widgets.get(596, 65).click(true);
}
if(Widgets.get(596, 13).getText().startsWith("Too many")) {
if(Widgets.get(596, 65).click(true)) {
System.out.println("Too many bad logins, waiting 5 minutes.");
Time.sleep(3000 * 100);
}
}
if(Widgets.get(596, 13).getText().startsWith("Your game")) {
//I need a method to make the client restart.
//Widgets.get(596, 65).click(true);
//We are now forcing the client into its anti-random mode.
clientDead = true;
System.out.println("Crash Prevented.");
}
}
}
public boolean validate() {
return !Game.isLoggedIn() || Squeal.isLogoutNeeded();
}
}
| true | true | public void run() {
if(Squeal.isLogoutNeeded()) {
while(Game.isLoggedIn()) {
Game.logout(false);
Time.sleep(1000);
}
Squeal.setLogout(false);
}
clientDead = false;
if(!Lobby.isOpen() || !Lobby.getOpenDialog().isOpen()) {
while(!Lobby.isOpen() && !clientDead) {
getAccount();
clearDetails();
enterDetails();
attemptLog();
}
} else {
if(clientDead == false) {
while(!Game.isLoggedIn()) {
if(Lobby.enterGame()) {
//Method sometimes fails for some unknown reason.
Time.sleep(3000, 5000);
}
}
if(Widgets.get(1313, 11).isOnScreen()) {
Widgets.get(1313, 2).click(true);
}
if(Inventory.isFull()) {
if(Widgets.get(548, 159).click(true)) {
Time.sleep(100, 200);
if (Game.logout(false)) {
//Method sometimes fails.. The game fails to logout and the script stops for some currently unknown reason.
}
}
}
}
}
}
| public void run() {
if(Squeal.isLogoutNeeded()) {
while(Game.isLoggedIn()) {
Game.logout(false);
Time.sleep(1000);
}
Squeal.setLogout(false);
}
clientDead = false;
if(!Lobby.isOpen() || !Lobby.getOpenDialog().isOpen()) {
while(!Lobby.isOpen() && !clientDead && !Game.isLoggedIn() && Widgets.get(596, 70).isOnScreen()) {
getAccount();
clearDetails();
enterDetails();
attemptLog();
}
} else {
if(clientDead == false) {
while(!Game.isLoggedIn()) {
if(Lobby.enterGame()) {
//Method sometimes fails for some unknown reason.
Time.sleep(3000, 5000);
}
}
if(Widgets.get(1313, 11).isOnScreen()) {
Widgets.get(1313, 2).click(true);
}
if(Inventory.isFull()) {
if(Widgets.get(548, 159).click(true)) {
Time.sleep(100, 200);
if (Game.logout(false)) {
//Method sometimes fails.. The game fails to logout and the script stops for some currently unknown reason.
}
}
}
}
}
}
|
diff --git a/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/dom/AST.java b/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/dom/AST.java
index f12d8af75..72b665473 100644
--- a/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/dom/AST.java
+++ b/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/dom/AST.java
@@ -1,243 +1,243 @@
/*
* Copyright (c) 2012, the Dart project authors.
*
* Licensed under the Eclipse Public License v1.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/epl-v10.html
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.dart.tools.core.dom;
import com.google.dart.compiler.ast.DartArrayAccess;
import com.google.dart.compiler.ast.DartArrayLiteral;
import com.google.dart.compiler.ast.DartBinaryExpression;
import com.google.dart.compiler.ast.DartBlock;
import com.google.dart.compiler.ast.DartBooleanLiteral;
import com.google.dart.compiler.ast.DartBreakStatement;
import com.google.dart.compiler.ast.DartCase;
import com.google.dart.compiler.ast.DartCatchBlock;
import com.google.dart.compiler.ast.DartClass;
import com.google.dart.compiler.ast.DartComment;
import com.google.dart.compiler.ast.DartConditional;
import com.google.dart.compiler.ast.DartContinueStatement;
import com.google.dart.compiler.ast.DartDefault;
import com.google.dart.compiler.ast.DartDoWhileStatement;
import com.google.dart.compiler.ast.DartDoubleLiteral;
import com.google.dart.compiler.ast.DartEmptyStatement;
import com.google.dart.compiler.ast.DartExprStmt;
import com.google.dart.compiler.ast.DartExpression;
import com.google.dart.compiler.ast.DartField;
import com.google.dart.compiler.ast.DartFieldDefinition;
import com.google.dart.compiler.ast.DartForStatement;
import com.google.dart.compiler.ast.DartFunction;
import com.google.dart.compiler.ast.DartFunctionExpression;
import com.google.dart.compiler.ast.DartFunctionObjectInvocation;
import com.google.dart.compiler.ast.DartFunctionTypeAlias;
import com.google.dart.compiler.ast.DartIdentifier;
import com.google.dart.compiler.ast.DartIfStatement;
import com.google.dart.compiler.ast.DartInitializer;
import com.google.dart.compiler.ast.DartLabel;
import com.google.dart.compiler.ast.DartMapLiteral;
import com.google.dart.compiler.ast.DartMapLiteralEntry;
import com.google.dart.compiler.ast.DartMethodDefinition;
import com.google.dart.compiler.ast.DartMethodInvocation;
import com.google.dart.compiler.ast.DartNativeBlock;
import com.google.dart.compiler.ast.DartNewExpression;
import com.google.dart.compiler.ast.DartNode;
import com.google.dart.compiler.ast.DartNullLiteral;
import com.google.dart.compiler.ast.DartParameter;
import com.google.dart.compiler.ast.DartParenthesizedExpression;
import com.google.dart.compiler.ast.DartPropertyAccess;
import com.google.dart.compiler.ast.DartReturnStatement;
import com.google.dart.compiler.ast.DartStatement;
import com.google.dart.compiler.ast.DartStringInterpolation;
import com.google.dart.compiler.ast.DartStringLiteral;
import com.google.dart.compiler.ast.DartSuperConstructorInvocation;
import com.google.dart.compiler.ast.DartSuperExpression;
import com.google.dart.compiler.ast.DartSwitchMember;
import com.google.dart.compiler.ast.DartSwitchStatement;
import com.google.dart.compiler.ast.DartThisExpression;
import com.google.dart.compiler.ast.DartThrowStatement;
import com.google.dart.compiler.ast.DartTryStatement;
import com.google.dart.compiler.ast.DartTypeExpression;
import com.google.dart.compiler.ast.DartTypeNode;
import com.google.dart.compiler.ast.DartTypeParameter;
import com.google.dart.compiler.ast.DartUnaryExpression;
import com.google.dart.compiler.ast.DartUnit;
import com.google.dart.compiler.ast.DartUnqualifiedInvocation;
import com.google.dart.compiler.ast.DartVariable;
import com.google.dart.compiler.ast.DartVariableStatement;
import com.google.dart.compiler.ast.DartWhileStatement;
import com.google.dart.compiler.ast.Modifiers;
import com.google.dart.tools.core.DartCore;
import java.util.ArrayList;
/**
* Instances of the class <code>AST</code>
*/
public class AST {
/**
* Create a new node with the given type.
*
* @param nodeClass the class of the node to be created
* @return the node that was created
*/
@SuppressWarnings("unchecked")
public <N extends DartNode> N createInstance(Class<N> nodeClass) {
if (nodeClass == DartArrayAccess.class) {
return (N) new DartArrayAccess(null, null);
} else if (nodeClass == DartArrayLiteral.class) {
return (N) new DartArrayLiteral(false, null, new ArrayList<DartExpression>());
} else if (nodeClass == DartBinaryExpression.class) {
- return (N) new DartBinaryExpression(null, null, null);
+ return (N) new DartBinaryExpression(null, 0, null, null);
} else if (nodeClass == DartBlock.class) {
return (N) new DartBlock(new ArrayList<DartStatement>());
} else if (nodeClass == DartBooleanLiteral.class) {
return (N) DartBooleanLiteral.get(false);
} else if (nodeClass == DartBreakStatement.class) {
return (N) new DartBreakStatement(null);
} else if (nodeClass == DartCase.class) {
return (N) new DartCase(null, null, new ArrayList<DartStatement>());
} else if (nodeClass == DartCatchBlock.class) {
return (N) new DartCatchBlock(null, null, null);
} else if (nodeClass == DartClass.class) {
return (N) new DartClass(
null,
null,
null,
new ArrayList<DartTypeNode>(),
new ArrayList<DartNode>(),
new ArrayList<DartTypeParameter>(),
null,
false,
Modifiers.NONE);
} else if (nodeClass == DartComment.class) {
return (N) new DartComment(null, 0, 0, 0, 0, null);
} else if (nodeClass == DartConditional.class) {
return (N) new DartConditional(null, null, null);
} else if (nodeClass == DartContinueStatement.class) {
return (N) new DartContinueStatement(null);
} else if (nodeClass == DartDefault.class) {
return (N) new DartDefault(null, new ArrayList<DartStatement>());
} else if (nodeClass == DartDoubleLiteral.class) {
return (N) DartDoubleLiteral.get(0.0);
} else if (nodeClass == DartDoWhileStatement.class) {
return (N) new DartDoWhileStatement(null, null);
} else if (nodeClass == DartEmptyStatement.class) {
return (N) new DartEmptyStatement();
} else if (nodeClass == DartExprStmt.class) {
return (N) new DartExprStmt(null);
} else if (nodeClass == DartField.class) {
return (N) new DartField(null, null, null, null);
} else if (nodeClass == DartFieldDefinition.class) {
return (N) new DartFieldDefinition(null, new ArrayList<DartField>());
} else if (nodeClass == DartForStatement.class) {
return (N) new DartForStatement(null, null, null, null);
} else if (nodeClass == DartFunction.class) {
return (N) new DartFunction(new ArrayList<DartParameter>(), null, null);
} else if (nodeClass == DartFunctionExpression.class) {
return (N) new DartFunctionExpression(null, null, false);
} else if (nodeClass == DartFunctionObjectInvocation.class) {
return (N) new DartFunctionObjectInvocation(null, new ArrayList<DartExpression>());
} else if (nodeClass == DartFunctionTypeAlias.class) {
return (N) new DartFunctionTypeAlias(
null,
null,
new ArrayList<DartParameter>(),
new ArrayList<DartTypeParameter>());
} else if (nodeClass == DartIdentifier.class) {
return (N) new DartIdentifier("");
} else if (nodeClass == DartIfStatement.class) {
return (N) new DartIfStatement(null, null, null);
} else if (nodeClass == DartInitializer.class) {
return (N) new DartInitializer(null, null);
} else if (nodeClass == DartLabel.class) {
return (N) new DartLabel(null, null);
} else if (nodeClass == DartMapLiteral.class) {
return (N) new DartMapLiteral(false, null, new ArrayList<DartMapLiteralEntry>());
} else if (nodeClass == DartMapLiteralEntry.class) {
return (N) new DartMapLiteralEntry(null, null);
} else if (nodeClass == DartMethodDefinition.class) {
return (N) DartMethodDefinition.create(null, null, null, null);
} else if (nodeClass == DartMethodInvocation.class) {
return (N) new DartMethodInvocation(null, null, new ArrayList<DartExpression>());
} else if (nodeClass == DartNativeBlock.class) {
return (N) new DartNativeBlock();
} else if (nodeClass == DartNewExpression.class) {
return (N) new DartNewExpression(null, new ArrayList<DartExpression>(), false);
} else if (nodeClass == DartNullLiteral.class) {
return (N) DartNullLiteral.get();
} else if (nodeClass == DartParameter.class) {
return (N) new DartParameter(null, null, new ArrayList<DartParameter>(), null, Modifiers.NONE);
} else if (nodeClass == DartParenthesizedExpression.class) {
return (N) new DartParenthesizedExpression(null);
} else if (nodeClass == DartPropertyAccess.class) {
return (N) new DartPropertyAccess(null, null);
} else if (nodeClass == DartReturnStatement.class) {
return (N) new DartReturnStatement(null);
} else if (nodeClass == DartStringInterpolation.class) {
return (N) new DartStringInterpolation(
new ArrayList<DartStringLiteral>(),
new ArrayList<DartExpression>());
} else if (nodeClass == DartStringLiteral.class) {
return (N) DartStringLiteral.get("");
} else if (nodeClass == DartSuperConstructorInvocation.class) {
return (N) new DartSuperConstructorInvocation(null, new ArrayList<DartExpression>());
} else if (nodeClass == DartSuperExpression.class) {
return (N) DartSuperExpression.get();
} else if (nodeClass == DartSwitchStatement.class) {
return (N) new DartSwitchStatement(null, new ArrayList<DartSwitchMember>());
} else if (nodeClass == DartThisExpression.class) {
return (N) DartThisExpression.get();
} else if (nodeClass == DartThrowStatement.class) {
return (N) new DartThrowStatement(null);
} else if (nodeClass == DartTryStatement.class) {
return (N) new DartTryStatement(null, new ArrayList<DartCatchBlock>(), null);
} else if (nodeClass == DartTypeExpression.class) {
return (N) new DartTypeExpression(null);
} else if (nodeClass == DartTypeNode.class) {
return (N) new DartTypeNode(null, new ArrayList<DartTypeNode>());
} else if (nodeClass == DartTypeParameter.class) {
return (N) new DartTypeParameter(null, null);
} else if (nodeClass == DartUnaryExpression.class) {
return (N) new DartUnaryExpression(null, null, true);
} else if (nodeClass == DartUnit.class) {
return (N) new DartUnit(null, false);
} else if (nodeClass == DartUnqualifiedInvocation.class) {
return (N) new DartUnqualifiedInvocation(null, new ArrayList<DartExpression>());
} else if (nodeClass == DartVariable.class) {
return (N) new DartVariable(null, null);
} else if (nodeClass == DartVariableStatement.class) {
return (N) new DartVariableStatement(new ArrayList<DartVariable>(), null);
} else if (nodeClass == DartWhileStatement.class) {
return (N) new DartWhileStatement(null, null);
}
return null;
}
/**
* Create a new node with the given type.
*
* @param nodeType the type of the node to be created
* @return the node that was created
*/
public DartNode createInstance(int nodeType) {
DartCore.notYetImplemented();
return null;
}
/**
* Create a new block with an empty list of statements.
*
* @return the block that was created
*/
public DartBlock newBlock() {
return new DartBlock(new ArrayList<DartStatement>());
}
}
| true | true | public <N extends DartNode> N createInstance(Class<N> nodeClass) {
if (nodeClass == DartArrayAccess.class) {
return (N) new DartArrayAccess(null, null);
} else if (nodeClass == DartArrayLiteral.class) {
return (N) new DartArrayLiteral(false, null, new ArrayList<DartExpression>());
} else if (nodeClass == DartBinaryExpression.class) {
return (N) new DartBinaryExpression(null, null, null);
} else if (nodeClass == DartBlock.class) {
return (N) new DartBlock(new ArrayList<DartStatement>());
} else if (nodeClass == DartBooleanLiteral.class) {
return (N) DartBooleanLiteral.get(false);
} else if (nodeClass == DartBreakStatement.class) {
return (N) new DartBreakStatement(null);
} else if (nodeClass == DartCase.class) {
return (N) new DartCase(null, null, new ArrayList<DartStatement>());
} else if (nodeClass == DartCatchBlock.class) {
return (N) new DartCatchBlock(null, null, null);
} else if (nodeClass == DartClass.class) {
return (N) new DartClass(
null,
null,
null,
new ArrayList<DartTypeNode>(),
new ArrayList<DartNode>(),
new ArrayList<DartTypeParameter>(),
null,
false,
Modifiers.NONE);
} else if (nodeClass == DartComment.class) {
return (N) new DartComment(null, 0, 0, 0, 0, null);
} else if (nodeClass == DartConditional.class) {
return (N) new DartConditional(null, null, null);
} else if (nodeClass == DartContinueStatement.class) {
return (N) new DartContinueStatement(null);
} else if (nodeClass == DartDefault.class) {
return (N) new DartDefault(null, new ArrayList<DartStatement>());
} else if (nodeClass == DartDoubleLiteral.class) {
return (N) DartDoubleLiteral.get(0.0);
} else if (nodeClass == DartDoWhileStatement.class) {
return (N) new DartDoWhileStatement(null, null);
} else if (nodeClass == DartEmptyStatement.class) {
return (N) new DartEmptyStatement();
} else if (nodeClass == DartExprStmt.class) {
return (N) new DartExprStmt(null);
} else if (nodeClass == DartField.class) {
return (N) new DartField(null, null, null, null);
} else if (nodeClass == DartFieldDefinition.class) {
return (N) new DartFieldDefinition(null, new ArrayList<DartField>());
} else if (nodeClass == DartForStatement.class) {
return (N) new DartForStatement(null, null, null, null);
} else if (nodeClass == DartFunction.class) {
return (N) new DartFunction(new ArrayList<DartParameter>(), null, null);
} else if (nodeClass == DartFunctionExpression.class) {
return (N) new DartFunctionExpression(null, null, false);
} else if (nodeClass == DartFunctionObjectInvocation.class) {
return (N) new DartFunctionObjectInvocation(null, new ArrayList<DartExpression>());
} else if (nodeClass == DartFunctionTypeAlias.class) {
return (N) new DartFunctionTypeAlias(
null,
null,
new ArrayList<DartParameter>(),
new ArrayList<DartTypeParameter>());
} else if (nodeClass == DartIdentifier.class) {
return (N) new DartIdentifier("");
} else if (nodeClass == DartIfStatement.class) {
return (N) new DartIfStatement(null, null, null);
} else if (nodeClass == DartInitializer.class) {
return (N) new DartInitializer(null, null);
} else if (nodeClass == DartLabel.class) {
return (N) new DartLabel(null, null);
} else if (nodeClass == DartMapLiteral.class) {
return (N) new DartMapLiteral(false, null, new ArrayList<DartMapLiteralEntry>());
} else if (nodeClass == DartMapLiteralEntry.class) {
return (N) new DartMapLiteralEntry(null, null);
} else if (nodeClass == DartMethodDefinition.class) {
return (N) DartMethodDefinition.create(null, null, null, null);
} else if (nodeClass == DartMethodInvocation.class) {
return (N) new DartMethodInvocation(null, null, new ArrayList<DartExpression>());
} else if (nodeClass == DartNativeBlock.class) {
return (N) new DartNativeBlock();
} else if (nodeClass == DartNewExpression.class) {
return (N) new DartNewExpression(null, new ArrayList<DartExpression>(), false);
} else if (nodeClass == DartNullLiteral.class) {
return (N) DartNullLiteral.get();
} else if (nodeClass == DartParameter.class) {
return (N) new DartParameter(null, null, new ArrayList<DartParameter>(), null, Modifiers.NONE);
} else if (nodeClass == DartParenthesizedExpression.class) {
return (N) new DartParenthesizedExpression(null);
} else if (nodeClass == DartPropertyAccess.class) {
return (N) new DartPropertyAccess(null, null);
} else if (nodeClass == DartReturnStatement.class) {
return (N) new DartReturnStatement(null);
} else if (nodeClass == DartStringInterpolation.class) {
return (N) new DartStringInterpolation(
new ArrayList<DartStringLiteral>(),
new ArrayList<DartExpression>());
} else if (nodeClass == DartStringLiteral.class) {
return (N) DartStringLiteral.get("");
} else if (nodeClass == DartSuperConstructorInvocation.class) {
return (N) new DartSuperConstructorInvocation(null, new ArrayList<DartExpression>());
} else if (nodeClass == DartSuperExpression.class) {
return (N) DartSuperExpression.get();
} else if (nodeClass == DartSwitchStatement.class) {
return (N) new DartSwitchStatement(null, new ArrayList<DartSwitchMember>());
} else if (nodeClass == DartThisExpression.class) {
return (N) DartThisExpression.get();
} else if (nodeClass == DartThrowStatement.class) {
return (N) new DartThrowStatement(null);
} else if (nodeClass == DartTryStatement.class) {
return (N) new DartTryStatement(null, new ArrayList<DartCatchBlock>(), null);
} else if (nodeClass == DartTypeExpression.class) {
return (N) new DartTypeExpression(null);
} else if (nodeClass == DartTypeNode.class) {
return (N) new DartTypeNode(null, new ArrayList<DartTypeNode>());
} else if (nodeClass == DartTypeParameter.class) {
return (N) new DartTypeParameter(null, null);
} else if (nodeClass == DartUnaryExpression.class) {
return (N) new DartUnaryExpression(null, null, true);
} else if (nodeClass == DartUnit.class) {
return (N) new DartUnit(null, false);
} else if (nodeClass == DartUnqualifiedInvocation.class) {
return (N) new DartUnqualifiedInvocation(null, new ArrayList<DartExpression>());
} else if (nodeClass == DartVariable.class) {
return (N) new DartVariable(null, null);
} else if (nodeClass == DartVariableStatement.class) {
return (N) new DartVariableStatement(new ArrayList<DartVariable>(), null);
} else if (nodeClass == DartWhileStatement.class) {
return (N) new DartWhileStatement(null, null);
}
return null;
}
| public <N extends DartNode> N createInstance(Class<N> nodeClass) {
if (nodeClass == DartArrayAccess.class) {
return (N) new DartArrayAccess(null, null);
} else if (nodeClass == DartArrayLiteral.class) {
return (N) new DartArrayLiteral(false, null, new ArrayList<DartExpression>());
} else if (nodeClass == DartBinaryExpression.class) {
return (N) new DartBinaryExpression(null, 0, null, null);
} else if (nodeClass == DartBlock.class) {
return (N) new DartBlock(new ArrayList<DartStatement>());
} else if (nodeClass == DartBooleanLiteral.class) {
return (N) DartBooleanLiteral.get(false);
} else if (nodeClass == DartBreakStatement.class) {
return (N) new DartBreakStatement(null);
} else if (nodeClass == DartCase.class) {
return (N) new DartCase(null, null, new ArrayList<DartStatement>());
} else if (nodeClass == DartCatchBlock.class) {
return (N) new DartCatchBlock(null, null, null);
} else if (nodeClass == DartClass.class) {
return (N) new DartClass(
null,
null,
null,
new ArrayList<DartTypeNode>(),
new ArrayList<DartNode>(),
new ArrayList<DartTypeParameter>(),
null,
false,
Modifiers.NONE);
} else if (nodeClass == DartComment.class) {
return (N) new DartComment(null, 0, 0, 0, 0, null);
} else if (nodeClass == DartConditional.class) {
return (N) new DartConditional(null, null, null);
} else if (nodeClass == DartContinueStatement.class) {
return (N) new DartContinueStatement(null);
} else if (nodeClass == DartDefault.class) {
return (N) new DartDefault(null, new ArrayList<DartStatement>());
} else if (nodeClass == DartDoubleLiteral.class) {
return (N) DartDoubleLiteral.get(0.0);
} else if (nodeClass == DartDoWhileStatement.class) {
return (N) new DartDoWhileStatement(null, null);
} else if (nodeClass == DartEmptyStatement.class) {
return (N) new DartEmptyStatement();
} else if (nodeClass == DartExprStmt.class) {
return (N) new DartExprStmt(null);
} else if (nodeClass == DartField.class) {
return (N) new DartField(null, null, null, null);
} else if (nodeClass == DartFieldDefinition.class) {
return (N) new DartFieldDefinition(null, new ArrayList<DartField>());
} else if (nodeClass == DartForStatement.class) {
return (N) new DartForStatement(null, null, null, null);
} else if (nodeClass == DartFunction.class) {
return (N) new DartFunction(new ArrayList<DartParameter>(), null, null);
} else if (nodeClass == DartFunctionExpression.class) {
return (N) new DartFunctionExpression(null, null, false);
} else if (nodeClass == DartFunctionObjectInvocation.class) {
return (N) new DartFunctionObjectInvocation(null, new ArrayList<DartExpression>());
} else if (nodeClass == DartFunctionTypeAlias.class) {
return (N) new DartFunctionTypeAlias(
null,
null,
new ArrayList<DartParameter>(),
new ArrayList<DartTypeParameter>());
} else if (nodeClass == DartIdentifier.class) {
return (N) new DartIdentifier("");
} else if (nodeClass == DartIfStatement.class) {
return (N) new DartIfStatement(null, null, null);
} else if (nodeClass == DartInitializer.class) {
return (N) new DartInitializer(null, null);
} else if (nodeClass == DartLabel.class) {
return (N) new DartLabel(null, null);
} else if (nodeClass == DartMapLiteral.class) {
return (N) new DartMapLiteral(false, null, new ArrayList<DartMapLiteralEntry>());
} else if (nodeClass == DartMapLiteralEntry.class) {
return (N) new DartMapLiteralEntry(null, null);
} else if (nodeClass == DartMethodDefinition.class) {
return (N) DartMethodDefinition.create(null, null, null, null);
} else if (nodeClass == DartMethodInvocation.class) {
return (N) new DartMethodInvocation(null, null, new ArrayList<DartExpression>());
} else if (nodeClass == DartNativeBlock.class) {
return (N) new DartNativeBlock();
} else if (nodeClass == DartNewExpression.class) {
return (N) new DartNewExpression(null, new ArrayList<DartExpression>(), false);
} else if (nodeClass == DartNullLiteral.class) {
return (N) DartNullLiteral.get();
} else if (nodeClass == DartParameter.class) {
return (N) new DartParameter(null, null, new ArrayList<DartParameter>(), null, Modifiers.NONE);
} else if (nodeClass == DartParenthesizedExpression.class) {
return (N) new DartParenthesizedExpression(null);
} else if (nodeClass == DartPropertyAccess.class) {
return (N) new DartPropertyAccess(null, null);
} else if (nodeClass == DartReturnStatement.class) {
return (N) new DartReturnStatement(null);
} else if (nodeClass == DartStringInterpolation.class) {
return (N) new DartStringInterpolation(
new ArrayList<DartStringLiteral>(),
new ArrayList<DartExpression>());
} else if (nodeClass == DartStringLiteral.class) {
return (N) DartStringLiteral.get("");
} else if (nodeClass == DartSuperConstructorInvocation.class) {
return (N) new DartSuperConstructorInvocation(null, new ArrayList<DartExpression>());
} else if (nodeClass == DartSuperExpression.class) {
return (N) DartSuperExpression.get();
} else if (nodeClass == DartSwitchStatement.class) {
return (N) new DartSwitchStatement(null, new ArrayList<DartSwitchMember>());
} else if (nodeClass == DartThisExpression.class) {
return (N) DartThisExpression.get();
} else if (nodeClass == DartThrowStatement.class) {
return (N) new DartThrowStatement(null);
} else if (nodeClass == DartTryStatement.class) {
return (N) new DartTryStatement(null, new ArrayList<DartCatchBlock>(), null);
} else if (nodeClass == DartTypeExpression.class) {
return (N) new DartTypeExpression(null);
} else if (nodeClass == DartTypeNode.class) {
return (N) new DartTypeNode(null, new ArrayList<DartTypeNode>());
} else if (nodeClass == DartTypeParameter.class) {
return (N) new DartTypeParameter(null, null);
} else if (nodeClass == DartUnaryExpression.class) {
return (N) new DartUnaryExpression(null, null, true);
} else if (nodeClass == DartUnit.class) {
return (N) new DartUnit(null, false);
} else if (nodeClass == DartUnqualifiedInvocation.class) {
return (N) new DartUnqualifiedInvocation(null, new ArrayList<DartExpression>());
} else if (nodeClass == DartVariable.class) {
return (N) new DartVariable(null, null);
} else if (nodeClass == DartVariableStatement.class) {
return (N) new DartVariableStatement(new ArrayList<DartVariable>(), null);
} else if (nodeClass == DartWhileStatement.class) {
return (N) new DartWhileStatement(null, null);
}
return null;
}
|
diff --git a/src/pro/oneredpixel/deflektorclassic/LevelsState.java b/src/pro/oneredpixel/deflektorclassic/LevelsState.java
index eae3c3d..2246021 100644
--- a/src/pro/oneredpixel/deflektorclassic/LevelsState.java
+++ b/src/pro/oneredpixel/deflektorclassic/LevelsState.java
@@ -1,105 +1,105 @@
package pro.oneredpixel.deflektorclassic;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class LevelsState extends State {
int page=-1;
int maxpage = -1;
int savedUnlockedLevel = -1;
LevelsState(Deflektor defl) {
super(defl);
// TODO Auto-generated constructor stub
}
//init state for showing
void start() {
maxpage = app.unlockedLevel/20+1;
if (maxpage>3) maxpage=3;
if (savedUnlockedLevel!=app.unlockedLevel) {
savedUnlockedLevel=app.unlockedLevel;
page = app.unlockedLevel/20+1;
if (page>3) page=3;
};
};
public boolean tap(float x, float y, int tapCount, int button) {
//app.gotoAppState(Deflektor.APPSTATE_GAME);
int ix=(int)((x-app.winX)/app.sprScale);
int iy=(int)((y-app.winY)/app.sprScale);
if ((ix>=0) && (ix<240) && (iy>=0) && (iy<160)) {
if ((page>1) && checkInBox(ix,iy,0,160/2-8-8,32,32)) {
page--;
app.playSound(Deflektor.SND_TAP);
};
if ((page<maxpage) && checkInBox(ix,iy,240-16-8-8-8, 160/2-8,32,32)) {
page++;
app.playSound(Deflektor.SND_TAP);
}
int lx=(ix-44)/8;
int ly=(iy-20)/8;
- if ( ((lx&3)!=3) && ((ly&3)!=3) ) {
+ if ( ((lx&3)!=3) && ((ly&3)!=3) && (ix>=44) && (iy>=20)) {
lx=lx/4; ly=ly/4;
int lev=ly*5+lx+(page-1)*20+1;
if ((lx>=0) && (lx<5) && (ly>=0) && (ly<4) && (lev<=app.unlockedLevel)) {
app.playingLevel = lev;
app.gotoAppState(Deflektor.APPSTATE_GAME);
app.playSound(Deflektor.SND_TAP);
};
}
if (checkInBox(ix,iy,8, 160-8-16,16,16)) {
app.gotoAppState(Deflektor.APPSTATE_MENU);
app.playSound(Deflektor.SND_TAP);
}
}
return false;
}
public boolean keyUp(int k) {
if (k==Keys.BACK) {
app.gotoAppState(Deflektor.APPSTATE_MENU);
app.playSound(Deflektor.SND_TAP);
return true;
};
return false;
}
boolean checkInBox(int x,int y, int bx, int by, int bwidth, int bheight) {
return (x>=bx)&&(x<(bx+bwidth))&&(y>=by)&&(y<(by+bheight));
};
public void render(SpriteBatch batch) {
batch.setProjectionMatrix(app.camera.combined);
batch.begin();
app.showString((240-8*14)/2, 8, "SELECT A LEVEL");
int s=(page-1)*20+1;
for (int i=0;i<4;i++) {
for (int j=0;j<5;j++) {
drawLevelBox(44+j*32,20+i*32,s++);
if (s>app.countOfLevels) break;
};
if (s>app.countOfLevels) break;
};
if (page>1) app.spr_putRegion(8, 160/2-8, 16, 16, 64,160);
if (page<maxpage) app.spr_putRegion(240-8-16, 160/2-8, 16, 16, 80, 160);
app.spr_putRegion(8, 160-8-16, 16, 16, 96, 160);
batch.end();
};
void drawLevelBox(int x, int y, int levelNumber) {
app.spr_putRegion(x, y, 24, 24, 0,32+144);
app.showBigNumber(x+4,y+8,levelNumber);
if (app.unlockedLevel<levelNumber) app.spr_putRegion(x+15, y+15, 8, 8, 48,192);
};
}
| true | true | public boolean tap(float x, float y, int tapCount, int button) {
//app.gotoAppState(Deflektor.APPSTATE_GAME);
int ix=(int)((x-app.winX)/app.sprScale);
int iy=(int)((y-app.winY)/app.sprScale);
if ((ix>=0) && (ix<240) && (iy>=0) && (iy<160)) {
if ((page>1) && checkInBox(ix,iy,0,160/2-8-8,32,32)) {
page--;
app.playSound(Deflektor.SND_TAP);
};
if ((page<maxpage) && checkInBox(ix,iy,240-16-8-8-8, 160/2-8,32,32)) {
page++;
app.playSound(Deflektor.SND_TAP);
}
int lx=(ix-44)/8;
int ly=(iy-20)/8;
if ( ((lx&3)!=3) && ((ly&3)!=3) ) {
lx=lx/4; ly=ly/4;
int lev=ly*5+lx+(page-1)*20+1;
if ((lx>=0) && (lx<5) && (ly>=0) && (ly<4) && (lev<=app.unlockedLevel)) {
app.playingLevel = lev;
app.gotoAppState(Deflektor.APPSTATE_GAME);
app.playSound(Deflektor.SND_TAP);
};
}
if (checkInBox(ix,iy,8, 160-8-16,16,16)) {
app.gotoAppState(Deflektor.APPSTATE_MENU);
app.playSound(Deflektor.SND_TAP);
}
}
return false;
}
| public boolean tap(float x, float y, int tapCount, int button) {
//app.gotoAppState(Deflektor.APPSTATE_GAME);
int ix=(int)((x-app.winX)/app.sprScale);
int iy=(int)((y-app.winY)/app.sprScale);
if ((ix>=0) && (ix<240) && (iy>=0) && (iy<160)) {
if ((page>1) && checkInBox(ix,iy,0,160/2-8-8,32,32)) {
page--;
app.playSound(Deflektor.SND_TAP);
};
if ((page<maxpage) && checkInBox(ix,iy,240-16-8-8-8, 160/2-8,32,32)) {
page++;
app.playSound(Deflektor.SND_TAP);
}
int lx=(ix-44)/8;
int ly=(iy-20)/8;
if ( ((lx&3)!=3) && ((ly&3)!=3) && (ix>=44) && (iy>=20)) {
lx=lx/4; ly=ly/4;
int lev=ly*5+lx+(page-1)*20+1;
if ((lx>=0) && (lx<5) && (ly>=0) && (ly<4) && (lev<=app.unlockedLevel)) {
app.playingLevel = lev;
app.gotoAppState(Deflektor.APPSTATE_GAME);
app.playSound(Deflektor.SND_TAP);
};
}
if (checkInBox(ix,iy,8, 160-8-16,16,16)) {
app.gotoAppState(Deflektor.APPSTATE_MENU);
app.playSound(Deflektor.SND_TAP);
}
}
return false;
}
|
diff --git a/src/mmode/Commands.java b/src/mmode/Commands.java
index 48e1725..d767985 100644
--- a/src/mmode/Commands.java
+++ b/src/mmode/Commands.java
@@ -1,121 +1,121 @@
/**
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
package mmode;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.command.RemoteConsoleCommandSender;
import org.bukkit.entity.Player;
public class Commands implements CommandExecutor {
private Config config;
public Commands(Config config)
{
this.config = config;
}
@Override
public boolean onCommand(CommandSender sender, Command arg1, String arg2,
String[] args) {
//check permissions
if (!hasPerm(sender))
{
sender.sendMessage(ColorParser.parseColor("&4You don't have permission to do this"));
return true;
}
//handle command
if (args.length == 1 && args[0].equalsIgnoreCase("on"))
{
config.mmodeEnabled = true;
if (config.allowedlistEnabled && config.kickOnEnable) {
for (Player p :Bukkit.getOnlinePlayers())
{
if (!config.mmodeAllowedList.contains(p.getName()))
{
p.kickPlayer(ColorParser.parseColor(config.kickMessage));
}
}
}
sender.sendMessage(ColorParser.parseColor("&9Maintenance mode on"));
return true;
} else
if (args.length == 1 && args[0].equalsIgnoreCase("off"))
{
config.mmodeEnabled = false;
sender.sendMessage(ColorParser.parseColor("&9Maintenance mode off"));
return true;
} else
if (args.length == 1 && args[0].equalsIgnoreCase("reload"))
{
config.loadConfig();
sender.sendMessage(ColorParser.parseColor("&9Config reloaded"));
return true;
} else
if ((args.length == 2 || args.length == 3) && args[0].equalsIgnoreCase("alist"))
{
if (args.length == 2)
{
if (args[1].equalsIgnoreCase("on")) {
config.allowedlistEnabled = true;
config.saveConfig();
sender.sendMessage(ColorParser.parseColor("&9Allowed list enabled"));
return true;
- } else if (args[1].equalsIgnoreCase("on")) {
+ } else if (args[1].equalsIgnoreCase("off")) {
config.allowedlistEnabled = false;
config.saveConfig();
- sender.sendMessage(ColorParser.parseColor("&9Allowed list enabled"));
+ sender.sendMessage(ColorParser.parseColor("&9Allowed list disabled"));
return true;
}
} else
if (args.length == 3)
{
if (args[1].equalsIgnoreCase("add")) {
config.mmodeAllowedList.add(args[2]);
config.saveConfig();
sender.sendMessage(ColorParser.parseColor("&9Player added to list"));
} else if (args[1].equalsIgnoreCase("remove")) {
config.mmodeAllowedList.remove(args[2]);
config.saveConfig();
sender.sendMessage(ColorParser.parseColor("&9Player removed from list"));
}
}
}
return false;
}
private boolean hasPerm(CommandSender sender)
{
boolean has = false;
if (sender instanceof ConsoleCommandSender || sender instanceof RemoteConsoleCommandSender)
{
has = true;
}
if (sender instanceof Player && sender.hasPermission("mmode.admin"))
{
has = true;
}
return has;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command arg1, String arg2,
String[] args) {
//check permissions
if (!hasPerm(sender))
{
sender.sendMessage(ColorParser.parseColor("&4You don't have permission to do this"));
return true;
}
//handle command
if (args.length == 1 && args[0].equalsIgnoreCase("on"))
{
config.mmodeEnabled = true;
if (config.allowedlistEnabled && config.kickOnEnable) {
for (Player p :Bukkit.getOnlinePlayers())
{
if (!config.mmodeAllowedList.contains(p.getName()))
{
p.kickPlayer(ColorParser.parseColor(config.kickMessage));
}
}
}
sender.sendMessage(ColorParser.parseColor("&9Maintenance mode on"));
return true;
} else
if (args.length == 1 && args[0].equalsIgnoreCase("off"))
{
config.mmodeEnabled = false;
sender.sendMessage(ColorParser.parseColor("&9Maintenance mode off"));
return true;
} else
if (args.length == 1 && args[0].equalsIgnoreCase("reload"))
{
config.loadConfig();
sender.sendMessage(ColorParser.parseColor("&9Config reloaded"));
return true;
} else
if ((args.length == 2 || args.length == 3) && args[0].equalsIgnoreCase("alist"))
{
if (args.length == 2)
{
if (args[1].equalsIgnoreCase("on")) {
config.allowedlistEnabled = true;
config.saveConfig();
sender.sendMessage(ColorParser.parseColor("&9Allowed list enabled"));
return true;
} else if (args[1].equalsIgnoreCase("on")) {
config.allowedlistEnabled = false;
config.saveConfig();
sender.sendMessage(ColorParser.parseColor("&9Allowed list enabled"));
return true;
}
} else
if (args.length == 3)
{
if (args[1].equalsIgnoreCase("add")) {
config.mmodeAllowedList.add(args[2]);
config.saveConfig();
sender.sendMessage(ColorParser.parseColor("&9Player added to list"));
} else if (args[1].equalsIgnoreCase("remove")) {
config.mmodeAllowedList.remove(args[2]);
config.saveConfig();
sender.sendMessage(ColorParser.parseColor("&9Player removed from list"));
}
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command arg1, String arg2,
String[] args) {
//check permissions
if (!hasPerm(sender))
{
sender.sendMessage(ColorParser.parseColor("&4You don't have permission to do this"));
return true;
}
//handle command
if (args.length == 1 && args[0].equalsIgnoreCase("on"))
{
config.mmodeEnabled = true;
if (config.allowedlistEnabled && config.kickOnEnable) {
for (Player p :Bukkit.getOnlinePlayers())
{
if (!config.mmodeAllowedList.contains(p.getName()))
{
p.kickPlayer(ColorParser.parseColor(config.kickMessage));
}
}
}
sender.sendMessage(ColorParser.parseColor("&9Maintenance mode on"));
return true;
} else
if (args.length == 1 && args[0].equalsIgnoreCase("off"))
{
config.mmodeEnabled = false;
sender.sendMessage(ColorParser.parseColor("&9Maintenance mode off"));
return true;
} else
if (args.length == 1 && args[0].equalsIgnoreCase("reload"))
{
config.loadConfig();
sender.sendMessage(ColorParser.parseColor("&9Config reloaded"));
return true;
} else
if ((args.length == 2 || args.length == 3) && args[0].equalsIgnoreCase("alist"))
{
if (args.length == 2)
{
if (args[1].equalsIgnoreCase("on")) {
config.allowedlistEnabled = true;
config.saveConfig();
sender.sendMessage(ColorParser.parseColor("&9Allowed list enabled"));
return true;
} else if (args[1].equalsIgnoreCase("off")) {
config.allowedlistEnabled = false;
config.saveConfig();
sender.sendMessage(ColorParser.parseColor("&9Allowed list disabled"));
return true;
}
} else
if (args.length == 3)
{
if (args[1].equalsIgnoreCase("add")) {
config.mmodeAllowedList.add(args[2]);
config.saveConfig();
sender.sendMessage(ColorParser.parseColor("&9Player added to list"));
} else if (args[1].equalsIgnoreCase("remove")) {
config.mmodeAllowedList.remove(args[2]);
config.saveConfig();
sender.sendMessage(ColorParser.parseColor("&9Player removed from list"));
}
}
}
return false;
}
|
diff --git a/src/DVN-EJB/src/java/edu/harvard/hmdc/vdcnet/util/FileUtil.java b/src/DVN-EJB/src/java/edu/harvard/hmdc/vdcnet/util/FileUtil.java
index 95be90428..97063bc57 100644
--- a/src/DVN-EJB/src/java/edu/harvard/hmdc/vdcnet/util/FileUtil.java
+++ b/src/DVN-EJB/src/java/edu/harvard/hmdc/vdcnet/util/FileUtil.java
@@ -1,249 +1,249 @@
/*
* Dataverse Network - A web application to distribute, share and analyze quantitative data.
* Copyright (C) 2007
*
* 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
* or write to the Free Software Foundation,Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* FileUtil.java
*
* Created on February 12, 2007, 5:38 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package edu.harvard.hmdc.vdcnet.util;
import edu.harvard.hmdc.vdcnet.dsb.JhoveWrapper;
import edu.harvard.hmdc.vdcnet.dsb.SubsettableFileChecker;
import edu.harvard.hmdc.vdcnet.study.Study;
import edu.harvard.hmdc.vdcnet.study.StudyFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.util.HashMap;
import java.util.Map;
import javax.activation.MimetypesFileTypeMap;
import javax.ejb.EJBException;
/**
*
* @author Ellen Kraffmiller
*/
public class FileUtil implements java.io.Serializable {
private static final String[] SUBSETTABLE_FORMAT_SET = {"POR", "SAV", "DTA"};
private static Map<String, String> STATISTICAL_SYNTAX_FILE_EXTENSION = new HashMap<String, String>();
static {
STATISTICAL_SYNTAX_FILE_EXTENSION.put("do", "x-stata-syntax");
STATISTICAL_SYNTAX_FILE_EXTENSION.put("sas", "x-sas-syntax");
STATISTICAL_SYNTAX_FILE_EXTENSION.put("sps", "x-spss-syntax");
}
private static MimetypesFileTypeMap MIME_TYPE_MAP = new MimetypesFileTypeMap();
/** Creates a new instance of FileUtil */
public FileUtil() {
}
public static void copyFile(File inputFile, File outputFile) throws IOException {
FileChannel in = null;
WritableByteChannel out = null;
try {
in = new FileInputStream(inputFile).getChannel();
out = new FileOutputStream(outputFile).getChannel();
long bytesPerIteration = 50000;
long start = 0;
while ( start < in.size() ) {
in.transferTo(start, bytesPerIteration, out);
start += bytesPerIteration;
}
} finally {
if (in != null) { in.close(); }
if (out != null) { out.close(); }
}
}
public static String determineFileType(File f) throws IOException{
return determineFileType( f, f.getName()) ;
}
public static String determineFileType(StudyFile sf) throws IOException{
if (sf.isSubsettable()) {
return determineSubsettableFileType(sf);
} else {
if ( sf.isRemote() ) {
return FileUtil.determineFileType( sf.getFileName() );
} else {
return FileUtil.determineFileType( new File( sf.getFileSystemLocation() ), sf.getFileName() );
}
}
}
public static String determineSubsettableFileType(StudyFile sf) {
if ( sf.getDataTable().getRecordsPerCase() != null ) {
return "text/x-fixed-field";
} else {
return "text/tab-separated-values";
}
}
public static String determineFileType(String fileName) {
return MIME_TYPE_MAP.getContentType(fileName);
}
private static String determineFileType(File f, String fileName) throws IOException{
String fileType = null;
// step 1: check whether the file is subsettable
SubsettableFileChecker sfchk = new SubsettableFileChecker(SUBSETTABLE_FORMAT_SET);
fileType = sfchk.detectSubsettableFormat(f);
// step 2: check the mime type of this file with Jhove
if (fileType == null){
JhoveWrapper jw = new JhoveWrapper();
fileType = jw.getFileMimeType(f);
}
// step 3: handle Jhove fileType (if we have an extension)
// if text/plain and syntax file, replace the "plain" part
// if application/octet-stream, check for mime type by extension
String fileExtension = getFileExtension(fileName);
if ( fileExtension != null) {
if (fileType.startsWith("text/plain")){
if (( fileExtension != null) && (STATISTICAL_SYNTAX_FILE_EXTENSION.containsKey(fileExtension))) {
// replace the mime type with the value of the HashMap
fileType = fileType.replace("plain",STATISTICAL_SYNTAX_FILE_EXTENSION.get(fileExtension));
}
} else if (fileType.equals("application/octet-stream")) {
- determineFileType(fileName);
+ fileType = determineFileType(fileName);
}
}
return fileType;
}
public static String getFileExtension(String fileName){
String ext = null;
if ( fileName.lastIndexOf(".") != -1){
ext = (fileName.substring( fileName.lastIndexOf(".") + 1 )).toLowerCase();
}
return ext;
}
public static String replaceExtension(String originalName) {
int extensionIndex = originalName.lastIndexOf(".");
if (extensionIndex != -1 ) {
return originalName.substring(0, extensionIndex) + ".tab" ;
} else {
return originalName + ".tab";
}
}
public static String getStudyFileDir() {
String studyFileDir = System.getProperty("vdc.study.file.dir");
if (studyFileDir != null) {
return studyFileDir;
} else {
throw new EJBException("System property \"vdc.study.file.dir\" has not been set.");
}
}
public static String getLegacyFileDir() {
String studyFileDir = System.getProperty("vdc.legacy.file.dir");
if (studyFileDir != null) {
return studyFileDir;
} else {
throw new EJBException("System property \"vdc.legacy.file.dir\" has not been set.");
}
}
public static String getImportFileDir() {
String importFileDir = System.getProperty("vdc.import.log.dir");
if (importFileDir != null) {
File importLogDir = new File(importFileDir);
if (!importLogDir.exists()) {
importLogDir.mkdirs();
}
return importFileDir;
} else {
throw new EJBException("System property \"vdc.import.log.dir\" has not been set.");
}
}
public static String getExportFileDir() {
String exportFileDir = System.getProperty("vdc.export.log.dir");
if (exportFileDir != null) {
File exportLogDir = new File(exportFileDir);
if (!exportLogDir.exists()) {
exportLogDir.mkdirs();
}
return exportFileDir;
} else {
throw new EJBException("System property \"vdc.export.log.dir\" has not been set.");
}
}
public static File getStudyFileDir(Study study) {
File file = new File(FileUtil.getStudyFileDir(), study.getAuthority() + File.separator + study.getStudyId());
if (!file.exists()) {
file.mkdirs();
}
return file;
}
public static File createTempFile(String sessionId, String originalFileName) throws Exception{
String filePathDir = System.getProperty("vdc.temp.file.dir");
if (filePathDir != null) {
File tempDir = new File(filePathDir, sessionId);
if (!tempDir.exists()) {
tempDir.mkdirs();
}
// now create the file
String tempFileName = originalFileName;
File file = new File(tempDir, tempFileName);
int fileSuffix = 1;
while (!file.createNewFile()) {
int extensionIndex = originalFileName.lastIndexOf(".");
if (extensionIndex != -1 ) {
tempFileName = originalFileName.substring(0, extensionIndex) + "_" + fileSuffix++ + originalFileName.substring(extensionIndex);
} else {
tempFileName = originalFileName + "_" + fileSuffix++;
}
file = new File(tempDir, tempFileName);
}
return file;
} else {
throw new Exception("System property \"vdc.temp.file.dir\" has not been set.");
}
}
}
| true | true | private static String determineFileType(File f, String fileName) throws IOException{
String fileType = null;
// step 1: check whether the file is subsettable
SubsettableFileChecker sfchk = new SubsettableFileChecker(SUBSETTABLE_FORMAT_SET);
fileType = sfchk.detectSubsettableFormat(f);
// step 2: check the mime type of this file with Jhove
if (fileType == null){
JhoveWrapper jw = new JhoveWrapper();
fileType = jw.getFileMimeType(f);
}
// step 3: handle Jhove fileType (if we have an extension)
// if text/plain and syntax file, replace the "plain" part
// if application/octet-stream, check for mime type by extension
String fileExtension = getFileExtension(fileName);
if ( fileExtension != null) {
if (fileType.startsWith("text/plain")){
if (( fileExtension != null) && (STATISTICAL_SYNTAX_FILE_EXTENSION.containsKey(fileExtension))) {
// replace the mime type with the value of the HashMap
fileType = fileType.replace("plain",STATISTICAL_SYNTAX_FILE_EXTENSION.get(fileExtension));
}
} else if (fileType.equals("application/octet-stream")) {
determineFileType(fileName);
}
}
return fileType;
}
| private static String determineFileType(File f, String fileName) throws IOException{
String fileType = null;
// step 1: check whether the file is subsettable
SubsettableFileChecker sfchk = new SubsettableFileChecker(SUBSETTABLE_FORMAT_SET);
fileType = sfchk.detectSubsettableFormat(f);
// step 2: check the mime type of this file with Jhove
if (fileType == null){
JhoveWrapper jw = new JhoveWrapper();
fileType = jw.getFileMimeType(f);
}
// step 3: handle Jhove fileType (if we have an extension)
// if text/plain and syntax file, replace the "plain" part
// if application/octet-stream, check for mime type by extension
String fileExtension = getFileExtension(fileName);
if ( fileExtension != null) {
if (fileType.startsWith("text/plain")){
if (( fileExtension != null) && (STATISTICAL_SYNTAX_FILE_EXTENSION.containsKey(fileExtension))) {
// replace the mime type with the value of the HashMap
fileType = fileType.replace("plain",STATISTICAL_SYNTAX_FILE_EXTENSION.get(fileExtension));
}
} else if (fileType.equals("application/octet-stream")) {
fileType = determineFileType(fileName);
}
}
return fileType;
}
|
diff --git a/entitystore-rest/src/main/java/org/qi4j/rest/client/RESTEntityStoreServiceMixin.java b/entitystore-rest/src/main/java/org/qi4j/rest/client/RESTEntityStoreServiceMixin.java
index 2e41b511e..28dd09cfa 100644
--- a/entitystore-rest/src/main/java/org/qi4j/rest/client/RESTEntityStoreServiceMixin.java
+++ b/entitystore-rest/src/main/java/org/qi4j/rest/client/RESTEntityStoreServiceMixin.java
@@ -1,218 +1,218 @@
/*
* Copyright (c) 2008, Rickard Öberg. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.qi4j.rest.client;
import java.io.IOException;
import java.util.UUID;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFParseException;
import org.qi4j.api.configuration.Configuration;
import org.qi4j.api.entity.EntityReference;
import org.qi4j.api.injection.scope.Service;
import org.qi4j.api.injection.scope.This;
import org.qi4j.api.injection.scope.Uses;
import org.qi4j.api.service.Activatable;
import org.qi4j.api.usecase.Usecase;
import org.qi4j.library.rdf.entity.EntityStateParser;
import org.qi4j.spi.entity.EntityDescriptor;
import org.qi4j.spi.entity.EntityState;
import org.qi4j.spi.entitystore.DefaultEntityStoreUnitOfWork;
import org.qi4j.spi.entitystore.EntityNotFoundException;
import org.qi4j.spi.entitystore.EntityStore;
import org.qi4j.spi.entitystore.EntityStoreException;
import org.qi4j.spi.entitystore.EntityStoreSPI;
import org.qi4j.spi.entitystore.EntityStoreUnitOfWork;
import org.qi4j.spi.entitystore.StateCommitter;
import org.qi4j.spi.structure.ModuleSPI;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Uniform;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Preference;
import org.restlet.data.Reference;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
/**
* EntityStore implementation that uses REST to access EntityState from a server.
*/
public class RESTEntityStoreServiceMixin
implements EntityStore, EntityStoreSPI, Activatable
{
@Uses
private EntityStateParser parser;
@This
private Configuration<RESTEntityStoreConfiguration> config;
@This
EntityStoreSPI entityStoreSpi;
@Service
private Uniform client;
private Reference entityStoreUrl;
protected String uuid;
private int count;
public void activate()
throws Exception
{
uuid = UUID.randomUUID().toString() + "-";
entityStoreUrl = new Reference( config.configuration().storeUrl().get() );
}
public void passivate()
throws Exception
{
}
public EntityStoreUnitOfWork newUnitOfWork( Usecase usecase, ModuleSPI module )
{
return new DefaultEntityStoreUnitOfWork( entityStoreSpi, newUnitOfWorkId(), module );
}
public EntityStoreUnitOfWork visitEntityStates( EntityStateVisitor visitor, ModuleSPI moduleInstance )
{
return null;
}
public EntityState newEntityState( EntityStoreUnitOfWork unitOfWork,
EntityReference identity,
EntityDescriptor entityType
)
{
return null;
}
public EntityState getEntityState( EntityStoreUnitOfWork unitOfWork, EntityReference identity )
{
try
{
Reference ref = entityStoreUrl.clone().addSegment( identity.identity() );
Request request = new Request( Method.GET, ref );
request.getClientInfo()
.getAcceptedMediaTypes()
.add( new Preference<MediaType>( MediaType.APPLICATION_JAVA_OBJECT ) );
Response response = new Response( request );
client.handle( request, response );
if( response.getStatus().isSuccess() )
{
if( response.isEntityAvailable() )
{
Representation entity = response.getEntity();
return parseEntityState( unitOfWork, identity, ref, response, entity );
}
}
else if( response.getStatus().equals( Status.CLIENT_ERROR_NOT_FOUND ) )
{
throw new EntityNotFoundException( identity );
}
}
catch( EntityStoreException e )
{
throw e;
}
catch( Exception e )
{
throw new EntityStoreException( e );
}
throw new EntityStoreException();
}
private EntityState parseEntityState( EntityStoreUnitOfWork uow,
EntityReference anReference,
Reference ref,
Response response,
Representation entity
)
throws IOException, RDFParseException, RDFHandlerException, ClassNotFoundException
{
/*
Reader reader = entity.getReader();
RDFParser rdfParser = new RDFXMLParserFactory().getParser();
Collection<Statement> statements = new ArrayList<Statement>();
StatementCollector statementCollector = new StatementCollector( statements );
rdfParser.setRDFHandler( statementCollector );
rdfParser.parse( reader, ref.toString() );
long modified = response.getEntity().getModificationDate().getTime();
String version = response.getEntity().getTag().getName();
EntityState entityState = new DefaultEntityState( uow, version, modified,
anReference, EntityStatus.LOADED,
null, // TODO
new HashMap<QualifiedName, Object>(),
new HashMap<QualifiedName, EntityReference>(),
new HashMap<QualifiedName, List<EntityReference>>() );
parser.parse( statements, entityState );
return entityState;
*/
return null;
}
- public StateCommitter applyChanges( Iterable<EntityState> state, String identity )
+ public StateCommitter applyChanges( Iterable<EntityState> state, String identity, long lastModified )
{
/*
Reference ref = entityStoreUrl.clone();
Response response = client.post( ref, new OutputRepresentation( MediaType.APPLICATION_JAVA_OBJECT )
{
public void write( OutputStream outputStream ) throws IOException
{
ObjectOutputStream oout = new ObjectOutputStream( outputStream );
oout.writeUTF( unitOfWorkIdentity );
oout.writeUnshared( usecase );
oout.writeUnshared( metaInfo );
oout.writeUnshared( events );
oout.close();
}
} );
if( response.getStatus() == Status.CLIENT_ERROR_CONFLICT )
{
// TODO Figure out which ones were changed
Collection<EntityReference> modifiedReferences = new ArrayList<EntityReference>();
throw new ConcurrentEntityStateModificationException( modifiedReferences );
}
else if( !response.getStatus().isSuccess() )
{
throw new EntityStoreException( response.getStatus().toString() );
}
*/
return new StateCommitter()
{
public void commit()
{
}
public void cancel()
{
}
};
}
public EntityStoreUnitOfWork visitEntityStates( EntityStateVisitor visitor )
{
// TODO Iterate over all EntityStates
return null;
}
private String newUnitOfWorkId()
{
return uuid + Integer.toHexString( count++ );
}
}
| true | true | public StateCommitter applyChanges( Iterable<EntityState> state, String identity )
{
/*
Reference ref = entityStoreUrl.clone();
Response response = client.post( ref, new OutputRepresentation( MediaType.APPLICATION_JAVA_OBJECT )
{
public void write( OutputStream outputStream ) throws IOException
{
ObjectOutputStream oout = new ObjectOutputStream( outputStream );
oout.writeUTF( unitOfWorkIdentity );
oout.writeUnshared( usecase );
oout.writeUnshared( metaInfo );
oout.writeUnshared( events );
oout.close();
}
} );
if( response.getStatus() == Status.CLIENT_ERROR_CONFLICT )
{
// TODO Figure out which ones were changed
Collection<EntityReference> modifiedReferences = new ArrayList<EntityReference>();
throw new ConcurrentEntityStateModificationException( modifiedReferences );
}
else if( !response.getStatus().isSuccess() )
{
throw new EntityStoreException( response.getStatus().toString() );
}
*/
return new StateCommitter()
{
public void commit()
{
}
public void cancel()
{
}
};
}
| public StateCommitter applyChanges( Iterable<EntityState> state, String identity, long lastModified )
{
/*
Reference ref = entityStoreUrl.clone();
Response response = client.post( ref, new OutputRepresentation( MediaType.APPLICATION_JAVA_OBJECT )
{
public void write( OutputStream outputStream ) throws IOException
{
ObjectOutputStream oout = new ObjectOutputStream( outputStream );
oout.writeUTF( unitOfWorkIdentity );
oout.writeUnshared( usecase );
oout.writeUnshared( metaInfo );
oout.writeUnshared( events );
oout.close();
}
} );
if( response.getStatus() == Status.CLIENT_ERROR_CONFLICT )
{
// TODO Figure out which ones were changed
Collection<EntityReference> modifiedReferences = new ArrayList<EntityReference>();
throw new ConcurrentEntityStateModificationException( modifiedReferences );
}
else if( !response.getStatus().isSuccess() )
{
throw new EntityStoreException( response.getStatus().toString() );
}
*/
return new StateCommitter()
{
public void commit()
{
}
public void cancel()
{
}
};
}
|
diff --git a/src/gov/nist/javax/sip/stack/IOHandler.java b/src/gov/nist/javax/sip/stack/IOHandler.java
index 8afc69bb..d343bbab 100755
--- a/src/gov/nist/javax/sip/stack/IOHandler.java
+++ b/src/gov/nist/javax/sip/stack/IOHandler.java
@@ -1,304 +1,304 @@
/*
* Conditions Of Use
*
* This software was developed by employees of the National Institute of
* Standards and Technology (NIST), an agency of the Federal Government.
* Pursuant to title 15 Untied States Code Section 105, works of NIST
* employees are not subject to copyright protection in the United States
* and are considered to be in the public domain. As a result, a formal
* license is not needed to use the software.
*
* This software is provided by NIST as a service and is expressly
* provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY. NIST does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement
*
* .
*
*/
/*******************************************************************************
* Product of NIST/ITL Advanced Networking Technologies Division (ANTD). *
*******************************************************************************/
package gov.nist.javax.sip.stack;
import gov.nist.javax.sip.SipStackImpl;
import java.io.*;
import java.net.*;
import java.util.Hashtable;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/*
* TLS support Added by Daniel J.Martinez Manzano <[email protected]>
*
*/
/**
* Low level Input output to a socket. Caches TCP connections and takes care of
* re-connecting to the remote party if the other end drops the connection
*
* @version 1.2
*
* @author M. Ranganathan <br/>
*
*
*/
class IOHandler {
private Semaphore ioSemaphore = new Semaphore(1);
private SipStackImpl sipStack;
private static String TCP = "tcp";
// Added by Daniel J. Martinez Manzano <[email protected]>
private static String TLS = "tls";
// A cache of client sockets that can be re-used for
// sending tcp messages.
private ConcurrentHashMap<String, Socket> socketTable;
protected static String makeKey(InetAddress addr, int port) {
return addr.getHostAddress() + ":" + port;
}
protected IOHandler(SIPTransactionStack sipStack) {
this.sipStack = (SipStackImpl) sipStack;
this.socketTable = new ConcurrentHashMap<String, Socket>();
}
protected void putSocket(String key, Socket sock) {
socketTable.put(key, sock);
}
protected Socket getSocket(String key) {
return (Socket) socketTable.get(key);
}
protected void removeSocket(String key) {
socketTable.remove(key);
}
/**
* A private function to write things out. This needs to be syncrhonized as
* writes can occur from multiple threads. We write in chunks to allow the
* other side to synchronize for large sized writes.
*/
private void writeChunks(OutputStream outputStream, byte[] bytes, int length)
throws IOException {
// Chunk size is 16K - this hack is for large
// writes over slow connections.
synchronized (outputStream) {
// outputStream.write(bytes,0,length);
int chunksize = 8 * 1024;
for (int p = 0; p < length; p += chunksize) {
int chunk = p + chunksize < length ? chunksize : length - p;
outputStream.write(bytes, p, chunk);
}
}
outputStream.flush();
}
/**
* Send an array of bytes.
*
* @param receiverAddress --
* inet address
* @param contactPort --
* port to connect to.
* @param transport --
* tcp or udp.
* @param retry --
* retry to connect if the other end closed connection
* @throws IOException --
* if there is an IO exception sending message.
*/
public Socket sendBytes(InetAddress senderAddress,
InetAddress receiverAddress, int contactPort, String transport,
byte[] bytes, boolean retry) throws IOException {
int retry_count = 0;
int max_retry = retry ? 2 : 1;
// Server uses TCP transport. TCP client sockets are cached
int length = bytes.length;
if (sipStack.isLoggingEnabled()) {
sipStack.logWriter.logDebug("sendBytes " + transport + " inAddr "
+ receiverAddress.getHostAddress() + " port = "
+ contactPort + " length = " + length);
}
if (transport.compareToIgnoreCase(TCP) == 0) {
String key = makeKey(receiverAddress, contactPort);
// This should be in a synchronized block ( reported by
// Jayashenkhar ( lucent ).
try {
- boolean retval = this.ioSemaphore.tryAcquire(1000, TimeUnit.MILLISECONDS);
+ boolean retval = this.ioSemaphore.tryAcquire(10000, TimeUnit.MILLISECONDS); // TODO - make this a stack config parameter?
if ( !retval ) {
- throw new IOException("Could not acquire IO Semaphore after 1 second -- giving up ");
+ throw new IOException("Could not acquire IO Semaphore after 10 second -- giving up ");
}
} catch (InterruptedException ex) {
throw new IOException("exception in aquiring sem");
}
Socket clientSock = getSocket(key);
try {
while (retry_count < max_retry) {
if (clientSock == null) {
if (sipStack.isLoggingEnabled()) {
sipStack.logWriter.logDebug("inaddr = "
+ receiverAddress);
sipStack.logWriter
.logDebug("port = " + contactPort);
}
// note that the IP Address for stack may not be
// assigned.
// sender address is the address of the listening point.
// in version 1.1 all listening points have the same IP
// address (i.e. that of the stack). In version 1.2
// the IP address is on a per listening point basis.
clientSock = sipStack.getNetworkLayer().createSocket(
receiverAddress, contactPort, senderAddress);
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
putSocket(key, clientSock);
break;
} else {
try {
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
break;
} catch (IOException ex) {
if (sipStack.isLoggingEnabled())
sipStack.logWriter.logException(ex);
// old connection is bad.
// remove from our table.
removeSocket(key);
try {
clientSock.close();
} catch (Exception e) {
}
clientSock = null;
retry_count++;
}
}
}
} finally {
ioSemaphore.release();
}
if (clientSock == null) {
throw new IOException("Could not connect to " + receiverAddress
+ ":" + contactPort);
} else
return clientSock;
// Added by Daniel J. Martinez Manzano <[email protected]>
// Copied and modified from the former section for TCP
} else if (transport.compareToIgnoreCase(TLS) == 0) {
String key = makeKey(receiverAddress, contactPort);
try {
this.ioSemaphore.acquire();
} catch (InterruptedException ex) {
throw new IOException("exception in aquiring sem", ex);
}
Socket clientSock = getSocket(key);
try {
while (retry_count < max_retry) {
if (clientSock == null) {
if (sipStack.isLoggingEnabled()) {
sipStack.logWriter.logDebug("inaddr = "
+ receiverAddress);
sipStack.logWriter
.logDebug("port = " + contactPort);
}
if (!sipStack.useTlsAccelerator) {
clientSock = sipStack.getNetworkLayer()
.createSSLSocket(receiverAddress,
contactPort, senderAddress);
} else {
clientSock = sipStack.getNetworkLayer()
.createSocket(receiverAddress, contactPort,
senderAddress);
}
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
putSocket(key, clientSock);
break;
} else {
try {
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
break;
} catch (IOException ex) {
if (sipStack.isLoggingEnabled())
sipStack.logWriter.logException(ex);
// old connection is bad.
// remove from our table.
removeSocket(key);
try {
clientSock.close();
} catch (Exception e) {
}
clientSock = null;
retry_count++;
}
}
}
} finally {
ioSemaphore.release();
}
if (clientSock == null) {
throw new IOException("Could not connect to " + receiverAddress
+ ":" + contactPort);
} else
return clientSock;
} else {
// This is a UDP transport...
DatagramSocket datagramSock = sipStack.getNetworkLayer()
.createDatagramSocket();
datagramSock.connect(receiverAddress, contactPort);
DatagramPacket dgPacket = new DatagramPacket(bytes, 0, length,
receiverAddress, contactPort);
datagramSock.send(dgPacket);
datagramSock.close();
return null;
}
}
/**
* Close all the cached connections.
*/
public void closeAll() {
for (Enumeration<Socket> values = socketTable.elements(); values
.hasMoreElements();) {
Socket s = (Socket) values.nextElement();
try {
s.close();
} catch (IOException ex) {
}
}
}
}
| false | true | public Socket sendBytes(InetAddress senderAddress,
InetAddress receiverAddress, int contactPort, String transport,
byte[] bytes, boolean retry) throws IOException {
int retry_count = 0;
int max_retry = retry ? 2 : 1;
// Server uses TCP transport. TCP client sockets are cached
int length = bytes.length;
if (sipStack.isLoggingEnabled()) {
sipStack.logWriter.logDebug("sendBytes " + transport + " inAddr "
+ receiverAddress.getHostAddress() + " port = "
+ contactPort + " length = " + length);
}
if (transport.compareToIgnoreCase(TCP) == 0) {
String key = makeKey(receiverAddress, contactPort);
// This should be in a synchronized block ( reported by
// Jayashenkhar ( lucent ).
try {
boolean retval = this.ioSemaphore.tryAcquire(1000, TimeUnit.MILLISECONDS);
if ( !retval ) {
throw new IOException("Could not acquire IO Semaphore after 1 second -- giving up ");
}
} catch (InterruptedException ex) {
throw new IOException("exception in aquiring sem");
}
Socket clientSock = getSocket(key);
try {
while (retry_count < max_retry) {
if (clientSock == null) {
if (sipStack.isLoggingEnabled()) {
sipStack.logWriter.logDebug("inaddr = "
+ receiverAddress);
sipStack.logWriter
.logDebug("port = " + contactPort);
}
// note that the IP Address for stack may not be
// assigned.
// sender address is the address of the listening point.
// in version 1.1 all listening points have the same IP
// address (i.e. that of the stack). In version 1.2
// the IP address is on a per listening point basis.
clientSock = sipStack.getNetworkLayer().createSocket(
receiverAddress, contactPort, senderAddress);
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
putSocket(key, clientSock);
break;
} else {
try {
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
break;
} catch (IOException ex) {
if (sipStack.isLoggingEnabled())
sipStack.logWriter.logException(ex);
// old connection is bad.
// remove from our table.
removeSocket(key);
try {
clientSock.close();
} catch (Exception e) {
}
clientSock = null;
retry_count++;
}
}
}
} finally {
ioSemaphore.release();
}
if (clientSock == null) {
throw new IOException("Could not connect to " + receiverAddress
+ ":" + contactPort);
} else
return clientSock;
// Added by Daniel J. Martinez Manzano <[email protected]>
// Copied and modified from the former section for TCP
} else if (transport.compareToIgnoreCase(TLS) == 0) {
String key = makeKey(receiverAddress, contactPort);
try {
this.ioSemaphore.acquire();
} catch (InterruptedException ex) {
throw new IOException("exception in aquiring sem", ex);
}
Socket clientSock = getSocket(key);
try {
while (retry_count < max_retry) {
if (clientSock == null) {
if (sipStack.isLoggingEnabled()) {
sipStack.logWriter.logDebug("inaddr = "
+ receiverAddress);
sipStack.logWriter
.logDebug("port = " + contactPort);
}
if (!sipStack.useTlsAccelerator) {
clientSock = sipStack.getNetworkLayer()
.createSSLSocket(receiverAddress,
contactPort, senderAddress);
} else {
clientSock = sipStack.getNetworkLayer()
.createSocket(receiverAddress, contactPort,
senderAddress);
}
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
putSocket(key, clientSock);
break;
} else {
try {
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
break;
} catch (IOException ex) {
if (sipStack.isLoggingEnabled())
sipStack.logWriter.logException(ex);
// old connection is bad.
// remove from our table.
removeSocket(key);
try {
clientSock.close();
} catch (Exception e) {
}
clientSock = null;
retry_count++;
}
}
}
} finally {
ioSemaphore.release();
}
if (clientSock == null) {
throw new IOException("Could not connect to " + receiverAddress
+ ":" + contactPort);
} else
return clientSock;
} else {
// This is a UDP transport...
DatagramSocket datagramSock = sipStack.getNetworkLayer()
.createDatagramSocket();
datagramSock.connect(receiverAddress, contactPort);
DatagramPacket dgPacket = new DatagramPacket(bytes, 0, length,
receiverAddress, contactPort);
datagramSock.send(dgPacket);
datagramSock.close();
return null;
}
}
| public Socket sendBytes(InetAddress senderAddress,
InetAddress receiverAddress, int contactPort, String transport,
byte[] bytes, boolean retry) throws IOException {
int retry_count = 0;
int max_retry = retry ? 2 : 1;
// Server uses TCP transport. TCP client sockets are cached
int length = bytes.length;
if (sipStack.isLoggingEnabled()) {
sipStack.logWriter.logDebug("sendBytes " + transport + " inAddr "
+ receiverAddress.getHostAddress() + " port = "
+ contactPort + " length = " + length);
}
if (transport.compareToIgnoreCase(TCP) == 0) {
String key = makeKey(receiverAddress, contactPort);
// This should be in a synchronized block ( reported by
// Jayashenkhar ( lucent ).
try {
boolean retval = this.ioSemaphore.tryAcquire(10000, TimeUnit.MILLISECONDS); // TODO - make this a stack config parameter?
if ( !retval ) {
throw new IOException("Could not acquire IO Semaphore after 10 second -- giving up ");
}
} catch (InterruptedException ex) {
throw new IOException("exception in aquiring sem");
}
Socket clientSock = getSocket(key);
try {
while (retry_count < max_retry) {
if (clientSock == null) {
if (sipStack.isLoggingEnabled()) {
sipStack.logWriter.logDebug("inaddr = "
+ receiverAddress);
sipStack.logWriter
.logDebug("port = " + contactPort);
}
// note that the IP Address for stack may not be
// assigned.
// sender address is the address of the listening point.
// in version 1.1 all listening points have the same IP
// address (i.e. that of the stack). In version 1.2
// the IP address is on a per listening point basis.
clientSock = sipStack.getNetworkLayer().createSocket(
receiverAddress, contactPort, senderAddress);
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
putSocket(key, clientSock);
break;
} else {
try {
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
break;
} catch (IOException ex) {
if (sipStack.isLoggingEnabled())
sipStack.logWriter.logException(ex);
// old connection is bad.
// remove from our table.
removeSocket(key);
try {
clientSock.close();
} catch (Exception e) {
}
clientSock = null;
retry_count++;
}
}
}
} finally {
ioSemaphore.release();
}
if (clientSock == null) {
throw new IOException("Could not connect to " + receiverAddress
+ ":" + contactPort);
} else
return clientSock;
// Added by Daniel J. Martinez Manzano <[email protected]>
// Copied and modified from the former section for TCP
} else if (transport.compareToIgnoreCase(TLS) == 0) {
String key = makeKey(receiverAddress, contactPort);
try {
this.ioSemaphore.acquire();
} catch (InterruptedException ex) {
throw new IOException("exception in aquiring sem", ex);
}
Socket clientSock = getSocket(key);
try {
while (retry_count < max_retry) {
if (clientSock == null) {
if (sipStack.isLoggingEnabled()) {
sipStack.logWriter.logDebug("inaddr = "
+ receiverAddress);
sipStack.logWriter
.logDebug("port = " + contactPort);
}
if (!sipStack.useTlsAccelerator) {
clientSock = sipStack.getNetworkLayer()
.createSSLSocket(receiverAddress,
contactPort, senderAddress);
} else {
clientSock = sipStack.getNetworkLayer()
.createSocket(receiverAddress, contactPort,
senderAddress);
}
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
putSocket(key, clientSock);
break;
} else {
try {
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
break;
} catch (IOException ex) {
if (sipStack.isLoggingEnabled())
sipStack.logWriter.logException(ex);
// old connection is bad.
// remove from our table.
removeSocket(key);
try {
clientSock.close();
} catch (Exception e) {
}
clientSock = null;
retry_count++;
}
}
}
} finally {
ioSemaphore.release();
}
if (clientSock == null) {
throw new IOException("Could not connect to " + receiverAddress
+ ":" + contactPort);
} else
return clientSock;
} else {
// This is a UDP transport...
DatagramSocket datagramSock = sipStack.getNetworkLayer()
.createDatagramSocket();
datagramSock.connect(receiverAddress, contactPort);
DatagramPacket dgPacket = new DatagramPacket(bytes, 0, length,
receiverAddress, contactPort);
datagramSock.send(dgPacket);
datagramSock.close();
return null;
}
}
|
diff --git a/src/test/com/jogamp/opengl/test/junit/newt/event/TestNewtKeyEventAutoRepeatAWT.java b/src/test/com/jogamp/opengl/test/junit/newt/event/TestNewtKeyEventAutoRepeatAWT.java
index 3ef96edc2..c374f1efe 100644
--- a/src/test/com/jogamp/opengl/test/junit/newt/event/TestNewtKeyEventAutoRepeatAWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/newt/event/TestNewtKeyEventAutoRepeatAWT.java
@@ -1,318 +1,319 @@
/**
* Copyright 2012 JogAmp Community. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of JogAmp Community.
*/
package com.jogamp.opengl.test.junit.newt.event;
import org.junit.After;
import org.junit.Assert;
import org.junit.AfterClass;
import org.junit.Assume;
import org.junit.Before;
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Robot;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.EventObject;
import java.util.List;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLEventListener;
import javax.swing.JFrame;
import java.io.IOException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import com.jogamp.newt.awt.NewtCanvasAWT;
import com.jogamp.newt.event.InputEvent;
import com.jogamp.newt.event.KeyEvent;
import com.jogamp.newt.opengl.GLWindow;
import com.jogamp.opengl.util.Animator;
import com.jogamp.opengl.test.junit.jogl.demos.es2.RedSquareES2;
import com.jogamp.opengl.test.junit.util.*;
/**
* Testing key event order incl. auto-repeat (Bug 601)
*
* <p>
* Note Event order:
* <ol>
* <li>{@link #EVENT_KEY_PRESSED}</li>
* <li>{@link #EVENT_KEY_RELEASED}</li>
* </ol>
* </p>
* <p>
* Auto-Repeat shall behave as follow:
* <pre>
D = pressed, U = released
0 = normal, 1 = auto-repeat
D(0), [ U(1), D(1), U(1), D(1) ..], U(0)
* </pre>
*
* The idea is if you mask out auto-repeat in your event listener
* you just get one long pressed key D/U tuple.
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestNewtKeyEventAutoRepeatAWT extends UITestCase {
static int width, height;
static long durationPerTest = 100;
static long awtWaitTimeout = 1000;
static GLCapabilities glCaps;
@BeforeClass
public static void initClass() {
width = 640;
height = 480;
glCaps = new GLCapabilities(null);
}
@AfterClass
public static void release() {
}
@Before
public void initTest() {
}
@After
public void releaseTest() {
}
@Test(timeout=180000) // TO 3 min
public void test01NEWT() throws AWTException, InterruptedException, InvocationTargetException {
GLWindow glWindow = GLWindow.create(glCaps);
glWindow.setSize(width, height);
glWindow.setVisible(true);
testImpl(glWindow);
glWindow.destroy();
}
@Test(timeout=180000) // TO 3 min
public void test02NewtCanvasAWT() throws AWTException, InterruptedException, InvocationTargetException {
GLWindow glWindow = GLWindow.create(glCaps);
// Wrap the window in a canvas.
final NewtCanvasAWT newtCanvasAWT = new NewtCanvasAWT(glWindow);
// Add the canvas to a frame, and make it all visible.
final JFrame frame1 = new JFrame("Swing AWT Parent Frame: "+ glWindow.getTitle());
frame1.getContentPane().add(newtCanvasAWT, BorderLayout.CENTER);
frame1.setSize(width, height);
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
frame1.setVisible(true);
} } );
Assert.assertEquals(true, AWTRobotUtil.waitForVisible(frame1, true));
testImpl(glWindow);
try {
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
frame1.setVisible(false);
frame1.dispose();
}});
} catch( Throwable throwable ) {
throwable.printStackTrace();
Assume.assumeNoException( throwable );
}
glWindow.destroy();
}
static void testKeyEventAutoRepeat(Robot robot, NEWTKeyAdapter keyAdapter, int loops, int pressDurationMS) {
System.err.println("KEY Event Auto-Repeat Test: "+loops);
EventObject[][] first = new EventObject[loops][2];
EventObject[][] last = new EventObject[loops][2];
keyAdapter.reset();
int firstIdx = 0;
+ // final ArrayList<EventObject> keyEvents = new ArrayList<EventObject>();
for(int i=0; i<loops; i++) {
System.err.println("+++ KEY Event Auto-Repeat START Input Loop: "+i);
AWTRobotUtil.waitForIdle(robot);
AWTRobotUtil.keyPress(0, robot, true, java.awt.event.KeyEvent.VK_A, pressDurationMS);
AWTRobotUtil.keyPress(0, robot, false, java.awt.event.KeyEvent.VK_A, 500); // 1s .. no AR anymore
AWTRobotUtil.waitForIdle(robot);
final int minCodeCount = firstIdx + 2;
final int desiredCodeCount = firstIdx + 4;
for(int j=0; j < NEWTKeyUtil.POLL_DIVIDER && keyAdapter.getQueueSize() < desiredCodeCount; j++) { // wait until events are collected
robot.delay(NEWTKeyUtil.TIME_SLICE);
}
final List<EventObject> keyEvents = keyAdapter.copyQueue();
Assert.assertTrue("AR Test didn't collect enough key events: required min "+minCodeCount+", received "+(keyAdapter.getQueueSize()-firstIdx)+", "+keyEvents,
keyAdapter.getQueueSize() >= minCodeCount );
first[i][0] = keyEvents.get(firstIdx+0);
first[i][1] = keyEvents.get(firstIdx+1);
firstIdx = keyEvents.size() - 2;
last[i][0] = keyEvents.get(firstIdx+0);
last[i][1] = keyEvents.get(firstIdx+1);
System.err.println("+++ KEY Event Auto-Repeat END Input Loop: "+i);
// add a pair of normal press/release in between auto-repeat!
firstIdx = keyEvents.size();
AWTRobotUtil.waitForIdle(robot);
AWTRobotUtil.keyPress(0, robot, true, java.awt.event.KeyEvent.VK_B, 10);
AWTRobotUtil.keyPress(0, robot, false, java.awt.event.KeyEvent.VK_B, 250);
AWTRobotUtil.waitForIdle(robot);
- for(int j=0; j < NEWTKeyUtil.POLL_DIVIDER && keyAdapter.getQueueSize() < firstIdx+3; j++) { // wait until events are collected
+ for(int j=0; j < NEWTKeyUtil.POLL_DIVIDER && keyAdapter.getQueueSize() < firstIdx+2; j++) { // wait until events are collected
robot.delay(NEWTKeyUtil.TIME_SLICE);
}
- firstIdx = keyEvents.size();
+ firstIdx = keyAdapter.getQueueSize();
}
// dumpKeyEvents(keyEvents);
final List<EventObject> keyEvents = keyAdapter.copyQueue();
NEWTKeyUtil.validateKeyEventOrder(keyEvents);
final boolean hasAR = 0 < keyAdapter.getKeyPressedCount(true) ;
{
final int perLoopSI = 2; // per loop: 1 non AR event and 1 for non AR 'B'
final int expSI, expAR;
if( hasAR ) {
expSI = perLoopSI * loops;
expAR = ( keyEvents.size() - expSI*2 ) / 2; // auto-repeat release
} else {
expSI = keyEvents.size() / 2; // all released events
expAR = 0;
}
NEWTKeyUtil.validateKeyAdapterStats(keyAdapter,
expSI /* press-SI */, expSI /* release-SI */,
expAR /* press-AR */, expAR /* release-AR */ );
}
if( !hasAR ) {
System.err.println("No AUTO-REPEAT triggered by AWT Robot .. aborting test analysis");
return;
}
for(int i=0; i<loops; i++) {
System.err.println("Auto-Repeat Loop "+i+" - Head:");
NEWTKeyUtil.dumpKeyEvents(Arrays.asList(first[i]));
System.err.println("Auto-Repeat Loop "+i+" - Tail:");
NEWTKeyUtil.dumpKeyEvents(Arrays.asList(last[i]));
}
for(int i=0; i<loops; i++) {
KeyEvent e = (KeyEvent) first[i][0];
Assert.assertTrue("1st Shall be A, but is "+e, KeyEvent.VK_A == e.getKeyCode() );
Assert.assertTrue("1st Shall be PRESSED, but is "+e, KeyEvent.EVENT_KEY_PRESSED == e.getEventType() );
Assert.assertTrue("1st Shall not be AR, but is "+e, 0 == ( InputEvent.AUTOREPEAT_MASK & e.getModifiers() ) );
e = (KeyEvent) first[i][1];
Assert.assertTrue("2nd Shall be A, but is "+e, KeyEvent.VK_A == e.getKeyCode() );
Assert.assertTrue("2nd Shall be RELEASED, but is "+e, KeyEvent.EVENT_KEY_RELEASED == e.getEventType() );
Assert.assertTrue("2nd Shall be AR, but is "+e, 0 != ( InputEvent.AUTOREPEAT_MASK & e.getModifiers() ) );
e = (KeyEvent) last[i][0];
Assert.assertTrue("last-1 Shall be A, but is "+e, KeyEvent.VK_A == e.getKeyCode() );
Assert.assertTrue("last-1 Shall be PRESSED, but is "+e, KeyEvent.EVENT_KEY_PRESSED == e.getEventType() );
Assert.assertTrue("last-1 Shall be AR, but is "+e, 0 != ( InputEvent.AUTOREPEAT_MASK & e.getModifiers() ) );
e = (KeyEvent) last[i][1];
Assert.assertTrue("last-0 Shall be A, but is "+e, KeyEvent.VK_A == e.getKeyCode() );
Assert.assertTrue("last-2 Shall be RELEASED, but is "+e, KeyEvent.EVENT_KEY_RELEASED == e.getEventType() );
Assert.assertTrue("last-0 Shall not be AR, but is "+e, 0 == ( InputEvent.AUTOREPEAT_MASK & e.getModifiers() ) );
}
}
void testImpl(GLWindow glWindow) throws AWTException, InterruptedException, InvocationTargetException {
final Robot robot = new Robot();
robot.setAutoWaitForIdle(true);
GLEventListener demo1 = new RedSquareES2();
glWindow.addGLEventListener(demo1);
NEWTKeyAdapter glWindow1KA = new NEWTKeyAdapter("GLWindow1");
glWindow1KA.setVerbose(false);
glWindow.addKeyListener(glWindow1KA);
Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glWindow, true));
// Continuous animation ..
Animator animator = new Animator(glWindow);
animator.start();
Thread.sleep(durationPerTest); // manual testing
AWTRobotUtil.assertRequestFocusAndWait(null, glWindow, glWindow, null, null); // programmatic
AWTRobotUtil.requestFocus(robot, glWindow, false); // within unit framework, prev. tests (TestFocus02SwingAWTRobot) 'confuses' Windows keyboard input
glWindow1KA.reset();
//
// Test the key event order w/ auto-repeat
//
final int origAutoDelay = robot.getAutoDelay();
robot.setAutoDelay(10);
try {
testKeyEventAutoRepeat(robot, glWindow1KA, 3, 1000);
} finally {
robot.setAutoDelay(origAutoDelay);
}
// Remove listeners to avoid logging during dispose/destroy.
glWindow.removeKeyListener(glWindow1KA);
// Shutdown the test.
animator.stop();
}
static int atoi(String a) {
int i=0;
try {
i = Integer.parseInt(a);
} catch (Exception ex) { ex.printStackTrace(); }
return i;
}
public static void main(String args[]) throws IOException {
for(int i=0; i<args.length; i++) {
if(args[i].equals("-time")) {
durationPerTest = atoi(args[++i]);
}
}
/**
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.err.println("Press enter to continue");
System.err.println(stdin.readLine());
*/
System.out.println("durationPerTest: "+durationPerTest);
String tstname = TestNewtKeyEventAutoRepeatAWT.class.getName();
org.junit.runner.JUnitCore.main(tstname);
}
}
| false | true | static void testKeyEventAutoRepeat(Robot robot, NEWTKeyAdapter keyAdapter, int loops, int pressDurationMS) {
System.err.println("KEY Event Auto-Repeat Test: "+loops);
EventObject[][] first = new EventObject[loops][2];
EventObject[][] last = new EventObject[loops][2];
keyAdapter.reset();
int firstIdx = 0;
for(int i=0; i<loops; i++) {
System.err.println("+++ KEY Event Auto-Repeat START Input Loop: "+i);
AWTRobotUtil.waitForIdle(robot);
AWTRobotUtil.keyPress(0, robot, true, java.awt.event.KeyEvent.VK_A, pressDurationMS);
AWTRobotUtil.keyPress(0, robot, false, java.awt.event.KeyEvent.VK_A, 500); // 1s .. no AR anymore
AWTRobotUtil.waitForIdle(robot);
final int minCodeCount = firstIdx + 2;
final int desiredCodeCount = firstIdx + 4;
for(int j=0; j < NEWTKeyUtil.POLL_DIVIDER && keyAdapter.getQueueSize() < desiredCodeCount; j++) { // wait until events are collected
robot.delay(NEWTKeyUtil.TIME_SLICE);
}
final List<EventObject> keyEvents = keyAdapter.copyQueue();
Assert.assertTrue("AR Test didn't collect enough key events: required min "+minCodeCount+", received "+(keyAdapter.getQueueSize()-firstIdx)+", "+keyEvents,
keyAdapter.getQueueSize() >= minCodeCount );
first[i][0] = keyEvents.get(firstIdx+0);
first[i][1] = keyEvents.get(firstIdx+1);
firstIdx = keyEvents.size() - 2;
last[i][0] = keyEvents.get(firstIdx+0);
last[i][1] = keyEvents.get(firstIdx+1);
System.err.println("+++ KEY Event Auto-Repeat END Input Loop: "+i);
// add a pair of normal press/release in between auto-repeat!
firstIdx = keyEvents.size();
AWTRobotUtil.waitForIdle(robot);
AWTRobotUtil.keyPress(0, robot, true, java.awt.event.KeyEvent.VK_B, 10);
AWTRobotUtil.keyPress(0, robot, false, java.awt.event.KeyEvent.VK_B, 250);
AWTRobotUtil.waitForIdle(robot);
for(int j=0; j < NEWTKeyUtil.POLL_DIVIDER && keyAdapter.getQueueSize() < firstIdx+3; j++) { // wait until events are collected
robot.delay(NEWTKeyUtil.TIME_SLICE);
}
firstIdx = keyEvents.size();
}
// dumpKeyEvents(keyEvents);
final List<EventObject> keyEvents = keyAdapter.copyQueue();
NEWTKeyUtil.validateKeyEventOrder(keyEvents);
final boolean hasAR = 0 < keyAdapter.getKeyPressedCount(true) ;
{
final int perLoopSI = 2; // per loop: 1 non AR event and 1 for non AR 'B'
final int expSI, expAR;
if( hasAR ) {
expSI = perLoopSI * loops;
expAR = ( keyEvents.size() - expSI*2 ) / 2; // auto-repeat release
} else {
expSI = keyEvents.size() / 2; // all released events
expAR = 0;
}
NEWTKeyUtil.validateKeyAdapterStats(keyAdapter,
expSI /* press-SI */, expSI /* release-SI */,
expAR /* press-AR */, expAR /* release-AR */ );
}
if( !hasAR ) {
System.err.println("No AUTO-REPEAT triggered by AWT Robot .. aborting test analysis");
return;
}
for(int i=0; i<loops; i++) {
System.err.println("Auto-Repeat Loop "+i+" - Head:");
NEWTKeyUtil.dumpKeyEvents(Arrays.asList(first[i]));
System.err.println("Auto-Repeat Loop "+i+" - Tail:");
NEWTKeyUtil.dumpKeyEvents(Arrays.asList(last[i]));
}
for(int i=0; i<loops; i++) {
KeyEvent e = (KeyEvent) first[i][0];
Assert.assertTrue("1st Shall be A, but is "+e, KeyEvent.VK_A == e.getKeyCode() );
Assert.assertTrue("1st Shall be PRESSED, but is "+e, KeyEvent.EVENT_KEY_PRESSED == e.getEventType() );
Assert.assertTrue("1st Shall not be AR, but is "+e, 0 == ( InputEvent.AUTOREPEAT_MASK & e.getModifiers() ) );
e = (KeyEvent) first[i][1];
Assert.assertTrue("2nd Shall be A, but is "+e, KeyEvent.VK_A == e.getKeyCode() );
Assert.assertTrue("2nd Shall be RELEASED, but is "+e, KeyEvent.EVENT_KEY_RELEASED == e.getEventType() );
Assert.assertTrue("2nd Shall be AR, but is "+e, 0 != ( InputEvent.AUTOREPEAT_MASK & e.getModifiers() ) );
e = (KeyEvent) last[i][0];
Assert.assertTrue("last-1 Shall be A, but is "+e, KeyEvent.VK_A == e.getKeyCode() );
Assert.assertTrue("last-1 Shall be PRESSED, but is "+e, KeyEvent.EVENT_KEY_PRESSED == e.getEventType() );
Assert.assertTrue("last-1 Shall be AR, but is "+e, 0 != ( InputEvent.AUTOREPEAT_MASK & e.getModifiers() ) );
e = (KeyEvent) last[i][1];
Assert.assertTrue("last-0 Shall be A, but is "+e, KeyEvent.VK_A == e.getKeyCode() );
Assert.assertTrue("last-2 Shall be RELEASED, but is "+e, KeyEvent.EVENT_KEY_RELEASED == e.getEventType() );
Assert.assertTrue("last-0 Shall not be AR, but is "+e, 0 == ( InputEvent.AUTOREPEAT_MASK & e.getModifiers() ) );
}
}
| static void testKeyEventAutoRepeat(Robot robot, NEWTKeyAdapter keyAdapter, int loops, int pressDurationMS) {
System.err.println("KEY Event Auto-Repeat Test: "+loops);
EventObject[][] first = new EventObject[loops][2];
EventObject[][] last = new EventObject[loops][2];
keyAdapter.reset();
int firstIdx = 0;
// final ArrayList<EventObject> keyEvents = new ArrayList<EventObject>();
for(int i=0; i<loops; i++) {
System.err.println("+++ KEY Event Auto-Repeat START Input Loop: "+i);
AWTRobotUtil.waitForIdle(robot);
AWTRobotUtil.keyPress(0, robot, true, java.awt.event.KeyEvent.VK_A, pressDurationMS);
AWTRobotUtil.keyPress(0, robot, false, java.awt.event.KeyEvent.VK_A, 500); // 1s .. no AR anymore
AWTRobotUtil.waitForIdle(robot);
final int minCodeCount = firstIdx + 2;
final int desiredCodeCount = firstIdx + 4;
for(int j=0; j < NEWTKeyUtil.POLL_DIVIDER && keyAdapter.getQueueSize() < desiredCodeCount; j++) { // wait until events are collected
robot.delay(NEWTKeyUtil.TIME_SLICE);
}
final List<EventObject> keyEvents = keyAdapter.copyQueue();
Assert.assertTrue("AR Test didn't collect enough key events: required min "+minCodeCount+", received "+(keyAdapter.getQueueSize()-firstIdx)+", "+keyEvents,
keyAdapter.getQueueSize() >= minCodeCount );
first[i][0] = keyEvents.get(firstIdx+0);
first[i][1] = keyEvents.get(firstIdx+1);
firstIdx = keyEvents.size() - 2;
last[i][0] = keyEvents.get(firstIdx+0);
last[i][1] = keyEvents.get(firstIdx+1);
System.err.println("+++ KEY Event Auto-Repeat END Input Loop: "+i);
// add a pair of normal press/release in between auto-repeat!
firstIdx = keyEvents.size();
AWTRobotUtil.waitForIdle(robot);
AWTRobotUtil.keyPress(0, robot, true, java.awt.event.KeyEvent.VK_B, 10);
AWTRobotUtil.keyPress(0, robot, false, java.awt.event.KeyEvent.VK_B, 250);
AWTRobotUtil.waitForIdle(robot);
for(int j=0; j < NEWTKeyUtil.POLL_DIVIDER && keyAdapter.getQueueSize() < firstIdx+2; j++) { // wait until events are collected
robot.delay(NEWTKeyUtil.TIME_SLICE);
}
firstIdx = keyAdapter.getQueueSize();
}
// dumpKeyEvents(keyEvents);
final List<EventObject> keyEvents = keyAdapter.copyQueue();
NEWTKeyUtil.validateKeyEventOrder(keyEvents);
final boolean hasAR = 0 < keyAdapter.getKeyPressedCount(true) ;
{
final int perLoopSI = 2; // per loop: 1 non AR event and 1 for non AR 'B'
final int expSI, expAR;
if( hasAR ) {
expSI = perLoopSI * loops;
expAR = ( keyEvents.size() - expSI*2 ) / 2; // auto-repeat release
} else {
expSI = keyEvents.size() / 2; // all released events
expAR = 0;
}
NEWTKeyUtil.validateKeyAdapterStats(keyAdapter,
expSI /* press-SI */, expSI /* release-SI */,
expAR /* press-AR */, expAR /* release-AR */ );
}
if( !hasAR ) {
System.err.println("No AUTO-REPEAT triggered by AWT Robot .. aborting test analysis");
return;
}
for(int i=0; i<loops; i++) {
System.err.println("Auto-Repeat Loop "+i+" - Head:");
NEWTKeyUtil.dumpKeyEvents(Arrays.asList(first[i]));
System.err.println("Auto-Repeat Loop "+i+" - Tail:");
NEWTKeyUtil.dumpKeyEvents(Arrays.asList(last[i]));
}
for(int i=0; i<loops; i++) {
KeyEvent e = (KeyEvent) first[i][0];
Assert.assertTrue("1st Shall be A, but is "+e, KeyEvent.VK_A == e.getKeyCode() );
Assert.assertTrue("1st Shall be PRESSED, but is "+e, KeyEvent.EVENT_KEY_PRESSED == e.getEventType() );
Assert.assertTrue("1st Shall not be AR, but is "+e, 0 == ( InputEvent.AUTOREPEAT_MASK & e.getModifiers() ) );
e = (KeyEvent) first[i][1];
Assert.assertTrue("2nd Shall be A, but is "+e, KeyEvent.VK_A == e.getKeyCode() );
Assert.assertTrue("2nd Shall be RELEASED, but is "+e, KeyEvent.EVENT_KEY_RELEASED == e.getEventType() );
Assert.assertTrue("2nd Shall be AR, but is "+e, 0 != ( InputEvent.AUTOREPEAT_MASK & e.getModifiers() ) );
e = (KeyEvent) last[i][0];
Assert.assertTrue("last-1 Shall be A, but is "+e, KeyEvent.VK_A == e.getKeyCode() );
Assert.assertTrue("last-1 Shall be PRESSED, but is "+e, KeyEvent.EVENT_KEY_PRESSED == e.getEventType() );
Assert.assertTrue("last-1 Shall be AR, but is "+e, 0 != ( InputEvent.AUTOREPEAT_MASK & e.getModifiers() ) );
e = (KeyEvent) last[i][1];
Assert.assertTrue("last-0 Shall be A, but is "+e, KeyEvent.VK_A == e.getKeyCode() );
Assert.assertTrue("last-2 Shall be RELEASED, but is "+e, KeyEvent.EVENT_KEY_RELEASED == e.getEventType() );
Assert.assertTrue("last-0 Shall not be AR, but is "+e, 0 == ( InputEvent.AUTOREPEAT_MASK & e.getModifiers() ) );
}
}
|
diff --git a/Core/src/java/ho/module/lineup/substitution/SubstitutionEditView.java b/Core/src/java/ho/module/lineup/substitution/SubstitutionEditView.java
index b4b0034b..f2a5d11f 100644
--- a/Core/src/java/ho/module/lineup/substitution/SubstitutionEditView.java
+++ b/Core/src/java/ho/module/lineup/substitution/SubstitutionEditView.java
@@ -1,464 +1,464 @@
package ho.module.lineup.substitution;
import ho.core.datatype.CBItem;
import ho.core.model.HOVerwaltung;
import ho.core.model.player.ISpielerPosition;
import ho.core.util.Helper;
import ho.module.lineup.substitution.model.GoalDiffCriteria;
import ho.module.lineup.substitution.model.MatchOrderType;
import ho.module.lineup.substitution.model.RedCardCriteria;
import ho.module.lineup.substitution.model.Substitution;
import ho.module.lineup.substitution.positionchooser.PositionChooser;
import ho.module.lineup.substitution.positionchooser.PositionSelectionEvent;
import ho.module.lineup.substitution.positionchooser.PositionSelectionListener;
import ho.module.lineup.substitution.positionchooser.PositionSelectionEvent.Change;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import java.util.Map;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SubstitutionEditView extends JPanel {
private static final long serialVersionUID = 6041242290064429972L;
private MatchOrderType orderType;
private JComboBox playerComboBox;
private JComboBox playerInComboBox;
private JComboBox behaviourComboBox;
private JComboBox positionComboBox;
private JComboBox redCardsComboBox;
private JComboBox standingComboBox;
private PositionChooser positionChooser;
private JSlider whenSlider;
private WhenTextField whenTextField;
public SubstitutionEditView(MatchOrderType orderType) {
this.orderType = orderType;
initComponents();
addListeners();
Map<Integer, PlayerPositionItem> lineupPositions = SubstitutionDataProvider
.getLineupPositions();
this.playerComboBox.setModel(new DefaultComboBoxModel(lineupPositions
.values().toArray()));
this.playerComboBox.setSelectedItem(null);
if (isSubstitution()) {
List<PlayerPositionItem> substitutionPlayers = SubstitutionDataProvider
.getFieldPositions(ISpielerPosition.substKeeper,
ISpielerPosition.substForward, false);
this.playerInComboBox.setModel(new DefaultComboBoxModel(
substitutionPlayers.toArray()));
this.playerInComboBox.setSelectedItem(null);
} else if (isPositionSwap()) {
this.playerInComboBox.setModel(new DefaultComboBoxModel(
lineupPositions.values().toArray()));
this.playerInComboBox.setSelectedItem(null);
}
if (!isPositionSwap()) {
List<PlayerPositionItem> positions = SubstitutionDataProvider
.getFieldPositions(ISpielerPosition.keeper,
ISpielerPosition.leftForward, true);
this.positionComboBox.setModel(new DefaultComboBoxModel(positions
.toArray()));
this.positionComboBox.setSelectedItem(null);
this.positionChooser.init(lineupPositions);
this.behaviourComboBox.setModel(new DefaultComboBoxModel(
SubstitutionDataProvider.getBehaviourItems(
!isNewBehaviour()).toArray()));
}
if (isNewBehaviour()) {
this.behaviourComboBox.setSelectedItem(null);
}
}
/**
* Initializes the view with the given {@link Substitution}. The given
* object will not be changed. To retrieve the data from the view, use
* {@link #getSubstitution()} method.
*
* @param sub
* the substitution to initialize the view.
*/
public void init(Substitution sub) {
this.orderType = sub.getOrderType();
if (sub.getSubjectPlayerID() != -1) {
ComboBoxModel model = this.playerComboBox.getModel();
for (int i = 0; i < model.getSize(); i++) {
if (((PlayerPositionItem) model.getElementAt(i)).getSpieler()
.getSpielerID() == sub.getSubjectPlayerID()) {
playerComboBox.setSelectedItem(model.getElementAt(i));
break;
}
}
}
if (!isNewBehaviour() && sub.getObjectPlayerID() != -1) {
ComboBoxModel model = this.playerInComboBox.getModel();
for (int i = 0; i < model.getSize(); i++) {
if (((PlayerPositionItem) model.getElementAt(i)).getSpieler()
.getSpielerID() == sub.getObjectPlayerID()) {
playerInComboBox.setSelectedItem(model.getElementAt(i));
break;
}
}
}
if (!isPositionSwap()) {
ComboBoxModel model = this.positionComboBox.getModel();
for (int i = 0; i < model.getSize(); i++) {
if (((PlayerPositionItem) model.getElementAt(i)).getPosition()
.byteValue() == sub.getRoleId()) {
positionComboBox.setSelectedItem(model.getElementAt(i));
break;
}
}
}
Helper.markierenComboBox(this.behaviourComboBox, sub.getBehaviour());
Helper.markierenComboBox(this.redCardsComboBox, sub
.getRedCardCriteria().getId());
Helper.markierenComboBox(this.standingComboBox, sub.getStanding()
.getId());
this.whenTextField.setValue(Integer.valueOf(sub
.getMatchMinuteCriteria()));
}
/**
* Gets a new {@link ISubstitution} which represents the values chosen in
* the view. Note that <i>new</i> is returned and not the one which may be
* provided to the {@link #init(ISubstitution)} method.
*
* @return
*/
public Substitution getSubstitution() {
Substitution sub = new Substitution();
sub.setBehaviour((byte) getSelectedId(this.behaviourComboBox));
sub.setRedCardCriteria(RedCardCriteria
.getById((byte) getSelectedId(this.redCardsComboBox)));
sub.setStanding(GoalDiffCriteria
.getById((byte) getSelectedId(this.standingComboBox)));
sub.setMatchMinuteCriteria(((Integer) this.whenTextField.getValue())
.byteValue());
sub.setOrderType(this.orderType);
PlayerPositionItem item = (PlayerPositionItem) this.playerComboBox
.getSelectedItem();
if (item != null) {
sub.setObjectPlayerID(item.getSpieler().getSpielerID());
}
// sub.setPlayerOrderId(id); ???????????
if (!isPositionSwap()) {
item = (PlayerPositionItem) this.positionComboBox.getSelectedItem();
if (item != null) {
if (item.getSpieler() != null) {
sub.setRoleId(item.getPosition().byteValue());
}
sub.setRoleId(item.getPosition().byteValue());
}
}
item = (PlayerPositionItem) this.playerComboBox.getSelectedItem();
if (item != null) {
sub.setSubjectPlayerID(item.getSpieler().getSpielerID());
}
if (isPositionSwap() || isSubstitution()) {
item = (PlayerPositionItem) this.playerInComboBox.getSelectedItem();
if (item != null) {
sub.setObjectPlayerID(item.getSpieler().getSpielerID());
}
} else if (isNewBehaviour()) {
sub.setObjectPlayerID(-1);
}
return sub;
}
private int getSelectedId(JComboBox comboBox) {
CBItem item = (CBItem) comboBox.getSelectedItem();
if (item != null) {
return item.getId();
}
return -1;
}
private void addListeners() {
// ChangeListener that will updates the "when" textfield with the number
// of minutes when slider changed
this.whenSlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
whenTextField.setValue(Integer.valueOf(whenSlider.getModel()
.getValue()));
}
});
// PropertyChangeListener that will update the slider when value in the
// "when" textfield changed
this.whenTextField.addPropertyChangeListener("value",
new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
Integer value = (Integer) whenTextField.getValue();
if (value != null) {
whenSlider.setValue(value.intValue());
} else {
whenSlider.setValue(-1);
}
}
});
if (!isPositionSwap()) {
// ItemListener that will update the PositionChooser if selection in
// the position combobox changes
this.positionComboBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
PlayerPositionItem item = (PlayerPositionItem) positionComboBox
.getSelectedItem();
if (item != null) {
positionChooser.select(Integer.valueOf(item
.getPosition()));
} else {
positionChooser.select(null);
}
}
});
// PositionSelectionListener that will update position combobox
// selection if selection in the PositionChooser changes
this.positionChooser
.addPositionSelectionListener(new PositionSelectionListener() {
@Override
public void selectionChanged(
PositionSelectionEvent event) {
if (event.getChange() == Change.SELECTED) {
for (int i = 0; i < positionComboBox.getModel()
.getSize(); i++) {
PlayerPositionItem item = (PlayerPositionItem) positionComboBox
.getModel().getElementAt(i);
if (event.getPosition().equals(
item.getPosition())) {
if (item != positionComboBox
.getSelectedItem()) {
positionComboBox
.setSelectedItem(item);
}
break;
}
}
} else {
if (positionComboBox.getSelectedItem() != null) {
positionComboBox.setSelectedItem(null);
}
}
}
});
}
}
private void initComponents() {
setLayout(new GridBagLayout());
JLabel playerLabel = new JLabel();
if (isSubstitution()) {
playerLabel.setText(HOVerwaltung.instance().getLanguageString(
"subs.Out"));
} else if (isPositionSwap()) {
playerLabel.setText(HOVerwaltung.instance().getLanguageString(
"subs.Reposition"));
} else {
playerLabel.setText(HOVerwaltung.instance().getLanguageString(
"subs.Player"));
}
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(10, 10, 4, 2);
add(playerLabel, gbc);
this.playerComboBox = new JComboBox();
Dimension comboBoxSize = new Dimension(200,
this.playerComboBox.getPreferredSize().height);
this.playerComboBox.setMinimumSize(comboBoxSize);
this.playerComboBox.setPreferredSize(comboBoxSize);
gbc.gridx = 1;
gbc.insets = new Insets(10, 2, 4, 10);
add(this.playerComboBox, gbc);
if (isSubstitution() || isPositionSwap()) {
JLabel playerInLabel = new JLabel();
if (isSubstitution()) {
playerInLabel.setText(HOVerwaltung.instance()
.getLanguageString("subs.In"));
} else {
playerInLabel.setText(HOVerwaltung.instance()
.getLanguageString("subs.RepositionWith"));
}
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(4, 10, 4, 2);
add(playerInLabel, gbc);
this.playerInComboBox = new JComboBox();
this.playerInComboBox.setMinimumSize(comboBoxSize);
this.playerInComboBox.setPreferredSize(comboBoxSize);
gbc.gridx = 1;
gbc.insets = new Insets(4, 2, 4, 10);
add(this.playerInComboBox, gbc);
}
+ this.behaviourComboBox = new JComboBox();
if (!isPositionSwap()) {
JLabel behaviourLabel = new JLabel(HOVerwaltung.instance()
.getLanguageString("subs.Behavior"));
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(4, 10, 4, 2);
add(behaviourLabel, gbc);
- this.behaviourComboBox = new JComboBox();
this.behaviourComboBox.setMinimumSize(comboBoxSize);
this.behaviourComboBox.setPreferredSize(comboBoxSize);
gbc.gridx = 1;
gbc.insets = new Insets(4, 2, 4, 10);
add(this.behaviourComboBox, gbc);
}
JLabel whenLabel = new JLabel(HOVerwaltung.instance()
.getLanguageString("subs.When"));
gbc.gridx = 0;
gbc.gridy++;
gbc.insets = new Insets(4, 10, 4, 2);
add(whenLabel, gbc);
this.whenTextField = new WhenTextField(HOVerwaltung.instance()
.getLanguageString("subs.MinuteAnytime"), HOVerwaltung
.instance().getLanguageString("subs.MinuteAfterX"));
Dimension textFieldSize = new Dimension(200,
this.whenTextField.getPreferredSize().height);
this.whenTextField.setMinimumSize(textFieldSize);
this.whenTextField.setPreferredSize(textFieldSize);
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 1;
gbc.insets = new Insets(4, 2, 4, 10);
add(this.whenTextField, gbc);
this.whenSlider = new JSlider(-1, 119, -1);
this.whenSlider.setMinimumSize(new Dimension(this.whenTextField
.getMinimumSize().width,
this.whenSlider.getPreferredSize().height));
gbc.gridx = 1;
gbc.gridy++;
gbc.insets = new Insets(0, 2, 8, 10);
add(this.whenSlider, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.gridwidth = 2;
gbc.insets = new Insets(8, 4, 8, 4);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
add(new Divider(HOVerwaltung.instance().getLanguageString(
"subs.AdvancedConditions")), gbc);
gbc.gridwidth = 1;
gbc.weightx = 0.0;
if (!isPositionSwap()) {
JLabel positionLabel = new JLabel(HOVerwaltung.instance()
.getLanguageString("subs.Position"));
gbc.gridx = 0;
gbc.gridy++;
gbc.insets = new Insets(4, 10, 4, 2);
add(positionLabel, gbc);
this.positionComboBox = new JComboBox();
this.positionComboBox.setMinimumSize(comboBoxSize);
this.positionComboBox.setPreferredSize(comboBoxSize);
gbc.gridx = 1;
gbc.insets = new Insets(4, 2, 4, 10);
add(this.positionComboBox, gbc);
this.positionChooser = new PositionChooser();
gbc.gridy++;
gbc.insets = new Insets(2, 10, 8, 10);
gbc.fill = GridBagConstraints.NONE;
add(this.positionChooser, gbc);
}
JLabel redCardsLabel = new JLabel(HOVerwaltung.instance()
.getLanguageString("subs.RedCard"));
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy++;
gbc.insets = new Insets(4, 10, 4, 2);
add(redCardsLabel, gbc);
this.redCardsComboBox = new JComboBox(
SubstitutionDataProvider.getRedCardItems());
this.redCardsComboBox.setMinimumSize(comboBoxSize);
this.redCardsComboBox.setPreferredSize(comboBoxSize);
gbc.gridx = 1;
gbc.insets = new Insets(4, 2, 4, 10);
add(this.redCardsComboBox, gbc);
JLabel standingLabel = new JLabel(HOVerwaltung.instance()
.getLanguageString("subs.Standing"));
gbc.gridx = 0;
gbc.gridy++;
gbc.insets = new Insets(4, 10, 4, 2);
add(standingLabel, gbc);
this.standingComboBox = new JComboBox(
SubstitutionDataProvider.getStandingItems());
this.standingComboBox.setMinimumSize(comboBoxSize);
this.standingComboBox.setPreferredSize(comboBoxSize);
gbc.gridx = 1;
gbc.insets = new Insets(4, 2, 4, 10);
add(this.standingComboBox, gbc);
// dummy to consume all extra space
gbc.gridy++;
gbc.weighty = 1.0;
add(new JPanel(), gbc);
}
private boolean isSubstitution() {
return this.orderType == MatchOrderType.SUBSTITUTION;
}
private boolean isPositionSwap() {
return this.orderType == MatchOrderType.POSITION_SWAP;
}
private boolean isNewBehaviour() {
return this.orderType == MatchOrderType.NEW_BEHAVIOUR;
}
}
| false | true | private void initComponents() {
setLayout(new GridBagLayout());
JLabel playerLabel = new JLabel();
if (isSubstitution()) {
playerLabel.setText(HOVerwaltung.instance().getLanguageString(
"subs.Out"));
} else if (isPositionSwap()) {
playerLabel.setText(HOVerwaltung.instance().getLanguageString(
"subs.Reposition"));
} else {
playerLabel.setText(HOVerwaltung.instance().getLanguageString(
"subs.Player"));
}
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(10, 10, 4, 2);
add(playerLabel, gbc);
this.playerComboBox = new JComboBox();
Dimension comboBoxSize = new Dimension(200,
this.playerComboBox.getPreferredSize().height);
this.playerComboBox.setMinimumSize(comboBoxSize);
this.playerComboBox.setPreferredSize(comboBoxSize);
gbc.gridx = 1;
gbc.insets = new Insets(10, 2, 4, 10);
add(this.playerComboBox, gbc);
if (isSubstitution() || isPositionSwap()) {
JLabel playerInLabel = new JLabel();
if (isSubstitution()) {
playerInLabel.setText(HOVerwaltung.instance()
.getLanguageString("subs.In"));
} else {
playerInLabel.setText(HOVerwaltung.instance()
.getLanguageString("subs.RepositionWith"));
}
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(4, 10, 4, 2);
add(playerInLabel, gbc);
this.playerInComboBox = new JComboBox();
this.playerInComboBox.setMinimumSize(comboBoxSize);
this.playerInComboBox.setPreferredSize(comboBoxSize);
gbc.gridx = 1;
gbc.insets = new Insets(4, 2, 4, 10);
add(this.playerInComboBox, gbc);
}
if (!isPositionSwap()) {
JLabel behaviourLabel = new JLabel(HOVerwaltung.instance()
.getLanguageString("subs.Behavior"));
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(4, 10, 4, 2);
add(behaviourLabel, gbc);
this.behaviourComboBox = new JComboBox();
this.behaviourComboBox.setMinimumSize(comboBoxSize);
this.behaviourComboBox.setPreferredSize(comboBoxSize);
gbc.gridx = 1;
gbc.insets = new Insets(4, 2, 4, 10);
add(this.behaviourComboBox, gbc);
}
JLabel whenLabel = new JLabel(HOVerwaltung.instance()
.getLanguageString("subs.When"));
gbc.gridx = 0;
gbc.gridy++;
gbc.insets = new Insets(4, 10, 4, 2);
add(whenLabel, gbc);
this.whenTextField = new WhenTextField(HOVerwaltung.instance()
.getLanguageString("subs.MinuteAnytime"), HOVerwaltung
.instance().getLanguageString("subs.MinuteAfterX"));
Dimension textFieldSize = new Dimension(200,
this.whenTextField.getPreferredSize().height);
this.whenTextField.setMinimumSize(textFieldSize);
this.whenTextField.setPreferredSize(textFieldSize);
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 1;
gbc.insets = new Insets(4, 2, 4, 10);
add(this.whenTextField, gbc);
this.whenSlider = new JSlider(-1, 119, -1);
this.whenSlider.setMinimumSize(new Dimension(this.whenTextField
.getMinimumSize().width,
this.whenSlider.getPreferredSize().height));
gbc.gridx = 1;
gbc.gridy++;
gbc.insets = new Insets(0, 2, 8, 10);
add(this.whenSlider, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.gridwidth = 2;
gbc.insets = new Insets(8, 4, 8, 4);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
add(new Divider(HOVerwaltung.instance().getLanguageString(
"subs.AdvancedConditions")), gbc);
gbc.gridwidth = 1;
gbc.weightx = 0.0;
if (!isPositionSwap()) {
JLabel positionLabel = new JLabel(HOVerwaltung.instance()
.getLanguageString("subs.Position"));
gbc.gridx = 0;
gbc.gridy++;
gbc.insets = new Insets(4, 10, 4, 2);
add(positionLabel, gbc);
this.positionComboBox = new JComboBox();
this.positionComboBox.setMinimumSize(comboBoxSize);
this.positionComboBox.setPreferredSize(comboBoxSize);
gbc.gridx = 1;
gbc.insets = new Insets(4, 2, 4, 10);
add(this.positionComboBox, gbc);
this.positionChooser = new PositionChooser();
gbc.gridy++;
gbc.insets = new Insets(2, 10, 8, 10);
gbc.fill = GridBagConstraints.NONE;
add(this.positionChooser, gbc);
}
JLabel redCardsLabel = new JLabel(HOVerwaltung.instance()
.getLanguageString("subs.RedCard"));
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy++;
gbc.insets = new Insets(4, 10, 4, 2);
add(redCardsLabel, gbc);
this.redCardsComboBox = new JComboBox(
SubstitutionDataProvider.getRedCardItems());
this.redCardsComboBox.setMinimumSize(comboBoxSize);
this.redCardsComboBox.setPreferredSize(comboBoxSize);
gbc.gridx = 1;
gbc.insets = new Insets(4, 2, 4, 10);
add(this.redCardsComboBox, gbc);
JLabel standingLabel = new JLabel(HOVerwaltung.instance()
.getLanguageString("subs.Standing"));
gbc.gridx = 0;
gbc.gridy++;
gbc.insets = new Insets(4, 10, 4, 2);
add(standingLabel, gbc);
this.standingComboBox = new JComboBox(
SubstitutionDataProvider.getStandingItems());
this.standingComboBox.setMinimumSize(comboBoxSize);
this.standingComboBox.setPreferredSize(comboBoxSize);
gbc.gridx = 1;
gbc.insets = new Insets(4, 2, 4, 10);
add(this.standingComboBox, gbc);
// dummy to consume all extra space
gbc.gridy++;
gbc.weighty = 1.0;
add(new JPanel(), gbc);
}
| private void initComponents() {
setLayout(new GridBagLayout());
JLabel playerLabel = new JLabel();
if (isSubstitution()) {
playerLabel.setText(HOVerwaltung.instance().getLanguageString(
"subs.Out"));
} else if (isPositionSwap()) {
playerLabel.setText(HOVerwaltung.instance().getLanguageString(
"subs.Reposition"));
} else {
playerLabel.setText(HOVerwaltung.instance().getLanguageString(
"subs.Player"));
}
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(10, 10, 4, 2);
add(playerLabel, gbc);
this.playerComboBox = new JComboBox();
Dimension comboBoxSize = new Dimension(200,
this.playerComboBox.getPreferredSize().height);
this.playerComboBox.setMinimumSize(comboBoxSize);
this.playerComboBox.setPreferredSize(comboBoxSize);
gbc.gridx = 1;
gbc.insets = new Insets(10, 2, 4, 10);
add(this.playerComboBox, gbc);
if (isSubstitution() || isPositionSwap()) {
JLabel playerInLabel = new JLabel();
if (isSubstitution()) {
playerInLabel.setText(HOVerwaltung.instance()
.getLanguageString("subs.In"));
} else {
playerInLabel.setText(HOVerwaltung.instance()
.getLanguageString("subs.RepositionWith"));
}
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(4, 10, 4, 2);
add(playerInLabel, gbc);
this.playerInComboBox = new JComboBox();
this.playerInComboBox.setMinimumSize(comboBoxSize);
this.playerInComboBox.setPreferredSize(comboBoxSize);
gbc.gridx = 1;
gbc.insets = new Insets(4, 2, 4, 10);
add(this.playerInComboBox, gbc);
}
this.behaviourComboBox = new JComboBox();
if (!isPositionSwap()) {
JLabel behaviourLabel = new JLabel(HOVerwaltung.instance()
.getLanguageString("subs.Behavior"));
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(4, 10, 4, 2);
add(behaviourLabel, gbc);
this.behaviourComboBox.setMinimumSize(comboBoxSize);
this.behaviourComboBox.setPreferredSize(comboBoxSize);
gbc.gridx = 1;
gbc.insets = new Insets(4, 2, 4, 10);
add(this.behaviourComboBox, gbc);
}
JLabel whenLabel = new JLabel(HOVerwaltung.instance()
.getLanguageString("subs.When"));
gbc.gridx = 0;
gbc.gridy++;
gbc.insets = new Insets(4, 10, 4, 2);
add(whenLabel, gbc);
this.whenTextField = new WhenTextField(HOVerwaltung.instance()
.getLanguageString("subs.MinuteAnytime"), HOVerwaltung
.instance().getLanguageString("subs.MinuteAfterX"));
Dimension textFieldSize = new Dimension(200,
this.whenTextField.getPreferredSize().height);
this.whenTextField.setMinimumSize(textFieldSize);
this.whenTextField.setPreferredSize(textFieldSize);
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 1;
gbc.insets = new Insets(4, 2, 4, 10);
add(this.whenTextField, gbc);
this.whenSlider = new JSlider(-1, 119, -1);
this.whenSlider.setMinimumSize(new Dimension(this.whenTextField
.getMinimumSize().width,
this.whenSlider.getPreferredSize().height));
gbc.gridx = 1;
gbc.gridy++;
gbc.insets = new Insets(0, 2, 8, 10);
add(this.whenSlider, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.gridwidth = 2;
gbc.insets = new Insets(8, 4, 8, 4);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
add(new Divider(HOVerwaltung.instance().getLanguageString(
"subs.AdvancedConditions")), gbc);
gbc.gridwidth = 1;
gbc.weightx = 0.0;
if (!isPositionSwap()) {
JLabel positionLabel = new JLabel(HOVerwaltung.instance()
.getLanguageString("subs.Position"));
gbc.gridx = 0;
gbc.gridy++;
gbc.insets = new Insets(4, 10, 4, 2);
add(positionLabel, gbc);
this.positionComboBox = new JComboBox();
this.positionComboBox.setMinimumSize(comboBoxSize);
this.positionComboBox.setPreferredSize(comboBoxSize);
gbc.gridx = 1;
gbc.insets = new Insets(4, 2, 4, 10);
add(this.positionComboBox, gbc);
this.positionChooser = new PositionChooser();
gbc.gridy++;
gbc.insets = new Insets(2, 10, 8, 10);
gbc.fill = GridBagConstraints.NONE;
add(this.positionChooser, gbc);
}
JLabel redCardsLabel = new JLabel(HOVerwaltung.instance()
.getLanguageString("subs.RedCard"));
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy++;
gbc.insets = new Insets(4, 10, 4, 2);
add(redCardsLabel, gbc);
this.redCardsComboBox = new JComboBox(
SubstitutionDataProvider.getRedCardItems());
this.redCardsComboBox.setMinimumSize(comboBoxSize);
this.redCardsComboBox.setPreferredSize(comboBoxSize);
gbc.gridx = 1;
gbc.insets = new Insets(4, 2, 4, 10);
add(this.redCardsComboBox, gbc);
JLabel standingLabel = new JLabel(HOVerwaltung.instance()
.getLanguageString("subs.Standing"));
gbc.gridx = 0;
gbc.gridy++;
gbc.insets = new Insets(4, 10, 4, 2);
add(standingLabel, gbc);
this.standingComboBox = new JComboBox(
SubstitutionDataProvider.getStandingItems());
this.standingComboBox.setMinimumSize(comboBoxSize);
this.standingComboBox.setPreferredSize(comboBoxSize);
gbc.gridx = 1;
gbc.insets = new Insets(4, 2, 4, 10);
add(this.standingComboBox, gbc);
// dummy to consume all extra space
gbc.gridy++;
gbc.weighty = 1.0;
add(new JPanel(), gbc);
}
|
diff --git a/crypto/src/org/bouncycastle/asn1/DERVisibleString.java b/crypto/src/org/bouncycastle/asn1/DERVisibleString.java
index 13a3aadd..1c385b7a 100644
--- a/crypto/src/org/bouncycastle/asn1/DERVisibleString.java
+++ b/crypto/src/org/bouncycastle/asn1/DERVisibleString.java
@@ -1,123 +1,123 @@
package org.bouncycastle.asn1;
import java.io.IOException;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Strings;
/**
* DER VisibleString object.
*/
public class DERVisibleString
extends ASN1Primitive
implements ASN1String
{
private byte[] string;
/**
* return a Visible String from the passed in object.
*
* @exception IllegalArgumentException if the object cannot be converted.
*/
public static DERVisibleString getInstance(
Object obj)
{
if (obj == null || obj instanceof DERVisibleString)
{
return (DERVisibleString)obj;
}
throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
}
/**
* return a Visible String from a tagged object.
*
* @param obj the tagged object holding the object we want
* @param explicit true if the object is meant to be explicitly
* tagged false otherwise.
* @exception IllegalArgumentException if the tagged object cannot
* be converted.
*/
public static DERVisibleString getInstance(
ASN1TaggedObject obj,
boolean explicit)
{
ASN1Primitive o = obj.getObject();
- if (explicit || o instanceof DERUTF8String)
+ if (explicit || o instanceof DERVisibleString)
{
return getInstance(o);
}
else
{
return new DERVisibleString(ASN1OctetString.getInstance(o).getOctets());
}
}
/**
* basic constructor - byte encoded string.
*/
DERVisibleString(
byte[] string)
{
this.string = string;
}
/**
* basic constructor
*/
public DERVisibleString(
String string)
{
this.string = Strings.toByteArray(string);
}
public String getString()
{
return Strings.fromByteArray(string);
}
public String toString()
{
return getString();
}
public byte[] getOctets()
{
return Arrays.clone(string);
}
boolean isConstructed()
{
return false;
}
int encodedLength()
{
return 1 + StreamUtil.calculateBodyLength(string.length) + string.length;
}
void encode(
ASN1OutputStream out)
throws IOException
{
out.writeEncoded(BERTags.VISIBLE_STRING, this.string);
}
boolean asn1Equals(
ASN1Primitive o)
{
if (!(o instanceof DERVisibleString))
{
return false;
}
return Arrays.areEqual(string, ((DERVisibleString)o).string);
}
public int hashCode()
{
return Arrays.hashCode(string);
}
}
| true | true | public static DERVisibleString getInstance(
ASN1TaggedObject obj,
boolean explicit)
{
ASN1Primitive o = obj.getObject();
if (explicit || o instanceof DERUTF8String)
{
return getInstance(o);
}
else
{
return new DERVisibleString(ASN1OctetString.getInstance(o).getOctets());
}
}
| public static DERVisibleString getInstance(
ASN1TaggedObject obj,
boolean explicit)
{
ASN1Primitive o = obj.getObject();
if (explicit || o instanceof DERVisibleString)
{
return getInstance(o);
}
else
{
return new DERVisibleString(ASN1OctetString.getInstance(o).getOctets());
}
}
|
diff --git a/src/org/woltage/irssiconnectbot/service/TerminalKeyListener.java b/src/org/woltage/irssiconnectbot/service/TerminalKeyListener.java
index 14fd8cf..466d341 100644
--- a/src/org/woltage/irssiconnectbot/service/TerminalKeyListener.java
+++ b/src/org/woltage/irssiconnectbot/service/TerminalKeyListener.java
@@ -1,523 +1,523 @@
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2010 Kenny Root, Jeffrey Sharkey
*
* 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.woltage.irssiconnectbot.service;
import java.io.IOException;
import org.woltage.irssiconnectbot.TerminalView;
import org.woltage.irssiconnectbot.bean.SelectionArea;
import org.woltage.irssiconnectbot.util.PreferenceConstants;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import de.mud.terminal.VDUBuffer;
import de.mud.terminal.vt320;
/**
* @author kenny
*
*/
public class TerminalKeyListener implements OnKeyListener, OnSharedPreferenceChangeListener {
private static final String TAG = "ConnectBot.OnKeyListener";
public final static int META_CTRL_ON = 0x01;
public final static int META_CTRL_LOCK = 0x02;
public final static int META_ALT_ON = 0x04;
public final static int META_ALT_LOCK = 0x08;
public final static int META_SHIFT_ON = 0x10;
public final static int META_SHIFT_LOCK = 0x20;
public final static int META_SLASH = 0x40;
public final static int META_TAB = 0x80;
// The bit mask of momentary and lock states for each
public final static int META_CTRL_MASK = META_CTRL_ON | META_CTRL_LOCK;
public final static int META_ALT_MASK = META_ALT_ON | META_ALT_LOCK;
public final static int META_SHIFT_MASK = META_SHIFT_ON | META_SHIFT_LOCK;
// All the transient key codes
public final static int META_TRANSIENT = META_CTRL_ON | META_ALT_ON
| META_SHIFT_ON;
private final TerminalManager manager;
private final TerminalBridge bridge;
private final VDUBuffer buffer;
protected KeyCharacterMap keymap = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
private String keymode = null;
private boolean hardKeyboard = false;
private int metaState = 0;
private ClipboardManager clipboard = null;
private boolean selectingForCopy = false;
private final SelectionArea selectionArea;
private String encoding;
private final SharedPreferences prefs;
public TerminalKeyListener(TerminalManager manager,
TerminalBridge bridge,
VDUBuffer buffer,
String encoding) {
this.manager = manager;
this.bridge = bridge;
this.buffer = buffer;
this.encoding = encoding;
selectionArea = new SelectionArea();
prefs = PreferenceManager.getDefaultSharedPreferences(manager);
prefs.registerOnSharedPreferenceChangeListener(this);
hardKeyboard = (manager.res.getConfiguration().keyboard
== Configuration.KEYBOARD_QWERTY);
updateKeymode();
}
/**
* Handle onKey() events coming down from a {@link TerminalView} above us.
* Modify the keys to make more sense to a host then pass it to the transport.
*/
public boolean onKey(View v, int keyCode, KeyEvent event) {
try {
final boolean hardKeyboardHidden = manager.hardKeyboardHidden;
// Ignore all key-up events except for the special keys
if (event.getAction() == KeyEvent.ACTION_UP) {
// There's nothing here for virtual keyboard users.
if (!hardKeyboard || (hardKeyboard && hardKeyboardHidden))
return false;
// skip keys if we aren't connected yet or have been disconnected
if (bridge.isDisconnected() || bridge.transport == null)
return false;
if (PreferenceConstants.KEYMODE_RIGHT.equals(keymode)) {
if (keyCode == KeyEvent.KEYCODE_ALT_RIGHT
&& (metaState & META_SLASH) != 0) {
metaState &= ~(META_SLASH | META_TRANSIENT);
bridge.transport.write('/');
return true;
} else if (keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT
&& (metaState & META_TAB) != 0) {
metaState &= ~(META_TAB | META_TRANSIENT);
bridge.transport.write(0x09);
return true;
}
} else if (PreferenceConstants.KEYMODE_LEFT.equals(keymode)) {
if (keyCode == KeyEvent.KEYCODE_ALT_LEFT
&& (metaState & META_SLASH) != 0) {
metaState &= ~(META_SLASH | META_TRANSIENT);
bridge.transport.write('/');
return true;
} else if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
&& (metaState & META_TAB) != 0) {
metaState &= ~(META_TAB | META_TRANSIENT);
bridge.transport.write(0x09);
return true;
}
}
return false;
}
// check for terminal resizing keys
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
bridge.increaseFontSize();
return true;
} else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
bridge.decreaseFontSize();
return true;
}
// skip keys if we aren't connected yet or have been disconnected
if (bridge.isDisconnected() || bridge.transport == null)
return false;
bridge.resetScrollPosition();
boolean printing = (keymap.isPrintingKey(keyCode) || keyCode == KeyEvent.KEYCODE_SPACE);
// otherwise pass through to existing session
// print normal keys
if (printing) {
int curMetaState = event.getMetaState();
metaState &= ~(META_SLASH | META_TAB);
if ((metaState & META_SHIFT_MASK) != 0) {
curMetaState |= KeyEvent.META_SHIFT_ON;
metaState &= ~META_SHIFT_ON;
bridge.redraw();
}
if ((metaState & META_ALT_MASK) != 0) {
curMetaState |= KeyEvent.META_ALT_ON;
metaState &= ~META_ALT_ON;
bridge.redraw();
}
int key = keymap.get(keyCode, curMetaState);
if ((metaState & META_CTRL_MASK) != 0) {
metaState &= ~META_CTRL_ON;
bridge.redraw();
if ((!hardKeyboard || (hardKeyboard && hardKeyboardHidden))
&& sendFunctionKey(keyCode))
return true;
// Support CTRL-a through CTRL-z
if (key >= 0x61 && key <= 0x7A)
key -= 0x60;
// Support CTRL-A through CTRL-_
else if (key >= 0x41 && key <= 0x5F)
key -= 0x40;
else if (key == 0x20)
key = 0x00;
else if (key == 0x3F)
key = 0x7F;
}
// handle pressing f-keys
if ((hardKeyboard && !hardKeyboardHidden)
&& (curMetaState & KeyEvent.META_SHIFT_ON) != 0
&& sendFunctionKey(keyCode))
return true;
if (key < 0x80) {
bridge.transport.write(key);
} else {
// TODO write encoding routine that doesn't allocate each time
- if(prefs.getBoolean("htcDesireZ", false)) {
- // Desire Z, force lowercase! Problem with HW keymapping?
+ if(prefs.getBoolean("htcDesireZ", false) && curMetaState == 0) {
+ // Desire Z, lowercase if curMetaState == 0! Problem with HW keymapping?
if(key == 0xc4)
key = 0xe4;
if(key == 0xd6)
key = 0xf6;
if(key == 0xc5)
key = 0xe5;
if(key == 0xd8)
key = 0xf8;
if(key == 0xc6)
key = 0xe6;
}
bridge.transport.write(new String(Character.toChars(key)).getBytes(encoding));
}
return true;
}
if (keyCode == KeyEvent.KEYCODE_UNKNOWN && event.getAction() == KeyEvent.ACTION_MULTIPLE) {
byte[] input = event.getCharacters().getBytes(encoding);
bridge.transport.write(input);
return true;
}
// try handling keymode shortcuts
if (hardKeyboard && !hardKeyboardHidden &&
event.getRepeatCount() == 0) {
if (PreferenceConstants.KEYMODE_RIGHT.equals(keymode)) {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_RIGHT:
metaState |= META_SLASH;
return true;
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaState |= META_TAB;
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
metaPress(META_SHIFT_ON);
return true;
case KeyEvent.KEYCODE_ALT_LEFT:
metaPress(META_ALT_ON);
return true;
}
} else if (PreferenceConstants.KEYMODE_LEFT.equals(keymode)) {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_LEFT:
metaState |= META_SLASH;
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
metaState |= META_TAB;
return true;
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaPress(META_SHIFT_ON);
return true;
case KeyEvent.KEYCODE_ALT_RIGHT:
metaPress(META_ALT_ON);
return true;
}
} else {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_LEFT:
case KeyEvent.KEYCODE_ALT_RIGHT:
metaPress(META_ALT_ON);
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaPress(META_SHIFT_ON);
return true;
}
}
}
// look for special chars
switch(keyCode) {
case KeyEvent.KEYCODE_CAMERA:
// check to see which shortcut the camera button triggers
String camera = manager.prefs.getString(
PreferenceConstants.CAMERA,
PreferenceConstants.CAMERA_CTRLA_SPACE);
if(PreferenceConstants.CAMERA_CTRLA_SPACE.equals(camera)) {
bridge.transport.write(0x01);
bridge.transport.write(' ');
} else if(PreferenceConstants.CAMERA_CTRLA.equals(camera)) {
bridge.transport.write(0x01);
} else if(PreferenceConstants.CAMERA_ESC.equals(camera)) {
((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0);
} else if(PreferenceConstants.CAMERA_ESC_A.equals(camera)) {
((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0);
bridge.transport.write('a');
}
break;
case KeyEvent.KEYCODE_DEL:
((vt320) buffer).keyPressed(vt320.KEY_BACK_SPACE, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
return true;
case KeyEvent.KEYCODE_ENTER:
((vt320)buffer).keyTyped(vt320.KEY_ENTER, ' ', 0);
metaState &= ~META_TRANSIENT;
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (selectingForCopy) {
selectionArea.decrementColumn();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_LEFT, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_UP:
if (selectingForCopy) {
selectionArea.decrementRow();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_UP, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (selectingForCopy) {
selectionArea.incrementRow();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_DOWN, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (selectingForCopy) {
selectionArea.incrementColumn();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_RIGHT, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
if (selectingForCopy) {
if (selectionArea.isSelectingOrigin())
selectionArea.finishSelectingOrigin();
else {
if (clipboard != null) {
// copy selected area to clipboard
String copiedText = selectionArea.copyFrom(buffer);
clipboard.setText(copiedText);
// XXX STOPSHIP
// manager.notifyUser(manager.getString(
// R.string.console_copy_done,
// copiedText.length()));
selectingForCopy = false;
selectionArea.reset();
}
}
} else {
if ((metaState & META_CTRL_ON) != 0) {
sendEscape();
metaState &= ~META_CTRL_ON;
} else
metaPress(META_CTRL_ON);
}
bridge.redraw();
return true;
}
} catch (IOException e) {
Log.e(TAG, "Problem while trying to handle an onKey() event", e);
try {
bridge.transport.flush();
} catch (IOException ioe) {
Log.d(TAG, "Our transport was closed, dispatching disconnect event");
bridge.dispatchDisconnect(false);
}
} catch (NullPointerException npe) {
Log.d(TAG, "Input before connection established ignored.");
return true;
}
return false;
}
public void sendEscape() {
((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0);
}
/**
* @param key
* @return successful
*/
private boolean sendFunctionKey(int keyCode) {
switch (keyCode) {
case KeyEvent.KEYCODE_1:
((vt320) buffer).keyPressed(vt320.KEY_F1, ' ', 0);
return true;
case KeyEvent.KEYCODE_2:
((vt320) buffer).keyPressed(vt320.KEY_F2, ' ', 0);
return true;
case KeyEvent.KEYCODE_3:
((vt320) buffer).keyPressed(vt320.KEY_F3, ' ', 0);
return true;
case KeyEvent.KEYCODE_4:
((vt320) buffer).keyPressed(vt320.KEY_F4, ' ', 0);
return true;
case KeyEvent.KEYCODE_5:
((vt320) buffer).keyPressed(vt320.KEY_F5, ' ', 0);
return true;
case KeyEvent.KEYCODE_6:
((vt320) buffer).keyPressed(vt320.KEY_F6, ' ', 0);
return true;
case KeyEvent.KEYCODE_7:
((vt320) buffer).keyPressed(vt320.KEY_F7, ' ', 0);
return true;
case KeyEvent.KEYCODE_8:
((vt320) buffer).keyPressed(vt320.KEY_F8, ' ', 0);
return true;
case KeyEvent.KEYCODE_9:
((vt320) buffer).keyPressed(vt320.KEY_F9, ' ', 0);
return true;
case KeyEvent.KEYCODE_0:
((vt320) buffer).keyPressed(vt320.KEY_F10, ' ', 0);
return true;
default:
return false;
}
}
/**
* Handle meta key presses where the key can be locked on.
* <p>
* 1st press: next key to have meta state<br />
* 2nd press: meta state is locked on<br />
* 3rd press: disable meta state
*
* @param code
*/
public void metaPress(int code) {
if ((metaState & (code << 1)) != 0) {
metaState &= ~(code << 1);
} else if ((metaState & code) != 0) {
metaState &= ~code;
metaState |= code << 1;
} else
metaState |= code;
bridge.redraw();
}
public void setTerminalKeyMode(String keymode) {
this.keymode = keymode;
}
private int getStateForBuffer() {
int bufferState = 0;
if ((metaState & META_CTRL_MASK) != 0)
bufferState |= vt320.KEY_CONTROL;
if ((metaState & META_SHIFT_MASK) != 0)
bufferState |= vt320.KEY_SHIFT;
if ((metaState & META_ALT_MASK) != 0)
bufferState |= vt320.KEY_ALT;
return bufferState;
}
public int getMetaState() {
return metaState;
}
public void setClipboardManager(ClipboardManager clipboard) {
this.clipboard = clipboard;
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (PreferenceConstants.KEYMODE.equals(key)) {
updateKeymode();
}
}
private void updateKeymode() {
keymode = prefs.getString(PreferenceConstants.KEYMODE, PreferenceConstants.KEYMODE_RIGHT);
}
public void setCharset(String encoding) {
this.encoding = encoding;
}
}
| true | true | public boolean onKey(View v, int keyCode, KeyEvent event) {
try {
final boolean hardKeyboardHidden = manager.hardKeyboardHidden;
// Ignore all key-up events except for the special keys
if (event.getAction() == KeyEvent.ACTION_UP) {
// There's nothing here for virtual keyboard users.
if (!hardKeyboard || (hardKeyboard && hardKeyboardHidden))
return false;
// skip keys if we aren't connected yet or have been disconnected
if (bridge.isDisconnected() || bridge.transport == null)
return false;
if (PreferenceConstants.KEYMODE_RIGHT.equals(keymode)) {
if (keyCode == KeyEvent.KEYCODE_ALT_RIGHT
&& (metaState & META_SLASH) != 0) {
metaState &= ~(META_SLASH | META_TRANSIENT);
bridge.transport.write('/');
return true;
} else if (keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT
&& (metaState & META_TAB) != 0) {
metaState &= ~(META_TAB | META_TRANSIENT);
bridge.transport.write(0x09);
return true;
}
} else if (PreferenceConstants.KEYMODE_LEFT.equals(keymode)) {
if (keyCode == KeyEvent.KEYCODE_ALT_LEFT
&& (metaState & META_SLASH) != 0) {
metaState &= ~(META_SLASH | META_TRANSIENT);
bridge.transport.write('/');
return true;
} else if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
&& (metaState & META_TAB) != 0) {
metaState &= ~(META_TAB | META_TRANSIENT);
bridge.transport.write(0x09);
return true;
}
}
return false;
}
// check for terminal resizing keys
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
bridge.increaseFontSize();
return true;
} else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
bridge.decreaseFontSize();
return true;
}
// skip keys if we aren't connected yet or have been disconnected
if (bridge.isDisconnected() || bridge.transport == null)
return false;
bridge.resetScrollPosition();
boolean printing = (keymap.isPrintingKey(keyCode) || keyCode == KeyEvent.KEYCODE_SPACE);
// otherwise pass through to existing session
// print normal keys
if (printing) {
int curMetaState = event.getMetaState();
metaState &= ~(META_SLASH | META_TAB);
if ((metaState & META_SHIFT_MASK) != 0) {
curMetaState |= KeyEvent.META_SHIFT_ON;
metaState &= ~META_SHIFT_ON;
bridge.redraw();
}
if ((metaState & META_ALT_MASK) != 0) {
curMetaState |= KeyEvent.META_ALT_ON;
metaState &= ~META_ALT_ON;
bridge.redraw();
}
int key = keymap.get(keyCode, curMetaState);
if ((metaState & META_CTRL_MASK) != 0) {
metaState &= ~META_CTRL_ON;
bridge.redraw();
if ((!hardKeyboard || (hardKeyboard && hardKeyboardHidden))
&& sendFunctionKey(keyCode))
return true;
// Support CTRL-a through CTRL-z
if (key >= 0x61 && key <= 0x7A)
key -= 0x60;
// Support CTRL-A through CTRL-_
else if (key >= 0x41 && key <= 0x5F)
key -= 0x40;
else if (key == 0x20)
key = 0x00;
else if (key == 0x3F)
key = 0x7F;
}
// handle pressing f-keys
if ((hardKeyboard && !hardKeyboardHidden)
&& (curMetaState & KeyEvent.META_SHIFT_ON) != 0
&& sendFunctionKey(keyCode))
return true;
if (key < 0x80) {
bridge.transport.write(key);
} else {
// TODO write encoding routine that doesn't allocate each time
if(prefs.getBoolean("htcDesireZ", false)) {
// Desire Z, force lowercase! Problem with HW keymapping?
if(key == 0xc4)
key = 0xe4;
if(key == 0xd6)
key = 0xf6;
if(key == 0xc5)
key = 0xe5;
if(key == 0xd8)
key = 0xf8;
if(key == 0xc6)
key = 0xe6;
}
bridge.transport.write(new String(Character.toChars(key)).getBytes(encoding));
}
return true;
}
if (keyCode == KeyEvent.KEYCODE_UNKNOWN && event.getAction() == KeyEvent.ACTION_MULTIPLE) {
byte[] input = event.getCharacters().getBytes(encoding);
bridge.transport.write(input);
return true;
}
// try handling keymode shortcuts
if (hardKeyboard && !hardKeyboardHidden &&
event.getRepeatCount() == 0) {
if (PreferenceConstants.KEYMODE_RIGHT.equals(keymode)) {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_RIGHT:
metaState |= META_SLASH;
return true;
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaState |= META_TAB;
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
metaPress(META_SHIFT_ON);
return true;
case KeyEvent.KEYCODE_ALT_LEFT:
metaPress(META_ALT_ON);
return true;
}
} else if (PreferenceConstants.KEYMODE_LEFT.equals(keymode)) {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_LEFT:
metaState |= META_SLASH;
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
metaState |= META_TAB;
return true;
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaPress(META_SHIFT_ON);
return true;
case KeyEvent.KEYCODE_ALT_RIGHT:
metaPress(META_ALT_ON);
return true;
}
} else {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_LEFT:
case KeyEvent.KEYCODE_ALT_RIGHT:
metaPress(META_ALT_ON);
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaPress(META_SHIFT_ON);
return true;
}
}
}
// look for special chars
switch(keyCode) {
case KeyEvent.KEYCODE_CAMERA:
// check to see which shortcut the camera button triggers
String camera = manager.prefs.getString(
PreferenceConstants.CAMERA,
PreferenceConstants.CAMERA_CTRLA_SPACE);
if(PreferenceConstants.CAMERA_CTRLA_SPACE.equals(camera)) {
bridge.transport.write(0x01);
bridge.transport.write(' ');
} else if(PreferenceConstants.CAMERA_CTRLA.equals(camera)) {
bridge.transport.write(0x01);
} else if(PreferenceConstants.CAMERA_ESC.equals(camera)) {
((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0);
} else if(PreferenceConstants.CAMERA_ESC_A.equals(camera)) {
((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0);
bridge.transport.write('a');
}
break;
case KeyEvent.KEYCODE_DEL:
((vt320) buffer).keyPressed(vt320.KEY_BACK_SPACE, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
return true;
case KeyEvent.KEYCODE_ENTER:
((vt320)buffer).keyTyped(vt320.KEY_ENTER, ' ', 0);
metaState &= ~META_TRANSIENT;
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (selectingForCopy) {
selectionArea.decrementColumn();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_LEFT, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_UP:
if (selectingForCopy) {
selectionArea.decrementRow();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_UP, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (selectingForCopy) {
selectionArea.incrementRow();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_DOWN, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (selectingForCopy) {
selectionArea.incrementColumn();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_RIGHT, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
if (selectingForCopy) {
if (selectionArea.isSelectingOrigin())
selectionArea.finishSelectingOrigin();
else {
if (clipboard != null) {
// copy selected area to clipboard
String copiedText = selectionArea.copyFrom(buffer);
clipboard.setText(copiedText);
// XXX STOPSHIP
// manager.notifyUser(manager.getString(
// R.string.console_copy_done,
// copiedText.length()));
selectingForCopy = false;
selectionArea.reset();
}
}
} else {
if ((metaState & META_CTRL_ON) != 0) {
sendEscape();
metaState &= ~META_CTRL_ON;
} else
metaPress(META_CTRL_ON);
}
bridge.redraw();
return true;
}
} catch (IOException e) {
Log.e(TAG, "Problem while trying to handle an onKey() event", e);
try {
bridge.transport.flush();
} catch (IOException ioe) {
Log.d(TAG, "Our transport was closed, dispatching disconnect event");
bridge.dispatchDisconnect(false);
}
} catch (NullPointerException npe) {
Log.d(TAG, "Input before connection established ignored.");
return true;
}
return false;
}
| public boolean onKey(View v, int keyCode, KeyEvent event) {
try {
final boolean hardKeyboardHidden = manager.hardKeyboardHidden;
// Ignore all key-up events except for the special keys
if (event.getAction() == KeyEvent.ACTION_UP) {
// There's nothing here for virtual keyboard users.
if (!hardKeyboard || (hardKeyboard && hardKeyboardHidden))
return false;
// skip keys if we aren't connected yet or have been disconnected
if (bridge.isDisconnected() || bridge.transport == null)
return false;
if (PreferenceConstants.KEYMODE_RIGHT.equals(keymode)) {
if (keyCode == KeyEvent.KEYCODE_ALT_RIGHT
&& (metaState & META_SLASH) != 0) {
metaState &= ~(META_SLASH | META_TRANSIENT);
bridge.transport.write('/');
return true;
} else if (keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT
&& (metaState & META_TAB) != 0) {
metaState &= ~(META_TAB | META_TRANSIENT);
bridge.transport.write(0x09);
return true;
}
} else if (PreferenceConstants.KEYMODE_LEFT.equals(keymode)) {
if (keyCode == KeyEvent.KEYCODE_ALT_LEFT
&& (metaState & META_SLASH) != 0) {
metaState &= ~(META_SLASH | META_TRANSIENT);
bridge.transport.write('/');
return true;
} else if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
&& (metaState & META_TAB) != 0) {
metaState &= ~(META_TAB | META_TRANSIENT);
bridge.transport.write(0x09);
return true;
}
}
return false;
}
// check for terminal resizing keys
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
bridge.increaseFontSize();
return true;
} else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
bridge.decreaseFontSize();
return true;
}
// skip keys if we aren't connected yet or have been disconnected
if (bridge.isDisconnected() || bridge.transport == null)
return false;
bridge.resetScrollPosition();
boolean printing = (keymap.isPrintingKey(keyCode) || keyCode == KeyEvent.KEYCODE_SPACE);
// otherwise pass through to existing session
// print normal keys
if (printing) {
int curMetaState = event.getMetaState();
metaState &= ~(META_SLASH | META_TAB);
if ((metaState & META_SHIFT_MASK) != 0) {
curMetaState |= KeyEvent.META_SHIFT_ON;
metaState &= ~META_SHIFT_ON;
bridge.redraw();
}
if ((metaState & META_ALT_MASK) != 0) {
curMetaState |= KeyEvent.META_ALT_ON;
metaState &= ~META_ALT_ON;
bridge.redraw();
}
int key = keymap.get(keyCode, curMetaState);
if ((metaState & META_CTRL_MASK) != 0) {
metaState &= ~META_CTRL_ON;
bridge.redraw();
if ((!hardKeyboard || (hardKeyboard && hardKeyboardHidden))
&& sendFunctionKey(keyCode))
return true;
// Support CTRL-a through CTRL-z
if (key >= 0x61 && key <= 0x7A)
key -= 0x60;
// Support CTRL-A through CTRL-_
else if (key >= 0x41 && key <= 0x5F)
key -= 0x40;
else if (key == 0x20)
key = 0x00;
else if (key == 0x3F)
key = 0x7F;
}
// handle pressing f-keys
if ((hardKeyboard && !hardKeyboardHidden)
&& (curMetaState & KeyEvent.META_SHIFT_ON) != 0
&& sendFunctionKey(keyCode))
return true;
if (key < 0x80) {
bridge.transport.write(key);
} else {
// TODO write encoding routine that doesn't allocate each time
if(prefs.getBoolean("htcDesireZ", false) && curMetaState == 0) {
// Desire Z, lowercase if curMetaState == 0! Problem with HW keymapping?
if(key == 0xc4)
key = 0xe4;
if(key == 0xd6)
key = 0xf6;
if(key == 0xc5)
key = 0xe5;
if(key == 0xd8)
key = 0xf8;
if(key == 0xc6)
key = 0xe6;
}
bridge.transport.write(new String(Character.toChars(key)).getBytes(encoding));
}
return true;
}
if (keyCode == KeyEvent.KEYCODE_UNKNOWN && event.getAction() == KeyEvent.ACTION_MULTIPLE) {
byte[] input = event.getCharacters().getBytes(encoding);
bridge.transport.write(input);
return true;
}
// try handling keymode shortcuts
if (hardKeyboard && !hardKeyboardHidden &&
event.getRepeatCount() == 0) {
if (PreferenceConstants.KEYMODE_RIGHT.equals(keymode)) {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_RIGHT:
metaState |= META_SLASH;
return true;
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaState |= META_TAB;
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
metaPress(META_SHIFT_ON);
return true;
case KeyEvent.KEYCODE_ALT_LEFT:
metaPress(META_ALT_ON);
return true;
}
} else if (PreferenceConstants.KEYMODE_LEFT.equals(keymode)) {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_LEFT:
metaState |= META_SLASH;
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
metaState |= META_TAB;
return true;
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaPress(META_SHIFT_ON);
return true;
case KeyEvent.KEYCODE_ALT_RIGHT:
metaPress(META_ALT_ON);
return true;
}
} else {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_LEFT:
case KeyEvent.KEYCODE_ALT_RIGHT:
metaPress(META_ALT_ON);
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaPress(META_SHIFT_ON);
return true;
}
}
}
// look for special chars
switch(keyCode) {
case KeyEvent.KEYCODE_CAMERA:
// check to see which shortcut the camera button triggers
String camera = manager.prefs.getString(
PreferenceConstants.CAMERA,
PreferenceConstants.CAMERA_CTRLA_SPACE);
if(PreferenceConstants.CAMERA_CTRLA_SPACE.equals(camera)) {
bridge.transport.write(0x01);
bridge.transport.write(' ');
} else if(PreferenceConstants.CAMERA_CTRLA.equals(camera)) {
bridge.transport.write(0x01);
} else if(PreferenceConstants.CAMERA_ESC.equals(camera)) {
((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0);
} else if(PreferenceConstants.CAMERA_ESC_A.equals(camera)) {
((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0);
bridge.transport.write('a');
}
break;
case KeyEvent.KEYCODE_DEL:
((vt320) buffer).keyPressed(vt320.KEY_BACK_SPACE, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
return true;
case KeyEvent.KEYCODE_ENTER:
((vt320)buffer).keyTyped(vt320.KEY_ENTER, ' ', 0);
metaState &= ~META_TRANSIENT;
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (selectingForCopy) {
selectionArea.decrementColumn();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_LEFT, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_UP:
if (selectingForCopy) {
selectionArea.decrementRow();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_UP, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (selectingForCopy) {
selectionArea.incrementRow();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_DOWN, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (selectingForCopy) {
selectionArea.incrementColumn();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_RIGHT, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
if (selectingForCopy) {
if (selectionArea.isSelectingOrigin())
selectionArea.finishSelectingOrigin();
else {
if (clipboard != null) {
// copy selected area to clipboard
String copiedText = selectionArea.copyFrom(buffer);
clipboard.setText(copiedText);
// XXX STOPSHIP
// manager.notifyUser(manager.getString(
// R.string.console_copy_done,
// copiedText.length()));
selectingForCopy = false;
selectionArea.reset();
}
}
} else {
if ((metaState & META_CTRL_ON) != 0) {
sendEscape();
metaState &= ~META_CTRL_ON;
} else
metaPress(META_CTRL_ON);
}
bridge.redraw();
return true;
}
} catch (IOException e) {
Log.e(TAG, "Problem while trying to handle an onKey() event", e);
try {
bridge.transport.flush();
} catch (IOException ioe) {
Log.d(TAG, "Our transport was closed, dispatching disconnect event");
bridge.dispatchDisconnect(false);
}
} catch (NullPointerException npe) {
Log.d(TAG, "Input before connection established ignored.");
return true;
}
return false;
}
|
diff --git a/src/org/opensolaris/opengrok/history/HistoryCache.java b/src/org/opensolaris/opengrok/history/HistoryCache.java
index 9e25349..3dad462 100644
--- a/src/org/opensolaris/opengrok/history/HistoryCache.java
+++ b/src/org/opensolaris/opengrok/history/HistoryCache.java
@@ -1,207 +1,215 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* See LICENSE.txt included in this distribution for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
package org.opensolaris.opengrok.history;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.beans.XMLDecoder;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import org.opensolaris.opengrok.configuration.RuntimeEnvironment;
class HistoryCache {
private static Object lock = new Object();
/**
* Retrieve the history for the given file, either from the cache or by
* parsing the history information in the repository.
*
* @param file The file to retrieve history for
* @param parserClass The class that implements the parser to use
* @param repository The external repository to read the history from (can
* be <code>null</code>)
*/
static History get(File file,
Class<? extends HistoryParser> parserClass,
ExternalRepository repository)
throws Exception {
File cache = getCachedFile(file);
boolean hasCache = (cache != null) && cache.exists();
if (hasCache && file.lastModified() < cache.lastModified()) {
try {
return readCache(cache);
} catch (Exception e) {
System.err.println("Error when reading cache file '" +
cache + "':");
e.printStackTrace();
}
}
- long time = System.currentTimeMillis();
HistoryParser parser = parserClass.newInstance();
- History history = parser.parse(file, repository);
+ History history = null;
+ long time;
+ try {
+ time = System.currentTimeMillis();
+ history = parser.parse(file, repository);
+ time = System.currentTimeMillis() - time;
+ } catch (Exception e) {
+ System.err.println("Failed to parse " + file.getAbsolutePath());
+ e.printStackTrace();
+ throw e;
+ }
- time = System.currentTimeMillis() - time;
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
if (env.useHistoryCache()) {
if ((cache != null) &&
(cache.exists() ||
(parser.isCacheable() &&
(time > env.getHistoryReaderTimeLimit())))) {
// retrieving the history takes too long, cache it!
try {
writeCache(history, cache);
} catch (Exception e) {
System.err.println("Error when writing cache file '" +
cache + "':");
e.printStackTrace();
}
}
}
return history;
}
/**
* Get a <code>File</code> object describing the cache file.
*
* @param file the file to find the cache for
* @return file that might contain cached history for <code>file</code>
*/
private static File getCachedFile(File file) {
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
StringBuilder sb = new StringBuilder();
sb.append(env.getDataRootPath());
sb.append(File.separatorChar);
sb.append("historycache");
String sourceRoot = env.getSourceRootPath();
if (sourceRoot == null) {
return null;
}
try {
String add = file.getCanonicalPath().substring(sourceRoot.length());
if (add.length() == 0) {
add = File.separator;
}
sb.append(add);
} catch (IOException ex) {
ex.printStackTrace();
}
sb.append(".log");
return new File(sb.toString());
}
/**
* Write history to a file.
*/
private static void writeCache(History history, File file)
throws IOException {
File dir = file.getParentFile();
if (!dir.isDirectory()) {
if (!dir.mkdirs()) {
throw new IOException(
"Unable to create directory '" + dir + "'.");
}
}
// We have a problem that multiple threads may access the cache layer
// at the same time. Since I would like to avoid read-locking, I just
// serialize the write access to the cache file. The generation of the
// cache file would most likely be executed during index generation, and
// that happens sequencial anyway....
// Generate the file with a temporary name and move it into place when
// I'm done so I don't have to protect the readers for partially updated
// files...
synchronized (lock) {
File output = File.createTempFile("oghist", null, dir);
XMLEncoder e = new XMLEncoder(
new BufferedOutputStream(new FileOutputStream(output)));
e.writeObject(history);
e.close();
if (!file.delete() && file.exists()) {
output.delete();
throw new IOException(
"Cachefile exists, and I could not delete it.");
}
if (!output.renameTo(file)) {
output.delete();
throw new IOException("Failed to rename cache tmpfile.");
}
}
}
/**
* Read history from a file.
*/
private static History readCache(File file) throws IOException {
XMLDecoder d = new XMLDecoder(
new BufferedInputStream(new FileInputStream(file)));
Object obj = d.readObject();
d.close();
return (History) obj;
}
/**
* Store a history object to file in the same format as writeCache, but
* this method does not try to synchonize access (so this function must
* not be called on the same file from multiple threads). It's intended
* usage is from the ExternalRepository's createCache.
* @param name the name of the file (relative from source root)
* @param history the history for this file
* @throws IOException if an error occurs
*/
protected static void writeCacheFile(String name, History history) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append(RuntimeEnvironment.getInstance().getDataRootPath());
sb.append(File.separatorChar);
sb.append("historycache");
sb.append(File.separatorChar);
sb.append(name);
sb.append(".log");
File file = new File(sb.toString());
File dir = file.getParentFile();
if (!dir.isDirectory()) {
if (!dir.mkdirs()) {
throw new IOException(
"Unable to create directory '" + dir + "'.");
}
}
XMLEncoder e = new XMLEncoder(
new BufferedOutputStream(new FileOutputStream(file)));
e.writeObject(history);
e.close();
}
}
| false | true | static History get(File file,
Class<? extends HistoryParser> parserClass,
ExternalRepository repository)
throws Exception {
File cache = getCachedFile(file);
boolean hasCache = (cache != null) && cache.exists();
if (hasCache && file.lastModified() < cache.lastModified()) {
try {
return readCache(cache);
} catch (Exception e) {
System.err.println("Error when reading cache file '" +
cache + "':");
e.printStackTrace();
}
}
long time = System.currentTimeMillis();
HistoryParser parser = parserClass.newInstance();
History history = parser.parse(file, repository);
time = System.currentTimeMillis() - time;
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
if (env.useHistoryCache()) {
if ((cache != null) &&
(cache.exists() ||
(parser.isCacheable() &&
(time > env.getHistoryReaderTimeLimit())))) {
// retrieving the history takes too long, cache it!
try {
writeCache(history, cache);
} catch (Exception e) {
System.err.println("Error when writing cache file '" +
cache + "':");
e.printStackTrace();
}
}
}
return history;
}
| static History get(File file,
Class<? extends HistoryParser> parserClass,
ExternalRepository repository)
throws Exception {
File cache = getCachedFile(file);
boolean hasCache = (cache != null) && cache.exists();
if (hasCache && file.lastModified() < cache.lastModified()) {
try {
return readCache(cache);
} catch (Exception e) {
System.err.println("Error when reading cache file '" +
cache + "':");
e.printStackTrace();
}
}
HistoryParser parser = parserClass.newInstance();
History history = null;
long time;
try {
time = System.currentTimeMillis();
history = parser.parse(file, repository);
time = System.currentTimeMillis() - time;
} catch (Exception e) {
System.err.println("Failed to parse " + file.getAbsolutePath());
e.printStackTrace();
throw e;
}
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
if (env.useHistoryCache()) {
if ((cache != null) &&
(cache.exists() ||
(parser.isCacheable() &&
(time > env.getHistoryReaderTimeLimit())))) {
// retrieving the history takes too long, cache it!
try {
writeCache(history, cache);
} catch (Exception e) {
System.err.println("Error when writing cache file '" +
cache + "':");
e.printStackTrace();
}
}
}
return history;
}
|
diff --git a/src/chameleon/support/test/ExpressionTest.java b/src/chameleon/support/test/ExpressionTest.java
index 1865ee7..7ac5e1a 100644
--- a/src/chameleon/support/test/ExpressionTest.java
+++ b/src/chameleon/support/test/ExpressionTest.java
@@ -1,107 +1,108 @@
package chameleon.support.test;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.Test;
import chameleon.core.expression.Expression;
import chameleon.input.ParseException;
import chameleon.oo.type.Type;
import chameleon.output.Syntax;
import chameleon.test.ModelTest;
import chameleon.test.provider.ElementProvider;
import chameleon.test.provider.ModelProvider;
/**
* @author Marko van Dooren
*/
public class ExpressionTest extends ModelTest {
/**
* Create a new expression tester
* @param provider
* @throws IOException
* @throws ParseException
*/
/*@
@ public behavior
@
@ post modelProvider() == modelProvider;
@ post typeProvider() == typeProvider;
@ post baseRecursive();
@ post customRecursive();
@*/
public ExpressionTest(ModelProvider provider, ElementProvider<Type> typeProvider) throws ParseException, IOException {
super(provider);
_typeProvider = typeProvider;
}
private ElementProvider<Type> _typeProvider;
public ElementProvider<Type> typeProvider() {
return _typeProvider;
}
private static Logger _expressionLogger = Logger.getLogger("chameleon.test.expression");
public static Logger getExpressionLogger() {
return _expressionLogger;
}
public void setLogLevels() {
//Logger.getRootLogger().setLevel(Level.FATAL);
getLogger().setLevel(Level.INFO);
//Logger.getLogger("chameleon.test.expression").setLevel(Level.FATAL);
}
@Test
public void testExpressionTypes() throws Exception {
Collection<Type> types = typeProvider().elements(language());
getLogger().info("Starting to test "+types.size() + " types.");
Iterator<Type> iter = types.iterator();
long startTime = System.nanoTime();
int count = 1;
while (iter.hasNext()) {
Type type = iter.next();
getLogger().info(count+" Testing "+type.getFullyQualifiedName());
processType(type);
count++;
}
long endTime = System.nanoTime();
System.out.println("Testing took "+(endTime-startTime)/1000000+" milliseconds.");
}
private int _count = 0;
public void processType(Type type) throws Exception {
_count++;
Expression expr = null;
Object o = null;
try {
List<Expression> exprs = type.descendants(Expression.class);
for(Expression expression : exprs) {
Syntax syntax = language().connector(Syntax.class);
// if(syntax != null) {
// getExpressionLogger().info(_count + " Testing: "+syntax.toCode(expression));
// } else {
// getExpressionLogger().info(_count + " Add a Syntax connector to the language for printing the code of the expression being tested.");
// }
Type expressionType = expression.getType();
assertTrue(expressionType != null);
// getExpressionLogger().info(_count + " : "+expressionType.getFullyQualifiedName());
}
}
catch (Exception e) {
+ e.printStackTrace();
throw e;
}
}
}
| true | true | public void processType(Type type) throws Exception {
_count++;
Expression expr = null;
Object o = null;
try {
List<Expression> exprs = type.descendants(Expression.class);
for(Expression expression : exprs) {
Syntax syntax = language().connector(Syntax.class);
// if(syntax != null) {
// getExpressionLogger().info(_count + " Testing: "+syntax.toCode(expression));
// } else {
// getExpressionLogger().info(_count + " Add a Syntax connector to the language for printing the code of the expression being tested.");
// }
Type expressionType = expression.getType();
assertTrue(expressionType != null);
// getExpressionLogger().info(_count + " : "+expressionType.getFullyQualifiedName());
}
}
catch (Exception e) {
throw e;
}
}
| public void processType(Type type) throws Exception {
_count++;
Expression expr = null;
Object o = null;
try {
List<Expression> exprs = type.descendants(Expression.class);
for(Expression expression : exprs) {
Syntax syntax = language().connector(Syntax.class);
// if(syntax != null) {
// getExpressionLogger().info(_count + " Testing: "+syntax.toCode(expression));
// } else {
// getExpressionLogger().info(_count + " Add a Syntax connector to the language for printing the code of the expression being tested.");
// }
Type expressionType = expression.getType();
assertTrue(expressionType != null);
// getExpressionLogger().info(_count + " : "+expressionType.getFullyQualifiedName());
}
}
catch (Exception e) {
e.printStackTrace();
throw e;
}
}
|
diff --git a/Paintroid/src/org/catrobat/paintroid/tools/implementation/BaseTool.java b/Paintroid/src/org/catrobat/paintroid/tools/implementation/BaseTool.java
index 3be84e97..5b1cfa48 100644
--- a/Paintroid/src/org/catrobat/paintroid/tools/implementation/BaseTool.java
+++ b/Paintroid/src/org/catrobat/paintroid/tools/implementation/BaseTool.java
@@ -1,316 +1,316 @@
/**
* Paintroid: An image manipulation application for Android.
* Copyright (C) 2010-2013 The Catrobat Team
* (<http://developer.catrobat.org/credits>)
*
* 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 org.catrobat.paintroid.tools.implementation;
import java.util.Observable;
import java.util.Observer;
import org.catrobat.paintroid.MainActivity;
import org.catrobat.paintroid.PaintroidApplication;
import org.catrobat.paintroid.R;
import org.catrobat.paintroid.command.implementation.BaseCommand;
import org.catrobat.paintroid.dialog.BrushPickerDialog;
import org.catrobat.paintroid.dialog.BrushPickerDialog.OnBrushChangedListener;
import org.catrobat.paintroid.dialog.ProgressIntermediateDialog;
import org.catrobat.paintroid.dialog.colorpicker.ColorPickerDialog;
import org.catrobat.paintroid.dialog.colorpicker.ColorPickerDialog.OnColorPickedListener;
import org.catrobat.paintroid.tools.Tool;
import org.catrobat.paintroid.tools.ToolType;
import org.catrobat.paintroid.ui.TopBar.ToolButtonIDs;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Cap;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader;
import android.view.WindowManager;
public abstract class BaseTool extends Observable implements Tool, Observer {
// TODO maybe move to PaintroidApplication.
public static final Paint CHECKERED_PATTERN = new Paint();
protected static final int NO_BUTTON_RESOURCE = R.drawable.icon_menu_no_icon;
public static final float MOVE_TOLERANCE = 5;
public static final int SCROLL_TOLERANCE_PERCENTAGE = 10;
protected static Paint mBitmapPaint;
protected static Paint mCanvasPaint;
protected ToolType mToolType;
protected Context mContext;
protected PointF mMovedDistance;
protected PointF mPreviousEventCoordinate;
protected static int mScrollTolerance;
private OnBrushChangedListener mStroke;
protected OnColorPickedListener mColor;
protected static final PorterDuffXfermode eraseXfermode = new PorterDuffXfermode(
PorterDuff.Mode.CLEAR);
static {
mBitmapPaint = new Paint();
mBitmapPaint.setColor(Color.BLACK);
mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setDither(true);
mBitmapPaint.setStyle(Paint.Style.STROKE);
mBitmapPaint.setStrokeJoin(Paint.Join.ROUND);
mBitmapPaint.setStrokeCap(Paint.Cap.ROUND);
mBitmapPaint.setStrokeWidth(Tool.stroke25);
mCanvasPaint = new Paint(mBitmapPaint);
Bitmap checkerboard = BitmapFactory.decodeResource(
PaintroidApplication.applicationContext.getResources(),
R.drawable.checkeredbg);
BitmapShader shader = new BitmapShader(checkerboard,
Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
CHECKERED_PATTERN.setShader(shader);
WindowManager windowManager = (WindowManager) PaintroidApplication.applicationContext
.getSystemService(Context.WINDOW_SERVICE);
mScrollTolerance = windowManager.getDefaultDisplay().getWidth()
* SCROLL_TOLERANCE_PERCENTAGE / 100;
}
public BaseTool(Context context, ToolType toolType) {
super();
mToolType = toolType;
mContext = context;
mColor = new OnColorPickedListener() {
@Override
public void colorChanged(int color) {
changePaintColor(color);
}
};
mStroke = new OnBrushChangedListener() {
@Override
public void setCap(Cap cap) {
changePaintStrokeCap(cap);
}
@Override
public void setStroke(int strokeWidth) {
changePaintStrokeWidth(strokeWidth);
}
};
BrushPickerDialog.getInstance().addBrushChangedListener(mStroke);
ColorPickerDialog.getInstance().addOnColorPickedListener(mColor);
mMovedDistance = new PointF(0f, 0f);
mPreviousEventCoordinate = new PointF(0f, 0f);
}
@Override
public void changePaintColor(int color) {
mBitmapPaint.setColor(color);
if (Color.alpha(color) == 0x00) {
mBitmapPaint.setXfermode(eraseXfermode);
mCanvasPaint.reset();
mCanvasPaint.setStyle(mBitmapPaint.getStyle());
mCanvasPaint.setStrokeJoin(mBitmapPaint.getStrokeJoin());
mCanvasPaint.setStrokeCap(mBitmapPaint.getStrokeCap());
mCanvasPaint.setStrokeWidth(mBitmapPaint.getStrokeWidth());
mCanvasPaint.setShader(CHECKERED_PATTERN.getShader());
mCanvasPaint.setColor(Color.BLACK);
mBitmapPaint.setAlpha(0x00);
mCanvasPaint.setAlpha(0x00);
} else {
mBitmapPaint.setXfermode(null);
mCanvasPaint.set(mBitmapPaint);
}
super.setChanged();
super.notifyObservers();
}
@Override
public void changePaintStrokeWidth(int strokeWidth) {
mBitmapPaint.setStrokeWidth(strokeWidth);
mCanvasPaint.setStrokeWidth(strokeWidth);
boolean antiAliasing = (strokeWidth > 1);
mBitmapPaint.setAntiAlias(antiAliasing);
mCanvasPaint.setAntiAlias(antiAliasing);
super.setChanged();
super.notifyObservers();
}
@Override
public void changePaintStrokeCap(Cap cap) {
mBitmapPaint.setStrokeCap(cap);
mCanvasPaint.setStrokeCap(cap);
super.setChanged();
super.notifyObservers();
}
@Override
public void setDrawPaint(Paint paint) {
mBitmapPaint.set(paint);
mCanvasPaint.set(paint);
super.setChanged();
super.notifyObservers();
}
@Override
public Paint getDrawPaint() {
return new Paint(mBitmapPaint);
}
@Override
public abstract void draw(Canvas canvas);
@Override
public ToolType getToolType() {
return this.mToolType;
}
protected void showColorPicker() {
ColorPickerDialog.getInstance().addOnColorPickedListener(mColor);
ColorPickerDialog.getInstance().show();
ColorPickerDialog.getInstance().setInitialColor(
getDrawPaint().getColor());
}
protected void showBrushPicker() {
BrushPickerDialog.getInstance().addBrushChangedListener(mStroke);
BrushPickerDialog.getInstance().setCurrentPaint(mBitmapPaint);
BrushPickerDialog.getInstance().show(
((MainActivity) mContext).getSupportFragmentManager(),
"brushpicker");
}
@Override
public void attributeButtonClick(ToolButtonIDs buttonNumber) {
// no default action
}
@Override
public int getAttributeButtonResource(ToolButtonIDs buttonNumber) {
switch (buttonNumber) {
case BUTTON_ID_TOOL:
switch (mToolType) {
case BRUSH:
return R.drawable.icon_menu_brush;
case CROP:
return R.drawable.icon_menu_crop;
case CURSOR:
return R.drawable.icon_menu_cursor;
case ELLIPSE:
return R.drawable.icon_menu_ellipse;
case FILL:
return R.drawable.icon_menu_bucket;
case PIPETTE:
return R.drawable.icon_menu_pipette;
case RECT:
return R.drawable.icon_menu_rectangle;
case STAMP:
return R.drawable.icon_menu_stamp;
case ERASER:
return R.drawable.icon_menu_eraser;
case FLIP:
return R.drawable.icon_menu_flip_horizontal;
case MOVE:
return R.drawable.icon_menu_move;
case ZOOM:
return R.drawable.icon_menu_zoom;
case ROTATE:
- return R.drawable.icon_menu_rotate;
+ return R.drawable.icon_menu_rotate_left;
case LINE:
return R.drawable.icon_menu_straight_line;
default:
return R.drawable.icon_menu_brush;
}
default:
return NO_BUTTON_RESOURCE;
}
}
@Override
public int getAttributeButtonColor(ToolButtonIDs buttonNumber) {
switch (buttonNumber) {
case BUTTON_ID_PARAMETER_TOP:
return mBitmapPaint.getColor();
default:
return Color.BLACK;
}
}
protected int getStrokeColorResource() {
if (mBitmapPaint.getColor() == Color.TRANSPARENT) {
return R.drawable.checkeredbg_repeat;
} else {
return NO_BUTTON_RESOURCE;
}
}
@Override
public void update(Observable observable, Object data) {
if (data instanceof BaseCommand.NOTIFY_STATES) {
if (BaseCommand.NOTIFY_STATES.COMMAND_DONE == data
|| BaseCommand.NOTIFY_STATES.COMMAND_FAILED == data) {
ProgressIntermediateDialog.getInstance().dismiss();
observable.deleteObserver(this);
}
}
}
protected abstract void resetInternalState();
@Override
public void resetInternalState(StateChange stateChange) {
if (getToolType().shouldReactToStateChange(stateChange)) {
resetInternalState();
}
}
@Override
public Point getAutoScrollDirection(float pointX, float pointY,
int viewWidth, int viewHeight) {
int deltaX = 0;
int deltaY = 0;
if (pointX < mScrollTolerance) {
deltaX = 1;
}
if (pointX > viewWidth - mScrollTolerance) {
deltaX = -1;
}
if (pointY < mScrollTolerance) {
deltaY = 1;
}
if (pointY > viewHeight - mScrollTolerance) {
deltaY = -1;
}
return new Point(deltaX, deltaY);
}
}
| true | true | public int getAttributeButtonResource(ToolButtonIDs buttonNumber) {
switch (buttonNumber) {
case BUTTON_ID_TOOL:
switch (mToolType) {
case BRUSH:
return R.drawable.icon_menu_brush;
case CROP:
return R.drawable.icon_menu_crop;
case CURSOR:
return R.drawable.icon_menu_cursor;
case ELLIPSE:
return R.drawable.icon_menu_ellipse;
case FILL:
return R.drawable.icon_menu_bucket;
case PIPETTE:
return R.drawable.icon_menu_pipette;
case RECT:
return R.drawable.icon_menu_rectangle;
case STAMP:
return R.drawable.icon_menu_stamp;
case ERASER:
return R.drawable.icon_menu_eraser;
case FLIP:
return R.drawable.icon_menu_flip_horizontal;
case MOVE:
return R.drawable.icon_menu_move;
case ZOOM:
return R.drawable.icon_menu_zoom;
case ROTATE:
return R.drawable.icon_menu_rotate;
case LINE:
return R.drawable.icon_menu_straight_line;
default:
return R.drawable.icon_menu_brush;
}
default:
return NO_BUTTON_RESOURCE;
}
}
| public int getAttributeButtonResource(ToolButtonIDs buttonNumber) {
switch (buttonNumber) {
case BUTTON_ID_TOOL:
switch (mToolType) {
case BRUSH:
return R.drawable.icon_menu_brush;
case CROP:
return R.drawable.icon_menu_crop;
case CURSOR:
return R.drawable.icon_menu_cursor;
case ELLIPSE:
return R.drawable.icon_menu_ellipse;
case FILL:
return R.drawable.icon_menu_bucket;
case PIPETTE:
return R.drawable.icon_menu_pipette;
case RECT:
return R.drawable.icon_menu_rectangle;
case STAMP:
return R.drawable.icon_menu_stamp;
case ERASER:
return R.drawable.icon_menu_eraser;
case FLIP:
return R.drawable.icon_menu_flip_horizontal;
case MOVE:
return R.drawable.icon_menu_move;
case ZOOM:
return R.drawable.icon_menu_zoom;
case ROTATE:
return R.drawable.icon_menu_rotate_left;
case LINE:
return R.drawable.icon_menu_straight_line;
default:
return R.drawable.icon_menu_brush;
}
default:
return NO_BUTTON_RESOURCE;
}
}
|
diff --git a/farrago/src/net/sf/farrago/namespace/mdr/MedMdrJoinRule.java b/farrago/src/net/sf/farrago/namespace/mdr/MedMdrJoinRule.java
index 760a9afb7..4455bc117 100644
--- a/farrago/src/net/sf/farrago/namespace/mdr/MedMdrJoinRule.java
+++ b/farrago/src/net/sf/farrago/namespace/mdr/MedMdrJoinRule.java
@@ -1,154 +1,158 @@
/*
// $Id$
// Farrago is an extensible data management system.
// Copyright (C) 2005-2005 The Eigenbase Project
// Copyright (C) 2005-2005 Disruptive Tech
// Copyright (C) 2005-2005 LucidEra, Inc.
// Portions Copyright (C) 2003-2005 John V. Sichi
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License, or (at your option)
// any later version approved by The Eigenbase Project.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.sf.farrago.namespace.mdr;
import java.util.List;
import javax.jmi.model.Reference;
import javax.jmi.model.StructuralFeature;
import net.sf.farrago.util.JmiUtil;
import org.eigenbase.rel.*;
import org.eigenbase.relopt.*;
/**
* MedMdrJoinRule is a rule for converting a JoinRel into a
* MedMdrJoinRel when the join condition navigates an association.
*
* @author John V. Sichi
* @version $Id$
*/
class MedMdrJoinRule extends RelOptRule
{
//~ Constructors ----------------------------------------------------------
MedMdrJoinRule()
{
// TODO: allow join to work on inputs other
// than MedMdrClassExtentRel (e.g. filters, projects, other joins)
super(new RelOptRuleOperand(
JoinRel.class,
new RelOptRuleOperand [] {
new RelOptRuleOperand(RelNode.class, null),
new RelOptRuleOperand(MedMdrClassExtentRel.class, null)
}));
}
//~ Methods ---------------------------------------------------------------
// implement RelOptRule
public CallingConvention getOutConvention()
{
return CallingConvention.ITERATOR;
}
// implement RelOptRule
public void onMatch(RelOptRuleCall call)
{
JoinRel joinRel = (JoinRel) call.rels[0];
RelNode leftRel = call.rels[1];
MedMdrClassExtentRel rightRel = (MedMdrClassExtentRel) call.rels[2];
if (!joinRel.getVariablesStopped().isEmpty()) {
return;
}
if ((joinRel.getJoinType() != JoinRelType.INNER)
&& (joinRel.getJoinType() != JoinRelType.LEFT)) {
return;
}
int [] joinFieldOrdinals = new int[2];
if (!RelOptUtil.analyzeSimpleEquiJoin(joinRel, joinFieldOrdinals)) {
return;
}
int leftOrdinal = joinFieldOrdinals[0];
int rightOrdinal = joinFieldOrdinals[1];
// on right side, must join to reference field which refers to
// left side type
List features =
JmiUtil.getFeatures(rightRel.mdrClassExtent.refClass,
StructuralFeature.class, false);
Reference reference;
if (rightOrdinal == features.size()) {
// join to mofId: this is a many-to-one join (primary key lookup on
// right hand side), which we will represent with a null reference
reference = null;
} else {
+ if (rightOrdinal > features.size()) {
+ // Pseudocolumn such as mofClassName: can't join.
+ return;
+ }
StructuralFeature feature =
(StructuralFeature) features.get(rightOrdinal);
if (!(feature instanceof Reference)) {
return;
}
reference = (Reference) feature;
}
// TODO: verify that leftOrdinal specifies a MOFID of an
// appropriate type; also, verify that left and right
// are from same repository
/*
Classifier referencedType = reference.getReferencedEnd().getType();
Classifier leftType =
(Classifier) leftRel.mdrClassExtent.refClass.refMetaObject();
if (!leftType.equals(referencedType)
&& !leftType.allSupertypes().contains(referencedType))
{
// REVIEW: we now know this is a bogus join; could optimize it by
// skipping querying altogether, but a warning of some kind would
// be friendlier
return;
}
*/
RelNode iterLeft =
mergeTraitsAndConvert(
joinRel.getTraits(), CallingConvention.ITERATOR, leftRel);
if (iterLeft == null) {
return;
}
RelNode iterRight =
mergeTraitsAndConvert(
joinRel.getTraits(), CallingConvention.ITERATOR, rightRel);
if (iterRight == null) {
return;
}
call.transformTo(
new MedMdrJoinRel(
joinRel.getCluster(),
iterLeft,
iterRight,
joinRel.getCondition(),
joinRel.getJoinType(),
leftOrdinal,
reference));
}
}
// End MedMdrJoinRule.java
| true | true | public void onMatch(RelOptRuleCall call)
{
JoinRel joinRel = (JoinRel) call.rels[0];
RelNode leftRel = call.rels[1];
MedMdrClassExtentRel rightRel = (MedMdrClassExtentRel) call.rels[2];
if (!joinRel.getVariablesStopped().isEmpty()) {
return;
}
if ((joinRel.getJoinType() != JoinRelType.INNER)
&& (joinRel.getJoinType() != JoinRelType.LEFT)) {
return;
}
int [] joinFieldOrdinals = new int[2];
if (!RelOptUtil.analyzeSimpleEquiJoin(joinRel, joinFieldOrdinals)) {
return;
}
int leftOrdinal = joinFieldOrdinals[0];
int rightOrdinal = joinFieldOrdinals[1];
// on right side, must join to reference field which refers to
// left side type
List features =
JmiUtil.getFeatures(rightRel.mdrClassExtent.refClass,
StructuralFeature.class, false);
Reference reference;
if (rightOrdinal == features.size()) {
// join to mofId: this is a many-to-one join (primary key lookup on
// right hand side), which we will represent with a null reference
reference = null;
} else {
StructuralFeature feature =
(StructuralFeature) features.get(rightOrdinal);
if (!(feature instanceof Reference)) {
return;
}
reference = (Reference) feature;
}
// TODO: verify that leftOrdinal specifies a MOFID of an
// appropriate type; also, verify that left and right
// are from same repository
/*
Classifier referencedType = reference.getReferencedEnd().getType();
Classifier leftType =
(Classifier) leftRel.mdrClassExtent.refClass.refMetaObject();
if (!leftType.equals(referencedType)
&& !leftType.allSupertypes().contains(referencedType))
{
// REVIEW: we now know this is a bogus join; could optimize it by
// skipping querying altogether, but a warning of some kind would
// be friendlier
return;
}
*/
RelNode iterLeft =
mergeTraitsAndConvert(
joinRel.getTraits(), CallingConvention.ITERATOR, leftRel);
if (iterLeft == null) {
return;
}
RelNode iterRight =
mergeTraitsAndConvert(
joinRel.getTraits(), CallingConvention.ITERATOR, rightRel);
if (iterRight == null) {
return;
}
call.transformTo(
new MedMdrJoinRel(
joinRel.getCluster(),
iterLeft,
iterRight,
joinRel.getCondition(),
joinRel.getJoinType(),
leftOrdinal,
reference));
}
| public void onMatch(RelOptRuleCall call)
{
JoinRel joinRel = (JoinRel) call.rels[0];
RelNode leftRel = call.rels[1];
MedMdrClassExtentRel rightRel = (MedMdrClassExtentRel) call.rels[2];
if (!joinRel.getVariablesStopped().isEmpty()) {
return;
}
if ((joinRel.getJoinType() != JoinRelType.INNER)
&& (joinRel.getJoinType() != JoinRelType.LEFT)) {
return;
}
int [] joinFieldOrdinals = new int[2];
if (!RelOptUtil.analyzeSimpleEquiJoin(joinRel, joinFieldOrdinals)) {
return;
}
int leftOrdinal = joinFieldOrdinals[0];
int rightOrdinal = joinFieldOrdinals[1];
// on right side, must join to reference field which refers to
// left side type
List features =
JmiUtil.getFeatures(rightRel.mdrClassExtent.refClass,
StructuralFeature.class, false);
Reference reference;
if (rightOrdinal == features.size()) {
// join to mofId: this is a many-to-one join (primary key lookup on
// right hand side), which we will represent with a null reference
reference = null;
} else {
if (rightOrdinal > features.size()) {
// Pseudocolumn such as mofClassName: can't join.
return;
}
StructuralFeature feature =
(StructuralFeature) features.get(rightOrdinal);
if (!(feature instanceof Reference)) {
return;
}
reference = (Reference) feature;
}
// TODO: verify that leftOrdinal specifies a MOFID of an
// appropriate type; also, verify that left and right
// are from same repository
/*
Classifier referencedType = reference.getReferencedEnd().getType();
Classifier leftType =
(Classifier) leftRel.mdrClassExtent.refClass.refMetaObject();
if (!leftType.equals(referencedType)
&& !leftType.allSupertypes().contains(referencedType))
{
// REVIEW: we now know this is a bogus join; could optimize it by
// skipping querying altogether, but a warning of some kind would
// be friendlier
return;
}
*/
RelNode iterLeft =
mergeTraitsAndConvert(
joinRel.getTraits(), CallingConvention.ITERATOR, leftRel);
if (iterLeft == null) {
return;
}
RelNode iterRight =
mergeTraitsAndConvert(
joinRel.getTraits(), CallingConvention.ITERATOR, rightRel);
if (iterRight == null) {
return;
}
call.transformTo(
new MedMdrJoinRel(
joinRel.getCluster(),
iterLeft,
iterRight,
joinRel.getCondition(),
joinRel.getJoinType(),
leftOrdinal,
reference));
}
|
diff --git a/net.sf.jmoney.qif-stock/src/net/sf/jmoney/qifstock/InvestmentImporter.java b/net.sf.jmoney.qif-stock/src/net/sf/jmoney/qifstock/InvestmentImporter.java
index 38c30916..9602b4b3 100644
--- a/net.sf.jmoney.qif-stock/src/net/sf/jmoney/qifstock/InvestmentImporter.java
+++ b/net.sf.jmoney.qif-stock/src/net/sf/jmoney/qifstock/InvestmentImporter.java
@@ -1,565 +1,565 @@
package net.sf.jmoney.qifstock;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.jmoney.model2.Account;
import net.sf.jmoney.model2.CapitalAccount;
import net.sf.jmoney.model2.Commodity;
import net.sf.jmoney.model2.Currency;
import net.sf.jmoney.model2.Entry;
import net.sf.jmoney.model2.IncomeExpenseAccount;
import net.sf.jmoney.model2.IncomeExpenseAccountInfo;
import net.sf.jmoney.model2.Session;
import net.sf.jmoney.model2.Transaction;
import net.sf.jmoney.qif.IQifImporter;
import net.sf.jmoney.qif.QIFEntry;
import net.sf.jmoney.qif.QIFEntryInfo;
import net.sf.jmoney.qif.QIFPlugin;
import net.sf.jmoney.qif.parser.QifAccount;
import net.sf.jmoney.qif.parser.QifCategoryLine;
import net.sf.jmoney.qif.parser.QifDate;
import net.sf.jmoney.qif.parser.QifFile;
import net.sf.jmoney.qif.parser.QifInvstTransaction;
import net.sf.jmoney.qif.parser.QifSplitTransaction;
import net.sf.jmoney.stocks.model.Stock;
import net.sf.jmoney.stocks.model.StockAccount;
import net.sf.jmoney.stocks.model.StockAccountInfo;
import net.sf.jmoney.stocks.model.StockEntry;
import net.sf.jmoney.stocks.model.StockEntryInfo;
import net.sf.jmoney.stocks.model.StockInfo;
public class InvestmentImporter implements IQifImporter {
/**
* A local copy of all bank accounts in the current session, stored by name.
* Before use accountMap must be initialized by calling the buildAccountMap
* method
*/
private Map<String, CapitalAccount> accountMap = new HashMap<String, CapitalAccount>();
/**
* A local copy of all categories in the current session, stored by name.
* Before use this must be initialized by calling the buildCategoryMap
* method
*/
private Map<String, IncomeExpenseAccount> categoryMap = new HashMap<String, IncomeExpenseAccount>();
/**
* Creates a temporary map of all the accounts in the given session using
* the account's name as the key.
*/
private void buildAccountMap(Session session) {
for (Account account: session.getAccountCollection()) {
if (account instanceof CapitalAccount) {
CapitalAccount capitalAccount = (CapitalAccount)account;
addToCapitalMap(capitalAccount);
}
}
}
private void addToCapitalMap(CapitalAccount capitalAccount) {
accountMap.put(capitalAccount.getName(), capitalAccount);
for (CapitalAccount subAccount: capitalAccount.getSubAccountCollection()) {
addToCapitalMap(subAccount);
}
}
/**
* Creates a temporary map of all the categories in the given session using
* the categories' names as keys.
*/
private void buildCategoryMap(Session session) {
for (Account account: session.getAccountCollection()) {
if (account instanceof IncomeExpenseAccount) {
IncomeExpenseAccount category = (IncomeExpenseAccount) account;
addToCategoryMap(category);
}
}
}
private void addToCategoryMap(IncomeExpenseAccount category) {
categoryMap.put(category.getName(), category);
for (IncomeExpenseAccount subCategory: category.getSubAccountCollection()) {
addToCategoryMap(subCategory);
}
}
public String importData(QifFile qifFile, Session session) {
buildAccountMap(session);
buildCategoryMap(session);
for (QifAccount qifAccount : qifFile.accountList) {
if (qifAccount.getInvstTransactions().size() == 0) {
// No investment transactions, so don't process
continue;
}
StockAccount account = getStockAccount(qifAccount.getName(), session);
// account.setStartBalance(qifAccount.startBalance);
importAccount(session, account, qifAccount.getInvstTransactions());
}
return "some investment transactions";
}
/**
* Imports an account from a QIF-file.
* <P>
* As soon as a split category, memo, or amount is found when one has
* already been specified for the split, a new split is created. If split
* lines are specified then any category specified in the 'L' line is
* ignored. The first split is put into the entry that had been initially
* created for the category.
* <P>
* Split entries that involve transfers are complicated. One or more of the
* splits in a split entry may be a transfer. When a transfer is in a split,
* the QIF export of the other account in the transfer will not show the split.
* It will show only a simple transfer. (At least, that is how MS-Money exports
* QIF data). When we see a transfer, and we find a match indicating that the
* transfer is already is the datastore, we must see whether either end of the
* transfer is a split transaction and we must be sure to keep the split entries.
* Normally, when we find a transfer is already in the datastore, we simply leave
* it there and delete our transaction. However, if our transaction is a split
* entry then we instead keep our transaction and delete the other transaction.
* In the latter case, it is possible that additional data has been set in the
* other transaction and we must copy that data across to our transaction.
* <P>
* If the transaction in this account is split, and there are one or more transfers
* in the split entries, and if the other account in a transfer has already been imported,
* then an entry will have been entered into this account for the transfer amount of that
* split. If there are multiple transfers in the split then multiple entries will exist
* in this account. All of those entries and their transactions must be deleted.
*/
private void importAccount(Session session, StockAccount account,
List<QifInvstTransaction> transactions) {
// TODO: This should come from the account????
Currency currency = session.getDefaultCurrency();
Account miscIncAccount = getCategory("Ameritrade - Misc Income", session);
Account interestIncomeAccount = getCategory("Interest - Ameritrade", session);
Account stockSplitAccount = getStockAccount("Stock Split - Ameritrade", session);
for (QifInvstTransaction qifTransaction : transactions) {
// Create a new transaction
Transaction transaction = session.createTransaction();
System.out.println("Processing " + qifTransaction.getAction());
if (qifTransaction.getAction().equals("MargInt")) {
System.out.println("Processing " + qifTransaction.getAction());
}
// Add the first entry for this transaction and set the account
QIFEntry firstEntry = transaction.createEntry().getExtension(QIFEntryInfo.getPropertySet(), true);
firstEntry.setAccount(account);
transaction.setDate(convertDate(qifTransaction.getDate()));
// Get amount for all cases except script issues, which don't have amounts.
long amount = 0;
if (!qifTransaction.getAction().equals("ScrIssue")
&& !qifTransaction.getAction().equals("ShrsIn")
&& !qifTransaction.getAction().equals("ShrsOut")) {
// There will be no amount if the sale is really because the shares
// are deemed worthless.
if (qifTransaction.getAmount() != null) {
amount = adjustAmount(qifTransaction.getAmount(), currency);
System.out.println("amount: " + amount);
}
}
firstEntry.setReconcilingState(qifTransaction.getStatus());
firstEntry.setMemo(qifTransaction.getMemo());
if (qifTransaction.getAction().equals("ShrsIn") || qifTransaction.getAction().equals("ShrsOut")) {
// For time being, just do as a purchase or sale for zero.
firstEntry.setAmount(0);
// Find the security
String security = qifTransaction.getSecurity();
Stock stock = findStock(session, security);
Long quantity = stock.parse(qifTransaction.getQuantity());
StockEntry saleEntry = transaction.createEntry().getExtension(StockEntryInfo.getPropertySet(), true);
saleEntry.setAccount(account);
if (qifTransaction.getAction().equals("ShrsIn")) {
saleEntry.setAmount(quantity);
} else {
saleEntry.setAmount(-quantity);
}
saleEntry.setStock(stock);
saleEntry.setStockChange(true);
} else if (qifTransaction.getAction().equals("Buy") || qifTransaction.getAction().equals("Sell")) {
if (qifTransaction.getAction().equals("Sell")) {
firstEntry.setAmount(amount);
} else {
firstEntry.setAmount(-amount);
}
// Find the security
String security = qifTransaction.getSecurity();
Stock stock = findStock(session, security);
Long quantity = stock.parse(qifTransaction.getQuantity());
StockEntry saleEntry = transaction.createEntry().getExtension(StockEntryInfo.getPropertySet(), true);
saleEntry.setAccount(account);
if (qifTransaction.getAction().equals("Buy")) {
saleEntry.setAmount(quantity);
} else {
saleEntry.setAmount(-quantity);
}
saleEntry.setStock(stock);
saleEntry.setStockChange(true);
BigDecimal c = new BigDecimal(9.99);
if (qifTransaction.getCommission() != null) {
StockEntry commissionEntry = transaction.createEntry().getExtension(StockEntryInfo.getPropertySet(), true);
commissionEntry.setAccount(account.getCommissionAccount());
commissionEntry.setAmount(adjustAmount(qifTransaction.getCommission().min(c), currency));
commissionEntry.setStock(stock);
if (qifTransaction.getCommission().compareTo(new BigDecimal(9.99)) > 0) {
StockEntry salesFeeEntry = transaction.createEntry().getExtension(StockEntryInfo.getPropertySet(), true);
salesFeeEntry.setAccount(account.getTax1Account());
salesFeeEntry.setAmount(adjustAmount(qifTransaction.getCommission().subtract(c), currency));
salesFeeEntry.setStock(stock);
}
}
} else if (qifTransaction.getAction().equals("Div")) {
firstEntry.setAmount(amount);
Entry dividendEntry = transaction.createEntry();
dividendEntry.setAccount(account.getDividendAccount());
dividendEntry.setAmount(-amount);
} else if (qifTransaction.getAction().equals("IntInc")) {
firstEntry.setAmount(amount);
Entry interestEntry = transaction.createEntry();
interestEntry.setAccount(interestIncomeAccount);
interestEntry.setAmount(-amount);
} else if (qifTransaction.getAction().equals("MiscInc") || qifTransaction.getAction().equals("XIn")) {
firstEntry.setAmount(amount);
Entry transferEntry = transaction.createEntry();
if (qifTransaction.getTransferAccount() == null) {
transferEntry.setAccount(miscIncAccount);
} else {
transferEntry.setAccount(findCategory(session, qifTransaction.getTransferAccount()));
}
transferEntry.setAmount(-amount);
} else if (qifTransaction.getAction().equals("MiscExp") || qifTransaction.getAction().equals("MargInt") || qifTransaction.getAction().equals("XOut")) {
firstEntry.setAmount(-amount);
Entry transferEntry = transaction.createEntry();
if (qifTransaction.getTransferAccount() == null) {
transferEntry.setAccount(interestIncomeAccount);
} else {
transferEntry.setAccount(findCategory(session, qifTransaction.getTransferAccount()));
}
if (qifTransaction.getAction().equals("MargInt")) {
transferEntry.setMemo("margin interest");
} else if (qifTransaction.getAction().equals("MiscExp")) {
transferEntry.setMemo(qifTransaction.getMemo());
} else if (qifTransaction.getAction().equals("XOut")) {
transferEntry.setMemo(qifTransaction.getMemo());
}
- transferEntry.setAmount(-amount);
+ transferEntry.setAmount(amount);
} else if (qifTransaction.getAction().equals("ScrIssue")) {
// For a stock split, the share arrive as though income paid as share
// for an income account. The entry for the source of the shares is
// associated with the shares already in this account.
// Find the security
String security = qifTransaction.getSecurity();
Stock stock = findStock(session, security);
Long quantity = stock.parse(qifTransaction.getQuantity());
int ratio = 1;
if (qifTransaction.getMemo().equals("2:1 stock split")) {
ratio = 2;
}
StockEntry firstEntryAsStock = firstEntry.getExtension(StockEntryInfo.getPropertySet(), true);
firstEntryAsStock.setStock(stock);
firstEntryAsStock.setStockChange(true);
firstEntryAsStock.setAmount(quantity);
StockEntry otherEntry = transaction.createEntry().getExtension(StockEntryInfo.getPropertySet(), true);
otherEntry.setAccount(stockSplitAccount);
otherEntry.setAmount(-quantity);
otherEntry.setStock(stock);
otherEntry.setStockChange(true);
} else {
System.out.println("unknown type");
}
// Process the category
// if (qifTransaction.getSplits().size() == 0) {
// // Add the second entry for this transaction
// Entry secondEntry = transaction.createEntry();
//
// secondEntry.setAmount(-amount);
//
// Account category = findCategory(session, qifTransaction.getCategory());
// secondEntry.setAccount(category);
// if (category instanceof CapitalAccount) {
// // isTransfer = true;
// } else {
// IncomeExpenseAccount incomeExpenseCategory = (IncomeExpenseAccount)category;
// if (incomeExpenseCategory.isMultiCurrency()) {
// secondEntry.setIncomeExpenseCurrency(currency);
// } else {
// // Quicken categories are (I think) always multi-currency.
// // This means that under the quicken model, all expenses are
// // in the same currency as the account from which the expense came.
// // For example, I am visiting a customer in Europe and I incur a
// // business expense in Euro, but I charge to my US dollar billed
// // credit card. Under the JMoney model, the expense category for the
// // client can be set to 'Euro only' and the actual cost in Euro may
// // be entered, resulting an expense report for the European client that
// // has all amounts in Euro exactly matching the receipts.
// // The Quicken model, however, is problematic. The expense shows
// // up in US dollars. The report may translate at some exchange rate,
// // but the amounts on the expense report will then not match the
// // receipts.
// // This gives us a problem in this import. If the currency of the
// // bank account does not match the currency of the category then we do
// // not have sufficient information. Quicken only gives us the amount
// // in the currency of the bank account.
// if (!incomeExpenseCategory.getCurrency().equals(currency)) {
// // TODO: resolve this. For time being, the amount is set even though
// // the currency is different, thus assuming an exchange rate of
// // one to one.
// }
// }
// }
// }
// Split transactions.
for (QifSplitTransaction qifSplit : qifTransaction.getSplits()) {
Entry splitEntry = transaction.createEntry();
splitEntry.setAccount(findCategory(session, qifSplit.getCategory()));
splitEntry.setMemo(qifSplit.getMemo());
splitEntry.setAmount(-adjustAmount(qifSplit.getAmount(), currency));
}
// If we have a transfer then we need to search through the other
// account to see if a matching entry exists and then keep only one
// (if one is a split transaction, we should keep that one, otherwise
// it does not matter which we keep so keep the old one).
for (Entry entry : transaction.getEntryCollection()) {
if (!entry.equals(firstEntry)) {
// Force a category in each account.
// This is required by the JMoney data model.
if (entry.getAccount() == null) {
entry.setAccount(getCategory("Unknown Category", session));
}
if (entry.getAccount() instanceof IncomeExpenseAccount) {
// If this entry is for a multi-currency account,
// set the currency to be the same as the currency for this
// bank account.
if (((IncomeExpenseAccount)entry.getAccount()).isMultiCurrency()) {
entry.setIncomeExpenseCurrency(currency);
}
}
if (entry.getAccount() instanceof CapitalAccount) {
Entry oldEntry = findMatch(account, transaction.getDate(), -entry.getAmount(), transaction);
if (oldEntry != null) {
if (transaction.hasMoreThanTwoEntries()) {
// Our transaction is split. The other should
// not be, so delete the other transaction,
// leaving only our transaction.
Transaction oldTransaction = oldEntry.getTransaction();
if (oldTransaction.hasMoreThanTwoEntries()) {
// We have problems. Both are split.
// For time being, leave both, but we should
// alert the user or something. Actually, this
// should not happen (at least MS-Money does not seem
// to allow this to happen), so perhaps it does not
// really matter what we do.
} else {
// Copy some of the properties across from the old
// before we delete it.
Entry oldOtherEntry = oldTransaction.getOther(oldEntry);
entry.setCheck(oldOtherEntry.getCheck());
entry.setValuta(oldOtherEntry.getValuta());
session.deleteTransaction(oldTransaction);
}
} else {
// Delete the transaction that we have created,
// leaving only the existing transaction.
session.deleteTransaction(transaction);
// We must stop processing because this transaction
// is now dead.
break;
}
}
}
}
}
}
}
private Stock findStock(Session session, String security) {
Stock stock = null;
if (security.length() != 0) {
for (Commodity commodity : session.getCommodityCollection()) {
if (commodity instanceof Stock) {
Stock eachStock = (Stock)commodity;
if (security.equals(eachStock.getSymbol())) {
stock = eachStock;
break;
}
}
}
if (stock == null) {
// Create it. The name is not available in the import file,
// so for time being we use the symbol as the name.
stock = session.createCommodity(StockInfo.getPropertySet());
stock.setName(security);
stock.setSymbol(security);
}
}
return stock;
}
private Date convertDate(QifDate date) {
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.YEAR, date.getYear());
calendar.set(Calendar.MONTH, date.getMonth()-1);
calendar.set(Calendar.DAY_OF_MONTH, date.getDay());
return calendar.getTime();
}
private long adjustAmount(BigDecimal amount, Currency currency) {
// TODO: revisit this method.
return amount.movePointRight(currency.getDecimals()).longValue();
}
/**
* Find an entry in this account that has the given date and amount.
*
* @param date
* @param amount
* @param ourTransaction
* When we look for a match, ignore this transaction. This is the
* transaction we have added so of course it will match. We are
* looking for another transaction that matches.
*/
private Entry findMatch(CapitalAccount capAccount, Date date, long amount, Transaction ourTransaction) {
for (Entry otherEntry : capAccount.getEntries()) {
Transaction otherTransaction = otherEntry.getTransaction();
if (!otherTransaction.equals(ourTransaction)) {
// Transaction dates must match
// Entry amounts must match
if (otherTransaction.getDate().equals(date)
&& otherEntry.getAmount() == amount) {
return otherEntry;
}
}
}
return null;
}
/**
* Returns the account in "session" associated with the category specified
* by "line".
*/
private Account findCategory(Session session, QifCategoryLine qifCategoryLine) {
switch (qifCategoryLine.getType()) {
case CategoryType:
return getCategory(qifCategoryLine.getName(), session);
case SubCategoryType:
IncomeExpenseAccount category = getCategory(qifCategoryLine.getName(), session);
return getSubcategory(qifCategoryLine.getSubCategoryName(), category);
case TransferType:
return getStockAccount(qifCategoryLine.getName(), session);
}
throw new RuntimeException("bad case");
}
/**
* Returns the account with the specified name. If there is no account in
* the session with that name then a new account is created
*
* @param name
* the name of account to get
* @param session
* the session to check for the account
*/
private StockAccount getStockAccount(String name, Session session) {
// Test to see if we have an account with the same name in our map
CapitalAccount account = accountMap.get(name);
// If not then create a new account, set the name and add it to the map
if (account == null) {
account = session.createAccount(StockAccountInfo.getPropertySet());
account.setName(name);
accountMap.put(name, account);
}
if (!(account instanceof StockAccount)) {
// TODO: process error properly
if (QIFPlugin.DEBUG) System.out.println("account is not a currency account");
throw new RuntimeException("account is not a currency account");
}
return (StockAccount)account;
}
/**
* Returns the category with the specified name. If it doesn't exist a new
* category will be created.
*/
private IncomeExpenseAccount getCategory(String name, Session session) {
IncomeExpenseAccount category;
category = categoryMap.get(name);
if (category == null) {
category = session.createAccount(IncomeExpenseAccountInfo.getPropertySet());
category.setName(name);
categoryMap.put(name, category);
}
return category;
}
/**
* Returns the sub-category with the specified name. If it doesn't exist a
* new sub-category will be created. We don't use a map for sub categories
* instead we just iterate through them trying to find a match.
*/
private IncomeExpenseAccount getSubcategory(
String name,
IncomeExpenseAccount category) {
for (IncomeExpenseAccount subcategory : category.getSubAccountCollection()) {
if (subcategory.getName().equals(name))
return subcategory;
}
IncomeExpenseAccount subcategory = category.createSubAccount();
subcategory.setName(name);
return subcategory;
}
}
| true | true | private void importAccount(Session session, StockAccount account,
List<QifInvstTransaction> transactions) {
// TODO: This should come from the account????
Currency currency = session.getDefaultCurrency();
Account miscIncAccount = getCategory("Ameritrade - Misc Income", session);
Account interestIncomeAccount = getCategory("Interest - Ameritrade", session);
Account stockSplitAccount = getStockAccount("Stock Split - Ameritrade", session);
for (QifInvstTransaction qifTransaction : transactions) {
// Create a new transaction
Transaction transaction = session.createTransaction();
System.out.println("Processing " + qifTransaction.getAction());
if (qifTransaction.getAction().equals("MargInt")) {
System.out.println("Processing " + qifTransaction.getAction());
}
// Add the first entry for this transaction and set the account
QIFEntry firstEntry = transaction.createEntry().getExtension(QIFEntryInfo.getPropertySet(), true);
firstEntry.setAccount(account);
transaction.setDate(convertDate(qifTransaction.getDate()));
// Get amount for all cases except script issues, which don't have amounts.
long amount = 0;
if (!qifTransaction.getAction().equals("ScrIssue")
&& !qifTransaction.getAction().equals("ShrsIn")
&& !qifTransaction.getAction().equals("ShrsOut")) {
// There will be no amount if the sale is really because the shares
// are deemed worthless.
if (qifTransaction.getAmount() != null) {
amount = adjustAmount(qifTransaction.getAmount(), currency);
System.out.println("amount: " + amount);
}
}
firstEntry.setReconcilingState(qifTransaction.getStatus());
firstEntry.setMemo(qifTransaction.getMemo());
if (qifTransaction.getAction().equals("ShrsIn") || qifTransaction.getAction().equals("ShrsOut")) {
// For time being, just do as a purchase or sale for zero.
firstEntry.setAmount(0);
// Find the security
String security = qifTransaction.getSecurity();
Stock stock = findStock(session, security);
Long quantity = stock.parse(qifTransaction.getQuantity());
StockEntry saleEntry = transaction.createEntry().getExtension(StockEntryInfo.getPropertySet(), true);
saleEntry.setAccount(account);
if (qifTransaction.getAction().equals("ShrsIn")) {
saleEntry.setAmount(quantity);
} else {
saleEntry.setAmount(-quantity);
}
saleEntry.setStock(stock);
saleEntry.setStockChange(true);
} else if (qifTransaction.getAction().equals("Buy") || qifTransaction.getAction().equals("Sell")) {
if (qifTransaction.getAction().equals("Sell")) {
firstEntry.setAmount(amount);
} else {
firstEntry.setAmount(-amount);
}
// Find the security
String security = qifTransaction.getSecurity();
Stock stock = findStock(session, security);
Long quantity = stock.parse(qifTransaction.getQuantity());
StockEntry saleEntry = transaction.createEntry().getExtension(StockEntryInfo.getPropertySet(), true);
saleEntry.setAccount(account);
if (qifTransaction.getAction().equals("Buy")) {
saleEntry.setAmount(quantity);
} else {
saleEntry.setAmount(-quantity);
}
saleEntry.setStock(stock);
saleEntry.setStockChange(true);
BigDecimal c = new BigDecimal(9.99);
if (qifTransaction.getCommission() != null) {
StockEntry commissionEntry = transaction.createEntry().getExtension(StockEntryInfo.getPropertySet(), true);
commissionEntry.setAccount(account.getCommissionAccount());
commissionEntry.setAmount(adjustAmount(qifTransaction.getCommission().min(c), currency));
commissionEntry.setStock(stock);
if (qifTransaction.getCommission().compareTo(new BigDecimal(9.99)) > 0) {
StockEntry salesFeeEntry = transaction.createEntry().getExtension(StockEntryInfo.getPropertySet(), true);
salesFeeEntry.setAccount(account.getTax1Account());
salesFeeEntry.setAmount(adjustAmount(qifTransaction.getCommission().subtract(c), currency));
salesFeeEntry.setStock(stock);
}
}
} else if (qifTransaction.getAction().equals("Div")) {
firstEntry.setAmount(amount);
Entry dividendEntry = transaction.createEntry();
dividendEntry.setAccount(account.getDividendAccount());
dividendEntry.setAmount(-amount);
} else if (qifTransaction.getAction().equals("IntInc")) {
firstEntry.setAmount(amount);
Entry interestEntry = transaction.createEntry();
interestEntry.setAccount(interestIncomeAccount);
interestEntry.setAmount(-amount);
} else if (qifTransaction.getAction().equals("MiscInc") || qifTransaction.getAction().equals("XIn")) {
firstEntry.setAmount(amount);
Entry transferEntry = transaction.createEntry();
if (qifTransaction.getTransferAccount() == null) {
transferEntry.setAccount(miscIncAccount);
} else {
transferEntry.setAccount(findCategory(session, qifTransaction.getTransferAccount()));
}
transferEntry.setAmount(-amount);
} else if (qifTransaction.getAction().equals("MiscExp") || qifTransaction.getAction().equals("MargInt") || qifTransaction.getAction().equals("XOut")) {
firstEntry.setAmount(-amount);
Entry transferEntry = transaction.createEntry();
if (qifTransaction.getTransferAccount() == null) {
transferEntry.setAccount(interestIncomeAccount);
} else {
transferEntry.setAccount(findCategory(session, qifTransaction.getTransferAccount()));
}
if (qifTransaction.getAction().equals("MargInt")) {
transferEntry.setMemo("margin interest");
} else if (qifTransaction.getAction().equals("MiscExp")) {
transferEntry.setMemo(qifTransaction.getMemo());
} else if (qifTransaction.getAction().equals("XOut")) {
transferEntry.setMemo(qifTransaction.getMemo());
}
transferEntry.setAmount(-amount);
} else if (qifTransaction.getAction().equals("ScrIssue")) {
// For a stock split, the share arrive as though income paid as share
// for an income account. The entry for the source of the shares is
// associated with the shares already in this account.
// Find the security
String security = qifTransaction.getSecurity();
Stock stock = findStock(session, security);
Long quantity = stock.parse(qifTransaction.getQuantity());
int ratio = 1;
if (qifTransaction.getMemo().equals("2:1 stock split")) {
ratio = 2;
}
StockEntry firstEntryAsStock = firstEntry.getExtension(StockEntryInfo.getPropertySet(), true);
firstEntryAsStock.setStock(stock);
firstEntryAsStock.setStockChange(true);
firstEntryAsStock.setAmount(quantity);
StockEntry otherEntry = transaction.createEntry().getExtension(StockEntryInfo.getPropertySet(), true);
otherEntry.setAccount(stockSplitAccount);
otherEntry.setAmount(-quantity);
otherEntry.setStock(stock);
otherEntry.setStockChange(true);
} else {
System.out.println("unknown type");
}
// Process the category
// if (qifTransaction.getSplits().size() == 0) {
// // Add the second entry for this transaction
// Entry secondEntry = transaction.createEntry();
//
// secondEntry.setAmount(-amount);
//
// Account category = findCategory(session, qifTransaction.getCategory());
// secondEntry.setAccount(category);
// if (category instanceof CapitalAccount) {
// // isTransfer = true;
// } else {
// IncomeExpenseAccount incomeExpenseCategory = (IncomeExpenseAccount)category;
// if (incomeExpenseCategory.isMultiCurrency()) {
// secondEntry.setIncomeExpenseCurrency(currency);
// } else {
// // Quicken categories are (I think) always multi-currency.
// // This means that under the quicken model, all expenses are
// // in the same currency as the account from which the expense came.
// // For example, I am visiting a customer in Europe and I incur a
// // business expense in Euro, but I charge to my US dollar billed
// // credit card. Under the JMoney model, the expense category for the
// // client can be set to 'Euro only' and the actual cost in Euro may
// // be entered, resulting an expense report for the European client that
// // has all amounts in Euro exactly matching the receipts.
// // The Quicken model, however, is problematic. The expense shows
// // up in US dollars. The report may translate at some exchange rate,
// // but the amounts on the expense report will then not match the
// // receipts.
// // This gives us a problem in this import. If the currency of the
// // bank account does not match the currency of the category then we do
// // not have sufficient information. Quicken only gives us the amount
// // in the currency of the bank account.
// if (!incomeExpenseCategory.getCurrency().equals(currency)) {
// // TODO: resolve this. For time being, the amount is set even though
// // the currency is different, thus assuming an exchange rate of
// // one to one.
// }
// }
// }
// }
// Split transactions.
for (QifSplitTransaction qifSplit : qifTransaction.getSplits()) {
Entry splitEntry = transaction.createEntry();
splitEntry.setAccount(findCategory(session, qifSplit.getCategory()));
splitEntry.setMemo(qifSplit.getMemo());
splitEntry.setAmount(-adjustAmount(qifSplit.getAmount(), currency));
}
// If we have a transfer then we need to search through the other
// account to see if a matching entry exists and then keep only one
// (if one is a split transaction, we should keep that one, otherwise
// it does not matter which we keep so keep the old one).
for (Entry entry : transaction.getEntryCollection()) {
if (!entry.equals(firstEntry)) {
// Force a category in each account.
// This is required by the JMoney data model.
if (entry.getAccount() == null) {
entry.setAccount(getCategory("Unknown Category", session));
}
if (entry.getAccount() instanceof IncomeExpenseAccount) {
// If this entry is for a multi-currency account,
// set the currency to be the same as the currency for this
// bank account.
if (((IncomeExpenseAccount)entry.getAccount()).isMultiCurrency()) {
entry.setIncomeExpenseCurrency(currency);
}
}
if (entry.getAccount() instanceof CapitalAccount) {
Entry oldEntry = findMatch(account, transaction.getDate(), -entry.getAmount(), transaction);
if (oldEntry != null) {
if (transaction.hasMoreThanTwoEntries()) {
// Our transaction is split. The other should
// not be, so delete the other transaction,
// leaving only our transaction.
Transaction oldTransaction = oldEntry.getTransaction();
if (oldTransaction.hasMoreThanTwoEntries()) {
// We have problems. Both are split.
// For time being, leave both, but we should
// alert the user or something. Actually, this
// should not happen (at least MS-Money does not seem
// to allow this to happen), so perhaps it does not
// really matter what we do.
} else {
// Copy some of the properties across from the old
// before we delete it.
Entry oldOtherEntry = oldTransaction.getOther(oldEntry);
entry.setCheck(oldOtherEntry.getCheck());
entry.setValuta(oldOtherEntry.getValuta());
session.deleteTransaction(oldTransaction);
}
} else {
// Delete the transaction that we have created,
// leaving only the existing transaction.
session.deleteTransaction(transaction);
// We must stop processing because this transaction
// is now dead.
break;
}
}
}
}
}
}
}
| private void importAccount(Session session, StockAccount account,
List<QifInvstTransaction> transactions) {
// TODO: This should come from the account????
Currency currency = session.getDefaultCurrency();
Account miscIncAccount = getCategory("Ameritrade - Misc Income", session);
Account interestIncomeAccount = getCategory("Interest - Ameritrade", session);
Account stockSplitAccount = getStockAccount("Stock Split - Ameritrade", session);
for (QifInvstTransaction qifTransaction : transactions) {
// Create a new transaction
Transaction transaction = session.createTransaction();
System.out.println("Processing " + qifTransaction.getAction());
if (qifTransaction.getAction().equals("MargInt")) {
System.out.println("Processing " + qifTransaction.getAction());
}
// Add the first entry for this transaction and set the account
QIFEntry firstEntry = transaction.createEntry().getExtension(QIFEntryInfo.getPropertySet(), true);
firstEntry.setAccount(account);
transaction.setDate(convertDate(qifTransaction.getDate()));
// Get amount for all cases except script issues, which don't have amounts.
long amount = 0;
if (!qifTransaction.getAction().equals("ScrIssue")
&& !qifTransaction.getAction().equals("ShrsIn")
&& !qifTransaction.getAction().equals("ShrsOut")) {
// There will be no amount if the sale is really because the shares
// are deemed worthless.
if (qifTransaction.getAmount() != null) {
amount = adjustAmount(qifTransaction.getAmount(), currency);
System.out.println("amount: " + amount);
}
}
firstEntry.setReconcilingState(qifTransaction.getStatus());
firstEntry.setMemo(qifTransaction.getMemo());
if (qifTransaction.getAction().equals("ShrsIn") || qifTransaction.getAction().equals("ShrsOut")) {
// For time being, just do as a purchase or sale for zero.
firstEntry.setAmount(0);
// Find the security
String security = qifTransaction.getSecurity();
Stock stock = findStock(session, security);
Long quantity = stock.parse(qifTransaction.getQuantity());
StockEntry saleEntry = transaction.createEntry().getExtension(StockEntryInfo.getPropertySet(), true);
saleEntry.setAccount(account);
if (qifTransaction.getAction().equals("ShrsIn")) {
saleEntry.setAmount(quantity);
} else {
saleEntry.setAmount(-quantity);
}
saleEntry.setStock(stock);
saleEntry.setStockChange(true);
} else if (qifTransaction.getAction().equals("Buy") || qifTransaction.getAction().equals("Sell")) {
if (qifTransaction.getAction().equals("Sell")) {
firstEntry.setAmount(amount);
} else {
firstEntry.setAmount(-amount);
}
// Find the security
String security = qifTransaction.getSecurity();
Stock stock = findStock(session, security);
Long quantity = stock.parse(qifTransaction.getQuantity());
StockEntry saleEntry = transaction.createEntry().getExtension(StockEntryInfo.getPropertySet(), true);
saleEntry.setAccount(account);
if (qifTransaction.getAction().equals("Buy")) {
saleEntry.setAmount(quantity);
} else {
saleEntry.setAmount(-quantity);
}
saleEntry.setStock(stock);
saleEntry.setStockChange(true);
BigDecimal c = new BigDecimal(9.99);
if (qifTransaction.getCommission() != null) {
StockEntry commissionEntry = transaction.createEntry().getExtension(StockEntryInfo.getPropertySet(), true);
commissionEntry.setAccount(account.getCommissionAccount());
commissionEntry.setAmount(adjustAmount(qifTransaction.getCommission().min(c), currency));
commissionEntry.setStock(stock);
if (qifTransaction.getCommission().compareTo(new BigDecimal(9.99)) > 0) {
StockEntry salesFeeEntry = transaction.createEntry().getExtension(StockEntryInfo.getPropertySet(), true);
salesFeeEntry.setAccount(account.getTax1Account());
salesFeeEntry.setAmount(adjustAmount(qifTransaction.getCommission().subtract(c), currency));
salesFeeEntry.setStock(stock);
}
}
} else if (qifTransaction.getAction().equals("Div")) {
firstEntry.setAmount(amount);
Entry dividendEntry = transaction.createEntry();
dividendEntry.setAccount(account.getDividendAccount());
dividendEntry.setAmount(-amount);
} else if (qifTransaction.getAction().equals("IntInc")) {
firstEntry.setAmount(amount);
Entry interestEntry = transaction.createEntry();
interestEntry.setAccount(interestIncomeAccount);
interestEntry.setAmount(-amount);
} else if (qifTransaction.getAction().equals("MiscInc") || qifTransaction.getAction().equals("XIn")) {
firstEntry.setAmount(amount);
Entry transferEntry = transaction.createEntry();
if (qifTransaction.getTransferAccount() == null) {
transferEntry.setAccount(miscIncAccount);
} else {
transferEntry.setAccount(findCategory(session, qifTransaction.getTransferAccount()));
}
transferEntry.setAmount(-amount);
} else if (qifTransaction.getAction().equals("MiscExp") || qifTransaction.getAction().equals("MargInt") || qifTransaction.getAction().equals("XOut")) {
firstEntry.setAmount(-amount);
Entry transferEntry = transaction.createEntry();
if (qifTransaction.getTransferAccount() == null) {
transferEntry.setAccount(interestIncomeAccount);
} else {
transferEntry.setAccount(findCategory(session, qifTransaction.getTransferAccount()));
}
if (qifTransaction.getAction().equals("MargInt")) {
transferEntry.setMemo("margin interest");
} else if (qifTransaction.getAction().equals("MiscExp")) {
transferEntry.setMemo(qifTransaction.getMemo());
} else if (qifTransaction.getAction().equals("XOut")) {
transferEntry.setMemo(qifTransaction.getMemo());
}
transferEntry.setAmount(amount);
} else if (qifTransaction.getAction().equals("ScrIssue")) {
// For a stock split, the share arrive as though income paid as share
// for an income account. The entry for the source of the shares is
// associated with the shares already in this account.
// Find the security
String security = qifTransaction.getSecurity();
Stock stock = findStock(session, security);
Long quantity = stock.parse(qifTransaction.getQuantity());
int ratio = 1;
if (qifTransaction.getMemo().equals("2:1 stock split")) {
ratio = 2;
}
StockEntry firstEntryAsStock = firstEntry.getExtension(StockEntryInfo.getPropertySet(), true);
firstEntryAsStock.setStock(stock);
firstEntryAsStock.setStockChange(true);
firstEntryAsStock.setAmount(quantity);
StockEntry otherEntry = transaction.createEntry().getExtension(StockEntryInfo.getPropertySet(), true);
otherEntry.setAccount(stockSplitAccount);
otherEntry.setAmount(-quantity);
otherEntry.setStock(stock);
otherEntry.setStockChange(true);
} else {
System.out.println("unknown type");
}
// Process the category
// if (qifTransaction.getSplits().size() == 0) {
// // Add the second entry for this transaction
// Entry secondEntry = transaction.createEntry();
//
// secondEntry.setAmount(-amount);
//
// Account category = findCategory(session, qifTransaction.getCategory());
// secondEntry.setAccount(category);
// if (category instanceof CapitalAccount) {
// // isTransfer = true;
// } else {
// IncomeExpenseAccount incomeExpenseCategory = (IncomeExpenseAccount)category;
// if (incomeExpenseCategory.isMultiCurrency()) {
// secondEntry.setIncomeExpenseCurrency(currency);
// } else {
// // Quicken categories are (I think) always multi-currency.
// // This means that under the quicken model, all expenses are
// // in the same currency as the account from which the expense came.
// // For example, I am visiting a customer in Europe and I incur a
// // business expense in Euro, but I charge to my US dollar billed
// // credit card. Under the JMoney model, the expense category for the
// // client can be set to 'Euro only' and the actual cost in Euro may
// // be entered, resulting an expense report for the European client that
// // has all amounts in Euro exactly matching the receipts.
// // The Quicken model, however, is problematic. The expense shows
// // up in US dollars. The report may translate at some exchange rate,
// // but the amounts on the expense report will then not match the
// // receipts.
// // This gives us a problem in this import. If the currency of the
// // bank account does not match the currency of the category then we do
// // not have sufficient information. Quicken only gives us the amount
// // in the currency of the bank account.
// if (!incomeExpenseCategory.getCurrency().equals(currency)) {
// // TODO: resolve this. For time being, the amount is set even though
// // the currency is different, thus assuming an exchange rate of
// // one to one.
// }
// }
// }
// }
// Split transactions.
for (QifSplitTransaction qifSplit : qifTransaction.getSplits()) {
Entry splitEntry = transaction.createEntry();
splitEntry.setAccount(findCategory(session, qifSplit.getCategory()));
splitEntry.setMemo(qifSplit.getMemo());
splitEntry.setAmount(-adjustAmount(qifSplit.getAmount(), currency));
}
// If we have a transfer then we need to search through the other
// account to see if a matching entry exists and then keep only one
// (if one is a split transaction, we should keep that one, otherwise
// it does not matter which we keep so keep the old one).
for (Entry entry : transaction.getEntryCollection()) {
if (!entry.equals(firstEntry)) {
// Force a category in each account.
// This is required by the JMoney data model.
if (entry.getAccount() == null) {
entry.setAccount(getCategory("Unknown Category", session));
}
if (entry.getAccount() instanceof IncomeExpenseAccount) {
// If this entry is for a multi-currency account,
// set the currency to be the same as the currency for this
// bank account.
if (((IncomeExpenseAccount)entry.getAccount()).isMultiCurrency()) {
entry.setIncomeExpenseCurrency(currency);
}
}
if (entry.getAccount() instanceof CapitalAccount) {
Entry oldEntry = findMatch(account, transaction.getDate(), -entry.getAmount(), transaction);
if (oldEntry != null) {
if (transaction.hasMoreThanTwoEntries()) {
// Our transaction is split. The other should
// not be, so delete the other transaction,
// leaving only our transaction.
Transaction oldTransaction = oldEntry.getTransaction();
if (oldTransaction.hasMoreThanTwoEntries()) {
// We have problems. Both are split.
// For time being, leave both, but we should
// alert the user or something. Actually, this
// should not happen (at least MS-Money does not seem
// to allow this to happen), so perhaps it does not
// really matter what we do.
} else {
// Copy some of the properties across from the old
// before we delete it.
Entry oldOtherEntry = oldTransaction.getOther(oldEntry);
entry.setCheck(oldOtherEntry.getCheck());
entry.setValuta(oldOtherEntry.getValuta());
session.deleteTransaction(oldTransaction);
}
} else {
// Delete the transaction that we have created,
// leaving only the existing transaction.
session.deleteTransaction(transaction);
// We must stop processing because this transaction
// is now dead.
break;
}
}
}
}
}
}
}
|
diff --git a/coastal-hazards-wps/src/test/java/gov/usgs/cida/coastalhazards/wps/CreateResultsLayerProcessTest.java b/coastal-hazards-wps/src/test/java/gov/usgs/cida/coastalhazards/wps/CreateResultsLayerProcessTest.java
index aa50bfe5d..7d8b9ff77 100644
--- a/coastal-hazards-wps/src/test/java/gov/usgs/cida/coastalhazards/wps/CreateResultsLayerProcessTest.java
+++ b/coastal-hazards-wps/src/test/java/gov/usgs/cida/coastalhazards/wps/CreateResultsLayerProcessTest.java
@@ -1,43 +1,43 @@
package gov.usgs.cida.coastalhazards.wps;
import gov.usgs.cida.coastalhazards.util.FeatureCollectionFromShp;
import java.io.BufferedReader;
import java.io.FileReader;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.junit.Ignore;
import org.junit.Test;
/**
*
* @author jiwalker
*/
public class CreateResultsLayerProcessTest {
/**
* Test of execute method, of class CreateResultsLayerProcess.
*/
@Test
//@Ignore
public void testExecute() throws Exception {
URL resource = CreateResultsLayerProcessTest.class.getClassLoader()
- .getResource("gov/usgs/cida/coastalhazards/jersey/NewJerseyN_results");
+ .getResource("gov/usgs/cida/coastalhazards/jersey/NewJerseyN_results.txt");
URL transects = CreateResultsLayerProcessTest.class.getClassLoader()
.getResource("gov/usgs/cida/coastalhazards/jersey/NewJerseyNa_transects.shp");
BufferedReader reader = new BufferedReader(new FileReader(resource.getFile()));
StringBuffer buffer = new StringBuffer();
String line = null;
while (null != (line = reader.readLine())) {
buffer.append(line);
buffer.append("\n");
}
IOUtils.closeQuietly(reader);
SimpleFeatureCollection transectfc = (SimpleFeatureCollection)
FeatureCollectionFromShp.featureCollectionFromShp(transects);
// need to get the matching transect layer to run against
CreateResultsLayerProcess createResultsLayerProcess = new CreateResultsLayerProcess(new DummyImportProcess(), new DummyCatalog());
createResultsLayerProcess.execute(buffer, transectfc, null, null, null);
}
}
| true | true | public void testExecute() throws Exception {
URL resource = CreateResultsLayerProcessTest.class.getClassLoader()
.getResource("gov/usgs/cida/coastalhazards/jersey/NewJerseyN_results");
URL transects = CreateResultsLayerProcessTest.class.getClassLoader()
.getResource("gov/usgs/cida/coastalhazards/jersey/NewJerseyNa_transects.shp");
BufferedReader reader = new BufferedReader(new FileReader(resource.getFile()));
StringBuffer buffer = new StringBuffer();
String line = null;
while (null != (line = reader.readLine())) {
buffer.append(line);
buffer.append("\n");
}
IOUtils.closeQuietly(reader);
SimpleFeatureCollection transectfc = (SimpleFeatureCollection)
FeatureCollectionFromShp.featureCollectionFromShp(transects);
// need to get the matching transect layer to run against
CreateResultsLayerProcess createResultsLayerProcess = new CreateResultsLayerProcess(new DummyImportProcess(), new DummyCatalog());
createResultsLayerProcess.execute(buffer, transectfc, null, null, null);
}
| public void testExecute() throws Exception {
URL resource = CreateResultsLayerProcessTest.class.getClassLoader()
.getResource("gov/usgs/cida/coastalhazards/jersey/NewJerseyN_results.txt");
URL transects = CreateResultsLayerProcessTest.class.getClassLoader()
.getResource("gov/usgs/cida/coastalhazards/jersey/NewJerseyNa_transects.shp");
BufferedReader reader = new BufferedReader(new FileReader(resource.getFile()));
StringBuffer buffer = new StringBuffer();
String line = null;
while (null != (line = reader.readLine())) {
buffer.append(line);
buffer.append("\n");
}
IOUtils.closeQuietly(reader);
SimpleFeatureCollection transectfc = (SimpleFeatureCollection)
FeatureCollectionFromShp.featureCollectionFromShp(transects);
// need to get the matching transect layer to run against
CreateResultsLayerProcess createResultsLayerProcess = new CreateResultsLayerProcess(new DummyImportProcess(), new DummyCatalog());
createResultsLayerProcess.execute(buffer, transectfc, null, null, null);
}
|
diff --git a/sipXconfig/neoconf/test/org/sipfoundry/sipxconfig/common/X509SelectorTest.java b/sipXconfig/neoconf/test/org/sipfoundry/sipxconfig/common/X509SelectorTest.java
index 30240c944..7a874e99a 100644
--- a/sipXconfig/neoconf/test/org/sipfoundry/sipxconfig/common/X509SelectorTest.java
+++ b/sipXconfig/neoconf/test/org/sipfoundry/sipxconfig/common/X509SelectorTest.java
@@ -1,30 +1,30 @@
/*
*
*
* Copyright (C) 2006 SIPfoundry Inc.
* Licensed by SIPfoundry under the LGPL license.
*
* Copyright (C) 2006 Pingtel Corp.
* Licensed to SIPfoundry under a Contributor Agreement.
*
* $
*/
package org.sipfoundry.sipxconfig.common;
import org.sipfoundry.sipxconfig.common.X509Selector;
import junit.framework.TestCase;
public class X509SelectorTest extends TestCase {
public void testAvailableAlgorithm() {
- String alg = new X509Selector.getAvailableAlgorithm();
+ String alg = new X509Selector().getAvailableAlgorithm();
// only works w/2 VM vendors. If others are known to work, add here
assertTrue(alg.equals("SunX509") || alg.equals("IbmX509"));
}
public void testUnavailableAlgorithm() {
assertNull(new X509Selector().getAvailableAlgorithm(new String[] { "bogus" }));
}
}
| true | true | public void testAvailableAlgorithm() {
String alg = new X509Selector.getAvailableAlgorithm();
// only works w/2 VM vendors. If others are known to work, add here
assertTrue(alg.equals("SunX509") || alg.equals("IbmX509"));
}
| public void testAvailableAlgorithm() {
String alg = new X509Selector().getAvailableAlgorithm();
// only works w/2 VM vendors. If others are known to work, add here
assertTrue(alg.equals("SunX509") || alg.equals("IbmX509"));
}
|
diff --git a/modules/foundation/appbase/src/classes/org/jdesktop/wonderland/modules/appbase/client/HUDDisplayer.java b/modules/foundation/appbase/src/classes/org/jdesktop/wonderland/modules/appbase/client/HUDDisplayer.java
index 1290c430a..97252aa35 100644
--- a/modules/foundation/appbase/src/classes/org/jdesktop/wonderland/modules/appbase/client/HUDDisplayer.java
+++ b/modules/foundation/appbase/src/classes/org/jdesktop/wonderland/modules/appbase/client/HUDDisplayer.java
@@ -1,100 +1,100 @@
/**
* Project Wonderland
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved
*
* Redistributions in source code form must reproduce the above
* copyright and this condition.
*
* The contents of this file are subject to the GNU General Public
* License, Version 2 (the "License"); you may not use this file
* except in compliance with the License. A copy of the License is
* available at http://www.opensource.org/licenses/gpl-license.php.
*
* Sun designates this particular file as subject to the "Classpath"
* exception as provided by Sun in the License file that accompanied
* this code.
*/
package org.jdesktop.wonderland.modules.appbase.client;
import java.util.Iterator;
import java.util.LinkedList;
import org.jdesktop.wonderland.client.hud.CompassLayout.Layout;
import org.jdesktop.wonderland.client.hud.HUD;
import org.jdesktop.wonderland.client.hud.HUDComponent;
import org.jdesktop.wonderland.client.hud.HUDEvent;
import org.jdesktop.wonderland.client.hud.HUDEventListener;
import org.jdesktop.wonderland.client.hud.HUDManagerFactory;
import org.jdesktop.wonderland.common.ExperimentalAPI;
import org.jdesktop.wonderland.modules.appbase.client.view.View2D;
import org.jdesktop.wonderland.modules.appbase.client.view.View2DDisplayer;
import org.jdesktop.wonderland.modules.appbase.client.view.WindowSwingHeader;
@ExperimentalAPI
public class HUDDisplayer implements View2DDisplayer {
/** The app displayed by this displayer. */
private App2D app;
/** The HUD. */
private HUD mainHUD;
/** HUD components for windows shown in the HUD. */
private LinkedList<HUDComponent> hudComponents;
public HUDDisplayer (App2D app) {
this.app = app;
mainHUD = HUDManagerFactory.getHUDManager().getHUD("main");
hudComponents = new LinkedList<HUDComponent>();
}
public void cleanup () {
if (hudComponents != null) {
HUD mainHUD = HUDManagerFactory.getHUDManager().getHUD("main");
for (HUDComponent component : hudComponents) {
component.setVisible(false);
mainHUD.removeComponent(component);
}
hudComponents.clear();
hudComponents = null;
}
mainHUD = null;
app = null;
}
public View2D createView (Window2D window) {
// Don't ever show frame headers in the HUD
if (window instanceof WindowSwingHeader) return null;
HUDComponent component = mainHUD.createComponent(window);
component.setName(app.getName());
- component.setPreferredLocation(Layout.CENTER);
+ component.setPreferredLocation(Layout.NORTH);
hudComponents.add(component);
component.addEventListener(new HUDEventListener() {
public void HUDObjectChanged(HUDEvent e) {
if (e.getEventType().equals(HUDEvent.HUDEventType.CLOSED)) {
// TODO: currently we take the entire app off the HUD when
// any HUD view of any app window is quit
app.setShowInHUD(false);
}
}
});
mainHUD.addComponent(component);
component.setVisible(true);
// TODO: get the view from the HUD component and return it?
return null;
}
public void destroyView (View2D view) {
}
public void destroyAllViews () {
}
public Iterator<? extends View2D> getViews () {
return null;
}
}
| true | true | public View2D createView (Window2D window) {
// Don't ever show frame headers in the HUD
if (window instanceof WindowSwingHeader) return null;
HUDComponent component = mainHUD.createComponent(window);
component.setName(app.getName());
component.setPreferredLocation(Layout.CENTER);
hudComponents.add(component);
component.addEventListener(new HUDEventListener() {
public void HUDObjectChanged(HUDEvent e) {
if (e.getEventType().equals(HUDEvent.HUDEventType.CLOSED)) {
// TODO: currently we take the entire app off the HUD when
// any HUD view of any app window is quit
app.setShowInHUD(false);
}
}
});
mainHUD.addComponent(component);
component.setVisible(true);
// TODO: get the view from the HUD component and return it?
return null;
}
| public View2D createView (Window2D window) {
// Don't ever show frame headers in the HUD
if (window instanceof WindowSwingHeader) return null;
HUDComponent component = mainHUD.createComponent(window);
component.setName(app.getName());
component.setPreferredLocation(Layout.NORTH);
hudComponents.add(component);
component.addEventListener(new HUDEventListener() {
public void HUDObjectChanged(HUDEvent e) {
if (e.getEventType().equals(HUDEvent.HUDEventType.CLOSED)) {
// TODO: currently we take the entire app off the HUD when
// any HUD view of any app window is quit
app.setShowInHUD(false);
}
}
});
mainHUD.addComponent(component);
component.setVisible(true);
// TODO: get the view from the HUD component and return it?
return null;
}
|
diff --git a/src/main/java/com/jdkcn/jabber/web/filter/UserLoginFilter.java b/src/main/java/com/jdkcn/jabber/web/filter/UserLoginFilter.java
index 92f52f0..93aa111 100644
--- a/src/main/java/com/jdkcn/jabber/web/filter/UserLoginFilter.java
+++ b/src/main/java/com/jdkcn/jabber/web/filter/UserLoginFilter.java
@@ -1,53 +1,54 @@
package com.jdkcn.jabber.web.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.google.inject.Singleton;
import com.jdkcn.jabber.util.Constants;
/**
* @author <a href="mailto:[email protected]">Rory</a>
* @version $Id$
*/
@Singleton
public class UserLoginFilter implements Filter {
/**
* {@inheritDoc}
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
/**
* {@inheritDoc}
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
if (session == null || session.getAttribute(Constants.LOGIN_USER) == null) {
((HttpServletResponse) response).sendRedirect(req.getContextPath() + "/login");
+ } else {
+ chain.doFilter(request, response);
}
- chain.doFilter(request, response);
}
/**
* {@inheritDoc}
*/
@Override
public void destroy() {
}
}
| false | true | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
if (session == null || session.getAttribute(Constants.LOGIN_USER) == null) {
((HttpServletResponse) response).sendRedirect(req.getContextPath() + "/login");
}
chain.doFilter(request, response);
}
| public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
if (session == null || session.getAttribute(Constants.LOGIN_USER) == null) {
((HttpServletResponse) response).sendRedirect(req.getContextPath() + "/login");
} else {
chain.doFilter(request, response);
}
}
|
diff --git a/x10.compiler/src/polyglot/types/TypeEnv_c.java b/x10.compiler/src/polyglot/types/TypeEnv_c.java
index d14cec320..319d728d3 100644
--- a/x10.compiler/src/polyglot/types/TypeEnv_c.java
+++ b/x10.compiler/src/polyglot/types/TypeEnv_c.java
@@ -1,815 +1,815 @@
package polyglot.types;
import java.util.*;
import polyglot.frontend.Globals;
import polyglot.main.Reporter;
import polyglot.types.TypeSystem_c.ConstructorMatcher;
import x10.types.MethodInstance;
import x10.types.X10TypeEnv_c;
/**
* Typing environment.
*
* For a given typing rule Gamma |- Phi, this is Gamma. Phi is a method of
* TypeEnv.
*/
public abstract class TypeEnv_c implements TypeEnv, Cloneable {
protected Context context; // the actual context. Eliminate this and merge
// with Context.
protected TypeSystem ts;
protected Reporter reporter;
public TypeEnv_c(Context context) {
assert context != null;
this.context = context;
this.ts = context.typeSystem();
this.reporter = this.ts.extensionInfo().getOptions().reporter;
}
public X10TypeEnv_c shallowCopy() {
try {
return (X10TypeEnv_c) super.clone();
}
catch (CloneNotSupportedException e) {
assert false;
return null;
}
}
/**
* Returns true iff the type t can be coerced to a String in the given
* Context. If a type can be coerced to a String then it can be concatenated
* with Strings, e.g. if o is of type T, then the code snippet "" + o would
* be allowed.
*/
public boolean canCoerceToString(Type t) {
// every Object can be coerced to a string, as can any primitive,
// except void.
return !t.isVoid();
}
/**
* Returns true iff type1 and type2 are equivalent.
*/
public boolean typeEquals(Type type1, Type type2) {
if (type1 == type2)
return true;
if (type1 == null || type2 == null)
return false;
if (type1 instanceof JavaArrayType && type2 instanceof JavaArrayType) {
JavaArrayType at1 = (JavaArrayType) type1;
JavaArrayType at2 = (JavaArrayType) type2;
return typeEquals(at1.base(), at2.base());
}
return ts.equals((TypeObject) type1, (TypeObject) type2);
}
/**
* Returns true iff type1 and type2 are equivalent.
*/
public boolean packageEquals(Package type1, Package type2) {
if (type1 == type2)
return true;
if (type1 == null || type2 == null)
return false;
return type1.packageEquals(type2);
}
/**
* Requires: all type arguments are canonical. ToType is not a NullType.
*
* Returns true iff a cast from fromType to toType is valid; in other words,
* some non-null members of fromType are also members of toType.
**/
public boolean isCastValid(Type fromType, Type toType) {
if (fromType instanceof NullType) {
return toType.isNull() || toType.isReference();
}
if (fromType.isJavaPrimitive() && toType.isJavaPrimitive()) {
if (fromType.isVoid() || toType.isVoid())
return false;
if (ts.typeEquals(fromType, toType, context))
return true;
if (fromType.isNumeric() && toType.isNumeric())
return true;
return false;
}
if (fromType instanceof JavaArrayType && toType instanceof JavaArrayType) {
JavaArrayType fromAT = (JavaArrayType) fromType;
JavaArrayType toAT = (JavaArrayType) toType;
Type fromBase = fromAT.base();
Type toBase = toAT.base();
if (fromBase.isJavaPrimitive())
return ts.typeEquals(toBase, fromBase, context);
if (toBase.isJavaPrimitive())
return false;
if (fromBase.isNull())
return false;
if (toBase.isNull())
return false;
// Both are reference types.
return ts.isCastValid(fromBase, toBase, context);
}
if (fromType instanceof JavaArrayType && toType instanceof ObjectType) {
// Ancestor is not an array, but child is. Check if the array
// is a subtype of the ancestor. This happens when ancestor
// is java.lang.Object.
return ts.isSubtype(fromType, toType, context);
}
if (fromType instanceof ClassType && toType instanceof JavaArrayType) {
// From type is not an array, but to type is. Check if the array
// is a subtype of the from type. This happens when from type
// is java.lang.Object.
return ts.isSubtype(toType, fromType, context);
}
if (fromType instanceof ClassType && toType instanceof ClassType) {
ClassType fromCT = (ClassType) fromType;
ClassType toCT = (ClassType) toType;
// From and to are neither primitive nor an array. They are
// distinct.
boolean fromInterface = fromCT.flags().isInterface();
boolean toInterface = toCT.flags().isInterface();
- boolean fromFinal = fromCT.flags().isFinal();
+ boolean fromFinal = fromCT.flags().isFinal() || Types.isX10Struct(fromCT);
boolean toFinal = toCT.flags().isFinal();
// This is taken from Section 5.5 of the JLS.
if (fromInterface) {
// From is an interface
if (!toInterface && !toFinal) {
// To is a non-final class.
return true;
}
if (toFinal) {
// To is a final class.
return ts.isSubtype(toType, fromCT, context);
}
// To and From are both interfaces.
return true;
}
else {
// From is not an interface.
if (!toInterface) {
// Nether from nor to is an interface.
return ts.isSubtype(fromCT, toType, context) || ts.isSubtype(toType, fromCT, context);
}
if (fromFinal) {
// From is a final class, and to is an interface
return ts.isSubtype(fromCT, toType, context);
}
// From is a non-final class, and to is an interface.
return true;
}
}
if (fromType instanceof ObjectType) {
if (!toType.isReference())
return false;
return ts.isSubtype(fromType, toType, context) || ts.isSubtype(toType, fromType, context);
}
return false;
}
/**
* Requires: all type arguments are canonical.
*
* Returns true iff an implicit cast from fromType to toType is valid; in
* other words, every member of fromType is member of toType.
*
* Returns true iff child and ancestor are non-primitive types, and a
* variable of type child may be legally assigned to a variable of type
* ancestor.
*
*/
public boolean isImplicitCastValid(Type fromType, Type toType) {
if (fromType.isJavaPrimitive() && toType.isJavaPrimitive()) {
if (toType.isVoid())
return false;
if (fromType.isVoid())
return false;
if (ts.typeEquals(toType, fromType, context))
return true;
if (toType.isBoolean())
return fromType.isBoolean();
if (fromType.isBoolean())
return false;
if (!fromType.isNumeric() || !toType.isNumeric())
return false;
if (toType.isDouble())
return true;
if (fromType.isDouble())
return false;
if (toType.isFloat())
return true;
if (fromType.isFloat())
return false;
if (toType.isLong())
return true;
if (fromType.isLong())
return false;
if (toType.isInt())
return true;
if (fromType.isInt())
return false;
if (toType.isShort())
return fromType.isShort() || fromType.isByte();
if (fromType.isShort())
return false;
if (toType.isChar())
return fromType.isChar();
if (fromType.isChar())
return false;
if (toType.isByte())
return fromType.isByte();
if (fromType.isByte())
return false;
return false;
}
if (fromType instanceof JavaArrayType && toType instanceof JavaArrayType) {
JavaArrayType fromAT = (JavaArrayType) fromType;
Type fromBase = fromAT.base();
JavaArrayType toAT = (JavaArrayType) toType;
Type toBase = toAT.base();
if (fromBase.isJavaPrimitive() || toBase.isJavaPrimitive()) {
return ts.typeEquals(fromBase, toBase, context);
}
else {
return isImplicitCastValid(fromBase, toBase);
}
}
if (fromType instanceof NullType) {
return toType.isNull() || toType.isReference();
}
if (fromType instanceof ObjectType) {
// This handles classes and also coercions from Array to Object
return ts.isSubtype(fromType, toType, context);
}
return false;
}
/**
* Returns true if <code>value</code> can be implicitly cast to Primitive
* type <code>t</code>.
*/
public boolean numericConversionValid(Type t, Object value) {
if (value instanceof Float || value instanceof Double)
return false;
long v;
if (value instanceof Number) {
v = ((Number) value).longValue();
}
else if (value instanceof Character) {
v = ((Character) value).charValue();
}
else {
return false;
}
if (t.isLong())
return true;
if (t.isInt())
return Integer.MIN_VALUE <= v && v <= Integer.MAX_VALUE;
if (t.isChar())
return Character.MIN_VALUE <= v && v <= Character.MAX_VALUE;
if (t.isShort())
return Short.MIN_VALUE <= v && v <= Short.MAX_VALUE;
if (t.isByte())
return Byte.MIN_VALUE <= v && v <= Byte.MAX_VALUE;
return false;
}
// //
// Functions for one-type checking and resolution.
// //
/**
* Checks whether the member mi can be accessed from Context "context".
*/
public boolean isAccessible(MemberInstance<?> mi) {
ClassDef contextClass = context.currentClassDef();
Type target = mi.container();
Flags flags = mi.flags();
if (!target.isClass()) {
// public members of non-classes are accessible;
// non-public members of non-classes are inaccessible
return flags.isPublic();
}
if (contextClass == null) {
return flags.isPublic();
}
ClassType contextClassType = contextClass.asType();
ClassType targetClass = target.toClass();
if (!classAccessible(targetClass.def())) {
return false;
}
if (ts.equals(targetClass.def(), contextClass))
return true;
// If the current class and the target class are both in the
// same class body, then protection doesn't matter, i.e.
// protected and private members may be accessed. Do this by
// working up through contextClass's containers.
if (ts.isEnclosed(contextClass, targetClass.def()) || ts.isEnclosed(targetClass.def(), contextClass))
return true;
ClassDef cd = contextClass;
while (!cd.isTopLevel()) {
cd = cd.outer().get();
if (ts.isEnclosed(targetClass.def(), cd))
return true;
}
// protected
if (flags.isProtected()) {
// If the current class is in a
// class body that extends/implements the target class, then
// protected members can be accessed. Do this by
// working up through contextClass's containers.
if (ts.descendsFrom(ts.classDefOf(contextClassType), ts.classDefOf(targetClass))) {
return true;
}
ClassType ct = contextClassType;
while (!ct.isTopLevel()) {
ct = ct.outer();
if (ts.descendsFrom(ts.classDefOf(ct), ts.classDefOf(targetClass))) {
return true;
}
}
}
return accessibleFromPackage(flags, targetClass.package_(), contextClassType.package_());
}
/** True if the class targetClass accessible from the context. */
public boolean classAccessible(ClassDef targetClass) {
ClassDef contextClass = context.currentClassDef();
if (contextClass == null) {
return classAccessibleFromPackage(targetClass, context.package_());
}
if (targetClass.isMember()) {
return isAccessible(targetClass.asType());
}
ClassType contextClassType = contextClass.asType();
// Local and anonymous classes are accessible if they can be named.
// This method wouldn't be called if they weren't named.
if (!targetClass.isTopLevel()) {
return true;
}
// targetClass must be a top-level class
// same class
if (ts.equals(targetClass, contextClass))
return true;
if (ts.isEnclosed(contextClass, targetClass))
return true;
return classAccessibleFromPackage(targetClass, contextClassType.package_());
}
/** True if the class targetClass accessible from the package pkg. */
public boolean classAccessibleFromPackage(ClassDef targetClass, Package pkg) {
// Local and anonymous classes are not accessible from the outermost
// scope of a compilation unit.
if (!targetClass.isTopLevel() && !targetClass.isMember())
return false;
Flags flags = targetClass.flags();
if (targetClass.isMember()) {
if (!targetClass.container().get().isClass()) {
// public members of non-classes are accessible
return flags.isPublic();
}
if (!classAccessibleFromPackage(targetClass.container().get().toClass().def(), pkg)) {
return false;
}
}
return accessibleFromPackage(flags, Types.get(targetClass.package_()), pkg);
}
/**
* Return true if a member (in an accessible container) or a top-level class
* with access flags <code>flags</code> in package <code>pkg1</code> is
* accessible from package <code>pkg2</code>.
*/
public boolean accessibleFromPackage(Flags flags, Package pkg1, Package pkg2) {
// Check if public.
if (flags.isPublic()) {
return true;
}
// Check if same package.
if (flags.isPackage() || flags.isProtected()) {
if (pkg1 == null && pkg2 == null)
return true;
if (pkg1 == null || pkg2 == null)
return false;
if (pkg1.packageEquals(pkg2))
return true;
}
// Otherwise private.
return false;
}
public boolean isSubtype(Type t1, Type t2) {
if (typeEquals(t1, t2))
return true;
if (t1.isNull()) {
return t2.isNull() || t2.isReference();
}
if (t1.isReference() && t2.isNull()) {
return false;
}
Type child = t1;
Type ancestor = t2;
if (child instanceof ObjectType) {
ObjectType childRT = (ObjectType) child;
if (typeEquals(ancestor, ts.Object())) {
return true;
}
if (typeEquals(childRT, ts.Object())) {
return false;
}
// Check subclass relation.
if (childRT.superClass() != null) {
if (isSubtype(childRT.superClass(), ancestor)) {
return true;
}
}
// Next check interfaces.
for (Type parentType : childRT.interfaces()) {
if (isSubtype(parentType, ancestor)) {
return true;
}
}
}
return false;
}
/**
* Returns whether method 1 is <i>more specific</i> than method 2, where
* <i>more specific</i> is defined as JLS 15.11.2.2
*/
public <T extends ProcedureDef> boolean moreSpecific(ProcedureInstance<T> p1, ProcedureInstance<T> p2) {
return p1.moreSpecific(null, p2, context);
}
/**
* Requires: all type arguments are canonical. Returns the least common
* ancestor of Type1 and Type2
**/
public Type leastCommonAncestor(Type type1, Type type2) throws SemanticException {
if (typeEquals(type1, type2))
return type1;
if (type1.isNumeric() && type2.isNumeric()) {
if (isImplicitCastValid(type1, type2)) {
return type2;
}
if (isImplicitCastValid(type2, type1)) {
return type1;
}
if (type1.isChar() && type2.isByte() || type1.isByte() && type2.isChar()) {
return ts.Int();
}
if (type1.isChar() && type2.isShort() || type1.isShort() && type2.isChar()) {
return ts.Int();
}
}
if (type1.isArray() && type2.isArray()) {
if (type1.toArray().base().isReference() && type2.toArray().base().isReference()) {
return ts.arrayOf(leastCommonAncestor(type1.toArray().base(), type2.toArray().base()));
}
else {
return ts.Object();
}
}
if (type1.isReference() && type2.isNull())
return type1;
if (type2.isReference() && type1.isNull())
return type2;
// Don't consider interfaces.
if (type1.isClass() && type1.toClass().flags().isInterface()) {
return ts.Object();
}
if (type2.isClass() && type2.toClass().flags().isInterface()) {
return ts.Object();
}
// Check against Object to ensure superType() is not null.
if (typeEquals(type1, ts.Object()))
return type1;
if (typeEquals(type2, ts.Object()))
return type2;
if (isSubtype(type1, type2))
return type2;
if (isSubtype(type2, type1))
return type1;
if (type1 instanceof ObjectType && type2 instanceof ObjectType) {
// Walk up the hierarchy
Type t1 = leastCommonAncestor(((ObjectType) type1).superClass(), type2);
Type t2 = leastCommonAncestor(((ObjectType) type2).superClass(), type1);
if (typeEquals(t1, t2))
return t1;
return ts.Object();
}
throw new SemanticException("No least common ancestor found for types \"" + type1 + "\" and \"" + type2 + "\".");
}
/** Return true if t overrides mi */
public boolean hasMethod(Type t, MethodInstance mi) {
return t instanceof ContainerType && ((ContainerType) t).hasMethod(mi, context);
}
/** Return true if t overrides mi */
public boolean hasFormals(ProcedureInstance<? extends ProcedureDef> pi, List<Type> formalTypes) {
return ((ProcedureInstance_c<?>) pi).hasFormals(formalTypes, context);
}
public List<MethodInstance> overrides(MethodInstance mi) {
List<MethodInstance> l = new ArrayList<MethodInstance>();
ContainerType rt = mi.container();
while (rt != null) {
// add any method with the same name and formalTypes from rt
l.addAll(rt.methods(mi.name(), mi.formalTypes(), context));
ContainerType sup = null;
if (rt instanceof ObjectType) {
ObjectType ot = (ObjectType) rt;
if (ot.superClass() instanceof ContainerType) {
sup = (ContainerType) ot.superClass();
}
}
rt = sup;
}
;
return l;
}
public List<MethodInstance> implemented(MethodInstance mi) {
return implemented(mi, mi.container());
}
public List<MethodInstance> implemented(MethodInstance mi, ContainerType st) {
if (st == null) {
return Collections.<MethodInstance> emptyList();
}
List<MethodInstance> l = new LinkedList<MethodInstance>();
l.addAll(st.methods(mi.name(), mi.formalTypes(), context));
if (st instanceof ObjectType) {
ObjectType rt = (ObjectType) st;
Type superType = rt.superClass();
if (superType instanceof ContainerType) {
l.addAll(implemented(mi, (ContainerType) superType));
}
List<Type> ints = rt.interfaces();
for (Type t : ints) {
if (t instanceof ContainerType) {
ContainerType rt2 = (ContainerType) t;
l.addAll(implemented(mi, rt2));
}
}
}
return l;
}
/**
* Assert that <code>ct</code> implements all abstract methods required;
* that is, if it is a concrete class, then it must implement all interfaces
* and abstract methods that it or it's superclasses declare, and if it is
* an abstract class then any methods that it overrides are overridden
* correctly.
*/
public void checkClassConformance(ClassType ct) throws SemanticException {
if (ct.flags().isAbstract()) {
// don't need to check interfaces or abstract classes
return;
}
// build up a list of superclasses and interfaces that ct
// extends/implements that may contain abstract methods that
// ct must define.
List<Type> superInterfaces = ts.abstractSuperInterfaces(ct);
// check each abstract method of the classes and interfaces in
// superInterfaces
for (Iterator<Type> i = superInterfaces.iterator(); i.hasNext();) {
Type it = i.next();
if (it instanceof ContainerType) {
ContainerType rt = (ContainerType) it;
for (Iterator<MethodInstance> j = rt.methods().iterator(); j.hasNext();) {
MethodInstance mi = j.next();
if (!mi.flags().isAbstract()) {
// the method isn't abstract, so ct doesn't have to
// implement it.
continue;
}
MethodInstance mj = ts.findImplementingMethod(ct, mi, context);
if (mj == null) {
if (!ct.flags().isAbstract()) {
throw new SemanticException(ct.fullName() + " should be declared abstract; it does not define " + mi.signature()+ ", which is declared in " + rt.toClass().fullName(), ct.position());
}
else {
// no implementation, but that's ok, the class is
// abstract.
}
}
else if (!typeEquals(ct, mj.container()) && !typeEquals(ct, mi.container())) {
try {
// check that mj can override mi, which
// includes access protection checks.
checkOverride(mj, mi);
}
catch (SemanticException e) {
// change the position of the semantic
// exception to be the class that we
// are checking.
throw new SemanticException(e.getMessage(), ct.position());
}
}
else {
// the method implementation mj or mi was
// declared in ct. So other checks will take
// care of access issues
}
}
}
}
}
public boolean canOverride(MethodInstance mi, MethodInstance mj) {
try {
checkOverride(mi, mj);
return true;
}
catch (SemanticException e) {
return false;
}
}
public void checkOverride(MethodInstance mi, MethodInstance mj) throws SemanticException {
// HACK: Java5 allows return types to be covariant. We'll allow
// covariant
// return if we mj is defined in a class file.
boolean allowCovariantReturn = false;
if (mj.container() instanceof ClassType) {
ClassType ct = (ClassType) mj.container();
if (ct.def().fromJavaClassFile()) {
allowCovariantReturn = true;
}
}
checkOverride(mi, mj, allowCovariantReturn);
}
public void checkOverride(MethodInstance mi, MethodInstance mj, boolean allowCovariantReturn) throws SemanticException {
if (mi == mj)
return;
if (!(mi.name().equals(mj.name()) && mi.hasFormals(mj.formalTypes(), context))) {
throw new SemanticException(mi.signature()
+ " in " + mi.container() + " cannot override " + mj.signature()
+ " in " + mj.container()+ "; incompatible " + "parameter types", mi.position());
}
boolean shouldReport = reporter.should_report(Reporter.types, 3);
if (allowCovariantReturn ? !isSubtype(mi.returnType(), mj.returnType()) : !typeEquals(mi.returnType(), mj.returnType())) {
if (shouldReport)
reporter.report(3, "return type " + mi.returnType() + " != " + mj.returnType());
throw new SemanticException(mi.signature()
+ " in " + mi.container() + " cannot override " + mj.signature()
+ " in " + mj.container()+ "; attempting to use incompatible return type."
+ "\n\tFound: " + mi.returnType()
+ "\n\tExpected: " + mj.returnType(),mi.position());
}
/* if (!ts.throwsSubset(mi, mj)) {
if (Report.should_report(Report.types, 3))
Report.report(3, mi.throwTypes() + " not subset of " + mj.throwTypes());
throw new SemanticException(mi.signature() + " in " + mi.container() + " cannot override " + mj.signature() + " in " + mj.container()
+ "; the throw set " + mi.throwTypes() + " is not a subset of the " + "overridden method's throw set " + mj.throwTypes() + ".",
mi.position());
}
*/
if (mi.flags().moreRestrictiveThan(mj.flags())) {
if (shouldReport)
reporter.report(3, mi.flags() + " more restrictive than " + mj.flags());
throw new SemanticException(mi.signature()
+ " in " + mi.container() + " cannot override " + mj.signature()
+ " in " + mj.container()+ "; attempting to assign weaker "
+ "access privileges", mi.position());
}
if (mi.flags().isStatic() != mj.flags().isStatic()) {
if (shouldReport)
reporter.report(3, mi.signature() + " is " + (mi.flags().isStatic() ? "" : "not") + " static but " + mj.signature() + " is "
+ (mj.flags().isStatic() ? "" : "not") + " static");
throw new SemanticException(mi.signature() + " in " + mi.container() + " cannot override " + mj.signature() + " in " + mj.container()+ "; overridden method is " + (mj.flags().isStatic() ? "" : "not") + "static", mi.position());
}
if (!mi.def().equals(mj.def()) && mj.flags().isFinal()) {
// mi can "override" a final method mj if mi and mj are the same
// method instance.
if (shouldReport)
reporter.report(3, mj.flags() + " final");
throw new SemanticException(mi.signature() + " in " + mi.container() + " cannot override " + mj.signature() + " in " + mj.container()+ "; overridden method is final", mi.position());
}
}
/**
* Returns true iff <m1> is the same method as <m2>
*/
public boolean isSameMethod(MethodInstance m1, MethodInstance m2) {
return m1.name().equals(m2.name()) && m1.hasFormals(m2.formalTypes(), context);
}
public boolean callValid(ProcedureInstance<? extends ProcedureDef> prototype, Type thisType, List<Type> argTypes) {
return ((ProcedureInstance_c<?>) prototype).callValid(thisType, argTypes, context);
}
public abstract Type findMemberType(Type container, Name name) throws SemanticException;
}
| true | true | public boolean isCastValid(Type fromType, Type toType) {
if (fromType instanceof NullType) {
return toType.isNull() || toType.isReference();
}
if (fromType.isJavaPrimitive() && toType.isJavaPrimitive()) {
if (fromType.isVoid() || toType.isVoid())
return false;
if (ts.typeEquals(fromType, toType, context))
return true;
if (fromType.isNumeric() && toType.isNumeric())
return true;
return false;
}
if (fromType instanceof JavaArrayType && toType instanceof JavaArrayType) {
JavaArrayType fromAT = (JavaArrayType) fromType;
JavaArrayType toAT = (JavaArrayType) toType;
Type fromBase = fromAT.base();
Type toBase = toAT.base();
if (fromBase.isJavaPrimitive())
return ts.typeEquals(toBase, fromBase, context);
if (toBase.isJavaPrimitive())
return false;
if (fromBase.isNull())
return false;
if (toBase.isNull())
return false;
// Both are reference types.
return ts.isCastValid(fromBase, toBase, context);
}
if (fromType instanceof JavaArrayType && toType instanceof ObjectType) {
// Ancestor is not an array, but child is. Check if the array
// is a subtype of the ancestor. This happens when ancestor
// is java.lang.Object.
return ts.isSubtype(fromType, toType, context);
}
if (fromType instanceof ClassType && toType instanceof JavaArrayType) {
// From type is not an array, but to type is. Check if the array
// is a subtype of the from type. This happens when from type
// is java.lang.Object.
return ts.isSubtype(toType, fromType, context);
}
if (fromType instanceof ClassType && toType instanceof ClassType) {
ClassType fromCT = (ClassType) fromType;
ClassType toCT = (ClassType) toType;
// From and to are neither primitive nor an array. They are
// distinct.
boolean fromInterface = fromCT.flags().isInterface();
boolean toInterface = toCT.flags().isInterface();
boolean fromFinal = fromCT.flags().isFinal();
boolean toFinal = toCT.flags().isFinal();
// This is taken from Section 5.5 of the JLS.
if (fromInterface) {
// From is an interface
if (!toInterface && !toFinal) {
// To is a non-final class.
return true;
}
if (toFinal) {
// To is a final class.
return ts.isSubtype(toType, fromCT, context);
}
// To and From are both interfaces.
return true;
}
else {
// From is not an interface.
if (!toInterface) {
// Nether from nor to is an interface.
return ts.isSubtype(fromCT, toType, context) || ts.isSubtype(toType, fromCT, context);
}
if (fromFinal) {
// From is a final class, and to is an interface
return ts.isSubtype(fromCT, toType, context);
}
// From is a non-final class, and to is an interface.
return true;
}
}
if (fromType instanceof ObjectType) {
if (!toType.isReference())
return false;
return ts.isSubtype(fromType, toType, context) || ts.isSubtype(toType, fromType, context);
}
return false;
}
| public boolean isCastValid(Type fromType, Type toType) {
if (fromType instanceof NullType) {
return toType.isNull() || toType.isReference();
}
if (fromType.isJavaPrimitive() && toType.isJavaPrimitive()) {
if (fromType.isVoid() || toType.isVoid())
return false;
if (ts.typeEquals(fromType, toType, context))
return true;
if (fromType.isNumeric() && toType.isNumeric())
return true;
return false;
}
if (fromType instanceof JavaArrayType && toType instanceof JavaArrayType) {
JavaArrayType fromAT = (JavaArrayType) fromType;
JavaArrayType toAT = (JavaArrayType) toType;
Type fromBase = fromAT.base();
Type toBase = toAT.base();
if (fromBase.isJavaPrimitive())
return ts.typeEquals(toBase, fromBase, context);
if (toBase.isJavaPrimitive())
return false;
if (fromBase.isNull())
return false;
if (toBase.isNull())
return false;
// Both are reference types.
return ts.isCastValid(fromBase, toBase, context);
}
if (fromType instanceof JavaArrayType && toType instanceof ObjectType) {
// Ancestor is not an array, but child is. Check if the array
// is a subtype of the ancestor. This happens when ancestor
// is java.lang.Object.
return ts.isSubtype(fromType, toType, context);
}
if (fromType instanceof ClassType && toType instanceof JavaArrayType) {
// From type is not an array, but to type is. Check if the array
// is a subtype of the from type. This happens when from type
// is java.lang.Object.
return ts.isSubtype(toType, fromType, context);
}
if (fromType instanceof ClassType && toType instanceof ClassType) {
ClassType fromCT = (ClassType) fromType;
ClassType toCT = (ClassType) toType;
// From and to are neither primitive nor an array. They are
// distinct.
boolean fromInterface = fromCT.flags().isInterface();
boolean toInterface = toCT.flags().isInterface();
boolean fromFinal = fromCT.flags().isFinal() || Types.isX10Struct(fromCT);
boolean toFinal = toCT.flags().isFinal();
// This is taken from Section 5.5 of the JLS.
if (fromInterface) {
// From is an interface
if (!toInterface && !toFinal) {
// To is a non-final class.
return true;
}
if (toFinal) {
// To is a final class.
return ts.isSubtype(toType, fromCT, context);
}
// To and From are both interfaces.
return true;
}
else {
// From is not an interface.
if (!toInterface) {
// Nether from nor to is an interface.
return ts.isSubtype(fromCT, toType, context) || ts.isSubtype(toType, fromCT, context);
}
if (fromFinal) {
// From is a final class, and to is an interface
return ts.isSubtype(fromCT, toType, context);
}
// From is a non-final class, and to is an interface.
return true;
}
}
if (fromType instanceof ObjectType) {
if (!toType.isReference())
return false;
return ts.isSubtype(fromType, toType, context) || ts.isSubtype(toType, fromType, context);
}
return false;
}
|
diff --git a/src/java/com/threerings/media/FrameInterval.java b/src/java/com/threerings/media/FrameInterval.java
index e5dc43f3a..f168c3960 100644
--- a/src/java/com/threerings/media/FrameInterval.java
+++ b/src/java/com/threerings/media/FrameInterval.java
@@ -1,110 +1,111 @@
package com.threerings.media;
import java.awt.Component;
import com.threerings.media.FrameManager;
import com.threerings.media.FrameParticipant;
public abstract class FrameInterval
implements FrameParticipant
{
/**
* Constructor - registers the interval as a frame participant
*/
public FrameInterval (FrameManager mgr)
{
_mgr = mgr;
}
// documentation inhertied from FrameParticipant
public Component getComponent ()
{
return null;
}
// documentation inherited from FrameParticipant
public boolean needsPaint ()
{
return false;
}
// documentation inherited from FrameParticipant
public void tick (long tickStamp)
{
if (_nextTime == -1) {
// First time through
_nextTime = tickStamp + _initDelay;
} else if (tickStamp >= _nextTime) {
// If we're repeating, set the next time to run, otherwise, reset
if (_repeatDelay != 0L) {
_nextTime += _repeatDelay;
} else {
_nextTime = -1;
+ cancel();
}
expired();
}
}
/**
*
* The main method where your interval should do its work.
*
*/
public abstract void expired ();
/**
* Schedule the interval to execute once, after the specified delay.
* Supersedes any previous schedule that this Interval may have had.
*/
public final void schedule (long delay)
{
schedule(delay, 0L);
}
/**
* Schedule the interval to execute repeatedly, with the same delay.
* Supersedes any previous schedule that this Interval may have had.
*/
public final void schedule (long delay, boolean repeat)
{
schedule(delay, repeat ? delay : 0L);
}
/**
* Schedule the interval to execute repeatedly with the specified
* initial delay and repeat delay.
* Supersedes any previous schedule that this Interval may have had.
*/
public final void schedule (long initialDelay, long repeatDelay)
{
if (!_mgr.isRegisteredFrameParticipant(this)) {
_mgr.registerFrameParticipant(this);
}
_repeatDelay = repeatDelay;
_initDelay = initialDelay;
_nextTime = -1;
}
/**
* Cancel the current schedule, and ensure that any expirations that
* are queued up but have not yet run do not run.
*/
public final void cancel ()
{
_mgr.removeFrameParticipant(this);
}
/** Time of the next expiration. */
protected long _nextTime;
/** Time between expirations. */
protected long _repeatDelay;
/** Time between expirations. */
protected long _initDelay;
/** The context whose FrameManager we are using. */
protected FrameManager _mgr;
}
| true | true | public void tick (long tickStamp)
{
if (_nextTime == -1) {
// First time through
_nextTime = tickStamp + _initDelay;
} else if (tickStamp >= _nextTime) {
// If we're repeating, set the next time to run, otherwise, reset
if (_repeatDelay != 0L) {
_nextTime += _repeatDelay;
} else {
_nextTime = -1;
}
expired();
}
}
| public void tick (long tickStamp)
{
if (_nextTime == -1) {
// First time through
_nextTime = tickStamp + _initDelay;
} else if (tickStamp >= _nextTime) {
// If we're repeating, set the next time to run, otherwise, reset
if (_repeatDelay != 0L) {
_nextTime += _repeatDelay;
} else {
_nextTime = -1;
cancel();
}
expired();
}
}
|
diff --git a/antipasto/GUI/ImageListView/ImageListPanel.java b/antipasto/GUI/ImageListView/ImageListPanel.java
index e3f5c37..868de18 100644
--- a/antipasto/GUI/ImageListView/ImageListPanel.java
+++ b/antipasto/GUI/ImageListView/ImageListPanel.java
@@ -1,336 +1,338 @@
package antipasto.GUI.ImageListView;
import javax.swing.BoxLayout;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.io.*;
import antipasto.GUI.GadgetListView.GadgetPanel;
import antipasto.GUI.GadgetListView.GadgetPanelEvents.ActiveGadgetObject;
import antipasto.GUI.GadgetListView.GadgetPanelEvents.IActiveGadgetChangedEventListener;
import antipasto.Interfaces.IModule;
import processing.app.Base;
import processing.app.Serial;
import processing.app.SerialException;
import processing.app.FlashTransfer;
import javax.swing.TransferHandler;
import javax.swing.*;
import java.awt.datatransfer.*;
import java.util.List;
import java.util.Iterator;
import java.net.*;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.math.*;
import java.awt.BorderLayout;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ImageListPanel extends JPanel implements IActiveGadgetChangedEventListener, ComponentListener {
private ImageListView list;
final FlashTransfer imageTransfer;
Serial mySerial = null;
private JButton removeButton;
private JButton transferButton;
private GadgetPanel panel;
private IModule _module;
private JProgressBar progressBar;
boolean isTransfering = false;
private JLabel infoLabel;
private JLabel progressLabel;
private long totalSize = 0;
private long totalFileCount = 0;
private JScrollPane scrollPane;
public ImageListPanel(GadgetPanel panel, FlashTransfer imageTransfer){
this.imageTransfer = imageTransfer;
this.init();
}
private void init(){
this.createTransferButton();
this.transferButton.setVisible(true);
this.setLayout(new BorderLayout());
this.createRemoveButton();
/* The north panel */
JPanel northPanel = new JPanel();
northPanel.setBackground(new Color(0x04, 0x4F, 0x6F));
northPanel.setOpaque(true);
northPanel.setLayout(new BorderLayout());
/* I'm the transfer buttons area */
JPanel northButtonPanel = new JPanel();
northButtonPanel.setLayout(new BorderLayout());
northButtonPanel.setBackground(new Color(0x04, 0x4F, 0x6F));
northButtonPanel.setOpaque(true);
northButtonPanel.add(transferButton, BorderLayout.WEST);
northButtonPanel.add(removeButton, BorderLayout.EAST);
/* I'm the transfer label area */
JPanel northLabelPanel = new JPanel();
+ northLabelPanel.setBackground(new Color(0x04, 0x4F, 0x6F));
+ northLabelPanel.setOpaque(true);
JLabel infoLabel = new JLabel(" Drop files below. ");
infoLabel.setForeground(Color.white);
infoLabel.setBackground(new Color(0x04, 0x4F, 0x6F));
infoLabel.setOpaque(true);
northLabelPanel.add(infoLabel);
/* Add everything that's North */
northPanel.add(northButtonPanel,BorderLayout.EAST);
northPanel.add(northLabelPanel, BorderLayout.WEST);
this.add(northPanel, BorderLayout.NORTH);
/* The south label */
JPanel southProgressPanel = new JPanel();
southProgressPanel.setLayout(new BorderLayout());
southProgressPanel.setBackground(new Color(0x04, 0x4f, 0x6f));
southProgressPanel.setOpaque(true);
/* A progress bar for the transfer */
progressBar = new JProgressBar();
progressBar.setVisible(false);
/* A label to describe stuff */
progressLabel = new JLabel(" Files: " + totalFileCount +
" | Total Size: " + totalSize / 1000 + " KB of 2000 KB Max ");
progressLabel.setForeground(Color.WHITE);
/* Add everything that's South */
southProgressPanel.add(progressBar,BorderLayout.EAST);
southProgressPanel.add(progressLabel, BorderLayout.WEST);
this.add(southProgressPanel, BorderLayout.SOUTH);
this.transferButton.setVisible(true);
this.removeButton.setVisible(true);
this.progressBar.setVisible(true);
this.progressLabel.setVisible(true);
}
public void setModule(IModule module){
if(module != null){
/* Build the center */
File[] files = module.getData();
list = new ImageListView(module);
if(scrollPane != null){
this.remove(scrollPane);
scrollPane.setVisible(false);
scrollPane = null; //let's take out the trash!
}
scrollPane = new JScrollPane(list);
this.add(scrollPane, BorderLayout.CENTER);
scrollPane.setSize(this.getWidth(), this.getHeight() - transferButton.getHeight());
scrollPane.setVisible(true);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
list.setVisible(true);
}
this.transferButton.setVisible(true);
//this.setSizesOfComponents();
_module = module;
}
public IModule getModule(){
return this._module;
}
public void paint(java.awt.Graphics g){
//this.setSizesOfComponents();
super.paint(g);
}
private void setSizesOfComponents(){
Dimension parentSize = this.getParent().getSize();
Dimension btnSize = this.transferButton.getSize();
double height = this.getParent().getSize().getHeight() - this.transferButton.getSize().getHeight();
int heightI = (int)height;
//Dimension listViewSize = new Dimension(this.getParent().getWidth(), heightI);
//list.setSize(listViewSize);
this.repaint();
}
private JButton createRemoveButton(){
this.removeButton = new JButton("Remove File");
//this.removeButton.setBackground(new Color(0x04, 0x4F, 0x6F));
this.removeButton.addMouseListener(
new MouseListener(){
public void mouseClicked(MouseEvent arg0) {
if(list.getSelectedValue() != null){
list.removeSelected();
}
}
public void mouseEntered(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent arg0) {
}
public void mouseReleased(MouseEvent arg0) {
}
});
return this.removeButton;
}
private void createTransferButton(){
this.transferButton = new JButton("Transfer");
//this.transferButton.setBackground(new Color(0x04, 0x4F, 0x6F));
this.transferButton.addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent arg0) {
if (isTransfering == false) {
transfer();
}
}
public void mouseEntered(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent arg0) {
}
public void mouseReleased(MouseEvent arg0) {
}
});
}
/*
*Transfers the files
*/
private void transfer(){
try {
final File fileList[] = this._module.getData();
final FlashTransfer transfer = imageTransfer;
transferButton.setText("Sending...");
progressBar.setVisible(true);
progressBar.setMaximum(fileList.length+1);
progressBar.setValue(1); //bump the progress bar
//up one for visual friendliness
final ImageListPanel ilist = this;
new Thread(
new Runnable() {
public void run() {
try {
mySerial = new Serial();
isTransfering = true;
transfer.setSerial(mySerial);
transfer.format();
boolean errorFree = true;
/* For each file... */
for(int i = 0; i < fileList.length; i++){
System.out.println("sending: " + fileList[i].getName());
if (transfer.sendFile(fileList[i])) {
/* Made some progress */
progressBar.setValue(progressBar.getValue()+1);
progressBar.repaint();
} else {
errorFree = false;
progressBar.setValue(progressBar.getValue()+1);
}
}
/* Exit the image transfer */
if( errorFree){
transfer.close();
}
isTransfering = false;
/* Reset UI after transfer */
ilist.resetUI();
} catch (SerialException err) {
err.printStackTrace();
//editor.error(err);
try { Thread.sleep(500); } catch (Exception e) { ilist.resetUI(); }
isTransfering = false;
/* Reset UI after transfer */
ilist.resetUI();
}
}}).start();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Reset the UI after transfer.
*/
public void resetUI() {
System.out.println("Reseting progress bar");
transferButton.setText("Transfer");
progressBar.setValue(0);
progressBar.setVisible(false);
this.repaint();
}
public void onActiveGadgetChanged(ActiveGadgetObject obj) {
}
public void componentHidden(ComponentEvent e) {
// TODO Auto-generated method stub
}
public void componentMoved(ComponentEvent e) {
// TODO Auto-generated method stub
}
public void componentResized(ComponentEvent e) {
// TODO Auto-generated method stub
this.show();
this.validate();
this.repaint();
}
public void componentShown(ComponentEvent e) {
// TODO Auto-generated method stub
}
}
| true | true | private void init(){
this.createTransferButton();
this.transferButton.setVisible(true);
this.setLayout(new BorderLayout());
this.createRemoveButton();
/* The north panel */
JPanel northPanel = new JPanel();
northPanel.setBackground(new Color(0x04, 0x4F, 0x6F));
northPanel.setOpaque(true);
northPanel.setLayout(new BorderLayout());
/* I'm the transfer buttons area */
JPanel northButtonPanel = new JPanel();
northButtonPanel.setLayout(new BorderLayout());
northButtonPanel.setBackground(new Color(0x04, 0x4F, 0x6F));
northButtonPanel.setOpaque(true);
northButtonPanel.add(transferButton, BorderLayout.WEST);
northButtonPanel.add(removeButton, BorderLayout.EAST);
/* I'm the transfer label area */
JPanel northLabelPanel = new JPanel();
JLabel infoLabel = new JLabel(" Drop files below. ");
infoLabel.setForeground(Color.white);
infoLabel.setBackground(new Color(0x04, 0x4F, 0x6F));
infoLabel.setOpaque(true);
northLabelPanel.add(infoLabel);
/* Add everything that's North */
northPanel.add(northButtonPanel,BorderLayout.EAST);
northPanel.add(northLabelPanel, BorderLayout.WEST);
this.add(northPanel, BorderLayout.NORTH);
/* The south label */
JPanel southProgressPanel = new JPanel();
southProgressPanel.setLayout(new BorderLayout());
southProgressPanel.setBackground(new Color(0x04, 0x4f, 0x6f));
southProgressPanel.setOpaque(true);
/* A progress bar for the transfer */
progressBar = new JProgressBar();
progressBar.setVisible(false);
/* A label to describe stuff */
progressLabel = new JLabel(" Files: " + totalFileCount +
" | Total Size: " + totalSize / 1000 + " KB of 2000 KB Max ");
progressLabel.setForeground(Color.WHITE);
/* Add everything that's South */
southProgressPanel.add(progressBar,BorderLayout.EAST);
southProgressPanel.add(progressLabel, BorderLayout.WEST);
this.add(southProgressPanel, BorderLayout.SOUTH);
this.transferButton.setVisible(true);
this.removeButton.setVisible(true);
this.progressBar.setVisible(true);
this.progressLabel.setVisible(true);
}
| private void init(){
this.createTransferButton();
this.transferButton.setVisible(true);
this.setLayout(new BorderLayout());
this.createRemoveButton();
/* The north panel */
JPanel northPanel = new JPanel();
northPanel.setBackground(new Color(0x04, 0x4F, 0x6F));
northPanel.setOpaque(true);
northPanel.setLayout(new BorderLayout());
/* I'm the transfer buttons area */
JPanel northButtonPanel = new JPanel();
northButtonPanel.setLayout(new BorderLayout());
northButtonPanel.setBackground(new Color(0x04, 0x4F, 0x6F));
northButtonPanel.setOpaque(true);
northButtonPanel.add(transferButton, BorderLayout.WEST);
northButtonPanel.add(removeButton, BorderLayout.EAST);
/* I'm the transfer label area */
JPanel northLabelPanel = new JPanel();
northLabelPanel.setBackground(new Color(0x04, 0x4F, 0x6F));
northLabelPanel.setOpaque(true);
JLabel infoLabel = new JLabel(" Drop files below. ");
infoLabel.setForeground(Color.white);
infoLabel.setBackground(new Color(0x04, 0x4F, 0x6F));
infoLabel.setOpaque(true);
northLabelPanel.add(infoLabel);
/* Add everything that's North */
northPanel.add(northButtonPanel,BorderLayout.EAST);
northPanel.add(northLabelPanel, BorderLayout.WEST);
this.add(northPanel, BorderLayout.NORTH);
/* The south label */
JPanel southProgressPanel = new JPanel();
southProgressPanel.setLayout(new BorderLayout());
southProgressPanel.setBackground(new Color(0x04, 0x4f, 0x6f));
southProgressPanel.setOpaque(true);
/* A progress bar for the transfer */
progressBar = new JProgressBar();
progressBar.setVisible(false);
/* A label to describe stuff */
progressLabel = new JLabel(" Files: " + totalFileCount +
" | Total Size: " + totalSize / 1000 + " KB of 2000 KB Max ");
progressLabel.setForeground(Color.WHITE);
/* Add everything that's South */
southProgressPanel.add(progressBar,BorderLayout.EAST);
southProgressPanel.add(progressLabel, BorderLayout.WEST);
this.add(southProgressPanel, BorderLayout.SOUTH);
this.transferButton.setVisible(true);
this.removeButton.setVisible(true);
this.progressBar.setVisible(true);
this.progressLabel.setVisible(true);
}
|
diff --git a/java/de/sanandrew/mods/particledeco/tileentity/TileEntityParticleBox.java b/java/de/sanandrew/mods/particledeco/tileentity/TileEntityParticleBox.java
index 5b591cf..f190cf6 100644
--- a/java/de/sanandrew/mods/particledeco/tileentity/TileEntityParticleBox.java
+++ b/java/de/sanandrew/mods/particledeco/tileentity/TileEntityParticleBox.java
@@ -1,109 +1,109 @@
/*******************************************************************************************************************
* Authors: SanAndreasP
* Copyright: SanAndreasP
* License: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
* http://creativecommons.org/licenses/by-nc-sa/4.0/
*******************************************************************************************************************/
package de.sanandrew.mods.particledeco.tileentity;
import de.sanandrew.core.manpack.mod.client.particle.EntityParticle;
import de.sanandrew.core.manpack.mod.client.particle.SAPEffectRenderer;
import de.sanandrew.core.manpack.util.SAPUtils;
import de.sanandrew.mods.particledeco.client.particle.EntityDustFX;
import de.sanandrew.mods.particledeco.util.ParticleBoxData;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.ForgeDirection;
import org.apache.commons.lang3.mutable.MutableFloat;
public class TileEntityParticleBox
extends TileEntity
{
private int ticksExisted;
public ParticleBoxData particleData = new ParticleBoxData();
public int prevColor = this.particleData.particleColor;
public float[] particleColorSplit = SAPUtils.getRgbaFromColorInt(this.particleData.particleColor).getColorFloatArray();
public TileEntityParticleBox() {
}
public boolean canUpdate() {
return true;
}
@Override
public void updateEntity() {
this.ticksExisted++;
if( this.worldObj.isRemote && this.ticksExisted % 2 == 0 ) {
if( this.prevColor != this.particleData.particleColor ) {
this.particleColorSplit = SAPUtils.getRgbaFromColorInt(this.particleData.particleColor).getColorFloatArray();
this.prevColor = this.particleData.particleColor;
}
MutableFloat[] motions = new MutableFloat[] {new MutableFloat(0.0F), new MutableFloat(0.0F), new MutableFloat(0.0F)};
this.changeDirection(motions[0], motions[1], motions[2]);
EntityParticle particle = new EntityDustFX(this.worldObj, this.xCoord + 0.5F, this.yCoord + 0.5F, this.zCoord + 0.5F, this.particleData.particleHeight,
this.particleData.particleSpeed, motions[0].getValue(), motions[1].getValue(), motions[2].getValue());
particle.setParticleColorRNG(this.particleColorSplit[0], this.particleColorSplit[1], this.particleColorSplit[2]);
particle.setBrightness(0xF0);
SAPEffectRenderer.INSTANCE.addEffect(particle);
}
}
@Override
public void writeToNBT(NBTTagCompound nbt) {
super.writeToNBT(nbt);
this.particleData.writeDataToNBT(nbt);
}
@Override
public void readFromNBT(NBTTagCompound nbt) {
super.readFromNBT(nbt);
this.particleData = ParticleBoxData.getDataFromNbt(nbt);
}
@Override
public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) {
this.particleData = ParticleBoxData.getDataFromNbt(pkt.func_148857_g());
}
@Override
public Packet getDescriptionPacket() {
NBTTagCompound nbt = new NBTTagCompound();
this.particleData.writeDataToNBT(nbt);
return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, 0, nbt);
}
private void changeDirection(MutableFloat motionX, MutableFloat motionY, MutableFloat motionZ) {
ForgeDirection dir = ForgeDirection.getOrientation(this.getBlockMetadata());
switch( this.particleData.particleSpread ) {
case SPREADED_FOUR_DIAG:
int ticksMod = this.ticksExisted % 5;
if( ticksMod != 0 ) {
- float facingMulti = 0.025F - (ticksMod % 2) * 0.5F;
+ float facingMulti = 0.025F - (ticksMod % 2) * 0.05F;
motionX.setValue(0.05F * dir.offsetX + facingMulti * (ticksMod < 3 ? dir.offsetY : dir.offsetZ));
motionY.setValue(0.05F * dir.offsetY + facingMulti * (ticksMod < 3 ? dir.offsetZ : dir.offsetX));
motionZ.setValue(0.05F * dir.offsetZ + facingMulti * (ticksMod < 3 ? dir.offsetX : dir.offsetY));
} else {
motionX.setValue(0.075F * dir.offsetX);
motionY.setValue(0.075F * dir.offsetY);
motionZ.setValue(0.075F * dir.offsetZ);
}
break;
case STRAIGHT_UP:
motionX.setValue(0.075F * dir.offsetX);
motionY.setValue(0.075F * dir.offsetY);
motionZ.setValue(0.075F * dir.offsetZ);
break;
}
}
}
| true | true | private void changeDirection(MutableFloat motionX, MutableFloat motionY, MutableFloat motionZ) {
ForgeDirection dir = ForgeDirection.getOrientation(this.getBlockMetadata());
switch( this.particleData.particleSpread ) {
case SPREADED_FOUR_DIAG:
int ticksMod = this.ticksExisted % 5;
if( ticksMod != 0 ) {
float facingMulti = 0.025F - (ticksMod % 2) * 0.5F;
motionX.setValue(0.05F * dir.offsetX + facingMulti * (ticksMod < 3 ? dir.offsetY : dir.offsetZ));
motionY.setValue(0.05F * dir.offsetY + facingMulti * (ticksMod < 3 ? dir.offsetZ : dir.offsetX));
motionZ.setValue(0.05F * dir.offsetZ + facingMulti * (ticksMod < 3 ? dir.offsetX : dir.offsetY));
} else {
motionX.setValue(0.075F * dir.offsetX);
motionY.setValue(0.075F * dir.offsetY);
motionZ.setValue(0.075F * dir.offsetZ);
}
break;
case STRAIGHT_UP:
motionX.setValue(0.075F * dir.offsetX);
motionY.setValue(0.075F * dir.offsetY);
motionZ.setValue(0.075F * dir.offsetZ);
break;
}
}
| private void changeDirection(MutableFloat motionX, MutableFloat motionY, MutableFloat motionZ) {
ForgeDirection dir = ForgeDirection.getOrientation(this.getBlockMetadata());
switch( this.particleData.particleSpread ) {
case SPREADED_FOUR_DIAG:
int ticksMod = this.ticksExisted % 5;
if( ticksMod != 0 ) {
float facingMulti = 0.025F - (ticksMod % 2) * 0.05F;
motionX.setValue(0.05F * dir.offsetX + facingMulti * (ticksMod < 3 ? dir.offsetY : dir.offsetZ));
motionY.setValue(0.05F * dir.offsetY + facingMulti * (ticksMod < 3 ? dir.offsetZ : dir.offsetX));
motionZ.setValue(0.05F * dir.offsetZ + facingMulti * (ticksMod < 3 ? dir.offsetX : dir.offsetY));
} else {
motionX.setValue(0.075F * dir.offsetX);
motionY.setValue(0.075F * dir.offsetY);
motionZ.setValue(0.075F * dir.offsetZ);
}
break;
case STRAIGHT_UP:
motionX.setValue(0.075F * dir.offsetX);
motionY.setValue(0.075F * dir.offsetY);
motionZ.setValue(0.075F * dir.offsetZ);
break;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.