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/server/src/main/java/org/apache/abdera/server/exceptions/MethodNotAllowedException.java b/server/src/main/java/org/apache/abdera/server/exceptions/MethodNotAllowedException.java
index ed46ceb6..05ca3da5 100644
--- a/server/src/main/java/org/apache/abdera/server/exceptions/MethodNotAllowedException.java
+++ b/server/src/main/java/org/apache/abdera/server/exceptions/MethodNotAllowedException.java
@@ -1,49 +1,49 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. 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. For additional information regarding
* copyright in this work, please see the NOTICE file in the top level
* directory of this distribution.
*/
package org.apache.abdera.server.exceptions;
public class MethodNotAllowedException
extends AbderaServerException {
private static final long serialVersionUID = -633052744794889086L;
public MethodNotAllowedException() {
super(405, null);
}
public MethodNotAllowedException(String text) {
super(405, text);
}
public void setAllow(String[] methods) {
if(methods == null || methods.length == 0) {
throw new IllegalArgumentException("Methods argument must not be empty or null.");
}
boolean first = true;
StringBuffer value = new StringBuffer();
for(String method : methods) {
if(first) {
value.append(method.toUpperCase());
first = false;
continue;
}
- value.append(", ").append(method);
+ value.append(", ").append(method);
}
setHeader("Allow", value.toString());
}
}
| true | true |
public void setAllow(String[] methods) {
if(methods == null || methods.length == 0) {
throw new IllegalArgumentException("Methods argument must not be empty or null.");
}
boolean first = true;
StringBuffer value = new StringBuffer();
for(String method : methods) {
if(first) {
value.append(method.toUpperCase());
first = false;
continue;
}
value.append(", ").append(method);
}
setHeader("Allow", value.toString());
}
|
public void setAllow(String[] methods) {
if(methods == null || methods.length == 0) {
throw new IllegalArgumentException("Methods argument must not be empty or null.");
}
boolean first = true;
StringBuffer value = new StringBuffer();
for(String method : methods) {
if(first) {
value.append(method.toUpperCase());
first = false;
continue;
}
value.append(", ").append(method);
}
setHeader("Allow", value.toString());
}
|
diff --git a/source/server/test/edu/wustl/cab2b/server/ejb/sqlquery/SQLQueryBeanTest.java b/source/server/test/edu/wustl/cab2b/server/ejb/sqlquery/SQLQueryBeanTest.java
index 81fe67ec..2662bc8a 100644
--- a/source/server/test/edu/wustl/cab2b/server/ejb/sqlquery/SQLQueryBeanTest.java
+++ b/source/server/test/edu/wustl/cab2b/server/ejb/sqlquery/SQLQueryBeanTest.java
@@ -1,80 +1,80 @@
package edu.wustl.cab2b.server.ejb.sqlquery;
import java.rmi.RemoteException;
import java.sql.SQLException;
import junit.framework.TestCase;
import edu.wustl.cab2b.common.ejb.EjbNamesConstants;
import edu.wustl.cab2b.common.ejb.sqlquery.SQLQueryBusinessInterface;
import edu.wustl.cab2b.common.ejb.sqlquery.SQLQueryHomeInterface;
import edu.wustl.cab2b.common.locator.Locator;
import edu.wustl.common.util.logger.Logger;
/**
* Test class to test {@link SQLQueryUtil}
* To Run this test case a started server even though it is JUnit
* @author Chandrakant Talele
*/
public class SQLQueryBeanTest extends TestCase {
SQLQueryBusinessInterface sqlQueryBean;
/**
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
Logger.configure();
String createTableSQL = "create table TEST_TABLE (ID BIGINT(38) NOT NULL, NAME VARCHAR(10) NULL,PRIMARY KEY (ID))";// insert into TEST_TABLE (ID,NAME) values (1,'ABC'),(2,'GAAL'),(3,'CLASS'),(4,'FOO')";
sqlQueryBean = (SQLQueryBusinessInterface) Locator.getInstance().locate(EjbNamesConstants.SQL_QUERY_BEAN,SQLQueryHomeInterface.class);
sqlQueryBean.executeUpdate(createTableSQL);
}
/**
* This method tests funtionality provided by {@link SQLQueryUtil}
* @throws RemoteException
*/
public void testSQLQueryUtil() throws RemoteException {
String insertDataSQL = "insert into TEST_TABLE (ID,NAME) values (1,'ABC'),(2,'GAAL'),(3,'CLASS'),(4,'FOO')";
int res=-1;
try {
res = sqlQueryBean.executeUpdate(insertDataSQL);
} catch (RemoteException e1) {
e1.printStackTrace();
fail("Remote Exception");
} catch (SQLException e1) {
e1.printStackTrace();
fail("SQLException");
}
assertEquals(4, res);
String selectSQL = "SELECT id,name FROM test_table WHERE name like ?";
int recordCount = 0;
- Object[][] rs = null;
+ String[][] rs = null;
try {
rs = sqlQueryBean.executeQuery(selectSQL, "%A%");
} catch (SQLException e) {
e.printStackTrace();
fail("SQLQueryUtil.executeQuery() failed ");
}
for (int i = 0; i < rs.length; i++) {
recordCount++;
- Long id = (Long) rs[i][0];
+ Long id = Long.parseLong(rs[i][0]);
String name = (String) rs[i][1];
assertTrue(id != 4);
assertTrue(name.indexOf((char) 'A') != -1);
}
assertTrue(recordCount == 3);
}
/**
* @see junit.framework.TestCase#tearDown()
*/
@Override
protected void tearDown() throws Exception {
sqlQueryBean.executeUpdate("DROP table TEST_TABLE");
}
}
| false | true |
public void testSQLQueryUtil() throws RemoteException {
String insertDataSQL = "insert into TEST_TABLE (ID,NAME) values (1,'ABC'),(2,'GAAL'),(3,'CLASS'),(4,'FOO')";
int res=-1;
try {
res = sqlQueryBean.executeUpdate(insertDataSQL);
} catch (RemoteException e1) {
e1.printStackTrace();
fail("Remote Exception");
} catch (SQLException e1) {
e1.printStackTrace();
fail("SQLException");
}
assertEquals(4, res);
String selectSQL = "SELECT id,name FROM test_table WHERE name like ?";
int recordCount = 0;
Object[][] rs = null;
try {
rs = sqlQueryBean.executeQuery(selectSQL, "%A%");
} catch (SQLException e) {
e.printStackTrace();
fail("SQLQueryUtil.executeQuery() failed ");
}
for (int i = 0; i < rs.length; i++) {
recordCount++;
Long id = (Long) rs[i][0];
String name = (String) rs[i][1];
assertTrue(id != 4);
assertTrue(name.indexOf((char) 'A') != -1);
}
assertTrue(recordCount == 3);
}
|
public void testSQLQueryUtil() throws RemoteException {
String insertDataSQL = "insert into TEST_TABLE (ID,NAME) values (1,'ABC'),(2,'GAAL'),(3,'CLASS'),(4,'FOO')";
int res=-1;
try {
res = sqlQueryBean.executeUpdate(insertDataSQL);
} catch (RemoteException e1) {
e1.printStackTrace();
fail("Remote Exception");
} catch (SQLException e1) {
e1.printStackTrace();
fail("SQLException");
}
assertEquals(4, res);
String selectSQL = "SELECT id,name FROM test_table WHERE name like ?";
int recordCount = 0;
String[][] rs = null;
try {
rs = sqlQueryBean.executeQuery(selectSQL, "%A%");
} catch (SQLException e) {
e.printStackTrace();
fail("SQLQueryUtil.executeQuery() failed ");
}
for (int i = 0; i < rs.length; i++) {
recordCount++;
Long id = Long.parseLong(rs[i][0]);
String name = (String) rs[i][1];
assertTrue(id != 4);
assertTrue(name.indexOf((char) 'A') != -1);
}
assertTrue(recordCount == 3);
}
|
diff --git a/wicket-select2/src/main/java/com/vaynberg/wicket/select2/Select2Choice.java b/wicket-select2/src/main/java/com/vaynberg/wicket/select2/Select2Choice.java
index 6e4fbd4..1642abc 100755
--- a/wicket-select2/src/main/java/com/vaynberg/wicket/select2/Select2Choice.java
+++ b/wicket-select2/src/main/java/com/vaynberg/wicket/select2/Select2Choice.java
@@ -1,82 +1,79 @@
/*
* Copyright 2012 Igor Vaynberg
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with
* the License. You may obtain a copy of the License in the LICENSE file, or 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.vaynberg.wicket.select2;
import java.util.Collections;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.model.IModel;
import org.apache.wicket.util.string.Strings;
import org.json.JSONException;
import com.vaynberg.wicket.select2.json.JsonBuilder;
/**
* Single-select Select2 component. Should be attached to a {@code <input type='hidden'/>} element.
*
* @author igor
*
* @param <T>
* type of choice object
*/
public class Select2Choice<T> extends AbstractSelect2Choice<T, T> {
public Select2Choice(String id, IModel<T> model, ChoiceProvider<T> provider) {
super(id, model, provider);
}
public Select2Choice(String id, IModel<T> model) {
super(id, model);
}
public Select2Choice(String id) {
super(id);
}
@Override
protected void convertInput() {
String input = getWebRequest().getRequestParameters().getParameterValue(getInputName()).toString();
if (Strings.isEmpty(input)) {
setConvertedInput(null);
} else {
setConvertedInput(getProvider().toChoices(Collections.singleton(input)).iterator().next());
}
}
@Override
protected void renderInitializationScript(IHeaderResponse response) {
- T state = getConvertedInput();
- if (state == null) {
- state = getModelObject();
- }
+ T state = hasRawInput() ? getConvertedInput() : getModelObject();
if (state != null) {
JsonBuilder selection = new JsonBuilder();
try {
selection.object();
getProvider().toJson(state, selection);
selection.endObject();
} catch (JSONException e) {
throw new RuntimeException("Error converting model object to Json", e);
}
response.render(OnDomReadyHeaderItem.forScript(JQuery.execute("$('#%s').select2('data', %s);", getMarkupId(),
selection.toJson())));
}
}
}
| true | true |
protected void renderInitializationScript(IHeaderResponse response) {
T state = getConvertedInput();
if (state == null) {
state = getModelObject();
}
if (state != null) {
JsonBuilder selection = new JsonBuilder();
try {
selection.object();
getProvider().toJson(state, selection);
selection.endObject();
} catch (JSONException e) {
throw new RuntimeException("Error converting model object to Json", e);
}
response.render(OnDomReadyHeaderItem.forScript(JQuery.execute("$('#%s').select2('data', %s);", getMarkupId(),
selection.toJson())));
}
}
|
protected void renderInitializationScript(IHeaderResponse response) {
T state = hasRawInput() ? getConvertedInput() : getModelObject();
if (state != null) {
JsonBuilder selection = new JsonBuilder();
try {
selection.object();
getProvider().toJson(state, selection);
selection.endObject();
} catch (JSONException e) {
throw new RuntimeException("Error converting model object to Json", e);
}
response.render(OnDomReadyHeaderItem.forScript(JQuery.execute("$('#%s').select2('data', %s);", getMarkupId(),
selection.toJson())));
}
}
|
diff --git a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/io/dav/http/HTTPSSLKeyManager.java b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/io/dav/http/HTTPSSLKeyManager.java
index d84e9653a..eaa137559 100644
--- a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/io/dav/http/HTTPSSLKeyManager.java
+++ b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/io/dav/http/HTTPSSLKeyManager.java
@@ -1,476 +1,476 @@
/*
* ====================================================================
* Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://svnkit.com/license.html
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
package org.tmatesoft.svn.core.internal.io.dav.http;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.security.KeyStore;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.X509KeyManager;
import org.tmatesoft.svn.core.SVNAuthenticationException;
import org.tmatesoft.svn.core.SVNCancelException;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.BasicAuthenticationManager;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.auth.SVNAuthentication;
import org.tmatesoft.svn.core.auth.SVNPasswordAuthentication;
import org.tmatesoft.svn.core.auth.SVNSSLAuthentication;
import org.tmatesoft.svn.core.internal.wc.ISVNSSLPasspharsePromptSupport;
import org.tmatesoft.svn.core.internal.wc.SVNErrorManager;
import org.tmatesoft.svn.core.internal.wc.SVNFileUtil;
import org.tmatesoft.svn.util.SVNDebugLog;
import org.tmatesoft.svn.util.SVNLogType;
/**
* @version 1.3
* @author TMate Software Ltd.
*/
public final class HTTPSSLKeyManager implements X509KeyManager {
public static KeyManager[] loadClientCertificate() throws SVNException {
Provider pjacapi = Security.getProvider("CAPI");
Provider pmscapi = Security.getProvider("SunMSCAPI");
KeyManager[] result = null;
SVNDebugLog.getDefaultLog().logError(SVNLogType.CLIENT,"using mscapi");
// get key store
KeyStore keyStore = null;
// Note: When a security manager is installed,
// the following call requires SecurityPermission
// "authProvider.SunMSCAPI".
try {
if (pmscapi != null) {
pmscapi.setProperty("Signature.SHA1withRSA","sun.security.mscapi.RSASignature$SHA1");
keyStore = KeyStore.getInstance("Windows-MY",pmscapi);
} else if (pjacapi != null) {
keyStore = KeyStore.getInstance("CAPI");
}
if (keyStore != null) {
keyStore.load(null, null);
}
} catch (Throwable th) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, th);
throw new SVNException(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "Problems, when connecting with ms capi! "+th.getMessage(), null, SVNErrorMessage.TYPE_ERROR, th));
}
KeyManagerFactory kmf = null;
if (keyStore != null) {
try {
kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
if (kmf != null) {
kmf.init(keyStore, null);
result = kmf.getKeyManagers();
}
}
catch (Throwable th) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, th);
throw new SVNException(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "MS Capi error: "+th.getMessage()).initCause(th));
}
}
return result;
}
public static KeyManager[] loadClientCertificate(File clientCertFile, String clientCertPassword) throws SVNException {
char[] passphrase = null;
if (clientCertPassword == null || clientCertPassword.length() == 0) {
// Client certificates without an passphrase can't be received from Java Keystores.
throw new SVNException(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "No client certificate passphrase supplied (did you forget to specify?).\n" +
"Note that client certificates with empty passphrases can''t be used. In this case please re-create the certificate with a passphrase."));
}
if (clientCertPassword != null) {
passphrase = clientCertPassword.toCharArray();
}
if (clientCertFile != null && clientCertFile.getName().startsWith(SVNSSLAuthentication.MSCAPI)) {
SVNDebugLog.getDefaultLog().logError(SVNLogType.CLIENT,"using mscapi");
try {
KeyStore keyStore = KeyStore.getInstance("Windows-MY");
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, "using my windows store");
if (keyStore != null) {
keyStore.load(null, null);
}
KeyManagerFactory kmf = null;
if (keyStore != null) {
kmf = KeyManagerFactory.getInstance("SunX509");
if (kmf != null) {
kmf.init(keyStore, passphrase);
return kmf.getKeyManagers();
}
}
return null;
}
catch (Throwable th) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, th);
throw new SVNException(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "loadClientCertificate ms capi with file - should not be called: "+th.getMessage(), null, SVNErrorMessage.TYPE_ERROR, th));
}
}
final InputStream is = SVNFileUtil.openFileForReading(clientCertFile, SVNLogType.NETWORK);
return loadClientCertificate(is,clientCertPassword);
}
public static KeyManager[] loadClientCertificate(InputStream clientCertFile, String clientCertPassword) throws SVNException {
char[] passphrase = null;
if (clientCertPassword != null) {
passphrase = clientCertPassword.toCharArray();
}
KeyStore keyStore;
try {
keyStore = KeyStore.getInstance("PKCS12");
if (keyStore != null) {
keyStore.load(clientCertFile, passphrase);
}
}
catch (Throwable th) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, th);
throw new SVNException(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, th.getMessage(), null, SVNErrorMessage.TYPE_ERROR, th));
}
finally {
SVNFileUtil.closeFile(clientCertFile);
}
if (keyStore != null) {
try {
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
if (kmf != null) {
kmf.init(keyStore, passphrase);
return kmf.getKeyManagers();
}
}
catch (Throwable th) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, th);
throw new SVNException(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, th));
}
}
return null;
}
public KeyManager[] loadClientCertificate(SVNSSLAuthentication sslAuthentication) throws SVNException {
String clientCertPassword = sslAuthentication.getPassword();
String clientCertPath = sslAuthentication.getCertificatePath();
byte[] clientCertFile = sslAuthentication.getCertificateFile();
char[] passphrase = clientCertPassword == null || clientCertPassword.length() == 0 ? new char[0] : clientCertPassword.toCharArray();
String realm = clientCertPath;
SVNAuthentication auth = null;
KeyManager[] result = null;
KeyStore keyStore = null;
- if (clientCertFile != null && clientCertPath.startsWith(SVNSSLAuthentication.MSCAPI)) {
+ if (clientCertPath != null && clientCertPath.startsWith(SVNSSLAuthentication.MSCAPI)) {
SVNDebugLog.getDefaultLog().logError(SVNLogType.CLIENT,"using mscapi");
try {
keyStore = KeyStore.getInstance("Windows-MY");
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, "using my windows store");
if (keyStore != null) {
keyStore.load(null, null);
}
KeyManagerFactory kmf = null;
if (keyStore != null) {
kmf = KeyManagerFactory.getInstance("SunX509");
if (kmf != null) {
kmf.init(keyStore, passphrase);
result = kmf.getKeyManagers();
}
}
return result;
} catch (Throwable th) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, th);
throw new SVNAuthenticationException(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "loadClientCertificate ms capi with file - should not be called: "+th.getMessage(), null, SVNErrorMessage.TYPE_ERROR, th), th);
}
}
while(true) {
try {
final InputStream is = new ByteArrayInputStream(clientCertFile);
try {
keyStore = KeyStore.getInstance("PKCS12");
if (keyStore != null) {
keyStore.load(is, passphrase);
}
} finally {
SVNFileUtil.closeFile(is);
}
if (auth != null) {
BasicAuthenticationManager.acknowledgeAuthentication(true, ISVNAuthenticationManager.SSL, realm, null, auth, url, authenticationManager);
} else {
BasicAuthenticationManager.acknowledgeAuthentication(true, ISVNAuthenticationManager.SSL, clientCertPath, null,
new SVNPasswordAuthentication("", clientCertPassword, sslAuthentication.isStorageAllowed(), sslAuthentication.getURL(), false), url, authenticationManager);
}
break;
} catch (IOException io) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, io);
if (auth != null) {
BasicAuthenticationManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.SSL, realm, SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, io.getMessage()), auth, url, authenticationManager);
auth = authenticationManager.getNextAuthentication(ISVNAuthenticationManager.SSL, realm, sslAuthentication.getURL());
} else {
auth = authenticationManager.getFirstAuthentication(ISVNAuthenticationManager.SSL, realm, sslAuthentication.getURL());
}
if (auth instanceof SVNPasswordAuthentication) {
passphrase = ((SVNPasswordAuthentication) auth).getPassword().toCharArray();
} else {
auth = null;
SVNErrorManager.cancel("authentication cancelled", SVNLogType.NETWORK);
break;
}
continue;
} catch (Throwable th) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, th);
throw new SVNException(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, th.getMessage(), null, SVNErrorMessage.TYPE_ERROR, th), th);
}
}
KeyManagerFactory kmf = null;
if (keyStore != null) {
try {
kmf = KeyManagerFactory.getInstance("SunX509");
if (kmf != null) {
kmf.init(keyStore, passphrase);
result = kmf.getKeyManagers();
}
}
catch (Throwable th) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, th);
throw new SVNAuthenticationException(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, th.getMessage()), th);
}
}
return result;
}
private final ISVNAuthenticationManager authenticationManager;
private final String realm;
private final SVNURL url;
private KeyManager[] myKeyManagers;
private SVNSSLAuthentication myAuthentication;
private Exception myException;
private String chooseAlias = null;
private boolean myIsFirstRequest = true;
public HTTPSSLKeyManager(ISVNAuthenticationManager authenticationManager, String realm, SVNURL url) {
this.authenticationManager = authenticationManager;
this.realm = realm;
this.url = url;
}
public String[] getClientAliases(String location, Principal[] principals) {
if (!initializeNoException()) {
return null;
}
for (Iterator<X509KeyManager> it = getX509KeyManagers(myKeyManagers).iterator(); it.hasNext();) {
final X509KeyManager keyManager = it.next();
final String[] clientAliases = keyManager.getClientAliases(location, principals);
if (clientAliases != null) {
return clientAliases;
}
}
return null;
}
public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
if (!initializeNoException()) {
return null;
}
if (chooseAlias != null) {
return chooseAlias;
}
for (Iterator<X509KeyManager> it = getX509KeyManagers(myKeyManagers).iterator(); it.hasNext();) {
final X509KeyManager keyManager = it.next();
final String clientAlias = keyManager.chooseClientAlias(strings, principals, socket);
if (clientAlias != null) {
return clientAlias;
}
}
return null;
}
public String[] getServerAliases(String location, Principal[] principals) {
if (!initializeNoException()) {
return null;
}
for (Iterator<X509KeyManager> it = getX509KeyManagers(myKeyManagers).iterator(); it.hasNext();) {
final X509KeyManager keyManager = it.next();
final String[] serverAliases = keyManager.getServerAliases(location, principals);
if (serverAliases != null) {
return serverAliases;
}
}
return null;
}
public String chooseServerAlias(String location, Principal[] principals, Socket socket) {
if (!initializeNoException()) {
return null;
}
for (Iterator<X509KeyManager> it = getX509KeyManagers(myKeyManagers).iterator(); it.hasNext();) {
final X509KeyManager keyManager = it.next();
final String serverAlias = keyManager.chooseServerAlias(location, principals, socket);
if (serverAlias != null) {
return serverAlias;
}
}
return null;
}
public X509Certificate[] getCertificateChain(String location) {
if (!initializeNoException()) {
return null;
}
for (Iterator<X509KeyManager> it = getX509KeyManagers(myKeyManagers).iterator(); it.hasNext();) {
final X509KeyManager keyManager = it.next();
final X509Certificate[] certificateChain = keyManager.getCertificateChain(location);
if (certificateChain != null) {
return certificateChain;
}
}
return null;
}
public PrivateKey getPrivateKey(String string) {
if (!initializeNoException()) {
return null;
}
for (Iterator<X509KeyManager> it = getX509KeyManagers(myKeyManagers).iterator(); it.hasNext();) {
final X509KeyManager keyManager = it.next();
final PrivateKey privateKey = keyManager.getPrivateKey(string);
if (privateKey != null) {
return privateKey;
}
}
return null;
}
public Exception getException() {
return myException;
}
public void acknowledgeAndClearAuthentication(SVNErrorMessage errorMessage) throws SVNException {
if (myAuthentication != null) {
BasicAuthenticationManager.acknowledgeAuthentication(errorMessage == null, ISVNAuthenticationManager.SSL, realm, errorMessage, myAuthentication, url, authenticationManager);
}
if (errorMessage != null) {
myKeyManagers = null;
chooseAlias = null;
} else {
myAuthentication = null;
myIsFirstRequest = true;
}
final Exception exception = myException;
myException = null;
if (exception instanceof SVNException) {
throw (SVNException)exception;
} else if (exception != null) {
throw new SVNException(SVNErrorMessage.UNKNOWN_ERROR_MESSAGE, exception);
}
}
private boolean initializeNoException() {
try {
final boolean result = initialize();
myException = null;
return result;
}
catch (Exception exception) {
myException = exception;
return false;
}
}
private boolean initialize() throws SVNException {
if (myKeyManagers != null) {
return true;
}
for (; ;) {
if (myIsFirstRequest) {
myAuthentication = (SVNSSLAuthentication)authenticationManager.getFirstAuthentication(ISVNAuthenticationManager.SSL, realm, url);
myIsFirstRequest = false;
} else {
myAuthentication = (SVNSSLAuthentication)authenticationManager.getNextAuthentication(ISVNAuthenticationManager.SSL, realm, url);
}
if (myAuthentication == null) {
SVNErrorManager.cancel("SSL authentication with client certificate cancelled", SVNLogType.NETWORK);
}
final KeyManager[] keyManagers;
try {
if (isMSCAPI(myAuthentication)) {
keyManagers = loadClientCertificate();
chooseAlias = myAuthentication.getAlias();
} else {
if (authenticationManager instanceof ISVNSSLPasspharsePromptSupport &&
((ISVNSSLPasspharsePromptSupport) authenticationManager).isSSLPassphrasePromtSupported()) {
keyManagers = loadClientCertificate(myAuthentication);
} else {
keyManagers = loadClientCertificate(new ByteArrayInputStream(myAuthentication.getCertificateFile()), myAuthentication.getPassword());
}
}
} catch (SVNAuthenticationException authenticationException) {
throw authenticationException;
} catch (SVNCancelException cancel) {
throw cancel;
} catch (SVNException ex) {
final SVNErrorMessage sslErr = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "Failed to load SSL client certificate: ''{0}''", new Object[] { ex.getMessage() }, SVNErrorMessage.TYPE_ERROR, ex.getCause());
BasicAuthenticationManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.SSL, realm, sslErr, myAuthentication, url, authenticationManager);
continue;
}
myKeyManagers = keyManagers;
return true;
}
}
private static List<X509KeyManager> getX509KeyManagers(KeyManager[] keyManagers) {
final List<X509KeyManager> x509KeyManagers = new ArrayList<X509KeyManager>();
for (int index = 0; index < keyManagers.length; index++) {
final KeyManager keyManager = keyManagers[index];
if (keyManager instanceof X509KeyManager) {
x509KeyManagers.add((X509KeyManager) keyManager);
}
}
return x509KeyManagers;
}
private static boolean isMSCAPI(SVNSSLAuthentication sslAuthentication) {
return sslAuthentication != null && SVNSSLAuthentication.MSCAPI.equals(sslAuthentication.getSSLKind());
}
}
| true | true |
public KeyManager[] loadClientCertificate(SVNSSLAuthentication sslAuthentication) throws SVNException {
String clientCertPassword = sslAuthentication.getPassword();
String clientCertPath = sslAuthentication.getCertificatePath();
byte[] clientCertFile = sslAuthentication.getCertificateFile();
char[] passphrase = clientCertPassword == null || clientCertPassword.length() == 0 ? new char[0] : clientCertPassword.toCharArray();
String realm = clientCertPath;
SVNAuthentication auth = null;
KeyManager[] result = null;
KeyStore keyStore = null;
if (clientCertFile != null && clientCertPath.startsWith(SVNSSLAuthentication.MSCAPI)) {
SVNDebugLog.getDefaultLog().logError(SVNLogType.CLIENT,"using mscapi");
try {
keyStore = KeyStore.getInstance("Windows-MY");
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, "using my windows store");
if (keyStore != null) {
keyStore.load(null, null);
}
KeyManagerFactory kmf = null;
if (keyStore != null) {
kmf = KeyManagerFactory.getInstance("SunX509");
if (kmf != null) {
kmf.init(keyStore, passphrase);
result = kmf.getKeyManagers();
}
}
return result;
} catch (Throwable th) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, th);
throw new SVNAuthenticationException(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "loadClientCertificate ms capi with file - should not be called: "+th.getMessage(), null, SVNErrorMessage.TYPE_ERROR, th), th);
}
}
while(true) {
try {
final InputStream is = new ByteArrayInputStream(clientCertFile);
try {
keyStore = KeyStore.getInstance("PKCS12");
if (keyStore != null) {
keyStore.load(is, passphrase);
}
} finally {
SVNFileUtil.closeFile(is);
}
if (auth != null) {
BasicAuthenticationManager.acknowledgeAuthentication(true, ISVNAuthenticationManager.SSL, realm, null, auth, url, authenticationManager);
} else {
BasicAuthenticationManager.acknowledgeAuthentication(true, ISVNAuthenticationManager.SSL, clientCertPath, null,
new SVNPasswordAuthentication("", clientCertPassword, sslAuthentication.isStorageAllowed(), sslAuthentication.getURL(), false), url, authenticationManager);
}
break;
} catch (IOException io) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, io);
if (auth != null) {
BasicAuthenticationManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.SSL, realm, SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, io.getMessage()), auth, url, authenticationManager);
auth = authenticationManager.getNextAuthentication(ISVNAuthenticationManager.SSL, realm, sslAuthentication.getURL());
} else {
auth = authenticationManager.getFirstAuthentication(ISVNAuthenticationManager.SSL, realm, sslAuthentication.getURL());
}
if (auth instanceof SVNPasswordAuthentication) {
passphrase = ((SVNPasswordAuthentication) auth).getPassword().toCharArray();
} else {
auth = null;
SVNErrorManager.cancel("authentication cancelled", SVNLogType.NETWORK);
break;
}
continue;
} catch (Throwable th) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, th);
throw new SVNException(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, th.getMessage(), null, SVNErrorMessage.TYPE_ERROR, th), th);
}
}
KeyManagerFactory kmf = null;
if (keyStore != null) {
try {
kmf = KeyManagerFactory.getInstance("SunX509");
if (kmf != null) {
kmf.init(keyStore, passphrase);
result = kmf.getKeyManagers();
}
}
catch (Throwable th) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, th);
throw new SVNAuthenticationException(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, th.getMessage()), th);
}
}
return result;
}
|
public KeyManager[] loadClientCertificate(SVNSSLAuthentication sslAuthentication) throws SVNException {
String clientCertPassword = sslAuthentication.getPassword();
String clientCertPath = sslAuthentication.getCertificatePath();
byte[] clientCertFile = sslAuthentication.getCertificateFile();
char[] passphrase = clientCertPassword == null || clientCertPassword.length() == 0 ? new char[0] : clientCertPassword.toCharArray();
String realm = clientCertPath;
SVNAuthentication auth = null;
KeyManager[] result = null;
KeyStore keyStore = null;
if (clientCertPath != null && clientCertPath.startsWith(SVNSSLAuthentication.MSCAPI)) {
SVNDebugLog.getDefaultLog().logError(SVNLogType.CLIENT,"using mscapi");
try {
keyStore = KeyStore.getInstance("Windows-MY");
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, "using my windows store");
if (keyStore != null) {
keyStore.load(null, null);
}
KeyManagerFactory kmf = null;
if (keyStore != null) {
kmf = KeyManagerFactory.getInstance("SunX509");
if (kmf != null) {
kmf.init(keyStore, passphrase);
result = kmf.getKeyManagers();
}
}
return result;
} catch (Throwable th) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, th);
throw new SVNAuthenticationException(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "loadClientCertificate ms capi with file - should not be called: "+th.getMessage(), null, SVNErrorMessage.TYPE_ERROR, th), th);
}
}
while(true) {
try {
final InputStream is = new ByteArrayInputStream(clientCertFile);
try {
keyStore = KeyStore.getInstance("PKCS12");
if (keyStore != null) {
keyStore.load(is, passphrase);
}
} finally {
SVNFileUtil.closeFile(is);
}
if (auth != null) {
BasicAuthenticationManager.acknowledgeAuthentication(true, ISVNAuthenticationManager.SSL, realm, null, auth, url, authenticationManager);
} else {
BasicAuthenticationManager.acknowledgeAuthentication(true, ISVNAuthenticationManager.SSL, clientCertPath, null,
new SVNPasswordAuthentication("", clientCertPassword, sslAuthentication.isStorageAllowed(), sslAuthentication.getURL(), false), url, authenticationManager);
}
break;
} catch (IOException io) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, io);
if (auth != null) {
BasicAuthenticationManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.SSL, realm, SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, io.getMessage()), auth, url, authenticationManager);
auth = authenticationManager.getNextAuthentication(ISVNAuthenticationManager.SSL, realm, sslAuthentication.getURL());
} else {
auth = authenticationManager.getFirstAuthentication(ISVNAuthenticationManager.SSL, realm, sslAuthentication.getURL());
}
if (auth instanceof SVNPasswordAuthentication) {
passphrase = ((SVNPasswordAuthentication) auth).getPassword().toCharArray();
} else {
auth = null;
SVNErrorManager.cancel("authentication cancelled", SVNLogType.NETWORK);
break;
}
continue;
} catch (Throwable th) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, th);
throw new SVNException(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, th.getMessage(), null, SVNErrorMessage.TYPE_ERROR, th), th);
}
}
KeyManagerFactory kmf = null;
if (keyStore != null) {
try {
kmf = KeyManagerFactory.getInstance("SunX509");
if (kmf != null) {
kmf.init(keyStore, passphrase);
result = kmf.getKeyManagers();
}
}
catch (Throwable th) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, th);
throw new SVNAuthenticationException(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, th.getMessage()), th);
}
}
return result;
}
|
diff --git a/sikuli-script/src/main/java/org/sikuli/script/internal/hotkey/LinuxHotkeyManager.java b/sikuli-script/src/main/java/org/sikuli/script/internal/hotkey/LinuxHotkeyManager.java
index 3d3798d1..704b1769 100644
--- a/sikuli-script/src/main/java/org/sikuli/script/internal/hotkey/LinuxHotkeyManager.java
+++ b/sikuli-script/src/main/java/org/sikuli/script/internal/hotkey/LinuxHotkeyManager.java
@@ -1,106 +1,106 @@
/*
* Copyright 2010-2011, Sikuli.org
* Released under the MIT License.
*
*/
package org.sikuli.script.internal.hotkey;
import java.lang.reflect.*;
import java.awt.Event;
import java.awt.event.*;
import java.util.*;
import java.io.IOException;
import org.sikuli.script.Debug;
import org.sikuli.script.HotkeyListener;
import org.sikuli.script.HotkeyEvent;
import com.wapmx.nativeutils.jniloader.NativeLoader;
import jxgrabkey.HotkeyConflictException;
import jxgrabkey.JXGrabKey;
public class LinuxHotkeyManager extends HotkeyManager {
static{
try{
NativeLoader.loadLibrary("JXGrabKey");
}
catch(IOException e){
Debug.error("Can't load native lib JXGrabKey");
e.printStackTrace();
}
}
class HotkeyData {
int key, modifiers;
HotkeyListener listener;
public HotkeyData(int key_, int mod_, HotkeyListener l_){
key = key_;
modifiers = mod_;
listener = l_;
}
};
class MyHotkeyHandler implements jxgrabkey.HotkeyListener{
public void onHotkey(int id){
Debug.log(4, "Hotkey pressed");
HotkeyData data = _idCallbackMap.get(id);
HotkeyEvent e = new HotkeyEvent(data.key, data.modifiers);
data.listener.hotkeyPressed(e);
}
};
private Map<Integer, HotkeyData> _idCallbackMap = new HashMap<Integer,HotkeyData >();
private int _gHotkeyId = 1;
protected boolean _addHotkey(int keyCode, int modifiers, HotkeyListener listener){
JXGrabKey grabKey = JXGrabKey.getInstance();
if(_gHotkeyId == 1){
grabKey.addHotkeyListener(new MyHotkeyHandler());
}
_removeHotkey(keyCode, modifiers);
int id = _gHotkeyId++;
HotkeyData data = new HotkeyData(keyCode, modifiers, listener);
_idCallbackMap.put(id, data);
try{
//JXGrabKey.setDebugOutput(true);
grabKey.registerAwtHotkey(id, modifiers, keyCode);
}catch(HotkeyConflictException e){
- Debug.error("Hot key conflicts: " + txtMod + "+" + txtCode);
+ Debug.error("Hot key conflicts");
return false;
}
return true;
}
protected boolean _removeHotkey(int keyCode, int modifiers){
for( Map.Entry<Integer, HotkeyData> entry : _idCallbackMap.entrySet() ){
HotkeyData data = entry.getValue();
if(data.key == keyCode && data.modifiers == modifiers){
JXGrabKey grabKey = JXGrabKey.getInstance();
int id = entry.getKey();
grabKey.unregisterHotKey(id);
_idCallbackMap.remove(id);
return true;
}
}
return false;
}
public void cleanUp(){
JXGrabKey grabKey = JXGrabKey.getInstance();
for( Map.Entry<Integer, HotkeyData> entry : _idCallbackMap.entrySet() ){
int id = entry.getKey();
grabKey.unregisterHotKey(id);
}
_gHotkeyId = 1;
_idCallbackMap.clear();
grabKey.getInstance().cleanUp();
}
}
| true | true |
protected boolean _addHotkey(int keyCode, int modifiers, HotkeyListener listener){
JXGrabKey grabKey = JXGrabKey.getInstance();
if(_gHotkeyId == 1){
grabKey.addHotkeyListener(new MyHotkeyHandler());
}
_removeHotkey(keyCode, modifiers);
int id = _gHotkeyId++;
HotkeyData data = new HotkeyData(keyCode, modifiers, listener);
_idCallbackMap.put(id, data);
try{
//JXGrabKey.setDebugOutput(true);
grabKey.registerAwtHotkey(id, modifiers, keyCode);
}catch(HotkeyConflictException e){
Debug.error("Hot key conflicts: " + txtMod + "+" + txtCode);
return false;
}
return true;
}
|
protected boolean _addHotkey(int keyCode, int modifiers, HotkeyListener listener){
JXGrabKey grabKey = JXGrabKey.getInstance();
if(_gHotkeyId == 1){
grabKey.addHotkeyListener(new MyHotkeyHandler());
}
_removeHotkey(keyCode, modifiers);
int id = _gHotkeyId++;
HotkeyData data = new HotkeyData(keyCode, modifiers, listener);
_idCallbackMap.put(id, data);
try{
//JXGrabKey.setDebugOutput(true);
grabKey.registerAwtHotkey(id, modifiers, keyCode);
}catch(HotkeyConflictException e){
Debug.error("Hot key conflicts");
return false;
}
return true;
}
|
diff --git a/src/com/android/phone/CallCard.java b/src/com/android/phone/CallCard.java
index 80b6fd8a..78129938 100644
--- a/src/com/android/phone/CallCard.java
+++ b/src/com/android/phone/CallCard.java
@@ -1,1783 +1,1791 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.phone;
import android.animation.LayoutTransition;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract.Contacts;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.accessibility.AccessibilityEvent;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.internal.telephony.Call;
import com.android.internal.telephony.CallManager;
import com.android.internal.telephony.CallerInfo;
import com.android.internal.telephony.CallerInfoAsyncQuery;
import com.android.internal.telephony.Connection;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneConstants;
import java.util.List;
/**
* "Call card" UI element: the in-call screen contains a tiled layout of call
* cards, each representing the state of a current "call" (ie. an active call,
* a call on hold, or an incoming call.)
*/
public class CallCard extends LinearLayout
implements CallTime.OnTickListener, CallerInfoAsyncQuery.OnQueryCompleteListener,
ContactsAsyncHelper.OnImageLoadCompleteListener {
private static final String LOG_TAG = "CallCard";
private static final boolean DBG = (PhoneGlobals.DBG_LEVEL >= 2);
private static final int TOKEN_UPDATE_PHOTO_FOR_CALL_STATE = 0;
private static final int TOKEN_DO_NOTHING = 1;
/**
* Used with {@link ContactsAsyncHelper#startObtainPhotoAsync(int, Context, Uri,
* ContactsAsyncHelper.OnImageLoadCompleteListener, Object)}
*/
private static class AsyncLoadCookie {
public final ImageView imageView;
public final CallerInfo callerInfo;
public final Call call;
public AsyncLoadCookie(ImageView imageView, CallerInfo callerInfo, Call call) {
this.imageView = imageView;
this.callerInfo = callerInfo;
this.call = call;
}
}
/**
* Reference to the InCallScreen activity that owns us. This may be
* null if we haven't been initialized yet *or* after the InCallScreen
* activity has been destroyed.
*/
private InCallScreen mInCallScreen;
// Phone app instance
private PhoneGlobals mApplication;
// Top-level subviews of the CallCard
/** Container for info about the current call(s) */
private ViewGroup mCallInfoContainer;
/** Primary "call info" block (the foreground or ringing call) */
private ViewGroup mPrimaryCallInfo;
/** "Call banner" for the primary call */
private ViewGroup mPrimaryCallBanner;
/** Secondary "call info" block (the background "on hold" call) */
private ViewStub mSecondaryCallInfo;
/**
* Container for both provider info and call state. This will take care of showing/hiding
* animation for those views.
*/
private ViewGroup mSecondaryInfoContainer;
private ViewGroup mProviderInfo;
private TextView mProviderLabel;
private TextView mProviderAddress;
// "Call state" widgets
private TextView mCallStateLabel;
private TextView mElapsedTime;
// Text colors, used for various labels / titles
private int mTextColorCallTypeSip;
// The main block of info about the "primary" or "active" call,
// including photo / name / phone number / etc.
private ImageView mPhoto;
private View mPhotoDimEffect;
private TextView mName;
private TextView mPhoneNumber;
private TextView mLabel;
private TextView mCallTypeLabel;
// private TextView mSocialStatus;
/**
* Uri being used to load contact photo for mPhoto. Will be null when nothing is being loaded,
* or a photo is already loaded.
*/
private Uri mLoadingPersonUri;
// Info about the "secondary" call, which is the "call on hold" when
// two lines are in use.
private TextView mSecondaryCallName;
private ImageView mSecondaryCallPhoto;
private View mSecondaryCallPhotoDimEffect;
// Onscreen hint for the incoming call RotarySelector widget.
private int mIncomingCallWidgetHintTextResId;
private int mIncomingCallWidgetHintColorResId;
private CallTime mCallTime;
// Track the state for the photo.
private ContactsAsyncHelper.ImageTracker mPhotoTracker;
// Cached DisplayMetrics density.
private float mDensity;
/**
* Sent when it takes too long (MESSAGE_DELAY msec) to load a contact photo for the given
* person, at which we just start showing the default avatar picture instead of the person's
* one. Note that we will *not* cancel the ongoing query and eventually replace the avatar
* with the person's photo, when it is available anyway.
*/
private static final int MESSAGE_SHOW_UNKNOWN_PHOTO = 101;
private static final int MESSAGE_DELAY = 500; // msec
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_SHOW_UNKNOWN_PHOTO:
showImage(mPhoto, R.drawable.picture_unknown);
break;
default:
Log.wtf(LOG_TAG, "mHandler: unexpected message: " + msg);
break;
}
}
};
public CallCard(Context context, AttributeSet attrs) {
super(context, attrs);
if (DBG) log("CallCard constructor...");
if (DBG) log("- this = " + this);
if (DBG) log("- context " + context + ", attrs " + attrs);
mApplication = PhoneGlobals.getInstance();
mCallTime = new CallTime(this);
// create a new object to track the state for the photo.
mPhotoTracker = new ContactsAsyncHelper.ImageTracker();
mDensity = getResources().getDisplayMetrics().density;
if (DBG) log("- Density: " + mDensity);
}
/* package */ void setInCallScreenInstance(InCallScreen inCallScreen) {
mInCallScreen = inCallScreen;
}
@Override
public void onTickForCallTimeElapsed(long timeElapsed) {
// While a call is in progress, update the elapsed time shown
// onscreen.
updateElapsedTimeWidget(timeElapsed);
}
/* package */ void stopTimer() {
mCallTime.cancelTimer();
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
if (DBG) log("CallCard onFinishInflate(this = " + this + ")...");
mCallInfoContainer = (ViewGroup) findViewById(R.id.call_info_container);
mPrimaryCallInfo = (ViewGroup) findViewById(R.id.primary_call_info);
mPrimaryCallBanner = (ViewGroup) findViewById(R.id.primary_call_banner);
mSecondaryInfoContainer = (ViewGroup) findViewById(R.id.secondary_info_container);
mProviderInfo = (ViewGroup) findViewById(R.id.providerInfo);
mProviderLabel = (TextView) findViewById(R.id.providerLabel);
mProviderAddress = (TextView) findViewById(R.id.providerAddress);
mCallStateLabel = (TextView) findViewById(R.id.callStateLabel);
mElapsedTime = (TextView) findViewById(R.id.elapsedTime);
// Text colors
mTextColorCallTypeSip = getResources().getColor(R.color.incall_callTypeSip);
// "Caller info" area, including photo / name / phone numbers / etc
mPhoto = (ImageView) findViewById(R.id.photo);
mPhotoDimEffect = findViewById(R.id.dim_effect_for_primary_photo);
mName = (TextView) findViewById(R.id.name);
mPhoneNumber = (TextView) findViewById(R.id.phoneNumber);
mLabel = (TextView) findViewById(R.id.label);
mCallTypeLabel = (TextView) findViewById(R.id.callTypeLabel);
// mSocialStatus = (TextView) findViewById(R.id.socialStatus);
// Secondary info area, for the background ("on hold") call
mSecondaryCallInfo = (ViewStub) findViewById(R.id.secondary_call_info);
}
/**
* Updates the state of all UI elements on the CallCard, based on the
* current state of the phone.
*/
/* package */ void updateState(CallManager cm) {
if (DBG) log("updateState(" + cm + ")...");
// Update the onscreen UI based on the current state of the phone.
PhoneConstants.State state = cm.getState(); // IDLE, RINGING, or OFFHOOK
Call ringingCall = cm.getFirstActiveRingingCall();
Call fgCall = cm.getActiveFgCall();
Call bgCall = cm.getFirstActiveBgCall();
// Update the overall layout of the onscreen elements, if in PORTRAIT.
// Portrait uses a programatically altered layout, whereas landscape uses layout xml's.
// Landscape view has the views side by side, so no shifting of the picture is needed
if (!PhoneUtils.isLandscape(this.getContext())) {
updateCallInfoLayout(state);
}
// If the FG call is dialing/alerting, we should display for that call
// and ignore the ringing call. This case happens when the telephony
// layer rejects the ringing call while the FG call is dialing/alerting,
// but the incoming call *does* briefly exist in the DISCONNECTING or
// DISCONNECTED state.
if ((ringingCall.getState() != Call.State.IDLE)
&& !fgCall.getState().isDialing()) {
// A phone call is ringing, call waiting *or* being rejected
// (ie. another call may also be active as well.)
updateRingingCall(cm);
} else if ((fgCall.getState() != Call.State.IDLE)
|| (bgCall.getState() != Call.State.IDLE)) {
// We are here because either:
// (1) the phone is off hook. At least one call exists that is
// dialing, active, or holding, and no calls are ringing or waiting,
// or:
// (2) the phone is IDLE but a call just ended and it's still in
// the DISCONNECTING or DISCONNECTED state. In this case, we want
// the main CallCard to display "Hanging up" or "Call ended".
// The normal "foreground call" code path handles both cases.
updateForegroundCall(cm);
} else {
// We don't have any DISCONNECTED calls, which means that the phone
// is *truly* idle.
if (mApplication.inCallUiState.showAlreadyDisconnectedState) {
// showAlreadyDisconnectedState implies the phone call is disconnected
// and we want to show the disconnected phone call for a moment.
//
// This happens when a phone call ends while the screen is off,
// which means the user had no chance to see the last status of
// the call. We'll turn off showAlreadyDisconnectedState flag
// and bail out of the in-call screen soon.
updateAlreadyDisconnected(cm);
} else {
// It's very rare to be on the InCallScreen at all in this
// state, but it can happen in some cases:
// - A stray onPhoneStateChanged() event came in to the
// InCallScreen *after* it was dismissed.
// - We're allowed to be on the InCallScreen because
// an MMI or USSD is running, but there's no actual "call"
// to display.
// - We're displaying an error dialog to the user
// (explaining why the call failed), so we need to stay on
// the InCallScreen so that the dialog will be visible.
//
// In these cases, put the callcard into a sane but "blank" state:
updateNoCall(cm);
}
}
}
/**
* Updates the overall size and positioning of mCallInfoContainer and
* the "Call info" blocks, based on the phone state.
*/
private void updateCallInfoLayout(PhoneConstants.State state) {
boolean ringing = (state == PhoneConstants.State.RINGING);
if (DBG) log("updateCallInfoLayout()... ringing = " + ringing);
// Based on the current state, update the overall
// CallCard layout:
// - Update the bottom margin of mCallInfoContainer to make sure
// the call info area won't overlap with the touchable
// controls on the bottom part of the screen.
int reservedVerticalSpace = mInCallScreen.getInCallTouchUi().getTouchUiHeight();
ViewGroup.MarginLayoutParams callInfoLp =
(ViewGroup.MarginLayoutParams) mCallInfoContainer.getLayoutParams();
callInfoLp.bottomMargin = reservedVerticalSpace; // Equivalent to setting
// android:layout_marginBottom in XML
if (DBG) log(" ==> callInfoLp.bottomMargin: " + reservedVerticalSpace);
mCallInfoContainer.setLayoutParams(callInfoLp);
}
/**
* Updates the UI for the state where the phone is in use, but not ringing.
*/
private void updateForegroundCall(CallManager cm) {
if (DBG) log("updateForegroundCall()...");
// if (DBG) PhoneUtils.dumpCallManager();
Call fgCall = cm.getActiveFgCall();
Call bgCall = cm.getFirstActiveBgCall();
if (fgCall.getState() == Call.State.IDLE) {
if (DBG) log("updateForegroundCall: no active call, show holding call");
// TODO: make sure this case agrees with the latest UI spec.
// Display the background call in the main info area of the
// CallCard, since there is no foreground call. Note that
// displayMainCallStatus() will notice if the call we passed in is on
// hold, and display the "on hold" indication.
fgCall = bgCall;
// And be sure to not display anything in the "on hold" box.
bgCall = null;
}
displayMainCallStatus(cm, fgCall);
Phone phone = fgCall.getPhone();
int phoneType = phone.getPhoneType();
if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
if ((mApplication.cdmaPhoneCallState.getCurrentCallState()
== CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
&& mApplication.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()) {
displaySecondaryCallStatus(cm, fgCall);
} else {
//This is required so that even if a background call is not present
// we need to clean up the background call area.
displaySecondaryCallStatus(cm, bgCall);
}
} else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
|| (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
displaySecondaryCallStatus(cm, bgCall);
}
}
/**
* Updates the UI for the state where an incoming call is ringing (or
* call waiting), regardless of whether the phone's already offhook.
*/
private void updateRingingCall(CallManager cm) {
if (DBG) log("updateRingingCall()...");
Call ringingCall = cm.getFirstActiveRingingCall();
// Display caller-id info and photo from the incoming call:
displayMainCallStatus(cm, ringingCall);
// And even in the Call Waiting case, *don't* show any info about
// the current ongoing call and/or the current call on hold.
// (Since the caller-id info for the incoming call totally trumps
// any info about the current call(s) in progress.)
displaySecondaryCallStatus(cm, null);
}
/**
* Updates the UI for the state where an incoming call is just disconnected while we want to
* show the screen for a moment.
*
* This case happens when the whole in-call screen is in background when phone calls are hanged
* up, which means there's no way to determine which call was the last call finished. Right now
* this method simply shows the previous primary call status with a photo, closing the
* secondary call status. In most cases (including conference call or misc call happening in
* CDMA) this behaves right.
*
* If there were two phone calls both of which were hung up but the primary call was the
* first, this would behave a bit odd (since the first one still appears as the
* "last disconnected").
*/
private void updateAlreadyDisconnected(CallManager cm) {
// For the foreground call, we manually set up every component based on previous state.
mPrimaryCallInfo.setVisibility(View.VISIBLE);
mSecondaryInfoContainer.setLayoutTransition(null);
mProviderInfo.setVisibility(View.GONE);
mCallStateLabel.setVisibility(View.VISIBLE);
mCallStateLabel.setText(mContext.getString(R.string.card_title_call_ended));
mElapsedTime.setVisibility(View.VISIBLE);
mCallTime.cancelTimer();
// Just hide it.
displaySecondaryCallStatus(cm, null);
}
/**
* Updates the UI for the state where the phone is not in use.
* This is analogous to updateForegroundCall() and updateRingingCall(),
* but for the (uncommon) case where the phone is
* totally idle. (See comments in updateState() above.)
*
* This puts the callcard into a sane but "blank" state.
*/
private void updateNoCall(CallManager cm) {
if (DBG) log("updateNoCall()...");
displayMainCallStatus(cm, null);
displaySecondaryCallStatus(cm, null);
}
/**
* Updates the main block of caller info on the CallCard
* (ie. the stuff in the primaryCallInfo block) based on the specified Call.
*/
private void displayMainCallStatus(CallManager cm, Call call) {
if (DBG) log("displayMainCallStatus(call " + call + ")...");
if (call == null) {
// There's no call to display, presumably because the phone is idle.
mPrimaryCallInfo.setVisibility(View.GONE);
return;
}
mPrimaryCallInfo.setVisibility(View.VISIBLE);
Call.State state = call.getState();
if (DBG) log(" - call.state: " + call.getState());
switch (state) {
case ACTIVE:
case DISCONNECTING:
// update timer field
if (DBG) log("displayMainCallStatus: start periodicUpdateTimer");
mCallTime.setActiveCallMode(call);
mCallTime.reset();
mCallTime.periodicUpdateTimer();
break;
case HOLDING:
// update timer field
mCallTime.cancelTimer();
break;
case DISCONNECTED:
// Stop getting timer ticks from this call
mCallTime.cancelTimer();
break;
case DIALING:
case ALERTING:
// Stop getting timer ticks from a previous call
mCallTime.cancelTimer();
break;
case INCOMING:
case WAITING:
// Stop getting timer ticks from a previous call
mCallTime.cancelTimer();
break;
case IDLE:
// The "main CallCard" should never be trying to display
// an idle call! In updateState(), if the phone is idle,
// we call updateNoCall(), which means that we shouldn't
// have passed a call into this method at all.
Log.w(LOG_TAG, "displayMainCallStatus: IDLE call in the main call card!");
// (It is possible, though, that we had a valid call which
// became idle *after* the check in updateState() but
// before we get here... So continue the best we can,
// with whatever (stale) info we can get from the
// passed-in Call object.)
break;
default:
Log.w(LOG_TAG, "displayMainCallStatus: unexpected call state: " + state);
break;
}
updateCallStateWidgets(call);
if (PhoneUtils.isConferenceCall(call)) {
// Update onscreen info for a conference call.
updateDisplayForConference(call);
} else {
// Update onscreen info for a regular call (which presumably
// has only one connection.)
Connection conn = null;
int phoneType = call.getPhone().getPhoneType();
if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
conn = call.getLatestConnection();
} else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
|| (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
conn = call.getEarliestConnection();
} else {
throw new IllegalStateException("Unexpected phone type: " + phoneType);
}
if (conn == null) {
if (DBG) log("displayMainCallStatus: connection is null, using default values.");
// if the connection is null, we run through the behaviour
// we had in the past, which breaks down into trivial steps
// with the current implementation of getCallerInfo and
// updateDisplayForPerson.
CallerInfo info = PhoneUtils.getCallerInfo(getContext(), null /* conn */);
updateDisplayForPerson(info, PhoneConstants.PRESENTATION_ALLOWED, false, call,
conn);
} else {
if (DBG) log(" - CONN: " + conn + ", state = " + conn.getState());
int presentation = conn.getNumberPresentation();
// make sure that we only make a new query when the current
// callerinfo differs from what we've been requested to display.
boolean runQuery = true;
Object o = conn.getUserData();
if (o instanceof PhoneUtils.CallerInfoToken) {
runQuery = mPhotoTracker.isDifferentImageRequest(
((PhoneUtils.CallerInfoToken) o).currentInfo);
} else {
runQuery = mPhotoTracker.isDifferentImageRequest(conn);
}
// Adding a check to see if the update was caused due to a Phone number update
// or CNAP update. If so then we need to start a new query
if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
Object obj = conn.getUserData();
String updatedNumber = conn.getAddress();
String updatedCnapName = conn.getCnapName();
CallerInfo info = null;
if (obj instanceof PhoneUtils.CallerInfoToken) {
info = ((PhoneUtils.CallerInfoToken) o).currentInfo;
} else if (o instanceof CallerInfo) {
info = (CallerInfo) o;
}
if (info != null) {
if (updatedNumber != null && !updatedNumber.equals(info.phoneNumber)) {
if (DBG) log("- displayMainCallStatus: updatedNumber = "
+ updatedNumber);
runQuery = true;
}
if (updatedCnapName != null && !updatedCnapName.equals(info.cnapName)) {
if (DBG) log("- displayMainCallStatus: updatedCnapName = "
+ updatedCnapName);
runQuery = true;
}
}
}
if (runQuery) {
if (DBG) log("- displayMainCallStatus: starting CallerInfo query...");
PhoneUtils.CallerInfoToken info =
PhoneUtils.startGetCallerInfo(getContext(), conn, this, call);
updateDisplayForPerson(info.currentInfo, presentation, !info.isFinal,
call, conn);
} else {
// No need to fire off a new query. We do still need
// to update the display, though (since we might have
// previously been in the "conference call" state.)
if (DBG) log("- displayMainCallStatus: using data we already have...");
if (o instanceof CallerInfo) {
CallerInfo ci = (CallerInfo) o;
// Update CNAP information if Phone state change occurred
ci.cnapName = conn.getCnapName();
ci.numberPresentation = conn.getNumberPresentation();
ci.namePresentation = conn.getCnapNamePresentation();
if (DBG) log("- displayMainCallStatus: CNAP data from Connection: "
+ "CNAP name=" + ci.cnapName
+ ", Number/Name Presentation=" + ci.numberPresentation);
if (DBG) log(" ==> Got CallerInfo; updating display: ci = " + ci);
updateDisplayForPerson(ci, presentation, false, call, conn);
} else if (o instanceof PhoneUtils.CallerInfoToken){
CallerInfo ci = ((PhoneUtils.CallerInfoToken) o).currentInfo;
if (DBG) log("- displayMainCallStatus: CNAP data from Connection: "
+ "CNAP name=" + ci.cnapName
+ ", Number/Name Presentation=" + ci.numberPresentation);
if (DBG) log(" ==> Got CallerInfoToken; updating display: ci = " + ci);
updateDisplayForPerson(ci, presentation, true, call, conn);
} else {
Log.w(LOG_TAG, "displayMainCallStatus: runQuery was false, "
+ "but we didn't have a cached CallerInfo object! o = " + o);
// TODO: any easy way to recover here (given that
// the CallCard is probably displaying stale info
// right now?) Maybe force the CallCard into the
// "Unknown" state?
}
}
}
}
// In some states we override the "photo" ImageView to be an
// indication of the current state, rather than displaying the
// regular photo as set above.
updatePhotoForCallState(call);
// One special feature of the "number" text field: For incoming
// calls, while the user is dragging the RotarySelector widget, we
// use mPhoneNumber to display a hint like "Rotate to answer".
if (mIncomingCallWidgetHintTextResId != 0) {
// Display the hint!
mPhoneNumber.setText(mIncomingCallWidgetHintTextResId);
mPhoneNumber.setTextColor(getResources().getColor(mIncomingCallWidgetHintColorResId));
mPhoneNumber.setVisibility(View.VISIBLE);
mLabel.setVisibility(View.GONE);
}
// If we don't have a hint to display, just don't touch
// mPhoneNumber and mLabel. (Their text / color / visibility have
// already been set correctly, by either updateDisplayForPerson()
// or updateDisplayForConference().)
}
/**
* Implemented for CallerInfoAsyncQuery.OnQueryCompleteListener interface.
* refreshes the CallCard data when it called.
*/
@Override
public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
if (DBG) log("onQueryComplete: token " + token + ", cookie " + cookie + ", ci " + ci);
if (cookie instanceof Call) {
// grab the call object and update the display for an individual call,
// as well as the successive call to update image via call state.
// If the object is a textview instead, we update it as we need to.
if (DBG) log("callerinfo query complete, updating ui from displayMainCallStatus()");
Call call = (Call) cookie;
Connection conn = null;
int phoneType = call.getPhone().getPhoneType();
if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
conn = call.getLatestConnection();
} else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
|| (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
conn = call.getEarliestConnection();
} else {
throw new IllegalStateException("Unexpected phone type: " + phoneType);
}
PhoneUtils.CallerInfoToken cit =
PhoneUtils.startGetCallerInfo(getContext(), conn, this, null);
int presentation = PhoneConstants.PRESENTATION_ALLOWED;
if (conn != null) presentation = conn.getNumberPresentation();
if (DBG) log("- onQueryComplete: presentation=" + presentation
+ ", contactExists=" + ci.contactExists);
// Depending on whether there was a contact match or not, we want to pass in different
// CallerInfo (for CNAP). Therefore if ci.contactExists then use the ci passed in.
// Otherwise, regenerate the CIT from the Connection and use the CallerInfo from there.
if (ci.contactExists) {
updateDisplayForPerson(ci, PhoneConstants.PRESENTATION_ALLOWED, false, call, conn);
} else {
updateDisplayForPerson(cit.currentInfo, presentation, false, call, conn);
}
updatePhotoForCallState(call);
} else if (cookie instanceof TextView){
if (DBG) log("callerinfo query complete, updating ui from ongoing or onhold");
((TextView) cookie).setText(PhoneUtils.getCompactNameFromCallerInfo(ci, mContext));
}
}
/**
* Implemented for ContactsAsyncHelper.OnImageLoadCompleteListener interface.
* make sure that the call state is reflected after the image is loaded.
*/
@Override
public void onImageLoadComplete(int token, Drawable photo, Bitmap photoIcon, Object cookie) {
mHandler.removeMessages(MESSAGE_SHOW_UNKNOWN_PHOTO);
if (mLoadingPersonUri != null) {
// Start sending view notification after the current request being done.
// New image may possibly be available from the next phone calls.
//
// TODO: may be nice to update the image view again once the newer one
// is available on contacts database.
PhoneUtils.sendViewNotificationAsync(mApplication, mLoadingPersonUri);
} else {
// This should not happen while we need some verbose info if it happens..
Log.w(LOG_TAG, "Person Uri isn't available while Image is successfully loaded.");
}
mLoadingPersonUri = null;
AsyncLoadCookie asyncLoadCookie = (AsyncLoadCookie) cookie;
CallerInfo callerInfo = asyncLoadCookie.callerInfo;
ImageView imageView = asyncLoadCookie.imageView;
Call call = asyncLoadCookie.call;
callerInfo.cachedPhoto = photo;
callerInfo.cachedPhotoIcon = photoIcon;
callerInfo.isCachedPhotoCurrent = true;
// Note: previously ContactsAsyncHelper has done this job.
// TODO: We will need fade-in animation. See issue 5236130.
if (photo != null) {
showImage(imageView, photo);
} else if (photoIcon != null) {
showImage(imageView, photoIcon);
} else {
showImage(imageView, R.drawable.picture_unknown);
}
if (token == TOKEN_UPDATE_PHOTO_FOR_CALL_STATE) {
updatePhotoForCallState(call);
}
}
/**
* Updates the "call state label" and the elapsed time widget based on the
* current state of the call.
*/
private void updateCallStateWidgets(Call call) {
if (DBG) log("updateCallStateWidgets(call " + call + ")...");
final Call.State state = call.getState();
final Context context = getContext();
final Phone phone = call.getPhone();
final int phoneType = phone.getPhoneType();
String callStateLabel = null; // Label to display as part of the call banner
int bluetoothIconId = 0; // Icon to display alongside the call state label
switch (state) {
case IDLE:
// "Call state" is meaningless in this state.
break;
case ACTIVE:
// We normally don't show a "call state label" at all in
// this state (but see below for some special cases).
break;
case HOLDING:
callStateLabel = context.getString(R.string.card_title_on_hold);
break;
case DIALING:
case ALERTING:
callStateLabel = context.getString(R.string.card_title_dialing);
break;
case INCOMING:
case WAITING:
callStateLabel = context.getString(R.string.card_title_incoming_call);
// Also, display a special icon (alongside the "Incoming call"
// label) if there's an incoming call and audio will be routed
// to bluetooth when you answer it.
if (mApplication.showBluetoothIndication()) {
bluetoothIconId = R.drawable.ic_incoming_call_bluetooth;
}
break;
case DISCONNECTING:
// While in the DISCONNECTING state we display a "Hanging up"
// message in order to make the UI feel more responsive. (In
// GSM it's normal to see a delay of a couple of seconds while
// negotiating the disconnect with the network, so the "Hanging
// up" state at least lets the user know that we're doing
// something. This state is currently not used with CDMA.)
callStateLabel = context.getString(R.string.card_title_hanging_up);
break;
case DISCONNECTED:
callStateLabel = getCallFailedString(call);
break;
default:
Log.wtf(LOG_TAG, "updateCallStateWidgets: unexpected call state: " + state);
break;
}
// Check a couple of other special cases (these are all CDMA-specific).
if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
if ((state == Call.State.ACTIVE)
&& mApplication.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()) {
// Display "Dialing" while dialing a 3Way call, even
// though the foreground call state is actually ACTIVE.
callStateLabel = context.getString(R.string.card_title_dialing);
} else if (PhoneGlobals.getInstance().notifier.getIsCdmaRedialCall()) {
callStateLabel = context.getString(R.string.card_title_redialing);
}
}
if (PhoneUtils.isPhoneInEcm(phone)) {
// In emergency callback mode (ECM), use a special label
// that shows your own phone number.
callStateLabel = getECMCardTitle(context, phone);
}
final InCallUiState inCallUiState = mApplication.inCallUiState;
if (DBG) {
log("==> callStateLabel: '" + callStateLabel
+ "', bluetoothIconId = " + bluetoothIconId
+ ", providerInfoVisible = " + inCallUiState.providerInfoVisible);
}
// Animation will be done by mCallerDetail's LayoutTransition, but in some cases, we don't
// want that.
// - DIALING: This is at the beginning of the phone call.
// - DISCONNECTING, DISCONNECTED: Screen will disappear soon; we have no time for animation.
final boolean skipAnimation = (state == Call.State.DIALING
|| state == Call.State.DISCONNECTING
|| state == Call.State.DISCONNECTED);
LayoutTransition layoutTransition = null;
if (skipAnimation) {
// Evict LayoutTransition object to skip animation.
layoutTransition = mSecondaryInfoContainer.getLayoutTransition();
mSecondaryInfoContainer.setLayoutTransition(null);
}
if (inCallUiState.providerInfoVisible) {
mProviderInfo.setVisibility(View.VISIBLE);
mProviderLabel.setText(context.getString(R.string.calling_via_template,
inCallUiState.providerLabel));
mProviderAddress.setText(inCallUiState.providerAddress);
mInCallScreen.requestRemoveProviderInfoWithDelay();
} else {
mProviderInfo.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(callStateLabel)) {
mCallStateLabel.setVisibility(View.VISIBLE);
mCallStateLabel.setText(callStateLabel);
// ...and display the icon too if necessary.
if (bluetoothIconId != 0) {
mCallStateLabel.setCompoundDrawablesWithIntrinsicBounds(bluetoothIconId, 0, 0, 0);
mCallStateLabel.setCompoundDrawablePadding((int) (mDensity * 5));
} else {
// Clear out any icons
mCallStateLabel.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
} else {
mCallStateLabel.setVisibility(View.GONE);
// Gravity is aligned left when receiving an incoming call in landscape.
// In that rare case, the gravity needs to be reset to the right.
// Also, setText("") is used since there is a delay in making the view GONE,
// so the user will otherwise see the text jump to the right side before disappearing.
if(mCallStateLabel.getGravity() != Gravity.RIGHT) {
mCallStateLabel.setText("");
mCallStateLabel.setGravity(Gravity.RIGHT);
}
}
if (skipAnimation) {
// Restore LayoutTransition object to recover animation.
mSecondaryInfoContainer.setLayoutTransition(layoutTransition);
}
// ...and update the elapsed time widget too.
switch (state) {
case ACTIVE:
case DISCONNECTING:
// Show the time with fade-in animation.
AnimationUtils.Fade.show(mElapsedTime);
updateElapsedTimeWidget(call);
break;
case DISCONNECTED:
// In the "Call ended" state, leave the mElapsedTime widget
// visible, but don't touch it (so we continue to see the
// elapsed time of the call that just ended.)
// Check visibility to keep possible fade-in animation.
if (mElapsedTime.getVisibility() != View.VISIBLE) {
mElapsedTime.setVisibility(View.VISIBLE);
}
break;
default:
// Call state here is IDLE, ACTIVE, HOLDING, DIALING, ALERTING,
// INCOMING, or WAITING.
// In all of these states, the "elapsed time" is meaningless, so
// don't show it.
AnimationUtils.Fade.hide(mElapsedTime, View.INVISIBLE);
// Additionally, in call states that can only occur at the start
// of a call, reset the elapsed time to be sure we won't display
// stale info later (like if we somehow go straight from DIALING
// or ALERTING to DISCONNECTED, which can actually happen in
// some failure cases like "line busy").
if ((state == Call.State.DIALING) || (state == Call.State.ALERTING)) {
updateElapsedTimeWidget(0);
}
break;
}
}
/**
* Updates mElapsedTime based on the given {@link Call} object's information.
*
* @see CallTime#getCallDuration(Call)
* @see Connection#getDurationMillis()
*/
/* package */ void updateElapsedTimeWidget(Call call) {
long duration = CallTime.getCallDuration(call); // msec
updateElapsedTimeWidget(duration / 1000);
// Also see onTickForCallTimeElapsed(), which updates this
// widget once per second while the call is active.
}
/**
* Updates mElapsedTime based on the specified number of seconds.
*/
private void updateElapsedTimeWidget(long timeElapsed) {
// if (DBG) log("updateElapsedTimeWidget: " + timeElapsed);
mElapsedTime.setText(DateUtils.formatElapsedTime(timeElapsed));
}
/**
* Updates the "on hold" box in the "other call" info area
* (ie. the stuff in the secondaryCallInfo block)
* based on the specified Call.
* Or, clear out the "on hold" box if the specified call
* is null or idle.
*/
private void displaySecondaryCallStatus(CallManager cm, Call call) {
if (DBG) log("displayOnHoldCallStatus(call =" + call + ")...");
if ((call == null) || (PhoneGlobals.getInstance().isOtaCallInActiveState())) {
mSecondaryCallInfo.setVisibility(View.GONE);
return;
}
Call.State state = call.getState();
switch (state) {
case HOLDING:
// Ok, there actually is a background call on hold.
// Display the "on hold" box.
// Note this case occurs only on GSM devices. (On CDMA,
// the "call on hold" is actually the 2nd connection of
// that ACTIVE call; see the ACTIVE case below.)
showSecondaryCallInfo();
if (PhoneUtils.isConferenceCall(call)) {
if (DBG) log("==> conference call.");
mSecondaryCallName.setText(getContext().getString(R.string.confCall));
showImage(mSecondaryCallPhoto, R.drawable.picture_conference);
} else {
// perform query and update the name temporarily
// make sure we hand the textview we want updated to the
// callback function.
if (DBG) log("==> NOT a conf call; call startGetCallerInfo...");
PhoneUtils.CallerInfoToken infoToken = PhoneUtils.startGetCallerInfo(
getContext(), call, this, mSecondaryCallName);
mSecondaryCallName.setText(
PhoneUtils.getCompactNameFromCallerInfo(infoToken.currentInfo,
getContext()));
// Also pull the photo out of the current CallerInfo.
// (Note we assume we already have a valid photo at
// this point, since *presumably* the caller-id query
// was already run at some point *before* this call
// got put on hold. If there's no cached photo, just
// fall back to the default "unknown" image.)
if (infoToken.isFinal) {
showCachedImage(mSecondaryCallPhoto, infoToken.currentInfo);
} else {
showImage(mSecondaryCallPhoto, R.drawable.picture_unknown);
}
}
AnimationUtils.Fade.show(mSecondaryCallPhotoDimEffect);
break;
case ACTIVE:
// CDMA: This is because in CDMA when the user originates the second call,
// although the Foreground call state is still ACTIVE in reality the network
// put the first call on hold.
if (mApplication.phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
showSecondaryCallInfo();
List<Connection> connections = call.getConnections();
if (connections.size() > 2) {
// This means that current Mobile Originated call is the not the first 3-Way
// call the user is making, which in turn tells the PhoneGlobals that we no
// longer know which previous caller/party had dropped out before the user
// made this call.
mSecondaryCallName.setText(
getContext().getString(R.string.card_title_in_call));
showImage(mSecondaryCallPhoto, R.drawable.picture_unknown);
} else {
// This means that the current Mobile Originated call IS the first 3-Way
// and hence we display the first callers/party's info here.
Connection conn = call.getEarliestConnection();
PhoneUtils.CallerInfoToken infoToken = PhoneUtils.startGetCallerInfo(
getContext(), conn, this, mSecondaryCallName);
// Get the compactName to be displayed, but then check that against
// the number presentation value for the call. If it's not an allowed
// presentation, then display the appropriate presentation string instead.
CallerInfo info = infoToken.currentInfo;
String name = PhoneUtils.getCompactNameFromCallerInfo(info, getContext());
boolean forceGenericPhoto = false;
if (info != null && info.numberPresentation !=
PhoneConstants.PRESENTATION_ALLOWED) {
name = PhoneUtils.getPresentationString(
getContext(), info.numberPresentation);
forceGenericPhoto = true;
}
mSecondaryCallName.setText(name);
// Also pull the photo out of the current CallerInfo.
// (Note we assume we already have a valid photo at
// this point, since *presumably* the caller-id query
// was already run at some point *before* this call
// got put on hold. If there's no cached photo, just
// fall back to the default "unknown" image.)
if (!forceGenericPhoto && infoToken.isFinal) {
showCachedImage(mSecondaryCallPhoto, info);
} else {
showImage(mSecondaryCallPhoto, R.drawable.picture_unknown);
}
}
} else {
// We shouldn't ever get here at all for non-CDMA devices.
Log.w(LOG_TAG, "displayOnHoldCallStatus: ACTIVE state on non-CDMA device");
mSecondaryCallInfo.setVisibility(View.GONE);
}
AnimationUtils.Fade.hide(mSecondaryCallPhotoDimEffect, View.GONE);
break;
default:
// There's actually no call on hold. (Presumably this call's
// state is IDLE, since any other state is meaningless for the
// background call.)
mSecondaryCallInfo.setVisibility(View.GONE);
break;
}
}
private void showSecondaryCallInfo() {
// This will call ViewStub#inflate() when needed.
mSecondaryCallInfo.setVisibility(View.VISIBLE);
if (mSecondaryCallName == null) {
mSecondaryCallName = (TextView) findViewById(R.id.secondaryCallName);
}
if (mSecondaryCallPhoto == null) {
mSecondaryCallPhoto = (ImageView) findViewById(R.id.secondaryCallPhoto);
}
if (mSecondaryCallPhotoDimEffect == null) {
mSecondaryCallPhotoDimEffect = findViewById(R.id.dim_effect_for_secondary_photo);
mSecondaryCallPhotoDimEffect.setOnClickListener(mInCallScreen);
// Add a custom OnTouchListener to manually shrink the "hit target".
mSecondaryCallPhotoDimEffect.setOnTouchListener(new SmallerHitTargetTouchListener());
}
mInCallScreen.updateButtonStateOutsideInCallTouchUi();
}
/**
* Method which is expected to be called from
* {@link InCallScreen#updateButtonStateOutsideInCallTouchUi()}.
*/
/* package */ void setSecondaryCallClickable(boolean clickable) {
if (mSecondaryCallPhotoDimEffect != null) {
mSecondaryCallPhotoDimEffect.setEnabled(clickable);
}
}
private String getCallFailedString(Call call) {
Connection c = call.getEarliestConnection();
int resID;
if (c == null) {
if (DBG) log("getCallFailedString: connection is null, using default values.");
// if this connection is null, just assume that the
// default case occurs.
resID = R.string.card_title_call_ended;
} else {
Connection.DisconnectCause cause = c.getDisconnectCause();
// TODO: The card *title* should probably be "Call ended" in all
// cases, but if the DisconnectCause was an error condition we should
// probably also display the specific failure reason somewhere...
switch (cause) {
case BUSY:
resID = R.string.callFailed_userBusy;
break;
case CONGESTION:
resID = R.string.callFailed_congestion;
break;
case TIMED_OUT:
resID = R.string.callFailed_timedOut;
break;
case SERVER_UNREACHABLE:
resID = R.string.callFailed_server_unreachable;
break;
case NUMBER_UNREACHABLE:
resID = R.string.callFailed_number_unreachable;
break;
case INVALID_CREDENTIALS:
resID = R.string.callFailed_invalid_credentials;
break;
case SERVER_ERROR:
resID = R.string.callFailed_server_error;
break;
case OUT_OF_NETWORK:
resID = R.string.callFailed_out_of_network;
break;
case LOST_SIGNAL:
case CDMA_DROP:
resID = R.string.callFailed_noSignal;
break;
case LIMIT_EXCEEDED:
resID = R.string.callFailed_limitExceeded;
break;
case POWER_OFF:
resID = R.string.callFailed_powerOff;
break;
case ICC_ERROR:
resID = R.string.callFailed_simError;
break;
case OUT_OF_SERVICE:
resID = R.string.callFailed_outOfService;
break;
case INVALID_NUMBER:
case UNOBTAINABLE_NUMBER:
resID = R.string.callFailed_unobtainable_number;
break;
default:
resID = R.string.card_title_call_ended;
break;
}
}
return getContext().getString(resID);
}
/**
* Updates the name / photo / number / label fields on the CallCard
* based on the specified CallerInfo.
*
* If the current call is a conference call, use
* updateDisplayForConference() instead.
*/
private void updateDisplayForPerson(CallerInfo info,
int presentation,
boolean isTemporary,
Call call,
Connection conn) {
if (DBG) log("updateDisplayForPerson(" + info + ")\npresentation:" +
presentation + " isTemporary:" + isTemporary);
// inform the state machine that we are displaying a photo.
mPhotoTracker.setPhotoRequest(info);
mPhotoTracker.setPhotoState(ContactsAsyncHelper.ImageTracker.DISPLAY_IMAGE);
// The actual strings we're going to display onscreen:
boolean displayNameIsNumber = false;
String displayName;
String displayNumber = null;
String label = null;
Uri personUri = null;
// String socialStatusText = null;
// Drawable socialStatusBadge = null;
if (info != null) {
// It appears that there is a small change in behaviour with the
// PhoneUtils' startGetCallerInfo whereby if we query with an
// empty number, we will get a valid CallerInfo object, but with
// fields that are all null, and the isTemporary boolean input
// parameter as true.
// In the past, we would see a NULL callerinfo object, but this
// ends up causing null pointer exceptions elsewhere down the
// line in other cases, so we need to make this fix instead. It
// appears that this was the ONLY call to PhoneUtils
// .getCallerInfo() that relied on a NULL CallerInfo to indicate
// an unknown contact.
// Currently, info.phoneNumber may actually be a SIP address, and
// if so, it might sometimes include the "sip:" prefix. That
// prefix isn't really useful to the user, though, so strip it off
// if present. (For any other URI scheme, though, leave the
// prefix alone.)
// TODO: It would be cleaner for CallerInfo to explicitly support
// SIP addresses instead of overloading the "phoneNumber" field.
// Then we could remove this hack, and instead ask the CallerInfo
// for a "user visible" form of the SIP address.
String number = info.phoneNumber;
if ((number != null) && number.startsWith("sip:")) {
number = number.substring(4);
}
if (TextUtils.isEmpty(info.name)) {
// No valid "name" in the CallerInfo, so fall back to
// something else.
// (Typically, we promote the phone number up to the "name" slot
// onscreen, and possibly display a descriptive string in the
// "number" slot.)
if (TextUtils.isEmpty(number)) {
// No name *or* number! Display a generic "unknown" string
// (or potentially some other default based on the presentation.)
displayName = PhoneUtils.getPresentationString(getContext(), presentation);
if (DBG) log(" ==> no name *or* number! displayName = " + displayName);
} else if (presentation != PhoneConstants.PRESENTATION_ALLOWED) {
// This case should never happen since the network should never send a phone #
// AND a restricted presentation. However we leave it here in case of weird
// network behavior
displayName = PhoneUtils.getPresentationString(getContext(), presentation);
if (DBG) log(" ==> presentation not allowed! displayName = " + displayName);
} else if (!TextUtils.isEmpty(info.cnapName)) {
// No name, but we do have a valid CNAP name, so use that.
displayName = info.cnapName;
info.name = info.cnapName;
displayNumber = number;
if (DBG) log(" ==> cnapName available: displayName '"
+ displayName + "', displayNumber '" + displayNumber + "'");
} else {
// No name; all we have is a number. This is the typical
// case when an incoming call doesn't match any contact,
// or if you manually dial an outgoing number using the
// dialpad.
// Promote the phone number up to the "name" slot:
displayName = number;
displayNameIsNumber = true;
// ...and use the "number" slot for a geographical description
// string if available (but only for incoming calls.)
if ((conn != null) && (conn.isIncoming())) {
// TODO (CallerInfoAsyncQuery cleanup): Fix the CallerInfo
// query to only do the geoDescription lookup in the first
// place for incoming calls.
displayNumber = info.geoDescription; // may be null
}
if (DBG) log(" ==> no name; falling back to number: displayName '"
+ displayName + "', displayNumber '" + displayNumber + "'");
}
} else {
// We do have a valid "name" in the CallerInfo. Display that
// in the "name" slot, and the phone number in the "number" slot.
if (presentation != PhoneConstants.PRESENTATION_ALLOWED) {
// This case should never happen since the network should never send a name
// AND a restricted presentation. However we leave it here in case of weird
// network behavior
displayName = PhoneUtils.getPresentationString(getContext(), presentation);
if (DBG) log(" ==> valid name, but presentation not allowed!"
+ " displayName = " + displayName);
} else {
displayName = info.name;
displayNumber = number;
label = info.phoneLabel;
if (DBG) log(" ==> name is present in CallerInfo: displayName '"
+ displayName + "', displayNumber '" + displayNumber + "'");
}
}
personUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, info.person_id);
if (DBG) log("- got personUri: '" + personUri
+ "', based on info.person_id: " + info.person_id);
} else {
displayName = PhoneUtils.getPresentationString(getContext(), presentation);
}
+ // TODO: Revisit/cleanup following code when underlying telephony issue
+ // is fixed (b/7705977).
+ //
+ // Following logic was added to prevent screen flicker caused by receiving
+ // a momentary disconnect with only a stripped phone number (the phone
+ // would quickly flip between full caller info, stripped phone number, and
+ // back to full caller info). Note this only prevents the name/number/label
+ // fields from flickering--the phone state field will still briefly flicker.
boolean updateNameAndNumber = true;
// If the new info is just a phone number, check to make sure it's not less
// information than what's already being displayed.
if (displayNameIsNumber) {
// If the new number is the same as the number already displayed, ignore it
// because that means we're also already displaying a name for it.
// If the new number is the same as the name currently being displayed, only
// display if the new number is longer (ie, has formatting).
String visiblePhoneNumber = null;
if (mPhoneNumber.getVisibility() == View.VISIBLE) {
visiblePhoneNumber = mPhoneNumber.getText().toString();
}
if ((visiblePhoneNumber != null &&
PhoneNumberUtils.compare(visiblePhoneNumber, displayName)) ||
(PhoneNumberUtils.compare(mName.getText().toString(), displayName) &&
displayName.length() < mName.length())) {
if (DBG) log("chose not to update display {" + mName.getText() + ", "
+ visiblePhoneNumber + "} with number " + displayName);
updateNameAndNumber = false;
}
}
if (updateNameAndNumber) {
if (call.isGeneric()) {
mName.setText(R.string.card_title_in_call);
} else {
mName.setText(displayName);
}
mName.setVisibility(View.VISIBLE);
- if (displayNumber != null && !call.isGeneric()) {
+ if (!TextUtils.isEmpty(displayNumber) && !call.isGeneric()) {
mPhoneNumber.setText(displayNumber);
mPhoneNumber.setVisibility(View.VISIBLE);
} else {
mPhoneNumber.setVisibility(View.GONE);
}
- if (label != null && !call.isGeneric()) {
+ if (!TextUtils.isEmpty(label) && !call.isGeneric()) {
mLabel.setText(label);
mLabel.setVisibility(View.VISIBLE);
} else {
mLabel.setVisibility(View.GONE);
}
}
// Update mPhoto
// if the temporary flag is set, we know we'll be getting another call after
// the CallerInfo has been correctly updated. So, we can skip the image
// loading until then.
// If the photoResource is filled in for the CallerInfo, (like with the
// Emergency Number case), then we can just set the photo image without
// requesting for an image load. Please refer to CallerInfoAsyncQuery.java
// for cases where CallerInfo.photoResource may be set. We can also avoid
// the image load step if the image data is cached.
if (isTemporary && (info == null || !info.isCachedPhotoCurrent)) {
mPhoto.setTag(null);
mPhoto.setVisibility(View.INVISIBLE);
} else if (info != null && info.photoResource != 0){
showImage(mPhoto, info.photoResource);
} else if (!showCachedImage(mPhoto, info)) {
if (personUri == null) {
Log.w(LOG_TAG, "personPri is null. Just use Unknown picture.");
showImage(mPhoto, R.drawable.picture_unknown);
} else if (personUri.equals(mLoadingPersonUri)) {
if (DBG) {
log("The requested Uri (" + personUri + ") is being loaded already."
+ " Ignoret the duplicate load request.");
}
} else {
// Remember which person's photo is being loaded right now so that we won't issue
// unnecessary load request multiple times, which will mess up animation around
// the contact photo.
mLoadingPersonUri = personUri;
// Forget the drawable previously used.
mPhoto.setTag(null);
// Show empty screen for a moment.
mPhoto.setVisibility(View.INVISIBLE);
// Load the image with a callback to update the image state.
// When the load is finished, onImageLoadComplete() will be called.
ContactsAsyncHelper.startObtainPhotoAsync(TOKEN_UPDATE_PHOTO_FOR_CALL_STATE,
getContext(), personUri, this, new AsyncLoadCookie(mPhoto, info, call));
// If the image load is too slow, we show a default avatar icon afterward.
// If it is fast enough, this message will be canceled on onImageLoadComplete().
mHandler.removeMessages(MESSAGE_SHOW_UNKNOWN_PHOTO);
mHandler.sendEmptyMessageDelayed(MESSAGE_SHOW_UNKNOWN_PHOTO, MESSAGE_DELAY);
}
}
// If the phone call is on hold, show it with darker status.
// Right now we achieve it by overlaying opaque View.
// Note: See also layout file about why so and what is the other possibilities.
if (call.getState() == Call.State.HOLDING) {
AnimationUtils.Fade.show(mPhotoDimEffect);
} else {
AnimationUtils.Fade.hide(mPhotoDimEffect, View.GONE);
}
// Other text fields:
updateCallTypeLabel(call);
// updateSocialStatus(socialStatusText, socialStatusBadge, call); // Currently unused
}
/**
* Updates the name / photo / number / label fields
* for the special "conference call" state.
*
* If the current call has only a single connection, use
* updateDisplayForPerson() instead.
*/
private void updateDisplayForConference(Call call) {
if (DBG) log("updateDisplayForConference()...");
int phoneType = call.getPhone().getPhoneType();
if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
// This state corresponds to both 3-Way merged call and
// Call Waiting accepted call.
// In this case we display the UI in a "generic" state, with
// the generic "dialing" icon and no caller information,
// because in this state in CDMA the user does not really know
// which caller party he is talking to.
showImage(mPhoto, R.drawable.picture_dialing);
mName.setText(R.string.card_title_in_call);
} else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
|| (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
// Normal GSM (or possibly SIP?) conference call.
// Display the "conference call" image as the contact photo.
// TODO: Better visual treatment for contact photos in a
// conference call (see bug 1313252).
showImage(mPhoto, R.drawable.picture_conference);
mName.setText(R.string.card_title_conf_call);
} else {
throw new IllegalStateException("Unexpected phone type: " + phoneType);
}
mName.setVisibility(View.VISIBLE);
// TODO: For a conference call, the "phone number" slot is specced
// to contain a summary of who's on the call, like "Bill Foldes
// and Hazel Nutt" or "Bill Foldes and 2 others".
// But for now, just hide it:
mPhoneNumber.setVisibility(View.GONE);
mLabel.setVisibility(View.GONE);
// Other text fields:
updateCallTypeLabel(call);
// updateSocialStatus(null, null, null); // socialStatus is never visible in this state
// TODO: for a GSM conference call, since we do actually know who
// you're talking to, consider also showing names / numbers /
// photos of some of the people on the conference here, so you can
// see that info without having to click "Manage conference". We
// probably have enough space to show info for 2 people, at least.
//
// To do this, our caller would pass us the activeConnections
// list, and we'd call PhoneUtils.getCallerInfo() separately for
// each connection.
}
/**
* Updates the CallCard "photo" IFF the specified Call is in a state
* that needs a special photo (like "busy" or "dialing".)
*
* If the current call does not require a special image in the "photo"
* slot onscreen, don't do anything, since presumably the photo image
* has already been set (to the photo of the person we're talking, or
* the generic "picture_unknown" image, or the "conference call"
* image.)
*/
private void updatePhotoForCallState(Call call) {
if (DBG) log("updatePhotoForCallState(" + call + ")...");
int photoImageResource = 0;
// Check for the (relatively few) telephony states that need a
// special image in the "photo" slot.
Call.State state = call.getState();
switch (state) {
case DISCONNECTED:
// Display the special "busy" photo for BUSY or CONGESTION.
// Otherwise (presumably the normal "call ended" state)
// leave the photo alone.
Connection c = call.getEarliestConnection();
// if the connection is null, we assume the default case,
// otherwise update the image resource normally.
if (c != null) {
Connection.DisconnectCause cause = c.getDisconnectCause();
if ((cause == Connection.DisconnectCause.BUSY)
|| (cause == Connection.DisconnectCause.CONGESTION)) {
photoImageResource = R.drawable.picture_busy;
}
} else if (DBG) {
log("updatePhotoForCallState: connection is null, ignoring.");
}
// TODO: add special images for any other DisconnectCauses?
break;
case ALERTING:
case DIALING:
default:
// Leave the photo alone in all other states.
// If this call is an individual call, and the image is currently
// displaying a state, (rather than a photo), we'll need to update
// the image.
// This is for the case where we've been displaying the state and
// now we need to restore the photo. This can happen because we
// only query the CallerInfo once, and limit the number of times
// the image is loaded. (So a state image may overwrite the photo
// and we would otherwise have no way of displaying the photo when
// the state goes away.)
// if the photoResource field is filled-in in the Connection's
// caller info, then we can just use that instead of requesting
// for a photo load.
// look for the photoResource if it is available.
CallerInfo ci = null;
{
Connection conn = null;
int phoneType = call.getPhone().getPhoneType();
if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
conn = call.getLatestConnection();
} else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
|| (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
conn = call.getEarliestConnection();
} else {
throw new IllegalStateException("Unexpected phone type: " + phoneType);
}
if (conn != null) {
Object o = conn.getUserData();
if (o instanceof CallerInfo) {
ci = (CallerInfo) o;
} else if (o instanceof PhoneUtils.CallerInfoToken) {
ci = ((PhoneUtils.CallerInfoToken) o).currentInfo;
}
}
}
if (ci != null) {
photoImageResource = ci.photoResource;
}
// If no photoResource found, check to see if this is a conference call. If
// it is not a conference call:
// 1. Try to show the cached image
// 2. If the image is not cached, check to see if a load request has been
// made already.
// 3. If the load request has not been made [DISPLAY_DEFAULT], start the
// request and note that it has started by updating photo state with
// [DISPLAY_IMAGE].
if (photoImageResource == 0) {
if (!PhoneUtils.isConferenceCall(call)) {
if (!showCachedImage(mPhoto, ci) && (mPhotoTracker.getPhotoState() ==
ContactsAsyncHelper.ImageTracker.DISPLAY_DEFAULT)) {
Uri photoUri = mPhotoTracker.getPhotoUri();
if (photoUri == null) {
Log.w(LOG_TAG, "photoUri became null. Show default avatar icon");
showImage(mPhoto, R.drawable.picture_unknown);
} else {
if (DBG) {
log("start asynchronous load inside updatePhotoForCallState()");
}
mPhoto.setTag(null);
// Make it invisible for a moment
mPhoto.setVisibility(View.INVISIBLE);
ContactsAsyncHelper.startObtainPhotoAsync(TOKEN_DO_NOTHING,
getContext(), photoUri, this,
new AsyncLoadCookie(mPhoto, ci, null));
}
mPhotoTracker.setPhotoState(
ContactsAsyncHelper.ImageTracker.DISPLAY_IMAGE);
}
}
} else {
showImage(mPhoto, photoImageResource);
mPhotoTracker.setPhotoState(ContactsAsyncHelper.ImageTracker.DISPLAY_IMAGE);
return;
}
break;
}
if (photoImageResource != 0) {
if (DBG) log("- overrriding photo image: " + photoImageResource);
showImage(mPhoto, photoImageResource);
// Track the image state.
mPhotoTracker.setPhotoState(ContactsAsyncHelper.ImageTracker.DISPLAY_DEFAULT);
}
}
/**
* Try to display the cached image from the callerinfo object.
*
* @return true if we were able to find the image in the cache, false otherwise.
*/
private static final boolean showCachedImage(ImageView view, CallerInfo ci) {
if ((ci != null) && ci.isCachedPhotoCurrent) {
if (ci.cachedPhoto != null) {
showImage(view, ci.cachedPhoto);
} else {
showImage(view, R.drawable.picture_unknown);
}
return true;
}
return false;
}
/** Helper function to display the resource in the imageview AND ensure its visibility.*/
private static final void showImage(ImageView view, int resource) {
showImage(view, view.getContext().getResources().getDrawable(resource));
}
private static final void showImage(ImageView view, Bitmap bitmap) {
showImage(view, new BitmapDrawable(view.getContext().getResources(), bitmap));
}
/** Helper function to display the drawable in the imageview AND ensure its visibility.*/
private static final void showImage(ImageView view, Drawable drawable) {
Resources res = view.getContext().getResources();
Drawable current = (Drawable) view.getTag();
if (current == null) {
if (DBG) log("Start fade-in animation for " + view);
view.setImageDrawable(drawable);
AnimationUtils.Fade.show(view);
view.setTag(drawable);
} else {
AnimationUtils.startCrossFade(view, current, drawable);
view.setVisibility(View.VISIBLE);
}
}
/**
* Returns the special card title used in emergency callback mode (ECM),
* which shows your own phone number.
*/
private String getECMCardTitle(Context context, Phone phone) {
String rawNumber = phone.getLine1Number(); // may be null or empty
String formattedNumber;
if (!TextUtils.isEmpty(rawNumber)) {
formattedNumber = PhoneNumberUtils.formatNumber(rawNumber);
} else {
formattedNumber = context.getString(R.string.unknown);
}
String titleFormat = context.getString(R.string.card_title_my_phone_number);
return String.format(titleFormat, formattedNumber);
}
/**
* Updates the "Call type" label, based on the current foreground call.
* This is a special label and/or branding we display for certain
* kinds of calls.
*
* (So far, this is used only for SIP calls, which get an
* "Internet call" label. TODO: But eventually, the telephony
* layer might allow each pluggable "provider" to specify a string
* and/or icon to be displayed here.)
*/
private void updateCallTypeLabel(Call call) {
int phoneType = (call != null) ? call.getPhone().getPhoneType() :
PhoneConstants.PHONE_TYPE_NONE;
if (phoneType == PhoneConstants.PHONE_TYPE_SIP) {
mCallTypeLabel.setVisibility(View.VISIBLE);
mCallTypeLabel.setText(R.string.incall_call_type_label_sip);
mCallTypeLabel.setTextColor(mTextColorCallTypeSip);
// If desired, we could also display a "badge" next to the label, as follows:
// mCallTypeLabel.setCompoundDrawablesWithIntrinsicBounds(
// callTypeSpecificBadge, null, null, null);
// mCallTypeLabel.setCompoundDrawablePadding((int) (mDensity * 6));
} else {
mCallTypeLabel.setVisibility(View.GONE);
}
}
/**
* Updates the "social status" label with the specified text and
* (optional) badge.
*/
/*private void updateSocialStatus(String socialStatusText,
Drawable socialStatusBadge,
Call call) {
// The socialStatus field is *only* visible while an incoming call
// is ringing, never in any other call state.
if ((socialStatusText != null)
&& (call != null)
&& call.isRinging()
&& !call.isGeneric()) {
mSocialStatus.setVisibility(View.VISIBLE);
mSocialStatus.setText(socialStatusText);
mSocialStatus.setCompoundDrawablesWithIntrinsicBounds(
socialStatusBadge, null, null, null);
mSocialStatus.setCompoundDrawablePadding((int) (mDensity * 6));
} else {
mSocialStatus.setVisibility(View.GONE);
}
}*/
/**
* Hides the top-level UI elements of the call card: The "main
* call card" element representing the current active or ringing call,
* and also the info areas for "ongoing" or "on hold" calls in some
* states.
*
* This is intended to be used in special states where the normal
* in-call UI is totally replaced by some other UI, like OTA mode on a
* CDMA device.
*
* To bring back the regular CallCard UI, just re-run the normal
* updateState() call sequence.
*/
public void hideCallCardElements() {
mPrimaryCallInfo.setVisibility(View.GONE);
mSecondaryCallInfo.setVisibility(View.GONE);
}
/*
* Updates the hint (like "Rotate to answer") that we display while
* the user is dragging the incoming call RotarySelector widget.
*/
/* package */ void setIncomingCallWidgetHint(int hintTextResId, int hintColorResId) {
mIncomingCallWidgetHintTextResId = hintTextResId;
mIncomingCallWidgetHintColorResId = hintColorResId;
}
// Accessibility event support.
// Since none of the CallCard elements are focusable, we need to manually
// fill in the AccessibilityEvent here (so that the name / number / etc will
// get pronounced by a screen reader, for example.)
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
dispatchPopulateAccessibilityEvent(event, mName);
dispatchPopulateAccessibilityEvent(event, mPhoneNumber);
return true;
}
dispatchPopulateAccessibilityEvent(event, mCallStateLabel);
dispatchPopulateAccessibilityEvent(event, mPhoto);
dispatchPopulateAccessibilityEvent(event, mName);
dispatchPopulateAccessibilityEvent(event, mPhoneNumber);
dispatchPopulateAccessibilityEvent(event, mLabel);
// dispatchPopulateAccessibilityEvent(event, mSocialStatus);
if (mSecondaryCallName != null) {
dispatchPopulateAccessibilityEvent(event, mSecondaryCallName);
}
if (mSecondaryCallPhoto != null) {
dispatchPopulateAccessibilityEvent(event, mSecondaryCallPhoto);
}
return true;
}
private void dispatchPopulateAccessibilityEvent(AccessibilityEvent event, View view) {
List<CharSequence> eventText = event.getText();
int size = eventText.size();
view.dispatchPopulateAccessibilityEvent(event);
// if no text added write null to keep relative position
if (size == eventText.size()) {
eventText.add(null);
}
}
// Debugging / testing code
private static void log(String msg) {
Log.d(LOG_TAG, msg);
}
}
| false | true |
private void updateDisplayForPerson(CallerInfo info,
int presentation,
boolean isTemporary,
Call call,
Connection conn) {
if (DBG) log("updateDisplayForPerson(" + info + ")\npresentation:" +
presentation + " isTemporary:" + isTemporary);
// inform the state machine that we are displaying a photo.
mPhotoTracker.setPhotoRequest(info);
mPhotoTracker.setPhotoState(ContactsAsyncHelper.ImageTracker.DISPLAY_IMAGE);
// The actual strings we're going to display onscreen:
boolean displayNameIsNumber = false;
String displayName;
String displayNumber = null;
String label = null;
Uri personUri = null;
// String socialStatusText = null;
// Drawable socialStatusBadge = null;
if (info != null) {
// It appears that there is a small change in behaviour with the
// PhoneUtils' startGetCallerInfo whereby if we query with an
// empty number, we will get a valid CallerInfo object, but with
// fields that are all null, and the isTemporary boolean input
// parameter as true.
// In the past, we would see a NULL callerinfo object, but this
// ends up causing null pointer exceptions elsewhere down the
// line in other cases, so we need to make this fix instead. It
// appears that this was the ONLY call to PhoneUtils
// .getCallerInfo() that relied on a NULL CallerInfo to indicate
// an unknown contact.
// Currently, info.phoneNumber may actually be a SIP address, and
// if so, it might sometimes include the "sip:" prefix. That
// prefix isn't really useful to the user, though, so strip it off
// if present. (For any other URI scheme, though, leave the
// prefix alone.)
// TODO: It would be cleaner for CallerInfo to explicitly support
// SIP addresses instead of overloading the "phoneNumber" field.
// Then we could remove this hack, and instead ask the CallerInfo
// for a "user visible" form of the SIP address.
String number = info.phoneNumber;
if ((number != null) && number.startsWith("sip:")) {
number = number.substring(4);
}
if (TextUtils.isEmpty(info.name)) {
// No valid "name" in the CallerInfo, so fall back to
// something else.
// (Typically, we promote the phone number up to the "name" slot
// onscreen, and possibly display a descriptive string in the
// "number" slot.)
if (TextUtils.isEmpty(number)) {
// No name *or* number! Display a generic "unknown" string
// (or potentially some other default based on the presentation.)
displayName = PhoneUtils.getPresentationString(getContext(), presentation);
if (DBG) log(" ==> no name *or* number! displayName = " + displayName);
} else if (presentation != PhoneConstants.PRESENTATION_ALLOWED) {
// This case should never happen since the network should never send a phone #
// AND a restricted presentation. However we leave it here in case of weird
// network behavior
displayName = PhoneUtils.getPresentationString(getContext(), presentation);
if (DBG) log(" ==> presentation not allowed! displayName = " + displayName);
} else if (!TextUtils.isEmpty(info.cnapName)) {
// No name, but we do have a valid CNAP name, so use that.
displayName = info.cnapName;
info.name = info.cnapName;
displayNumber = number;
if (DBG) log(" ==> cnapName available: displayName '"
+ displayName + "', displayNumber '" + displayNumber + "'");
} else {
// No name; all we have is a number. This is the typical
// case when an incoming call doesn't match any contact,
// or if you manually dial an outgoing number using the
// dialpad.
// Promote the phone number up to the "name" slot:
displayName = number;
displayNameIsNumber = true;
// ...and use the "number" slot for a geographical description
// string if available (but only for incoming calls.)
if ((conn != null) && (conn.isIncoming())) {
// TODO (CallerInfoAsyncQuery cleanup): Fix the CallerInfo
// query to only do the geoDescription lookup in the first
// place for incoming calls.
displayNumber = info.geoDescription; // may be null
}
if (DBG) log(" ==> no name; falling back to number: displayName '"
+ displayName + "', displayNumber '" + displayNumber + "'");
}
} else {
// We do have a valid "name" in the CallerInfo. Display that
// in the "name" slot, and the phone number in the "number" slot.
if (presentation != PhoneConstants.PRESENTATION_ALLOWED) {
// This case should never happen since the network should never send a name
// AND a restricted presentation. However we leave it here in case of weird
// network behavior
displayName = PhoneUtils.getPresentationString(getContext(), presentation);
if (DBG) log(" ==> valid name, but presentation not allowed!"
+ " displayName = " + displayName);
} else {
displayName = info.name;
displayNumber = number;
label = info.phoneLabel;
if (DBG) log(" ==> name is present in CallerInfo: displayName '"
+ displayName + "', displayNumber '" + displayNumber + "'");
}
}
personUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, info.person_id);
if (DBG) log("- got personUri: '" + personUri
+ "', based on info.person_id: " + info.person_id);
} else {
displayName = PhoneUtils.getPresentationString(getContext(), presentation);
}
boolean updateNameAndNumber = true;
// If the new info is just a phone number, check to make sure it's not less
// information than what's already being displayed.
if (displayNameIsNumber) {
// If the new number is the same as the number already displayed, ignore it
// because that means we're also already displaying a name for it.
// If the new number is the same as the name currently being displayed, only
// display if the new number is longer (ie, has formatting).
String visiblePhoneNumber = null;
if (mPhoneNumber.getVisibility() == View.VISIBLE) {
visiblePhoneNumber = mPhoneNumber.getText().toString();
}
if ((visiblePhoneNumber != null &&
PhoneNumberUtils.compare(visiblePhoneNumber, displayName)) ||
(PhoneNumberUtils.compare(mName.getText().toString(), displayName) &&
displayName.length() < mName.length())) {
if (DBG) log("chose not to update display {" + mName.getText() + ", "
+ visiblePhoneNumber + "} with number " + displayName);
updateNameAndNumber = false;
}
}
if (updateNameAndNumber) {
if (call.isGeneric()) {
mName.setText(R.string.card_title_in_call);
} else {
mName.setText(displayName);
}
mName.setVisibility(View.VISIBLE);
if (displayNumber != null && !call.isGeneric()) {
mPhoneNumber.setText(displayNumber);
mPhoneNumber.setVisibility(View.VISIBLE);
} else {
mPhoneNumber.setVisibility(View.GONE);
}
if (label != null && !call.isGeneric()) {
mLabel.setText(label);
mLabel.setVisibility(View.VISIBLE);
} else {
mLabel.setVisibility(View.GONE);
}
}
// Update mPhoto
// if the temporary flag is set, we know we'll be getting another call after
// the CallerInfo has been correctly updated. So, we can skip the image
// loading until then.
// If the photoResource is filled in for the CallerInfo, (like with the
// Emergency Number case), then we can just set the photo image without
// requesting for an image load. Please refer to CallerInfoAsyncQuery.java
// for cases where CallerInfo.photoResource may be set. We can also avoid
// the image load step if the image data is cached.
if (isTemporary && (info == null || !info.isCachedPhotoCurrent)) {
mPhoto.setTag(null);
mPhoto.setVisibility(View.INVISIBLE);
} else if (info != null && info.photoResource != 0){
showImage(mPhoto, info.photoResource);
} else if (!showCachedImage(mPhoto, info)) {
if (personUri == null) {
Log.w(LOG_TAG, "personPri is null. Just use Unknown picture.");
showImage(mPhoto, R.drawable.picture_unknown);
} else if (personUri.equals(mLoadingPersonUri)) {
if (DBG) {
log("The requested Uri (" + personUri + ") is being loaded already."
+ " Ignoret the duplicate load request.");
}
} else {
// Remember which person's photo is being loaded right now so that we won't issue
// unnecessary load request multiple times, which will mess up animation around
// the contact photo.
mLoadingPersonUri = personUri;
// Forget the drawable previously used.
mPhoto.setTag(null);
// Show empty screen for a moment.
mPhoto.setVisibility(View.INVISIBLE);
// Load the image with a callback to update the image state.
// When the load is finished, onImageLoadComplete() will be called.
ContactsAsyncHelper.startObtainPhotoAsync(TOKEN_UPDATE_PHOTO_FOR_CALL_STATE,
getContext(), personUri, this, new AsyncLoadCookie(mPhoto, info, call));
// If the image load is too slow, we show a default avatar icon afterward.
// If it is fast enough, this message will be canceled on onImageLoadComplete().
mHandler.removeMessages(MESSAGE_SHOW_UNKNOWN_PHOTO);
mHandler.sendEmptyMessageDelayed(MESSAGE_SHOW_UNKNOWN_PHOTO, MESSAGE_DELAY);
}
}
// If the phone call is on hold, show it with darker status.
// Right now we achieve it by overlaying opaque View.
// Note: See also layout file about why so and what is the other possibilities.
if (call.getState() == Call.State.HOLDING) {
AnimationUtils.Fade.show(mPhotoDimEffect);
} else {
AnimationUtils.Fade.hide(mPhotoDimEffect, View.GONE);
}
// Other text fields:
updateCallTypeLabel(call);
// updateSocialStatus(socialStatusText, socialStatusBadge, call); // Currently unused
}
|
private void updateDisplayForPerson(CallerInfo info,
int presentation,
boolean isTemporary,
Call call,
Connection conn) {
if (DBG) log("updateDisplayForPerson(" + info + ")\npresentation:" +
presentation + " isTemporary:" + isTemporary);
// inform the state machine that we are displaying a photo.
mPhotoTracker.setPhotoRequest(info);
mPhotoTracker.setPhotoState(ContactsAsyncHelper.ImageTracker.DISPLAY_IMAGE);
// The actual strings we're going to display onscreen:
boolean displayNameIsNumber = false;
String displayName;
String displayNumber = null;
String label = null;
Uri personUri = null;
// String socialStatusText = null;
// Drawable socialStatusBadge = null;
if (info != null) {
// It appears that there is a small change in behaviour with the
// PhoneUtils' startGetCallerInfo whereby if we query with an
// empty number, we will get a valid CallerInfo object, but with
// fields that are all null, and the isTemporary boolean input
// parameter as true.
// In the past, we would see a NULL callerinfo object, but this
// ends up causing null pointer exceptions elsewhere down the
// line in other cases, so we need to make this fix instead. It
// appears that this was the ONLY call to PhoneUtils
// .getCallerInfo() that relied on a NULL CallerInfo to indicate
// an unknown contact.
// Currently, info.phoneNumber may actually be a SIP address, and
// if so, it might sometimes include the "sip:" prefix. That
// prefix isn't really useful to the user, though, so strip it off
// if present. (For any other URI scheme, though, leave the
// prefix alone.)
// TODO: It would be cleaner for CallerInfo to explicitly support
// SIP addresses instead of overloading the "phoneNumber" field.
// Then we could remove this hack, and instead ask the CallerInfo
// for a "user visible" form of the SIP address.
String number = info.phoneNumber;
if ((number != null) && number.startsWith("sip:")) {
number = number.substring(4);
}
if (TextUtils.isEmpty(info.name)) {
// No valid "name" in the CallerInfo, so fall back to
// something else.
// (Typically, we promote the phone number up to the "name" slot
// onscreen, and possibly display a descriptive string in the
// "number" slot.)
if (TextUtils.isEmpty(number)) {
// No name *or* number! Display a generic "unknown" string
// (or potentially some other default based on the presentation.)
displayName = PhoneUtils.getPresentationString(getContext(), presentation);
if (DBG) log(" ==> no name *or* number! displayName = " + displayName);
} else if (presentation != PhoneConstants.PRESENTATION_ALLOWED) {
// This case should never happen since the network should never send a phone #
// AND a restricted presentation. However we leave it here in case of weird
// network behavior
displayName = PhoneUtils.getPresentationString(getContext(), presentation);
if (DBG) log(" ==> presentation not allowed! displayName = " + displayName);
} else if (!TextUtils.isEmpty(info.cnapName)) {
// No name, but we do have a valid CNAP name, so use that.
displayName = info.cnapName;
info.name = info.cnapName;
displayNumber = number;
if (DBG) log(" ==> cnapName available: displayName '"
+ displayName + "', displayNumber '" + displayNumber + "'");
} else {
// No name; all we have is a number. This is the typical
// case when an incoming call doesn't match any contact,
// or if you manually dial an outgoing number using the
// dialpad.
// Promote the phone number up to the "name" slot:
displayName = number;
displayNameIsNumber = true;
// ...and use the "number" slot for a geographical description
// string if available (but only for incoming calls.)
if ((conn != null) && (conn.isIncoming())) {
// TODO (CallerInfoAsyncQuery cleanup): Fix the CallerInfo
// query to only do the geoDescription lookup in the first
// place for incoming calls.
displayNumber = info.geoDescription; // may be null
}
if (DBG) log(" ==> no name; falling back to number: displayName '"
+ displayName + "', displayNumber '" + displayNumber + "'");
}
} else {
// We do have a valid "name" in the CallerInfo. Display that
// in the "name" slot, and the phone number in the "number" slot.
if (presentation != PhoneConstants.PRESENTATION_ALLOWED) {
// This case should never happen since the network should never send a name
// AND a restricted presentation. However we leave it here in case of weird
// network behavior
displayName = PhoneUtils.getPresentationString(getContext(), presentation);
if (DBG) log(" ==> valid name, but presentation not allowed!"
+ " displayName = " + displayName);
} else {
displayName = info.name;
displayNumber = number;
label = info.phoneLabel;
if (DBG) log(" ==> name is present in CallerInfo: displayName '"
+ displayName + "', displayNumber '" + displayNumber + "'");
}
}
personUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, info.person_id);
if (DBG) log("- got personUri: '" + personUri
+ "', based on info.person_id: " + info.person_id);
} else {
displayName = PhoneUtils.getPresentationString(getContext(), presentation);
}
// TODO: Revisit/cleanup following code when underlying telephony issue
// is fixed (b/7705977).
//
// Following logic was added to prevent screen flicker caused by receiving
// a momentary disconnect with only a stripped phone number (the phone
// would quickly flip between full caller info, stripped phone number, and
// back to full caller info). Note this only prevents the name/number/label
// fields from flickering--the phone state field will still briefly flicker.
boolean updateNameAndNumber = true;
// If the new info is just a phone number, check to make sure it's not less
// information than what's already being displayed.
if (displayNameIsNumber) {
// If the new number is the same as the number already displayed, ignore it
// because that means we're also already displaying a name for it.
// If the new number is the same as the name currently being displayed, only
// display if the new number is longer (ie, has formatting).
String visiblePhoneNumber = null;
if (mPhoneNumber.getVisibility() == View.VISIBLE) {
visiblePhoneNumber = mPhoneNumber.getText().toString();
}
if ((visiblePhoneNumber != null &&
PhoneNumberUtils.compare(visiblePhoneNumber, displayName)) ||
(PhoneNumberUtils.compare(mName.getText().toString(), displayName) &&
displayName.length() < mName.length())) {
if (DBG) log("chose not to update display {" + mName.getText() + ", "
+ visiblePhoneNumber + "} with number " + displayName);
updateNameAndNumber = false;
}
}
if (updateNameAndNumber) {
if (call.isGeneric()) {
mName.setText(R.string.card_title_in_call);
} else {
mName.setText(displayName);
}
mName.setVisibility(View.VISIBLE);
if (!TextUtils.isEmpty(displayNumber) && !call.isGeneric()) {
mPhoneNumber.setText(displayNumber);
mPhoneNumber.setVisibility(View.VISIBLE);
} else {
mPhoneNumber.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(label) && !call.isGeneric()) {
mLabel.setText(label);
mLabel.setVisibility(View.VISIBLE);
} else {
mLabel.setVisibility(View.GONE);
}
}
// Update mPhoto
// if the temporary flag is set, we know we'll be getting another call after
// the CallerInfo has been correctly updated. So, we can skip the image
// loading until then.
// If the photoResource is filled in for the CallerInfo, (like with the
// Emergency Number case), then we can just set the photo image without
// requesting for an image load. Please refer to CallerInfoAsyncQuery.java
// for cases where CallerInfo.photoResource may be set. We can also avoid
// the image load step if the image data is cached.
if (isTemporary && (info == null || !info.isCachedPhotoCurrent)) {
mPhoto.setTag(null);
mPhoto.setVisibility(View.INVISIBLE);
} else if (info != null && info.photoResource != 0){
showImage(mPhoto, info.photoResource);
} else if (!showCachedImage(mPhoto, info)) {
if (personUri == null) {
Log.w(LOG_TAG, "personPri is null. Just use Unknown picture.");
showImage(mPhoto, R.drawable.picture_unknown);
} else if (personUri.equals(mLoadingPersonUri)) {
if (DBG) {
log("The requested Uri (" + personUri + ") is being loaded already."
+ " Ignoret the duplicate load request.");
}
} else {
// Remember which person's photo is being loaded right now so that we won't issue
// unnecessary load request multiple times, which will mess up animation around
// the contact photo.
mLoadingPersonUri = personUri;
// Forget the drawable previously used.
mPhoto.setTag(null);
// Show empty screen for a moment.
mPhoto.setVisibility(View.INVISIBLE);
// Load the image with a callback to update the image state.
// When the load is finished, onImageLoadComplete() will be called.
ContactsAsyncHelper.startObtainPhotoAsync(TOKEN_UPDATE_PHOTO_FOR_CALL_STATE,
getContext(), personUri, this, new AsyncLoadCookie(mPhoto, info, call));
// If the image load is too slow, we show a default avatar icon afterward.
// If it is fast enough, this message will be canceled on onImageLoadComplete().
mHandler.removeMessages(MESSAGE_SHOW_UNKNOWN_PHOTO);
mHandler.sendEmptyMessageDelayed(MESSAGE_SHOW_UNKNOWN_PHOTO, MESSAGE_DELAY);
}
}
// If the phone call is on hold, show it with darker status.
// Right now we achieve it by overlaying opaque View.
// Note: See also layout file about why so and what is the other possibilities.
if (call.getState() == Call.State.HOLDING) {
AnimationUtils.Fade.show(mPhotoDimEffect);
} else {
AnimationUtils.Fade.hide(mPhotoDimEffect, View.GONE);
}
// Other text fields:
updateCallTypeLabel(call);
// updateSocialStatus(socialStatusText, socialStatusBadge, call); // Currently unused
}
|
diff --git a/DataExtractionOSM/src/net/osmand/binary/BinaryMapAddressReaderAdapter.java b/DataExtractionOSM/src/net/osmand/binary/BinaryMapAddressReaderAdapter.java
index 38c58a01..ed903e6e 100644
--- a/DataExtractionOSM/src/net/osmand/binary/BinaryMapAddressReaderAdapter.java
+++ b/DataExtractionOSM/src/net/osmand/binary/BinaryMapAddressReaderAdapter.java
@@ -1,580 +1,580 @@
package net.osmand.binary;
import gnu.trove.list.array.TIntArrayList;
import java.io.IOException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.List;
import net.osmand.CollatorStringMatcher;
import net.osmand.CollatorStringMatcher.StringMatcherMode;
import net.osmand.LogUtil;
import net.osmand.StringMatcher;
import net.osmand.binary.BinaryMapIndexReader.SearchRequest;
import net.osmand.binary.OsmandOdb.AddressNameIndexDataAtom;
import net.osmand.binary.OsmandOdb.OsmAndAddressIndex.CitiesIndex;
import net.osmand.binary.OsmandOdb.OsmAndAddressNameIndexData;
import net.osmand.binary.OsmandOdb.OsmAndAddressNameIndexData.AddressNameIndexData;
import net.osmand.data.Building;
import net.osmand.data.Building.BuildingInterpolation;
import net.osmand.data.City;
import net.osmand.data.City.CityType;
import net.osmand.data.MapObject;
import net.osmand.data.Street;
import net.osmand.osm.LatLon;
import net.osmand.osm.MapUtils;
import net.sf.junidecode.Junidecode;
import org.apache.commons.logging.Log;
import com.google.protobuf.CodedInputStreamRAF;
import com.google.protobuf.WireFormat;
public class BinaryMapAddressReaderAdapter {
public final static int CITY_TOWN_TYPE = 1;
public final static int POSTCODES_TYPE = 2;
public final static int VILLAGES_TYPE = 3;
public final static int STREET_TYPE = 4;
private static final Log LOG = LogUtil.getLog(BinaryMapAddressReaderAdapter.class);
public static class AddressRegion extends BinaryIndexPart {
String enName;
int indexNameOffset = -1;
List<CitiesBlock> cities = new ArrayList<BinaryMapAddressReaderAdapter.CitiesBlock>();
LatLon calculatedCenter = null;
}
public static class CitiesBlock extends BinaryIndexPart {
int type;
}
private CodedInputStreamRAF codedIS;
private final BinaryMapIndexReader map;
protected BinaryMapAddressReaderAdapter(BinaryMapIndexReader map){
this.codedIS = map.codedIS;
this.map = map;
}
private void skipUnknownField(int t) throws IOException {
map.skipUnknownField(t);
}
private int readInt() throws IOException {
return map.readInt();
}
protected void readAddressIndex(AddressRegion region) throws IOException {
while(true){
int t = codedIS.readTag();
int tag = WireFormat.getTagFieldNumber(t);
switch (tag) {
case 0:
if(region.enName == null || region.enName.length() == 0){
region.enName = Junidecode.unidecode(region.name);
}
return;
case OsmandOdb.OsmAndAddressIndex.NAME_FIELD_NUMBER :
region.name = codedIS.readString();
break;
case OsmandOdb.OsmAndAddressIndex.NAME_EN_FIELD_NUMBER :
region.enName = codedIS.readString();
break;
case OsmandOdb.OsmAndAddressIndex.CITIES_FIELD_NUMBER :
CitiesBlock block = new CitiesBlock();
region.cities.add(block);
block.type = 1;
block.length = readInt();
block.filePointer = codedIS.getTotalBytesRead();
while(true){
int tt = codedIS.readTag();
int ttag = WireFormat.getTagFieldNumber(tt);
if(ttag == 0) {
break;
} else if(ttag == CitiesIndex.TYPE_FIELD_NUMBER){
block.type = codedIS.readUInt32();
break;
} else {
skipUnknownField(tt);
}
}
codedIS.seek(block.filePointer + block.length);
break;
case OsmandOdb.OsmAndAddressIndex.NAMEINDEX_FIELD_NUMBER :
region.indexNameOffset = codedIS.getTotalBytesRead();
int length = readInt();
codedIS.seek(region.indexNameOffset + length + 4);
break;
default:
skipUnknownField(t);
break;
}
}
}
protected void readCities(List<City> cities, SearchRequest<City> resultMatcher, StringMatcher matcher, boolean useEn) throws IOException {
while(true){
int t = codedIS.readTag();
int tag = WireFormat.getTagFieldNumber(t);
switch (tag) {
case 0:
return;
case CitiesIndex.CITIES_FIELD_NUMBER :
int fp = codedIS.getTotalBytesRead();
int length = codedIS.readRawVarint32();
int oldLimit = codedIS.pushLimit(length);
City c = readCityHeader(matcher, fp, useEn);
if(c != null){
if (resultMatcher == null || resultMatcher.publish(c)) {
cities.add(c);
}
}
codedIS.popLimit(oldLimit);
if(resultMatcher != null && resultMatcher.isCancelled()){
codedIS.skipRawBytes(codedIS.getBytesUntilLimit());
}
break;
default:
skipUnknownField(t);
break;
}
}
}
protected void readCityStreets(SearchRequest<Street> resultMatcher, City city) throws IOException{
int x = MapUtils.get31TileNumberX(city.getLocation().getLongitude());
int y = MapUtils.get31TileNumberY(city.getLocation().getLatitude());
while(true){
int t = codedIS.readTag();
int tag = WireFormat.getTagFieldNumber(t);
switch (tag) {
case 0:
return;
case OsmandOdb.CityBlockIndex.STREETS_FIELD_NUMBER :
Street s = new Street(city);
s.setFileOffset(codedIS.getTotalBytesRead());
int length = codedIS.readRawVarint32();
int oldLimit = codedIS.pushLimit(length);
readStreet(s, null, false, x >> 7, y >> 7, city.isPostcode() ? city.getName() : null);
if(resultMatcher == null || resultMatcher.publish(s)){
city.registerStreet(s);
}
if(resultMatcher != null && resultMatcher.isCancelled()) {
codedIS.skipRawBytes(codedIS.getBytesUntilLimit());
}
codedIS.popLimit(oldLimit);
break;
case OsmandOdb.CityBlockIndex.BUILDINGS_FIELD_NUMBER :
// buildings for the town are not used now
skipUnknownField(t);
default:
skipUnknownField(t);
break;
}
}
}
protected City readCityHeader(StringMatcher nameMatcher, int filePointer, boolean useEn) throws IOException{
int x = 0;
int y = 0;
City c = null;
boolean englishNameMatched = false;
while(true){
int t = codedIS.readTag();
int tag = WireFormat.getTagFieldNumber(t);
switch (tag) {
case 0:
return c;
case OsmandOdb.CityIndex.CITY_TYPE_FIELD_NUMBER :
int type = codedIS.readUInt32();
c = new City(CityType.values()[type]);
break;
case OsmandOdb.CityIndex.ID_FIELD_NUMBER :
c.setId(codedIS.readUInt64());
if(nameMatcher != null && useEn && !englishNameMatched){
codedIS.skipRawBytes(codedIS.getBytesUntilLimit());
return null;
}
break;
case OsmandOdb.CityIndex.NAME_EN_FIELD_NUMBER :
String enName = codedIS.readString();
if (nameMatcher != null && enName.length() > 0) {
if(!nameMatcher.matches(enName)){
codedIS.skipRawBytes(codedIS.getBytesUntilLimit());
return null;
} else {
englishNameMatched = true;
}
}
c.setEnName(enName);
break;
case OsmandOdb.CityIndex.NAME_FIELD_NUMBER :
String name = codedIS.readString();
if(nameMatcher != null){
if(!useEn){
if(!nameMatcher.matches(name)) {
codedIS.skipRawBytes(codedIS.getBytesUntilLimit());
return null;
}
} else {
if(nameMatcher.matches(Junidecode.unidecode(name))){
englishNameMatched = true;
}
}
}
if(c == null) {
c = City.createPostcode(name);
}
c.setName(name);
break;
case OsmandOdb.CityIndex.X_FIELD_NUMBER :
x = codedIS.readUInt32();
break;
case OsmandOdb.CityIndex.Y_FIELD_NUMBER :
y = codedIS.readUInt32();
c.setLocation(MapUtils.get31LatitudeY(y), MapUtils.get31LongitudeX(x));
if(c.getEnName().length() == 0){
c.setEnName(Junidecode.unidecode(c.getName()));
}
break;
case OsmandOdb.CityIndex.SHIFTTOCITYBLOCKINDEX_FIELD_NUMBER :
int offset = readInt();
offset += filePointer;
c.setFileOffset(offset);
break;
default:
skipUnknownField(t);
break;
}
}
}
protected Street readStreet(Street s, SearchRequest<Building> buildingsMatcher, boolean loadBuildingsAndIntersected, int city24X, int city24Y, String postcodeFilter) throws IOException{
int x = 0;
int y = 0;
boolean loadLocation = city24X != 0 || city24Y != 0;
while(true){
int t = codedIS.readTag();
int tag = WireFormat.getTagFieldNumber(t);
switch (tag) {
case 0:
if(loadLocation){
s.setLocation(MapUtils.getLatitudeFromTile(24, y), MapUtils.getLongitudeFromTile(24, x));
}
if(s.getEnName().length() == 0){
s.setEnName(Junidecode.unidecode(s.getName()));
}
return s;
case OsmandOdb.StreetIndex.ID_FIELD_NUMBER :
s.setId(codedIS.readUInt64());
break;
case OsmandOdb.StreetIndex.NAME_EN_FIELD_NUMBER :
s.setEnName(codedIS.readString());
break;
case OsmandOdb.StreetIndex.NAME_FIELD_NUMBER :
s.setName(codedIS.readString());
break;
case OsmandOdb.StreetIndex.X_FIELD_NUMBER :
int sx = codedIS.readSInt32();
if(loadLocation){
x = sx + city24X;
} else {
x = (int) MapUtils.getTileNumberX(24, s.getLocation().getLongitude());
}
break;
case OsmandOdb.StreetIndex.Y_FIELD_NUMBER :
int sy = codedIS.readSInt32();
if(loadLocation){
y = sy + city24Y;
} else {
y = (int) MapUtils.getTileNumberY(24, s.getLocation().getLatitude());
}
break;
case OsmandOdb.StreetIndex.INTERSECTIONS_FIELD_NUMBER :
int length = codedIS.readRawVarint32();
if(loadBuildingsAndIntersected){
int oldLimit = codedIS.pushLimit(length);
Street si = readIntersectedStreet(s.getCity(), x, y);
s.addIntersectedStreet(si);
codedIS.popLimit(oldLimit);
} else {
codedIS.skipRawBytes(length);
}
break;
case OsmandOdb.StreetIndex.BUILDINGS_FIELD_NUMBER :
int offset = codedIS.getTotalBytesRead();
length = codedIS.readRawVarint32();
if(loadBuildingsAndIntersected){
int oldLimit = codedIS.pushLimit(length);
Building b = readBuilding(offset, x, y);
if (postcodeFilter == null || postcodeFilter.equalsIgnoreCase(b.getPostcode())) {
if (buildingsMatcher == null || buildingsMatcher.publish(b)) {
s.registerBuilding(b);
}
}
codedIS.popLimit(oldLimit);
} else {
codedIS.skipRawBytes(length);
}
break;
default:
skipUnknownField(t);
break;
}
}
}
protected Street readIntersectedStreet(City c, int street24X, int street24Y) throws IOException{
int x = 0;
int y = 0;
Street s = new Street(c);
while(true){
int t = codedIS.readTag();
int tag = WireFormat.getTagFieldNumber(t);
switch (tag) {
case 0:
s.setLocation(MapUtils.getLatitudeFromTile(24, y), MapUtils.getLongitudeFromTile(24, x));
if(s.getEnName().length() == 0){
s.setEnName(Junidecode.unidecode(s.getName()));
}
return s;
case OsmandOdb.BuildingIndex.ID_FIELD_NUMBER :
s.setId(codedIS.readUInt64());
break;
case OsmandOdb.StreetIntersection.NAME_EN_FIELD_NUMBER:
s.setEnName(codedIS.readString());
break;
case OsmandOdb.StreetIntersection.NAME_FIELD_NUMBER:
s.setName(codedIS.readString());
break;
case OsmandOdb.StreetIntersection.INTERSECTEDX_FIELD_NUMBER :
x = codedIS.readSInt32() + street24X;
break;
case OsmandOdb.StreetIntersection.INTERSECTEDY_FIELD_NUMBER :
y = codedIS.readSInt32() + street24Y;
break;
default:
skipUnknownField(t);
break;
}
}
}
protected Building readBuilding(int fileOffset, int street24X, int street24Y) throws IOException{
int x = 0;
int y = 0;
Building b = new Building();
b.setFileOffset(fileOffset);
while(true){
int t = codedIS.readTag();
int tag = WireFormat.getTagFieldNumber(t);
switch (tag) {
case 0:
b.setLocation(MapUtils.getLatitudeFromTile(24, y), MapUtils.getLongitudeFromTile(24, x));
if(b.getEnName().length() == 0){
b.setEnName(Junidecode.unidecode(b.getName()));
}
return b;
case OsmandOdb.BuildingIndex.ID_FIELD_NUMBER :
b.setId(codedIS.readUInt64());
break;
case OsmandOdb.BuildingIndex.NAME_EN_FIELD_NUMBER :
b.setEnName(codedIS.readString());
break;
case OsmandOdb.BuildingIndex.NAME_FIELD_NUMBER :
b.setName(codedIS.readString());
break;
case OsmandOdb.BuildingIndex.NAME_EN2_FIELD_NUMBER :
// no where to set now
codedIS.readString();
break;
case OsmandOdb.BuildingIndex.NAME2_FIELD_NUMBER :
b.setName2(codedIS.readString());
break;
case OsmandOdb.BuildingIndex.INTERPOLATION_FIELD_NUMBER :
int sint = codedIS.readSInt32();
if(sint > 0) {
b.setInterpolationInterval(sint);
} else {
b.setInterpolationType(BuildingInterpolation.fromValue(sint));
}
break;
case OsmandOdb.BuildingIndex.X_FIELD_NUMBER :
x = codedIS.readSInt32() + street24X;
break;
case OsmandOdb.BuildingIndex.Y_FIELD_NUMBER :
y = codedIS.readSInt32() + street24Y;
break;
case OsmandOdb.BuildingIndex.POSTCODE_FIELD_NUMBER :
b.setPostcode(codedIS.readString());
break;
default:
skipUnknownField(t);
break;
}
}
}
public void searchAddressDataByName(AddressRegion reg, SearchRequest<MapObject> req, int[] typeFilter) throws IOException {
TIntArrayList loffsets = new TIntArrayList();
Collator instance = Collator.getInstance();
instance.setStrength(Collator.PRIMARY);
CollatorStringMatcher matcher = new CollatorStringMatcher(instance, req.nameQuery, StringMatcherMode.CHECK_STARTS_FROM_SPACE);
long time = System.currentTimeMillis();
int indexOffset = 0;
while (true) {
if (req.isCancelled()) {
return;
}
int t = codedIS.readTag();
int tag = WireFormat.getTagFieldNumber(t);
switch (tag) {
case 0:
return;
case OsmAndAddressNameIndexData.TABLE_FIELD_NUMBER:
int length = readInt();
indexOffset = codedIS.getTotalBytesRead();
int oldLimit = codedIS.pushLimit(length);
// here offsets are sorted by distance
map.readIndexedStringTable(instance, req.nameQuery, "", loffsets, 0);
codedIS.popLimit(oldLimit);
break;
case OsmAndAddressNameIndexData.ATOM_FIELD_NUMBER:
// also offsets can be randomly skipped by limit
loffsets.sort();
TIntArrayList[] refs = new TIntArrayList[5];
for (int i = 0; i < refs.length; i++) {
refs[i] = new TIntArrayList();
}
LOG.info("Searched address structure in " + (System.currentTimeMillis() - time) + "ms. Found " + loffsets.size()
+ " subtress");
for (int j = 0; j < loffsets.size(); j++) {
int fp = indexOffset + loffsets.get(j);
codedIS.seek(fp);
int len = codedIS.readRawVarint32();
int oldLim = codedIS.pushLimit(len);
int stag = 0;
do {
int st = codedIS.readTag();
stag = WireFormat.getTagFieldNumber(st);
if(stag == AddressNameIndexData.ATOM_FIELD_NUMBER) {
int slen = codedIS.readRawVarint32();
int soldLim = codedIS.pushLimit(slen);
readAddressNameData(req, refs, fp);
codedIS.popLimit(soldLim);
} else if(stag != 0){
skipUnknownField(st);
}
} while(stag != 0);
codedIS.popLimit(oldLim);
if (req.isCancelled()) {
return;
}
}
if (typeFilter == null) {
typeFilter = new int[] { CITY_TOWN_TYPE, POSTCODES_TYPE, VILLAGES_TYPE, STREET_TYPE };
}
for (int i = 0; i < typeFilter.length && !req.isCancelled(); i++) {
TIntArrayList list = refs[typeFilter[i]];
if (typeFilter[i] == STREET_TYPE) {
for (int j = 0; j < list.size() && !req.isCancelled(); j += 2) {
City obj = null;
{
codedIS.seek(list.get(j + 1));
int len = codedIS.readRawVarint32();
int old = codedIS.pushLimit(len);
obj = readCityHeader(null, list.get(j + 1), false);
codedIS.popLimit(old);
}
if (obj != null) {
System.out.println("STREET " + list.get(j) );
codedIS.seek(list.get(j));
int len = codedIS.readRawVarint32();
int old = codedIS.pushLimit(len);
LatLon l = obj.getLocation();
Street s = new Street(obj);
- readStreet(s, null, false, MapUtils.get31TileNumberX(l.getLatitude()) >> 7,
- MapUtils.get31TileNumberY(l.getLongitude()) >> 7, obj.isPostcode() ? obj.getName() : null);
+ readStreet(s, null, false, MapUtils.get31TileNumberX(l.getLongitude()) >> 7,
+ MapUtils.get31TileNumberY(l.getLatitude()) >> 7, obj.isPostcode() ? obj.getName() : null);
if (matcher.matches(s.getName())) {
req.publish(s);
}
codedIS.popLimit(old);
}
}
} else {
list.sort();
for (int j = 0; j < list.size() && !req.isCancelled(); j++) {
codedIS.seek(list.get(j));
int len = codedIS.readRawVarint32();
int old = codedIS.pushLimit(len);
City obj = readCityHeader(matcher, list.get(j), false);
if (obj != null) {
req.publish(obj);
}
codedIS.popLimit(old);
}
}
}
LOG.info("Whole address search by name is done in " + (System.currentTimeMillis() - time) + "ms. Found "
+ req.getSearchResults().size());
return;
default:
skipUnknownField(t);
break;
}
}
}
private void readAddressNameData(SearchRequest<MapObject> req, TIntArrayList[] refs, int fp) throws IOException {
TIntArrayList toAdd = null;
while(true){
if(req.isCancelled()){
return;
}
int t = codedIS.readTag();
int tag = WireFormat.getTagFieldNumber(t);
switch (tag) {
case 0:
return;
case AddressNameIndexDataAtom.NAMEEN_FIELD_NUMBER :
codedIS.readString();
break;
case AddressNameIndexDataAtom.NAME_FIELD_NUMBER :
codedIS.readString();
break;
case AddressNameIndexDataAtom.SHIFTTOCITYINDEX_FIELD_NUMBER :
if(toAdd != null) {
toAdd.add(fp - codedIS.readInt32());
}
break;
case AddressNameIndexDataAtom.SHIFTTOINDEX_FIELD_NUMBER :
if(toAdd != null) {
toAdd.add(fp - codedIS.readInt32());
}
break;
case AddressNameIndexDataAtom.TYPE_FIELD_NUMBER :
int type = codedIS.readInt32();
toAdd = refs[type];
break;
default:
skipUnknownField(t);
break;
}
}
}
}
| true | true |
public void searchAddressDataByName(AddressRegion reg, SearchRequest<MapObject> req, int[] typeFilter) throws IOException {
TIntArrayList loffsets = new TIntArrayList();
Collator instance = Collator.getInstance();
instance.setStrength(Collator.PRIMARY);
CollatorStringMatcher matcher = new CollatorStringMatcher(instance, req.nameQuery, StringMatcherMode.CHECK_STARTS_FROM_SPACE);
long time = System.currentTimeMillis();
int indexOffset = 0;
while (true) {
if (req.isCancelled()) {
return;
}
int t = codedIS.readTag();
int tag = WireFormat.getTagFieldNumber(t);
switch (tag) {
case 0:
return;
case OsmAndAddressNameIndexData.TABLE_FIELD_NUMBER:
int length = readInt();
indexOffset = codedIS.getTotalBytesRead();
int oldLimit = codedIS.pushLimit(length);
// here offsets are sorted by distance
map.readIndexedStringTable(instance, req.nameQuery, "", loffsets, 0);
codedIS.popLimit(oldLimit);
break;
case OsmAndAddressNameIndexData.ATOM_FIELD_NUMBER:
// also offsets can be randomly skipped by limit
loffsets.sort();
TIntArrayList[] refs = new TIntArrayList[5];
for (int i = 0; i < refs.length; i++) {
refs[i] = new TIntArrayList();
}
LOG.info("Searched address structure in " + (System.currentTimeMillis() - time) + "ms. Found " + loffsets.size()
+ " subtress");
for (int j = 0; j < loffsets.size(); j++) {
int fp = indexOffset + loffsets.get(j);
codedIS.seek(fp);
int len = codedIS.readRawVarint32();
int oldLim = codedIS.pushLimit(len);
int stag = 0;
do {
int st = codedIS.readTag();
stag = WireFormat.getTagFieldNumber(st);
if(stag == AddressNameIndexData.ATOM_FIELD_NUMBER) {
int slen = codedIS.readRawVarint32();
int soldLim = codedIS.pushLimit(slen);
readAddressNameData(req, refs, fp);
codedIS.popLimit(soldLim);
} else if(stag != 0){
skipUnknownField(st);
}
} while(stag != 0);
codedIS.popLimit(oldLim);
if (req.isCancelled()) {
return;
}
}
if (typeFilter == null) {
typeFilter = new int[] { CITY_TOWN_TYPE, POSTCODES_TYPE, VILLAGES_TYPE, STREET_TYPE };
}
for (int i = 0; i < typeFilter.length && !req.isCancelled(); i++) {
TIntArrayList list = refs[typeFilter[i]];
if (typeFilter[i] == STREET_TYPE) {
for (int j = 0; j < list.size() && !req.isCancelled(); j += 2) {
City obj = null;
{
codedIS.seek(list.get(j + 1));
int len = codedIS.readRawVarint32();
int old = codedIS.pushLimit(len);
obj = readCityHeader(null, list.get(j + 1), false);
codedIS.popLimit(old);
}
if (obj != null) {
System.out.println("STREET " + list.get(j) );
codedIS.seek(list.get(j));
int len = codedIS.readRawVarint32();
int old = codedIS.pushLimit(len);
LatLon l = obj.getLocation();
Street s = new Street(obj);
readStreet(s, null, false, MapUtils.get31TileNumberX(l.getLatitude()) >> 7,
MapUtils.get31TileNumberY(l.getLongitude()) >> 7, obj.isPostcode() ? obj.getName() : null);
if (matcher.matches(s.getName())) {
req.publish(s);
}
codedIS.popLimit(old);
}
}
} else {
list.sort();
for (int j = 0; j < list.size() && !req.isCancelled(); j++) {
codedIS.seek(list.get(j));
int len = codedIS.readRawVarint32();
int old = codedIS.pushLimit(len);
City obj = readCityHeader(matcher, list.get(j), false);
if (obj != null) {
req.publish(obj);
}
codedIS.popLimit(old);
}
}
}
LOG.info("Whole address search by name is done in " + (System.currentTimeMillis() - time) + "ms. Found "
+ req.getSearchResults().size());
return;
default:
skipUnknownField(t);
break;
}
}
}
|
public void searchAddressDataByName(AddressRegion reg, SearchRequest<MapObject> req, int[] typeFilter) throws IOException {
TIntArrayList loffsets = new TIntArrayList();
Collator instance = Collator.getInstance();
instance.setStrength(Collator.PRIMARY);
CollatorStringMatcher matcher = new CollatorStringMatcher(instance, req.nameQuery, StringMatcherMode.CHECK_STARTS_FROM_SPACE);
long time = System.currentTimeMillis();
int indexOffset = 0;
while (true) {
if (req.isCancelled()) {
return;
}
int t = codedIS.readTag();
int tag = WireFormat.getTagFieldNumber(t);
switch (tag) {
case 0:
return;
case OsmAndAddressNameIndexData.TABLE_FIELD_NUMBER:
int length = readInt();
indexOffset = codedIS.getTotalBytesRead();
int oldLimit = codedIS.pushLimit(length);
// here offsets are sorted by distance
map.readIndexedStringTable(instance, req.nameQuery, "", loffsets, 0);
codedIS.popLimit(oldLimit);
break;
case OsmAndAddressNameIndexData.ATOM_FIELD_NUMBER:
// also offsets can be randomly skipped by limit
loffsets.sort();
TIntArrayList[] refs = new TIntArrayList[5];
for (int i = 0; i < refs.length; i++) {
refs[i] = new TIntArrayList();
}
LOG.info("Searched address structure in " + (System.currentTimeMillis() - time) + "ms. Found " + loffsets.size()
+ " subtress");
for (int j = 0; j < loffsets.size(); j++) {
int fp = indexOffset + loffsets.get(j);
codedIS.seek(fp);
int len = codedIS.readRawVarint32();
int oldLim = codedIS.pushLimit(len);
int stag = 0;
do {
int st = codedIS.readTag();
stag = WireFormat.getTagFieldNumber(st);
if(stag == AddressNameIndexData.ATOM_FIELD_NUMBER) {
int slen = codedIS.readRawVarint32();
int soldLim = codedIS.pushLimit(slen);
readAddressNameData(req, refs, fp);
codedIS.popLimit(soldLim);
} else if(stag != 0){
skipUnknownField(st);
}
} while(stag != 0);
codedIS.popLimit(oldLim);
if (req.isCancelled()) {
return;
}
}
if (typeFilter == null) {
typeFilter = new int[] { CITY_TOWN_TYPE, POSTCODES_TYPE, VILLAGES_TYPE, STREET_TYPE };
}
for (int i = 0; i < typeFilter.length && !req.isCancelled(); i++) {
TIntArrayList list = refs[typeFilter[i]];
if (typeFilter[i] == STREET_TYPE) {
for (int j = 0; j < list.size() && !req.isCancelled(); j += 2) {
City obj = null;
{
codedIS.seek(list.get(j + 1));
int len = codedIS.readRawVarint32();
int old = codedIS.pushLimit(len);
obj = readCityHeader(null, list.get(j + 1), false);
codedIS.popLimit(old);
}
if (obj != null) {
System.out.println("STREET " + list.get(j) );
codedIS.seek(list.get(j));
int len = codedIS.readRawVarint32();
int old = codedIS.pushLimit(len);
LatLon l = obj.getLocation();
Street s = new Street(obj);
readStreet(s, null, false, MapUtils.get31TileNumberX(l.getLongitude()) >> 7,
MapUtils.get31TileNumberY(l.getLatitude()) >> 7, obj.isPostcode() ? obj.getName() : null);
if (matcher.matches(s.getName())) {
req.publish(s);
}
codedIS.popLimit(old);
}
}
} else {
list.sort();
for (int j = 0; j < list.size() && !req.isCancelled(); j++) {
codedIS.seek(list.get(j));
int len = codedIS.readRawVarint32();
int old = codedIS.pushLimit(len);
City obj = readCityHeader(matcher, list.get(j), false);
if (obj != null) {
req.publish(obj);
}
codedIS.popLimit(old);
}
}
}
LOG.info("Whole address search by name is done in " + (System.currentTimeMillis() - time) + "ms. Found "
+ req.getSearchResults().size());
return;
default:
skipUnknownField(t);
break;
}
}
}
|
diff --git a/src/java/com/idega/block/cal/business/CalendarRSSProducer.java b/src/java/com/idega/block/cal/business/CalendarRSSProducer.java
index 2483842..802ea89 100644
--- a/src/java/com/idega/block/cal/business/CalendarRSSProducer.java
+++ b/src/java/com/idega/block/cal/business/CalendarRSSProducer.java
@@ -1,372 +1,373 @@
package com.idega.block.cal.business;
import java.io.IOException;
import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import com.idega.block.cal.data.CalendarEntry;
import com.idega.block.rss.business.RSSAbstractProducer;
import com.idega.block.rss.business.RSSBusiness;
import com.idega.block.rss.business.RSSProducer;
import com.idega.block.rss.data.RSSRequest;
import com.idega.business.IBOLookup;
import com.idega.business.IBOLookupException;
import com.idega.presentation.IWContext;
import com.idega.slide.business.IWContentEvent;
import com.idega.slide.business.IWSlideChangeListener;
import com.idega.slide.business.IWSlideService;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
/**
*
* @author justinas
*
*/
public class CalendarRSSProducer extends RSSAbstractProducer implements RSSProducer, IWSlideChangeListener{
private List rssFileURIsCacheList = new ArrayList();
private static final int DATE_LENGTH = 8;
public void handleRSSRequest(RSSRequest rssRequest) throws IOException {
String extraURI = rssRequest.getExtraUri();
String feedParentFolder = null;
String feedFile = null;
if(extraURI == null)
extraURI = "";
if((!extraURI.endsWith("/")) && (extraURI.length() != 0))
extraURI = extraURI.concat("/");
IWContext iwc = getIWContext(rssRequest);
String uri = null;
if(extraURI.startsWith("period")){
try {
feedParentFolder = "/files/cms/calendar/rss/period/";
uri = extraURI.substring("period/".length(), extraURI.length());
feedFile = "period_"+getName(uri)+iwc.getLocale().getLanguage()+".xml";
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(extraURI.startsWith("group")){
feedParentFolder = "/files/cms/calendar/rss/group/";
uri = extraURI.substring("group/".length(), extraURI.length());
feedFile = "group_"+getName(uri)+getPeriod(uri)+iwc.getLocale().getLanguage()+".xml";
}
else if(extraURI.startsWith("ledger")){
feedParentFolder = "/files/cms/calendar/rss/ledger/";
feedFile = "ledger_"+extraURI.substring("ledger/".length(), extraURI.length()-1)+"_"+iwc.getLocale().getLanguage()+".xml";
}
else if(extraURI.startsWith("events")){
feedParentFolder = "/files/cms/calendar/rss/events/";
uri = extraURI.substring("events/".length(), extraURI.length());
feedFile = "events_"+getTypesString(uri)+getPeriod(uri)+iwc.getLocale().getLanguage()+".xml";
}
else{
// TODO handle wrong URI
}
String realURI = "/content"+feedParentFolder+feedFile;
if(rssFileURIsCacheList.contains(feedFile)){
// if(false){
try {
this.dispatch(realURI, rssRequest);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
//generate rss and store and the dispatch to it
//and add a listener to that directory
try {
searchForEntries(rssRequest,feedParentFolder,feedFile, extraURI);
rssFileURIsCacheList.add(feedFile);
this.dispatch(realURI, rssRequest);
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
}
public void searchForEntries(RSSRequest rssRequest, String feedParentFolder, String feedFileName, String extraURI) {
IWContext iwc = getIWContext(rssRequest);
Collection entries = null;
if(extraURI.startsWith("period"))
entries = getEntriesByPeriod(extraURI);
if(extraURI.startsWith("group"))
entries = getEntriesByGroup(extraURI);
if(extraURI.startsWith("ledger"))
entries = getEntriesByLedger(extraURI);
if(extraURI.startsWith("events"))
entries = getEntriesByEvents(extraURI);
if (entries != null){
Date now = new Date();
RSSBusiness rss = null;
try {
rss = (RSSBusiness) IBOLookup.getServiceInstance(iwc,RSSBusiness.class);
} catch (IBOLookupException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String serverName = iwc.getServerURL();
serverName = serverName.substring(0, serverName.length()-1);
SyndFeed allArticles = null;
if (entries.isEmpty()){
- allArticles = rss.createNewFeed("No entries found", serverName , "File feed generated by IdegaWeb ePlatform, Idega Software, http://www.idega.com", "atom_1.0", iwc.getCurrentLocale().toString(), new Timestamp(now.getTime()));
+ allArticles = rss.createNewFeed("No entries found", serverName , "Calendar feed generated by IdegaWeb ePlatform, Idega Software, http://www.idega.com", "atom_1.0", iwc.getCurrentLocale().toString(), new Timestamp(now.getTime()));
feedParentFolder = "/files/cms/calendar/rss/";
feedFileName = "empty_"+iwc.getLocale().getLanguage()+".xml";
}
else
- allArticles = rss.createNewFeed("title", serverName , "File feed generated by IdegaWeb ePlatform, Idega Software, http://www.idega.com", "atom_1.0", iwc.getCurrentLocale().toString(), new Timestamp(now.getTime()));
+ allArticles = rss.createNewFeed("title", serverName , "Calendar feed generated by IdegaWeb ePlatform, Idega Software, http://www.idega.com", "atom_1.0", iwc.getCurrentLocale().toString(), new Timestamp(now.getTime()));
List syndEntries = new ArrayList();
try {
List calendarEntries = new ArrayList(entries);
CalendarEntry calEntry = null;
for (int i = 0; i < entries.size(); i++) {
SyndEntry sEntry = new SyndEntryImpl();
calEntry = (CalendarEntry)calendarEntries.get(i);
SyndContent scont = new SyndContentImpl();
String content = "Name: "+calEntry.getName()+" Type: "+calEntry.getEntryTypeName()+" From: "+calEntry.getDate()+" To: "+calEntry.getEndDate();
scont.setValue(content);
sEntry.setTitle(calEntry.getName());
sEntry.setDescription(scont);
+ sEntry.setPublishedDate(calEntry.getDate());
syndEntries.add(sEntry);
}
} catch (RuntimeException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
allArticles.setEntries(syndEntries);
try {
String allArticlesContent = rss.convertFeedToAtomXMLString(allArticles);
IWSlideService service = this.getIWSlideService(rssRequest);
service.uploadFileAndCreateFoldersFromStringAsRoot(feedParentFolder, feedFileName, allArticlesContent, this.RSS_CONTENT_TYPE, true);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void onSlideChange(IWContentEvent contentEvent) {
// On a file change this code checks if an rss file already exists and if so updates it (overwrites) with a new folder list
String URI = contentEvent.getContentEvent().getUri();
//only do it for articles (whenever something changes in the articles folder)
if(URI.indexOf("/cms/calendar/")>-1){
//TODO dont remove cache on COmments change, just check the URI for commentesrss.
getrssFileURIsCacheList().clear();
}
}
protected List getrssFileURIsCacheList() {
return rssFileURIsCacheList;
}
private Collection getEntriesByPeriod(String extraURI){
String period = extraURI.substring("period/".length());
String fromStr = period.substring(0, DATE_LENGTH);
String toStr = period.substring(DATE_LENGTH+1, period.length()-1);
Timestamp fromTmst = getTimeStampFromString(fromStr);
Timestamp toTmst = getTimeStampFromString(toStr);
CalBusiness calendar = new CalBusinessBean();
return calendar.getEntriesBetweenTimestamps(fromTmst, toTmst);
}
private Collection getEntriesByGroup(String extraURI){
String group = extraURI.substring("group/".length());
String groupID = group.substring(0, group.indexOf("/"));
String groupPeriod = group.substring(groupID.length()+1, group.length());
Timestamp from = null;
Timestamp to = null;
CalBusiness calendar = new CalBusinessBean();
int entryGroupID;
try {
entryGroupID = Integer.parseInt(groupID);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
if (groupPeriod.length() != 0){
String fromStr = groupPeriod.substring(0, DATE_LENGTH);
String toStr = groupPeriod.substring(DATE_LENGTH+1, groupPeriod.length()-1);
from = getTimeStampFromString(fromStr);
to = getTimeStampFromString(toStr);
Collection coll = calendar.getEntriesBetweenTimestamps(from, to);
List entries = new ArrayList();
for (Iterator iter = coll.iterator(); iter.hasNext();) {
CalendarEntry element = (CalendarEntry) iter.next();
int id = element.getGroupID();
if (element.getGroupID() == entryGroupID){
entries.add(element);
}
}
return entries;
}
return calendar.getEntriesByICGroup(entryGroupID);
}
private Collection getEntriesByLedger(String extraURI){
String ledger = extraURI.substring("ledger/".length());
String ledgerID = ledger.substring(0, ledger.indexOf("/"));
String ledgerPeriod = ledger.substring(ledgerID.length()+1, ledger.length());
Timestamp from = null;
Timestamp to = null;
CalBusiness calendar = new CalBusinessBean();
int ledgerIdInt;
try {
ledgerIdInt = Integer.parseInt(ledgerID);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
if (ledgerPeriod.length() != 0){
String fromStr = ledgerPeriod.substring(0, DATE_LENGTH);
String toStr = ledgerPeriod.substring(DATE_LENGTH+1, ledgerPeriod.length()-1);
from = getTimeStampFromString(fromStr);
to = getTimeStampFromString(toStr);
Collection coll = calendar.getEntriesBetweenTimestamps(from, to);
List entries = new ArrayList();
for (Iterator iter = coll.iterator(); iter.hasNext();) {
CalendarEntry element = (CalendarEntry) iter.next();
if (element.getLedgerID() == ledgerIdInt){
entries.add(element);
}
}
return entries;
}
return calendar.getEntriesByLedgerID(ledgerIdInt);
}
private Collection getEntriesByEvents(String extraURI){
String events = extraURI.substring("events/".length());
String eventsPeriod = null;
List eventsList = new ArrayList();
int index = -1;
if (events.indexOf("+") == -1){
eventsList.add(events.substring(0, events.indexOf("/")));
events = events.substring(events.indexOf("/")+1, events.length());
}
else{
while(true){
index = events.indexOf("+");
if (index == -1){
index = events.indexOf("/");
eventsList.add(events.substring(0, index));
events = events.substring(index+1, events.length());
break;
}
else{
eventsList.add(events.substring(0, index));
events = events.substring(index+1, events.length());
}
}
}
eventsPeriod = events;
Timestamp from = null;
Timestamp to = null;
CalBusiness calendar = new CalBusinessBean();
if (eventsPeriod.length() != 0){
String fromStr = eventsPeriod.substring(0, DATE_LENGTH);
String toStr = eventsPeriod.substring(DATE_LENGTH+1, eventsPeriod.length()-1);
from = getTimeStampFromString(fromStr);
to = getTimeStampFromString(toStr);
Collection coll = calendar.getEntriesBetweenTimestamps(from, to);
List entries = new ArrayList();
for (Iterator iter = coll.iterator(); iter.hasNext();) {
CalendarEntry element = (CalendarEntry) iter.next();
if(eventsList.contains(element.getEntryTypeName())){
entries.add(element);
}
}
return entries;
}
Collection result = calendar.getEntriesByEvents(eventsList);
return calendar.getEntriesByEvents(eventsList);
}
private Timestamp getTimeStampFromString(String dateString){
try {
SimpleDateFormat simpleDate = new SimpleDateFormat("yyyyMMdd");
Date date = simpleDate.parse(dateString, new ParsePosition(0));
return new Timestamp(date.getTime());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private String getPeriod(String uri){
if(uri.length() == 0)
return "";
String period = uri.substring(uri.indexOf("/")+1);
if(period.length() == 0)
return "";
if(period.startsWith("/"))
return period.substring(1, period.length()-1)+"_";
else return period.substring(0, period.length()-1)+"_";
}
private String getName(String extraURI){
return extraURI.substring(0,extraURI.indexOf("/"))+"_";
}
private String getTypesString (String extraURI){
String events = new String();
try {
List eventsList = getTypesList(extraURI);
for (int i = 0; i < eventsList.size(); i++) {
events = events.concat(eventsList.get(i)+"_");
}
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return events;
}
private List getTypesList (String events){
List eventsList = new ArrayList();
int index;
if (events.indexOf("+") == -1){
eventsList.add(events.substring(0, events.indexOf("/")));
events = events.substring(events.indexOf("/")+1, events.length());
}
else{
while(true){
index = events.indexOf("+");
if (index == -1){
index = events.indexOf("/");
eventsList.add(events.substring(0, index));
events = events.substring(index+1, events.length());
break;
}
else{
eventsList.add(events.substring(0, index));
events = events.substring(index+1, events.length());
}
}
}
return eventsList;
}
}
| false | true |
public void searchForEntries(RSSRequest rssRequest, String feedParentFolder, String feedFileName, String extraURI) {
IWContext iwc = getIWContext(rssRequest);
Collection entries = null;
if(extraURI.startsWith("period"))
entries = getEntriesByPeriod(extraURI);
if(extraURI.startsWith("group"))
entries = getEntriesByGroup(extraURI);
if(extraURI.startsWith("ledger"))
entries = getEntriesByLedger(extraURI);
if(extraURI.startsWith("events"))
entries = getEntriesByEvents(extraURI);
if (entries != null){
Date now = new Date();
RSSBusiness rss = null;
try {
rss = (RSSBusiness) IBOLookup.getServiceInstance(iwc,RSSBusiness.class);
} catch (IBOLookupException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String serverName = iwc.getServerURL();
serverName = serverName.substring(0, serverName.length()-1);
SyndFeed allArticles = null;
if (entries.isEmpty()){
allArticles = rss.createNewFeed("No entries found", serverName , "File feed generated by IdegaWeb ePlatform, Idega Software, http://www.idega.com", "atom_1.0", iwc.getCurrentLocale().toString(), new Timestamp(now.getTime()));
feedParentFolder = "/files/cms/calendar/rss/";
feedFileName = "empty_"+iwc.getLocale().getLanguage()+".xml";
}
else
allArticles = rss.createNewFeed("title", serverName , "File feed generated by IdegaWeb ePlatform, Idega Software, http://www.idega.com", "atom_1.0", iwc.getCurrentLocale().toString(), new Timestamp(now.getTime()));
List syndEntries = new ArrayList();
try {
List calendarEntries = new ArrayList(entries);
CalendarEntry calEntry = null;
for (int i = 0; i < entries.size(); i++) {
SyndEntry sEntry = new SyndEntryImpl();
calEntry = (CalendarEntry)calendarEntries.get(i);
SyndContent scont = new SyndContentImpl();
String content = "Name: "+calEntry.getName()+" Type: "+calEntry.getEntryTypeName()+" From: "+calEntry.getDate()+" To: "+calEntry.getEndDate();
scont.setValue(content);
sEntry.setTitle(calEntry.getName());
sEntry.setDescription(scont);
syndEntries.add(sEntry);
}
} catch (RuntimeException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
allArticles.setEntries(syndEntries);
try {
String allArticlesContent = rss.convertFeedToAtomXMLString(allArticles);
IWSlideService service = this.getIWSlideService(rssRequest);
service.uploadFileAndCreateFoldersFromStringAsRoot(feedParentFolder, feedFileName, allArticlesContent, this.RSS_CONTENT_TYPE, true);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
public void searchForEntries(RSSRequest rssRequest, String feedParentFolder, String feedFileName, String extraURI) {
IWContext iwc = getIWContext(rssRequest);
Collection entries = null;
if(extraURI.startsWith("period"))
entries = getEntriesByPeriod(extraURI);
if(extraURI.startsWith("group"))
entries = getEntriesByGroup(extraURI);
if(extraURI.startsWith("ledger"))
entries = getEntriesByLedger(extraURI);
if(extraURI.startsWith("events"))
entries = getEntriesByEvents(extraURI);
if (entries != null){
Date now = new Date();
RSSBusiness rss = null;
try {
rss = (RSSBusiness) IBOLookup.getServiceInstance(iwc,RSSBusiness.class);
} catch (IBOLookupException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String serverName = iwc.getServerURL();
serverName = serverName.substring(0, serverName.length()-1);
SyndFeed allArticles = null;
if (entries.isEmpty()){
allArticles = rss.createNewFeed("No entries found", serverName , "Calendar feed generated by IdegaWeb ePlatform, Idega Software, http://www.idega.com", "atom_1.0", iwc.getCurrentLocale().toString(), new Timestamp(now.getTime()));
feedParentFolder = "/files/cms/calendar/rss/";
feedFileName = "empty_"+iwc.getLocale().getLanguage()+".xml";
}
else
allArticles = rss.createNewFeed("title", serverName , "Calendar feed generated by IdegaWeb ePlatform, Idega Software, http://www.idega.com", "atom_1.0", iwc.getCurrentLocale().toString(), new Timestamp(now.getTime()));
List syndEntries = new ArrayList();
try {
List calendarEntries = new ArrayList(entries);
CalendarEntry calEntry = null;
for (int i = 0; i < entries.size(); i++) {
SyndEntry sEntry = new SyndEntryImpl();
calEntry = (CalendarEntry)calendarEntries.get(i);
SyndContent scont = new SyndContentImpl();
String content = "Name: "+calEntry.getName()+" Type: "+calEntry.getEntryTypeName()+" From: "+calEntry.getDate()+" To: "+calEntry.getEndDate();
scont.setValue(content);
sEntry.setTitle(calEntry.getName());
sEntry.setDescription(scont);
sEntry.setPublishedDate(calEntry.getDate());
syndEntries.add(sEntry);
}
} catch (RuntimeException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
allArticles.setEntries(syndEntries);
try {
String allArticlesContent = rss.convertFeedToAtomXMLString(allArticles);
IWSlideService service = this.getIWSlideService(rssRequest);
service.uploadFileAndCreateFoldersFromStringAsRoot(feedParentFolder, feedFileName, allArticlesContent, this.RSS_CONTENT_TYPE, true);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
diff --git a/software/camod/src/gov/nih/nci/camod/util/DuplicateUtil.java b/software/camod/src/gov/nih/nci/camod/util/DuplicateUtil.java
index c2de2a70..f35b3540 100755
--- a/software/camod/src/gov/nih/nci/camod/util/DuplicateUtil.java
+++ b/software/camod/src/gov/nih/nci/camod/util/DuplicateUtil.java
@@ -1,246 +1,247 @@
/*
* DuplicateUtil.java
*
* October 19, 2005, 3:44 PM
*
* $Id: DuplicateUtil.java,v 1.12 2008-02-08 16:47:20 pandyas Exp $
*
* $Log: not supported by cvs2svn $
* Revision 1.11 2007/09/27 13:58:16 pandyas
* Added new folder
*
* Revision 1.10 2006/05/08 13:42:02 georgeda
* Reformat and clean up warnings
*
* Revision 1.9 2006/04/17 19:10:50 pandyas
* Added $Id: DuplicateUtil.java,v 1.12 2008-02-08 16:47:20 pandyas Exp $ and $log:$
*
*/
package gov.nih.nci.camod.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* DuplicateUtil - Bean Deep-Copy Utility
* <p>
* This class provides a utility method for performing a deep-copy (duplicate) of
* domain bean objects. Domain classes that implement the Duplicatable interface
* will be deep-copied along with any sub-classes.
* <p>
* @author Marc Piparo
* @version 1.1
* @see Duplicatable
*/
public class DuplicateUtil
{
private static Log log = LogFactory.getLog(DuplicateUtil.class);
/**
* Performs deep-copy "Duplicate" of the input parameter source bean object.
* Source Bean MUST implement Duplicatable interface.
* <p>
* Only public accessible Bean properties will be copied. (i.e properties
* with "public" set and get methods)
* <p>
* Associated property beans (including beans in a collection) will by default
* be copied by reference, unless they implement the Duplicatable interface
* as well, in which case they too will be deep-copied.
* <p>
* @param src source bean object to be duplicated
* @throws java.lang.Exception Exception
* @return Object duplicate bean
*/
public static Object duplicateBean(Duplicatable src) throws Exception
{
return duplicateBeanImpl(src, null, null, null, null);
}
/**
* Performs deep-copy "Duplicate" of the input parameter source bean object.
* Source Bean MUST implement Duplicatable interface.
* <p>
* Similar functionality to duplicateBean(Duplicatable src) method, however
* accepts an additional collection parameter which defines properties
* that should NOT be copied.
* <p>
* excludedProperties parameter consists of a Collection of String objects
* that should not be copied. String objects should use dot-notation to
* identify properties.
* <p>
* example: to exclude zipcode from a model containing a person object
* with an address object property bean during a duplicate of the person object.
* <p>
* excludedProperties.add("address.zipcode");
*
* @param src source bean object to be duplicated
* @param excludedProperties collection of strings representing property names (in dot-notation) not be copied
* @throws java.lang.Exception Exception
* @return Object duplicate bean
*/
public static Object duplicateBean(Duplicatable src,
Collection excludedProperties) throws Exception
{
return duplicateBeanImpl(src, null, null, null, excludedProperties);
}
private static Object duplicateBeanImpl(Object src,
List<Object> srcHistory,
List<Object> dupHistory,
String path,
Collection excludedProperties) throws Exception
{
Object duplicate = null;
if (src != null)
{
try
{
// reset history collections on root duplicate
if (srcHistory == null)
{
srcHistory = new ArrayList<Object>();
}
if (dupHistory == null)
{
dupHistory = new ArrayList<Object>();
}
// check if we've already duplicated this object
if (!srcHistory.contains(src))
{
// add this src object to the history
srcHistory.add(src);
// instantiate a new instance of this class
- // check for virtual enahancer classes (i.e. hibernate lazy loaders)
+ // check for virtual enahancer & javassist classes (i.e. hibernate lazy loaders)
Class duplicateClass = null;
- if (src.getClass().getName().indexOf("$$Enhancer") > -1)
+ if (src.getClass().getName().indexOf("$$Enhancer") > -1 || src.getClass().getName().indexOf("$$_javassist") > -1 )
{
duplicateClass = src.getClass().getSuperclass();
}
else
{
duplicateClass = src.getClass();
}
duplicate = (Object) duplicateClass.newInstance();
// add this new duplicate object to history
dupHistory.add(duplicate);
Map beanProps = PropertyUtils.describe(src);
Iterator props = beanProps.entrySet().iterator();
log.debug("***** DUPLICATE Deep-Copy of Class: " + duplicateClass.getName());
// loop thru bean properties
while (props.hasNext())
{
Map.Entry entry = (Map.Entry) props.next();
Object propValue = entry.getValue();
log.debug("entry: " + entry + "\tpropValue: " + propValue);
if (entry.getKey() != null)
{
String propName = entry.getKey().toString();
// determine path name
String pathName = "";
if (path != null)
{
pathName = path + ".";
}
pathName += propName;
// do no copy property if it is in the excluded list
if (!(excludedProperties != null && excludedProperties.contains(pathName)))
{
log.debug("** processing copy of property: " + pathName);
// check if property is a collection
if (propValue instanceof java.util.Collection)
{
Collection collectionProperty = (Collection) propValue;
if (!collectionProperty.isEmpty())
{
// get collection property -
// *note: bean class is responsible for instatiating collection on construction
Collection duplicateCollection = (Collection) PropertyUtils.getProperty(duplicate, propName);
if (duplicateCollection != null)
{
// iterate thru collection, duplicate elements and add to collection
for (Iterator iter = collectionProperty.iterator(); iter.hasNext();)
{
Object collectionEntry = iter.next();
duplicateCollection.add(duplicateProperty(collectionEntry, srcHistory, dupHistory,
pathName, excludedProperties));
}
}
}
}
else
{
// set member property in duplicate object
try
{
log.debug("** copying property: " + pathName);
BeanUtils.copyProperty(duplicate, propName, duplicateProperty(propValue, srcHistory, dupHistory,
pathName, excludedProperties));
}
catch (Exception ex)
{
// do nothing. skip and move on. property value may be null, or no set method found.
log.debug("** property '" + propName + "' not copied. Either no set method, or null.");
}
} // collection condition
}
} // key=null check
} // loop end
}
else
{
// this src object has already been duplicated, so return a reference
// to the duplicate created earlier rather than re-duplicate
duplicate = dupHistory.get(srcHistory.indexOf(src));
log.debug("** skipping - already duplicated: " + src.getClass().getName());
}
}
catch (Exception ex)
{
+ ex.printStackTrace();
throw new Exception("Error during Bean Duplicate: " + ex);
}
} // src=null check
return duplicate;
}
private static Object duplicateProperty(Object obj,
List<Object> srcHistory,
List<Object> dupHistory,
String path,
Collection excludedProperties) throws Exception
{
// if property implements Duplicatable, duplicate this object
// otherwise return a reference
if (obj instanceof Duplicatable)
{
return duplicateBeanImpl(obj, srcHistory, dupHistory, path, excludedProperties);
}
else
{
return obj;
}
}
}
| false | true |
private static Object duplicateBeanImpl(Object src,
List<Object> srcHistory,
List<Object> dupHistory,
String path,
Collection excludedProperties) throws Exception
{
Object duplicate = null;
if (src != null)
{
try
{
// reset history collections on root duplicate
if (srcHistory == null)
{
srcHistory = new ArrayList<Object>();
}
if (dupHistory == null)
{
dupHistory = new ArrayList<Object>();
}
// check if we've already duplicated this object
if (!srcHistory.contains(src))
{
// add this src object to the history
srcHistory.add(src);
// instantiate a new instance of this class
// check for virtual enahancer classes (i.e. hibernate lazy loaders)
Class duplicateClass = null;
if (src.getClass().getName().indexOf("$$Enhancer") > -1)
{
duplicateClass = src.getClass().getSuperclass();
}
else
{
duplicateClass = src.getClass();
}
duplicate = (Object) duplicateClass.newInstance();
// add this new duplicate object to history
dupHistory.add(duplicate);
Map beanProps = PropertyUtils.describe(src);
Iterator props = beanProps.entrySet().iterator();
log.debug("***** DUPLICATE Deep-Copy of Class: " + duplicateClass.getName());
// loop thru bean properties
while (props.hasNext())
{
Map.Entry entry = (Map.Entry) props.next();
Object propValue = entry.getValue();
log.debug("entry: " + entry + "\tpropValue: " + propValue);
if (entry.getKey() != null)
{
String propName = entry.getKey().toString();
// determine path name
String pathName = "";
if (path != null)
{
pathName = path + ".";
}
pathName += propName;
// do no copy property if it is in the excluded list
if (!(excludedProperties != null && excludedProperties.contains(pathName)))
{
log.debug("** processing copy of property: " + pathName);
// check if property is a collection
if (propValue instanceof java.util.Collection)
{
Collection collectionProperty = (Collection) propValue;
if (!collectionProperty.isEmpty())
{
// get collection property -
// *note: bean class is responsible for instatiating collection on construction
Collection duplicateCollection = (Collection) PropertyUtils.getProperty(duplicate, propName);
if (duplicateCollection != null)
{
// iterate thru collection, duplicate elements and add to collection
for (Iterator iter = collectionProperty.iterator(); iter.hasNext();)
{
Object collectionEntry = iter.next();
duplicateCollection.add(duplicateProperty(collectionEntry, srcHistory, dupHistory,
pathName, excludedProperties));
}
}
}
}
else
{
// set member property in duplicate object
try
{
log.debug("** copying property: " + pathName);
BeanUtils.copyProperty(duplicate, propName, duplicateProperty(propValue, srcHistory, dupHistory,
pathName, excludedProperties));
}
catch (Exception ex)
{
// do nothing. skip and move on. property value may be null, or no set method found.
log.debug("** property '" + propName + "' not copied. Either no set method, or null.");
}
} // collection condition
}
} // key=null check
} // loop end
}
else
{
// this src object has already been duplicated, so return a reference
// to the duplicate created earlier rather than re-duplicate
duplicate = dupHistory.get(srcHistory.indexOf(src));
log.debug("** skipping - already duplicated: " + src.getClass().getName());
}
}
catch (Exception ex)
{
throw new Exception("Error during Bean Duplicate: " + ex);
}
} // src=null check
return duplicate;
}
|
private static Object duplicateBeanImpl(Object src,
List<Object> srcHistory,
List<Object> dupHistory,
String path,
Collection excludedProperties) throws Exception
{
Object duplicate = null;
if (src != null)
{
try
{
// reset history collections on root duplicate
if (srcHistory == null)
{
srcHistory = new ArrayList<Object>();
}
if (dupHistory == null)
{
dupHistory = new ArrayList<Object>();
}
// check if we've already duplicated this object
if (!srcHistory.contains(src))
{
// add this src object to the history
srcHistory.add(src);
// instantiate a new instance of this class
// check for virtual enahancer & javassist classes (i.e. hibernate lazy loaders)
Class duplicateClass = null;
if (src.getClass().getName().indexOf("$$Enhancer") > -1 || src.getClass().getName().indexOf("$$_javassist") > -1 )
{
duplicateClass = src.getClass().getSuperclass();
}
else
{
duplicateClass = src.getClass();
}
duplicate = (Object) duplicateClass.newInstance();
// add this new duplicate object to history
dupHistory.add(duplicate);
Map beanProps = PropertyUtils.describe(src);
Iterator props = beanProps.entrySet().iterator();
log.debug("***** DUPLICATE Deep-Copy of Class: " + duplicateClass.getName());
// loop thru bean properties
while (props.hasNext())
{
Map.Entry entry = (Map.Entry) props.next();
Object propValue = entry.getValue();
log.debug("entry: " + entry + "\tpropValue: " + propValue);
if (entry.getKey() != null)
{
String propName = entry.getKey().toString();
// determine path name
String pathName = "";
if (path != null)
{
pathName = path + ".";
}
pathName += propName;
// do no copy property if it is in the excluded list
if (!(excludedProperties != null && excludedProperties.contains(pathName)))
{
log.debug("** processing copy of property: " + pathName);
// check if property is a collection
if (propValue instanceof java.util.Collection)
{
Collection collectionProperty = (Collection) propValue;
if (!collectionProperty.isEmpty())
{
// get collection property -
// *note: bean class is responsible for instatiating collection on construction
Collection duplicateCollection = (Collection) PropertyUtils.getProperty(duplicate, propName);
if (duplicateCollection != null)
{
// iterate thru collection, duplicate elements and add to collection
for (Iterator iter = collectionProperty.iterator(); iter.hasNext();)
{
Object collectionEntry = iter.next();
duplicateCollection.add(duplicateProperty(collectionEntry, srcHistory, dupHistory,
pathName, excludedProperties));
}
}
}
}
else
{
// set member property in duplicate object
try
{
log.debug("** copying property: " + pathName);
BeanUtils.copyProperty(duplicate, propName, duplicateProperty(propValue, srcHistory, dupHistory,
pathName, excludedProperties));
}
catch (Exception ex)
{
// do nothing. skip and move on. property value may be null, or no set method found.
log.debug("** property '" + propName + "' not copied. Either no set method, or null.");
}
} // collection condition
}
} // key=null check
} // loop end
}
else
{
// this src object has already been duplicated, so return a reference
// to the duplicate created earlier rather than re-duplicate
duplicate = dupHistory.get(srcHistory.indexOf(src));
log.debug("** skipping - already duplicated: " + src.getClass().getName());
}
}
catch (Exception ex)
{
ex.printStackTrace();
throw new Exception("Error during Bean Duplicate: " + ex);
}
} // src=null check
return duplicate;
}
|
diff --git a/source/de/anomic/crawler/robotsParser.java b/source/de/anomic/crawler/robotsParser.java
index 97b9648f0..74f49c91a 100644
--- a/source/de/anomic/crawler/robotsParser.java
+++ b/source/de/anomic/crawler/robotsParser.java
@@ -1,224 +1,227 @@
//robotsParser.java
//-------------------------------------
//part of YACY
//
//(C) 2005, 2006 by Alexander Schier
// Martin Thelian
//
//last change: $LastChangedDate$ by $LastChangedBy$
//Revision: $LastChangedRevision$
//
//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
// extended to return structured objects instead of a Object[] and
// extended to return a Allow-List by Michael Christen, 21.07.2008
package de.anomic.crawler;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.ArrayList;
/*
* A class for Parsing robots.txt files.
* It only parses the Deny Part, yet.
*
* Robots RFC
* http://www.robotstxt.org/wc/norobots-rfc.html
*
* TODO:
* - On the request attempt resulted in temporary failure a robot
* should defer visits to the site until such time as the resource
* can be retrieved.
*
* - Extended Standard for Robot Exclusion
* See: http://www.conman.org/people/spc/robots2.html
*
* - Robot Exclusion Standard Revisited
* See: http://www.kollar.com/robots.html
*/
public final class robotsParser {
public static final String ROBOTS_USER_AGENT = "User-agent:".toUpperCase();
public static final String ROBOTS_DISALLOW = "Disallow:".toUpperCase();
public static final String ROBOTS_ALLOW = "Allow:".toUpperCase();
public static final String ROBOTS_COMMENT = "#";
public static final String ROBOTS_SITEMAP = "Sitemap:".toUpperCase();
public static final String ROBOTS_CRAWL_DELAY = "Crawl-Delay:".toUpperCase();
private ArrayList<String> allowList;
private ArrayList<String> denyList;
private String sitemap;
private long crawlDelayMillis;
public robotsParser(final byte[] robotsTxt) {
if ((robotsTxt == null)||(robotsTxt.length == 0)) {
allowList = new ArrayList<String>(0);
denyList = new ArrayList<String>(0);
sitemap = "";
crawlDelayMillis = 0;
} else {
final ByteArrayInputStream bin = new ByteArrayInputStream(robotsTxt);
final BufferedReader reader = new BufferedReader(new InputStreamReader(bin));
parse(reader);
}
}
public robotsParser(final BufferedReader reader) {
if (reader == null) {
allowList = new ArrayList<String>(0);
denyList = new ArrayList<String>(0);
sitemap = "";
crawlDelayMillis = 0;
} else {
parse(reader);
}
}
private void parse(final BufferedReader reader) {
final ArrayList<String> deny4AllAgents = new ArrayList<String>();
final ArrayList<String> deny4YaCyAgent = new ArrayList<String>();
final ArrayList<String> allow4AllAgents = new ArrayList<String>();
final ArrayList<String> allow4YaCyAgent = new ArrayList<String>();
int pos;
String line = null, lineUpper = null;
sitemap = null;
crawlDelayMillis = 0;
boolean isRule4AllAgents = false,
isRule4YaCyAgent = false,
rule4YaCyFound = false,
inBlock = false;
try {
while ((line = reader.readLine()) != null) {
// replacing all tabs with spaces
line = line.replaceAll("\t"," ").trim();
lineUpper = line.toUpperCase();
if (line.length() == 0) {
// OLD: we have reached the end of the rule block
// rule4Yacy = false; inBlock = false;
// NEW: just ignore it
} else if (line.startsWith(ROBOTS_COMMENT)) {
// we can ignore this. Just a comment line
} else if (lineUpper.startsWith(ROBOTS_SITEMAP)) {
pos = line.indexOf(" ");
if (pos != -1) {
sitemap = line.substring(pos).trim();
}
} else if (lineUpper.startsWith(ROBOTS_USER_AGENT)) {
if (inBlock) {
// we have detected the start of a new block
inBlock = false;
isRule4AllAgents = false;
isRule4YaCyAgent = false;
crawlDelayMillis = 0; // each block has a separate delay
}
// cutting off comments at the line end
pos = line.indexOf(ROBOTS_COMMENT);
if (pos != -1) line = line.substring(0,pos).trim();
// getting out the robots name
pos = line.indexOf(" ");
if (pos != -1) {
final String userAgent = line.substring(pos).trim();
isRule4AllAgents |= userAgent.equals("*");
isRule4YaCyAgent |= userAgent.toLowerCase().indexOf("yacy") >=0;
if (isRule4YaCyAgent) rule4YaCyFound = true;
}
} else if (lineUpper.startsWith(ROBOTS_CRAWL_DELAY)) {
- pos = line.indexOf(" ");
- if (pos != -1) {
- try {
- // the crawl delay can be a float number and means number of seconds
- crawlDelayMillis = (long) (1000.0 * Float.parseFloat(line.substring(pos).trim()));
- } catch (final NumberFormatException e) {
- // invalid crawling delay
- }
- }
+ inBlock = true;
+ if (isRule4YaCyAgent || isRule4AllAgents) {
+ pos = line.indexOf(" ");
+ if (pos != -1) {
+ try {
+ // the crawl delay can be a float number and means number of seconds
+ crawlDelayMillis = (long) (1000.0 * Float.parseFloat(line.substring(pos).trim()));
+ } catch (final NumberFormatException e) {
+ // invalid crawling delay
+ }
+ }
+ }
} else if (lineUpper.startsWith(ROBOTS_DISALLOW) ||
lineUpper.startsWith(ROBOTS_ALLOW)) {
inBlock = true;
final boolean isDisallowRule = lineUpper.startsWith(ROBOTS_DISALLOW);
if (isRule4YaCyAgent || isRule4AllAgents) {
// cutting off comments at the line end
pos = line.indexOf(ROBOTS_COMMENT);
if (pos != -1) line = line.substring(0,pos).trim();
// cutting of tailing *
if (line.endsWith("*")) line = line.substring(0,line.length()-1);
// getting the path
pos = line.indexOf(" ");
if (pos != -1) {
// getting the path
String path = line.substring(pos).trim();
// unencoding all special charsx
try {
path = URLDecoder.decode(path,"UTF-8");
} catch (final Exception e) {
/*
* url decoding failed. E.g. because of
* "Incomplete trailing escape (%) pattern"
*/
}
// escaping all occurences of ; because this char is used as special char in the Robots DB
path = path.replaceAll(RobotsTxt.ROBOTS_DB_PATH_SEPARATOR,"%3B");
// adding it to the pathlist
if (isDisallowRule) {
if (isRule4AllAgents) deny4AllAgents.add(path);
if (isRule4YaCyAgent) deny4YaCyAgent.add(path);
} else {
if (isRule4AllAgents) allow4AllAgents.add(path);
if (isRule4YaCyAgent) allow4YaCyAgent.add(path);
}
}
}
}
}
} catch (final IOException e) {}
allowList = (rule4YaCyFound) ? allow4YaCyAgent : allow4AllAgents;
denyList = (rule4YaCyFound) ? deny4YaCyAgent : deny4AllAgents;
}
public long crawlDelayMillis() {
return this.crawlDelayMillis;
}
public String sitemap() {
return this.sitemap;
}
public ArrayList<String> allowList() {
return this.allowList;
}
public ArrayList<String> denyList() {
return this.denyList;
}
}
| true | true |
private void parse(final BufferedReader reader) {
final ArrayList<String> deny4AllAgents = new ArrayList<String>();
final ArrayList<String> deny4YaCyAgent = new ArrayList<String>();
final ArrayList<String> allow4AllAgents = new ArrayList<String>();
final ArrayList<String> allow4YaCyAgent = new ArrayList<String>();
int pos;
String line = null, lineUpper = null;
sitemap = null;
crawlDelayMillis = 0;
boolean isRule4AllAgents = false,
isRule4YaCyAgent = false,
rule4YaCyFound = false,
inBlock = false;
try {
while ((line = reader.readLine()) != null) {
// replacing all tabs with spaces
line = line.replaceAll("\t"," ").trim();
lineUpper = line.toUpperCase();
if (line.length() == 0) {
// OLD: we have reached the end of the rule block
// rule4Yacy = false; inBlock = false;
// NEW: just ignore it
} else if (line.startsWith(ROBOTS_COMMENT)) {
// we can ignore this. Just a comment line
} else if (lineUpper.startsWith(ROBOTS_SITEMAP)) {
pos = line.indexOf(" ");
if (pos != -1) {
sitemap = line.substring(pos).trim();
}
} else if (lineUpper.startsWith(ROBOTS_USER_AGENT)) {
if (inBlock) {
// we have detected the start of a new block
inBlock = false;
isRule4AllAgents = false;
isRule4YaCyAgent = false;
crawlDelayMillis = 0; // each block has a separate delay
}
// cutting off comments at the line end
pos = line.indexOf(ROBOTS_COMMENT);
if (pos != -1) line = line.substring(0,pos).trim();
// getting out the robots name
pos = line.indexOf(" ");
if (pos != -1) {
final String userAgent = line.substring(pos).trim();
isRule4AllAgents |= userAgent.equals("*");
isRule4YaCyAgent |= userAgent.toLowerCase().indexOf("yacy") >=0;
if (isRule4YaCyAgent) rule4YaCyFound = true;
}
} else if (lineUpper.startsWith(ROBOTS_CRAWL_DELAY)) {
pos = line.indexOf(" ");
if (pos != -1) {
try {
// the crawl delay can be a float number and means number of seconds
crawlDelayMillis = (long) (1000.0 * Float.parseFloat(line.substring(pos).trim()));
} catch (final NumberFormatException e) {
// invalid crawling delay
}
}
} else if (lineUpper.startsWith(ROBOTS_DISALLOW) ||
lineUpper.startsWith(ROBOTS_ALLOW)) {
inBlock = true;
final boolean isDisallowRule = lineUpper.startsWith(ROBOTS_DISALLOW);
if (isRule4YaCyAgent || isRule4AllAgents) {
// cutting off comments at the line end
pos = line.indexOf(ROBOTS_COMMENT);
if (pos != -1) line = line.substring(0,pos).trim();
// cutting of tailing *
if (line.endsWith("*")) line = line.substring(0,line.length()-1);
// getting the path
pos = line.indexOf(" ");
if (pos != -1) {
// getting the path
String path = line.substring(pos).trim();
// unencoding all special charsx
try {
path = URLDecoder.decode(path,"UTF-8");
} catch (final Exception e) {
/*
* url decoding failed. E.g. because of
* "Incomplete trailing escape (%) pattern"
*/
}
// escaping all occurences of ; because this char is used as special char in the Robots DB
path = path.replaceAll(RobotsTxt.ROBOTS_DB_PATH_SEPARATOR,"%3B");
// adding it to the pathlist
if (isDisallowRule) {
if (isRule4AllAgents) deny4AllAgents.add(path);
if (isRule4YaCyAgent) deny4YaCyAgent.add(path);
} else {
if (isRule4AllAgents) allow4AllAgents.add(path);
if (isRule4YaCyAgent) allow4YaCyAgent.add(path);
}
}
}
}
}
} catch (final IOException e) {}
allowList = (rule4YaCyFound) ? allow4YaCyAgent : allow4AllAgents;
denyList = (rule4YaCyFound) ? deny4YaCyAgent : deny4AllAgents;
}
|
private void parse(final BufferedReader reader) {
final ArrayList<String> deny4AllAgents = new ArrayList<String>();
final ArrayList<String> deny4YaCyAgent = new ArrayList<String>();
final ArrayList<String> allow4AllAgents = new ArrayList<String>();
final ArrayList<String> allow4YaCyAgent = new ArrayList<String>();
int pos;
String line = null, lineUpper = null;
sitemap = null;
crawlDelayMillis = 0;
boolean isRule4AllAgents = false,
isRule4YaCyAgent = false,
rule4YaCyFound = false,
inBlock = false;
try {
while ((line = reader.readLine()) != null) {
// replacing all tabs with spaces
line = line.replaceAll("\t"," ").trim();
lineUpper = line.toUpperCase();
if (line.length() == 0) {
// OLD: we have reached the end of the rule block
// rule4Yacy = false; inBlock = false;
// NEW: just ignore it
} else if (line.startsWith(ROBOTS_COMMENT)) {
// we can ignore this. Just a comment line
} else if (lineUpper.startsWith(ROBOTS_SITEMAP)) {
pos = line.indexOf(" ");
if (pos != -1) {
sitemap = line.substring(pos).trim();
}
} else if (lineUpper.startsWith(ROBOTS_USER_AGENT)) {
if (inBlock) {
// we have detected the start of a new block
inBlock = false;
isRule4AllAgents = false;
isRule4YaCyAgent = false;
crawlDelayMillis = 0; // each block has a separate delay
}
// cutting off comments at the line end
pos = line.indexOf(ROBOTS_COMMENT);
if (pos != -1) line = line.substring(0,pos).trim();
// getting out the robots name
pos = line.indexOf(" ");
if (pos != -1) {
final String userAgent = line.substring(pos).trim();
isRule4AllAgents |= userAgent.equals("*");
isRule4YaCyAgent |= userAgent.toLowerCase().indexOf("yacy") >=0;
if (isRule4YaCyAgent) rule4YaCyFound = true;
}
} else if (lineUpper.startsWith(ROBOTS_CRAWL_DELAY)) {
inBlock = true;
if (isRule4YaCyAgent || isRule4AllAgents) {
pos = line.indexOf(" ");
if (pos != -1) {
try {
// the crawl delay can be a float number and means number of seconds
crawlDelayMillis = (long) (1000.0 * Float.parseFloat(line.substring(pos).trim()));
} catch (final NumberFormatException e) {
// invalid crawling delay
}
}
}
} else if (lineUpper.startsWith(ROBOTS_DISALLOW) ||
lineUpper.startsWith(ROBOTS_ALLOW)) {
inBlock = true;
final boolean isDisallowRule = lineUpper.startsWith(ROBOTS_DISALLOW);
if (isRule4YaCyAgent || isRule4AllAgents) {
// cutting off comments at the line end
pos = line.indexOf(ROBOTS_COMMENT);
if (pos != -1) line = line.substring(0,pos).trim();
// cutting of tailing *
if (line.endsWith("*")) line = line.substring(0,line.length()-1);
// getting the path
pos = line.indexOf(" ");
if (pos != -1) {
// getting the path
String path = line.substring(pos).trim();
// unencoding all special charsx
try {
path = URLDecoder.decode(path,"UTF-8");
} catch (final Exception e) {
/*
* url decoding failed. E.g. because of
* "Incomplete trailing escape (%) pattern"
*/
}
// escaping all occurences of ; because this char is used as special char in the Robots DB
path = path.replaceAll(RobotsTxt.ROBOTS_DB_PATH_SEPARATOR,"%3B");
// adding it to the pathlist
if (isDisallowRule) {
if (isRule4AllAgents) deny4AllAgents.add(path);
if (isRule4YaCyAgent) deny4YaCyAgent.add(path);
} else {
if (isRule4AllAgents) allow4AllAgents.add(path);
if (isRule4YaCyAgent) allow4YaCyAgent.add(path);
}
}
}
}
}
} catch (final IOException e) {}
allowList = (rule4YaCyFound) ? allow4YaCyAgent : allow4AllAgents;
denyList = (rule4YaCyFound) ? deny4YaCyAgent : deny4AllAgents;
}
|
diff --git a/bundles/org.eclipse.orion.server.servlets/src/org/eclipse/orion/internal/server/servlets/workspace/WorkspaceResourceHandler.java b/bundles/org.eclipse.orion.server.servlets/src/org/eclipse/orion/internal/server/servlets/workspace/WorkspaceResourceHandler.java
index cbf1c71e..bfc75a95 100644
--- a/bundles/org.eclipse.orion.server.servlets/src/org/eclipse/orion/internal/server/servlets/workspace/WorkspaceResourceHandler.java
+++ b/bundles/org.eclipse.orion.server.servlets/src/org/eclipse/orion/internal/server/servlets/workspace/WorkspaceResourceHandler.java
@@ -1,597 +1,601 @@
/*******************************************************************************
* Copyright (c) 2010, 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.orion.internal.server.servlets.workspace;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.StringTokenizer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.runtime.*;
import org.eclipse.orion.internal.server.servlets.*;
import org.eclipse.orion.server.core.*;
import org.eclipse.orion.server.servlets.OrionServlet;
import org.eclipse.osgi.util.NLS;
import org.json.*;
/**
* Handles requests against a single workspace.
*/
public class WorkspaceResourceHandler extends WebElementResourceHandler<WebWorkspace> {
static final int CREATE_COPY = 0x1;
static final int CREATE_MOVE = 0x2;
static final int CREATE_NO_OVERWRITE = 0x4;
private final ServletResourceHandler<IStatus> statusHandler;
/**
* Returns the location of the project's content (conforming to File REST API).
*/
static URI computeProjectURI(URI parentLocation, WebWorkspace workspace, WebProject project) {
return URIUtil.append(parentLocation, ".." + Activator.LOCATION_FILE_SERVLET + '/' + workspace.getId() + '/' + project.getName() + '/'); //$NON-NLS-1$
}
/**
* Returns a JSON representation of the workspace, conforming to Orion
* workspace API protocol.
* @param workspace The workspace to store
* @param requestLocation The location of the current request
* @param baseLocation The base location for the workspace servlet
*/
public static JSONObject toJSON(WebWorkspace workspace, URI requestLocation, URI baseLocation) {
JSONObject result = WebElementResourceHandler.toJSON(workspace);
JSONArray projects = workspace.getProjectsJSON();
URI workspaceLocation = URIUtil.append(baseLocation, workspace.getId());
URI projectBaseLocation = URIUtil.append(workspaceLocation, "project"); //$NON-NLS-1$
if (projects == null)
projects = new JSONArray();
//augment project objects with their location
for (int i = 0; i < projects.length(); i++) {
try {
JSONObject project = (JSONObject) projects.get(i);
//this is the location of the project metadata
project.put(ProtocolConstants.KEY_LOCATION, URIUtil.append(projectBaseLocation, project.getString(ProtocolConstants.KEY_ID)));
} catch (JSONException e) {
//ignore malformed children
}
}
//add basic fields to workspace result
try {
result.put(ProtocolConstants.KEY_LOCATION, workspaceLocation);
result.put(ProtocolConstants.KEY_CHILDREN_LOCATION, workspaceLocation);
result.put(ProtocolConstants.KEY_DRIVE_LOCATION, URIUtil.append(workspaceLocation, ProtocolConstants.PATH_DRIVE));
result.put(ProtocolConstants.KEY_PROJECTS, projects);
result.put(ProtocolConstants.KEY_DIRECTORY, "true"); //$NON-NLS-1$
} catch (JSONException e) {
//can't happen because key and value are well-formed
}
//is caller requesting local children
boolean requestLocal = !ProtocolConstants.PATH_DRIVE.equals(URIUtil.lastSegment(requestLocation));
//add children element to conform to file API structure
JSONArray children = new JSONArray();
for (int i = 0; i < projects.length(); i++) {
try {
WebProject project = WebProject.fromId(projects.getJSONObject(i).getString(ProtocolConstants.KEY_ID));
+ //remote folders are listed separately
+ boolean isLocal = true;
+ IFileStore projectStore = null;
+ try {
+ projectStore = project.getProjectStore();
+ isLocal = EFS.SCHEME_FILE.equals(projectStore.getFileSystem().getScheme());
+ } catch (CoreException e) {
+ //ignore and treat as local
+ }
+ if (requestLocal) {
+ //only include local children
+ if (!isLocal)
+ continue;
+ } else {
+ //only include remote children
+ if (isLocal)
+ continue;
+ }
JSONObject child = new JSONObject();
child.put(ProtocolConstants.KEY_NAME, project.getName());
child.put(ProtocolConstants.KEY_DIRECTORY, true);
//this is the location of the project file contents
URI contentLocation = computeProjectURI(baseLocation, workspace, project);
child.put(ProtocolConstants.KEY_LOCATION, contentLocation);
try {
- child.put(ProtocolConstants.KEY_LOCAL_TIMESTAMP, project.getProjectStore().fetchInfo(EFS.NONE, null).getLastModified());
+ if (projectStore != null)
+ child.put(ProtocolConstants.KEY_LOCAL_TIMESTAMP, projectStore.fetchInfo(EFS.NONE, null).getLastModified());
} catch (CoreException coreException) {
//just omit the timestamp in this case because the project location is unreachable
}
try {
child.put(ProtocolConstants.KEY_CHILDREN_LOCATION, new URI(contentLocation.getScheme(), contentLocation.getUserInfo(), contentLocation.getHost(), contentLocation.getPort(), contentLocation.getPath(), ProtocolConstants.PARM_DEPTH + "=1", contentLocation.getFragment())); //$NON-NLS-1$
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
child.put(ProtocolConstants.KEY_ID, project.getId());
- //remote folders are listed separately
- boolean isLocal = true;
- try {
- isLocal = EFS.SCHEME_FILE.equals(project.getProjectStore().getFileSystem().getScheme());
- } catch (CoreException e) {
- //ignore and treat as local
- }
- if (requestLocal) {
- //only include local children
- if (isLocal)
- children.put(child);
- } else {
- //only include remote children
- if (!isLocal)
- children.put(child);
- }
+ children.put(child);
} catch (JSONException e) {
//ignore malformed children
}
}
try {
result.put(ProtocolConstants.KEY_CHILDREN, children);
} catch (JSONException e) {
//cannot happen
}
return result;
}
public WorkspaceResourceHandler(ServletResourceHandler<IStatus> statusHandler) {
this.statusHandler = statusHandler;
}
public static void computeProjectLocation(HttpServletRequest request, WebProject project, String location, boolean init) throws URISyntaxException, CoreException {
String user = request.getRemoteUser();
URI contentURI;
if (location == null) {
contentURI = generateProjectLocation(project, user);
} else {
//use the content location specified by the user
try {
contentURI = new URI(location);
EFS.getFileSystem(contentURI.getScheme());//check if we support this scheme
} catch (Exception e) {
//if this is not a valid URI or scheme try to parse it as file path
contentURI = new File(location).toURI();
}
if (init) {
project.setContentLocation(contentURI);
IFileStore child = project.getProjectStore(request);
child.mkdir(EFS.NONE, null);
}
}
project.setContentLocation(contentURI);
}
/**
* Generates a file system location for newly created project
*/
private static URI generateProjectLocation(WebProject project, String user) throws CoreException, URISyntaxException {
URI platformLocationURI = Activator.getDefault().getRootLocationURI();
IFileStore root = EFS.getStore(platformLocationURI);
//consult layout preference
String layout = PreferenceHelper.getString(ServerConstants.CONFIG_FILE_LAYOUT, "flat").toLowerCase(); //$NON-NLS-1$
IFileStore projectStore;
URI location;
if ("usertree".equals(layout) && user != null) { //$NON-NLS-1$
//the user-tree layout organises projects by the user who created it
String userPrefix = user.substring(0, Math.min(2, user.length()));
projectStore = root.getChild(userPrefix).getChild(user).getChild(project.getId());
location = projectStore.toURI();
} else {
//default layout is a flat list of projects at the root
projectStore = root.getChild(project.getId());
location = new URI(null, projectStore.getName(), null);
}
projectStore.mkdir(EFS.NONE, null);
return location;
}
/**
* Returns a bit-mask of create options as specified by the request.
*/
private int getCreateOptions(HttpServletRequest request) {
int result = 0;
String optionString = request.getHeader(ProtocolConstants.HEADER_CREATE_OPTIONS);
if (optionString != null) {
for (String option : optionString.split(",")) { //$NON-NLS-1$
if (ProtocolConstants.OPTION_COPY.equalsIgnoreCase(option))
result |= CREATE_COPY;
else if (ProtocolConstants.OPTION_MOVE.equalsIgnoreCase(option))
result |= CREATE_MOVE;
else if (ProtocolConstants.OPTION_NO_OVERWRITE.equalsIgnoreCase(option))
result |= CREATE_NO_OVERWRITE;
}
}
return result;
}
private boolean getInit(JSONObject toAdd) {
return Boolean.valueOf(toAdd.optBoolean(ProtocolConstants.KEY_CREATE_IF_DOESNT_EXIST));
}
private boolean handleAddOrRemoveProject(HttpServletRequest request, HttpServletResponse response, WebWorkspace workspace) throws IOException, JSONException, ServletException {
//make sure required fields are set
JSONObject data = OrionServlet.readJSONRequest(request);
if (!data.isNull("Remove")) //$NON-NLS-1$
return handleRemoveProject(request, response, workspace);
int options = getCreateOptions(request);
if ((options & (CREATE_COPY | CREATE_MOVE)) != 0)
return handleCopyMoveProject(request, response, workspace, data);
return handleAddProject(request, response, workspace, data);
}
private boolean handleAddProject(HttpServletRequest request, HttpServletResponse response, WebWorkspace workspace, JSONObject data) throws IOException, ServletException {
//make sure required fields are set
JSONObject toAdd = data;
String id = toAdd.optString(ProtocolConstants.KEY_ID, null);
String name = toAdd.optString(ProtocolConstants.KEY_NAME, null);
if (name == null)
name = request.getHeader(ProtocolConstants.HEADER_SLUG);
if (!validateProjectName(workspace, name, request, response))
return true;
if (id == null)
id = WebProject.nextProjectId();
WebProject project = WebProject.fromId(id);
project.setName(name);
String content = toAdd.optString(ProtocolConstants.KEY_CONTENT_LOCATION, null);
if (!isAllowedLinkDestination(content, request.getRemoteUser())) {
String msg = NLS.bind("Cannot link to server path {0}. Use the orion.file.allowedPaths property to specify server locations where content can be linked.", content);
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_FORBIDDEN, msg, null));
}
try {
computeProjectLocation(request, project, content, getInit(toAdd));
} catch (CoreException e) {
if (handleAuthFailure(request, response, e))
return true;
//we are unable to write in the platform location!
String msg = NLS.bind("Server content location could not be written: {0}", Activator.getDefault().getRootLocationURI());
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
} catch (URISyntaxException e) {
String msg = NLS.bind("Invalid project location: {0}", content);
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, e));
}
try {
//If all went well, add project to workspace
addProject(request.getRemoteUser(), workspace, project);
} catch (CoreException e) {
String msg = "Error persisting project state";
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
}
//serialize the new project in the response
//the baseLocation should be the workspace location
URI baseLocation = getURI(request);
JSONObject result = WebProjectResourceHandler.toJSON(workspace, project, baseLocation);
OrionServlet.writeJSONResponse(request, response, result);
//add project location to response header
response.setHeader(ProtocolConstants.HEADER_LOCATION, result.optString(ProtocolConstants.KEY_LOCATION));
response.setStatus(HttpServletResponse.SC_CREATED);
return true;
}
/**
* Handle a project copy or move request. Returns <code>true</code> if the request
* was handled (either success or failure). Returns <code>false</code> if this method
* does not know how to handle the request.
*/
private boolean handleCopyMoveProject(HttpServletRequest request, HttpServletResponse response, WebWorkspace workspace, JSONObject data) throws ServletException, IOException {
String sourceLocation = data.optString(ProtocolConstants.HEADER_LOCATION);
String sourceId = projectForLocation(request, response, sourceLocation);
//null result means there was an error and we already handled it
if (sourceId == null)
return true;
boolean sourceExists = WebProject.exists(sourceId);
if (!sourceExists) {
handleError(request, response, HttpServletResponse.SC_BAD_REQUEST, NLS.bind("Source does not exist: {0}", sourceId));
return true;
}
int options = getCreateOptions(request);
if (!validateOptions(request, response, options))
return true;
//get the slug first
String destinationName = request.getHeader(ProtocolConstants.HEADER_SLUG);
//If the data has a name then it must be used due to UTF-8 issues with names Bug 376671
try {
if (data != null && data.has("Name")) {
destinationName = data.getString("Name");
}
} catch (JSONException e) {
}
if (!validateProjectName(workspace, destinationName, request, response))
return true;
WebProject sourceProject = WebProject.fromId(sourceId);
if ((options & CREATE_MOVE) != 0) {
return handleMoveProject(request, response, workspace, sourceProject, sourceLocation, destinationName);
} else if ((options & CREATE_COPY) != 0) {
return handleCopyProject(request, response, workspace, sourceProject, destinationName);
}
//if we got here, it isn't a copy or a move, so we don't know how to handle the request
return false;
}
/**
* Implementation of project copy
* Returns <code>false</code> if this method doesn't know how to intepret the request.
*/
private boolean handleCopyProject(HttpServletRequest request, HttpServletResponse response, WebWorkspace workspace, WebProject sourceProject, String destinationName) throws IOException, ServletException {
//first create the destination project
String destinationId = WebProject.nextProjectId();
JSONObject projectInfo = new JSONObject();
try {
projectInfo.put(ProtocolConstants.KEY_ID, destinationId);
projectInfo.put(ProtocolConstants.KEY_NAME, destinationName);
} catch (JSONException e) {
//should never happen
throw new RuntimeException(e);
}
handleAddProject(request, response, workspace, projectInfo);
//copy the project data from source
WebProject destinationProject = WebProject.fromId(destinationId);
String sourceName = sourceProject.getName();
try {
copyProjectContents(sourceProject, destinationProject);
} catch (CoreException e) {
handleError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, NLS.bind("Error copying project {0} to {1}", sourceName, destinationName));
return true;
}
URI baseLocation = getURI(request);
JSONObject result = WebProjectResourceHandler.toJSON(workspace, destinationProject, baseLocation);
OrionServlet.writeJSONResponse(request, response, result);
response.setHeader(ProtocolConstants.HEADER_LOCATION, result.optString(ProtocolConstants.KEY_LOCATION, "")); //$NON-NLS-1$
response.setStatus(HttpServletResponse.SC_CREATED);
return true;
}
/**
* Implementation of project move. Returns whether the move requested was handled.
* Returns <code>false</code> if this method doesn't know how to interpret the request.
*/
private boolean handleMoveProject(HttpServletRequest request, HttpServletResponse response, WebWorkspace workspace, WebProject sourceProject, String sourceLocation, String destinationName) throws ServletException, IOException {
String sourceName = sourceProject.getName();
//a project move is simply a rename
sourceProject.setName(destinationName);
try {
sourceProject.save();
} catch (CoreException e) {
String msg = NLS.bind("Error persisting project state: {0}", sourceName);
return handleError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
}
//location doesn't change on move project
URI baseLocation = getURI(request);
JSONObject result = WebProjectResourceHandler.toJSON(workspace, sourceProject, baseLocation);
OrionServlet.writeJSONResponse(request, response, result);
response.setHeader(ProtocolConstants.HEADER_LOCATION, sourceLocation);
response.setStatus(HttpServletResponse.SC_OK);
return true;
}
/**
* Copies the content of one project to the location of a second project.
*/
private void copyProjectContents(WebProject sourceProject, WebProject destinationProject) throws CoreException {
sourceProject.getProjectStore().copy(destinationProject.getProjectStore(), EFS.OVERWRITE, null);
}
private boolean handleError(HttpServletRequest request, HttpServletResponse response, int httpCode, String message) throws ServletException {
return handleError(request, response, httpCode, message, null);
}
private boolean handleError(HttpServletRequest request, HttpServletResponse response, int httpCode, String message, Throwable cause) throws ServletException {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, httpCode, message, cause));
}
private boolean handleGetWorkspaceMetadata(HttpServletRequest request, HttpServletResponse response, WebWorkspace workspace) throws IOException {
//we need the base location for the workspace servlet. Since this is a GET
//on workspace servlet we need to strip off all but the first segment of the request path
URI requestLocation = getURI(request);
URI baseLocation;
try {
baseLocation = new URI(requestLocation.getScheme(), requestLocation.getUserInfo(), requestLocation.getHost(), requestLocation.getPort(), Activator.LOCATION_WORKSPACE_SERVLET, null, null);
} catch (URISyntaxException e) {
//should never happen
throw new RuntimeException(e);
}
OrionServlet.writeJSONResponse(request, response, toJSON(workspace, requestLocation, baseLocation));
return true;
}
private boolean handlePutWorkspaceMetadata(HttpServletRequest request, HttpServletResponse response, WebWorkspace workspace) {
return false;
}
private boolean handleRemoveProject(HttpServletRequest request, HttpServletResponse response, WebWorkspace workspace) throws IOException, JSONException, ServletException {
IPath path = new Path(request.getPathInfo());
//format is /workspaceId/project/<projectId>
if (path.segmentCount() != 3)
return false;
String projectId = path.segment(2);
if (!WebProject.exists(projectId)) {
//nothing to do
return true;
}
WebProject project = WebProject.fromId(projectId);
try {
removeProject(request.getRemoteUser(), workspace, project);
} catch (CoreException e) {
ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error removing project", e);
LogHelper.log(error);
return statusHandler.handleRequest(request, response, error);
}
return true;
}
@Override
public boolean handleRequest(HttpServletRequest request, HttpServletResponse response, WebWorkspace workspace) throws ServletException {
if (workspace == null)
return statusHandler.handleRequest(request, response, new Status(IStatus.ERROR, Activator.PI_SERVER_SERVLETS, "Workspace not specified"));
//we could split and handle different API versions here if needed
try {
switch (getMethod(request)) {
case GET :
return handleGetWorkspaceMetadata(request, response, workspace);
case PUT :
return handlePutWorkspaceMetadata(request, response, workspace);
case POST :
return handleAddOrRemoveProject(request, response, workspace);
case DELETE :
//TBD could also handle deleting the workspace itself
return handleRemoveProject(request, response, workspace);
default :
//fall through
}
} catch (IOException e) {
String msg = NLS.bind("Error handling request against workspace {0}", workspace.getId());
statusHandler.handleRequest(request, response, new Status(IStatus.ERROR, Activator.PI_SERVER_SERVLETS, msg, e));
} catch (JSONException e) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Syntax error in request", e));
}
return false;
}
private boolean isAllowedLinkDestination(String content, String user) {
if (content == null) {
return true;
}
String prefixes = PreferenceHelper.getString(ServerConstants.CONFIG_FILE_ALLOWED_PATHS);
if (prefixes == null)
prefixes = ServletTestingSupport.allowedPrefixes;
if (prefixes != null) {
StringTokenizer t = new StringTokenizer(prefixes, ","); //$NON-NLS-1$
while (t.hasMoreTokens()) {
String prefix = t.nextToken();
if (content.startsWith(prefix)) {
return true;
}
}
}
String userArea = System.getProperty(Activator.PROP_USER_AREA);
if (userArea == null)
return false;
IPath path = new Path(userArea).append(user);
URI contentURI = null;
//use the content location specified by the user
try {
URI candidate = new URI(content);
//check if we support this scheme
String scheme = candidate.getScheme();
if (scheme != null) {
if (EFS.getFileSystem(scheme) != null)
contentURI = candidate;
//we only restrict local file system access
if (!EFS.SCHEME_FILE.equals(scheme))
return true;
}
} catch (URISyntaxException e) {
//if this is not a valid URI try to parse it as file path below
} catch (CoreException e) {
//if we don't support given scheme try to parse as location as a file path below
}
if (contentURI == null)
contentURI = new File(content).toURI();
if (contentURI.toString().startsWith(path.toFile().toURI().toString()))
return true;
return false;
}
/**
* Returns the project id for the given project location. If the project id cannot
* be determined, this method will handle setting an appropriate HTTP response
* and return <code>null</code>.
*/
private String projectForLocation(HttpServletRequest request, HttpServletResponse response, String sourceLocation) throws ServletException {
try {
if (sourceLocation != null) {
URI sourceURI = new URI(sourceLocation);
String path = sourceURI.getPath();
if (path != null) {
String id = new Path(path).lastSegment();
if (id != null)
return id;
}
}
} catch (URISyntaxException e) {
//fall through and fail below
}
handleError(request, response, HttpServletResponse.SC_BAD_REQUEST, NLS.bind("Invalid source location for copy/move request: {0}", sourceLocation));
return null;
}
public static void addProject(String user, WebWorkspace workspace, WebProject project) throws CoreException {
//add project to workspace
workspace.addProject(project);
//save the workspace and project metadata
project.save();
workspace.save();
}
public static void removeProject(String user, WebWorkspace workspace, WebProject project) throws CoreException {
// remove the project folder
URI contentURI = project.getContentLocation();
// don't remove linked projects
if (project.getId().equals(contentURI.toString())) {
URI platformLocationURI = Activator.getDefault().getRootLocationURI();
IFileStore child;
child = EFS.getStore(platformLocationURI).getChild(project.getId());
if (child.fetchInfo(EFS.NONE, null).exists()) {
child.delete(EFS.NONE, null);
}
}
//If all went well, remove project from workspace
workspace.removeProject(project);
//remove project metadata
project.remove();
//save the workspace and project metadata
project.save();
workspace.save();
}
/**
* Asserts that request options are valid. If options are not valid then this method handles the request response and return false. If the options
* are valid this method return true.
*/
private boolean validateOptions(HttpServletRequest request, HttpServletResponse response, int options) throws ServletException {
//operation cannot be both copy and move
int copyMove = CREATE_COPY | CREATE_MOVE;
if ((options & copyMove) == copyMove) {
handleError(request, response, HttpServletResponse.SC_BAD_REQUEST, "Syntax error in request");
return false;
}
return true;
}
/**
* Validates that the provided project name is valid. Returns <code>true</code> if the
* project name is valid, and <code>false</code> otherwise. This method takes care of
* setting the error response when the project name is not valid.
*/
private boolean validateProjectName(WebWorkspace workspace, String name, HttpServletRequest request, HttpServletResponse response) throws ServletException {
if (name == null || name.trim().length() == 0) {
statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Project name cannot be empty", null));
return false;
}
if (name.contains("/")) { //$NON-NLS-1$
statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, NLS.bind("Invalid project name: {0}", name), null));
return false;
}
if (workspace.getProjectByName(name) != null) {
statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, NLS.bind("Duplicate project name: {0}", name), null));
return false;
}
return true;
}
}
| false | true |
public static JSONObject toJSON(WebWorkspace workspace, URI requestLocation, URI baseLocation) {
JSONObject result = WebElementResourceHandler.toJSON(workspace);
JSONArray projects = workspace.getProjectsJSON();
URI workspaceLocation = URIUtil.append(baseLocation, workspace.getId());
URI projectBaseLocation = URIUtil.append(workspaceLocation, "project"); //$NON-NLS-1$
if (projects == null)
projects = new JSONArray();
//augment project objects with their location
for (int i = 0; i < projects.length(); i++) {
try {
JSONObject project = (JSONObject) projects.get(i);
//this is the location of the project metadata
project.put(ProtocolConstants.KEY_LOCATION, URIUtil.append(projectBaseLocation, project.getString(ProtocolConstants.KEY_ID)));
} catch (JSONException e) {
//ignore malformed children
}
}
//add basic fields to workspace result
try {
result.put(ProtocolConstants.KEY_LOCATION, workspaceLocation);
result.put(ProtocolConstants.KEY_CHILDREN_LOCATION, workspaceLocation);
result.put(ProtocolConstants.KEY_DRIVE_LOCATION, URIUtil.append(workspaceLocation, ProtocolConstants.PATH_DRIVE));
result.put(ProtocolConstants.KEY_PROJECTS, projects);
result.put(ProtocolConstants.KEY_DIRECTORY, "true"); //$NON-NLS-1$
} catch (JSONException e) {
//can't happen because key and value are well-formed
}
//is caller requesting local children
boolean requestLocal = !ProtocolConstants.PATH_DRIVE.equals(URIUtil.lastSegment(requestLocation));
//add children element to conform to file API structure
JSONArray children = new JSONArray();
for (int i = 0; i < projects.length(); i++) {
try {
WebProject project = WebProject.fromId(projects.getJSONObject(i).getString(ProtocolConstants.KEY_ID));
JSONObject child = new JSONObject();
child.put(ProtocolConstants.KEY_NAME, project.getName());
child.put(ProtocolConstants.KEY_DIRECTORY, true);
//this is the location of the project file contents
URI contentLocation = computeProjectURI(baseLocation, workspace, project);
child.put(ProtocolConstants.KEY_LOCATION, contentLocation);
try {
child.put(ProtocolConstants.KEY_LOCAL_TIMESTAMP, project.getProjectStore().fetchInfo(EFS.NONE, null).getLastModified());
} catch (CoreException coreException) {
//just omit the timestamp in this case because the project location is unreachable
}
try {
child.put(ProtocolConstants.KEY_CHILDREN_LOCATION, new URI(contentLocation.getScheme(), contentLocation.getUserInfo(), contentLocation.getHost(), contentLocation.getPort(), contentLocation.getPath(), ProtocolConstants.PARM_DEPTH + "=1", contentLocation.getFragment())); //$NON-NLS-1$
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
child.put(ProtocolConstants.KEY_ID, project.getId());
//remote folders are listed separately
boolean isLocal = true;
try {
isLocal = EFS.SCHEME_FILE.equals(project.getProjectStore().getFileSystem().getScheme());
} catch (CoreException e) {
//ignore and treat as local
}
if (requestLocal) {
//only include local children
if (isLocal)
children.put(child);
} else {
//only include remote children
if (!isLocal)
children.put(child);
}
} catch (JSONException e) {
//ignore malformed children
}
}
try {
result.put(ProtocolConstants.KEY_CHILDREN, children);
} catch (JSONException e) {
//cannot happen
}
return result;
}
|
public static JSONObject toJSON(WebWorkspace workspace, URI requestLocation, URI baseLocation) {
JSONObject result = WebElementResourceHandler.toJSON(workspace);
JSONArray projects = workspace.getProjectsJSON();
URI workspaceLocation = URIUtil.append(baseLocation, workspace.getId());
URI projectBaseLocation = URIUtil.append(workspaceLocation, "project"); //$NON-NLS-1$
if (projects == null)
projects = new JSONArray();
//augment project objects with their location
for (int i = 0; i < projects.length(); i++) {
try {
JSONObject project = (JSONObject) projects.get(i);
//this is the location of the project metadata
project.put(ProtocolConstants.KEY_LOCATION, URIUtil.append(projectBaseLocation, project.getString(ProtocolConstants.KEY_ID)));
} catch (JSONException e) {
//ignore malformed children
}
}
//add basic fields to workspace result
try {
result.put(ProtocolConstants.KEY_LOCATION, workspaceLocation);
result.put(ProtocolConstants.KEY_CHILDREN_LOCATION, workspaceLocation);
result.put(ProtocolConstants.KEY_DRIVE_LOCATION, URIUtil.append(workspaceLocation, ProtocolConstants.PATH_DRIVE));
result.put(ProtocolConstants.KEY_PROJECTS, projects);
result.put(ProtocolConstants.KEY_DIRECTORY, "true"); //$NON-NLS-1$
} catch (JSONException e) {
//can't happen because key and value are well-formed
}
//is caller requesting local children
boolean requestLocal = !ProtocolConstants.PATH_DRIVE.equals(URIUtil.lastSegment(requestLocation));
//add children element to conform to file API structure
JSONArray children = new JSONArray();
for (int i = 0; i < projects.length(); i++) {
try {
WebProject project = WebProject.fromId(projects.getJSONObject(i).getString(ProtocolConstants.KEY_ID));
//remote folders are listed separately
boolean isLocal = true;
IFileStore projectStore = null;
try {
projectStore = project.getProjectStore();
isLocal = EFS.SCHEME_FILE.equals(projectStore.getFileSystem().getScheme());
} catch (CoreException e) {
//ignore and treat as local
}
if (requestLocal) {
//only include local children
if (!isLocal)
continue;
} else {
//only include remote children
if (isLocal)
continue;
}
JSONObject child = new JSONObject();
child.put(ProtocolConstants.KEY_NAME, project.getName());
child.put(ProtocolConstants.KEY_DIRECTORY, true);
//this is the location of the project file contents
URI contentLocation = computeProjectURI(baseLocation, workspace, project);
child.put(ProtocolConstants.KEY_LOCATION, contentLocation);
try {
if (projectStore != null)
child.put(ProtocolConstants.KEY_LOCAL_TIMESTAMP, projectStore.fetchInfo(EFS.NONE, null).getLastModified());
} catch (CoreException coreException) {
//just omit the timestamp in this case because the project location is unreachable
}
try {
child.put(ProtocolConstants.KEY_CHILDREN_LOCATION, new URI(contentLocation.getScheme(), contentLocation.getUserInfo(), contentLocation.getHost(), contentLocation.getPort(), contentLocation.getPath(), ProtocolConstants.PARM_DEPTH + "=1", contentLocation.getFragment())); //$NON-NLS-1$
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
child.put(ProtocolConstants.KEY_ID, project.getId());
children.put(child);
} catch (JSONException e) {
//ignore malformed children
}
}
try {
result.put(ProtocolConstants.KEY_CHILDREN, children);
} catch (JSONException e) {
//cannot happen
}
return result;
}
|
diff --git a/concourse/src/main/java/org/cinchapi/concourse/Concourse.java b/concourse/src/main/java/org/cinchapi/concourse/Concourse.java
index 7a443a980..484851d19 100644
--- a/concourse/src/main/java/org/cinchapi/concourse/Concourse.java
+++ b/concourse/src/main/java/org/cinchapi/concourse/Concourse.java
@@ -1,1595 +1,1597 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2013-2014 Jeff Nelson, Cinchapi Software Collective
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.cinchapi.concourse;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import javax.annotation.Nullable;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.cinchapi.concourse.annotate.CompoundOperation;
import org.cinchapi.concourse.config.ConcourseConfiguration;
import org.cinchapi.concourse.security.ClientSecurity;
import org.cinchapi.concourse.thrift.AccessToken;
import org.cinchapi.concourse.thrift.ConcourseService;
import org.cinchapi.concourse.thrift.Operator;
import org.cinchapi.concourse.thrift.TObject;
import org.cinchapi.concourse.thrift.TransactionToken;
import org.cinchapi.concourse.time.Time;
import org.cinchapi.concourse.util.Convert;
import org.cinchapi.concourse.util.TLinkedTableMap;
import org.cinchapi.concourse.util.Transformers;
import org.cinchapi.concourse.util.TLinkedHashMap;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
/**
* <p>
* Concourse is a schemaless and distributed version control database with
* optimistic availability, serializable transactions and full-text search.
* Concourse provides a more intuitive approach to data management that is easy
* to deploy, access and scale with minimal tuning while also maintaining the
* referential integrity and ACID characteristics of traditional database
* systems.
* </p>
* <h2>Data Model</h2>
* <p>
* The Concourse data model is lightweight and flexible which enables it to
* support any kind of data at very large scales. Concourse trades unnecessary
* structural notions of schemas, tables and indexes for a more natural modeling
* of data based solely on the following concepts:
* </p>
* <p>
* <ul>
* <li><strong>Record</strong> — A logical grouping of data about a single
* person, place, or thing (i.e. an object). Each {@code record} is a collection
* of key/value pairs that are together identified by a unique primary key.
* <li><strong>Key</strong> — An attribute that maps to a set of
* <em>one or more</em> distinct {@code values}. A {@code record} can have many
* different {@code keys}, and the {@code keys} in one {@code record} do not
* affect those in another {@code record}.
* <li><strong>Value</strong> — A dynamically typed quantity that is
* mapped from a {@code key} in a {@code record}.
* </ul>
* </p>
* <h4>Data Types</h4>
* <p>
* Concourse natively stores most of the Java primitives: boolean, double,
* float, integer, long, and string (UTF-8). Otherwise, the value of the
* {@link #toString()} method for the Object is stored.
* </p>
* <h4>Links</h4>
* <p>
* Concourse supports linking a {@code key} in one {@code record} to another
* {@code record}. Links are one-directional, but it is possible to add two
* links that are the inverse of each other to simulate bi-directionality (i.e.
* link "friend" in Record 1 to Record 2 and link "friend" in Record 2 to Record
* 1).
* </p>
* <h2>Transactions</h2>
* <p>
* By default, Concourse conducts every operation in {@code autocommit} mode
* where every change is immediately written. Concourse also supports the
* ability to stage a group of operations in transactions that are atomic,
* consistent, isolated, and durable using the {@link #stage()},
* {@link #commit()} and {@link #abort()} methods.
*
* </p>
*
* @author jnelson
*/
public abstract class Concourse {
/**
* Create a new Client connection using the details provided in
* {@code concourse_client.prefs}. If the prefs file does not exist or does
* not contain connection information, then the default connection details
* ({@code admin@localhost:1717}) will be used.
*
* @return the database handler
*/
public static Concourse connect() {
return new Client();
}
/**
* Create a new Client connection for {@code username}@{@code host}:
* {@code port} using {@code password}.
*
* @param host
* @param port
* @param username
* @param password
* @return the database handler
*/
public static Concourse connect(String host, int port, String username,
String password) {
return new Client(host, port, username, password);
}
/**
* Discard any changes that are currently staged for commit.
* <p>
* After this function returns, Concourse will return to {@code autocommit}
* mode and all subsequent changes will be committed immediately.
* </p>
*/
public abstract void abort();
/**
* Add {@code key} as {@code value} in each of the {@code records} if it is
* not already contained.
*
* @param key
* @param value
* @param records
* @return a mapping from each record to a boolean indicating if
* {@code value} is added
*/
@CompoundOperation
public abstract Map<Long, Boolean> add(String key, Object value,
Collection<Long> records);
/**
* Add {@code key} as {@code value} to {@code record} if it is not already
* contained.
*
* @param key
* @param value
* @param record
* @return {@code true} if {@code value} is added
*/
public abstract <T> boolean add(String key, T value, long record);
/**
* Audit {@code record} and return a log of revisions.
*
* @param record
* @return a mapping from timestamp to a description of a revision
*/
public abstract Map<Timestamp, String> audit(long record);
/**
* Audit {@code key} in {@code record} and return a log of revisions.
*
* @param key
* @param record
* @return a mapping from timestamp to a description of a revision
*/
public abstract Map<Timestamp, String> audit(String key, long record);
/**
* Clear each of the {@code keys} in each of the {@code records} by removing
* every value for each key in each record.
*
* @param keys
* @param records
*/
@CompoundOperation
public abstract void clear(Collection<String> keys, Collection<Long> records);
/**
* Clear each of the {@code keys} in {@code record} by removing every value
* for each key.
*
* @param keys
* @param record
*/
@CompoundOperation
public abstract void clear(Collection<String> keys, long record);
/**
* Clear {@code key} in each of the {@code records} by removing every value
* for {@code key} in each record.
*
* @param key
* @param records
*/
@CompoundOperation
public abstract void clear(String key, Collection<Long> records);
/**
* Atomically clear {@code key} in {@code record} by removing each contained
* value.
*
* @param record
*/
public abstract void clear(String key, long record);
/**
* Attempt to permanently commit all the currently staged changes. This
* function returns {@code true} if and only if all the changes can be
* successfully applied. Otherwise, this function returns {@code false} and
* all the changes are aborted.
* <p>
* After this function returns, Concourse will return to {@code autocommit}
* mode and all subsequent changes will be written immediately.
* </p>
*
* @return {@code true} if all staged changes are successfully committed
*/
public abstract boolean commit();
/**
* Create a new Record and return its Primary Key.
*
* @return the Primary Key of the new Record
*/
public abstract long create();
/**
* Describe each of the {@code records} and return a mapping from each
* record to the keys that currently have at least one value.
*
* @param records
* @return the populated keys in each record
*/
@CompoundOperation
public abstract Map<Long, Set<String>> describe(Collection<Long> records);
/**
* Describe each of the {@code records} at {@code timestamp} and return a
* mapping from each record to the keys that had at least one value.
*
* @param records
* @param timestamp
* @return the populated keys in each record at {@code timestamp}
*/
@CompoundOperation
public abstract Map<Long, Set<String>> describe(Collection<Long> records,
Timestamp timestamp);
/**
* Describe {@code record} and return the keys that currently have at least
* one value.
*
* @param record
* @return the populated keys in {@code record}
*/
public abstract Set<String> describe(long record);
/**
* Describe {@code record} at {@code timestamp} and return the keys that had
* at least one value.
*
* @param record
* @param timestamp
* @return the populated keys in {@code record} at {@code timestamp}
*/
public abstract Set<String> describe(long record, Timestamp timestamp);
/**
* Close the Client connection.
*/
public abstract void exit();
/**
* Fetch each of the {@code keys} from each of the {@code records} and
* return a mapping from each record to a mapping from each key to the
* contained values.
*
* @param keys
* @param records
* @return the contained values for each of the {@code keys} in each of the
* {@code records}
*/
@CompoundOperation
public abstract Map<Long, Map<String, Set<Object>>> fetch(
Collection<String> keys, Collection<Long> records);
/**
* Fetch each of the {@code keys} from each of the {@code records} at
* {@code timestamp} and return a mapping from each record to a mapping from
* each key to the contained values.
*
* @param keys
* @param records
* @param timestamp
* @return the contained values for each of the {@code keys} in each
* of the {@code records} at {@code timestamp}
*/
@CompoundOperation
public abstract Map<Long, Map<String, Set<Object>>> fetch(
Collection<String> keys, Collection<Long> records,
Timestamp timestamp);
/**
* Fetch each of the {@code keys} from {@code record} and return a mapping
* from each key to the contained values.
*
* @param keys
* @param record
* @return the contained values for each of the {@code keys} in
* {@code record}
*/
@CompoundOperation
public abstract Map<String, Set<Object>> fetch(Collection<String> keys,
long record);
/**
* Fetch each of the {@code keys} from {@code record} at {@code timestamp}
* and return a mapping from each key to the contained values.
*
* @param keys
* @param record
* @param timestamp
* @return the contained values for each of the {@code keys} in
* {@code record} at {@code timestamp}
*/
@CompoundOperation
public abstract Map<String, Set<Object>> fetch(Collection<String> keys,
long record, Timestamp timestamp);
/**
* Fetch {@code key} from each of the {@code records} and return a mapping
* from each record to contained values.
*
* @param key
* @param records
* @return the contained values for {@code key} in each {@code record}
*/
@CompoundOperation
public abstract Map<Long, Set<Object>> fetch(String key,
Collection<Long> records);
/**
* Fetch {@code key} from} each of the {@code records} at {@code timestamp}
* and return a mapping from each record to the contained values.
*
* @param key
* @param records
* @param timestamp
* @return the contained values for {@code key} in each of the
* {@code records} at {@code timestamp}
*/
@CompoundOperation
public abstract Map<Long, Set<Object>> fetch(String key,
Collection<Long> records, Timestamp timestamp);
/**
* Fetch {@code key} from {@code record} and return all the contained
* values.
*
* @param key
* @param record
* @return the contained values
*/
public abstract Set<Object> fetch(String key, long record);
/**
* Fetch {@code key} from {@code record} at {@code timestamp} and return the
* set of values that were mapped.
*
* @param key
* @param record
* @param timestamp
* @return the contained values
*/
public abstract Set<Object> fetch(String key, long record,
Timestamp timestamp);
/**
* Find {@code key} {@code operator} {@code value} and return the set of
* records that satisfy the criteria. This is analogous to the SELECT action
* in SQL.
*
* @param key
* @param operator
* @param value
* @return the records that match the criteria
*/
public abstract Set<Long> find(String key, Operator operator, Object value);
/**
* Find {@code key} {@code operator} {@code value} and {@code value2} and
* return the set of records that satisfy the criteria. This is analogous to
* the SELECT action in SQL.
*
* @param key
* @param operator
* @param value
* @param value2
* @return the records that match the criteria
*/
public abstract Set<Long> find(String key, Operator operator, Object value,
Object value2);
/**
* Find {@code key} {@code operator} {@code value} and {@code value2} at
* {@code timestamp} and return the set of records that satisfy the
* criteria. This is analogous to the SELECT action in SQL.
*
* @param key
* @param operator
* @param value
* @param value2
* @param timestamp
* @return the records that match the criteria
*/
public abstract Set<Long> find(String key, Operator operator, Object value,
Object value2, Timestamp timestamp);
/**
* Find {@code key} {@code operator} {@code value} at {@code timestamp} and
* return the set of records that satisfy the criteria. This is analogous to
* the SELECT action in SQL.
*
* @param key
* @param operator
* @param value
* @return the records that match the criteria
*/
public abstract Set<Long> find(String key, Operator operator, Object value,
Timestamp timestamp);
/**
* Get each of the {@code keys} from each of the {@code records} and return
* a mapping from each record to a mapping of each key to the first
* contained value.
*
* @param keys
* @param records
* @return the first contained value for each of the {@code keys} in each of
* the {@code records}
*/
@CompoundOperation
public abstract Map<Long, Map<String, Object>> get(Collection<String> keys,
Collection<Long> records);
/**
* Get each of the {@code keys} from each of the {@code records} at
* {@code timestamp} and return a mapping from each record to a mapping of
* each key to the first contained value.
*
* @param keys
* @param records
* @param timestamp
* @return the first contained value for each of the {@code keys} in each of
* the {@code records} at {@code timestamp}
*/
@CompoundOperation
public abstract Map<Long, Map<String, Object>> get(Collection<String> keys,
Collection<Long> records, Timestamp timestamp);
/**
* Get each of the {@code keys} from {@code record} and return a mapping
* from each key to the first contained value.
*
* @param keys
* @param record
* @return the first contained value for each of the {@code keys} in
* {@code record}
*/
@CompoundOperation
public abstract Map<String, Object> get(Collection<String> keys, long record);
/**
* Get each of the {@code keys} from {@code record} at {@code timestamp} and
* return a mapping from each key to the first contained value.
*
* @param keys
* @param record
* @param timestamp
* @return the first contained value for each of the {@code keys} in
* {@code record} at {@code timestamp}
*/
@CompoundOperation
public abstract Map<String, Object> get(Collection<String> keys,
long record, Timestamp timestamp);
/**
* Get {@code key} from each of the {@code records} and return a mapping
* from each record to the first contained value.
*
* @param key
* @param records
* @return the first contained value for {@code key} in each of the
* {@code records}
*/
@CompoundOperation
public abstract Map<Long, Object> get(String key, Collection<Long> records);
/**
* Get {@code key} from each of the {@code records} at {@code timestamp} and
* return a mapping from each record to the first contained value.
*
* @param key
* @param records
* @param timestamp
* @return the first contained value for {@code key} in each of the
* {@code records} at {@code timestamp}
*/
@CompoundOperation
public abstract Map<Long, Object> get(String key, Collection<Long> records,
Timestamp timestamp);
/**
* Get {@code key} from {@code record} and return the first contained value
* or {@code null} if there is none. Compared to
* {@link #fetch(String, long)}, this method is suited for cases when the
* caller is certain that {@code key} in {@code record} maps to a single
* value of type {@code T}.
*
* @param key
* @param record
* @return the first contained value
*/
public abstract <T> T get(String key, long record);
/**
* Get {@code key} from {@code record} at {@code timestamp} and return the
* first contained value or {@code null} if there was none. Compared to
* {@link #fetch(String, long, long)}, this method is suited for cases when
* the caller is certain that {@code key} in {@code record} mapped to a
* single value of type {@code T} at {@code timestamp}.
*
* @param key
* @param record
* @param timestamp
* @return the first contained value
*/
public abstract <T> T get(String key, long record, Timestamp timestamp);
/**
* Return the version of the server to which this client is currently
* connected.
*
* @return the server version
*/
public abstract String getServerVersion();
/**
* Link {@code key} in {@code source} to each of the {@code destinations}.
*
* @param key
* @param source
* @param destinations
* @return a mapping from each destination to a boolean indicating if the
* link was added
*/
public abstract Map<Long, Boolean> link(String key, long source,
Collection<Long> destinations);
/**
* Link {@code key} in {@code source} to {@code destination}.
*
* @param key
* @param source
* @param destination
* @return {@code true} if the link is added
*/
public abstract boolean link(String key, long source, long destination);
/**
* Ping each of the {@code records}.
*
* @param records
* @return a mapping from each record to a boolean indicating if the record
* currently has at least one populated key
*/
@CompoundOperation
public abstract Map<Long, Boolean> ping(Collection<Long> records);
/**
* Ping {@code record}.
*
* @param record
* @return {@code true} if {@code record} currently has at least one
* populated key
*/
public abstract boolean ping(long record);
/**
* Remove {@code key} as {@code value} in each of the {@code records} if it
* is contained.
*
* @param key
* @param value
* @param records
* @return a mapping from each record to a boolean indicating if
* {@code value} is removed
*/
@CompoundOperation
public abstract Map<Long, Boolean> remove(String key, Object value,
Collection<Long> records);
/**
* Remove {@code key} as {@code value} to {@code record} if it is contained.
*
* @param key
* @param value
* @param record
* @return {@code true} if {@code value} is removed
*/
public abstract <T> boolean remove(String key, T value, long record);
/**
* Revert each of the {@code keys} in each of the {@code records} to
* {@code timestamp} by creating new revisions that the relevant changes
* that have occurred since {@code timestamp}.
*
* @param keys
* @param records
* @param timestamp
*/
@CompoundOperation
public abstract void revert(Collection<String> keys,
Collection<Long> records, Timestamp timestamp);
/**
* Revert each of the {@code keys} in {@code record} to {@code timestamp} by
* creating new revisions that the relevant changes
* that have occurred since {@code timestamp}.
*
* @param keys
* @param record
* @param timestamp
*/
@CompoundOperation
public abstract void revert(Collection<String> keys, long record,
Timestamp timestamp);
/**
* Revert {@code key} in each of the {@code records} to {@code timestamp} by
* creating new revisions that the relevant changes that have occurred
* since {@code timestamp}.
*
* @param key
* @param records
* @param timestamp
*/
@CompoundOperation
public abstract void revert(String key, Collection<Long> records,
Timestamp timestamp);
/**
* Atomically revert {@code key} in {@code record} to {@code timestamp} by
* creating new revisions that undo the relevant changes that have
* occurred since {@code timestamp}.
*
* @param key
* @param record
* @param timestamp
*/
public abstract void revert(String key, long record, Timestamp timestamp);
/**
* Search {@code key} for {@code query} and return the set of records that
* match.
*
* @param key
* @param query
* @return the records that match the query
*/
public abstract Set<Long> search(String key, String query);
/**
* Set {@code key} as {@code value} in each of the {@code records}.
*
* @param key
* @param value
* @param records
*/
@CompoundOperation
public abstract void set(String key, Object value, Collection<Long> records);
/**
* Atomically set {@code key} as {@code value} in {@code record}. This is a
* convenience method that clears the values for {@code key} and adds
* {@code value}.
*
* @param key
* @param value
* @param record
*/
public abstract <T> void set(String key, T value, long record);
/**
* Turn on {@code staging} mode so that all subsequent changes are
* collected in a staging area before possibly being committed. Staged
* operations are guaranteed to be reliable, all or nothing
* units of work that allow correct recovery from failures and provide
* isolation between clients so that Concourse is always in a consistent
* state (e.g. a transaction).
* <p>
* After this method returns, all subsequent operations will be done in
* {@code staging} mode until either {@link #abort()} or {@link #commit()}
* is invoked.
* </p>
*/
public abstract void stage();
/**
* Remove link from {@code key} in {@code source} to {@code destination}.
*
* @param key
* @param source
* @param destination
* @return {@code true} if the link is removed
*/
public abstract boolean unlink(String key, long source, long destination);
/**
* Verify {@code key} equals {@code value} in {@code record} and return
* {@code true} if {@code value} is currently mapped from {@code key} in
* {@code record}.
*
* @param key
* @param value
* @param record
* @return {@code true} if {@code key} equals {@code value} in
* {@code record}
*/
public abstract boolean verify(String key, Object value, long record);
/**
* Verify {@code key} equaled {@code value} in {@code record} at
* {@code timestamp} and return {@code true} if {@code value} was mapped
* from {@code key} in {@code record}.
*
* @param key
* @param value
* @param record
* @param timestamp
* @return {@code true} if {@code key} equaled {@code value} in
* {@code record} at {@code timestamp}
*/
public abstract boolean verify(String key, Object value, long record,
Timestamp timestamp);
/**
* Atomically verify {@code key} equals {@code expected} in {@code record}
* and swap with {@code replacement}.
*
* @param key
* @param expected
* @param record
* @param replacement
* @return {@code true} if the swap is successful
*/
public abstract boolean verifyAndSwap(String key, Object expected,
long record, Object replacement);
/**
* The implementation of the {@link Concourse} interface that establishes a
* connection with the remote server and handles communication. This class
* is a more user friendly wrapper around a Thrift
* {@link ConcourseService.Client}.
*
* @author jnelson
*/
private final static class Client extends Concourse {
// NOTE: The configuration variables are static because we want to
// guarantee that they are set before the client connection is
// constructed. Even though these variables are static, it is still the
// case that any changes to the configuration will be picked up
// immediately for new client connections.
private static String SERVER_HOST;
private static int SERVER_PORT;
private static String USERNAME;
private static String PASSWORD;
static {
ConcourseConfiguration config;
try {
config = ConcourseConfiguration
.loadConfig("concourse_client.prefs");
}
catch (Exception e) {
config = null;
}
SERVER_HOST = "localhost";
SERVER_PORT = 1717;
USERNAME = "admin";
PASSWORD = "admin";
if(config != null) {
SERVER_HOST = config.getString("host", SERVER_HOST);
SERVER_PORT = config.getInt("port", SERVER_PORT);
USERNAME = config.getString("username", USERNAME);
PASSWORD = config.getString("password", PASSWORD);
}
}
/**
* Represents a request to respond to a query using the current state as
* opposed to the history.
*/
private static Timestamp now = Timestamp.fromMicros(0);
/**
* An encrypted copy of the username passed to the constructor.
*/
private final ByteBuffer username;
/**
* An encrypted copy of the password passed to the constructor.
*/
private final ByteBuffer password;
/**
* The host of the connection.
*/
private final String host;
/**
* The port of the connection.
*/
private final int port;
/**
* The Thrift client that actually handles all RPC communication.
*/
private final ConcourseService.Client client;
/**
* The client keeps a copy of its {@link AccessToken} and passes it to
* the
* server for each remote procedure call. The client will
* re-authenticate
* when necessary using the username/password read from the prefs file.
*/
private AccessToken creds = null;
/**
* Whenever the client starts a Transaction, it keeps a
* {@link TransactionToken} so that the server can stage the changes in
* the
* appropriate place.
*/
private TransactionToken transaction = null;
/**
* Create a new Client connection to the Concourse server specified in
* {@code concourse.prefs} and return a handler to facilitate database
* interaction.
*/
public Client() {
this(SERVER_HOST, SERVER_PORT, USERNAME, PASSWORD);
}
/**
* Create a new Client connection to a Concourse server and return a
* handler to facilitate database interaction.
*
* @param host
* @param port
* @param username
* @param password
*/
public Client(String host, int port, String username, String password) {
this.host = host;
this.port = port;
this.username = ClientSecurity.encrypt(username);
this.password = ClientSecurity.encrypt(password);
final TTransport transport = new TSocket(host, port);
try {
transport.open();
TProtocol protocol = new TBinaryProtocol(transport);
client = new ConcourseService.Client(protocol);
authenticate();
Runtime.getRuntime().addShutdownHook(new Thread("shutdown") {
@Override
public void run() {
if(transaction != null && transport.isOpen()) {
abort();
}
}
});
}
catch (TTransportException e) {
- throw Throwables.propagate(e);
+ throw new RuntimeException(
+ "Could not connect to the Concourse Server at " + host
+ + ":" + port);
}
}
@Override
public void abort() {
execute(new Callable<Void>() {
@Override
public Void call() throws Exception {
if(transaction != null) {
final TransactionToken token = transaction;
transaction = null;
client.abort(creds, token);
}
return null;
}
});
}
@Override
public Map<Long, Boolean> add(String key, Object value,
Collection<Long> records) {
Map<Long, Boolean> result = TLinkedHashMap.newTLinkedHashMap(
"Record", "Result");
for (long record : records) {
result.put(record, add(key, value, record));
}
return result;
}
@Override
public <T> boolean add(final String key, final T value,
final long record) {
return execute(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return client.add(key, Convert.javaToThrift(value), record,
creds, transaction);
}
});
}
@Override
public Map<Timestamp, String> audit(final long record) {
return execute(new Callable<Map<Timestamp, String>>() {
@Override
public Map<Timestamp, String> call() throws Exception {
Map<Long, String> audit = client.audit(record, null, creds,
transaction);
return ((TLinkedHashMap<Timestamp, String>) Transformers
.transformMap(audit,
new Function<Long, Timestamp>() {
@Override
public Timestamp apply(Long input) {
return Timestamp.fromMicros(input);
}
})).setKeyName("DateTime").setValueName(
"Revision");
}
});
}
@Override
public Map<Timestamp, String> audit(final String key, final long record) {
return execute(new Callable<Map<Timestamp, String>>() {
@Override
public Map<Timestamp, String> call() throws Exception {
Map<Long, String> audit = client.audit(record, key, creds,
transaction);
return ((TLinkedHashMap<Timestamp, String>) Transformers
.transformMap(audit,
new Function<Long, Timestamp>() {
@Override
public Timestamp apply(Long input) {
return Timestamp.fromMicros(input);
}
})).setKeyName("DateTime").setValueName(
"Revision");
}
});
}
@Override
public void clear(Collection<String> keys, Collection<Long> records) {
for (long record : records) {
for (String key : keys) {
clear(key, record);
}
}
}
@Override
public void clear(Collection<String> keys, long record) {
for (String key : keys) {
clear(key, record);
}
}
@Override
public void clear(String key, Collection<Long> records) {
for (long record : records) {
clear(key, record);
}
}
@Override
public void clear(final String key, final long record) {
execute(new Callable<Void>() {
@Override
public Void call() throws Exception {
client.clear(key, record, creds, transaction);
return null;
}
});
}
@Override
public boolean commit() {
return execute(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
final TransactionToken token = transaction;
transaction = null;
return client.commit(creds, token);
}
});
}
@Override
public long create() {
return Time.now(); // TODO get a primary key using a plugin
}
@Override
public Map<Long, Set<String>> describe(Collection<Long> records) {
Map<Long, Set<String>> result = TLinkedHashMap.newTLinkedHashMap(
"Record", "Keys");
for (long record : records) {
result.put(record, describe(record));
}
return result;
}
@Override
public Map<Long, Set<String>> describe(Collection<Long> records,
Timestamp timestamp) {
Map<Long, Set<String>> result = TLinkedHashMap.newTLinkedHashMap(
"Record", "Keys");
for (long record : records) {
result.put(record, describe(record, timestamp));
}
return result;
}
@Override
public Set<String> describe(long record) {
return describe(record, now);
}
@Override
public Set<String> describe(final long record, final Timestamp timestamp) {
return execute(new Callable<Set<String>>() {
@Override
public Set<String> call() throws Exception {
return client.describe(record, timestamp.getMicros(),
creds, transaction);
}
});
}
@Override
public void exit() {
client.getInputProtocol().getTransport().close();
client.getOutputProtocol().getTransport().close();
}
@Override
public Map<Long, Map<String, Set<Object>>> fetch(
Collection<String> keys, Collection<Long> records) {
TLinkedTableMap<Long, String, Set<Object>> result = TLinkedTableMap
.<Long, String, Set<Object>> newTLinkedTableMap("Record");
for (long record : records) {
for (String key : keys) {
result.put(record, key, fetch(key, record));
}
}
return result;
}
@Override
public Map<Long, Map<String, Set<Object>>> fetch(
Collection<String> keys, Collection<Long> records,
Timestamp timestamp) {
TLinkedTableMap<Long, String, Set<Object>> result = TLinkedTableMap
.<Long, String, Set<Object>> newTLinkedTableMap("Record");
for (long record : records) {
for (String key : keys) {
result.put(record, key, fetch(key, record, timestamp));
}
}
return result;
}
@Override
public Map<String, Set<Object>> fetch(Collection<String> keys,
long record) {
Map<String, Set<Object>> result = TLinkedHashMap.newTLinkedHashMap(
"Key", "Values");
for (String key : keys) {
result.put(key, fetch(key, record));
}
return result;
}
@Override
public Map<String, Set<Object>> fetch(Collection<String> keys,
long record, Timestamp timestamp) {
Map<String, Set<Object>> result = TLinkedHashMap.newTLinkedHashMap(
"Key", "Values");
for (String key : keys) {
result.put(key, fetch(key, record, timestamp));
}
return result;
}
@Override
public Map<Long, Set<Object>> fetch(String key, Collection<Long> records) {
Map<Long, Set<Object>> result = TLinkedHashMap.newTLinkedHashMap(
"Record", key);
for (long record : records) {
result.put(record, fetch(key, record));
}
return result;
}
@Override
public Map<Long, Set<Object>> fetch(String key,
Collection<Long> records, Timestamp timestamp) {
Map<Long, Set<Object>> result = TLinkedHashMap.newTLinkedHashMap(
"Record", key);
for (long record : records) {
result.put(record, fetch(key, record, timestamp));
}
return result;
}
@Override
public Set<Object> fetch(String key, long record) {
return fetch(key, record, now);
}
@Override
public Set<Object> fetch(final String key, final long record,
final Timestamp timestamp) {
return execute(new Callable<Set<Object>>() {
@Override
public Set<Object> call() throws Exception {
Set<TObject> values = client.fetch(key, record,
timestamp.getMicros(), creds, transaction);
return Transformers.transformSet(values,
new Function<TObject, Object>() {
@Override
public Object apply(TObject input) {
return Convert.thriftToJava(input);
}
});
}
});
}
@Override
public Set<Long> find(String key, Operator operator, Object value) {
return find(key, operator, value, now);
}
@Override
public Set<Long> find(String key, Operator operator, Object value,
Object value2) {
return find(key, operator, value, value2, now);
}
@Override
public Set<Long> find(final String key, final Operator operator,
final Object value, final Object value2,
final Timestamp timestamp) {
return execute(new Callable<Set<Long>>() {
@Override
public Set<Long> call() throws Exception {
return client.find(key, operator, Lists.transform(
Lists.newArrayList(value, value2),
new Function<Object, TObject>() {
@Override
public TObject apply(Object input) {
return Convert.javaToThrift(input);
}
}), timestamp.getMicros(), creds, transaction);
}
});
}
@Override
public Set<Long> find(final String key, final Operator operator,
final Object value, final Timestamp timestamp) {
return execute(new Callable<Set<Long>>() {
@Override
public Set<Long> call() throws Exception {
return client.find(key, operator, Lists.transform(
Lists.newArrayList(value),
new Function<Object, TObject>() {
@Override
public TObject apply(Object input) {
return Convert.javaToThrift(input);
}
}), timestamp.getMicros(), creds, transaction);
}
});
}
@Override
public Map<Long, Map<String, Object>> get(Collection<String> keys,
Collection<Long> records) {
TLinkedTableMap<Long, String, Object> result = TLinkedTableMap
.<Long, String, Object> newTLinkedTableMap("Record");
for (long record : records) {
for (String key : keys) {
result.put(record, key, get(key, record));
}
}
return result;
}
@Override
public Map<Long, Map<String, Object>> get(Collection<String> keys,
Collection<Long> records, Timestamp timestamp) {
TLinkedTableMap<Long, String, Object> result = TLinkedTableMap
.<Long, String, Object> newTLinkedTableMap("Record");
for (long record : records) {
for (String key : keys) {
result.put(record, key, get(key, record, timestamp));
}
}
return result;
}
@Override
public Map<String, Object> get(Collection<String> keys, long record) {
Map<String, Object> result = TLinkedHashMap.newTLinkedHashMap(
"Key", "Value");
for (String key : keys) {
result.put(key, get(key, record));
}
return result;
}
@Override
public Map<String, Object> get(Collection<String> keys, long record,
Timestamp timestamp) {
Map<String, Object> result = TLinkedHashMap.newTLinkedHashMap(
"Key", "Value");
for (String key : keys) {
result.put(key, get(key, record, timestamp));
}
return result;
}
@Override
public Map<Long, Object> get(String key, Collection<Long> records) {
Map<Long, Object> result = TLinkedHashMap.newTLinkedHashMap(
"Record", key);
for (long record : records) {
result.put(record, get(key, record));
}
return result;
}
@Override
public Map<Long, Object> get(String key, Collection<Long> records,
Timestamp timestamp) {
Map<Long, Object> result = TLinkedHashMap.newTLinkedHashMap(
"Record", key);
for (long record : records) {
result.put(record, get(key, record, timestamp));
}
return result;
}
@Override
@Nullable
public <T> T get(String key, long record) {
return get(key, record, now);
}
@SuppressWarnings("unchecked")
@Override
@Nullable
public <T> T get(String key, long record, Timestamp timestamp) {
Set<Object> values = fetch(key, record, timestamp);
if(!values.isEmpty()) {
return (T) values.iterator().next();
}
return null;
}
@Override
public String getServerVersion() {
return execute(new Callable<String>() {
@Override
public String call() throws Exception {
return client.getServerVersion();
}
});
}
@Override
public Map<Long, Boolean> link(String key, long source,
Collection<Long> destinations) {
Map<Long, Boolean> result = TLinkedHashMap.newTLinkedHashMap(
"Record", "Result");
for (long destination : destinations) {
result.put(destination, link(key, source, destination));
}
return result;
}
@Override
public boolean link(String key, long source, long destination) {
return add(key, Link.to(destination), source);
}
@Override
public Map<Long, Boolean> ping(Collection<Long> records) {
Map<Long, Boolean> result = TLinkedHashMap.newTLinkedHashMap(
"Record", "Result");
for (long record : records) {
result.put(record, ping(record));
}
return result;
}
@Override
public boolean ping(final long record) {
return execute(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return client.ping(record, creds, transaction);
}
});
}
@Override
public Map<Long, Boolean> remove(String key, Object value,
Collection<Long> records) {
Map<Long, Boolean> result = TLinkedHashMap.newTLinkedHashMap(
"Record", "Result");
for (long record : records) {
result.put(record, remove(key, value, record));
}
return result;
}
@Override
public <T> boolean remove(final String key, final T value,
final long record) {
return execute(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return client.remove(key, Convert.javaToThrift(value),
record, creds, transaction);
}
});
}
@Override
public void revert(Collection<String> keys, Collection<Long> records,
Timestamp timestamp) {
for (long record : records) {
for (String key : keys) {
revert(key, record, timestamp);
}
}
}
@Override
public void revert(Collection<String> keys, long record,
Timestamp timestamp) {
for (String key : keys) {
revert(key, record, timestamp);
}
}
@Override
public void revert(String key, Collection<Long> records,
Timestamp timestamp) {
for (long record : records) {
revert(key, record, timestamp);
}
}
@Override
public void revert(final String key, final long record,
final Timestamp timestamp) {
execute(new Callable<Void>() {
@Override
public Void call() throws Exception {
client.revert(key, record, timestamp.getMicros(), creds,
transaction);
return null;
}
});
}
@Override
public Set<Long> search(final String key, final String query) {
return execute(new Callable<Set<Long>>() {
@Override
public Set<Long> call() throws Exception {
return client.search(key, query, creds, transaction);
}
});
}
@Override
public void set(String key, Object value, Collection<Long> records) {
for (long record : records) {
set(key, value, record);
}
}
@Override
public <T> void set(final String key, final T value, final long record) {
execute(new Callable<Void>() {
@Override
public Void call() throws Exception {
client.set0(key, Convert.javaToThrift(value), record,
creds, transaction);
return null;
}
});
}
@Override
public void stage() {
execute(new Callable<Void>() {
@Override
public Void call() throws Exception {
transaction = client.stage(creds);
return null;
}
});
}
@Override
public String toString() {
return "Connected to " + host + ":" + port + " as "
+ new String(ClientSecurity.decrypt(username).array());
}
@Override
public boolean unlink(String key, long source, long destination) {
return remove(key, Link.to(destination), source);
}
@Override
public boolean verify(String key, Object value, long record) {
return verify(key, value, record, now);
}
@Override
public boolean verify(final String key, final Object value,
final long record, final Timestamp timestamp) {
return execute(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return client.verify(key, Convert.javaToThrift(value),
record, timestamp.getMicros(), creds, transaction);
}
});
}
@Override
public boolean verifyAndSwap(final String key, final Object expected,
final long record, final Object replacement) {
return execute(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return client.verifyAndSwap(key,
Convert.javaToThrift(expected), record,
Convert.javaToThrift(replacement), creds,
transaction);
}
});
}
/**
* Authenticate the {@link #username} and {@link #password} and populate
* {@link #creds} with the appropriate AccessToken.
*/
private void authenticate() {
try {
creds = client.login(ClientSecurity.decrypt(username),
ClientSecurity.decrypt(password));
}
catch (TException e) {
throw Throwables.propagate(e);
}
}
/**
* Execute the task defined in {@code callable}. This method contains
* retry logic to handle cases when {@code creds} expires and must be
* updated.
*
* @param callable
* @return the task result
*/
private <T> T execute(Callable<T> callable) {
try {
return callable.call();
}
catch (SecurityException e) {
authenticate();
return execute(callable);
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
}
| true | true |
public Client(String host, int port, String username, String password) {
this.host = host;
this.port = port;
this.username = ClientSecurity.encrypt(username);
this.password = ClientSecurity.encrypt(password);
final TTransport transport = new TSocket(host, port);
try {
transport.open();
TProtocol protocol = new TBinaryProtocol(transport);
client = new ConcourseService.Client(protocol);
authenticate();
Runtime.getRuntime().addShutdownHook(new Thread("shutdown") {
@Override
public void run() {
if(transaction != null && transport.isOpen()) {
abort();
}
}
});
}
catch (TTransportException e) {
throw Throwables.propagate(e);
}
}
|
public Client(String host, int port, String username, String password) {
this.host = host;
this.port = port;
this.username = ClientSecurity.encrypt(username);
this.password = ClientSecurity.encrypt(password);
final TTransport transport = new TSocket(host, port);
try {
transport.open();
TProtocol protocol = new TBinaryProtocol(transport);
client = new ConcourseService.Client(protocol);
authenticate();
Runtime.getRuntime().addShutdownHook(new Thread("shutdown") {
@Override
public void run() {
if(transaction != null && transport.isOpen()) {
abort();
}
}
});
}
catch (TTransportException e) {
throw new RuntimeException(
"Could not connect to the Concourse Server at " + host
+ ":" + port);
}
}
|
diff --git a/Android/CloudAppStudioAndroid/src/com/cloudappstudio/activities/LoginActivity.java b/Android/CloudAppStudioAndroid/src/com/cloudappstudio/activities/LoginActivity.java
index dec7114..40c0b99 100644
--- a/Android/CloudAppStudioAndroid/src/com/cloudappstudio/activities/LoginActivity.java
+++ b/Android/CloudAppStudioAndroid/src/com/cloudappstudio/activities/LoginActivity.java
@@ -1,35 +1,34 @@
package com.cloudappstudio.activities;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.actionbarsherlock.app.SherlockActivity;
import com.cloudappstudio.android.R;
import com.cloudappstudio.utility.CloudViewEntriesParser;
/**
* An activity that lets the user log in to their google account
* @author mrjanek <Jesper Lindberg>
*/
public class LoginActivity extends SherlockActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.cloudappstudio.android.R.layout.login_view);
Button logInButton = (Button) findViewById(R.id.logIn_button);
logInButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
- //Intent intent = new Intent(getApplicationContext(), WebApplicationsActivity.class);
- //startActivity(intent);
- CloudViewEntriesParser parser = new CloudViewEntriesParser();
+ Intent intent = new Intent(getApplicationContext(), WebApplicationsActivity.class);
+ startActivity(intent);
}
});
}
}
| true | true |
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.cloudappstudio.android.R.layout.login_view);
Button logInButton = (Button) findViewById(R.id.logIn_button);
logInButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Intent intent = new Intent(getApplicationContext(), WebApplicationsActivity.class);
//startActivity(intent);
CloudViewEntriesParser parser = new CloudViewEntriesParser();
}
});
}
|
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.cloudappstudio.android.R.layout.login_view);
Button logInButton = (Button) findViewById(R.id.logIn_button);
logInButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), WebApplicationsActivity.class);
startActivity(intent);
}
});
}
|
diff --git a/src-gwt/com/alkacon/acacia/client/widgets/HalloWidget.java b/src-gwt/com/alkacon/acacia/client/widgets/HalloWidget.java
index e841e5a..7378f3a 100644
--- a/src-gwt/com/alkacon/acacia/client/widgets/HalloWidget.java
+++ b/src-gwt/com/alkacon/acacia/client/widgets/HalloWidget.java
@@ -1,170 +1,180 @@
/*
* This library is part of the Acacia Editor -
* an open source inline and form based content editor for GWT.
*
* Copyright (c) Alkacon Software GmbH (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.alkacon.acacia.client.widgets;
import com.alkacon.acacia.client.css.I_LayoutBundle;
import com.alkacon.vie.client.Vie;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
/**
* Rich text editor widget based on the hallo editor.<p>
*/
public class HalloWidget extends A_EditWidget {
/** Indicating if the widget is active. */
private boolean m_active;
/**
* Constructor.<p>
*/
public HalloWidget() {
this(DOM.createDiv());
}
/**
* Constructor wrapping a specific DOM element.<p>
*
* @param element the element to wrap
*/
public HalloWidget(Element element) {
super(element);
}
/**
* @see com.alkacon.acacia.client.widgets.A_EditWidget#addValueChangeHandler(com.google.gwt.event.logical.shared.ValueChangeHandler)
*/
@Override
public HandlerRegistration addValueChangeHandler(ValueChangeHandler<String> handler) {
return addHandler(handler, ValueChangeEvent.getType());
}
/**
* @see com.alkacon.acacia.client.widgets.A_EditWidget#getValue()
*/
@Override
public String getValue() {
return getElement().getInnerHTML();
}
/**
* Initializes the widget.<p>
*/
private void init() {
addStyleName(I_LayoutBundle.INSTANCE.form().input());
}
/**
* @see com.google.gwt.user.client.ui.FocusWidget#onAttach()
*/
@Override
protected void onAttach() {
super.onAttach();
initNative(getElement(), Vie.getInstance());
}
/**
* @see com.alkacon.acacia.client.widgets.I_EditWidget#isActive()
*/
public boolean isActive() {
return m_active;
}
/**
* @see com.alkacon.acacia.client.widgets.I_EditWidget#setActive(boolean)
*/
public void setActive(boolean active) {
if (m_active == active) {
return;
}
m_active = active;
if (m_active) {
getElement().setAttribute("contentEditable", "true");
getElement().removeClassName(I_LayoutBundle.INSTANCE.form().inActive());
getElement().focus();
fireValueChange(true);
} else {
getElement().setAttribute("contentEditable", "false");
getElement().addClassName(I_LayoutBundle.INSTANCE.form().inActive());
}
}
/**
* @see com.google.gwt.user.client.ui.HasValue#setValue(java.lang.Object)
*/
public void setValue(String value) {
setValue(value, true);
}
/**
* @see com.google.gwt.user.client.ui.HasValue#setValue(java.lang.Object, boolean)
*/
public void setValue(String value, boolean fireEvents) {
getElement().setInnerHTML(value);
fireValueChange(false);
}
/**
* Initializes the native java-script components of the widget.<p>
*
* @param element the element
* @param vie the VIE instance
*/
private native void initNative(Element element, Vie vie) /*-{
var _self = this;
var editable = vie.jQuery(element);
editable.hallo({
plugins : {
'halloformat' : {},
'halloblock' : {},
'hallojustify' : {},
'hallolists' : {},
- 'hallolink' : {},
'halloreundo' : {}
},
- editable : true
+ editable : true,
+ showAlways : true
});
editable
.bind(
'hallomodified',
function(event, data) {
[email protected]::fireValueChange(Z)(false);
});
+ var selection = $wnd.rangy.getSelection();
+ var range = null;
+ if (selection.rangeCount > 0) {
+ range = selection.getRangeAt(0);
+ } else {
+ range = rangy.createRange();
+ }
+ if (editable.hallo("containsSelection")) {
+ editable.hallo("turnOn");
+ }
}-*/;
}
| false | true |
private native void initNative(Element element, Vie vie) /*-{
var _self = this;
var editable = vie.jQuery(element);
editable.hallo({
plugins : {
'halloformat' : {},
'halloblock' : {},
'hallojustify' : {},
'hallolists' : {},
'hallolink' : {},
'halloreundo' : {}
},
editable : true
});
editable
.bind(
'hallomodified',
function(event, data) {
[email protected]::fireValueChange(Z)(false);
});
}-*/;
|
private native void initNative(Element element, Vie vie) /*-{
var _self = this;
var editable = vie.jQuery(element);
editable.hallo({
plugins : {
'halloformat' : {},
'halloblock' : {},
'hallojustify' : {},
'hallolists' : {},
'halloreundo' : {}
},
editable : true,
showAlways : true
});
editable
.bind(
'hallomodified',
function(event, data) {
[email protected]::fireValueChange(Z)(false);
});
var selection = $wnd.rangy.getSelection();
var range = null;
if (selection.rangeCount > 0) {
range = selection.getRangeAt(0);
} else {
range = rangy.createRange();
}
if (editable.hallo("containsSelection")) {
editable.hallo("turnOn");
}
}-*/;
|
diff --git a/jslint4java/src/main/java/com/googlecode/jslint4java/JSLint.java b/jslint4java/src/main/java/com/googlecode/jslint4java/JSLint.java
index 7c2637a..bee9555 100644
--- a/jslint4java/src/main/java/com/googlecode/jslint4java/JSLint.java
+++ b/jslint4java/src/main/java/com/googlecode/jslint4java/JSLint.java
@@ -1,405 +1,403 @@
package com.googlecode.jslint4java;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextAction;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.UniqueTag;
import com.googlecode.jslint4java.Issue.IssueBuilder;
import com.googlecode.jslint4java.JSFunction.Builder;
import com.googlecode.jslint4java.JSLintResult.ResultBuilder;
import com.googlecode.jslint4java.Util.Converter;
/**
* A utility class to check JavaScript source code for potential problems.
*
* @author dom
* @see JSLintBuilder Construction of JSLint
*/
public class JSLint {
// Uncomment to enable the rhino debugger.
// static {
// org.mozilla.javascript.tools.debugger.Main.mainEmbedded(null);
// }
/** What should {@code indent} be set to by default? */
private static final String DEFAULT_INDENT = "4";
/** What should {@code maxerr} be set to by default? */
private static final String DEFAULT_MAXERR = "50";
/**
* A helper class for interpreting function parameter names. Note that we
* use this to work around a change in JSLint's data structure, which
* changed from being a single string to an object.
*/
private static final class JSFunctionParamConverter implements Util.Converter<String> {
public String convert(Object obj) {
Scriptable scope = (Scriptable) obj;
return Util.stringValue("string", scope);
}
}
/**
* A helper class for interpreting the output of {@code JSLINT.data()}.
*/
private static final class JSFunctionConverter implements Util.Converter<JSFunction> {
public JSFunction convert(Object obj) {
Scriptable scope = (Scriptable) obj;
String name = Util.stringValue("name", scope);
int line = Util.intValue("line", scope);
Builder b = new JSFunction.Builder(name, line);
b.last(Util.intValue("last", scope));
for (String param : Util.listValue("params", scope, new JSFunctionParamConverter())) {
b.addParam(param);
}
for (String closure : Util.listValueOfType("closure", String.class, scope)) {
b.addClosure(closure);
}
for (String var : Util.listValueOfType("var", String.class, scope)) {
b.addVar(var);
}
for (String exception : Util.listValueOfType("exception", String.class, scope)) {
b.addException(exception);
}
for (String outer : Util.listValueOfType("outer", String.class, scope)) {
b.addOuter(outer);
}
for (String unused : Util.listValueOfType("unused", String.class, scope)) {
b.addUnused(unused);
}
for (String undef : Util.listValueOfType("undef", String.class, scope)) {
b.addUndef(undef);
}
for (String global : Util.listValueOfType("global", String.class, scope)) {
b.addGlobal(global);
}
for (String label : Util.listValueOfType("label", String.class, scope)) {
b.addLabel(label);
}
return b.build();
}
}
/**
* A helper class for looking up undefined variable objects.
*/
private static class VariableWarningConverter implements Converter<VariableWarning> {
public VariableWarning convert(Object obj) {
Scriptable scope = (Scriptable) obj;
String name = Util.stringValue("name", scope);
int line = Util.intValue("line", scope);
String function = Util.stringValue("function", scope);
return new VariableWarning(name, line, function);
}
}
private final Map<Option, Object> options = new EnumMap<Option, Object>(Option.class);
private final ScriptableObject scope;
private final ContextFactory contextFactory;
/**
* Create a new {@link JSLint} object. You must pass in a {@link Scriptable}
* which already has the {@code JSLINT} function defined. You are expected
* to use {@link JSLintBuilder} rather than calling this constructor.
*/
JSLint(ContextFactory contextFactory, ScriptableObject scope) {
this.contextFactory = contextFactory;
this.scope = scope;
// We should no longer be updating this.
this.scope.sealObject();
}
/**
* Add an option to change the behaviour of the lint. This will be passed in
* with a value of "true".
*
* @param o
* Any {@link Option}.
*/
public void addOption(Option o) {
options.put(o, Boolean.TRUE);
}
/**
* Add an option to change the behaviour of the lint. The option will be
* parsed as appropriate using an {@link OptionParser}.
*
* @param o
* Any {@link Option}.
* @param arg
* The value to associate with <i>o</i>.
*/
public void addOption(Option o, String arg) {
OptionParser optionParser = new OptionParser();
options.put(o, optionParser.parse(o.getType(), arg));
}
/**
* Set options that should always be present. This mirrors what jslint.com
* does.
*/
private void applyDefaultOptions() {
if (!options.containsKey(Option.INDENT)) {
addOption(Option.INDENT, DEFAULT_INDENT);
}
if (!options.containsKey(Option.MAXERR)) {
addOption(Option.MAXERR, DEFAULT_MAXERR);
}
}
/**
* Assemble the {@link JSLintResult} object.
*/
@NeedsContext
private JSLintResult buildResults(final String systemId, final long startNanos, final long endNanos) {
return (JSLintResult) contextFactory.call(new ContextAction() {
public Object run(Context cx) {
ResultBuilder b = new JSLintResult.ResultBuilder(systemId);
b.duration(TimeUnit.NANOSECONDS.toMillis(endNanos - startNanos));
for (Issue issue : readErrors(systemId)) {
b.addIssue(issue);
}
// Collect a report on what we've just linted.
b.report(callReport(false));
// Extract JSLINT.data() output and set it on the result.
Scriptable lintScope = (Scriptable) scope.get("JSLINT", scope);
Object o = lintScope.get("data", lintScope);
// Real JSLINT will always have this, but some of my test stubs don't.
if (o != UniqueTag.NOT_FOUND) {
Function reportFunc = (Function) o;
Scriptable data = (Scriptable) reportFunc.call(cx, scope,
scope, new Object[] {});
for (String global : Util.listValueOfType("globals", String.class, data)) {
b.addGlobal(global);
}
for (String url : Util.listValueOfType("urls", String.class, data)) {
b.addUrl(url);
}
b.json(Util.booleanValue("json", data));
for (JSFunction f : Util.listValue("functions", data, new JSFunctionConverter())) {
b.addFunction(f);
}
- if (Boolean.TRUE.equals(options.get(Option.WARNINGS))) {
- // Pull out the list of unused variables as issues. This doesn't appear
- // to be a supported API, unfortunately, but it does work.
- for (VariableWarning u : Util.listValue("unused", data,
- new VariableWarningConverter())) {
- b.addIssue(issueForUnusedVariable(u, systemId));
- }
- // There is also a list of undefined variables. But… these are already
- // reported by JSLint. So let's not repeat them.
+ // Pull out the list of unused variables as issues. This doesn't appear
+ // to be a supported API, unfortunately, but it does work.
+ for (VariableWarning u : Util.listValue("unused", data,
+ new VariableWarningConverter())) {
+ b.addIssue(issueForUnusedVariable(u, systemId));
}
+ // There is also a list of undefined variables. But… these are already
+ // reported by JSLint. So let's not repeat them.
}
// Extract the list of properties. Note that we don't expose the counts, as it
// doesn't seem that useful.
Object properties = lintScope.get("property", lintScope);
if (properties != UniqueTag.NOT_FOUND) {
for (Object id: ScriptableObject.getPropertyIds((Scriptable) properties)) {
b.addProperty(id.toString());
}
}
return b.build();
}
});
}
/**
* Construct a JSLint error report. This is in two parts: a list of errors, and an optional
* function report.
*
* @param errorsOnly
* if the function report should be omitted.
* @return the report, an HTML string.
*/
@NeedsContext
private String callReport(final boolean errorsOnly) {
return (String) contextFactory.call(new ContextAction() {
// TODO: This would probably benefit from injecting an API to manage JSLint.
public Object run(Context cx) {
Function fn = null;
Object value = null;
StringBuilder sb = new StringBuilder();
Scriptable lintScope = (Scriptable) scope.get("JSLINT", scope);
// Look up JSLINT.data.
value = lintScope.get("data", lintScope);
if (value == UniqueTag.NOT_FOUND) {
return "";
}
fn = (Function) value;
// Call JSLINT.data(). This returns a JS data structure that we need below.
Object data = fn.call(cx, scope, scope, new Object[] {});
// Look up JSLINT.error_report.
value = lintScope.get("error_report", lintScope);
// Shouldn't happen ordinarily, but some of my tests don't have it.
if (value != UniqueTag.NOT_FOUND) {
fn = (Function) value;
// Call JSLint.report().
sb.append(fn.call(cx, scope, scope, new Object[] { data }));
}
if (!errorsOnly) {
// Look up JSLINT.report.
value = lintScope.get("report", lintScope);
// Shouldn't happen ordinarily, but some of my tests don't have it.
if (value != UniqueTag.NOT_FOUND) {
fn = (Function) value;
// Call JSLint.report().
sb.append(fn.call(cx, scope, scope, new Object[] { data }));
}
}
return sb.toString();
}
});
}
@NeedsContext
private void doLint(final String javaScript) {
contextFactory.call(new ContextAction() {
public Object run(Context cx) {
String src = javaScript == null ? "" : javaScript;
Object[] args = new Object[] { src, optionsAsJavaScriptObject() };
Function lintFunc = (Function) scope.get("JSLINT", scope);
// JSLINT actually returns a boolean, but we ignore it as we always go
// and look at the errors in more detail.
lintFunc.call(cx, scope, scope, args);
return null;
}
});
}
/**
* Return the version of jslint in use.
*/
public String getEdition() {
Scriptable lintScope = (Scriptable) scope.get("JSLINT", scope);
return (String) lintScope.get("edition", lintScope);
}
private Issue issueForUnusedVariable(VariableWarning u, String systemId) {
String reason = String.format("Unused variable: '%s' in %s.", u.getName(), u.getFunction());
return new IssueBuilder(systemId, u.getLine(), 0, reason).build();
}
/**
* Check for problems in a {@link Reader} which contains JavaScript source.
*
* @param systemId
* a filename
* @param reader
* a {@link Reader} over JavaScript source code.
*
* @return a {@link JSLintResult}.
*/
public JSLintResult lint(String systemId, Reader reader) throws IOException {
return lint(systemId, Util.readerToString(reader));
}
/**
* Check for problems in JavaScript source.
*
* @param systemId
* a filename
* @param javaScript
* a String of JavaScript source code.
*
* @return a {@link JSLintResult}.
*/
public JSLintResult lint(String systemId, String javaScript) {
long before = System.nanoTime();
doLint(javaScript);
long after = System.nanoTime();
return buildResults(systemId, before, after);
}
/**
* Turn the set of options into a JavaScript object, where the key is the
* name of the option and the value is true.
*/
@NeedsContext
private Scriptable optionsAsJavaScriptObject() {
return (Scriptable) contextFactory.call(new ContextAction() {
public Object run(Context cx) {
applyDefaultOptions();
Scriptable opts = cx.newObject(scope);
for (Entry<Option, Object> entry : options.entrySet()) {
String key = entry.getKey().getLowerName();
// Use our "custom" version in order to get native arrays.
Object value = Util.javaToJS(entry.getValue(), opts);
opts.put(key, opts, value);
}
return opts;
}
});
}
private List<Issue> readErrors(String systemId) {
ArrayList<Issue> issues = new ArrayList<Issue>();
Scriptable JSLINT = (Scriptable) scope.get("JSLINT", scope);
Scriptable errors = (Scriptable) JSLINT.get("errors", JSLINT);
int count = Util.intValue("length", errors);
for (int i = 0; i < count; i++) {
Scriptable err = (Scriptable) errors.get(i, errors);
// JSLINT spits out a null when it cannot proceed.
// TODO Should probably turn i-1th issue into a "fatal".
if (err != null) {
issues.add(IssueBuilder.fromJavaScript(systemId, err));
}
}
return issues;
}
/**
* Report on what variables / functions are in use by this code.
*
* @param javaScript
* @return an HTML report.
*/
public String report(String javaScript) {
return report(javaScript, false);
}
/**
* Report on what variables / functions are in use by this code.
*
* @param javaScript
* @param errorsOnly
* If a report consisting solely of the problems is desired.
* @return an HTML report.
*/
public String report(String javaScript, boolean errorsOnly) {
// Run the lint function itself as prep.
doLint(javaScript);
// The run the reporter.
return callReport(errorsOnly);
}
/**
* Clear out all options that have been set with {@link #addOption(Option)}.
*/
public void resetOptions() {
options.clear();
}
}
| false | true |
private JSLintResult buildResults(final String systemId, final long startNanos, final long endNanos) {
return (JSLintResult) contextFactory.call(new ContextAction() {
public Object run(Context cx) {
ResultBuilder b = new JSLintResult.ResultBuilder(systemId);
b.duration(TimeUnit.NANOSECONDS.toMillis(endNanos - startNanos));
for (Issue issue : readErrors(systemId)) {
b.addIssue(issue);
}
// Collect a report on what we've just linted.
b.report(callReport(false));
// Extract JSLINT.data() output and set it on the result.
Scriptable lintScope = (Scriptable) scope.get("JSLINT", scope);
Object o = lintScope.get("data", lintScope);
// Real JSLINT will always have this, but some of my test stubs don't.
if (o != UniqueTag.NOT_FOUND) {
Function reportFunc = (Function) o;
Scriptable data = (Scriptable) reportFunc.call(cx, scope,
scope, new Object[] {});
for (String global : Util.listValueOfType("globals", String.class, data)) {
b.addGlobal(global);
}
for (String url : Util.listValueOfType("urls", String.class, data)) {
b.addUrl(url);
}
b.json(Util.booleanValue("json", data));
for (JSFunction f : Util.listValue("functions", data, new JSFunctionConverter())) {
b.addFunction(f);
}
if (Boolean.TRUE.equals(options.get(Option.WARNINGS))) {
// Pull out the list of unused variables as issues. This doesn't appear
// to be a supported API, unfortunately, but it does work.
for (VariableWarning u : Util.listValue("unused", data,
new VariableWarningConverter())) {
b.addIssue(issueForUnusedVariable(u, systemId));
}
// There is also a list of undefined variables. But… these are already
// reported by JSLint. So let's not repeat them.
}
}
// Extract the list of properties. Note that we don't expose the counts, as it
// doesn't seem that useful.
Object properties = lintScope.get("property", lintScope);
if (properties != UniqueTag.NOT_FOUND) {
for (Object id: ScriptableObject.getPropertyIds((Scriptable) properties)) {
b.addProperty(id.toString());
}
}
return b.build();
}
});
}
|
private JSLintResult buildResults(final String systemId, final long startNanos, final long endNanos) {
return (JSLintResult) contextFactory.call(new ContextAction() {
public Object run(Context cx) {
ResultBuilder b = new JSLintResult.ResultBuilder(systemId);
b.duration(TimeUnit.NANOSECONDS.toMillis(endNanos - startNanos));
for (Issue issue : readErrors(systemId)) {
b.addIssue(issue);
}
// Collect a report on what we've just linted.
b.report(callReport(false));
// Extract JSLINT.data() output and set it on the result.
Scriptable lintScope = (Scriptable) scope.get("JSLINT", scope);
Object o = lintScope.get("data", lintScope);
// Real JSLINT will always have this, but some of my test stubs don't.
if (o != UniqueTag.NOT_FOUND) {
Function reportFunc = (Function) o;
Scriptable data = (Scriptable) reportFunc.call(cx, scope,
scope, new Object[] {});
for (String global : Util.listValueOfType("globals", String.class, data)) {
b.addGlobal(global);
}
for (String url : Util.listValueOfType("urls", String.class, data)) {
b.addUrl(url);
}
b.json(Util.booleanValue("json", data));
for (JSFunction f : Util.listValue("functions", data, new JSFunctionConverter())) {
b.addFunction(f);
}
// Pull out the list of unused variables as issues. This doesn't appear
// to be a supported API, unfortunately, but it does work.
for (VariableWarning u : Util.listValue("unused", data,
new VariableWarningConverter())) {
b.addIssue(issueForUnusedVariable(u, systemId));
}
// There is also a list of undefined variables. But… these are already
// reported by JSLint. So let's not repeat them.
}
// Extract the list of properties. Note that we don't expose the counts, as it
// doesn't seem that useful.
Object properties = lintScope.get("property", lintScope);
if (properties != UniqueTag.NOT_FOUND) {
for (Object id: ScriptableObject.getPropertyIds((Scriptable) properties)) {
b.addProperty(id.toString());
}
}
return b.build();
}
});
}
|
diff --git a/src/test/java/iron9light/coffeescriptMavenPlugin/test/CoffeeScriptCompilerTest.java b/src/test/java/iron9light/coffeescriptMavenPlugin/test/CoffeeScriptCompilerTest.java
index 4f292c0..2d6cfe8 100644
--- a/src/test/java/iron9light/coffeescriptMavenPlugin/test/CoffeeScriptCompilerTest.java
+++ b/src/test/java/iron9light/coffeescriptMavenPlugin/test/CoffeeScriptCompilerTest.java
@@ -1,22 +1,22 @@
package iron9light.coffeescriptMavenPlugin.test;
import iron9light.coffeescriptMavenPlugin.CoffeeScriptCompiler;
import org.junit.Test;
import java.net.MalformedURLException;
import java.net.URL;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
/**
* @author iron9light
*/
public class CoffeeScriptCompilerTest {
@Test
public void testVersion() throws MalformedURLException {
- URL url = getClass().getResource("/coffee-script-1.1.2.js");
+ URL url = getClass().getResource("/coffee-script.js");
CoffeeScriptCompiler compiler = new CoffeeScriptCompiler(url, false);
- assertThat(compiler.version, equalTo("1.1.2"));
+ assertThat(compiler.version, equalTo("1.1.3"));
}
}
| false | true |
public void testVersion() throws MalformedURLException {
URL url = getClass().getResource("/coffee-script-1.1.2.js");
CoffeeScriptCompiler compiler = new CoffeeScriptCompiler(url, false);
assertThat(compiler.version, equalTo("1.1.2"));
}
|
public void testVersion() throws MalformedURLException {
URL url = getClass().getResource("/coffee-script.js");
CoffeeScriptCompiler compiler = new CoffeeScriptCompiler(url, false);
assertThat(compiler.version, equalTo("1.1.3"));
}
|
diff --git a/webapp/src/uk/ac/horizon/ug/exploding/clientapi/ClientController.java b/webapp/src/uk/ac/horizon/ug/exploding/clientapi/ClientController.java
index 4f9a92f..9dd4d7d 100755
--- a/webapp/src/uk/ac/horizon/ug/exploding/clientapi/ClientController.java
+++ b/webapp/src/uk/ac/horizon/ug/exploding/clientapi/ClientController.java
@@ -1,602 +1,603 @@
/**
*
*/
package uk.ac.horizon.ug.exploding.clientapi;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import uk.ac.horizon.ug.exploding.db.Member;
//import uk.ac.horizon.ug.exploding.db.Message;
import uk.ac.horizon.ug.exploding.clientapi.LoginReplyMessage.Status;
import uk.ac.horizon.ug.exploding.db.ClientConversation;
import uk.ac.horizon.ug.exploding.db.Game;
import uk.ac.horizon.ug.exploding.db.MessageToClient;
import uk.ac.horizon.ug.exploding.db.Player;
import uk.ac.horizon.ug.exploding.db.Position;
import uk.ac.horizon.ug.exploding.db.TimelineEvent;
import uk.ac.horizon.ug.exploding.db.Zone;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.CompactWriter;
import com.thoughtworks.xstream.io.xml.DomDriver;
import equip2.core.IDataspace;
import equip2.core.ISession;
import equip2.core.QueryTemplate;
import equip2.spring.db.IDAllocator;
/**
* @author cmg
*
*/
public class ClientController {
private static final int CLIENT_VERSION = 1;
static Logger logger = Logger.getLogger(ClientController.class.getName());
protected IDataspace dataspace;
public void setDataspace(IDataspace dataspace)
{
this.dataspace = dataspace;
}
public IDataspace getDataspace()
{
return this.dataspace;
}
protected ClientSubscriptionManager clientSubscriptionManager;
public ClientSubscriptionManager getClientSubscriptionManager() {
return clientSubscriptionManager;
}
public void setClientSubscriptionManager(
ClientSubscriptionManager clientSubscriptionManager) {
this.clientSubscriptionManager = clientSubscriptionManager;
}
static XStream getXStream() {
XStream xs = new XStream(/*new DomDriver()*/);
xs.alias("login", LoginMessage.class);
xs.alias("reply", LoginReplyMessage.class);
xs.alias("list", LinkedList.class);
xs.alias("message", Message.class);
// game-specific types
xs.alias("zone", Zone.class);
xs.alias("position", Position.class);
xs.alias("player", Player.class);
xs.alias("member", uk.ac.horizon.ug.exploding.db.Member.class);
xs.alias("msg", uk.ac.horizon.ug.exploding.db.Message.class);
xs.alias("game", uk.ac.horizon.ug.exploding.db.Game.class);
return xs;
}
/** client login
* @throws IOException */
public ModelAndView login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
XStream xs = getXStream();
LoginMessage login = (LoginMessage)xs.fromXML(request.getReader());
logger.info("Login: "+login);
if (!"AndroidDevclient".equals(login.getClientType())) {
returnLoginError(LoginReplyMessage.Status.UNSUPPORTED_CLIENT_TYPE, "Client not supported ("+login.getClientType()+")", response);
return null;
}
if (login.getClientVersion()<CLIENT_VERSION) {
returnLoginError(LoginReplyMessage.Status.OLD_CLIENT_VERSION, "Client is too old (needs version "+CLIENT_VERSION+")", response);
return null;
}
if (login.getClientVersion()!=CLIENT_VERSION) {
returnLoginError(LoginReplyMessage.Status.BAD_CLIENT_VERSION, "Client is unknown (needs version "+CLIENT_VERSION+")", response);
return null;
}
ISession session = getDataspace().getSession();
session.begin();
// look for ClientConversation(s) with this client
QueryTemplate q = new QueryTemplate(ClientConversation.class);
q.addConstraintEq("clientID", login.getClientId());
Object ccs [] = session.match(q);
// first look for an association between this client and an active game to reuse...
Player player = null;
Game game = null;
boolean welcomeBack = false;
for (int cci=0; cci<ccs.length; cci++) {
ClientConversation cc = (ClientConversation)ccs[cci];
if (cc.getID().equals(login.getConversationId())) {
logger.warn("Received login for duplicate converation ID "+login.getConversationId());
session.end();
returnLoginError(LoginReplyMessage.Status.FAILED, "Please try again (duplicate conversation ID).", response);
return null;
}
if (cc.isSetActive() && cc.getActive()) {
// mark inactive!
cc.setActive(false);
logger.debug("Mark conversation "+cc.getID()+" with "+cc.getClientID()+" inactive on new login");
clientSubscriptionManager.handleConversationEnd(cc, session);
Game g = (Game) session.get(Game.class, cc.getGameID());
if (g.isSetState() && !Game.ENDED.equals(g.getState())) {
// jack pot
game = g;
player = (Player) session.get(Player.class, cc.getPlayerID());
welcomeBack = true;
logger.debug("Converation "+login.getConversationId()+" taking over Player "+player.getID()+" in game "+game.getID());
}
}
}
if (game==null) {
// look for an active game
Object games [] = session.match(new QueryTemplate(Game.class));
for (int gi=0; gi<games.length; gi++) {
Game g = (Game)games[gi];
if (g.isSetState() && !Game.ENDED.equals(g.getState())) {
game = g;
logger.debug("Client "+login.getClientId()+" joining active game "+game.getID());
}
}
if (game==null) {
logger.warn("No active game: client "+login.getClientId()+" rejected");
session.end();
returnLoginError(LoginReplyMessage.Status.GAME_NOT_FOUND, "No game available right now.", response);
return null;
}
}
if (player==null) {
// create a player
player = new Player();
player.setID(IDAllocator.getNewID(session, uk.ac.horizon.ug.exploding.db.Player.class, "P", null));
player.setName(login.getPlayerName());
player.setGameID(game.getID());
player.setCanAuthor(false); // have to earn the ability
player.setPoints(0);
player.setNewMemberQuota(1);
QueryTemplate pq = new QueryTemplate(Player.class);
pq.addConstraintEq("gameID", game.getID());
int playerCount = session.count(pq);
player.setColourRef(playerCount+1);
// Client will send an update when it can with Position
//player.setPosition(position);
session.add(player);
logger.info("Created player "+player.getID()+" ("+player.getName()+") for client "+login.getClientId());
}
else if (player.getName()!=login.getPlayerName() && login.getPlayerName()!=null && !login.getPlayerName().equals(player.getName())) {
logger.info("Updating player "+player.getID()+" name to "+login.getPlayerName()+" (was "+player.getName()+")");
player.setName(login.getPlayerName());
}
// create conversation
ClientConversation cc = new ClientConversation();
cc.setID(login.getConversationId());
cc.setActive(true);
cc.setClientID(login.getClientId());
cc.setClientType(login.getClientType());
cc.setClientVersion(login.getClientVersion());
cc.setCreationTime(System.currentTimeMillis());
cc.setNextSeqNo(1);
cc.setLastContactTime(0L);
cc.setGameID(game.getID());
cc.setPlayerID(player.getID());
session.add(cc);
logger.info("Created converation "+cc.getID()+" for client "+cc.getClientID()+" as player "+player.getID()+" in game "+game.getID());
clientSubscriptionManager.handleConversationStart(cc, session);
session.end();
LoginReplyMessage reply = new LoginReplyMessage();
reply.setGameStatus(GameStatus.valueOf(game.getState()));
reply.setGameId(game.getID());
reply.setMessage(welcomeBack ? "Welcome back" : "Welcome");
reply.setStatus(LoginReplyMessage.Status.OK);
response.setStatus(200);
Writer w = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), Charset.forName("UTF-8")));
xs.marshal(reply, new CompactWriter(w));
w.close();
logger.info("Sent login reply: "+reply);
return null;
}
private void returnLoginError(Status status, String message, HttpServletResponse response) throws IOException {
LoginReplyMessage reply = new LoginReplyMessage();
reply.setGameStatus(GameStatus.UNKNOWN);
reply.setMessage(message);
reply.setStatus(status);
XStream xs = getXStream();
response.setStatus(200);
PrintWriter pw = response.getWriter();
xs.toXML(reply, pw);
pw.close();
}
/** client messages exchange
* @throws IOException */
public ModelAndView messages(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String conversationID = request.getParameter("conversationID");
if (conversationID==null || conversationID.length()==0)
{
logger.warn("No conversationID parameter");
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No conversationID parameter");
return null;
}
XStream xs = getXStream();
List<Message> messages = (List<Message>)xs.fromXML(request.getReader());
logger.info("Got "+messages.size()+" messages: "+messages);
ISession session = dataspace.getSession();
session.begin();
ClientConversation conversation = (ClientConversation) session.get(ClientConversation.class, conversationID);
Game game = conversation!=null ? (Game)session.get(Game.class, conversation.getGameID()) : null;
session.end();
if (conversation==null) {
logger.warn("conversation "+conversationID+" unknown");
response.sendError(HttpServletResponse.SC_NOT_FOUND, "conversation "+conversationID+" unknown");
return null;
}
if (game==null) {
logger.warn("conversation "+conversationID+" references unknown game "+conversation.getGameID());
response.sendError(HttpServletResponse.SC_MOVED_PERMANENTLY, "conversation "+conversationID+" references unknown game "+conversation.getGameID());
return null;
}
if (!game.isSetState() || Game.ENDED.equals(game.getState())) {
logger.warn("Game "+game.getID()+" (conversation "+conversationID+") now inactive");
response.sendError(HttpServletResponse.SC_GONE, "game "+game.getID()+" now inactive");
return null;
}
if (!conversation.isSetActive() || !conversation.getActive()) {
logger.warn("conversation "+conversationID+" now inactive");
response.sendError(HttpServletResponse.SC_MOVED_PERMANENTLY, "conversation "+conversationID+" now inactive");
return null;
}
List<Message> responses = handleMessages(conversation, messages);
response.setStatus(200);
Writer w = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), Charset.forName("UTF-8")));
xs.marshal(responses, new CompactWriter(w));
w.close();
return null;
}
/** internal implementation */
public List<Message> handleMessages(ClientConversation conversation, List<Message> messages) {
List<Message> responses = new LinkedList<Message>();
for (Message message : messages)
handleMessage(conversation, message, responses);
return responses;
}
private void handleMessage(ClientConversation conversation, Message message, List<Message> responses) {
if (message.getType()==null) {
responses.add(createErrorMessage(message, MessageStatusType.INVALID_REQUEST, "No message type"));
return;
}
if (!message.getType().toServer()) {
responses.add(createErrorMessage(message, MessageStatusType.INVALID_REQUEST, "Message type "+message.getType()+" is not valid to server"));
return;
}
ISession session = dataspace.getSession();
session.begin();
try {
LinkedList<Message> newResponses = new LinkedList<Message>();
switch(message.getType()) {
//case NEW_CONV:// new conversation
//case FACT_EX: // fact already exists (matching a subscription)
//case FACT_ADD: // fact added (matching a subscription)
//case FACT_UPD: // fact updated (matching a subscription)
//case FACT_DEL: // fact deleted (matching a subscription)
//case POLL_RESP: // response to poll (e.g. no. messages still unsent)
case POLL: // poll request
handlePoll(conversation, message, newResponses, session);
break;
case ACK: // acknowledge message
case ADD_FACT:// request to add fact
case UPD_FACT:// request to update fact
case DEL_FACT:// request to delete fact
handleFactOperation(conversation, message, newResponses, session);
break;
//ERROR(false, true), // error response, e.g. to add/update/delete request
case SUBS_EN:// enable a subscription
case SUBS_DIS:// disable a subscription
// TODO implement
default:
newResponses.add(createErrorMessage(message, MessageStatusType.INTERNAL_ERROR, "Message type "+message.getType()+" not supported"));
break;
}
session.end();
// OK!
responses.addAll(newResponses);
}
catch (Exception e) {
logger.warn("Handling message "+message, e);
responses.add(createErrorMessage(message, MessageStatusType.INTERNAL_ERROR, "Exception: "+e));
}
}
private void handleFactOperation(ClientConversation conversation, Message message, List<Message> responses, ISession session) throws IllegalArgumentException, ClientAPIException, InstantiationException, IllegalAccessException {
// ....
Object oldVal = message.getOldVal();//!=null ? ClientSubscriptionManager.unmarshallFact(message.getOldVal()) : null;
Object newVal = message.getNewVal();//!=null ? ClientSubscriptionManager.unmarshallFact(message.getNewVal()) : null;
// APPLICATION-SPECIFIC SPECIAL CASES
if (newVal instanceof Player) {
if (message.getType()!=MessageType.UPD_FACT)
throw new ClientAPIException(MessageStatusType.NOT_PERMITTED, "Attempted "+message.getType()+" on Player (can only update)");
Player newPlayer = (Player)newVal;
if (newPlayer.getID()==null) {
// assume this player
Player player = (Player)session.get(Player.class, conversation.getPlayerID());
if (player==null) {
throw new ClientAPIException(MessageStatusType.INTERNAL_ERROR, "conversation Player "+conversation.getPlayerID()+" not found");
}
// position update?!
if (newPlayer.getPosition()!=null) {
logger.info("Updating position for player "+player.getID()+" to "+newPlayer.getPosition());
player.setPosition(newPlayer.getPosition());
player.setPositionUpdateTime(System.currentTimeMillis());
}
// nothing else should be updated!
}
return;
}
if (newVal instanceof Member) {
if (message.getType()==MessageType.ADD_FACT) {
Player player = (Player)session.get(Player.class, conversation.getPlayerID());
if (player==null)
throw new ClientAPIException(MessageStatusType.INTERNAL_ERROR, "conversation Player "+conversation.getPlayerID()+" not found");
if (player.getNewMemberQuota()<=0)
throw new ClientAPIException(MessageStatusType.NOT_PERMITTED, "Player "+player.getID()+" tried to create a Member but has no newMemberQuota left");
// reduce quota
player.setNewMemberQuota(player.getNewMemberQuota()-1);
Member newMember = (Member)newVal;
newMember.setID(IDAllocator.getNewID(session, Member.class, "M", null));
newMember.setPlayerID(conversation.getPlayerID());
newMember.setGameID(conversation.getGameID());
- newMember.setCarried(false);
+ if (!newMember.isSetCarried())
+ newMember.setCarried(false);
newMember.unsetParentMemberID();
if (player.isSetColourRef())
newMember.setColourRef(player.getColourRef());
// parent?!
QueryTemplate mt = new QueryTemplate(Member.class);
mt.addConstraintEq("playerID", conversation.getPlayerID());
mt.addConstraintIsNull("parentMemberID");
Object parentMembers []= session.match(mt);
if (parentMembers.length>0) {
Member parentMember = (Member)parentMembers[0];
newMember.setParentMemberID(parentMember.getID());
}
// check fields
- if (!newMember.isSetAction() || !newMember.isSetBrains() || !newMember.isSetHealth() || ! newMember.isSetPosition() || !newMember.isSetZone() || !newMember.isSetName())
+ if (!newMember.isSetAction() || !newMember.isSetBrains() || !newMember.isSetHealth() || !newMember.isSetCarried() || (!newMember.getCarried() && (! newMember.isSetPosition() || !newMember.isSetZone())) || !newMember.isSetName())
throw new ClientAPIException(MessageStatusType.INVALID_REQUEST, "new Member is missing required fields: "+newMember);
session.add(newMember);
logger.info("Adding new Member "+newMember+" for player "+conversation.getPlayerID());
return;
}
else if (message.getType()==MessageType.UPD_FACT) {
Member newMember = (Member)message.newVal;
Member member = (Member)session.get(Member.class, newMember.getID());
if (member==null)
throw new ClientAPIException(MessageStatusType.INVALID_REQUEST, "update unknown Member "+newMember.getID());
if (!member.getPlayerID().equals(conversation.getPlayerID()))
throw new ClientAPIException(MessageStatusType.INVALID_REQUEST, "update Member "+newMember.getID()+" owned by another Player ("+member.getPlayerID()+" vs "+conversation.getPlayerID());
if (newMember.isSetCarried())
member.setCarried(newMember.getCarried());
member.setPosition(newMember.getPosition());
if (newMember.isSetZone())
member.setZone(newMember.getZone());
logger.info("Updated Member "+member.getID()+": carried="+member.getCarried()+", zone="+member.getZone()+", position="+member.getPosition());
return;
}
else
throw new ClientAPIException(MessageStatusType.NOT_PERMITTED, "Attempted "+message.getType()+" on Member (can only add/update)");
}
if (newVal instanceof TimelineEvent) {
if (message.getType()!=MessageType.ADD_FACT)
throw new ClientAPIException(MessageStatusType.NOT_PERMITTED, "Attempted "+message.getType()+" on TimelineEvent (can only add)");
Player player = (Player)session.get(Player.class, conversation.getPlayerID());
if (player==null) {
throw new ClientAPIException(MessageStatusType.INTERNAL_ERROR, "conversation Player "+conversation.getPlayerID()+" not found");
}
if (!player.getCanAuthor())
throw new ClientAPIException(MessageStatusType.NOT_PERMITTED, "Player "+conversation.getPlayerID()+" attempted to add a TimelineEvent but is not canAuthor");
TimelineEvent newEvent = (TimelineEvent)newVal;
newEvent.setID(IDAllocator.getNewID(session, TimelineEvent.class, "TE", null));
Game game = (Game)session.get(Game.class, conversation.getGameID());
if (game==null)
throw new ClientAPIException(MessageStatusType.INTERNAL_ERROR, "conversation Game "+conversation.getGameID()+" not found");
newEvent.setContentGroupID(game.getContentGroupID());
// TODO validity check?
// TODO flags?
newEvent.setEnabled(0);
session.add(newEvent);
logger.info("Adding player("+player.getID()+")-authored TimelineEvent "+newEvent);
return;
}
logger.warn("Unhandled fact operation "+message.getType()+" "+message.getOldVal()+" -> "+message.getNewVal());
// generic
// switch (message.getType()) {
// case ADD_FACT: {
// if (oldVal!=null || newVal==null)
// throw new ClientAPIException(MessageStatusType.INVALID_REQUEST, "ADD_FACT with incorrect parameters: old="+oldVal+", new="+newVal);
// session.add(newVal);
// responses.add(createAckMessage(message));
// break;
// }
// case DEL_FACT: {
// if (oldVal==null || newVal!=null)
// throw new ClientAPIException(MessageStatusType.INVALID_REQUEST, "DEL_FACT with incorrect parameters: old="+oldVal+", new="+newVal);
// session.remove(oldVal);
// responses.add(createAckMessage(message));
// break;
// }
// case UPD_FACT: {
// if (oldVal==null || newVal==null)
// throw new ClientAPIException(MessageStatusType.INVALID_REQUEST, "UPD_FACT with incorrect parameters: old="+oldVal+", new="+newVal);
// session.remove(oldVal);
// session.add(newVal);
// // TODO use update if fixed in JPA drools
// responses.add(createAckMessage(message));
// break;
// }
// default:
// throw new RuntimeException("handleFactOperation called for message type "+message.getType());
// }
// TODO record of client action
}
private void handlePoll(ClientConversation conversation, Message message, List<Message> responses, ISession session) {
long time = System.currentTimeMillis();
int ackSeq = message.getAckSeq()!=null ? message.getAckSeq() : 0;
if (ackSeq>0) {
// ack
int removed = 0;
QueryTemplate q = new QueryTemplate(MessageToClient.class);
//("SELECT x FROM MessageToClient x WHERE x.clientId = :clientId AND x.ackedByClient = 0 AND x.seqNo <= :ackSeq");
q.addConstraintEq("clientID", conversation.getClientID());
q.addConstraintEq("ackedByClient", 0);
q.addConstraintLe("seqNo", ackSeq);
Object mtcs[] = session.match(q);
for (int mi=0; mi<mtcs.length; mi++) {
MessageToClient mtc = (MessageToClient)mtcs[mi];
mtc.setAckedByClient(time);
// delete on ack - we only have clientLifetime or not at the mo.
// (most messages are regenerated on new client)
//if (!mtc.isSetClientLifetime() || mtc.getClientLifetime()==false) {
session.remove(mtc);
removed ++;
//}
}
if (mtcs.length>0) {
logger.info("Acked "+mtcs.length+" messages to "+conversation.getClientID()+" (seq<="+ackSeq+") - "+removed+" removed");
}
}
//ClientConversation cc = em.find(ClientConversation.class, conversation.getConversationId());
// boolean checkToFollow = true;
int sentCount = 0;
int toFollow = 0;
if (message.getToFollow()==null || message.getToFollow()>0) {
// actually get some messages...
// TODO from
//Query q = em.createQuery ("SELECT x FROM MessageToClient x WHERE x.clientId = :clientId AND x.seqNo> :ackSeq ORDER BY x.seqNo ASC");
QueryTemplate q = new QueryTemplate(MessageToClient.class);
q.addConstraintEq("clientID", conversation.getClientID());
q.addConstraintGt("seqNo", ackSeq);
q.addOrder("seqNo", false);
if (message.getToFollow()!=null)
q.setMaxResults(message.getToFollow());
Object mtcs [] = session.match(q);
sentCount = mtcs.length;
if (message.getToFollow()==null || mtcs.length<message.getToFollow())
// can't be any left
; //checkToFollow = false;
else {
QueryTemplate q1 = new QueryTemplate(MessageToClient.class);
q1.addConstraintEq("clientID", conversation.getClientID());
q1.addConstraintGt("seqNo", ackSeq);
//Query q = em.createQuery ("SELECT COUNT(x) FROM MessageToClient x WHERE x.clientId = :clientId AND x.seqNo> :ackSeq ");
int countResult = session.count(q1);
toFollow = countResult-sentCount;
}
int removed = 0;
for (int mi=0; mi<mtcs.length; mi++) {
MessageToClient mtc = (MessageToClient)mtcs[mi];
Message msg = new Message();
//int seqNo = cc.getNextSeqNo();
msg.setSeqNo(mtc.getSeqNo());
//cc.setNextSeqNo(seqNo+1);
msg.setType(MessageType.values()[mtc.getType()]);
if (mtc.getOldVal()!=null)
msg.setOldVal(ClientSubscriptionManager.unmarshallFact(mtc.getOldVal()));
if (mtc.getNewVal()!=null)
msg.setNewVal(ClientSubscriptionManager.unmarshallFact(mtc.getNewVal()));
//msg.setSubsIx(mtc.getSubsIx());
//if (mtc.getHandle()!=null)
//msg.setHandle(mtc.getHandle());
responses.add(msg);
// mark sent
// delete on send?
//if (mtc.getLifetime()!=null && mtc.getLifetime()==ClientSubscriptionLifetimeType.UNTIL_SENT) {
// em.remove(mtc);
// removed ++;
//}
//else
mtc.setSentToClient(time);
}
if (removed>0) {
logger.info("Sent "+mtcs.length+" messages to "+conversation.getClientID()+" (seq>"+ackSeq+") - "+removed+" removed");
}
}
// response
Message pollResponse = new Message();
pollResponse.setAckSeq(message.getSeqNo());
if (message.getSubsIx()!=null)
pollResponse.setSubsIx(message.getSubsIx());
pollResponse.setType(MessageType.POLL_RESP);
pollResponse.setToFollow(toFollow);
responses.add(pollResponse);
}
private Message createErrorMessage(Message message,
MessageStatusType status, String errorMessage) {
Message response = new Message();
response.setAckSeq(message.getSeqNo());
response.setStatus(status);
response.setErrorMsg(errorMessage);
response.setType(MessageType.ERROR);
logger.warn("Error response to client: " +response);
return response;
}
private Message createAckMessage(Message message/*, String handle*/) {
Message response = new Message();
response.setAckSeq(message.getSeqNo());
response.setType(MessageType.ACK);
// if (handle!=null)
// response.setHandle(handle);
// logger.log(Level.WARNING, "Error response to client: " +response);
return response;
}
}
| false | true |
private void handleFactOperation(ClientConversation conversation, Message message, List<Message> responses, ISession session) throws IllegalArgumentException, ClientAPIException, InstantiationException, IllegalAccessException {
// ....
Object oldVal = message.getOldVal();//!=null ? ClientSubscriptionManager.unmarshallFact(message.getOldVal()) : null;
Object newVal = message.getNewVal();//!=null ? ClientSubscriptionManager.unmarshallFact(message.getNewVal()) : null;
// APPLICATION-SPECIFIC SPECIAL CASES
if (newVal instanceof Player) {
if (message.getType()!=MessageType.UPD_FACT)
throw new ClientAPIException(MessageStatusType.NOT_PERMITTED, "Attempted "+message.getType()+" on Player (can only update)");
Player newPlayer = (Player)newVal;
if (newPlayer.getID()==null) {
// assume this player
Player player = (Player)session.get(Player.class, conversation.getPlayerID());
if (player==null) {
throw new ClientAPIException(MessageStatusType.INTERNAL_ERROR, "conversation Player "+conversation.getPlayerID()+" not found");
}
// position update?!
if (newPlayer.getPosition()!=null) {
logger.info("Updating position for player "+player.getID()+" to "+newPlayer.getPosition());
player.setPosition(newPlayer.getPosition());
player.setPositionUpdateTime(System.currentTimeMillis());
}
// nothing else should be updated!
}
return;
}
if (newVal instanceof Member) {
if (message.getType()==MessageType.ADD_FACT) {
Player player = (Player)session.get(Player.class, conversation.getPlayerID());
if (player==null)
throw new ClientAPIException(MessageStatusType.INTERNAL_ERROR, "conversation Player "+conversation.getPlayerID()+" not found");
if (player.getNewMemberQuota()<=0)
throw new ClientAPIException(MessageStatusType.NOT_PERMITTED, "Player "+player.getID()+" tried to create a Member but has no newMemberQuota left");
// reduce quota
player.setNewMemberQuota(player.getNewMemberQuota()-1);
Member newMember = (Member)newVal;
newMember.setID(IDAllocator.getNewID(session, Member.class, "M", null));
newMember.setPlayerID(conversation.getPlayerID());
newMember.setGameID(conversation.getGameID());
newMember.setCarried(false);
newMember.unsetParentMemberID();
if (player.isSetColourRef())
newMember.setColourRef(player.getColourRef());
// parent?!
QueryTemplate mt = new QueryTemplate(Member.class);
mt.addConstraintEq("playerID", conversation.getPlayerID());
mt.addConstraintIsNull("parentMemberID");
Object parentMembers []= session.match(mt);
if (parentMembers.length>0) {
Member parentMember = (Member)parentMembers[0];
newMember.setParentMemberID(parentMember.getID());
}
// check fields
if (!newMember.isSetAction() || !newMember.isSetBrains() || !newMember.isSetHealth() || ! newMember.isSetPosition() || !newMember.isSetZone() || !newMember.isSetName())
throw new ClientAPIException(MessageStatusType.INVALID_REQUEST, "new Member is missing required fields: "+newMember);
session.add(newMember);
logger.info("Adding new Member "+newMember+" for player "+conversation.getPlayerID());
return;
}
else if (message.getType()==MessageType.UPD_FACT) {
Member newMember = (Member)message.newVal;
Member member = (Member)session.get(Member.class, newMember.getID());
if (member==null)
throw new ClientAPIException(MessageStatusType.INVALID_REQUEST, "update unknown Member "+newMember.getID());
if (!member.getPlayerID().equals(conversation.getPlayerID()))
throw new ClientAPIException(MessageStatusType.INVALID_REQUEST, "update Member "+newMember.getID()+" owned by another Player ("+member.getPlayerID()+" vs "+conversation.getPlayerID());
if (newMember.isSetCarried())
member.setCarried(newMember.getCarried());
member.setPosition(newMember.getPosition());
if (newMember.isSetZone())
member.setZone(newMember.getZone());
logger.info("Updated Member "+member.getID()+": carried="+member.getCarried()+", zone="+member.getZone()+", position="+member.getPosition());
return;
}
else
throw new ClientAPIException(MessageStatusType.NOT_PERMITTED, "Attempted "+message.getType()+" on Member (can only add/update)");
}
if (newVal instanceof TimelineEvent) {
if (message.getType()!=MessageType.ADD_FACT)
throw new ClientAPIException(MessageStatusType.NOT_PERMITTED, "Attempted "+message.getType()+" on TimelineEvent (can only add)");
Player player = (Player)session.get(Player.class, conversation.getPlayerID());
if (player==null) {
throw new ClientAPIException(MessageStatusType.INTERNAL_ERROR, "conversation Player "+conversation.getPlayerID()+" not found");
}
if (!player.getCanAuthor())
throw new ClientAPIException(MessageStatusType.NOT_PERMITTED, "Player "+conversation.getPlayerID()+" attempted to add a TimelineEvent but is not canAuthor");
TimelineEvent newEvent = (TimelineEvent)newVal;
newEvent.setID(IDAllocator.getNewID(session, TimelineEvent.class, "TE", null));
Game game = (Game)session.get(Game.class, conversation.getGameID());
if (game==null)
throw new ClientAPIException(MessageStatusType.INTERNAL_ERROR, "conversation Game "+conversation.getGameID()+" not found");
newEvent.setContentGroupID(game.getContentGroupID());
// TODO validity check?
// TODO flags?
newEvent.setEnabled(0);
session.add(newEvent);
logger.info("Adding player("+player.getID()+")-authored TimelineEvent "+newEvent);
return;
}
logger.warn("Unhandled fact operation "+message.getType()+" "+message.getOldVal()+" -> "+message.getNewVal());
// generic
// switch (message.getType()) {
// case ADD_FACT: {
// if (oldVal!=null || newVal==null)
// throw new ClientAPIException(MessageStatusType.INVALID_REQUEST, "ADD_FACT with incorrect parameters: old="+oldVal+", new="+newVal);
// session.add(newVal);
// responses.add(createAckMessage(message));
// break;
// }
// case DEL_FACT: {
// if (oldVal==null || newVal!=null)
// throw new ClientAPIException(MessageStatusType.INVALID_REQUEST, "DEL_FACT with incorrect parameters: old="+oldVal+", new="+newVal);
// session.remove(oldVal);
// responses.add(createAckMessage(message));
// break;
// }
// case UPD_FACT: {
// if (oldVal==null || newVal==null)
// throw new ClientAPIException(MessageStatusType.INVALID_REQUEST, "UPD_FACT with incorrect parameters: old="+oldVal+", new="+newVal);
// session.remove(oldVal);
// session.add(newVal);
// // TODO use update if fixed in JPA drools
// responses.add(createAckMessage(message));
// break;
// }
// default:
// throw new RuntimeException("handleFactOperation called for message type "+message.getType());
// }
// TODO record of client action
}
|
private void handleFactOperation(ClientConversation conversation, Message message, List<Message> responses, ISession session) throws IllegalArgumentException, ClientAPIException, InstantiationException, IllegalAccessException {
// ....
Object oldVal = message.getOldVal();//!=null ? ClientSubscriptionManager.unmarshallFact(message.getOldVal()) : null;
Object newVal = message.getNewVal();//!=null ? ClientSubscriptionManager.unmarshallFact(message.getNewVal()) : null;
// APPLICATION-SPECIFIC SPECIAL CASES
if (newVal instanceof Player) {
if (message.getType()!=MessageType.UPD_FACT)
throw new ClientAPIException(MessageStatusType.NOT_PERMITTED, "Attempted "+message.getType()+" on Player (can only update)");
Player newPlayer = (Player)newVal;
if (newPlayer.getID()==null) {
// assume this player
Player player = (Player)session.get(Player.class, conversation.getPlayerID());
if (player==null) {
throw new ClientAPIException(MessageStatusType.INTERNAL_ERROR, "conversation Player "+conversation.getPlayerID()+" not found");
}
// position update?!
if (newPlayer.getPosition()!=null) {
logger.info("Updating position for player "+player.getID()+" to "+newPlayer.getPosition());
player.setPosition(newPlayer.getPosition());
player.setPositionUpdateTime(System.currentTimeMillis());
}
// nothing else should be updated!
}
return;
}
if (newVal instanceof Member) {
if (message.getType()==MessageType.ADD_FACT) {
Player player = (Player)session.get(Player.class, conversation.getPlayerID());
if (player==null)
throw new ClientAPIException(MessageStatusType.INTERNAL_ERROR, "conversation Player "+conversation.getPlayerID()+" not found");
if (player.getNewMemberQuota()<=0)
throw new ClientAPIException(MessageStatusType.NOT_PERMITTED, "Player "+player.getID()+" tried to create a Member but has no newMemberQuota left");
// reduce quota
player.setNewMemberQuota(player.getNewMemberQuota()-1);
Member newMember = (Member)newVal;
newMember.setID(IDAllocator.getNewID(session, Member.class, "M", null));
newMember.setPlayerID(conversation.getPlayerID());
newMember.setGameID(conversation.getGameID());
if (!newMember.isSetCarried())
newMember.setCarried(false);
newMember.unsetParentMemberID();
if (player.isSetColourRef())
newMember.setColourRef(player.getColourRef());
// parent?!
QueryTemplate mt = new QueryTemplate(Member.class);
mt.addConstraintEq("playerID", conversation.getPlayerID());
mt.addConstraintIsNull("parentMemberID");
Object parentMembers []= session.match(mt);
if (parentMembers.length>0) {
Member parentMember = (Member)parentMembers[0];
newMember.setParentMemberID(parentMember.getID());
}
// check fields
if (!newMember.isSetAction() || !newMember.isSetBrains() || !newMember.isSetHealth() || !newMember.isSetCarried() || (!newMember.getCarried() && (! newMember.isSetPosition() || !newMember.isSetZone())) || !newMember.isSetName())
throw new ClientAPIException(MessageStatusType.INVALID_REQUEST, "new Member is missing required fields: "+newMember);
session.add(newMember);
logger.info("Adding new Member "+newMember+" for player "+conversation.getPlayerID());
return;
}
else if (message.getType()==MessageType.UPD_FACT) {
Member newMember = (Member)message.newVal;
Member member = (Member)session.get(Member.class, newMember.getID());
if (member==null)
throw new ClientAPIException(MessageStatusType.INVALID_REQUEST, "update unknown Member "+newMember.getID());
if (!member.getPlayerID().equals(conversation.getPlayerID()))
throw new ClientAPIException(MessageStatusType.INVALID_REQUEST, "update Member "+newMember.getID()+" owned by another Player ("+member.getPlayerID()+" vs "+conversation.getPlayerID());
if (newMember.isSetCarried())
member.setCarried(newMember.getCarried());
member.setPosition(newMember.getPosition());
if (newMember.isSetZone())
member.setZone(newMember.getZone());
logger.info("Updated Member "+member.getID()+": carried="+member.getCarried()+", zone="+member.getZone()+", position="+member.getPosition());
return;
}
else
throw new ClientAPIException(MessageStatusType.NOT_PERMITTED, "Attempted "+message.getType()+" on Member (can only add/update)");
}
if (newVal instanceof TimelineEvent) {
if (message.getType()!=MessageType.ADD_FACT)
throw new ClientAPIException(MessageStatusType.NOT_PERMITTED, "Attempted "+message.getType()+" on TimelineEvent (can only add)");
Player player = (Player)session.get(Player.class, conversation.getPlayerID());
if (player==null) {
throw new ClientAPIException(MessageStatusType.INTERNAL_ERROR, "conversation Player "+conversation.getPlayerID()+" not found");
}
if (!player.getCanAuthor())
throw new ClientAPIException(MessageStatusType.NOT_PERMITTED, "Player "+conversation.getPlayerID()+" attempted to add a TimelineEvent but is not canAuthor");
TimelineEvent newEvent = (TimelineEvent)newVal;
newEvent.setID(IDAllocator.getNewID(session, TimelineEvent.class, "TE", null));
Game game = (Game)session.get(Game.class, conversation.getGameID());
if (game==null)
throw new ClientAPIException(MessageStatusType.INTERNAL_ERROR, "conversation Game "+conversation.getGameID()+" not found");
newEvent.setContentGroupID(game.getContentGroupID());
// TODO validity check?
// TODO flags?
newEvent.setEnabled(0);
session.add(newEvent);
logger.info("Adding player("+player.getID()+")-authored TimelineEvent "+newEvent);
return;
}
logger.warn("Unhandled fact operation "+message.getType()+" "+message.getOldVal()+" -> "+message.getNewVal());
// generic
// switch (message.getType()) {
// case ADD_FACT: {
// if (oldVal!=null || newVal==null)
// throw new ClientAPIException(MessageStatusType.INVALID_REQUEST, "ADD_FACT with incorrect parameters: old="+oldVal+", new="+newVal);
// session.add(newVal);
// responses.add(createAckMessage(message));
// break;
// }
// case DEL_FACT: {
// if (oldVal==null || newVal!=null)
// throw new ClientAPIException(MessageStatusType.INVALID_REQUEST, "DEL_FACT with incorrect parameters: old="+oldVal+", new="+newVal);
// session.remove(oldVal);
// responses.add(createAckMessage(message));
// break;
// }
// case UPD_FACT: {
// if (oldVal==null || newVal==null)
// throw new ClientAPIException(MessageStatusType.INVALID_REQUEST, "UPD_FACT with incorrect parameters: old="+oldVal+", new="+newVal);
// session.remove(oldVal);
// session.add(newVal);
// // TODO use update if fixed in JPA drools
// responses.add(createAckMessage(message));
// break;
// }
// default:
// throw new RuntimeException("handleFactOperation called for message type "+message.getType());
// }
// TODO record of client action
}
|
diff --git a/src/main/java/com/alta189/chavaadmin/ConnectListener.java b/src/main/java/com/alta189/chavaadmin/ConnectListener.java
index f7adba8..050fed8 100644
--- a/src/main/java/com/alta189/chavaadmin/ConnectListener.java
+++ b/src/main/java/com/alta189/chavaadmin/ConnectListener.java
@@ -1,25 +1,25 @@
package com.alta189.chavaadmin;
import com.alta189.chavabot.ChavaManager;
import com.alta189.chavabot.events.Listener;
import com.alta189.chavabot.events.ircevents.ConnectEvent;
public class ConnectListener implements Listener<ConnectEvent> {
public void onEvent(ConnectEvent event) {
- if (ChavaAdmin.getSettings().getPropertyBoolean("znc-auth-enabled", false)) {
+ if (ChavaAdmin.getSettings().checkProperty("znc-auth-enabled") && ChavaAdmin.getSettings().getPropertyBoolean("znc-auth-enabled", false)) {
String user = ChavaAdmin.getSettings().getPropertyString("znc-user", null);
String pass = ChavaAdmin.getSettings().getPropertyString("znc-pass", null);
if (user != null && pass != null) {
ChavaManager.getInstance().getChavaBot().sendRawLine(new StringBuilder().append("PASS ").append(user).append(":").append(pass).toString());
}
}
String logChan = ChavaAdmin.getLogChannel();
if (logChan != null) {
ChavaManager.getInstance().getChavaBot().joinChannel(logChan);
}
}
}
| true | true |
public void onEvent(ConnectEvent event) {
if (ChavaAdmin.getSettings().getPropertyBoolean("znc-auth-enabled", false)) {
String user = ChavaAdmin.getSettings().getPropertyString("znc-user", null);
String pass = ChavaAdmin.getSettings().getPropertyString("znc-pass", null);
if (user != null && pass != null) {
ChavaManager.getInstance().getChavaBot().sendRawLine(new StringBuilder().append("PASS ").append(user).append(":").append(pass).toString());
}
}
String logChan = ChavaAdmin.getLogChannel();
if (logChan != null) {
ChavaManager.getInstance().getChavaBot().joinChannel(logChan);
}
}
|
public void onEvent(ConnectEvent event) {
if (ChavaAdmin.getSettings().checkProperty("znc-auth-enabled") && ChavaAdmin.getSettings().getPropertyBoolean("znc-auth-enabled", false)) {
String user = ChavaAdmin.getSettings().getPropertyString("znc-user", null);
String pass = ChavaAdmin.getSettings().getPropertyString("znc-pass", null);
if (user != null && pass != null) {
ChavaManager.getInstance().getChavaBot().sendRawLine(new StringBuilder().append("PASS ").append(user).append(":").append(pass).toString());
}
}
String logChan = ChavaAdmin.getLogChannel();
if (logChan != null) {
ChavaManager.getInstance().getChavaBot().joinChannel(logChan);
}
}
|
diff --git a/POS/src/ee/ut/math/tvt/salessystem/ui/PaymentConfirmation.java b/POS/src/ee/ut/math/tvt/salessystem/ui/PaymentConfirmation.java
index c1d8c7f..72b2a1e 100644
--- a/POS/src/ee/ut/math/tvt/salessystem/ui/PaymentConfirmation.java
+++ b/POS/src/ee/ut/math/tvt/salessystem/ui/PaymentConfirmation.java
@@ -1,213 +1,213 @@
package ee.ut.math.tvt.salessystem.ui;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
/**
* Purhase confirmation dialog
*
* @author TKasekamp
*
*/
public class PaymentConfirmation extends JDialog {
private boolean accepted;
private double payment = 0;
private double sum;
private static final long serialVersionUID = 1L;
private JLabel sumPayment;
private JTextField changePayment;
private JTextField amountField;
private JButton acceptPayment;
private JButton cancelPayment;
private JLabel message;
public PaymentConfirmation(JFrame frame, boolean modal, double sum) {
super(frame, modal);
this.sum = sum;
this.add(draw());
setTitle("Confirm purchase");
pack();
int width = 300;
int height = 200;
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation((screen.width - width) / 2,
(screen.height - height) / 2);
this.setSize(width, height);
setVisible(true);
}
private JPanel draw() {
JPanel panel = new JPanel();
setLayout(new GridLayout(5, 2));
// Initialize the buttons
acceptPayment = createAcceptPaymentButton();
cancelPayment = createCancelPaymentButton();
// Sum from purchase table
sumPayment = new JLabel();
- sumPayment.setText(Double.toString(sum));
+ sumPayment.setText(Double.toString(Math.round((sum*100))/100.0));
changePayment = new JTextField();
changePayment.setText("0");
changePayment.setEnabled(false);
amountField = new JFormattedTextField();
amountField.setText("0");
amountField.setColumns(10);
amountField.getDocument().addDocumentListener(new Dkuular());
// Warning message
message = new JLabel("");
add(new JLabel("Total: "));
add(sumPayment);
add(new JLabel("Return amount: "));
add(changePayment);
add(new JLabel("Enter money here: "));
add(amountField);
add(acceptPayment);
add(cancelPayment);
add(message);
return panel;
}
/**
* For checking if the purchase was accepted in the <code>PurchaseTab</code>
*
* @return boolean
*/
public boolean isAccepted() {
return accepted;
}
/**
* Creates the Accept payment button
*
* @return button
*/
private JButton createAcceptPaymentButton() {
JButton b = new JButton("Accept");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
acceptButtonClicked();
}
});
return b;
}
/**
* Creates the Cancel payment button
*
* @return button
*/
private JButton createCancelPaymentButton() {
JButton b = new JButton("Cancel");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cancelButtonClicked();
}
});
return b;
}
private void acceptButtonClicked() {
boolean allnumbers = true;
if (amountField.getText().isEmpty()) {
allnumbers = false;
message.setText("Enter more money");
}
for (int i = 0; i < amountField.getText().length(); i++) {
if (!Character.isDigit(amountField.getText().charAt(i))) {
message.setText("Enter integers only");
allnumbers = false;
}
}
if (allnumbers == true) {
// Checking if there is enough money entered
payment = ((Number) Double.parseDouble(amountField.getText()))
.doubleValue();
if ((payment - sum) >= 0) {
message.setText("Purchase accepted");
accepted = true;
setVisible(false);
} else {
message.setText("Enter more money");
}
}
}
private void cancelButtonClicked() {
amountField.setText("0");
changePayment.setText("0");
accepted = false;
setVisible(false);
}
/**
* Updates return amount in confirmation window.
*
*
*/
class Dkuular implements DocumentListener {
@Override
public void insertUpdate(DocumentEvent e) {
update();
}
@Override
public void removeUpdate(DocumentEvent e) {
if (amountField.getText().isEmpty() == false) {
update();
} else {
changePayment.setText("0");
}
}
@Override
public void changedUpdate(DocumentEvent e) {
update();
}
private void update() {
try {
payment = ((Number) Double.parseDouble(amountField.getText()))
.doubleValue();
changePayment.setText(Double.toString(Math.round((payment - sum)*100)/100.0));
} catch (NumberFormatException ex) { // handle your exception
changePayment.setText("0");
}
}
}
}
| true | true |
private JPanel draw() {
JPanel panel = new JPanel();
setLayout(new GridLayout(5, 2));
// Initialize the buttons
acceptPayment = createAcceptPaymentButton();
cancelPayment = createCancelPaymentButton();
// Sum from purchase table
sumPayment = new JLabel();
sumPayment.setText(Double.toString(sum));
changePayment = new JTextField();
changePayment.setText("0");
changePayment.setEnabled(false);
amountField = new JFormattedTextField();
amountField.setText("0");
amountField.setColumns(10);
amountField.getDocument().addDocumentListener(new Dkuular());
// Warning message
message = new JLabel("");
add(new JLabel("Total: "));
add(sumPayment);
add(new JLabel("Return amount: "));
add(changePayment);
add(new JLabel("Enter money here: "));
add(amountField);
add(acceptPayment);
add(cancelPayment);
add(message);
return panel;
}
|
private JPanel draw() {
JPanel panel = new JPanel();
setLayout(new GridLayout(5, 2));
// Initialize the buttons
acceptPayment = createAcceptPaymentButton();
cancelPayment = createCancelPaymentButton();
// Sum from purchase table
sumPayment = new JLabel();
sumPayment.setText(Double.toString(Math.round((sum*100))/100.0));
changePayment = new JTextField();
changePayment.setText("0");
changePayment.setEnabled(false);
amountField = new JFormattedTextField();
amountField.setText("0");
amountField.setColumns(10);
amountField.getDocument().addDocumentListener(new Dkuular());
// Warning message
message = new JLabel("");
add(new JLabel("Total: "));
add(sumPayment);
add(new JLabel("Return amount: "));
add(changePayment);
add(new JLabel("Enter money here: "));
add(amountField);
add(acceptPayment);
add(cancelPayment);
add(message);
return panel;
}
|
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/widgets/ConnectionStateComposite.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/widgets/ConnectionStateComposite.java
index 2897ad43a..f6472238f 100644
--- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/widgets/ConnectionStateComposite.java
+++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/widgets/ConnectionStateComposite.java
@@ -1,135 +1,137 @@
package de.fu_berlin.inf.dpp.ui.widgets;
import java.text.MessageFormat;
import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.widgets.Composite;
import org.jivesoftware.smack.Connection;
import org.picocontainer.annotations.Inject;
import de.fu_berlin.inf.dpp.Saros;
import de.fu_berlin.inf.dpp.SarosPluginContext;
import de.fu_berlin.inf.dpp.accountManagement.XMPPAccountStore;
import de.fu_berlin.inf.dpp.net.ConnectionState;
import de.fu_berlin.inf.dpp.net.IConnectionListener;
import de.fu_berlin.inf.dpp.net.JID;
import de.fu_berlin.inf.dpp.ui.Messages;
import de.fu_berlin.inf.dpp.ui.SarosUI;
import de.fu_berlin.inf.dpp.ui.views.SarosView;
import de.fu_berlin.inf.dpp.util.Utils;
import de.fu_berlin.inf.nebula.utils.FontUtils;
import de.fu_berlin.inf.nebula.utils.LayoutUtils;
public class ConnectionStateComposite extends Composite {
private static final String CONNECTED_TOOLTIP = Messages.ConnectionStateComposite_tooltip_connected;
private static final Logger log = Logger
.getLogger(ConnectionStateComposite.class);
protected final IConnectionListener connectionListener = new IConnectionListener() {
public void connectionStateChanged(Connection connection,
final ConnectionState newState) {
Utils.runSafeSWTAsync(log, new Runnable() {
public void run() {
updateLabel(newState);
}
});
}
};
@Inject
protected Saros saros;
@Inject
protected SarosUI sarosUI;
@Inject
protected XMPPAccountStore accountStore;
protected CLabel stateLabel;
public ConnectionStateComposite(Composite parent, int style) {
super(parent, style);
SarosPluginContext.initComponent(this);
this.setLayout(LayoutUtils.createGridLayout(1, false, 10, 3, 0, 0));
stateLabel = new CLabel(this, SWT.NONE);
stateLabel.setLayoutData(LayoutUtils.createFillHGrabGridData());
FontUtils.makeBold(stateLabel);
updateLabel(saros.getSarosNet().getConnectionState());
this.stateLabel.setForeground(getDisplay().getSystemColor(
SWT.COLOR_WHITE));
this.stateLabel.setBackground(getDisplay().getSystemColor(
SWT.COLOR_DARK_GRAY));
this.setBackground(getDisplay().getSystemColor(SWT.COLOR_DARK_GRAY));
saros.getSarosNet().addListener(connectionListener);
}
@Override
public void dispose() {
super.dispose();
saros.getSarosNet().removeListener(connectionListener);
}
protected void updateLabel(ConnectionState newState) {
if (stateLabel != null && !stateLabel.isDisposed()) {
stateLabel.setText(getDescription(newState));
if (newState == ConnectionState.CONNECTED) {
stateLabel.setToolTipText(String.format(CONNECTED_TOOLTIP,
saros.getVersion()));
} else {
stateLabel.setToolTipText(null);
}
layout();
}
}
/**
* @param state
* @return a nice string description of the given state, which can be used
* to be shown in labels (e.g. CONNECTING becomes "Connecting...").
*/
public String getDescription(ConnectionState state) {
if (accountStore.isEmpty()) {
return Messages.ConnectionStateComposite_info_add_jabber_account;
}
Exception e = null;
switch (state) {
case NOT_CONNECTED:
+ // FIXME: fix SarosNet if no ERROR is reported !!!
e = saros.getSarosNet().getConnectionError();
- if (e.toString().equalsIgnoreCase("stream:error (text)")) {
+ if (e != null
+ && e.toString().equalsIgnoreCase("stream:error (text)")) {
// the same user logged in via xmpp on another server/host
SarosView.showNotification("XMPP Connection lost",
Messages.ConnectionStateComposite_remote_login_warning);
}
return Messages.ConnectionStateComposite_not_connected;
case CONNECTING:
return Messages.ConnectionStateComposite_connecting;
case CONNECTED:
JID jid = new JID(saros.getSarosNet().getConnection().getUser());
return jid.getBase();
case DISCONNECTING:
return Messages.ConnectionStateComposite_disconnecting;
case ERROR:
e = saros.getSarosNet().getConnectionError();
if (e == null) {
return Messages.ConnectionStateComposite_error;
} else if (e.toString().equalsIgnoreCase("stream:error (conflict)")) { //$NON-NLS-1$
return Messages.ConnectionStateComposite_error_ressource_conflict;
} else {
return MessageFormat.format(
Messages.ConnectionStateComposite_error_with_message,
e.getMessage());
}
default:
return Messages.ConnectionStateComposite_error_unknown;
}
}
}
| false | true |
public String getDescription(ConnectionState state) {
if (accountStore.isEmpty()) {
return Messages.ConnectionStateComposite_info_add_jabber_account;
}
Exception e = null;
switch (state) {
case NOT_CONNECTED:
e = saros.getSarosNet().getConnectionError();
if (e.toString().equalsIgnoreCase("stream:error (text)")) {
// the same user logged in via xmpp on another server/host
SarosView.showNotification("XMPP Connection lost",
Messages.ConnectionStateComposite_remote_login_warning);
}
return Messages.ConnectionStateComposite_not_connected;
case CONNECTING:
return Messages.ConnectionStateComposite_connecting;
case CONNECTED:
JID jid = new JID(saros.getSarosNet().getConnection().getUser());
return jid.getBase();
case DISCONNECTING:
return Messages.ConnectionStateComposite_disconnecting;
case ERROR:
e = saros.getSarosNet().getConnectionError();
if (e == null) {
return Messages.ConnectionStateComposite_error;
} else if (e.toString().equalsIgnoreCase("stream:error (conflict)")) { //$NON-NLS-1$
return Messages.ConnectionStateComposite_error_ressource_conflict;
} else {
return MessageFormat.format(
Messages.ConnectionStateComposite_error_with_message,
e.getMessage());
}
default:
return Messages.ConnectionStateComposite_error_unknown;
}
}
|
public String getDescription(ConnectionState state) {
if (accountStore.isEmpty()) {
return Messages.ConnectionStateComposite_info_add_jabber_account;
}
Exception e = null;
switch (state) {
case NOT_CONNECTED:
// FIXME: fix SarosNet if no ERROR is reported !!!
e = saros.getSarosNet().getConnectionError();
if (e != null
&& e.toString().equalsIgnoreCase("stream:error (text)")) {
// the same user logged in via xmpp on another server/host
SarosView.showNotification("XMPP Connection lost",
Messages.ConnectionStateComposite_remote_login_warning);
}
return Messages.ConnectionStateComposite_not_connected;
case CONNECTING:
return Messages.ConnectionStateComposite_connecting;
case CONNECTED:
JID jid = new JID(saros.getSarosNet().getConnection().getUser());
return jid.getBase();
case DISCONNECTING:
return Messages.ConnectionStateComposite_disconnecting;
case ERROR:
e = saros.getSarosNet().getConnectionError();
if (e == null) {
return Messages.ConnectionStateComposite_error;
} else if (e.toString().equalsIgnoreCase("stream:error (conflict)")) { //$NON-NLS-1$
return Messages.ConnectionStateComposite_error_ressource_conflict;
} else {
return MessageFormat.format(
Messages.ConnectionStateComposite_error_with_message,
e.getMessage());
}
default:
return Messages.ConnectionStateComposite_error_unknown;
}
}
|
diff --git a/src/main/java/org/neo4j/kernel/impl/core/TransactionEventsSyncHook.java b/src/main/java/org/neo4j/kernel/impl/core/TransactionEventsSyncHook.java
index 1264c6e5..ff31ca0e 100644
--- a/src/main/java/org/neo4j/kernel/impl/core/TransactionEventsSyncHook.java
+++ b/src/main/java/org/neo4j/kernel/impl/core/TransactionEventsSyncHook.java
@@ -1,94 +1,93 @@
package org.neo4j.kernel.impl.core;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.transaction.Status;
import javax.transaction.Synchronization;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.event.TransactionData;
import org.neo4j.graphdb.event.TransactionEventHandler;
public class TransactionEventsSyncHook<T> implements Synchronization
{
private final Collection<TransactionEventHandler<T>> handlers;
private final NodeManager nodeManager;
private final Transaction transaction;
/**
* This is null at construction time, then populated in beforeCompletion and
* used in afterCompletion.
*/
private List<HandlerAndState> states;
private TransactionData transactionData;
public TransactionEventsSyncHook(
NodeManager nodeManager, Transaction transaction,
Collection<TransactionEventHandler<T>> transactionEventHandlers )
{
this.nodeManager = nodeManager;
this.transaction = transaction;
this.handlers = transactionEventHandlers;
}
public void beforeCompletion()
{
- TransactionData data = null;
- data = nodeManager.getTransactionData();
+ this.transactionData = nodeManager.getTransactionData();
states = new ArrayList<HandlerAndState>();
for ( TransactionEventHandler<T> handler : this.handlers )
{
try
{
- T state = handler.beforeCommit( data );
+ T state = handler.beforeCommit( transactionData );
states.add( new HandlerAndState( handler, state ) );
}
catch ( Throwable t )
{
// TODO Do something more than calling failure and
// throw exception?
transaction.failure();
// This will cause the transaction to throw a
// TransactionFailureException
throw new RuntimeException( t );
}
}
}
public void afterCompletion( int status )
{
if ( status == Status.STATUS_COMMITTED )
{
for ( HandlerAndState state : this.states )
{
state.handler.afterCommit( this.transactionData, state.state );
}
}
else if ( status == Status.STATUS_ROLLEDBACK )
{
for ( HandlerAndState state : this.states )
{
state.handler.afterRollback( this.transactionData, state.state );
}
}
else
{
throw new RuntimeException( "Unknown status " + status );
}
}
private class HandlerAndState
{
private final TransactionEventHandler<T> handler;
private final T state;
public HandlerAndState( TransactionEventHandler<T> handler, T state )
{
this.handler = handler;
this.state = state;
}
}
}
| false | true |
public void beforeCompletion()
{
TransactionData data = null;
data = nodeManager.getTransactionData();
states = new ArrayList<HandlerAndState>();
for ( TransactionEventHandler<T> handler : this.handlers )
{
try
{
T state = handler.beforeCommit( data );
states.add( new HandlerAndState( handler, state ) );
}
catch ( Throwable t )
{
// TODO Do something more than calling failure and
// throw exception?
transaction.failure();
// This will cause the transaction to throw a
// TransactionFailureException
throw new RuntimeException( t );
}
}
}
|
public void beforeCompletion()
{
this.transactionData = nodeManager.getTransactionData();
states = new ArrayList<HandlerAndState>();
for ( TransactionEventHandler<T> handler : this.handlers )
{
try
{
T state = handler.beforeCommit( transactionData );
states.add( new HandlerAndState( handler, state ) );
}
catch ( Throwable t )
{
// TODO Do something more than calling failure and
// throw exception?
transaction.failure();
// This will cause the transaction to throw a
// TransactionFailureException
throw new RuntimeException( t );
}
}
}
|
diff --git a/src/be/ibridge/kettle/spoon/Spoon.java b/src/be/ibridge/kettle/spoon/Spoon.java
index a5ecf0f0..a6804533 100644
--- a/src/be/ibridge/kettle/spoon/Spoon.java
+++ b/src/be/ibridge/kettle/spoon/Spoon.java
@@ -1,8660 +1,8664 @@
/**********************************************************************
** **
** 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.spoon;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabFolder2Adapter;
import org.eclipse.swt.custom.CTabFolderEvent;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import be.ibridge.kettle.chef.ChefGraph;
import be.ibridge.kettle.chef.ChefHistory;
import be.ibridge.kettle.chef.ChefHistoryRefresher;
import be.ibridge.kettle.chef.ChefLog;
import be.ibridge.kettle.chef.wizards.RipDatabaseWizardPage1;
import be.ibridge.kettle.chef.wizards.RipDatabaseWizardPage2;
import be.ibridge.kettle.chef.wizards.RipDatabaseWizardPage3;
import be.ibridge.kettle.cluster.ClusterSchema;
import be.ibridge.kettle.cluster.SlaveServer;
import be.ibridge.kettle.cluster.dialog.ClusterSchemaDialog;
import be.ibridge.kettle.cluster.dialog.SlaveServerDialog;
import be.ibridge.kettle.core.AddUndoPositionInterface;
import be.ibridge.kettle.core.ChangedFlagInterface;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.DBCache;
import be.ibridge.kettle.core.DragAndDropContainer;
import be.ibridge.kettle.core.GUIResource;
import be.ibridge.kettle.core.KettleVariables;
import be.ibridge.kettle.core.LastUsedFile;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.NotePadMeta;
import be.ibridge.kettle.core.Point;
import be.ibridge.kettle.core.PrintSpool;
import be.ibridge.kettle.core.Props;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.SharedObjectInterface;
import be.ibridge.kettle.core.SourceToTargetMapping;
import be.ibridge.kettle.core.TransAction;
import be.ibridge.kettle.core.WindowProperty;
import be.ibridge.kettle.core.XMLHandler;
import be.ibridge.kettle.core.XMLTransfer;
import be.ibridge.kettle.core.clipboard.ImageDataTransfer;
import be.ibridge.kettle.core.database.Database;
import be.ibridge.kettle.core.database.DatabaseMeta;
import be.ibridge.kettle.core.dialog.CheckResultDialog;
import be.ibridge.kettle.core.dialog.DatabaseDialog;
import be.ibridge.kettle.core.dialog.DatabaseExplorerDialog;
import be.ibridge.kettle.core.dialog.EnterMappingDialog;
import be.ibridge.kettle.core.dialog.EnterOptionsDialog;
import be.ibridge.kettle.core.dialog.EnterSearchDialog;
import be.ibridge.kettle.core.dialog.EnterSelectionDialog;
import be.ibridge.kettle.core.dialog.EnterStringDialog;
import be.ibridge.kettle.core.dialog.EnterStringsDialog;
import be.ibridge.kettle.core.dialog.ErrorDialog;
import be.ibridge.kettle.core.dialog.PreviewRowsDialog;
import be.ibridge.kettle.core.dialog.SQLEditor;
import be.ibridge.kettle.core.dialog.SQLStatementsDialog;
import be.ibridge.kettle.core.dialog.ShowBrowserDialog;
import be.ibridge.kettle.core.dialog.Splash;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleStepException;
import be.ibridge.kettle.core.reflection.StringSearchResult;
import be.ibridge.kettle.core.util.EnvUtil;
import be.ibridge.kettle.core.value.Value;
import be.ibridge.kettle.core.widget.TreeMemory;
import be.ibridge.kettle.core.wizards.createdatabase.CreateDatabaseWizard;
import be.ibridge.kettle.job.JobEntryLoader;
import be.ibridge.kettle.job.JobHopMeta;
import be.ibridge.kettle.job.JobMeta;
import be.ibridge.kettle.job.JobPlugin;
import be.ibridge.kettle.job.dialog.JobDialog;
import be.ibridge.kettle.job.dialog.JobLoadProgressDialog;
import be.ibridge.kettle.job.dialog.JobSaveProgressDialog;
import be.ibridge.kettle.job.entry.JobEntryCopy;
import be.ibridge.kettle.job.entry.JobEntryDialogInterface;
import be.ibridge.kettle.job.entry.JobEntryInterface;
import be.ibridge.kettle.job.entry.special.JobEntrySpecial;
import be.ibridge.kettle.job.entry.sql.JobEntrySQL;
import be.ibridge.kettle.job.entry.trans.JobEntryTrans;
import be.ibridge.kettle.pan.CommandLineOption;
import be.ibridge.kettle.partition.PartitionSchema;
import be.ibridge.kettle.partition.dialog.PartitionSchemaDialog;
import be.ibridge.kettle.pkg.JarfileGenerator;
import be.ibridge.kettle.repository.PermissionMeta;
import be.ibridge.kettle.repository.RepositoriesMeta;
import be.ibridge.kettle.repository.Repository;
import be.ibridge.kettle.repository.RepositoryDirectory;
import be.ibridge.kettle.repository.RepositoryMeta;
import be.ibridge.kettle.repository.RepositoryObject;
import be.ibridge.kettle.repository.UserInfo;
import be.ibridge.kettle.repository.dialog.RepositoriesDialog;
import be.ibridge.kettle.repository.dialog.RepositoryExplorerDialog;
import be.ibridge.kettle.repository.dialog.SelectObjectDialog;
import be.ibridge.kettle.repository.dialog.UserDialog;
import be.ibridge.kettle.spoon.dialog.AnalyseImpactProgressDialog;
import be.ibridge.kettle.spoon.dialog.CheckTransProgressDialog;
import be.ibridge.kettle.spoon.dialog.GetJobSQLProgressDialog;
import be.ibridge.kettle.spoon.dialog.GetSQLProgressDialog;
import be.ibridge.kettle.spoon.dialog.ShowCreditsDialog;
import be.ibridge.kettle.spoon.dialog.TipsDialog;
import be.ibridge.kettle.spoon.wizards.CopyTableWizardPage1;
import be.ibridge.kettle.spoon.wizards.CopyTableWizardPage2;
import be.ibridge.kettle.trans.DatabaseImpact;
import be.ibridge.kettle.trans.HasDatabasesInterface;
import be.ibridge.kettle.trans.StepLoader;
import be.ibridge.kettle.trans.StepPlugin;
import be.ibridge.kettle.trans.TransConfiguration;
import be.ibridge.kettle.trans.TransExecutionConfiguration;
import be.ibridge.kettle.trans.TransHopMeta;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.cluster.TransSplitter;
import be.ibridge.kettle.trans.dialog.TransDialog;
import be.ibridge.kettle.trans.dialog.TransExecutionConfigurationDialog;
import be.ibridge.kettle.trans.dialog.TransHopDialog;
import be.ibridge.kettle.trans.dialog.TransLoadProgressDialog;
import be.ibridge.kettle.trans.dialog.TransSaveProgressDialog;
import be.ibridge.kettle.trans.step.BaseStep;
import be.ibridge.kettle.trans.step.StepDialogInterface;
import be.ibridge.kettle.trans.step.StepMeta;
import be.ibridge.kettle.trans.step.StepMetaInterface;
import be.ibridge.kettle.trans.step.StepPartitioningMeta;
import be.ibridge.kettle.trans.step.selectvalues.SelectValuesMeta;
import be.ibridge.kettle.trans.step.tableinput.TableInputMeta;
import be.ibridge.kettle.trans.step.tableoutput.TableOutputMeta;
import be.ibridge.kettle.version.BuildVersion;
import be.ibridge.kettle.www.AddTransServlet;
import be.ibridge.kettle.www.PrepareExecutionTransHandler;
import be.ibridge.kettle.www.StartExecutionTransHandler;
import be.ibridge.kettle.www.WebResult;
/**
* This class handles the main window of the Spoon graphical transformation editor.
*
* @author Matt
* @since 16-may-2003, i18n at 07-Feb-2006, redesign 01-Dec-2006
*/
public class Spoon implements AddUndoPositionInterface
{
public static final String APP_NAME = Messages.getString("Spoon.Application.Name"); //"Spoon";
private static Spoon staticSpoon;
private LogWriter log;
private Display disp;
private Shell shell;
private boolean destroy;
private SashForm sashform;
public CTabFolder tabfolder;
public boolean shift;
public boolean control;
public Row variables;
/**
* These are the arguments that were given at Spoon launch time...
*/
private String[] arguments;
private boolean stopped;
private Cursor cursor_hourglass, cursor_hand;
public Props props;
public Repository rep;
/**
* This contains a map between the name of a transformation and the TransMeta object.
* If the transformation has no name it will be mapped under a number [1], [2] etc.
*/
private Map transformationMap;
/**
* This contains a map between the name of a transformation and the TransMeta object.
* If the transformation has no name it will be mapped under a number [1], [2] etc.
*/
private Map jobMap;
/**
* This contains a map between the name of the tab name and the object name and type
*/
private Map tabMap;
/**
* This contains a map with all the unnamed transformation (just a filename)
*/
private ToolBar tBar;
private Menu msFile;
private MenuItem miFileSep3;
private MenuItem miEditUndo, miEditRedo;
private Tree selectionTree;
private TreeItem tiTransBase, tiJobBase;
private Tree coreObjectsTree;
public static final String STRING_TRANSFORMATIONS = Messages.getString("Spoon.STRING_TRANSFORMATIONS"); // Transformations
public static final String STRING_JOBS = Messages.getString("Spoon.STRING_JOBS"); // Jobs
public static final String STRING_BUILDING_BLOCKS = Messages.getString("Spoon.STRING_BUILDING_BLOCKS"); // Building blocks
public static final String STRING_ELEMENTS = Messages.getString("Spoon.STRING_ELEMENTS"); // Model elements
public static final String STRING_CONNECTIONS = Messages.getString("Spoon.STRING_CONNECTIONS"); // Connections
public static final String STRING_STEPS = Messages.getString("Spoon.STRING_STEPS"); // Steps
public static final String STRING_JOB_ENTRIES = Messages.getString("Spoon.STRING_JOB_ENTRIES"); // Job entries
public static final String STRING_HOPS = Messages.getString("Spoon.STRING_HOPS"); // Hops
public static final String STRING_PARTITIONS = Messages.getString("Spoon.STRING_PARTITIONS"); // Database Partition schemas
public static final String STRING_SLAVES = Messages.getString("Spoon.STRING_SLAVES"); // Slave servers
public static final String STRING_CLUSTERS = Messages.getString("Spoon.STRING_CLUSTERS"); // Cluster Schemas
public static final String STRING_TRANS_BASE = Messages.getString("Spoon.STRING_BASE"); // Base step types
public static final String STRING_JOB_BASE = Messages.getString("Spoon.STRING_JOBENTRY_BASE"); // Base job entry types
public static final String STRING_HISTORY = Messages.getString("Spoon.STRING_HISTORY"); // Step creation history
public static final String STRING_TRANS_NO_NAME = Messages.getString("Spoon.STRING_TRANS_NO_NAME"); // <unnamed transformation>
public static final String STRING_JOB_NO_NAME = Messages.getString("Spoon.STRING_JOB_NO_NAME"); // <unnamed job>
public static final String STRING_TRANSFORMATION = Messages.getString("Spoon.STRING_TRANSFORMATION"); // Transformation
public static final String STRING_JOB = Messages.getString("Spoon.STRING_JOB"); // Job
private static final String APPL_TITLE = APP_NAME;
private static final String STRING_WELCOME_TAB_NAME = "Welcome!";
private static final String URL_WELCOME_PAGE = "http://kettle.pentaho.org";
public static final int STATE_CORE_OBJECTS_NONE = 1; // No core objects
public static final int STATE_CORE_OBJECTS_CHEF = 2; // Chef state: job entries
public static final int STATE_CORE_OBJECTS_SPOON = 3; // Spoon state: steps
public KeyAdapter defKeys;
public KeyAdapter modKeys;
private Menu mBar;
private Composite tabComp;
private SashForm leftSash;
private TransExecutionConfiguration executionConfiguration;
private TreeItem tiTrans, tiJobs;
private Menu spoonMenu; // Connections, Steps & hops
private MenuItem miFileClose, miFileSave, miFileSaveAs, miFilePrint;
private MenuItem miEditSelectAll, miEditUnselectAll, miEditCopy, miEditPaste;
private MenuItem miTransRun, miTransPreview, miTransCheck, miTransImpact, miTransSQL, miLastImpact, miLastCheck, miLastPreview, miTransCopy, miTransPaste, miTransImage, miTransDetails;
private MenuItem miWizardCopyTable, miWizardNewConnection, miWizardRipDatabase;
private MenuItem miRepDisconnect, miRepUser, miRepExplore;
private MenuItem miJobRun, miJobCopy, miJobPaste, miJobInfo;
private int coreObjectsState = STATE_CORE_OBJECTS_NONE;
private ToolItem tiSQL, tiImpact, tiFileCheck, tiFileReplay, tiFilePreview, tiFileRun, tiFilePrint, tiFileSaveAs, tiFileSave;
public Spoon(LogWriter l, Repository rep)
{
this(l, null, null, rep);
}
public Spoon(LogWriter l, Display d, Repository rep)
{
this(l, d, null, rep);
}
public Spoon(LogWriter log, Display d, TransMeta ti, Repository rep)
{
this.log = log;
this.rep = rep;
if (d!=null)
{
disp=d;
destroy=false;
}
else
{
disp=new Display();
destroy=true;
}
shell=new Shell(disp);
shell.setText(APPL_TITLE);
FormLayout layout = new FormLayout();
layout.marginWidth = 0;
layout.marginHeight = 0;
shell.setLayout (layout);
transformationMap = new Hashtable();
jobMap = new Hashtable();
tabMap = new Hashtable();
// INIT Data structure
if (ti!=null)
{
addTransformation(ti);
}
if (!Props.isInitialized())
{
//log.logDetailed(toString(), "Load properties for Spoon...");
log.logDetailed(toString(),Messages.getString("Spoon.Log.LoadProperties"));
Props.init(disp, Props.TYPE_PROPERTIES_SPOON); // things to remember...
}
props=Props.getInstance();
// Load settings in the props
loadSettings();
executionConfiguration = new TransExecutionConfiguration();
// Clean out every time we start, auto-loading etc, is not a good idea
// If they are needed that often, set them in the kettle.properties file
//
variables = new Row();
// props.setLook(shell);
shell.setImage(GUIResource.getInstance().getImageSpoon());
cursor_hourglass = new Cursor(disp, SWT.CURSOR_WAIT);
cursor_hand = new Cursor(disp, SWT.CURSOR_HAND);
// widgets = new WidgetContainer();
defKeys = new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
TransMeta transMeta = getActiveTransformation();
JobMeta jobMeta = getActiveJob();
UndoInterface undoInterface = getActiveUndoInterface();
SpoonLog spoonLog = getActiveSpoonLog();
boolean ctrl = (( e.stateMask&SWT.CONTROL)!=0);
boolean alt = (( e.stateMask&SWT.ALT)!=0);
// ESC --> Unselect All steps
if (e.keyCode == SWT.ESC && !ctrl && !alt)
{
if (transMeta!=null) { transMeta.unselectAll(); refreshGraph(); }
if (jobMeta!=null) { jobMeta.unselectAll(); refreshGraph(); }
};
// F3 --> createDatabaseWizard
if (e.keyCode == SWT.F3 && !ctrl && !alt) { createDatabaseWizard(transMeta); }
// F4 --> copyTableWizard
if (e.keyCode == SWT.F4 && !ctrl && !alt) { copyTableWizard(); }
// CTRL-F4 --> close active transformation
if (e.keyCode == SWT.F4 && ctrl && !alt) { closeFile(); }
// F5 --> refresh
if (e.keyCode == SWT.F5 && !ctrl && !alt) { refreshGraph(); refreshTree(); }
// F6 --> show last impact analyses
if (e.keyCode == SWT.F6 && !ctrl && !alt) { showLastImpactAnalyses(transMeta); }
// F7 --> show last verify results
if (e.keyCode == SWT.F7 && !ctrl && !alt) { showLastTransCheck(); }
// F8 --> show last preview
if (e.keyCode == SWT.F8 && !ctrl && !alt) { if (spoonLog!=null) { spoonLog.showPreview(); } }
// F9 --> run
if (e.keyCode == SWT.F9 && !ctrl && !alt) { executeFile(true, false, false, false, null); }
// F10 --> preview
if (e.keyCode == SWT.F10 && !ctrl && !alt) { executeFile(true, false, false, true, null); }
// CTRL-F10 --> ripDB wizard
if (e.keyCode == SWT.F12 && ctrl && !alt) { ripDBWizard(); }
// F11 --> Verify
if (e.keyCode == SWT.F11 && !ctrl && !alt) { checkTrans(transMeta); }
// CTRL-A --> Select All steps
if ((int)e.character == 1 && ctrl && !alt)
{
if (transMeta!=null) { transMeta.selectAll(); refreshGraph(); }
if (jobMeta!=null) { jobMeta.selectAll(); refreshGraph(); }
};
// CTRL-D --> Disconnect from repository
if ((int)e.character == 4 && ctrl && !alt) { closeRepository(); };
// CTRL-E --> Explore the repository
if ((int)e.character == 5 && ctrl && !alt) { exploreRepository(); };
// CTRL-F --> Java examination
if ((int)e.character == 6 && ctrl && !alt ) { searchMetaData(); };
// CTRL-I --> Import from XML file && (e.keyCode&SWT.CONTROL)!=0
if ((int)e.character == 9 && ctrl && !alt ) { openFile(true); };
// CTRL-ALT-I --> Copy Transformation Image to clipboard
if ((int)e.character == 9 && ctrl && alt) { if (transMeta!=null) { copyTransformationImage(transMeta); } }
// CTRL-J --> Edit job properties
if ((int)e.character == 10 && ctrl && !alt ) { editJobProperties(jobMeta); };
// CTRL-ALT-J --> Get variables
if ((int)e.character == 10 && ctrl && alt ) { getVariables(); };
// CTRL-K --> Create Kettle archive
if ((int)e.character == 11 && ctrl && !alt ) { if (transMeta!=null) { createKettleArchive(transMeta); } };
// CTRL-L --> Show variables
if ((int)e.character == 12 && ctrl && !alt ) { showVariables(); };
// CTRL-N --> new
if ((int)e.character == 14 && ctrl && !alt) { newFile(); }
// CTRL-O --> open
if ((int)e.character == 15 && ctrl && !alt) { openFile(false); }
// CTRL-P --> print
if ((int)e.character == 16 && ctrl && !alt) { printFile(); }
// CTRL-Q --> Impact analyses
if ((int)e.character == 17 && ctrl && !alt) { analyseImpact(transMeta);}
// CTRL-R --> Connect to repository
if ((int)e.character == 18 && ctrl && !alt) { openRepository(); };
// CTRL-S --> save
if ((int)e.character == 19 && ctrl && !alt) { saveFile(); }
// CTRL-ALT-S --> send to slave server
if ((int)e.character == 19 && ctrl && alt) { executeFile(false, true, false, false, null); }
// CTRL-T --> transformation
if ((int)e.character == 20 && ctrl && !alt) { editTransformationProperties(transMeta); }
// CTRL-U --> transformation replay
if ((int)e.character == 21 && ctrl && !alt) { executeFile(false, false, true, false, null); }
// CTRL-Y --> redo action
if ((int)e.character == 25 && ctrl && !alt) { redoAction(undoInterface); }
// CTRL-Z --> undo action
if ((int)e.character == 26 && ctrl && !alt) { undoAction(undoInterface); }
}
};
modKeys = new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
shift = (e.keyCode == SWT.SHIFT );
control = (e.keyCode == SWT.CONTROL);
}
public void keyReleased(KeyEvent e)
{
shift = (e.keyCode == SWT.SHIFT );
control = (e.keyCode == SWT.CONTROL);
}
};
addBar();
FormData fdBar = new FormData();
fdBar.left = new FormAttachment(0, 0);
fdBar.top = new FormAttachment(0, 0);
tBar.setLayoutData(fdBar);
sashform = new SashForm(shell, SWT.HORIZONTAL);
// props.setLook(sashform);
FormData fdSash = new FormData();
fdSash.left = new FormAttachment(0, 0);
fdSash.top = new FormAttachment(tBar, 0);
fdSash.bottom = new FormAttachment(100, 0);
fdSash.right = new FormAttachment(100, 0);
sashform.setLayoutData(fdSash);
addMenu();
addTree();
addTabs();
// In case someone dares to press the [X] in the corner ;-)
shell.addShellListener(
new ShellAdapter()
{
public void shellClosed(ShellEvent e)
{
e.doit=quitFile();
}
}
);
// Add a browser widget
if (props.showWelcomePageOnStartup())
{
addSpoonBrowser(STRING_WELCOME_TAB_NAME, "http://kettle.pentaho.org"); // ./docs/English/tips/index.htm
}
shell.layout();
// Set the shell size, based upon previous time...
WindowProperty winprop = props.getScreen(APPL_TITLE);
if (winprop!=null) winprop.setShell(shell);
else
{
shell.pack();
shell.setMaximized(true); // Default = maximized!
}
}
public static Spoon getInstance()
{
return staticSpoon;
}
/**
* Add a transformation to the
* @param transMeta the transformation to add to the map
* @return the key used to store the transformation in the map
*/
public String addTransformation(TransMeta transMeta)
{
String key = makeGraphTabName(transMeta);
if (transformationMap.get(key)==null)
{
transformationMap.put(key, transMeta);
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(Messages.getString("Spoon.Dialog.TransAlreadyLoaded.Message")); // Transformation is already loaded
mb.setText(Messages.getString("Spoon.Dialog.TransAlreadyLoaded.Title")); // Sorry!
mb.open();
}
return key;
}
/**
* Add a job to the job map
* @param jobMeta the job to add to the map
* @return the key used to store the transformation in the map
*/
public String addJob(JobMeta jobMeta)
{
String key = makeJobGraphTabName(jobMeta);
if (jobMap.get(key)==null)
{
jobMap.put(key, jobMeta);
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(Messages.getString("Spoon.Dialog.JobAlreadyLoaded.Message")); // Transformation is already loaded
mb.setText(Messages.getString("Spoon.Dialog.JobAlreadyLoaded.Title")); // Sorry!
mb.open();
}
return key;
}
public void closeFile()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null) closeTransformation(transMeta);
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null) closeJob(jobMeta);
}
/**
* @param transMeta the transformation to close, make sure it's ok to dispose of it BEFORE you call this.
*/
public void closeTransformation(TransMeta transMeta)
{
String tabName = makeGraphTabName(transMeta);
transformationMap.remove(tabName);
tabMap.remove(tabName);
// Close the associated tabs...
// Graph
String graphTabName = makeGraphTabName(transMeta);
CTabItem graphTab = findCTabItem(graphTabName);
if (graphTab!=null)
{
graphTab.dispose();
tabMap.remove(graphTabName);
}
// Logging
String logTabName = makeLogTabName(transMeta);
CTabItem logTab = findCTabItem(logTabName);
if (logTab!=null)
{
logTab.dispose();
tabMap.remove(logTabName);
}
//History
String historyTabName = makeHistoryTabName(transMeta);
CTabItem historyTab = findCTabItem(historyTabName);
if (historyTab!=null)
{
historyTab.dispose();
tabMap.remove(historyTabName);
}
refreshTree();
}
/**
* @param transMeta the transformation to close, make sure it's ok to dispose of it BEFORE you call this.
*/
public void closeJob(JobMeta jobMeta)
{
String tabName = makeJobGraphTabName(jobMeta);
jobMap.remove(tabName);
tabMap.remove(tabName);
// Close the associated tabs...
// Graph
String graphTabName = makeJobGraphTabName(jobMeta);
CTabItem graphTab = findCTabItem(graphTabName);
if (graphTab!=null)
{
graphTab.dispose();
tabMap.remove(graphTabName);
}
// Logging
String logTabName = makeJobLogTabName(jobMeta);
CTabItem logTab = findCTabItem(logTabName);
if (logTab!=null)
{
logTab.dispose();
tabMap.remove(logTabName);
}
//History
String historyTabName = makeJobHistoryTabName(jobMeta);
CTabItem historyTab = findCTabItem(historyTabName);
if (historyTab!=null)
{
historyTab.dispose();
tabMap.remove(historyTabName);
}
refreshTree();
}
public void closeSpoonBrowser()
{
tabMap.remove(STRING_WELCOME_TAB_NAME);
CTabItem tab = findCTabItem(STRING_WELCOME_TAB_NAME);
if (tab!=null) tab.dispose();
}
/**
* Search the transformation meta-data.
*
*/
public void searchMetaData()
{
TransMeta[] transMetas = getLoadedTransformations();
JobMeta[] jobMetas = getLoadedJobs();
if ( (transMetas==null || transMetas.length==0) && (jobMetas==null || jobMetas.length==0)) return;
EnterSearchDialog esd = new EnterSearchDialog(shell);
if (!esd.open())
{
return;
}
ArrayList rows = new ArrayList();
for (int t=0;t<transMetas.length;t++)
{
TransMeta transMeta = transMetas[t];
String filterString = esd.getFilterString();
String filter = filterString;
if (filter!=null) filter = filter.toUpperCase();
List stringList = transMeta.getStringList(esd.isSearchingSteps(), esd.isSearchingDatabases(), esd.isSearchingNotes());
for (int i=0;i<stringList.size();i++)
{
StringSearchResult result = (StringSearchResult) stringList.get(i);
boolean add = Const.isEmpty(filter);
if (filter!=null && result.getString().toUpperCase().indexOf(filter)>=0) add=true;
if (filter!=null && result.getFieldName().toUpperCase().indexOf(filter)>=0) add=true;
if (filter!=null && result.getParentObject().toString().toUpperCase().indexOf(filter)>=0) add=true;
if (filter!=null && result.getGrandParentObject().toString().toUpperCase().indexOf(filter)>=0) add=true;
if (add) rows.add(result.toRow());
}
}
for (int t=0;t<jobMetas.length;t++)
{
JobMeta jobMeta = jobMetas[t];
String filterString = esd.getFilterString();
String filter = filterString;
if (filter!=null) filter = filter.toUpperCase();
List stringList = jobMeta.getStringList(esd.isSearchingSteps(), esd.isSearchingDatabases(), esd.isSearchingNotes());
for (int i=0;i<stringList.size();i++)
{
StringSearchResult result = (StringSearchResult) stringList.get(i);
boolean add = Const.isEmpty(filter);
if (filter!=null && result.getString().toUpperCase().indexOf(filter)>=0) add=true;
if (filter!=null && result.getFieldName().toUpperCase().indexOf(filter)>=0) add=true;
if (filter!=null && result.getParentObject().toString().toUpperCase().indexOf(filter)>=0) add=true;
if (filter!=null && result.getGrandParentObject().toString().toUpperCase().indexOf(filter)>=0) add=true;
if (add) rows.add(result.toRow());
}
}
if (rows.size()!=0)
{
PreviewRowsDialog prd = new PreviewRowsDialog(shell, SWT.NONE, "String searcher", rows);
prd.open();
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(Messages.getString("Spoon.Dialog.NothingFound.Message")); // Nothing found that matches your criteria
mb.setText(Messages.getString("Spoon.Dialog.NothingFound.Title")); // Sorry!
mb.open();
}
}
public void getVariables()
{
TransMeta[] transMetas = getLoadedTransformations();
JobMeta[] jobMetas = getLoadedJobs();
if ( (transMetas==null || transMetas.length==0) && (jobMetas==null || jobMetas.length==0)) return;
KettleVariables kettleVariables = KettleVariables.getInstance();
Properties sp = new Properties();
sp.putAll(kettleVariables.getProperties());
sp.putAll(System.getProperties());
for (int t=0;t<transMetas.length;t++)
{
TransMeta transMeta = transMetas[t];
List list = transMeta.getUsedVariables();
for (int i=0;i<list.size();i++)
{
String varName = (String)list.get(i);
String varValue = sp.getProperty(varName, "");
if (variables.searchValueIndex(varName)<0 && !varName.startsWith(Const.INTERNAL_VARIABLE_PREFIX))
{
variables.addValue(new Value(varName, varValue));
}
}
}
for (int t=0;t<jobMetas.length;t++)
{
JobMeta jobMeta = jobMetas[t];
List list = jobMeta.getUsedVariables();
for (int i=0;i<list.size();i++)
{
String varName = (String)list.get(i);
String varValue = sp.getProperty(varName, "");
if (variables.searchValueIndex(varName)<0 && !varName.startsWith(Const.INTERNAL_VARIABLE_PREFIX))
{
variables.addValue(new Value(varName, varValue));
}
}
}
// Now ask the use for more info on these!
EnterStringsDialog esd = new EnterStringsDialog(shell, SWT.NONE, variables);
esd.setTitle(Messages.getString("Spoon.Dialog.SetVariables.Title"));
esd.setMessage(Messages.getString("Spoon.Dialog.SetVariables.Message"));
esd.setReadOnly(false);
if (esd.open()!=null)
{
for (int i=0;i<variables.size();i++)
{
Value varval = variables.getValue(i);
if (!Const.isEmpty(varval.getString()))
{
kettleVariables.setVariable(varval.getName(), varval.getString());
}
}
}
}
public void showVariables()
{
Properties sp = new Properties();
KettleVariables kettleVariables = KettleVariables.getInstance();
sp.putAll(kettleVariables.getProperties());
sp.putAll(System.getProperties());
Row allVars = new Row();
Enumeration keys = kettleVariables.getProperties().keys();
while (keys.hasMoreElements())
{
String key = (String) keys.nextElement();
String value = kettleVariables.getVariable(key);
allVars.addValue(new Value(key, value));
}
// Now ask the use for more info on these!
EnterStringsDialog esd = new EnterStringsDialog(shell, SWT.NONE, allVars);
esd.setTitle(Messages.getString("Spoon.Dialog.ShowVariables.Title"));
esd.setMessage(Messages.getString("Spoon.Dialog.ShowVariables.Message"));
esd.setReadOnly(true);
esd.open();
}
public void open()
{
shell.open();
// Shared database entries to load from repository?
// loadRepositoryObjects();
// Load shared objects from XML file.
// loadSharedObjects();
// Perhaps the transformation contains elements at startup?
refreshTree(); // Do a complete refresh then...
setShellText();
if (props.showTips())
{
TipsDialog tip = new TipsDialog(shell, props);
tip.open();
}
}
public boolean readAndDispatch ()
{
return disp.readAndDispatch();
}
/**
* @return check whether or not the application was stopped.
*/
public boolean isStopped()
{
return stopped;
}
/**
* @param stopped True to stop this application.
*/
public void setStopped(boolean stopped)
{
this.stopped = stopped;
}
/**
* @param destroy Whether or not to distroy the display.
*/
public void setDestroy(boolean destroy)
{
this.destroy = destroy;
}
/**
* @return Returns whether or not we should distroy the display.
*/
public boolean doDestroy()
{
return destroy;
}
/**
* @param arguments The arguments to set.
*/
public void setArguments(String[] arguments)
{
this.arguments = arguments;
}
/**
* @return Returns the arguments.
*/
public String[] getArguments()
{
return arguments;
}
public synchronized void dispose()
{
setStopped(true);
cursor_hand.dispose();
cursor_hourglass.dispose();
if (destroy && !disp.isDisposed()) disp.dispose();
}
public boolean isDisposed()
{
return disp.isDisposed();
}
public void sleep()
{
disp.sleep();
}
public void addMenu()
{
if (mBar!=null && !mBar.isDisposed())
{
mBar.dispose();
}
mBar = new Menu(shell, SWT.BAR);
shell.setMenuBar(mBar);
////////////////////////////////////////////////////////////
// File
//
//
// main File menu...
MenuItem mFile = new MenuItem(mBar, SWT.CASCADE);
//mFile.setText("&File");
mFile.setText(Messages.getString("Spoon.Menu.File") );
if (msFile!=null && !msFile.isDisposed())
{
msFile.dispose();
}
msFile = new Menu(shell, SWT.DROP_DOWN);
mFile.setMenu(msFile);
// New
//
MenuItem miFileNew = new MenuItem(msFile, SWT.CASCADE);
miFileNew.setText(Messages.getString("Spoon.Menu.File.New")); //miFileNew.setText("&New \tCTRL-N");
miFileNew.addListener (SWT.Selection, new Listener() { public void handleEvent(Event e) { newFile(); } } );
// Open
//
MenuItem miFileOpen = new MenuItem(msFile, SWT.CASCADE);
miFileOpen.setText(Messages.getString("Spoon.Menu.File.Open")); //&Open \tCTRL-O
miFileOpen.addListener (SWT.Selection, new Listener() { public void handleEvent(Event e) { openFile(false); } });
// Import from XML
//
MenuItem miFileImport = new MenuItem(msFile, SWT.CASCADE);
miFileImport.setText(Messages.getString("Spoon.Menu.File.Import")); //"&Import from an XML file\tCTRL-I"
miFileImport.addListener (SWT.Selection, new Listener() { public void handleEvent(Event e) { openFile(true); } });
// Export to XML
//
MenuItem miFileExport = new MenuItem(msFile, SWT.CASCADE);
miFileExport.setText(Messages.getString("Spoon.Menu.File.Export")); //&Export to an XML file
miFileExport.addListener (SWT.Selection, new Listener() { public void handleEvent(Event e) { saveXMLFile(); } });
// Save
//
miFileSave = new MenuItem(msFile, SWT.CASCADE);
miFileSave.setText(Messages.getString("Spoon.Menu.File.Save")); //"&Save \tCTRL-S"
miFileSave.addListener (SWT.Selection, new Listener() { public void handleEvent(Event e) { saveFile(); } });
// Save as
//
miFileSaveAs = new MenuItem(msFile, SWT.CASCADE);
miFileSaveAs.setText(Messages.getString("Spoon.Menu.File.SaveAs")); //"Save &as..."
miFileSaveAs.addListener (SWT.Selection, new Listener() { public void handleEvent(Event e) { saveFileAs(); } });
// Close
//
miFileClose = new MenuItem(msFile, SWT.CASCADE);
miFileClose.setText(Messages.getString("Spoon.Menu.File.Close")); //&Close \tCTRL-F4
miFileClose.addListener (SWT.Selection, new Listener() { public void handleEvent(Event e) { closeFile(); } });
new MenuItem(msFile, SWT.SEPARATOR);
// Print
//
miFilePrint = new MenuItem(msFile, SWT.CASCADE);
miFilePrint.setText(Messages.getString("Spoon.Menu.File.Print")); //"&Print \tCTRL-P"
miFilePrint.addListener (SWT.Selection, new Listener() { public void handleEvent(Event e) { printFile(); } });
new MenuItem(msFile, SWT.SEPARATOR);
// Quit
//
MenuItem miFileQuit = new MenuItem(msFile, SWT.CASCADE);
miFileQuit.setText(Messages.getString("Spoon.Menu.File.Quit")); //miFileQuit.setText("&Quit");
miFileQuit.addListener (SWT.Selection, new Listener() { public void handleEvent(Event e) { quitFile(); } });
miFileSep3= new MenuItem(msFile, SWT.SEPARATOR);
// History
addMenuLast();
////////////////////////////////////////////////////////////
// Edit
//
//
// main Edit menu...
MenuItem mEdit = new MenuItem(mBar, SWT.CASCADE);
mEdit.setText(Messages.getString("Spoon.Menu.Edit")); //&Edit
Menu msEdit = new Menu(shell, SWT.DROP_DOWN);
mEdit.setMenu(msEdit);
// Undo
//
miEditUndo = new MenuItem(msEdit, SWT.CASCADE);
miEditUndo.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { undoAction(getActiveUndoInterface()); } });
// Redo
//
miEditRedo = new MenuItem(msEdit, SWT.CASCADE);
miEditRedo.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { redoAction(getActiveUndoInterface()); } });
setUndoMenu(getActiveTransformation());
new MenuItem(msEdit, SWT.SEPARATOR);
// Search
//
MenuItem miEditSearch = new MenuItem(msEdit, SWT.CASCADE);
miEditSearch.setText(Messages.getString("Spoon.Menu.Edit.Search")); //Search Metadata \tCTRL-F
miEditSearch.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { searchMetaData(); } });
// Set variables
//
MenuItem miEditVars = new MenuItem(msEdit, SWT.CASCADE);
miEditVars.setText(Messages.getString("Spoon.Menu.Edit.Variables")); //Set variables \tCTRL-ALT-J
miEditVars.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { getVariables(); } });
// Show variables
MenuItem miEditSVars = new MenuItem(msEdit, SWT.CASCADE);
miEditSVars.setText(Messages.getString("Spoon.Menu.Edit.ShowVariables")); //Show variables \tCTRL-L
miEditSVars.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { showVariables(); } });
new MenuItem(msEdit, SWT.SEPARATOR);
// Clear selection
//
miEditUnselectAll = new MenuItem(msEdit, SWT.CASCADE);
miEditUnselectAll.setText(Messages.getString("Spoon.Menu.Edit.ClearSelection")); //&Clear selection \tESC
miEditUnselectAll.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { editUnselectAll(getActiveTransformation()); } });
// Select all
//
miEditSelectAll = new MenuItem(msEdit, SWT.CASCADE);
miEditSelectAll.setText(Messages.getString("Spoon.Menu.Edit.SelectAllSteps")); //"&Select all steps \tCTRL-A"
miEditSelectAll.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { editSelectAll(getActiveTransformation()); } });
new MenuItem(msEdit, SWT.SEPARATOR);
// Copy to clipboard
//
miEditCopy = new MenuItem(msEdit, SWT.CASCADE);
miEditCopy.setText(Messages.getString("Spoon.Menu.Edit.CopyToClipboard")); //Copy selected steps to clipboard\tCTRL-C
miEditCopy.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e)
{
TransMeta transMeta = getActiveTransformation();
copySelected(transMeta, transMeta.getSelectedSteps(), transMeta.getSelectedNotes());
}});
// Paste from clipboard
//
miEditPaste = new MenuItem(msEdit, SWT.CASCADE);
miEditPaste.setText(Messages.getString("Spoon.Menu.Edit.PasteFromClipboard")); //Paste steps from clipboard\tCTRL-V
miEditPaste.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { pasteSteps(); } });
new MenuItem(msEdit, SWT.SEPARATOR);
// Refresh
//
MenuItem miEditRefresh = new MenuItem(msEdit, SWT.CASCADE);
miEditRefresh.setText(Messages.getString("Spoon.Menu.Edit.Refresh")); //&Refresh \tF5
new MenuItem(msEdit, SWT.SEPARATOR);
// Options
//
MenuItem miEditOptions = new MenuItem(msEdit, SWT.CASCADE);
miEditOptions.setText(Messages.getString("Spoon.Menu.Edit.Options")); //&Options...
miEditOptions.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { editOptions(); } });
////////////////////////////////////////////////////////////
// Repository
//
//
// main Repository menu...
MenuItem mRep = new MenuItem(mBar, SWT.CASCADE); mRep.setText(Messages.getString("Spoon.Menu.Repository")); //&Repository
Menu msRep = new Menu(shell, SWT.DROP_DOWN);
mRep.setMenu(msRep);
// Connect to repository
//
MenuItem miRepConnect = new MenuItem(msRep, SWT.CASCADE);
miRepConnect.setText(Messages.getString("Spoon.Menu.Repository.ConnectToRepository")); //&Connect to repository \tCTRL-R
miRepConnect.addListener (SWT.Selection, new Listener() { public void handleEvent(Event e) { openRepository(); } });
// Disconnect from repository
//
miRepDisconnect = new MenuItem(msRep, SWT.CASCADE);
miRepDisconnect.setText(Messages.getString("Spoon.Menu.Repository.DisconnectRepository")); //&Disconnect repository \tCTRL-D
miRepDisconnect.addListener (SWT.Selection, new Listener() { public void handleEvent(Event e) { closeRepository(); } });
// Explore the repository
//
miRepExplore = new MenuItem(msRep, SWT.CASCADE);
miRepExplore.setText(Messages.getString("Spoon.Menu.Repository.ExploreRepository")); //&Explore repository \tCTRL-E
miRepExplore.addListener (SWT.Selection, new Listener() { public void handleEvent(Event e) { exploreRepository(); } });
new MenuItem(msRep, SWT.SEPARATOR);
// Edit current user
//
miRepUser = new MenuItem(msRep, SWT.CASCADE);
miRepUser.setText(Messages.getString("Spoon.Menu.Repository.EditCurrentUser")); //&Edit current user\tCTRL-U
miRepUser.addListener (SWT.Selection, new Listener() { public void handleEvent(Event e) { editRepositoryUser();} });
////////////////////////////////////////////////////////////
// Transformation
//
//
// main Transformation menu...
MenuItem mTrans = new MenuItem(mBar, SWT.CASCADE); mTrans.setText(Messages.getString("Spoon.Menu.Transformation")); //&Transformation
Menu msTrans = new Menu(shell, SWT.DROP_DOWN );
mTrans.setMenu(msTrans);
// Run
//
miTransRun = new MenuItem(msTrans, SWT.CASCADE);
miTransRun.setText(Messages.getString("Spoon.Menu.Transformation.Run"));//&Run \tF9
miTransRun.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { executeTransformation(getActiveTransformation(), true, false, false, false, null); } });
// Preview
//
miTransPreview = new MenuItem(msTrans, SWT.CASCADE);
miTransPreview.setText(Messages.getString("Spoon.Menu.Transformation.Preview"));//&Preview \tF10
miTransPreview.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { executeTransformation(getActiveTransformation(), true, false, false, true, null); } });
// Check
//
miTransCheck = new MenuItem(msTrans, SWT.CASCADE);
miTransCheck.setText(Messages.getString("Spoon.Menu.Transformation.Verify"));//&Verify \tF11
miTransCheck.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { checkTrans(getActiveTransformation());} });
// Impact
//
miTransImpact = new MenuItem(msTrans, SWT.CASCADE);
miTransImpact.setText(Messages.getString("Spoon.Menu.Transformation.Impact"));//&Impact
miTransImpact.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { analyseImpact(getActiveTransformation()); } });
// SQL
//
miTransSQL = new MenuItem(msTrans, SWT.CASCADE);
miTransSQL.setText(Messages.getString("Spoon.Menu.Transformation.GetSQL"));//&Get SQL
miTransSQL.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { getSQL(); } });
new MenuItem(msTrans, SWT.SEPARATOR);
// Show last Impact results
//
miLastImpact = new MenuItem(msTrans, SWT.CASCADE);
miLastImpact.setText(Messages.getString("Spoon.Menu.Transformation.ShowLastImpactAnalyses"));//Show last impact analyses \tF6
miLastImpact.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { showLastImpactAnalyses(getActiveTransformation()); } });
// Show last verify results
//
miLastCheck = new MenuItem(msTrans, SWT.CASCADE);
miLastCheck.setText(Messages.getString("Spoon.Menu.Transformation.ShowLastVerifyResults"));//Show last verify results \tF7
miLastCheck.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { showLastTransCheck(); } });
// Show last preview results
//
miLastPreview = new MenuItem(msTrans, SWT.CASCADE);
miLastPreview.setText(Messages.getString("Spoon.Menu.Transformation.ShowLastPreviewResults"));//Show last preview results \tF8
miLastPreview.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { SpoonLog spoonLog = getActiveSpoonLog(); if (spoonLog!=null) spoonLog.showPreview(); } });
new MenuItem(msTrans, SWT.SEPARATOR);
// Copy transformation to clipboard
//
miTransCopy = new MenuItem(msTrans, SWT.CASCADE);
miTransCopy.setText(Messages.getString("Spoon.Menu.Transformation.CopyTransformationToClipboard"));//&Copy transformation to clipboard
miTransCopy.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { copyTransformation(getActiveTransformation()); } });
// Paste transformation to clipboard
//
miTransPaste = new MenuItem(msTrans, SWT.CASCADE);
miTransPaste.setText(Messages.getString("Spoon.Menu.Transformation.PasteTransformationFromClipboard"));//P&aste transformation from clipboard
miTransPaste.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { pasteTransformation(); } });
// Copy image of transformation to clipboard
//
miTransImage = new MenuItem(msTrans, SWT.CASCADE);
miTransImage.setText(Messages.getString("Spoon.Menu.Transformation.CopyTransformationImageClipboard"));//Copy the transformation image clipboard \tCTRL-ALT-I
miTransImage.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { copyTransformationImage(getActiveTransformation()); } });
new MenuItem(msTrans, SWT.SEPARATOR);
// Edit transformation setttings
//
miTransDetails = new MenuItem(msTrans, SWT.CASCADE);
miTransDetails.setText(Messages.getString("Spoon.Menu.Transformation.Settings"));//&Settings... \tCTRL-T
miTransDetails.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { editTransformationProperties(getActiveTransformation()); } });
////////////////////////////////////////////////////////////
// Job
//
//
// The main job menu
MenuItem mJob = new MenuItem(mBar, SWT.CASCADE);
mJob.setText(Messages.getString("Spoon.Menu.Job")); //$NON-NLS-1$
Menu msJob = new Menu(shell, SWT.DROP_DOWN);
mJob.setMenu(msJob);
// Run
//
miJobRun = new MenuItem(msJob, SWT.CASCADE);
miJobRun.setText(Messages.getString("Spoon.Menu.Job.Run")); //$NON-NLS-1$
new MenuItem(msJob, SWT.SEPARATOR);
miJobRun.addListener (SWT.Selection, new Listener() { public void handleEvent(Event e) { executeJob(getActiveJob(), true, false, false, false, null); } });
// Copy to clipboard
//
miJobCopy = new MenuItem(msJob, SWT.CASCADE);
miJobCopy.setText(Messages.getString("Spoon.Menu.Job.CopyToClipboard")); //$NON-NLS-1$
miJobCopy.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { copyJob(getActiveJob()); } });
// Paste job from the clipboard
//
miJobPaste = new MenuItem(msJob, SWT.CASCADE);
miJobPaste.setText(Messages.getString("Spoon.Menu.Job.PasteJobFromClipboard"));//P&aste job from clipboard
miJobPaste.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { pasteJob(); } });
new MenuItem(msJob, SWT.SEPARATOR);
// Edit job properties
//
miJobInfo = new MenuItem(msJob, SWT.CASCADE);
miJobInfo.setText(Messages.getString("Spoon.Menu.Job.Settings")); //$NON-NLS-1$
miJobInfo.addListener (SWT.Selection, new Listener() { public void handleEvent(Event e) { editJobProperties(getActiveJob()); } });
////////////////////////////////////////////////////////////
// Wizard
//
//
// Wizard menu
MenuItem mWizard = new MenuItem(mBar, SWT.CASCADE); mWizard.setText(Messages.getString("Spoon.Menu.Wizard")); //"&Wizard"
Menu msWizard = new Menu(shell, SWT.DROP_DOWN );
mWizard.setMenu(msWizard);
// New database connection wizard
//
miWizardNewConnection = new MenuItem(msWizard, SWT.CASCADE);
miWizardNewConnection.setText(Messages.getString("Spoon.Menu.Wizard.CreateDatabaseConnectionWizard"));//&Create database connection wizard...\tF3
miWizardNewConnection.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { createDatabaseWizard(getActiveTransformation()); }});
// Copy table wizard
//
miWizardCopyTable = new MenuItem(msWizard, SWT.CASCADE);
miWizardCopyTable.setText(Messages.getString("Spoon.Menu.Wizard.CopyTableWizard"));//&Copy table wizard...\tF4
miWizardCopyTable.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { copyTableWizard(); }});
miWizardRipDatabase = new MenuItem(msWizard, SWT.CASCADE);
miWizardRipDatabase.setText(Messages.getString("Spoon.Menu.Wizard.CopyTables")); //$NON-NLS-1$
Listener lsWizardRipDatabase= new Listener() { public void handleEvent(Event e) { ripDBWizard(); } };
miWizardRipDatabase.addListener(SWT.Selection, lsWizardRipDatabase);
////////////////////////////////////////////////////////////
// Help
//
//
// main Help menu...
MenuItem mHelp = new MenuItem(mBar, SWT.CASCADE); mHelp.setText(Messages.getString("Spoon.Menu.Help")); //"&Help"
Menu msHelp = new Menu(shell, SWT.DROP_DOWN );
mHelp.setMenu(msHelp);
// Credits
//
MenuItem miHelpCredit = new MenuItem(msHelp, SWT.CASCADE);
miHelpCredit.setText(Messages.getString("Spoon.Menu.Help.Credits"));//&Credits
miHelpCredit.addListener (SWT.Selection, new Listener() { public void handleEvent(Event e) { ShowCreditsDialog scd = new ShowCreditsDialog(shell, props, GUIResource.getInstance().getImageCredits()); scd.open(); } });
// Tip of the day
//
MenuItem miHelpTOTD = new MenuItem(msHelp, SWT.CASCADE);
miHelpTOTD.setText(Messages.getString("Spoon.Menu.Help.Tip"));//&Tip of the day
miHelpTOTD.addListener (SWT.Selection, new Listener() { public void handleEvent(Event e) { new TipsDialog(shell, props).open(); }});
// Welcome screen
//
MenuItem miHelpWelcome = new MenuItem(msHelp, SWT.CASCADE);
miHelpWelcome.setText(Messages.getString("Spoon.Menu.Help.Welcome")); //&Welcome screen
miHelpWelcome.addListener (SWT.Selection, new Listener() { public void handleEvent(Event e) { addSpoonBrowser(STRING_WELCOME_TAB_NAME, URL_WELCOME_PAGE); }});
new MenuItem(msHelp, SWT.SEPARATOR);
// About
//
MenuItem miHelpAbout = new MenuItem(msHelp, SWT.CASCADE);
miHelpAbout.setText(Messages.getString("Spoon.Menu.About"));//"&About"
miHelpAbout.addListener (SWT.Selection, new Listener() { public void handleEvent(Event e) { helpAbout(); } });
}
private void addMenuLast()
{
int idx = msFile.indexOf(miFileSep3);
int max = msFile.getItemCount();
// Remove everything until end...
for (int i=max-1;i>idx;i--)
{
MenuItem mi = msFile.getItem(i);
mi.dispose();
}
// Previously loaded files...
List lastUsedFiles = props.getLastUsedFiles();
for (int i = 0; i < lastUsedFiles.size(); i++)
{
final LastUsedFile lastUsedFile = (LastUsedFile) lastUsedFiles.get(i);
MenuItem miFileLast = new MenuItem(msFile, SWT.CASCADE);
if (lastUsedFile.isTransformation())
{
miFileLast.setImage(GUIResource.getInstance().getImageSpoonGraph());
}
else
if (lastUsedFile.isJob())
{
miFileLast.setImage(GUIResource.getInstance().getImageChefGraph());
}
char chr = (char) ('1' + i);
int accel = SWT.CTRL | chr;
if (i < 9)
{
miFileLast.setAccelerator(accel);
miFileLast.setText("&" + chr + " " + lastUsedFile + "\tCTRL-" + chr);
}
else
{
miFileLast.setText(" " + lastUsedFile);
}
Listener lsFileLast = new Listener()
{
public void handleEvent(Event e)
{
// If the file comes from a repository and it's not the same as
// the one we're connected to, ask for a username/password!
//
boolean cancelled = false;
if (lastUsedFile.isSourceRepository() && (rep == null || !rep.getRepositoryInfo().getName().equalsIgnoreCase(lastUsedFile.getRepositoryName())))
{
// Ask for a username password to get the required repository access
//
int perms[] = new int[] { PermissionMeta.TYPE_PERMISSION_TRANSFORMATION };
RepositoriesDialog rd = new RepositoriesDialog(disp, SWT.NONE, perms, Messages.getString("Spoon.Application.Name")); // RepositoriesDialog.ToolName="Spoon"
rd.setRepositoryName(lastUsedFile.getRepositoryName());
if (rd.open())
{
// Close the previous connection...
if (rep != null) rep.disconnect();
rep = new Repository(log, rd.getRepository(), rd.getUser());
try
{
rep.connect(APP_NAME);
}
catch (KettleException ke)
{
rep = null;
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.UnableConnectRepository.Title"), Messages.getString("Spoon.Dialog.UnableConnectRepository.Message"), ke); //$NON-NLS-1$ //$NON-NLS-2$
}
}
else
{
cancelled = true;
}
}
if (!cancelled)
{
try
{
RepositoryMeta meta = (rep == null ? null : rep.getRepositoryInfo());
loadLastUsedFile(lastUsedFile, meta);
addMenuLast();
refreshHistory();
}
catch(KettleException ke)
{
// "Error loading transformation", "I was unable to load this transformation from the
// XML file because of an error"
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.LoadTransformationError.Title"), Messages.getString("Spoon.Dialog.LoadTransformationError.Message"), ke);
}
}
}
};
miFileLast.addListener(SWT.Selection, lsFileLast);
}
}
private void addBar()
{
tBar = new ToolBar(shell, SWT.HORIZONTAL | SWT.FLAT );
// props.setLook(tBar);
final ToolItem tiFileNew = new ToolItem(tBar, SWT.PUSH);
final Image imFileNew = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"new.png"));
tiFileNew.setImage(imFileNew);
tiFileNew.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { newFile(); }});
tiFileNew.setToolTipText(Messages.getString("Spoon.Tooltip.NewTranformation"));//New transformation, clear all settings
final ToolItem tiFileOpen = new ToolItem(tBar, SWT.PUSH);
final Image imFileOpen = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"open.png"));
tiFileOpen.setImage(imFileOpen);
tiFileOpen.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { openFile(false); }});
tiFileOpen.setToolTipText(Messages.getString("Spoon.Tooltip.OpenTranformation"));//Open tranformation
tiFileSave = new ToolItem(tBar, SWT.PUSH);
final Image imFileSave = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"save.png"));
tiFileSave.setImage(imFileSave);
tiFileSave.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { saveFile(); }});
tiFileSave.setToolTipText(Messages.getString("Spoon.Tooltip.SaveCurrentTranformation"));//Save current transformation
tiFileSaveAs = new ToolItem(tBar, SWT.PUSH);
final Image imFileSaveAs = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"saveas.png"));
tiFileSaveAs.setImage(imFileSaveAs);
tiFileSaveAs.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { saveFileAs(); }});
tiFileSaveAs.setToolTipText(Messages.getString("Spoon.Tooltip.SaveDifferentNameTranformation"));//Save transformation with different name
new ToolItem(tBar, SWT.SEPARATOR);
tiFilePrint = new ToolItem(tBar, SWT.PUSH);
final Image imFilePrint = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"print.png"));
tiFilePrint.setImage(imFilePrint);
tiFilePrint.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { printFile(); }});
tiFilePrint.setToolTipText(Messages.getString("Spoon.Tooltip.Print"));//Print
new ToolItem(tBar, SWT.SEPARATOR);
tiFileRun = new ToolItem(tBar, SWT.PUSH);
final Image imFileRun = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"run.png"));
tiFileRun.setImage(imFileRun);
tiFileRun.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { executeFile(true, false, false, false, null); }});
tiFileRun.setToolTipText(Messages.getString("Spoon.Tooltip.RunTranformation"));//Run this transformation
tiFilePreview = new ToolItem(tBar, SWT.PUSH);
final Image imFilePreview = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"preview.png"));
tiFilePreview.setImage(imFilePreview);
tiFilePreview.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { executeFile(true, false, false, true, null); }});
tiFilePreview.setToolTipText(Messages.getString("Spoon.Tooltip.PreviewTranformation"));//Preview this transformation
tiFileReplay = new ToolItem(tBar, SWT.PUSH);
final Image imFileReplay = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"replay.png"));
tiFileReplay.setImage(imFileReplay);
tiFileReplay.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { executeFile(true, false, false, true, null); }});
tiFileReplay.setToolTipText("Replay this transformation");
new ToolItem(tBar, SWT.SEPARATOR);
tiFileCheck = new ToolItem(tBar, SWT.PUSH);
final Image imFileCheck = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"check.png"));
tiFileCheck.setImage(imFileCheck);
tiFileCheck.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { checkTrans(getActiveTransformation()); }});
tiFileCheck.setToolTipText(Messages.getString("Spoon.Tooltip.VerifyTranformation"));//Verify this transformation
new ToolItem(tBar, SWT.SEPARATOR);
tiImpact = new ToolItem(tBar, SWT.PUSH);
final Image imImpact = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"impact.png"));
// Can't seem to get the transparency correct for this image!
ImageData idImpact = imImpact.getImageData();
int impactPixel = idImpact.palette.getPixel(new RGB(255, 255, 255));
idImpact.transparentPixel = impactPixel;
Image imImpact2 = new Image(disp, idImpact);
tiImpact.setImage(imImpact2);
tiImpact.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { analyseImpact(getActiveTransformation()); }});
tiImpact.setToolTipText(Messages.getString("Spoon.Tooltip.AnalyzeTranformation"));//Analyze the impact of this transformation on the database(s)
new ToolItem(tBar, SWT.SEPARATOR);
tiSQL = new ToolItem(tBar, SWT.PUSH);
final Image imSQL = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"SQLbutton.png"));
// Can't seem to get the transparency correct for this image!
ImageData idSQL = imSQL.getImageData();
int sqlPixel= idSQL.palette.getPixel(new RGB(255, 255, 255));
idSQL.transparentPixel = sqlPixel;
Image imSQL2= new Image(disp, idSQL);
tiSQL.setImage(imSQL2);
tiSQL.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { getSQL(); }});
tiSQL.setToolTipText(Messages.getString("Spoon.Tooltip.GenerateSQLForTranformation"));//Generate the SQL needed to run this transformation
tBar.addDisposeListener(new DisposeListener()
{
public void widgetDisposed(DisposeEvent e)
{
imFileNew.dispose();
imFileOpen.dispose();
imFileSave.dispose();
imFileSaveAs.dispose();
}
}
);
tBar.addKeyListener(defKeys);
tBar.addKeyListener(modKeys);
tBar.pack();
}
private static final String STRING_SPOON_MAIN_TREE = "Spoon Main Tree";
private static final String STRING_SPOON_CORE_OBJECTS_TREE= "Spoon Core Objects Tree";
private void addTree()
{
if (leftSash!=null)
{
leftSash.dispose();
}
// Split the left side of the screen in half
leftSash = new SashForm(sashform, SWT.VERTICAL);
// Now set up the main CSH tree
selectionTree = new Tree(leftSash, SWT.SINGLE | SWT.BORDER);
props.setLook(selectionTree);
selectionTree.setLayout(new FillLayout());
// Add a tree memory as well...
TreeMemory.addTreeListener(selectionTree, STRING_SPOON_MAIN_TREE);
tiTrans = new TreeItem(selectionTree, SWT.NONE); tiTrans.setText(STRING_TRANSFORMATIONS);
tiJobs = new TreeItem(selectionTree, SWT.NONE); tiJobs.setText(STRING_JOBS);
// Default selection (double-click, enter)
// lsNewDef = new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e){ newSelected(); } };
// Add all the listeners...
// selectionTree.addSelectionListener(lsEditDef); // double click somewhere in the tree...
// tCSH.addSelectionListener(lsNewDef); // double click somewhere in the tree...
selectionTree.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { setMenu(); } });
selectionTree.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { showSelection(); } });
selectionTree.addSelectionListener(new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e){ doubleClickedInTree(); } });
// Keyboard shortcuts!
selectionTree.addKeyListener(defKeys);
selectionTree.addKeyListener(modKeys);
// Set a listener on the tree
addDragSourceToTree(selectionTree);
// OK, now add a list of often-used icons to the bottom of the tree...
coreObjectsTree = new Tree(leftSash, SWT.SINGLE );
// Add a tree memory as well...
TreeMemory.addTreeListener(coreObjectsTree, STRING_SPOON_CORE_OBJECTS_TREE);
refreshCoreObjectsTree();
tiJobBase.setExpanded(true);
// Scroll to the top
coreObjectsTree.setSelection(tiTransBase);
coreObjectsTree.showSelection();
// Add tooltips for history tree too
addToolTipsToTree(coreObjectsTree);
// Set the same listener on this tree
addDragSourceToTree(coreObjectsTree);
leftSash.setWeights(new int[] { 50, 50 } );
setTreeImages();
}
private void refreshCoreObjectsTree()
{
clearCoreObjectsTree();
addCoreObjectsToTree();
}
private void clearCoreObjectsTree()
{
setCoreObjectsState(STATE_CORE_OBJECTS_NONE);
TreeItem[] items = coreObjectsTree.getItems();
for (int i=0;i<items.length;i++) items[i].dispose();
}
private void addCoreObjectsToTree()
{
boolean showTrans = getActiveTransformation()!=null;
boolean showJob = getActiveJob()!=null;
int nrTabs = tabMap.size();
if (showTrans || nrTabs==0)
{
tiTransBase = new TreeItem(coreObjectsTree, SWT.NONE);
tiTransBase.setText(STRING_TRANS_BASE);
tiTransBase.setImage(GUIResource.getInstance().getImageBol());
// Fill the base components...
//////////////////////////////////////////////////////////////////////////////////////////////////
// TRANSFORMATIONS
//////////////////////////////////////////////////////////////////////////////////////////////////
StepLoader steploader = StepLoader.getInstance();
StepPlugin basesteps[] = steploader.getStepsWithType(StepPlugin.TYPE_ALL);
String basecat[] = steploader.getCategories(StepPlugin.TYPE_ALL);
for (int i=0;i<basecat.length;i++)
{
TreeItem tiBaseCat = new TreeItem(tiTransBase, SWT.NONE);
tiBaseCat.setText(basecat[i]);
tiBaseCat.setImage(GUIResource.getInstance().getImageBol());
for (int j=0;j<basesteps.length;j++)
{
if (basesteps[j].getCategory().equalsIgnoreCase(basecat[i]))
{
TreeItem treeItem = new TreeItem(tiBaseCat, 0);
treeItem.setText(basesteps[j].getDescription());
if (basesteps[j].isPlugin()) treeItem.setFont(GUIResource.getInstance().getFontBold());
Image stepimg = (Image)GUIResource.getInstance().getImagesStepsSmall().get(basesteps[j].getID()[0]);
if (stepimg!=null)
{
treeItem.setImage(stepimg);
}
}
}
}
setCoreObjectsState(STATE_CORE_OBJECTS_SPOON);
}
if (showJob || nrTabs==0)
{
tiJobBase = new TreeItem(coreObjectsTree, SWT.NONE);
tiJobBase.setText(STRING_JOB_BASE);
tiJobBase.setImage(GUIResource.getInstance().getImageBol());
//////////////////////////////////////////////////////////////////////////////////////////////////
// JOBS
//////////////////////////////////////////////////////////////////////////////////////////////////
// First add a few "Special entries: Start, Dummy, OK, ERROR
//
String specialText[] = new String[] { JobMeta.STRING_SPECIAL_START, JobMeta.STRING_SPECIAL_DUMMY };
Image specialImage[]= new Image[] { GUIResource.getInstance().getImageStart(), GUIResource.getInstance().getImageDummy() };
for (int i=0;i<specialText.length;i++)
{
TreeItem treeItem = new TreeItem(tiJobBase, SWT.NONE);
treeItem.setText(specialText[i]);
treeItem.setImage(specialImage[i]);
}
JobEntryLoader jobEntryLoader = JobEntryLoader.getInstance();
JobPlugin baseEntries[] = jobEntryLoader.getJobEntriesWithType(JobPlugin.TYPE_NATIVE);
for (int i=0;i<baseEntries.length;i++)
{
if (!baseEntries[i].getID().equals("SPECIAL"))
{
TreeItem tiBaseItem = new TreeItem(tiJobBase, SWT.NONE);
tiBaseItem.setText(baseEntries[i].getDescription());
if (baseEntries[i].isPlugin()) tiBaseItem.setFont(GUIResource.getInstance().getFontBold());
Image image = (Image)GUIResource.getInstance().getImagesJobentriesSmall().get(baseEntries[i].getID());
tiBaseItem.setImage(image);
Image jobEntryImg = (Image)GUIResource.getInstance().getImagesJobentriesSmall().get(baseEntries[i].getID());
if (jobEntryImg!=null)
{
tiBaseItem.setImage(jobEntryImg);
}
}
}
setCoreObjectsState(STATE_CORE_OBJECTS_CHEF);
}
TreeMemory.setExpandedFromMemory(coreObjectsTree, STRING_SPOON_CORE_OBJECTS_TREE);
}
protected void shareObject(SharedObjectInterface sharedObjectInterface)
{
sharedObjectInterface.setShared(true);
refreshTree();
}
/**
* @return The object that is selected in the tree or null if we couldn't figure it out. (titles etc. == null)
*/
public TreeSelection[] getTreeObjects(final Tree tree)
{
List objects = new ArrayList();
if (tree.equals(selectionTree))
{
TreeItem[] selection = selectionTree.getSelection();
for (int s=0;s<selection.length;s++)
{
TreeItem treeItem = selection[s];
String[] path = Const.getTreeStrings(treeItem);
TreeSelection object = null;
switch(path.length)
{
case 0: break;
case 1: // ------complete-----
if (path[0].equals(STRING_TRANSFORMATIONS)) // the top level Transformations entry
{
object = new TreeSelection(path[0], TransMeta.class);
}
if (path[0].equals(STRING_JOBS)) // the top level Jobs entry
{
object = new TreeSelection(path[0], JobMeta.class);
}
break;
case 2: // ------complete-----
if (path[0].equals(STRING_BUILDING_BLOCKS)) // the top level Transformations entry
{
if (path[1].equals(STRING_TRANS_BASE))
{
object = new TreeSelection(path[1], StepPlugin.class);
}
}
if (path[0].equals(STRING_TRANSFORMATIONS)) // Transformations title
{
object = new TreeSelection(path[1], findTransformation(path[1]));
}
if (path[0].equals(STRING_JOBS)) // Jobs title
{
object = new TreeSelection(path[1], findJob(path[1]));
}
break;
case 3: // ------complete-----
if (path[0].equals(STRING_TRANSFORMATIONS)) // Transformations title
{
TransMeta transMeta = findTransformation(path[1]);
if (path[2].equals(STRING_CONNECTIONS)) object = new TreeSelection(path[2], DatabaseMeta.class, transMeta);
if (path[2].equals(STRING_STEPS)) object = new TreeSelection(path[2], StepMeta.class, transMeta);
if (path[2].equals(STRING_HOPS)) object = new TreeSelection(path[2], TransHopMeta.class, transMeta);
if (path[2].equals(STRING_PARTITIONS)) object = new TreeSelection(path[2], PartitionSchema.class, transMeta);
if (path[2].equals(STRING_SLAVES)) object = new TreeSelection(path[2], SlaveServer.class, transMeta);
if (path[2].equals(STRING_CLUSTERS)) object = new TreeSelection(path[2], ClusterSchema.class, transMeta);
}
if (path[0].equals(STRING_JOBS)) // Jobs title
{
JobMeta jobMeta = findJob(path[1]);
if (path[2].equals(STRING_CONNECTIONS)) object = new TreeSelection(path[2], DatabaseMeta.class, jobMeta);
if (path[2].equals(STRING_JOB_ENTRIES)) object = new TreeSelection(path[2], JobEntryCopy.class, jobMeta);
}
break;
case 4: // ------complete-----
if (path[0].equals(STRING_TRANSFORMATIONS)) // The name of a transformation
{
TransMeta transMeta = findTransformation(path[1]);
if (path[2].equals(STRING_CONNECTIONS)) object = new TreeSelection(path[3], transMeta.findDatabase(path[3]), transMeta);
if (path[2].equals(STRING_STEPS)) object = new TreeSelection(path[3], transMeta.findStep(path[3]), transMeta);
if (path[2].equals(STRING_HOPS)) object = new TreeSelection(path[3], transMeta.findTransHop(path[3]), transMeta);
if (path[2].equals(STRING_PARTITIONS)) object = new TreeSelection(path[3], transMeta.findPartitionSchema(path[3]), transMeta);
if (path[2].equals(STRING_SLAVES)) object = new TreeSelection(path[3], transMeta.findSlaveServer(path[3]), transMeta);
if (path[2].equals(STRING_CLUSTERS)) object = new TreeSelection(path[3], transMeta.findClusterSchema(path[3]), transMeta);
}
if (path[0].equals(STRING_JOBS)) // The name of a job
{
JobMeta jobMeta = findJob(path[1]);
if (jobMeta!=null && path[2].equals(STRING_CONNECTIONS)) object = new TreeSelection(path[3], jobMeta.findDatabase(path[3]), jobMeta);
if (jobMeta!=null && path[2].equals(STRING_JOB_ENTRIES)) object = new TreeSelection(path[3], jobMeta.findJobEntry(path[3]), jobMeta);
}
break;
case 5:
if (path[0].equals(STRING_TRANSFORMATIONS)) // The name of a transformation
{
TransMeta transMeta = findTransformation(path[1]);
if (transMeta!=null && path[2].equals(STRING_CLUSTERS))
{
ClusterSchema clusterSchema = transMeta.findClusterSchema(path[3]);
object = new TreeSelection(path[4], clusterSchema.findSlaveServer(path[4]), clusterSchema, transMeta);
}
}
break;
default: break;
}
if (object!=null)
{
objects.add(object);
}
}
}
if (tree.equals(coreObjectsTree))
{
TreeItem[] selection = coreObjectsTree.getSelection();
for (int s=0;s<selection.length;s++)
{
TreeItem treeItem = selection[s];
String[] path = Const.getTreeStrings(treeItem);
TreeSelection object = null;
switch(path.length)
{
case 0: break;
case 1: break; // nothing
case 2: // Job entries
if (path[0].equals(STRING_JOB_BASE))
{
JobPlugin jobPlugin = JobEntryLoader.getInstance().findJobEntriesWithDescription(path[1]);
if (jobPlugin!=null)
{
object = new TreeSelection(path[1], jobPlugin);
}
else
{
object = new TreeSelection(path[1], JobPlugin.class); // Special entries Start, Dummy, ...
}
}
break;
case 3: // Steps
if (path[0].equals(STRING_TRANS_BASE))
{
object = new TreeSelection(path[2], StepLoader.getInstance().findStepPluginWithDescription(path[2]));
}
break;
default: break;
}
if (object!=null)
{
objects.add(object);
}
}
}
return (TreeSelection[]) objects.toArray(new TreeSelection[objects.size()]);
}
private void addToolTipsToTree(Tree tree)
{
tree.addListener(SWT.MouseHover, new Listener()
{
public void handleEvent(Event e)
{
String tooltip=null;
Tree tree = (Tree)e.widget;
TreeItem item = tree.getItem(new org.eclipse.swt.graphics.Point(e.x, e.y));
if (item!=null)
{
StepLoader steploader = StepLoader.getInstance();
StepPlugin sp = steploader.findStepPluginWithDescription(item.getText());
if (sp!=null)
{
tooltip = sp.getTooltip();
}
else
{
JobEntryLoader jobEntryLoader = JobEntryLoader.getInstance();
JobPlugin jobPlugin = jobEntryLoader.findJobEntriesWithDescription(item.getText());
if (jobPlugin!=null)
{
tooltip = jobPlugin.getTooltip();
}
else
{
if (item.getText().equalsIgnoreCase(STRING_TRANS_BASE))
{
tooltip=Messages.getString("Spoon.Tooltip.SelectStepType",Const.CR); //"Select one of the step types listed below and"+Const.CR+"drag it onto the graphical view tab to the right.";
}
}
}
}
tree.setToolTipText(tooltip);
}
}
);
}
private void addDragSourceToTree(final Tree tree)
{
// Drag & Drop for steps
Transfer[] ttypes = new Transfer[] { XMLTransfer.getInstance() };
DragSource ddSource = new DragSource(tree, DND.DROP_MOVE);
ddSource.setTransfer(ttypes);
ddSource.addDragListener(new DragSourceListener()
{
public void dragStart(DragSourceEvent event){ }
public void dragSetData(DragSourceEvent event)
{
TreeSelection[] treeObjects = getTreeObjects(tree);
if (treeObjects.length==0)
{
event.doit=false;
return;
}
int type=0;
String data = null;
TreeSelection treeObject = treeObjects[0];
Object object = treeObject.getSelection();
JobMeta jobMeta = getActiveJob();
if (object instanceof StepMeta)
{
StepMeta stepMeta = (StepMeta)object;
type = DragAndDropContainer.TYPE_STEP;
data=stepMeta.getName(); // name of the step.
}
else
if (object instanceof StepPlugin)
{
StepPlugin stepPlugin = (StepPlugin)object;
type = DragAndDropContainer.TYPE_BASE_STEP_TYPE;
data=stepPlugin.getDescription(); // Step type
}
else
if (object instanceof DatabaseMeta)
{
DatabaseMeta databaseMeta = (DatabaseMeta) object;
type = DragAndDropContainer.TYPE_DATABASE_CONNECTION;
data=databaseMeta.getName();
}
else
if (object instanceof TransHopMeta)
{
TransHopMeta hop = (TransHopMeta) object;
type = DragAndDropContainer.TYPE_TRANS_HOP;
data=hop.toString(); // nothing for really ;-)
}
else
if (object instanceof JobEntryCopy)
{
JobEntryCopy jobEntryCopy = (JobEntryCopy)object;
type = DragAndDropContainer.TYPE_JOB_ENTRY;
data=jobEntryCopy.getName(); // name of the job entry.
}
else
if (object instanceof JobPlugin)
{
JobPlugin jobPlugin = (JobPlugin)object;
type = DragAndDropContainer.TYPE_BASE_JOB_ENTRY;
data=jobPlugin.getDescription(); // Step type
}
else
if (object instanceof Class && object.equals(JobPlugin.class))
{
JobEntryCopy dummy = null;
if (jobMeta!=null) dummy = jobMeta.findJobEntry("Dummy", 0, true);
if (JobMeta.STRING_SPECIAL_DUMMY.equalsIgnoreCase(treeObject.getItemText()) && dummy!=null)
{
// if dummy already exists, add a copy
type = DragAndDropContainer.TYPE_JOB_ENTRY;
data=dummy.getName();
}
else
{
type = DragAndDropContainer.TYPE_BASE_JOB_ENTRY;
data = treeObject.getItemText();
}
}
else
{
event.doit=false;
return; // ignore anything else you drag.
}
event.data = new DragAndDropContainer(type, data);
}
public void dragFinished(DragSourceEvent event) {}
}
);
}
/**
* If you click in the tree, you might want to show the corresponding window.
*/
public void showSelection()
{
TreeSelection[] objects = getTreeObjects(selectionTree);
if (objects.length!=1) return; // not yet supported, we can do this later when the OSX bug goes away
TreeSelection object = objects[0];
final Object selection = object.getSelection();
final Object parent = object.getParent();
TransMeta transMeta = null;
if (selection instanceof TransMeta) transMeta = (TransMeta) selection;
if (parent instanceof TransMeta) transMeta = (TransMeta) parent;
if (transMeta!=null)
{
// Search the corresponding SpoonGraph tab
CTabItem tabItem = findCTabItem(makeGraphTabName(transMeta));
if (tabItem!=null)
{
int current = tabfolder.getSelectionIndex();
int desired = tabfolder.indexOf(tabItem);
if (current!=desired) tabfolder.setSelection(desired);
if ( getCoreObjectsState() != STATE_CORE_OBJECTS_SPOON )
{
// Switch the core objects in the lower left corner to the spoon trans types
refreshCoreObjectsTree();
}
}
}
JobMeta jobMeta = null;
if (selection instanceof JobMeta) jobMeta = (JobMeta) selection;
if (parent instanceof JobMeta) jobMeta = (JobMeta) parent;
if (jobMeta!=null)
{
// Search the corresponding SpoonGraph tab
CTabItem tabItem = findCTabItem(makeJobGraphTabName(jobMeta));
if (tabItem!=null)
{
int current = tabfolder.getSelectionIndex();
int desired = tabfolder.indexOf(tabItem);
if (current!=desired) tabfolder.setSelection(desired);
if ( getCoreObjectsState() != STATE_CORE_OBJECTS_CHEF )
{
// Switch the core objects in the lower left corner to the spoon job types
refreshCoreObjectsTree();
}
}
}
}
private void setMenu()
{
if (spoonMenu==null)
{
spoonMenu = new Menu(shell, SWT.POP_UP);
}
else
{
MenuItem[] items = spoonMenu.getItems();
for (int i=0;i<items.length;i++) items[i].dispose();
}
TreeSelection[] objects = getTreeObjects(selectionTree);
if (objects.length!=1) return; // not yet supported, we can do this later when the OSX bug goes away
TreeSelection object = objects[0];
final Object selection = object.getSelection();
final Object parent = object.getParent();
// final Object grandParent = object.getGrandParent();
// No clicked on a real object: returns a class
if (selection instanceof Class)
{
if (selection.equals(TransMeta.class))
{
// New
MenuItem miNew = new MenuItem(spoonMenu, SWT.PUSH); miNew.setText(Messages.getString("Spoon.Menu.Popup.BASE.New"));
miNew.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { newTransFile(); }} );
}
if (selection.equals(JobMeta.class))
{
// New
MenuItem miNew = new MenuItem(spoonMenu, SWT.PUSH); miNew.setText(Messages.getString("Spoon.Menu.Popup.BASE.New"));
miNew.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { newJobFile(); }} );
}
if (selection.equals(TransHopMeta.class))
{
// New
MenuItem miNew = new MenuItem(spoonMenu, SWT.PUSH); miNew.setText(Messages.getString("Spoon.Menu.Popup.BASE.New"));
miNew.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { newHop((TransMeta)parent); }} );
// Sort hops
MenuItem miSort = new MenuItem(spoonMenu, SWT.PUSH); miSort.setText(Messages.getString("Spoon.Menu.Popup.HOPS.SortHops"));
miSort.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { ((TransMeta)parent).sortHops(); refreshTree(); } });
}
if (selection.equals(DatabaseMeta.class))
{
// New
MenuItem miNew = new MenuItem(spoonMenu, SWT.PUSH); miNew.setText(Messages.getString("Spoon.Menu.Popup.BASE.New"));
miNew.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { newConnection((HasDatabasesInterface)parent); }} );
// New Connection Wizard
MenuItem miWizard = new MenuItem(spoonMenu, SWT.PUSH); miWizard.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.NewConnectionWizard"));
miWizard.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { createDatabaseWizard((HasDatabasesInterface)parent); } } );
// Clear complete DB Cache
MenuItem miCache = new MenuItem(spoonMenu, SWT.PUSH); miCache.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.ClearDBCacheComplete"));
miCache.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { clearDBCache(); } } );
}
if (selection.equals(PartitionSchema.class))
{
// New
MenuItem miNew = new MenuItem(spoonMenu, SWT.PUSH); miNew.setText(Messages.getString("Spoon.Menu.Popup.BASE.New"));
miNew.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { newDatabasePartitioningSchema((TransMeta)parent); }} );
}
if (selection.equals(ClusterSchema.class))
{
MenuItem miNew = new MenuItem(spoonMenu, SWT.PUSH);
miNew.setText(Messages.getString("Spoon.Menu.Popup.CLUSTERS.New"));//New clustering schema
miNew.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { newClusteringSchema((TransMeta)parent); } } );
}
if (selection.equals(SlaveServer.class))
{
MenuItem miNew = new MenuItem(spoonMenu, SWT.PUSH);
miNew.setText(Messages.getString("Spoon.Menu.Popup.SLAVE_SERVER.New"));// New slave server
miNew.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { newSlaveServer((TransMeta)parent); } } );
}
}
else
{
if (selection instanceof TransMeta)
{
// Open log window
MenuItem miLog = new MenuItem(spoonMenu, SWT.PUSH); miLog.setText(Messages.getString("Spoon.Menu.Popup.BASE.LogWindow"));
miLog.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addSpoonLog((TransMeta)selection); }} );
MenuItem miHistory = new MenuItem(spoonMenu, SWT.PUSH); miHistory.setText(Messages.getString("Spoon.Menu.Popup.BASE.HistoryWindow"));
miHistory.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addSpoonHistory((TransMeta)selection, true); }} );
}
if (selection instanceof JobMeta)
{
// Open log window
MenuItem miLog = new MenuItem(spoonMenu, SWT.PUSH); miLog.setText(Messages.getString("Spoon.Menu.Popup.BASE.LogWindow"));
miLog.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addChefLog((JobMeta)selection); }} );
MenuItem miHistory = new MenuItem(spoonMenu, SWT.PUSH); miHistory.setText(Messages.getString("Spoon.Menu.Popup.BASE.HistoryWindow"));
miHistory.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addChefHistory((JobMeta)selection, true); }} );
}
if (selection instanceof StepPlugin)
{
// New
MenuItem miNew = new MenuItem(spoonMenu, SWT.PUSH); miNew.setText(Messages.getString("Spoon.Menu.Popup.BASE.New"));
miNew.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { newStep(getActiveTransformation()); }} );
}
if (selection instanceof DatabaseMeta)
{
final DatabaseMeta databaseMeta = (DatabaseMeta) selection;
final HasDatabasesInterface transMeta = (HasDatabasesInterface) parent;
MenuItem miNew = new MenuItem(spoonMenu, SWT.PUSH); miNew.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.New"));//New
miNew.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { newConnection(transMeta); } } );
MenuItem miEdit = new MenuItem(spoonMenu, SWT.PUSH); miEdit.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.Edit"));//Edit
miEdit.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { editConnection(transMeta, databaseMeta); } } );
MenuItem miDupe = new MenuItem(spoonMenu, SWT.PUSH); miDupe.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.Duplicate"));//Duplicate
miDupe.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { dupeConnection(transMeta, databaseMeta); } } );
MenuItem miCopy = new MenuItem(spoonMenu, SWT.PUSH); miCopy.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.CopyToClipboard"));//Copy to clipboard
miCopy.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { clipConnection(databaseMeta); } } );
MenuItem miDel = new MenuItem(spoonMenu, SWT.PUSH); miDel.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.Delete"));//Delete
miDel.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { delConnection(transMeta, databaseMeta); } } );
new MenuItem(spoonMenu, SWT.SEPARATOR);
MenuItem miSQL = new MenuItem(spoonMenu, SWT.PUSH); miSQL.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.SQLEditor"));//SQL Editor
miSQL.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { sqlConnection(databaseMeta); } } );
MenuItem miCache= new MenuItem(spoonMenu, SWT.PUSH); miCache.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.ClearDBCache")+databaseMeta.getName());//Clear DB Cache of
miCache.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { clearDBCache(databaseMeta); } } );
new MenuItem(spoonMenu, SWT.SEPARATOR);
MenuItem miShare = new MenuItem(spoonMenu, SWT.PUSH); miShare.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.Share"));
miShare.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { shareObject(databaseMeta); } } );
new MenuItem(spoonMenu, SWT.SEPARATOR);
MenuItem miExpl = new MenuItem(spoonMenu, SWT.PUSH); miExpl.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.Explore"));//Explore
miExpl.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { exploreDB(transMeta, databaseMeta); } } );
// disable for now if the connection is an SAP R/3 type of database...
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_SAPR3) miExpl.setEnabled(false);
}
if (selection instanceof StepMeta)
{
final TransMeta transMeta = (TransMeta)parent;
final StepMeta stepMeta = (StepMeta)selection;
// Edit
MenuItem miEdit = new MenuItem(spoonMenu, SWT.PUSH); miEdit.setText(Messages.getString("Spoon.Menu.Popup.STEPS.Edit"));
miEdit.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { editStep(transMeta, stepMeta); } } );
// Duplicate
MenuItem miDupe = new MenuItem(spoonMenu, SWT.PUSH); miDupe.setText(Messages.getString("Spoon.Menu.Popup.STEPS.Duplicate"));
miDupe.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { dupeStep(transMeta, stepMeta); } } );
// Delete
MenuItem miDel = new MenuItem(spoonMenu, SWT.PUSH); miDel.setText(Messages.getString("Spoon.Menu.Popup.STEPS.Delete"));
miDel.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { delStep(transMeta, stepMeta); } } );
MenuItem miShare = new MenuItem(spoonMenu, SWT.PUSH); miShare.setText(Messages.getString("Spoon.Menu.Popup.STEPS.Share"));
miShare.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { shareObject(stepMeta); } } );
}
if (selection instanceof JobEntryCopy)
{
final JobMeta jobMeta = (JobMeta)parent;
final JobEntryCopy jobEntry = (JobEntryCopy)selection;
// Edit
MenuItem miEdit = new MenuItem(spoonMenu, SWT.PUSH); miEdit.setText(Messages.getString("Spoon.Menu.Popup.JOBENTRIES.Edit"));
miEdit.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { editJobEntry(jobMeta, jobEntry); } } );
// Duplicate
MenuItem miDupe = new MenuItem(spoonMenu, SWT.PUSH); miDupe.setText(Messages.getString("Spoon.Menu.Popup.JOBENTRIES.Duplicate"));
miDupe.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { dupeJobEntry(jobMeta, jobEntry); } } );
// Delete
MenuItem miDel = new MenuItem(spoonMenu, SWT.PUSH); miDel.setText(Messages.getString("Spoon.Menu.Popup.JOBENTRIES.Delete"));
miDel.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { deleteJobEntryCopies(jobMeta, jobEntry); } } );
}
if (selection instanceof TransHopMeta)
{
final TransMeta transMeta = (TransMeta)parent;
final TransHopMeta transHopMeta = (TransHopMeta)selection;
MenuItem miEdit = new MenuItem(spoonMenu, SWT.PUSH); miEdit.setText(Messages.getString("Spoon.Menu.Popup.HOPS.Edit"));//Edit
miEdit.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { editHop(transMeta, transHopMeta); } } );
MenuItem miDel = new MenuItem(spoonMenu, SWT.PUSH); miDel.setText(Messages.getString("Spoon.Menu.Popup.HOPS.Delete"));//Delete
miDel.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { delHop(transMeta, transHopMeta); } } );
}
if (selection instanceof PartitionSchema)
{
final TransMeta transMeta = (TransMeta)parent;
final PartitionSchema partitionSchema = (PartitionSchema)selection;
MenuItem miEdit = new MenuItem(spoonMenu, SWT.PUSH); miEdit.setText(Messages.getString("Spoon.Menu.Popup.PARTITIONS.Edit"));//Edit
miEdit.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { editPartitionSchema(transMeta, partitionSchema); } } );
MenuItem miDel = new MenuItem(spoonMenu, SWT.PUSH); miDel.setText(Messages.getString("Spoon.Menu.Popup.PARTITIONS.Delete"));//Delete
miDel.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { delPartitionSchema(transMeta, partitionSchema); } } );
MenuItem miShare = new MenuItem(spoonMenu, SWT.PUSH); miShare.setText(Messages.getString("Spoon.Menu.Popup.PARTITIONS.Share"));
miShare.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { shareObject(partitionSchema); } } );
}
if (selection instanceof ClusterSchema)
{
final TransMeta transMeta = (TransMeta)parent;
final ClusterSchema clusterSchema = (ClusterSchema)selection;
MenuItem miEdit = new MenuItem(spoonMenu, SWT.PUSH);
miEdit.setText(Messages.getString("Spoon.Menu.Popup.CLUSTERS.Edit"));//Edit
miEdit.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { editClusterSchema(transMeta, clusterSchema); } } );
MenuItem miDel = new MenuItem(spoonMenu, SWT.PUSH);
miDel.setText(Messages.getString("Spoon.Menu.Popup.CLUSTERS.Delete"));//Delete
miDel.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { delClusterSchema(transMeta, clusterSchema); } } );
MenuItem miShare = new MenuItem(spoonMenu, SWT.PUSH);
miShare.setText(Messages.getString("Spoon.Menu.Popup.CLUSTERS.Share"));
miShare.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { shareObject(clusterSchema); } } );
MenuItem miMonitor = new MenuItem(spoonMenu, SWT.PUSH);
miMonitor.setText(Messages.getString("Spoon.Menu.Popup.CLUSTERS.Monitor"));//New
miMonitor.addListener( SWT.Selection, new Listener() { public void handleEvent(Event e) { monitorClusterSchema(clusterSchema); } } );
}
// Right click on a slave server
if (selection instanceof SlaveServer)
{
final TransMeta transMeta = (TransMeta)parent;
final SlaveServer slaveServer = (SlaveServer)selection;
MenuItem miEdit = new MenuItem(spoonMenu, SWT.PUSH);
miEdit.setText(Messages.getString("Spoon.Menu.Popup.SLAVE_SERVER.Edit"));//New
miEdit.addListener( SWT.Selection, new Listener() { public void handleEvent(Event e) { editSlaveServer(slaveServer); } } );
MenuItem miDel = new MenuItem(spoonMenu, SWT.PUSH);
miDel.setText(Messages.getString("Spoon.Menu.Popup.SLAVE_SERVER.Delete"));//Delete
miDel.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { delSlaveServer(transMeta, slaveServer); } } );
MenuItem miMonitor = new MenuItem(spoonMenu, SWT.PUSH);
miMonitor.setText(Messages.getString("Spoon.Menu.Popup.SLAVE_SERVER.Monitor"));//New
miMonitor.addListener( SWT.Selection, new Listener() { public void handleEvent(Event e) { addSpoonSlave(slaveServer); } } );
}
}
selectionTree.setMenu(spoonMenu);
}
/**
* Reaction to double click
*
*/
private void doubleClickedInTree()
{
TreeSelection[] objects = getTreeObjects(selectionTree);
if (objects.length!=1) return; // not yet supported, we can do this later when the OSX bug goes away
TreeSelection object = objects[0];
final Object selection = object.getSelection();
final Object parent = object.getParent();
if (selection instanceof Class)
{
if (selection.equals(TransMeta.class)) newTransFile();
if (selection.equals(JobMeta.class)) newJobFile();
if (selection.equals(TransHopMeta.class)) newHop((TransMeta)parent);
if (selection.equals(DatabaseMeta.class)) newConnection((HasDatabasesInterface)parent);
if (selection.equals(PartitionSchema.class)) newDatabasePartitioningSchema((TransMeta)parent);
if (selection.equals(ClusterSchema.class)) newClusteringSchema((TransMeta)parent);
if (selection.equals(SlaveServer.class)) newSlaveServer((TransMeta)parent);
}
else
{
if (selection instanceof StepPlugin) newStep(getActiveTransformation());
if (selection instanceof DatabaseMeta) editConnection((HasDatabasesInterface) parent, (DatabaseMeta) selection);
if (selection instanceof StepMeta) editStep((TransMeta)parent, (StepMeta)selection);
if (selection instanceof JobEntryCopy) editJobEntry((JobMeta)parent, (JobEntryCopy)selection);
if (selection instanceof TransHopMeta) editHop((TransMeta)parent, (TransHopMeta)selection);
if (selection instanceof PartitionSchema) editPartitionSchema((HasDatabasesInterface)parent, (PartitionSchema)selection);
if (selection instanceof ClusterSchema) editClusterSchema((TransMeta)parent, (ClusterSchema)selection);
if (selection instanceof SlaveServer) editSlaveServer((SlaveServer)selection);
}
}
protected void monitorClusterSchema(ClusterSchema clusterSchema)
{
for (int i=0;i<clusterSchema.getSlaveServers().size();i++)
{
SlaveServer slaveServer = (SlaveServer) clusterSchema.getSlaveServers().get(i);
addSpoonSlave(slaveServer);
}
}
protected void editSlaveServer(SlaveServer slaveServer)
{
SlaveServerDialog dialog = new SlaveServerDialog(shell, slaveServer);
if (dialog.open())
{
refreshTree();
refreshGraph();
}
}
private void addTabs()
{
if (tabComp!=null)
{
tabComp.dispose();
}
tabComp = new Composite(sashform, SWT.BORDER );
props.setLook(tabComp);
tabComp.setLayout(new GridLayout());
tabfolder= new CTabFolder(tabComp, SWT.BORDER);
tabfolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
props.setLook(tabfolder, Props.WIDGET_STYLE_TAB);
tabfolder.setSimple(false);
tabfolder.setUnselectedImageVisible(true);
tabfolder.setUnselectedCloseVisible(true);
tabfolder.addKeyListener(defKeys);
tabfolder.addKeyListener(modKeys);
// tabfolder.setSelection(0);
sashform.addKeyListener(defKeys);
sashform.addKeyListener(modKeys);
int weights[] = props.getSashWeights();
sashform.setWeights(weights);
sashform.setVisible(true);
tabfolder.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent event) {
ArrayList collection = new ArrayList();
collection.addAll(tabMap.values());
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
TabMapEntry entry = (TabMapEntry) iter.next();
if (event.item.equals(entry.getTabItem()))
{
// TabItemInterface itemInterface = entry.getObject();
//
// Another way to implement this may be to keep track of the
// state of the core object tree in method addCoreObjectsToTree()
//
if (event.doit && entry.getObject() instanceof SpoonGraph)
{
if ( getCoreObjectsState() != STATE_CORE_OBJECTS_SPOON )
{
refreshCoreObjectsTree();
}
}
if (event.doit && entry.getObject() instanceof ChefGraph)
{
if ( getCoreObjectsState() != STATE_CORE_OBJECTS_CHEF )
{
refreshCoreObjectsTree();
}
}
}
}
}
});
tabfolder.addCTabFolder2Listener(new CTabFolder2Adapter()
{
public void close(CTabFolderEvent event)
{
// Try to find the tab-item that's being closed.
ArrayList collection = new ArrayList();
collection.addAll(tabMap.values());
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
TabMapEntry entry = (TabMapEntry) iter.next();
if (event.item.equals(entry.getTabItem()))
{
TabItemInterface itemInterface = entry.getObject();
boolean close = true;
// Can we close this tab?
if (!itemInterface.canBeClosed())
{
int reply = itemInterface.showChangedWarning();
if (reply==SWT.YES)
{
close=itemInterface.applyChanges();
}
else
{
if (reply==SWT.CANCEL)
{
close = false;
}
else
{
close = true;
}
}
}
event.doit=close;
// Also clean up the log/history associated with this transformation/job
//
if (event.doit && entry.getObject() instanceof SpoonGraph)
{
TransMeta transMeta = (TransMeta)entry.getObject().getManagedObject();
closeTransformation(transMeta);
refreshTree();
}
if (event.doit && entry.getObject() instanceof ChefGraph)
{
JobMeta jobMeta = (JobMeta)entry.getObject().getManagedObject();
closeJob(jobMeta);
refreshTree();
}
if (event.doit && entry.getObject() instanceof SpoonBrowser)
{
closeSpoonBrowser();
refreshTree();
}
}
}
}
}
);
// Drag & Drop for steps
Transfer[] ttypes = new Transfer[] { XMLTransfer.getInstance() };
DropTarget ddTarget = new DropTarget(tabfolder, DND.DROP_MOVE);
ddTarget.setTransfer(ttypes);
ddTarget.addDropListener(new DropTargetListener()
{
public void dragEnter(DropTargetEvent event)
{
}
public void dragLeave(DropTargetEvent event)
{
}
public void dragOperationChanged(DropTargetEvent event)
{
}
public void dragOver(DropTargetEvent event)
{
}
public void drop(DropTargetEvent event)
{
// no data to copy, indicate failure in event.detail
if (event.data == null)
{
event.detail = DND.DROP_NONE;
return;
}
// What's the real drop position?
Point p = new Point(event.x, event.y);
// Subtract locations of parents...
Composite follow = tabfolder;
while (follow.getParent()!=null)
{
follow=follow.getParent();
org.eclipse.swt.graphics.Point parentLoc = follow.getLocation();
p.x-=parentLoc.x;
p.y-=parentLoc.y;
}
p.x-=10;
p.y-=75;
//
// We expect a Drag and Drop container... (encased in XML)
try
{
DragAndDropContainer container = (DragAndDropContainer)event.data;
switch(container.getType())
{
// Create a new step
// Since we drag onto the tabfolder, there is no graph to accept this
// Therefor we need to create a new transformation.
//
case DragAndDropContainer.TYPE_BASE_STEP_TYPE:
{
// Add the transformation.
// Since there is no transformation or job loaded, it should be safe to do so.
//
TransMeta transMeta = new TransMeta();
try
{
transMeta.readSharedObjects(rep);
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", makeGraphTabName(transMeta)), e);
}
addSpoonGraph(transMeta);
// Not an existing step: data refers to the type of step to create
String steptype = container.getData();
StepMeta stepMeta = newStep(transMeta, steptype, steptype, false, true);
stepMeta.setLocation(p);
stepMeta.setDraw(true);
addUndoNew(transMeta, new StepMeta[] { stepMeta }, new int[] { 0 });
refreshTree();
}
break;
// Create a new TableInput step using the selected connection...
case DragAndDropContainer.TYPE_BASE_JOB_ENTRY:
{
// Add the job.
// Since there is no job or job loaded, it should be safe to do so.
//
JobMeta jobMeta = new JobMeta(log);
try
{
jobMeta.readSharedObjects(rep);
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", makeJobGraphTabName(jobMeta)), e);
}
addChefGraph(jobMeta);
// Not an existing entry: data refers to the type of step to create
String steptype = container.getData();
JobEntryCopy jobEntry = newJobEntry(jobMeta, steptype, false);
jobEntry.setLocation(p);
jobEntry.setDrawn(true);
refreshGraph();
refreshTree();
}
break;
}
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("SpoonGraph.Dialog.ErrorDroppingObject.Message"), Messages.getString("SpoonGraph.Dialog.ErrorDroppingObject.Title"), e);
}
}
public void dropAccept(DropTargetEvent event)
{
}
}
);
}
public String getRepositoryName()
{
if (rep==null) return null;
return rep.getRepositoryInfo().getName();
}
public void sqlConnection(DatabaseMeta databaseMeta)
{
SQLEditor sql = new SQLEditor(shell, SWT.NONE, databaseMeta, DBCache.getInstance(), "");
sql.open();
}
public void editConnection(HasDatabasesInterface hasDatabasesInterface, DatabaseMeta databaseMeta)
{
DatabaseMeta before = (DatabaseMeta)databaseMeta.clone();
DatabaseDialog con = new DatabaseDialog(shell, databaseMeta);
con.setDatabases(hasDatabasesInterface.getDatabases());
String newname = con.open();
if (!Const.isEmpty(newname)) // null: CANCEL
{
// newname = db.verifyAndModifyDatabaseName(transMeta.getDatabases(), name);
// Store undo/redo information
DatabaseMeta after = (DatabaseMeta)databaseMeta.clone();
addUndoChange((UndoInterface)hasDatabasesInterface, new DatabaseMeta[] { before }, new DatabaseMeta[] { after }, new int[] { hasDatabasesInterface.indexOfDatabase(databaseMeta) } );
saveConnection(databaseMeta);
refreshTree();
}
setShellText();
}
public void dupeConnection(HasDatabasesInterface hasDatabasesInterface, DatabaseMeta databaseMeta)
{
String name = databaseMeta.getName();
int pos = hasDatabasesInterface.indexOfDatabase(databaseMeta);
if (databaseMeta!=null)
{
DatabaseMeta databaseMetaCopy = (DatabaseMeta)databaseMeta.clone();
String dupename = Messages.getString("Spoon.Various.DupeName") +name; //"(copy of) "
databaseMetaCopy.setName(dupename);
DatabaseDialog con = new DatabaseDialog(shell, databaseMetaCopy);
String newname = con.open();
if (newname != null) // null: CANCEL
{
databaseMetaCopy.verifyAndModifyDatabaseName(hasDatabasesInterface.getDatabases(), name);
hasDatabasesInterface.addDatabase(pos+1, databaseMetaCopy);
addUndoNew((UndoInterface)hasDatabasesInterface, new DatabaseMeta[] { (DatabaseMeta)databaseMetaCopy.clone() }, new int[] { pos+1 });
saveConnection(databaseMetaCopy);
refreshTree();
}
}
}
public void clipConnection(DatabaseMeta databaseMeta)
{
String xml = XMLHandler.getXMLHeader() + databaseMeta.getXML();
toClipboard(xml);
}
/**
* Delete a database connection
* @param name The name of the database connection.
*/
public void delConnection(HasDatabasesInterface hasDatabasesInterface, DatabaseMeta db)
{
int pos = hasDatabasesInterface.indexOfDatabase(db);
boolean worked=false;
// delete from repository?
if (rep!=null)
{
if (!rep.getUserInfo().isReadonly())
{
try
{
long id_database = rep.getDatabaseID(db.getName());
rep.delDatabase(id_database);
worked=true;
}
catch(KettleDatabaseException dbe)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorDeletingConnection.Title"), Messages.getString("Spoon.Dialog.ErrorDeletingConnection.Message",db.getName()), dbe);//"Error deleting connection ["+db+"] from repository!"
}
}
else
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorDeletingConnection.Title"),Messages.getString("Spoon.Dialog.ErrorDeletingConnection.Message",db.getName()) , new KettleException(Messages.getString("Spoon.Dialog.Exception.ReadOnlyUser")));//"Error deleting connection ["+db+"] from repository!" //This user is read-only!
}
}
if (rep==null || worked)
{
addUndoDelete((UndoInterface)hasDatabasesInterface, new DatabaseMeta[] { (DatabaseMeta)db.clone() }, new int[] { pos });
hasDatabasesInterface.removeDatabase(pos);
}
refreshTree();
setShellText();
}
public String editStep(TransMeta transMeta, StepMeta stepMeta)
{
boolean refresh = false;
try
{
String name = stepMeta.getName();
// Before we do anything, let's store the situation the way it was...
StepMeta before = (StepMeta) stepMeta.clone();
StepMetaInterface stepint = stepMeta.getStepMetaInterface();
StepDialogInterface dialog = stepint.getDialog(shell, stepMeta.getStepMetaInterface(), transMeta, name);
dialog.setRepository(rep);
String stepname = dialog.open();
if (stepname != null)
{
//
// See if the new name the user enter, doesn't collide with another step.
// If so, change the stepname and warn the user!
//
String newname = stepname;
StepMeta smeta = transMeta.findStep(newname, stepMeta);
int nr = 2;
while (smeta != null)
{
newname = stepname + " " + nr;
smeta = transMeta.findStep(newname);
nr++;
}
if (nr > 2)
{
stepname = newname;
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(Messages.getString("Spoon.Dialog.StepnameExists.Message", stepname)); // $NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.StepnameExists.Title")); // $NON-NLS-1$
mb.open();
}
if (!stepname.equals(name)) refresh=true;
stepMeta.setName(stepname);
//
// OK, so the step has changed...
// Backup the situation for undo/redo
//
StepMeta after = (StepMeta) stepMeta.clone();
addUndoChange(transMeta, new StepMeta[] { before }, new StepMeta[] { after }, new int[] { transMeta.indexOfStep(stepMeta) });
}
else
{
// Scenario: change connections and click cancel...
// Perhaps new connections were created in the step dialog?
if (transMeta.haveConnectionsChanged())
{
refresh=true;
}
}
refreshGraph(); // name is displayed on the graph too.
// TODO: verify "double pathway" steps for bug #4365
// After the step was edited we can complain about the possible deadlock here.
//
}
catch (Throwable e)
{
if (shell.isDisposed()) return null;
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.UnableOpenDialog.Title"), Messages.getString("Spoon.Dialog.UnableOpenDialog.Message"), new Exception(e));//"Unable to open dialog for this step"
}
if (refresh) refreshTree(); // Perhaps new connections were created in the step dialog or the step name changed.
return stepMeta.getName();
}
public void dupeStep(TransMeta transMeta, StepMeta stepMeta)
{
log.logDebug(toString(), Messages.getString("Spoon.Log.DuplicateStep")+stepMeta.getName());//Duplicate step:
StepMeta stMeta = (StepMeta)stepMeta.clone();
if (stMeta!=null)
{
String newname = transMeta.getAlternativeStepname(stepMeta.getName());
int nr=2;
while (transMeta.findStep(newname)!=null)
{
newname = stepMeta.getName()+" (copy "+nr+")";
nr++;
}
stMeta.setName(newname);
// Don't select this new step!
stMeta.setSelected(false);
Point loc = stMeta.getLocation();
stMeta.setLocation(loc.x+20, loc.y+20);
transMeta.addStep(stMeta);
addUndoNew(transMeta, new StepMeta[] { (StepMeta)stMeta.clone() }, new int[] { transMeta.indexOfStep(stMeta) });
refreshTree();
refreshGraph();
}
}
public void clipStep(TransMeta transMeta, StepMeta stepMeta)
{
String xml = stepMeta.getXML();
toClipboard(xml);
}
public void pasteXML(TransMeta transMeta, String clipcontent, Point loc)
{
try
{
Document doc = XMLHandler.loadXMLString(clipcontent);
Node transnode = XMLHandler.getSubNode(doc, "transformation");
// De-select all, re-select pasted steps...
transMeta.unselectAll();
Node stepsnode = XMLHandler.getSubNode(transnode, "steps");
int nr = XMLHandler.countNodes(stepsnode, "step");
log.logDebug(toString(), Messages.getString("Spoon.Log.FoundSteps",""+nr)+loc);//"I found "+nr+" steps to paste on location: "
StepMeta steps[] = new StepMeta[nr];
//Point min = new Point(loc.x, loc.y);
Point min = new Point(99999999,99999999);
// Load the steps...
for (int i=0;i<nr;i++)
{
Node stepnode = XMLHandler.getSubNodeByNr(stepsnode, "step", i);
steps[i] = new StepMeta(stepnode, transMeta.getDatabases(), transMeta.getCounters());
if (loc!=null)
{
Point p = steps[i].getLocation();
if (min.x > p.x) min.x = p.x;
if (min.y > p.y) min.y = p.y;
}
}
// Load the hops...
Node hopsnode = XMLHandler.getSubNode(transnode, "order");
nr = XMLHandler.countNodes(hopsnode, "hop");
log.logDebug(toString(), Messages.getString("Spoon.Log.FoundHops",""+nr));//"I found "+nr+" hops to paste."
TransHopMeta hops[] = new TransHopMeta[nr];
ArrayList alSteps = new ArrayList();
for (int i=0;i<steps.length;i++) alSteps.add(steps[i]);
for (int i=0;i<nr;i++)
{
Node hopnode = XMLHandler.getSubNodeByNr(hopsnode, "hop", i);
hops[i] = new TransHopMeta(hopnode, alSteps);
}
// What's the difference between loc and min?
// This is the offset:
Point offset = new Point(loc.x-min.x, loc.y-min.y);
// Undo/redo object positions...
int position[] = new int[steps.length];
for (int i=0;i<steps.length;i++)
{
Point p = steps[i].getLocation();
String name = steps[i].getName();
steps[i].setLocation(p.x+offset.x, p.y+offset.y);
steps[i].setDraw(true);
// Check the name, find alternative...
steps[i].setName( transMeta.getAlternativeStepname(name) );
transMeta.addStep(steps[i]);
position[i] = transMeta.indexOfStep(steps[i]);
steps[i].setSelected(true);
}
// Add the hops too...
for (int i=0;i<hops.length;i++)
{
transMeta.addTransHop(hops[i]);
}
// Load the notes...
Node notesnode = XMLHandler.getSubNode(transnode, "notepads");
nr = XMLHandler.countNodes(notesnode, "notepad");
log.logDebug(toString(), Messages.getString("Spoon.Log.FoundNotepads",""+nr));//"I found "+nr+" notepads to paste."
NotePadMeta notes[] = new NotePadMeta[nr];
for (int i=0;i<notes.length;i++)
{
Node notenode = XMLHandler.getSubNodeByNr(notesnode, "notepad", i);
notes[i] = new NotePadMeta(notenode);
Point p = notes[i].getLocation();
notes[i].setLocation(p.x+offset.x, p.y+offset.y);
transMeta.addNote(notes[i]);
notes[i].setSelected(true);
}
// Set the source and target steps ...
for (int i=0;i<steps.length;i++)
{
StepMetaInterface smi = steps[i].getStepMetaInterface();
smi.searchInfoAndTargetSteps(transMeta.getSteps());
}
// Save undo information too...
addUndoNew(transMeta, steps, position, false);
int hoppos[] = new int[hops.length];
for (int i=0;i<hops.length;i++) hoppos[i] = transMeta.indexOfTransHop(hops[i]);
addUndoNew(transMeta, hops, hoppos, true);
int notepos[] = new int[notes.length];
for (int i=0;i<notes.length;i++) notepos[i] = transMeta.indexOfNote(notes[i]);
addUndoNew(transMeta, notes, notepos, true);
if (transMeta.haveStepsChanged())
{
refreshTree();
refreshGraph();
}
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.UnablePasteSteps.Title"),Messages.getString("Spoon.Dialog.UnablePasteSteps.Message") , e);//"Error pasting steps...", "I was unable to paste steps to this transformation"
}
}
public void copySelected(TransMeta transMeta, StepMeta stepMeta[], NotePadMeta notePadMeta[])
{
if (stepMeta==null || stepMeta.length==0) return;
String xml = XMLHandler.getXMLHeader();
xml+="<transformation>"+Const.CR;
xml+=" <steps>"+Const.CR;
for (int i=0;i<stepMeta.length;i++)
{
xml+=stepMeta[i].getXML();
}
xml+=" </steps>"+Const.CR;
//
// Also check for the hops in between the selected steps...
//
xml+="<order>"+Const.CR;
if (stepMeta!=null)
for (int i=0;i<stepMeta.length;i++)
{
for (int j=0;j<stepMeta.length;j++)
{
if (i!=j)
{
TransHopMeta hop = transMeta.findTransHop(stepMeta[i], stepMeta[j], true);
if (hop!=null) // Ok, we found one...
{
xml+=hop.getXML()+Const.CR;
}
}
}
}
xml+=" </order>"+Const.CR;
xml+=" <notepads>"+Const.CR;
if (notePadMeta!=null)
for (int i=0;i<notePadMeta.length;i++)
{
xml+= notePadMeta[i].getXML();
}
xml+=" </notepads>"+Const.CR;
xml+=" </transformation>"+Const.CR;
toClipboard(xml);
}
public void delStep(TransMeta transMeta, StepMeta stepMeta)
{
log.logDebug(toString(), Messages.getString("Spoon.Log.DeleteStep")+stepMeta.getName());//"Delete step: "
for (int i=transMeta.nrTransHops()-1;i>=0;i--)
{
TransHopMeta hi = transMeta.getTransHop(i);
if ( hi.getFromStep().equals(stepMeta) || hi.getToStep().equals(stepMeta) )
{
addUndoDelete(transMeta, new TransHopMeta[] { hi }, new int[] { transMeta.indexOfTransHop(hi) }, true);
transMeta.removeTransHop(i);
refreshTree();
}
}
int pos = transMeta.indexOfStep(stepMeta);
transMeta.removeStep(pos);
addUndoDelete(transMeta, new StepMeta[] { stepMeta }, new int[] { pos });
refreshTree();
refreshGraph();
}
public void editHop(TransMeta transMeta, TransHopMeta transHopMeta)
{
// Backup situation BEFORE edit:
String name = transHopMeta.toString();
TransHopMeta before = (TransHopMeta)transHopMeta.clone();
TransHopDialog hd = new TransHopDialog(shell, SWT.NONE, transHopMeta, transMeta);
if (hd.open()!=null)
{
// Backup situation for redo/undo:
TransHopMeta after = (TransHopMeta)transHopMeta.clone();
addUndoChange(transMeta, new TransHopMeta[] { before }, new TransHopMeta[] { after }, new int[] { transMeta.indexOfTransHop(transHopMeta) } );
String newname = transHopMeta.toString();
if (!name.equalsIgnoreCase(newname))
{
refreshTree();
refreshGraph(); // color, nr of copies...
}
}
setShellText();
}
public void delHop(TransMeta transMeta, TransHopMeta transHopMeta)
{
int i = transMeta.indexOfTransHop(transHopMeta);
addUndoDelete(transMeta, new Object[] { (TransHopMeta)transHopMeta.clone() }, new int[] { transMeta.indexOfTransHop(transHopMeta) });
transMeta.removeTransHop(i);
refreshTree();
refreshGraph();
}
public void newHop(TransMeta transMeta, StepMeta fr, StepMeta to)
{
TransHopMeta hi = new TransHopMeta(fr, to);
TransHopDialog hd = new TransHopDialog(shell, SWT.NONE, hi, transMeta);
if (hd.open()!=null)
{
boolean error=false;
if (transMeta.findTransHop(hi.getFromStep(), hi.getToStep())!=null)
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("Spoon.Dialog.HopExists.Message"));//"This hop already exists!"
mb.setText(Messages.getString("Spoon.Dialog.HopExists.Title"));//Error!
mb.open();
error=true;
}
if (transMeta.hasLoop(fr) || transMeta.hasLoop(to))
{
refreshTree();
refreshGraph();
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_WARNING );
mb.setMessage(Messages.getString("Spoon.Dialog.AddingHopCausesLoop.Message"));//Adding this hop causes a loop in the transformation. Loops are not allowed!
mb.setText(Messages.getString("Spoon.Dialog.AddingHopCausesLoop.Title"));//Warning!
mb.open();
error=true;
}
if (!error)
{
transMeta.addTransHop(hi);
addUndoNew(transMeta, new TransHopMeta[] { (TransHopMeta)hi.clone() }, new int[] { transMeta.indexOfTransHop(hi) });
hi.getFromStep().drawStep();
hi.getToStep().drawStep();
refreshTree();
refreshGraph();
// Check if there are 2 hops coming out of the "From" step.
verifyCopyDistribute(transMeta, fr);
}
}
}
public void verifyCopyDistribute(TransMeta transMeta, StepMeta fr)
{
int nrNextSteps = transMeta.findNrNextSteps(fr);
// don't show it for 3 or more hops, by then you should have had the message
if (nrNextSteps==2)
{
boolean distributes = false;
if (props.showCopyOrDistributeWarning())
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell,
Messages.getString("System.Warning"),//"Warning!"
null,
Messages.getString("Spoon.Dialog.CopyOrDistribute.Message", fr.getName(), Integer.toString(nrNextSteps)),
MessageDialog.WARNING,
new String[] { Messages.getString("Spoon.Dialog.CopyOrDistribute.Copy"), Messages.getString("Spoon.Dialog.CopyOrDistribute.Distribute") },//"Copy Distribute
0,
Messages.getString("Spoon.Message.Warning.NotShowWarning"),//"Please, don't show this warning anymore."
!props.showCopyOrDistributeWarning()
);
int idx = md.open();
props.setShowCopyOrDistributeWarning(!md.getToggleState());
props.saveProps();
distributes = (idx&0xFF)==1;
}
if (distributes)
{
fr.setDistributes(true);
}
else
{
fr.setDistributes(false);
}
refreshTree();
refreshGraph();
}
}
public void newHop(TransMeta transMeta)
{
newHop(transMeta, null, null);
}
public void newConnection(HasDatabasesInterface hasDatabasesInterface)
{
DatabaseMeta databaseMeta = new DatabaseMeta();
DatabaseDialog con = new DatabaseDialog(shell, databaseMeta);
String con_name = con.open();
if (!Const.isEmpty(con_name))
{
databaseMeta.verifyAndModifyDatabaseName(hasDatabasesInterface.getDatabases(), null);
hasDatabasesInterface.addDatabase(databaseMeta);
addUndoNew((UndoInterface)hasDatabasesInterface, new DatabaseMeta[] { (DatabaseMeta)databaseMeta.clone() }, new int[] { hasDatabasesInterface.indexOfDatabase(databaseMeta) });
saveConnection(databaseMeta);
refreshTree();
}
}
public void saveConnection(DatabaseMeta db)
{
// Also add to repository?
if (rep!=null)
{
if (!rep.userinfo.isReadonly())
{
try
{
rep.lockRepository();
rep.insertLogEntry("Saving database '"+db.getName()+"'");
db.saveRep(rep);
log.logDetailed(toString(), Messages.getString("Spoon.Log.SavedDatabaseConnection",db.getDatabaseName()));//"Saved database connection ["+db+"] to the repository."
// Put a commit behind it!
rep.commit();
db.setChanged(false);
}
catch(KettleException ke)
{
rep.rollback(); // In case of failure: undo changes!
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorSavingConnection.Title"),Messages.getString("Spoon.Dialog.ErrorSavingConnection.Message",db.getDatabaseName()), ke);//"Can't save...","Error saving connection ["+db+"] to repository!"
}
finally
{
try
{
rep.unlockRepository();
}
catch(KettleDatabaseException e)
{
new ErrorDialog(shell, "Error", "Unexpected error unlocking the repository database", e);
}
}
}
else
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.UnableSave.Title"),Messages.getString("Spoon.Dialog.ErrorSavingConnection.Message",db.getDatabaseName()), new KettleException(Messages.getString("Spoon.Dialog.Exception.ReadOnlyRepositoryUser")));//This repository user is read-only!
}
}
}
public void openRepository()
{
int perms[] = new int[] { PermissionMeta.TYPE_PERMISSION_TRANSFORMATION };
RepositoriesDialog rd = new RepositoriesDialog(disp, SWT.NONE, perms, APP_NAME);
rd.getShell().setImage(GUIResource.getInstance().getImageSpoon());
if (rd.open())
{
// Close previous repository...
if (rep!=null)
{
rep.disconnect();
}
rep = new Repository(log, rd.getRepository(), rd.getUser());
try
{
rep.connect(APP_NAME);
}
catch(KettleException ke)
{
rep=null;
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorConnectingRepository.Title"), Messages.getString("Spoon.Dialog.ErrorConnectingRepository.Message",Const.CR), ke); //$NON-NLS-1$ //$NON-NLS-2$
}
TransMeta transMetas[] = getLoadedTransformations();
for (int t=0;t<transMetas.length;t++)
{
TransMeta transMeta = transMetas[t];
for (int i=0;i<transMeta.nrDatabases();i++)
{
transMeta.getDatabase(i).setID(-1L);
}
// Set for the existing transformation the ID at -1!
transMeta.setID(-1L);
// Keep track of the old databases for now.
ArrayList oldDatabases = transMeta.getDatabases();
// In order to re-match the databases on name (not content), we need to load the databases from the new repository.
// NOTE: for purposes such as DEVELOP - TEST - PRODUCTION sycles.
// first clear the list of databases, partition schemas, slave servers, clusters
transMeta.setDatabases(new ArrayList());
transMeta.setPartitionSchemas(new ArrayList());
transMeta.setSlaveServers(new ArrayList());
transMeta.setClusterSchemas(new ArrayList());
// Read them from the new repository.
try
{
transMeta.readSharedObjects(rep);
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", makeGraphTabName(transMeta)), e);
}
// Then we need to re-match the databases at save time...
for (int i=0;i<oldDatabases.size();i++)
{
DatabaseMeta oldDatabase = (DatabaseMeta) oldDatabases.get(i);
DatabaseMeta newDatabase = Const.findDatabase(transMeta.getDatabases(), oldDatabase.getName());
// If it exists, change the settings...
if (newDatabase!=null)
{
//
// A database connection with the same name exists in the new repository.
// Change the old connections to reflect the settings in the new repository
//
oldDatabase.setDatabaseInterface(newDatabase.getDatabaseInterface());
}
else
{
//
// The old database is not present in the new repository: simply add it to the list.
// When the transformation gets saved, it will be added to the repository.
//
transMeta.addDatabase(oldDatabase);
}
}
// For the existing transformation, change the directory too:
// Try to find the same directory in the new repository...
RepositoryDirectory redi = rep.getDirectoryTree().findDirectory(transMeta.getDirectory().getPath());
if (redi!=null)
{
transMeta.setDirectory(redi);
}
else
{
transMeta.setDirectory(rep.getDirectoryTree()); // the root is the default!
}
}
refreshTree();
setShellText();
}
else
{
// Not cancelled? --> Clear repository...
if (!rd.isCancelled())
{
closeRepository();
}
}
}
public void exploreRepository()
{
if (rep!=null)
{
RepositoryExplorerDialog erd = new RepositoryExplorerDialog(shell, SWT.NONE, rep, rep.getUserInfo());
String objname = erd.open();
if (objname!=null)
{
String object_type = erd.getObjectType();
RepositoryDirectory repdir = erd.getObjectDirectory();
// Try to open the selected transformation.
if (object_type.equals(RepositoryExplorerDialog.STRING_TRANSFORMATIONS))
{
try
{
TransMeta transMeta = new TransMeta(rep, objname, repdir);
transMeta.clearChanged();
transMeta.setFilename(objname);
addSpoonGraph(transMeta);
refreshTree();
refreshGraph();
}
catch(KettleException e)
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("Spoon.Dialog.ErrorOpening.Message")+objname+Const.CR+e.getMessage());//"Error opening : "
mb.setText(Messages.getString("Spoon.Dialog.ErrorOpening.Title"));
mb.open();
}
}
else
// Try to open the selected job.
if (object_type.equals(RepositoryExplorerDialog.STRING_JOBS))
{
try
{
JobMeta jobMeta = new JobMeta(log, rep, objname, repdir);
jobMeta.clearChanged();
jobMeta.setFilename(objname);
addChefGraph(jobMeta);
refreshTree();
refreshGraph();
}
catch(KettleException e)
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("Spoon.Dialog.ErrorOpening.Message")+objname+Const.CR+e.getMessage());//"Error opening : "
mb.setText(Messages.getString("Spoon.Dialog.ErrorOpening.Title"));
mb.open();
}
}
}
}
}
public void editRepositoryUser()
{
if (rep!=null)
{
UserInfo userinfo = rep.getUserInfo();
UserDialog ud = new UserDialog(shell, SWT.NONE, log, props, rep, userinfo);
UserInfo ui = ud.open();
if (!userinfo.isReadonly())
{
if (ui!=null)
{
try
{
ui.saveRep(rep);
}
catch(KettleException e)
{
MessageBox mb = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
mb.setMessage(Messages.getString("Spoon.Dialog.UnableChangeUser.Message")+Const.CR+e.getMessage());//Sorry, I was unable to change this user in the repository:
mb.setText(Messages.getString("Spoon.Dialog.UnableChangeUser.Title"));//"Edit user"
mb.open();
}
}
}
else
{
MessageBox mb = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
mb.setMessage(Messages.getString("Spoon.Dialog.NotAllowedChangeUser.Message"));//"Sorry, you are not allowed to change this user."
mb.setText(Messages.getString("Spoon.Dialog.NotAllowedChangeUser.Title"));
mb.open();
}
}
}
public void closeRepository()
{
if (rep!=null) rep.disconnect();
rep = null;
setShellText();
}
public void openFile(boolean importfile)
{
if (rep==null || importfile) // Load from XML
{
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(Const.STRING_TRANS_AND_JOB_FILTER_EXT);
dialog.setFilterNames(Const.STRING_TRANS_AND_JOB_FILTER_NAMES);
String fname = dialog.open();
if (fname!=null)
{
openFile(fname, importfile);
}
}
else
{
SelectObjectDialog sod = new SelectObjectDialog(shell, rep);
if (sod.open()!=null)
{
String type = sod.getObjectType();
String name = sod.getObjectName();
RepositoryDirectory repdir = sod.getDirectory();
// Load a transformation
if (RepositoryObject.STRING_OBJECT_TYPE_TRANSFORMATION.equals(type))
{
TransLoadProgressDialog tlpd = new TransLoadProgressDialog(shell, rep, name, repdir);
TransMeta transMeta = tlpd.open();
if (transMeta!=null)
{
log.logDetailed(toString(),Messages.getString("Spoon.Log.LoadToTransformation",name,repdir.getDirectoryName()) );//"Transformation ["+transname+"] in directory ["+repdir+"] loaded from the repository."
props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, name, repdir.getPath(), true, rep.getName());
addMenuLast();
transMeta.clearChanged();
transMeta.setFilename(name);
addSpoonGraph(transMeta);
}
refreshGraph();
refreshTree();
refreshHistory();
}
else
// Load a job
if (RepositoryObject.STRING_OBJECT_TYPE_JOB.equals(type))
{
JobLoadProgressDialog jlpd = new JobLoadProgressDialog(shell, rep, name, repdir);
JobMeta jobMeta = jlpd.open();
if (jobMeta!=null)
{
props.addLastFile(LastUsedFile.FILE_TYPE_JOB, name, repdir.getPath(), true, rep.getName());
saveSettings();
addMenuLast();
addChefGraph(jobMeta);
}
refreshGraph();
refreshTree();
}
}
}
}
public void openFile(String fname, boolean importfile)
{
// Open the XML and see what's in there.
// We expect a single <transformation> or <job> root at this time...
try
{
Document document = XMLHandler.loadXMLFile(fname);
boolean loaded = false;
// Check for a transformation...
Node transNode = XMLHandler.getSubNode(document, TransMeta.XML_TAG);
if (transNode!=null) // yep, found a transformation
{
TransMeta transMeta = new TransMeta();
transMeta.loadXML(transNode, rep, true);
props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, fname, null, false, null);
addMenuLast();
if (!importfile) transMeta.clearChanged();
transMeta.setFilename(fname);
addSpoonGraph(transMeta);
refreshTree();
refreshHistory();
loaded=true;
}
// Check for a job...
Node jobNode = XMLHandler.getSubNode(document, JobMeta.XML_TAG);
if (jobNode!=null) // Indeed, found a job
{
JobMeta jobMeta = new JobMeta(log);
jobMeta.loadXML(jobNode, rep);
props.addLastFile(LastUsedFile.FILE_TYPE_JOB, fname, null, false, null);
addMenuLast();
if (!importfile) jobMeta.clearChanged();
jobMeta.setFilename(fname);
addChefGraph(jobMeta);
loaded=true;
}
if (!loaded)
{
// Give error back
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("Spoon.UnknownFileType.Message", fname));
mb.setText(Messages.getString("Spoon.UnknownFileType.Title"));
mb.open();
}
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorOpening.Title"), Messages.getString("Spoon.Dialog.ErrorOpening.Message")+fname, e);
}
}
public void newFile()
{
String[] choices = new String[] { STRING_TRANSFORMATION, STRING_JOB };
EnterSelectionDialog enterSelectionDialog = new EnterSelectionDialog(shell, choices, Messages.getString("Spoon.Dialog.NewFile.Title"), Messages.getString("Spoon.Dialog.NewFile.Message"));
if (enterSelectionDialog.open()!=null)
{
switch( enterSelectionDialog.getSelectionNr() )
{
case 0: newTransFile(); break;
case 1: newJobFile(); break;
}
}
}
public void newTransFile()
{
TransMeta transMeta = new TransMeta();
try
{
transMeta.readSharedObjects(rep);
transMeta.clearChanged();
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Exception.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Exception.ErrorReadingSharedObjects.Message"), e);
}
addSpoonGraph(transMeta);
refreshTree();
}
public void newJobFile()
{
try
{
JobMeta jobMeta = new JobMeta(log);
try
{
jobMeta.readSharedObjects(rep);
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", makeJobGraphTabName(jobMeta)), e);
}
addChefGraph(jobMeta);
refreshTree();
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Exception.ErrorCreatingNewJob.Title"), Messages.getString("Spoon.Exception.ErrorCreatingNewJob.Message"), e);
}
}
public void loadRepositoryObjects(TransMeta transMeta)
{
// Load common database info from active repository...
if (rep!=null)
{
try
{
transMeta.readSharedObjects(rep);
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Error.UnableToLoadSharedObjects.Title"), Messages.getString("Spoon.Error.UnableToLoadSharedObjects.Message"), e);
}
}
}
public boolean quitFile()
{
log.logDetailed(toString(), Messages.getString("Spoon.Log.QuitApplication"));//"Quit application."
boolean exit = true;
saveSettings();
if (props.showExitWarning())
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell,
Messages.getString("System.Warning"),//"Warning!"
null,
Messages.getString("Spoon.Message.Warning.PromptExit"), // Are you sure you want to exit?
MessageDialog.WARNING,
new String[] { Messages.getString("Spoon.Message.Warning.Yes"), Messages.getString("Spoon.Message.Warning.No") },//"Yes", "No"
1,
Messages.getString("Spoon.Message.Warning.NotShowWarning"),//"Please, don't show this warning anymore."
!props.showExitWarning()
);
int idx = md.open();
props.setExitWarningShown(!md.getToggleState());
props.saveProps();
if ((idx&0xFF)==1) return false; // No selected: don't exit!
}
// Check all tabs to see if we can close them...
List list = new ArrayList();
list.addAll(tabMap.values());
for (Iterator iter = list.iterator(); iter.hasNext() && exit;)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
TabItemInterface itemInterface = mapEntry.getObject();
if (!itemInterface.canBeClosed())
{
// Show the tab
tabfolder.setSelection( mapEntry.getTabItem() );
// Unsaved work that needs to changes to be applied?
//
int reply= itemInterface.showChangedWarning();
if (reply==SWT.YES)
{
exit=itemInterface.applyChanges();
}
else
{
if (reply==SWT.CANCEL)
{
exit = false;
}
else // SWT.NO
{
exit = true;
}
}
/*
if (mapEntry.getObject() instanceof SpoonGraph)
{
TransMeta transMeta = (TransMeta) mapEntry.getObject().getManagedObject();
if (transMeta.hasChanged())
{
// Show the transformation in question
//
tabfolder.setSelection( mapEntry.getTabItem() );
// Ask if we should save it before closing...
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.CANCEL | SWT.ICON_WARNING );
mb.setMessage(Messages.getString("Spoon.Dialog.SaveChangedFile.Message", makeGraphTabName(transMeta)));//"File has changed! Do you want to save first?"
mb.setText(Messages.getString("Spoon.Dialog.SaveChangedFile.Title"));//"Warning!"
int answer = mb.open();
switch(answer)
{
case SWT.YES: exit=saveFile(transMeta); break;
case SWT.NO: exit=true; break;
case SWT.CANCEL:
exit=false;
break;
}
}
}
// A running transformation?
//
if (mapEntry.getObject() instanceof SpoonLog)
{
SpoonLog spoonLog = (SpoonLog) mapEntry.getObject();
if (spoonLog.isRunning())
{
if (reply==SWT.NO) exit=false; // No selected: don't exit!
}
}
*/
}
}
if (exit) // we have asked about it all and we're still here. Now close all the tabs, stop the running transformations
{
for (Iterator iter = list.iterator(); iter.hasNext() && exit;)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (!mapEntry.getObject().canBeClosed())
{
// Unsaved transformation?
//
if (mapEntry.getObject() instanceof SpoonGraph)
{
TransMeta transMeta = (TransMeta) mapEntry.getObject().getManagedObject();
if (transMeta.hasChanged())
{
mapEntry.getTabItem().dispose();
}
}
// A running transformation?
//
if (mapEntry.getObject() instanceof SpoonLog)
{
SpoonLog spoonLog = (SpoonLog) mapEntry.getObject();
if (spoonLog.isRunning())
{
spoonLog.stop();
mapEntry.getTabItem().dispose();
}
}
}
}
}
if (exit) dispose();
return exit;
}
public boolean saveFile()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null) return saveTransFile(transMeta);
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null) return saveJobFile(jobMeta);
return false;
}
public boolean saveTransFile(TransMeta transMeta)
{
if (transMeta==null) return false;
boolean saved=false;
log.logDetailed(toString(), Messages.getString("Spoon.Log.SaveToFileOrRepository"));//"Save to file or repository..."
if (rep!=null)
{
saved=saveTransRepository(transMeta);
}
else
{
if (transMeta.getFilename()!=null)
{
saved=save(transMeta, transMeta.getFilename());
}
else
{
saved=saveTransFileAs(transMeta);
}
}
if (saved) // all was OK
{
saved=saveTransSharedObjects(transMeta);
}
try
{
if (props.useDBCache()) transMeta.getDbCache().saveCache(log);
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorSavingDatabaseCache.Title"), Messages.getString("Spoon.Dialog.ErrorSavingDatabaseCache.Message"), e);//"An error occured saving the database cache to disk"
}
renameTabs(); // filename or name of transformation might have changed.
refreshTree();
return saved;
}
public boolean saveTransRepository(TransMeta transMeta)
{
return saveTransRepository(transMeta, false);
}
public boolean saveTransRepository(TransMeta transMeta, boolean ask_name)
{
log.logDetailed(toString(), Messages.getString("Spoon.Log.SaveToRepository"));//"Save to repository..."
if (rep!=null)
{
boolean answer = true;
boolean ask = ask_name;
while (answer && ( ask || transMeta.getName()==null || transMeta.getName().length()==0 ) )
{
if (!ask)
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("Spoon.Dialog.PromptTransformationName.Message"));//"Please give this transformation a name before saving it in the database."
mb.setText(Messages.getString("Spoon.Dialog.PromptTransformationName.Title"));//"Transformation has no name."
mb.open();
}
ask=false;
answer = editTransformationProperties(transMeta);
}
if (answer && transMeta.getName()!=null && transMeta.getName().length()>0)
{
if (!rep.getUserInfo().isReadonly())
{
int response = SWT.YES;
if (transMeta.showReplaceWarning(rep))
{
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.ICON_QUESTION);
mb.setMessage(Messages.getString("Spoon.Dialog.PromptOverwriteTransformation.Message",transMeta.getName(),Const.CR));//"There already is a transformation called ["+transMeta.getName()+"] in the repository."+Const.CR+"Do you want to overwrite the transformation?"
mb.setText(Messages.getString("Spoon.Dialog.PromptOverwriteTransformation.Title"));//"Overwrite?"
response = mb.open();
}
boolean saved=false;
if (response == SWT.YES)
{
shell.setCursor(cursor_hourglass);
// Keep info on who & when this transformation was changed...
transMeta.setModifiedDate( new Value("MODIFIED_DATE", Value.VALUE_TYPE_DATE) );
transMeta.getModifiedDate().sysdate();
transMeta.setModifiedUser( rep.getUserInfo().getLogin() );
TransSaveProgressDialog tspd = new TransSaveProgressDialog(shell, rep, transMeta);
if (tspd.open())
{
saved=true;
if (!props.getSaveConfirmation())
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell,
Messages.getString("Spoon.Message.Warning.SaveOK"), //"Save OK!"
null,
Messages.getString("Spoon.Message.Warning.TransformationWasStored"),//"This transformation was stored in repository"
MessageDialog.QUESTION,
new String[] { Messages.getString("Spoon.Message.Warning.OK") },//"OK!"
0,
Messages.getString("Spoon.Message.Warning.NotShowThisMessage"),//"Don't show this message again."
props.getSaveConfirmation()
);
md.open();
props.setSaveConfirmation(md.getToggleState());
}
// Handle last opened files...
props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, transMeta.getName(), transMeta.getDirectory().getPath(), true, getRepositoryName());
saveSettings();
addMenuLast();
setShellText();
}
shell.setCursor(null);
}
return saved;
}
else
{
MessageBox mb = new MessageBox(shell, SWT.CLOSE | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("Spoon.Dialog.OnlyreadRepository.Message"));//"Sorry, the user you're logged on with, can only read from the repository"
mb.setText(Messages.getString("Spoon.Dialog.OnlyreadRepository.Title"));//"Transformation not saved!"
mb.open();
}
}
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("Spoon.Dialog.NoRepositoryConnection.Message"));//"There is no repository connection available."
mb.setText(Messages.getString("Spoon.Dialog.NoRepositoryConnection.Title"));//"No repository available."
mb.open();
}
return false;
}
public boolean saveFileAs()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null) return saveTransFileAs(transMeta);
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null) return saveJobFileAs(jobMeta);
return false;
}
public boolean saveTransFileAs(TransMeta transMeta)
{
boolean saved=false;
log.logBasic(toString(), Messages.getString("Spoon.Log.SaveAs"));//"Save as..."
if (rep!=null)
{
transMeta.setID(-1L);
saved=saveTransRepository(transMeta, true);
renameTabs();
}
else
{
saved=saveTransXMLFile(transMeta);
renameTabs();
}
refreshTree();
return saved;
}
private void loadTransSharedObjects(TransMeta transMeta)
{
try
{
transMeta.readSharedObjects(rep);
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", makeGraphTabName(transMeta)), e);
}
}
private boolean saveTransSharedObjects(TransMeta transMeta)
{
try
{
transMeta.saveSharedObjects();
return true;
}
catch(Exception e)
{
log.logError(toString(), "Unable to save shared ojects: "+e.toString());
return false;
}
}
private void loadJobSharedObjects(JobMeta jobMeta)
{
try
{
jobMeta.readSharedObjects(rep);
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", makeJobGraphTabName(jobMeta)), e);
}
}
private boolean saveJobSharedObjects(JobMeta jobMeta)
{
try
{
jobMeta.saveSharedObjects();
return true;
}
catch(Exception e)
{
log.logError(toString(), "Unable to save shared ojects: "+e.toString());
return false;
}
}
private boolean saveXMLFile()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null) return saveTransXMLFile(transMeta);
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null) return saveJobXMLFile(jobMeta);
return false;
}
private boolean saveTransXMLFile(TransMeta transMeta)
{
boolean saved=false;
FileDialog dialog = new FileDialog(shell, SWT.SAVE);
dialog.setFilterExtensions(Const.STRING_TRANS_FILTER_EXT);
dialog.setFilterNames(Const.STRING_TRANS_FILTER_NAMES);
String fname = dialog.open();
if (fname!=null)
{
// Is the filename ending on .ktr, .xml?
boolean ending=false;
for (int i=0;i<Const.STRING_TRANS_FILTER_EXT.length-1;i++)
{
if (fname.endsWith(Const.STRING_TRANS_FILTER_EXT[i].substring(1)))
{
ending=true;
}
}
if (fname.endsWith(Const.STRING_TRANS_DEFAULT_EXT)) ending=true;
if (!ending)
{
fname+=Const.STRING_TRANS_DEFAULT_EXT;
}
// See if the file already exists...
File f = new File(fname);
int id = SWT.YES;
if (f.exists())
{
MessageBox mb = new MessageBox(shell, SWT.NO | SWT.YES | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("Spoon.Dialog.PromptOverwriteFile.Message"));//"This file already exists. Do you want to overwrite it?"
mb.setText(Messages.getString("Spoon.Dialog.PromptOverwriteFile.Title"));//"This file already exists!"
id = mb.open();
}
if (id==SWT.YES)
{
saved=save(transMeta, fname);
transMeta.setFilename(fname);
}
}
return saved;
}
private boolean save(TransMeta transMeta, String fname)
{
boolean saved = false;
String xml = XMLHandler.getXMLHeader() + transMeta.getXML();
try
{
DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File(fname)));
dos.write(xml.getBytes(Const.XML_ENCODING));
dos.close();
saved=true;
// Handle last opened files...
props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, fname, null, false, null);
saveSettings();
addMenuLast();
transMeta.clearChanged();
setShellText();
log.logDebug(toString(), Messages.getString("Spoon.Log.FileWritten")+" ["+fname+"]"); //"File written to
}
catch(Exception e)
{
log.logDebug(toString(), Messages.getString("Spoon.Log.ErrorOpeningFileForWriting")+e.toString());//"Error opening file for writing! --> "
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("Spoon.Dialog.ErrorSavingFile.Message")+Const.CR+e.toString());//"Error saving file:"
mb.setText(Messages.getString("Spoon.Dialog.ErrorSavingFile.Title"));//"ERROR"
mb.open();
}
return saved;
}
public void helpAbout()
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION | SWT.CENTER);
String mess = Messages.getString("System.ProductInfo")+Const.VERSION+Const.CR+Const.CR+Const.CR;//Kettle - Spoon version
mess+=Messages.getString("System.CompanyInfo")+Const.CR;
mess+=" "+Messages.getString("System.ProductWebsiteUrl")+Const.CR; //(c) 2001-2004 i-Bridge bvba www.kettle.be
mess+=Const.CR;
mess+=Const.CR;
mess+=Const.CR;
mess+=" Build version : "+BuildVersion.getInstance().getVersion()+Const.CR;
mess+=" Build date : "+BuildVersion.getInstance().getBuildDate()+Const.CR;
mb.setMessage(mess);
mb.setText(APP_NAME);
mb.open();
}
public void editUnselectAll(TransMeta transMeta)
{
transMeta.unselectAll();
// spoongraph.redraw();
}
public void editSelectAll(TransMeta transMeta)
{
transMeta.selectAll();
// spoongraph.redraw();
}
public void editOptions()
{
EnterOptionsDialog eod = new EnterOptionsDialog(shell, props);
if (eod.open()!=null)
{
props.saveProps();
loadSettings();
changeLooks();
MessageBox mb = new MessageBox(shell, SWT.ICON_INFORMATION);
mb.setMessage(Messages.getString("Spoon.Dialog.PleaseRestartApplication.Message"));
mb.setText(Messages.getString("Spoon.Dialog.PleaseRestartApplication.Title"));
mb.open();
}
}
/**
* Refresh the object selection tree (on the left of the screen)
* @param complete true refreshes the complete tree, false tries to do a differential update to avoid flickering.
*/
public void refreshTree()
{
if (shell.isDisposed()) return;
GUIResource guiResource = GUIResource.getInstance();
// get a list of transformations from the transformation map
Collection transformations = transformationMap.values();
TransMeta[] transMetas = (TransMeta[]) transformations.toArray(new TransMeta[transformations.size()]);
// get a list of jobs from the job map
Collection jobs = jobMap.values();
JobMeta[] jobMetas = (JobMeta[]) jobs.toArray(new JobMeta[jobs.size()]);
// Refresh the content of the tree for those transformations
//
// First remove the old ones.
tiTrans.removeAll();
tiJobs.removeAll();
// Now add the data back
//
for (int t=0;t<transMetas.length;t++)
{
TransMeta transMeta = transMetas[t];
// Add a tree item with the name of transformation
//
TreeItem tiTransName = new TreeItem(tiTrans, SWT.NONE);
String name = makeGraphTabName(transMeta);
if (Const.isEmpty(name)) name = STRING_TRANS_NO_NAME;
tiTransName.setText(name);
tiTransName.setImage(guiResource.getImageBol());
///////////////////////////////////////////////////////
//
// Now add the database connections
//
TreeItem tiDbTitle = new TreeItem(tiTransName, SWT.NONE);
tiDbTitle.setText(STRING_CONNECTIONS);
tiDbTitle.setImage(guiResource.getImageConnection());
// Draw the connections themselves below it.
for (int i=0;i<transMeta.nrDatabases();i++)
{
DatabaseMeta databaseMeta = transMeta.getDatabase(i);
TreeItem tiDb = new TreeItem(tiDbTitle, SWT.NONE);
tiDb.setText(databaseMeta.getName());
if (databaseMeta.isShared()) tiDb.setFont(guiResource.getFontBold());
tiDb.setImage(guiResource.getImageConnection());
}
///////////////////////////////////////////////////////
//
// The steps
//
TreeItem tiStepTitle = new TreeItem(tiTransName, SWT.NONE);
tiStepTitle.setText(STRING_STEPS);
tiStepTitle.setImage(guiResource.getImageBol());
// Put the steps below it.
for (int i=0;i<transMeta.nrSteps();i++)
{
StepMeta stepMeta = transMeta.getStep(i);
TreeItem tiStep = new TreeItem(tiStepTitle, SWT.NONE);
tiStep.setText(stepMeta.getName());
if (stepMeta.isShared()) tiStep.setFont(guiResource.getFontBold());
if (!stepMeta.isDrawn()) tiStep.setForeground(guiResource.getColorGray());
tiStep.setImage(guiResource.getImageBol());
}
///////////////////////////////////////////////////////
//
// The hops
//
TreeItem tiHopTitle = new TreeItem(tiTransName, SWT.NONE);
tiHopTitle.setText(STRING_HOPS);
tiHopTitle.setImage(guiResource.getImageHop());
// Put the steps below it.
for (int i=0;i<transMeta.nrTransHops();i++)
{
TransHopMeta hopMeta = transMeta.getTransHop(i);
TreeItem tiHop = new TreeItem(tiHopTitle, SWT.NONE);
tiHop.setText(hopMeta.toString());
tiHop.setImage(guiResource.getImageHop());
}
///////////////////////////////////////////////////////
//
// The partitions
//
TreeItem tiPartitionTitle = new TreeItem(tiTransName, SWT.NONE);
tiPartitionTitle.setText(STRING_PARTITIONS);
tiPartitionTitle.setImage(guiResource.getImageConnection());
// Put the steps below it.
for (int i=0;i<transMeta.getPartitionSchemas().size();i++)
{
PartitionSchema partitionSchema = (PartitionSchema) transMeta.getPartitionSchemas().get(i);
TreeItem tiPartition = new TreeItem(tiPartitionTitle, SWT.NONE);
tiPartition.setText(partitionSchema.getName());
tiPartition.setImage(guiResource.getImageBol());
if (partitionSchema.isShared()) tiPartition.setFont(guiResource.getFontBold());
}
///////////////////////////////////////////////////////
//
// The slaves
//
TreeItem tiSlaveTitle = new TreeItem(tiTransName, SWT.NONE);
tiSlaveTitle.setText(STRING_SLAVES);
tiSlaveTitle.setImage(guiResource.getImageBol());
// Put the steps below it.
for (int i=0;i<transMeta.getSlaveServers().size();i++)
{
SlaveServer slaveServer = (SlaveServer) transMeta.getSlaveServers().get(i);
TreeItem tiSlave = new TreeItem(tiSlaveTitle, SWT.NONE);
tiSlave.setText(slaveServer.getName());
tiSlave.setImage(guiResource.getImageBol());
if (slaveServer.isShared()) tiSlave.setFont(guiResource.getFontBold());
}
///////////////////////////////////////////////////////
//
// The clusters
//
TreeItem tiClusterTitle = new TreeItem(tiTransName, SWT.NONE);
tiClusterTitle.setText(STRING_CLUSTERS);
tiClusterTitle.setImage(guiResource.getImageBol());
// Put the steps below it.
for (int i=0;i<transMeta.getClusterSchemas().size();i++)
{
ClusterSchema clusterSchema = (ClusterSchema) transMeta.getClusterSchemas().get(i);
TreeItem tiCluster = new TreeItem(tiClusterTitle, SWT.NONE);
tiCluster.setText(clusterSchema.toString());
tiCluster.setImage(guiResource.getImageBol());
if (clusterSchema.isShared()) tiCluster.setFont(guiResource.getFontBold());
}
}
// Now add the jobs
//
for (int t=0;t<jobMetas.length;t++)
{
JobMeta jobMeta = jobMetas[t];
// Add a tree item with the name of job
//
TreeItem tiJobName = new TreeItem(tiJobs, SWT.NONE);
String name = makeJobGraphTabName(jobMeta);
if (Const.isEmpty(name)) name = STRING_JOB_NO_NAME;
tiJobName.setText(name);
tiJobName.setImage(guiResource.getImageBol());
///////////////////////////////////////////////////////
//
// Now add the database connections
//
TreeItem tiDbTitle = new TreeItem(tiJobName, SWT.NONE);
tiDbTitle.setText(STRING_CONNECTIONS);
tiDbTitle.setImage(guiResource.getImageConnection());
// Draw the connections themselves below it.
for (int i=0;i<jobMeta.nrDatabases();i++)
{
DatabaseMeta databaseMeta = jobMeta.getDatabase(i);
TreeItem tiDb = new TreeItem(tiDbTitle, SWT.NONE);
tiDb.setText(databaseMeta.getName());
if (databaseMeta.isShared()) tiDb.setFont(guiResource.getFontBold());
tiDb.setImage(guiResource.getImageConnection());
}
///////////////////////////////////////////////////////
//
// The job entries
//
TreeItem tiJobEntriesTitle = new TreeItem(tiJobName, SWT.NONE);
tiJobEntriesTitle.setText(STRING_JOB_ENTRIES);
tiJobEntriesTitle.setImage(guiResource.getImageBol());
// Put the steps below it.
for (int i=0;i<jobMeta.nrJobEntries();i++)
{
JobEntryCopy jobEntry = jobMeta.getJobEntry(i);
TreeItem tiJobEntry = Const.findTreeItem(tiJobEntriesTitle, jobEntry.getName());
if (tiJobEntry!=null) continue; // only show it once
tiJobEntry = new TreeItem(tiJobEntriesTitle, SWT.NONE);
tiJobEntry.setText(jobEntry.getName());
// if (jobEntry.isShared()) tiStep.setFont(guiResource.getFontBold()); TODO: allow job entries to be shared as well...
if (jobEntry.isStart())
{
tiJobEntry.setImage(GUIResource.getInstance().getImageStart());
}
else
if (jobEntry.isDummy())
{
tiJobEntry.setImage(GUIResource.getInstance().getImageDummy());
}
else
{
Image image = (Image)GUIResource.getInstance().getImagesJobentriesSmall().get(jobEntry.getTypeDesc());
tiJobEntry.setImage(image);
}
}
}
// Set the expanded state of the complete tree.
TreeMemory.setExpandedFromMemory(selectionTree, STRING_SPOON_MAIN_TREE);
selectionTree.setFocus();
setShellText();
}
public String getActiveTabText()
{
if (tabfolder.getSelection()==null) return null;
return tabfolder.getSelection().getText();
}
public void refreshGraph()
{
if (shell.isDisposed()) return;
String tabText = getActiveTabText();
if (tabText==null) return;
TabMapEntry tabMapEntry = (TabMapEntry) tabMap.get(tabText);
if (tabMapEntry.getObject() instanceof SpoonGraph)
{
SpoonGraph spoonGraph = (SpoonGraph) tabMapEntry.getObject();
spoonGraph.redraw();
}
if (tabMapEntry.getObject() instanceof ChefGraph)
{
ChefGraph chefGraph = (ChefGraph) tabMapEntry.getObject();
chefGraph.redraw();
}
setShellText();
}
public void refreshHistory()
{
final SpoonHistory spoonHistory = getActiveSpoonHistory();
if (spoonHistory!=null)
{
spoonHistory.markRefreshNeeded();
}
}
public StepMeta newStep(TransMeta transMeta)
{
return newStep(transMeta, true, true);
}
public StepMeta newStep(TransMeta transMeta, boolean openit, boolean rename)
{
if (transMeta==null) return null;
TreeItem ti[] = selectionTree.getSelection();
StepMeta inf = null;
if (ti.length==1)
{
String steptype = ti[0].getText();
log.logDebug(toString(), Messages.getString("Spoon.Log.NewStep")+steptype);//"New step: "
inf = newStep(transMeta, steptype, steptype, openit, rename);
}
return inf;
}
/**
* Allocate new step, optionally open and rename it.
*
* @param name Name of the new step
* @param description Description of the type of step
* @param openit Open the dialog for this step?
* @param rename Rename this step?
*
* @return The newly created StepMeta object.
*
*/
public StepMeta newStep(TransMeta transMeta, String name, String description, boolean openit, boolean rename)
{
StepMeta inf = null;
// See if we need to rename the step to avoid doubles!
if (rename && transMeta.findStep(name)!=null)
{
int i=2;
String newname = name+" "+i;
while (transMeta.findStep(newname)!=null)
{
i++;
newname = name+" "+i;
}
name=newname;
}
StepLoader steploader = StepLoader.getInstance();
StepPlugin stepPlugin = null;
try
{
stepPlugin = steploader.findStepPluginWithDescription(description);
if (stepPlugin!=null)
{
StepMetaInterface info = BaseStep.getStepInfo(stepPlugin, steploader);
info.setDefault();
if (openit)
{
StepDialogInterface dialog = info.getDialog(shell, info, transMeta, name);
name = dialog.open();
}
inf=new StepMeta(stepPlugin.getID()[0], name, info);
if (name!=null) // OK pressed in the dialog: we have a step-name
{
String newname=name;
StepMeta stepMeta = transMeta.findStep(newname);
int nr=2;
while (stepMeta!=null)
{
newname = name+" "+nr;
stepMeta = transMeta.findStep(newname);
nr++;
}
if (nr>2)
{
inf.setName(newname);
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(Messages.getString("Spoon.Dialog.ChangeStepname.Message",newname));//"This stepname already exists. Spoon changed the stepname to ["+newname+"]"
mb.setText(Messages.getString("Spoon.Dialog.ChangeStepname.Title"));//"Info!"
mb.open();
}
inf.setLocation(20, 20); // default location at (20,20)
transMeta.addStep(inf);
// Save for later:
// if openit is false: we drag&drop it onto the canvas!
if (openit)
{
addUndoNew(transMeta, new StepMeta[] { inf }, new int[] { transMeta.indexOfStep(inf) });
}
// Also store it in the pluginHistory list...
props.addPluginHistory(stepPlugin.getID()[0]);
refreshTree();
}
else
{
return null; // Cancel pressed in dialog.
}
setShellText();
}
}
catch(KettleException e)
{
String filename = stepPlugin.getErrorHelpFile();
if (stepPlugin!=null && filename!=null)
{
// OK, in stead of a normal error message, we give back the content of the error help file... (HTML)
try
{
StringBuffer content=new StringBuffer();
FileInputStream fis = new FileInputStream(new File(filename));
int ch = fis.read();
while (ch>=0)
{
content.append( (char)ch);
ch = fis.read();
}
ShowBrowserDialog sbd = new ShowBrowserDialog(shell, Messages.getString("Spoon.Dialog.ErrorHelpText.Title"), content.toString());//"Error help text"
sbd.open();
}
catch(Exception ex)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorShowingHelpText.Title"), Messages.getString("Spoon.Dialog.ErrorShowingHelpText.Message"), ex);//"Error showing help text"
}
}
else
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.UnableCreateNewStep.Title"),Messages.getString("Spoon.Dialog.UnableCreateNewStep.Message") , e);//"Error creating step" "I was unable to create a new step"
}
return null;
}
catch(Throwable e)
{
if (!shell.isDisposed()) new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorCreatingStep.Title"), Messages.getString("Spoon.Dialog.UnableCreateNewStep.Message"), new Exception(e));//"Error creating step"
return null;
}
return inf;
}
private void setTreeImages()
{
tiTrans.setImage(GUIResource.getInstance().getImageBol());
tiJobs.setImage(GUIResource.getInstance().getImageBol());
TreeItem tiBaseCat[]=tiTransBase.getItems();
for (int x=0;x<tiBaseCat.length;x++)
{
tiBaseCat[x].setImage(GUIResource.getInstance().getImageBol());
TreeItem ti[] = tiBaseCat[x].getItems();
for (int i=0;i<ti.length;i++)
{
TreeItem stepitem = ti[i];
String description = stepitem.getText();
StepLoader steploader = StepLoader.getInstance();
StepPlugin sp = steploader.findStepPluginWithDescription(description);
if (sp!=null)
{
Image stepimg = (Image)GUIResource.getInstance().getImagesStepsSmall().get(sp.getID()[0]);
if (stepimg!=null)
{
stepitem.setImage(stepimg);
}
}
}
}
}
public void setShellText()
{
if (shell.isDisposed()) return;
String fname = null;
String name = null;
long id = -1L;
ChangedFlagInterface changed = null;
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null)
{
changed = transMeta;
fname = transMeta.getFilename();
name = transMeta.getName();
id = transMeta.getID();
}
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null)
{
changed = jobMeta;
fname = jobMeta.getFilename();
name = jobMeta.getName();
id = jobMeta.getID();
}
String text = "";
if (rep!=null)
{
text+= APPL_TITLE+" - ["+getRepositoryName()+"] ";
}
else
{
text+= APPL_TITLE+" - ";
}
if (rep!=null && id>0)
{
if (Const.isEmpty(name))
{
text+=Messages.getString("Spoon.Various.NoName");//"[no name]"
}
else
{
text+=name;
}
}
else
{
if (!Const.isEmpty(fname))
{
text+=fname;
}
}
if (changed!=null && changed.hasChanged())
{
text+=" "+Messages.getString("Spoon.Various.Changed");
}
shell.setText(text);
enableMenus();
markTabsChanged();
}
public void enableMenus()
{
boolean enableTransMenu = getActiveTransformation()!=null;
boolean enableJobMenu = getActiveJob()!=null;
boolean enableRepositoryMenu = rep!=null;
// Only enable certain menu-items if we need to.
miFileSave.setEnabled(enableTransMenu || enableJobMenu);
miFileSaveAs.setEnabled(enableTransMenu || enableJobMenu);
miFileClose.setEnabled(enableTransMenu || enableJobMenu);
miFilePrint.setEnabled(enableTransMenu || enableJobMenu);
miEditUndo.setEnabled(enableTransMenu || enableJobMenu);
miEditRedo.setEnabled(enableTransMenu || enableJobMenu);
miEditUnselectAll.setEnabled(enableTransMenu);
miEditSelectAll.setEnabled(enableTransMenu);
miEditCopy.setEnabled(enableTransMenu);
miEditPaste.setEnabled(enableTransMenu);
// Transformations
miTransRun.setEnabled(enableTransMenu);
miTransPreview.setEnabled(enableTransMenu);
miTransCheck.setEnabled(enableTransMenu);
miTransImpact.setEnabled(enableTransMenu);
miTransSQL.setEnabled(enableTransMenu);
miLastImpact.setEnabled(enableTransMenu);
miLastCheck.setEnabled(enableTransMenu);
miLastPreview.setEnabled(enableTransMenu);
miTransCopy.setEnabled(enableTransMenu);
// miTransPaste.setEnabled(enableTransMenu);
miTransImage.setEnabled(enableTransMenu);
miTransDetails.setEnabled(enableTransMenu);
// Jobs
miJobRun.setEnabled(enableJobMenu);
miJobCopy.setEnabled(enableJobMenu);
miJobInfo.setEnabled(enableJobMenu);
miWizardNewConnection.setEnabled(enableTransMenu || enableJobMenu || enableRepositoryMenu);
miWizardCopyTable.setEnabled(enableTransMenu || enableJobMenu || enableRepositoryMenu);
miRepDisconnect.setEnabled(enableRepositoryMenu);
miRepExplore.setEnabled(enableRepositoryMenu);
miRepUser.setEnabled(enableRepositoryMenu);
// Do the bar as well
tiSQL.setEnabled(enableTransMenu || enableJobMenu);
tiImpact.setEnabled(enableTransMenu);
tiFileCheck.setEnabled(enableTransMenu);
tiFileReplay.setEnabled(enableTransMenu);
tiFilePreview.setEnabled(enableTransMenu);
tiFileRun.setEnabled(enableTransMenu || enableJobMenu);
tiFilePrint.setEnabled(enableTransMenu || enableJobMenu);
tiFileSaveAs.setEnabled(enableTransMenu || enableJobMenu);
tiFileSave.setEnabled(enableTransMenu || enableJobMenu);
// What steps & plugins to show?
refreshCoreObjectsTree();
}
private void markTabsChanged()
{
Collection c = tabMap.values();
for (Iterator iter = c.iterator(); iter.hasNext();)
{
TabMapEntry entry = (TabMapEntry) iter.next();
if (entry.getTabItem().isDisposed()) continue;
boolean changed = entry.getObject().hasContentChanged();
if (changed)
{
entry.getTabItem().setFont(GUIResource.getInstance().getFontBold());
}
else
{
entry.getTabItem().setFont(GUIResource.getInstance().getFontGraph());
}
}
}
private void printFile()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null)
{
printTransFile(transMeta);
}
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null)
{
printJobFile(jobMeta);
}
}
private void printTransFile(TransMeta transMeta)
{
SpoonGraph spoonGraph = getActiveSpoonGraph();
if (spoonGraph==null) return;
PrintSpool ps = new PrintSpool();
Printer printer = ps.getPrinter(shell);
// Create an image of the screen
Point max = transMeta.getMaximum();
Image img = spoonGraph.getTransformationImage(printer, max.x, max.y);
ps.printImage(shell, props, img);
img.dispose();
ps.dispose();
}
private void printJobFile(JobMeta jobMeta)
{
ChefGraph chefGraph = getActiveChefGraph();
if (chefGraph==null) return;
PrintSpool ps = new PrintSpool();
Printer printer = ps.getPrinter(shell);
// Create an image of the screen
Point max = jobMeta.getMaximum();
PaletteData pal = ps.getPaletteData();
ImageData imd = new ImageData(max.x, max.y, printer.getDepth(), pal);
Image img = new Image(printer, imd);
GC img_gc = new GC(img);
// Clear the background first, fill with background color...
img_gc.setForeground(GUIResource.getInstance().getColorBackground());
img_gc.fillRectangle(0,0,max.x, max.y);
// Draw the transformation...
chefGraph.drawJob(img_gc);
ps.printImage(shell, props, img);
img_gc.dispose();
img.dispose();
ps.dispose();
}
private SpoonGraph getActiveSpoonGraph()
{
TabMapEntry mapEntry = (TabMapEntry) tabMap.get(tabfolder.getSelection().getText());
if (mapEntry.getObject() instanceof SpoonGraph) return (SpoonGraph) mapEntry.getObject();
return null;
}
private ChefGraph getActiveChefGraph()
{
TabMapEntry mapEntry = (TabMapEntry) tabMap.get(tabfolder.getSelection().getText());
if (mapEntry.getObject() instanceof ChefGraph) return (ChefGraph) mapEntry.getObject();
return null;
}
/**
* @return the Log tab associated with the active transformation
*/
private SpoonLog getActiveSpoonLog()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta==null) return null; // nothing to work with.
return findSpoonLogOfTransformation(transMeta);
}
/**
* @return the Log tab associated with the active job
*/
private ChefLog getActiveJobLog()
{
JobMeta jobMeta = getActiveJob();
if (jobMeta==null) return null; // nothing to work with.
return findChefLogOfJob(jobMeta);
}
public SpoonGraph findSpoonGraphOfTransformation(TransMeta transMeta)
{
// Now loop over the entries in the tab-map
Collection collection = tabMap.values();
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (mapEntry.getObject() instanceof SpoonGraph)
{
SpoonGraph spoonGraph = (SpoonGraph) mapEntry.getObject();
if (spoonGraph.getTransMeta().equals(transMeta)) return spoonGraph;
}
}
return null;
}
public ChefGraph findChefGraphOfJob(JobMeta jobMeta)
{
// Now loop over the entries in the tab-map
Collection collection = tabMap.values();
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (mapEntry.getObject() instanceof ChefGraph)
{
ChefGraph chefGraph = (ChefGraph) mapEntry.getObject();
if (chefGraph.getJobMeta().equals(jobMeta)) return chefGraph;
}
}
return null;
}
public SpoonLog findSpoonLogOfTransformation(TransMeta transMeta)
{
// Now loop over the entries in the tab-map
Collection collection = tabMap.values();
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (mapEntry.getObject() instanceof SpoonLog)
{
SpoonLog spoonLog = (SpoonLog) mapEntry.getObject();
if (spoonLog.getTransMeta().equals(transMeta)) return spoonLog;
}
}
return null;
}
public ChefLog findChefLogOfJob(JobMeta jobMeta)
{
// Now loop over the entries in the tab-map
Collection collection = tabMap.values();
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (mapEntry.getObject() instanceof ChefLog)
{
ChefLog chefLog = (ChefLog) mapEntry.getObject();
if (chefLog.getJobMeta().equals(jobMeta)) return chefLog;
}
}
return null;
}
public SpoonHistory findSpoonHistoryOfTransformation(TransMeta transMeta)
{
if (transMeta==null) return null;
// Now loop over the entries in the tab-map
Collection collection = tabMap.values();
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (mapEntry.getObject() instanceof SpoonHistory)
{
SpoonHistory spoonHistory = (SpoonHistory) mapEntry.getObject();
if (spoonHistory.getTransMeta()!=null && spoonHistory.getTransMeta().equals(transMeta)) return spoonHistory;
}
}
return null;
}
public ChefHistory findChefHistoryOfJob(JobMeta jobMeta)
{
if (jobMeta==null) return null;
// Now loop over the entries in the tab-map
Collection collection = tabMap.values();
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (mapEntry.getObject() instanceof ChefHistory)
{
ChefHistory chefHistory = (ChefHistory) mapEntry.getObject();
if (chefHistory.getJobMeta()!=null && chefHistory.getJobMeta().equals(jobMeta)) return chefHistory;
}
}
return null;
}
/**
* @return the history tab associated with the active transformation
*/
private SpoonHistory getActiveSpoonHistory()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta==null) return null; // nothing to work with.
return findSpoonHistoryOfTransformation(transMeta);
}
/**
* @return The active TransMeta object by looking at the selected SpoonGraph, SpoonLog, SpoonHist
* If nothing valueable is selected, we return null
*/
public TransMeta getActiveTransformation()
{
if (tabfolder==null) return null;
CTabItem tabItem = tabfolder.getSelection();
if (tabItem==null) return null;
// What transformation is in the active tab?
// SpoonLog, SpoonGraph & SpoonHist contain the same transformation
//
TabMapEntry mapEntry = (TabMapEntry) tabMap.get(tabfolder.getSelection().getText());
TransMeta transMeta = null;
if (mapEntry.getObject() instanceof SpoonGraph) transMeta = ((SpoonGraph) mapEntry.getObject()).getTransMeta();
if (mapEntry.getObject() instanceof SpoonLog) transMeta = ((SpoonLog) mapEntry.getObject()).getTransMeta();
if (mapEntry.getObject() instanceof SpoonHistory) transMeta = ((SpoonHistory) mapEntry.getObject()).getTransMeta();
return transMeta;
}
/**
* @return The active JobMeta object by looking at the selected ChefGraph, ChefLog, ChefHist
* If nothing valueable is selected, we return null
*/
public JobMeta getActiveJob()
{
if (tabfolder==null) return null;
CTabItem tabItem = tabfolder.getSelection();
if (tabItem==null) return null;
// What job is in the active tab?
// ChefLog, ChefGraph & ChefHist contain the same job
//
TabMapEntry mapEntry = (TabMapEntry) tabMap.get(tabfolder.getSelection().getText());
JobMeta jobMeta = null;
if (mapEntry.getObject() instanceof ChefGraph) jobMeta = ((ChefGraph) mapEntry.getObject()).getJobMeta();
if (mapEntry.getObject() instanceof ChefLog) jobMeta = ((ChefLog) mapEntry.getObject()).getJobMeta();
if (mapEntry.getObject() instanceof ChefHistory) jobMeta = ((ChefHistory) mapEntry.getObject()).getJobMeta();
return jobMeta;
}
public UndoInterface getActiveUndoInterface()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null) return transMeta;
return getActiveJob();
}
public TransMeta findTransformation(String name)
{
return (TransMeta)transformationMap.get(name);
}
public JobMeta findJob(String name)
{
return (JobMeta)jobMap.get(name);
}
public TransMeta[] getLoadedTransformations()
{
List list = new ArrayList(transformationMap.values());
return (TransMeta[]) list.toArray(new TransMeta[list.size()]);
}
public JobMeta[] getLoadedJobs()
{
List list = new ArrayList(jobMap.values());
return (JobMeta[]) list.toArray(new JobMeta[list.size()]);
}
private boolean editTransformationProperties(TransMeta transMeta)
{
if (transMeta==null) return false;
TransDialog tid = new TransDialog(shell, SWT.NONE, transMeta, rep);
TransMeta ti = tid.open();
// In this case, load shared objects
//
if (tid.isSharedObjectsFileChanged())
{
loadTransSharedObjects(transMeta);
}
if (tid.isSharedObjectsFileChanged() || ti!=null)
{
try
{
transMeta.readSharedObjects(rep);
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", makeGraphTabName(transMeta)), e);
}
refreshTree();
renameTabs(); // cheap operation, might as will do it anyway
}
setShellText();
return ti!=null;
}
public void saveSettings()
{
WindowProperty winprop = new WindowProperty(shell);
winprop.setName(APPL_TITLE);
props.setScreen(winprop);
props.setLogLevel(log.getLogLevelDesc());
props.setLogFilter(log.getFilter());
props.setSashWeights(sashform.getWeights());
props.saveProps();
}
public void loadSettings()
{
log.setLogLevel(props.getLogLevel());
log.setFilter(props.getLogFilter());
// transMeta.setMaxUndo(props.getMaxUndo());
DBCache.getInstance().setActive(props.useDBCache());
}
public void changeLooks()
{
props.setLook(selectionTree);
props.setLook(tabfolder, Props.WIDGET_STYLE_TAB);
GUIResource.getInstance().reload();
refreshTree();
refreshGraph();
}
public void undoAction(UndoInterface undoInterface)
{
if (undoInterface==null) return;
TransAction ta = undoInterface.previousUndo();
if (ta==null) return;
setUndoMenu(undoInterface); // something changed: change the menu
if (undoInterface instanceof TransMeta) undoTransformationAction((TransMeta)undoInterface, ta);
if (undoInterface instanceof JobMeta) undoJobAction((JobMeta)undoInterface, ta);
// Put what we undo in focus
if (undoInterface instanceof TransMeta)
{
SpoonGraph spoonGraph = findSpoonGraphOfTransformation((TransMeta)undoInterface);
spoonGraph.forceFocus();
}
if (undoInterface instanceof JobMeta)
{
ChefGraph chefGraph = findChefGraphOfJob((JobMeta)undoInterface);
chefGraph.forceFocus();
}
}
private void undoTransformationAction(TransMeta transMeta, TransAction transAction)
{
switch(transAction.getType())
{
//
// NEW
//
// We created a new step : undo this...
case TransAction.TYPE_ACTION_NEW_STEP:
// Delete the step at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeStep(idx);
}
refreshTree();
refreshGraph();
break;
// We created a new connection : undo this...
case TransAction.TYPE_ACTION_NEW_CONNECTION:
// Delete the connection at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeDatabase(idx);
}
refreshTree();
refreshGraph();
break;
// We created a new note : undo this...
case TransAction.TYPE_ACTION_NEW_NOTE:
// Delete the note at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeNote(idx);
}
refreshTree();
refreshGraph();
break;
// We created a new hop : undo this...
case TransAction.TYPE_ACTION_NEW_HOP:
// Delete the hop at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeTransHop(idx);
}
refreshTree();
refreshGraph();
break;
// We created a new slave : undo this...
case TransAction.TYPE_ACTION_NEW_SLAVE:
// Delete the slave at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.getSlaveServers().remove(idx);
}
refreshTree();
refreshGraph();
break;
// We created a new slave : undo this...
case TransAction.TYPE_ACTION_NEW_CLUSTER:
// Delete the slave at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.getClusterSchemas().remove(idx);
}
refreshTree();
refreshGraph();
break;
//
// DELETE
//
// We delete a step : undo this...
case TransAction.TYPE_ACTION_DELETE_STEP:
// un-Delete the step at correct location: re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
StepMeta stepMeta = (StepMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addStep(idx, stepMeta);
}
refreshTree();
refreshGraph();
break;
// We deleted a connection : undo this...
case TransAction.TYPE_ACTION_DELETE_CONNECTION:
// re-insert the connection at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
DatabaseMeta ci = (DatabaseMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addDatabase(idx, ci);
}
refreshTree();
refreshGraph();
break;
// We delete new note : undo this...
case TransAction.TYPE_ACTION_DELETE_NOTE:
// re-insert the note at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
NotePadMeta ni = (NotePadMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addNote(idx, ni);
}
refreshTree();
refreshGraph();
break;
// We deleted a hop : undo this...
case TransAction.TYPE_ACTION_DELETE_HOP:
// re-insert the hop at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
TransHopMeta hi = (TransHopMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
// Build a new hop:
StepMeta from = transMeta.findStep(hi.getFromStep().getName());
StepMeta to = transMeta.findStep(hi.getToStep().getName());
TransHopMeta hinew = new TransHopMeta(from, to);
transMeta.addTransHop(idx, hinew);
}
refreshTree();
refreshGraph();
break;
//
// CHANGE
//
// We changed a step : undo this...
case TransAction.TYPE_ACTION_CHANGE_STEP:
// Delete the current step, insert previous version.
for (int i=0;i<transAction.getCurrent().length;i++)
{
StepMeta prev = (StepMeta) ((StepMeta)transAction.getPrevious()[i]).clone();
int idx = transAction.getCurrentIndex()[i];
transMeta.getStep(idx).replaceMeta(prev);
}
refreshTree();
refreshGraph();
break;
// We changed a connection : undo this...
case TransAction.TYPE_ACTION_CHANGE_CONNECTION:
// Delete & re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
DatabaseMeta prev = (DatabaseMeta)transAction.getPrevious()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.getDatabase(idx).replaceMeta((DatabaseMeta) prev.clone());
}
refreshTree();
refreshGraph();
break;
// We changed a note : undo this...
case TransAction.TYPE_ACTION_CHANGE_NOTE:
// Delete & re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeNote(idx);
NotePadMeta prev = (NotePadMeta)transAction.getPrevious()[i];
transMeta.addNote(idx, (NotePadMeta) prev.clone());
}
refreshTree();
refreshGraph();
break;
// We changed a hop : undo this...
case TransAction.TYPE_ACTION_CHANGE_HOP:
// Delete & re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
TransHopMeta prev = (TransHopMeta)transAction.getPrevious()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.removeTransHop(idx);
transMeta.addTransHop(idx, (TransHopMeta) prev.clone());
}
refreshTree();
refreshGraph();
break;
//
// POSITION
//
// The position of a step has changed: undo this...
case TransAction.TYPE_ACTION_POSITION_STEP:
// Find the location of the step:
for (int i = 0; i < transAction.getCurrentIndex().length; i++)
{
StepMeta stepMeta = transMeta.getStep(transAction.getCurrentIndex()[i]);
stepMeta.setLocation(transAction.getPreviousLocation()[i]);
}
refreshGraph();
break;
// The position of a note has changed: undo this...
case TransAction.TYPE_ACTION_POSITION_NOTE:
for (int i=0;i<transAction.getCurrentIndex().length;i++)
{
int idx = transAction.getCurrentIndex()[i];
NotePadMeta npi = transMeta.getNote(idx);
Point prev = transAction.getPreviousLocation()[i];
npi.setLocation(prev);
}
refreshGraph();
break;
default: break;
}
// OK, now check if we need to do this again...
if (transMeta.viewNextUndo()!=null)
{
if (transMeta.viewNextUndo().getNextAlso()) undoAction(transMeta);
}
}
private void undoJobAction(JobMeta jobMeta, TransAction transAction)
{
switch(transAction.getType())
{
//
// NEW
//
// We created a new entry : undo this...
case TransAction.TYPE_ACTION_NEW_JOB_ENTRY:
// Delete the entry at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i=idx.length-1;i>=0;i--) jobMeta.removeJobEntry(idx[i]);
refreshTree();
refreshGraph();
}
break;
// We created a new note : undo this...
case TransAction.TYPE_ACTION_NEW_NOTE:
// Delete the note at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i=idx.length-1;i>=0;i--) jobMeta.removeNote(idx[i]);
refreshTree();
refreshGraph();
}
break;
// We created a new hop : undo this...
case TransAction.TYPE_ACTION_NEW_JOB_HOP:
// Delete the hop at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i=idx.length-1;i>=0;i--) jobMeta.removeJobHop(idx[i]);
refreshTree();
refreshGraph();
}
break;
//
// DELETE
//
// We delete an entry : undo this...
case TransAction.TYPE_ACTION_DELETE_STEP:
// un-Delete the entry at correct location: re-insert
{
JobEntryCopy ce[] = (JobEntryCopy[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<ce.length;i++) jobMeta.addJobEntry(idx[i], ce[i]);
refreshTree();
refreshGraph();
}
break;
// We delete new note : undo this...
case TransAction.TYPE_ACTION_DELETE_NOTE:
// re-insert the note at correct location:
{
NotePadMeta ni[] = (NotePadMeta[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++) jobMeta.addNote(idx[i], ni[i]);
refreshTree();
refreshGraph();
}
break;
// We deleted a new hop : undo this...
case TransAction.TYPE_ACTION_DELETE_JOB_HOP:
// re-insert the hop at correct location:
{
JobHopMeta hi[] = (JobHopMeta[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<hi.length;i++)
{
jobMeta.addJobHop(idx[i], hi[i]);
}
refreshTree();
refreshGraph();
}
break;
//
// CHANGE
//
// We changed a job entry: undo this...
case TransAction.TYPE_ACTION_CHANGE_JOB_ENTRY:
// Delete the current job entry, insert previous version.
{
for (int i=0;i<transAction.getPrevious().length;i++)
{
JobEntryCopy copy = (JobEntryCopy) ((JobEntryCopy)transAction.getPrevious()[i]).clone();
jobMeta.getJobEntry(transAction.getCurrentIndex()[i]).replaceMeta(copy);
}
refreshTree();
refreshGraph();
}
break;
// We changed a note : undo this...
case TransAction.TYPE_ACTION_CHANGE_NOTE:
// Delete & re-insert
{
NotePadMeta prev[] = (NotePadMeta[])transAction.getPrevious();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++)
{
jobMeta.removeNote(idx[i]);
jobMeta.addNote(idx[i], prev[i]);
}
refreshTree();
refreshGraph();
}
break;
// We changed a hop : undo this...
case TransAction.TYPE_ACTION_CHANGE_JOB_HOP:
// Delete & re-insert
{
JobHopMeta prev[] = (JobHopMeta[])transAction.getPrevious();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++)
{
jobMeta.removeJobHop(idx[i]);
jobMeta.addJobHop(idx[i], prev[i]);
}
refreshTree();
refreshGraph();
}
break;
//
// POSITION
//
// The position of a step has changed: undo this...
case TransAction.TYPE_ACTION_POSITION_JOB_ENTRY:
// Find the location of the step:
{
int idx[] = transAction.getCurrentIndex();
Point p[] = transAction.getPreviousLocation();
for (int i = 0; i < p.length; i++)
{
JobEntryCopy entry = jobMeta.getJobEntry(idx[i]);
entry.setLocation(p[i]);
}
refreshGraph();
}
break;
// The position of a note has changed: undo this...
case TransAction.TYPE_ACTION_POSITION_NOTE:
int idx[] = transAction.getCurrentIndex();
Point prev[] = transAction.getPreviousLocation();
for (int i=0;i<idx.length;i++)
{
NotePadMeta npi = jobMeta.getNote(idx[i]);
npi.setLocation(prev[i]);
}
refreshGraph();
break;
default: break;
}
}
public void redoAction(UndoInterface undoInterface)
{
if (undoInterface==null) return;
TransAction ta = undoInterface.nextUndo();
if (ta==null) return;
setUndoMenu(undoInterface); // something changed: change the menu
if (undoInterface instanceof TransMeta) redoTransformationAction((TransMeta)undoInterface, ta);
if (undoInterface instanceof JobMeta) redoJobAction((JobMeta)undoInterface, ta);
// Put what we redo in focus
if (undoInterface instanceof TransMeta)
{
SpoonGraph spoonGraph = findSpoonGraphOfTransformation((TransMeta)undoInterface);
spoonGraph.forceFocus();
}
if (undoInterface instanceof JobMeta)
{
ChefGraph chefGraph = findChefGraphOfJob((JobMeta)undoInterface);
chefGraph.forceFocus();
}
}
private void redoTransformationAction(TransMeta transMeta, TransAction transAction)
{
switch(transAction.getType())
{
//
// NEW
//
case TransAction.TYPE_ACTION_NEW_STEP:
// re-delete the step at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
StepMeta stepMeta = (StepMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addStep(idx, stepMeta);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_NEW_CONNECTION:
// re-insert the connection at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
DatabaseMeta ci = (DatabaseMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addDatabase(idx, ci);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_NEW_NOTE:
// re-insert the note at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
NotePadMeta ni = (NotePadMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addNote(idx, ni);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_NEW_HOP:
// re-insert the hop at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
TransHopMeta hi = (TransHopMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addTransHop(idx, hi);
refreshTree();
refreshGraph();
}
break;
//
// DELETE
//
case TransAction.TYPE_ACTION_DELETE_STEP:
// re-remove the step at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeStep(idx);
}
refreshTree();
refreshGraph();
break;
case TransAction.TYPE_ACTION_DELETE_CONNECTION:
// re-remove the connection at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeDatabase(idx);
}
refreshTree();
refreshGraph();
break;
case TransAction.TYPE_ACTION_DELETE_NOTE:
// re-remove the note at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeNote(idx);
}
refreshTree();
refreshGraph();
break;
case TransAction.TYPE_ACTION_DELETE_HOP:
// re-remove the hop at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeTransHop(idx);
}
refreshTree();
refreshGraph();
break;
//
// CHANGE
//
// We changed a step : undo this...
case TransAction.TYPE_ACTION_CHANGE_STEP:
// Delete the current step, insert previous version.
for (int i=0;i<transAction.getCurrent().length;i++)
{
StepMeta stepMeta = (StepMeta) ((StepMeta)transAction.getCurrent()[i]).clone();
transMeta.getStep(transAction.getCurrentIndex()[i]).replaceMeta(stepMeta);
}
refreshTree();
refreshGraph();
break;
// We changed a connection : undo this...
case TransAction.TYPE_ACTION_CHANGE_CONNECTION:
// Delete & re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
DatabaseMeta databaseMeta = (DatabaseMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.getDatabase(idx).replaceMeta((DatabaseMeta) databaseMeta.clone());
}
refreshTree();
refreshGraph();
break;
// We changed a note : undo this...
case TransAction.TYPE_ACTION_CHANGE_NOTE:
// Delete & re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
NotePadMeta ni = (NotePadMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.removeNote(idx);
transMeta.addNote(idx, (NotePadMeta) ni.clone());
}
refreshTree();
refreshGraph();
break;
// We changed a hop : undo this...
case TransAction.TYPE_ACTION_CHANGE_HOP:
// Delete & re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
TransHopMeta hi = (TransHopMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.removeTransHop(idx);
transMeta.addTransHop(idx, (TransHopMeta) hi.clone());
}
refreshTree();
refreshGraph();
break;
//
// CHANGE POSITION
//
case TransAction.TYPE_ACTION_POSITION_STEP:
for (int i=0;i<transAction.getCurrentIndex().length;i++)
{
// Find & change the location of the step:
StepMeta stepMeta = transMeta.getStep(transAction.getCurrentIndex()[i]);
stepMeta.setLocation(transAction.getCurrentLocation()[i]);
}
refreshGraph();
break;
case TransAction.TYPE_ACTION_POSITION_NOTE:
for (int i=0;i<transAction.getCurrentIndex().length;i++)
{
int idx = transAction.getCurrentIndex()[i];
NotePadMeta npi = transMeta.getNote(idx);
Point curr = transAction.getCurrentLocation()[i];
npi.setLocation(curr);
}
refreshGraph();
break;
default: break;
}
// OK, now check if we need to do this again...
if (transMeta.viewNextUndo()!=null)
{
if (transMeta.viewNextUndo().getNextAlso()) redoAction(transMeta);
}
}
private void redoJobAction(JobMeta jobMeta, TransAction transAction)
{
switch(transAction.getType())
{
//
// NEW
//
case TransAction.TYPE_ACTION_NEW_JOB_ENTRY:
// re-delete the entry at correct location:
{
JobEntryCopy si[] = (JobEntryCopy[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++) jobMeta.addJobEntry(idx[i], si[i]);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_NEW_NOTE:
// re-insert the note at correct location:
{
NotePadMeta ni[] = (NotePadMeta[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++) jobMeta.addNote(idx[i], ni[i]);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_NEW_JOB_HOP:
// re-insert the hop at correct location:
{
JobHopMeta hi[] = (JobHopMeta[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++) jobMeta.addJobHop(idx[i], hi[i]);
refreshTree();
refreshGraph();
}
break;
//
// DELETE
//
case TransAction.TYPE_ACTION_DELETE_JOB_ENTRY:
// re-remove the entry at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i=idx.length-1;i>=0;i--) jobMeta.removeJobEntry(idx[i]);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_DELETE_NOTE:
// re-remove the note at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i=idx.length-1;i>=0;i--) jobMeta.removeNote(idx[i]);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_DELETE_JOB_HOP:
// re-remove the hop at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i=idx.length-1;i>=0;i--) jobMeta.removeJobHop(idx[i]);
refreshTree();
refreshGraph();
}
break;
//
// CHANGE
//
// We changed a step : undo this...
case TransAction.TYPE_ACTION_CHANGE_JOB_ENTRY:
// replace with "current" version.
{
for (int i=0;i<transAction.getCurrent().length;i++)
{
JobEntryCopy copy = (JobEntryCopy) ((JobEntryCopy)(transAction.getCurrent()[i])).clone_deep();
jobMeta.getJobEntry(transAction.getCurrentIndex()[i]).replaceMeta(copy);
}
refreshTree();
refreshGraph();
}
break;
// We changed a note : undo this...
case TransAction.TYPE_ACTION_CHANGE_NOTE:
// Delete & re-insert
{
NotePadMeta ni[] = (NotePadMeta[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++)
{
jobMeta.removeNote(idx[i]);
jobMeta.addNote(idx[i], ni[i]);
}
refreshTree();
refreshGraph();
}
break;
// We changed a hop : undo this...
case TransAction.TYPE_ACTION_CHANGE_JOB_HOP:
// Delete & re-insert
{
JobHopMeta hi[] = (JobHopMeta[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++)
{
jobMeta.removeJobHop(idx[i]);
jobMeta.addJobHop(idx[i], hi[i]);
}
refreshTree();
refreshGraph();
}
break;
//
// CHANGE POSITION
//
case TransAction.TYPE_ACTION_POSITION_JOB_ENTRY:
{
// Find the location of the step:
int idx[] = transAction.getCurrentIndex();
Point p[] = transAction.getCurrentLocation();
for (int i = 0; i < p.length; i++)
{
JobEntryCopy entry = jobMeta.getJobEntry(idx[i]);
entry.setLocation(p[i]);
}
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_POSITION_NOTE:
{
int idx[] = transAction.getCurrentIndex();
Point curr[] = transAction.getCurrentLocation();
for (int i=0;i<idx.length;i++)
{
NotePadMeta npi = jobMeta.getNote(idx[i]);
npi.setLocation(curr[i]);
}
refreshGraph();
}
break;
default: break;
}
}
public void setUndoMenu(UndoInterface undoInterface)
{
if (shell.isDisposed()) return;
TransAction prev = undoInterface!=null ? undoInterface.viewThisUndo() : null;
TransAction next = undoInterface!=null ? undoInterface.viewNextUndo() : null;
if (prev!=null)
{
miEditUndo.setEnabled(true);
miEditUndo.setText(Messages.getString("Spoon.Menu.Undo.Available", prev.toString()));//"Undo : "+prev.toString()+" \tCTRL-Z"
}
else
{
miEditUndo.setEnabled(false);
miEditUndo.setText(Messages.getString("Spoon.Menu.Undo.NotAvailable"));//"Undo : not available \tCTRL-Z"
}
if (next!=null)
{
miEditRedo.setEnabled(true);
miEditRedo.setText(Messages.getString("Spoon.Menu.Redo.Available",next.toString()));//"Redo : "+next.toString()+" \tCTRL-Y"
}
else
{
miEditRedo.setEnabled(false);
miEditRedo.setText(Messages.getString("Spoon.Menu.Redo.NotAvailable"));//"Redo : not available \tCTRL-Y"
}
}
public void addUndoNew(UndoInterface undoInterface, Object obj[], int position[])
{
addUndoNew(undoInterface, obj, position, false);
}
public void addUndoNew(UndoInterface undoInterface, Object obj[], int position[], boolean nextAlso)
{
undoInterface.addUndo(obj, null, position, null, null, TransMeta.TYPE_UNDO_NEW, nextAlso);
setUndoMenu(undoInterface);
}
// Undo delete object
public void addUndoDelete(UndoInterface undoInterface, Object obj[], int position[])
{
addUndoDelete(undoInterface, obj, position, false);
}
// Undo delete object
public void addUndoDelete(UndoInterface undoInterface, Object obj[], int position[], boolean nextAlso)
{
undoInterface.addUndo(obj, null, position, null, null, TransMeta.TYPE_UNDO_DELETE, nextAlso);
setUndoMenu(undoInterface);
}
// Change of step, connection, hop or note...
public void addUndoPosition(UndoInterface undoInterface, Object obj[], int pos[], Point prev[], Point curr[])
{
// It's better to store the indexes of the objects, not the objects itself!
undoInterface.addUndo(obj, null, pos, prev, curr, JobMeta.TYPE_UNDO_POSITION, false);
setUndoMenu(undoInterface);
}
// Change of step, connection, hop or note...
public void addUndoChange(UndoInterface undoInterface, Object from[], Object to[], int[] pos)
{
addUndoChange(undoInterface, from, to, pos, false);
}
// Change of step, connection, hop or note...
public void addUndoChange(UndoInterface undoInterface, Object from[], Object to[], int[] pos, boolean nextAlso)
{
undoInterface.addUndo(from, to, pos, null, null, JobMeta.TYPE_UNDO_CHANGE, nextAlso);
setUndoMenu(undoInterface);
}
/**
* Checks *all* the steps in the transformation, puts the result in remarks list
*/
public void checkTrans(TransMeta transMeta)
{
checkTrans(transMeta, false);
}
/**
* Check the steps in a transformation
*
* @param only_selected True: Check only the selected steps...
*/
public void checkTrans(TransMeta transMeta, boolean only_selected)
{
if (transMeta==null) return;
SpoonGraph spoonGraph = findSpoonGraphOfTransformation(transMeta);
if (spoonGraph==null) return;
CheckTransProgressDialog ctpd = new CheckTransProgressDialog(shell, transMeta, spoonGraph.getRemarks(), only_selected);
ctpd.open(); // manages the remarks arraylist...
showLastTransCheck();
}
/**
* Show the remarks of the last transformation check that was run.
* @see #checkTrans()
*/
public void showLastTransCheck()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta==null) return;
SpoonGraph spoonGraph = findSpoonGraphOfTransformation(transMeta);
if (spoonGraph==null) return;
CheckResultDialog crd = new CheckResultDialog(shell, SWT.NONE, spoonGraph.getRemarks());
String stepname = crd.open();
if (stepname!=null)
{
// Go to the indicated step!
StepMeta stepMeta = transMeta.findStep(stepname);
if (stepMeta!=null)
{
editStep(transMeta, stepMeta);
}
}
}
public void clearDBCache()
{
clearDBCache(null);
}
public void clearDBCache(DatabaseMeta databaseMeta)
{
if (databaseMeta!=null)
{
DBCache.getInstance().clear(databaseMeta.getName());
}
else
{
DBCache.getInstance().clear(null);
}
}
public void exploreDB(HasDatabasesInterface hasDatabasesInterface, DatabaseMeta databaseMeta)
{
DatabaseExplorerDialog std = new DatabaseExplorerDialog(shell, SWT.NONE, databaseMeta, hasDatabasesInterface.getDatabases(), true );
std.open();
}
public void analyseImpact(TransMeta transMeta)
{
if (transMeta==null) return;
SpoonGraph spoonGraph = findSpoonGraphOfTransformation(transMeta);
if (spoonGraph==null) return;
AnalyseImpactProgressDialog aipd = new AnalyseImpactProgressDialog(shell, transMeta, spoonGraph.getImpact());
spoonGraph.setImpactFinished( aipd.open() );
if (spoonGraph.isImpactFinished()) showLastImpactAnalyses(transMeta);
}
public void showLastImpactAnalyses(TransMeta transMeta)
{
if (transMeta==null) return;
SpoonGraph spoonGraph = findSpoonGraphOfTransformation(transMeta);
if (spoonGraph==null) return;
ArrayList rows = new ArrayList();
for (int i=0;i<spoonGraph.getImpact().size();i++)
{
DatabaseImpact ii = (DatabaseImpact)spoonGraph.getImpact().get(i);
rows.add(ii.getRow());
}
if (rows.size()>0)
{
// Display all the rows...
PreviewRowsDialog prd = new PreviewRowsDialog(shell, SWT.NONE, "-", rows);
prd.setTitleMessage(Messages.getString("Spoon.Dialog.ImpactAnalyses.Title"), Messages.getString("Spoon.Dialog.ImpactAnalyses.Message"));//"Impact analyses" "Result of analyses:"
prd.open();
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION );
if (spoonGraph.isImpactFinished())
{
mb.setMessage(Messages.getString("Spoon.Dialog.TransformationNoImpactOnDatabase.Message"));//"As far as I can tell, this transformation has no impact on any database."
}
else
{
mb.setMessage(Messages.getString("Spoon.Dialog.RunImpactAnalysesFirst.Message"));//"Please run the impact analyses first on this transformation."
}
mb.setText(Messages.getString("Spoon.Dialog.ImpactAnalyses.Title"));//Impact
mb.open();
}
}
public void getSQL()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null) getTransSQL(transMeta);
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null) getJobSQL(jobMeta);
}
/**
* Get & show the SQL required to run the loaded transformation...
*
*/
public void getTransSQL(TransMeta transMeta)
{
GetSQLProgressDialog pspd = new GetSQLProgressDialog(shell, transMeta);
ArrayList stats = pspd.open();
if (stats!=null) // null means error, but we already displayed the error
{
if (stats.size()>0)
{
SQLStatementsDialog ssd = new SQLStatementsDialog(shell, SWT.NONE, stats);
ssd.open();
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION );
mb.setMessage(Messages.getString("Spoon.Dialog.NoSQLNeedEexecuted.Message"));//As far as I can tell, no SQL statements need to be executed before this transformation can run.
mb.setText(Messages.getString("Spoon.Dialog.NoSQLNeedEexecuted.Title"));//"SQL"
mb.open();
}
}
}
/**
* Get & show the SQL required to run the loaded job entry...
*
*/
public void getJobSQL(JobMeta jobMeta)
{
GetJobSQLProgressDialog pspd = new GetJobSQLProgressDialog(shell, jobMeta, rep);
ArrayList stats = pspd.open();
if (stats!=null) // null means error, but we already displayed the error
{
if (stats.size()>0)
{
SQLStatementsDialog ssd = new SQLStatementsDialog(shell, SWT.NONE, stats);
ssd.open();
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION );
mb.setMessage(Messages.getString("Spoon.Dialog.JobNoSQLNeedEexecuted.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.JobNoSQLNeedEexecuted.Title")); //$NON-NLS-1$
mb.open();
}
}
}
public void toClipboard(String cliptext)
{
GUIResource.getInstance().toClipboard(cliptext);
}
public String fromClipboard()
{
return GUIResource.getInstance().fromClipboard();
}
/**
* Paste transformation from the clipboard...
*
*/
public void pasteTransformation()
{
log.logDetailed(toString(), Messages.getString("Spoon.Log.PasteTransformationFromClipboard"));//"Paste transformation from the clipboard!"
String xml = fromClipboard();
try
{
Document doc = XMLHandler.loadXMLString(xml);
TransMeta transMeta = new TransMeta(XMLHandler.getSubNode(doc, TransMeta.XML_TAG));
addSpoonGraph(transMeta); // create a new tab
refreshGraph();
refreshTree();
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorPastingTransformation.Title"), Messages.getString("Spoon.Dialog.ErrorPastingTransformation.Message"), e);//Error pasting transformation "An error occurred pasting a transformation from the clipboard"
}
}
/**
* Paste job from the clipboard...
*
*/
public void pasteJob()
{
String xml = fromClipboard();
try
{
Document doc = XMLHandler.loadXMLString(xml);
JobMeta jobMeta = new JobMeta(log, XMLHandler.getSubNode(doc, JobMeta.XML_TAG), rep);
addChefGraph(jobMeta); // create a new tab
refreshGraph();
refreshTree();
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorPastingJob.Title"), Messages.getString("Spoon.Dialog.ErrorPastingJob.Message"), e);//Error pasting transformation "An error occurred pasting a transformation from the clipboard"
}
}
public void copyTransformation(TransMeta transMeta)
{
if (transMeta==null) return;
toClipboard(XMLHandler.getXMLHeader() + transMeta.getXML());
}
public void copyJob(JobMeta jobMeta)
{
if (jobMeta==null) return;
toClipboard(XMLHandler.getXMLHeader() + jobMeta.getXML());
}
public void copyTransformationImage(TransMeta transMeta)
{
SpoonGraph spoonGraph = findSpoonGraphOfTransformation(transMeta);
if (spoonGraph==null) return;
Clipboard clipboard = GUIResource.getInstance().getNewClipboard();
Point area = transMeta.getMaximum();
Image image = spoonGraph.getTransformationImage(Display.getCurrent(), area.x, area.y);
clipboard.setContents(new Object[] { image.getImageData() }, new Transfer[]{ImageDataTransfer.getInstance()});
}
/**
* Shows a wizard that creates a new database connection...
*
*/
private void createDatabaseWizard(HasDatabasesInterface hasDatabasesInterface)
{
CreateDatabaseWizard cdw=new CreateDatabaseWizard();
DatabaseMeta newDBInfo=cdw.createAndRunDatabaseWizard(shell, props, hasDatabasesInterface.getDatabases());
if(newDBInfo!=null){ //finished
hasDatabasesInterface.addDatabase(newDBInfo);
refreshTree();
refreshGraph();
}
}
public ArrayList getActiveDatabases()
{
Map map = new Hashtable();
HasDatabasesInterface transMeta = getActiveTransformation();
if (transMeta!=null)
{
for (int i=0;i<transMeta.nrDatabases();i++)
{
map.put(transMeta.getDatabase(i).getName(), transMeta.getDatabase(i));
}
}
HasDatabasesInterface jobMeta = getActiveJob();
if (jobMeta!=null)
{
for (int i=0;i<jobMeta.nrDatabases();i++)
{
map.put(jobMeta.getDatabase(i).getName(), jobMeta.getDatabase(i));
}
}
if (rep!=null)
{
try
{
List repDBs = rep.getDatabases();
for (int i=0;i<repDBs.size();i++)
{
DatabaseMeta databaseMeta = (DatabaseMeta) repDBs.get(i);
map.put(databaseMeta.getName(), databaseMeta);
}
}
catch(Exception e)
{
log.logError(toString(), "Unexpected error reading databases from the repository: "+e.toString());
log.logError(toString(), Const.getStackTracker(e));
}
}
ArrayList databases = new ArrayList();
databases.addAll( map.values() );
return databases;
}
/**
* Create a transformation that extracts tables & data from a database.<p><p>
*
* 0) Select the database to rip<p>
* 1) Select the table in the database to copy<p>
* 2) Select the database to dump to<p>
* 3) Select the repository directory in which it will end up<p>
* 4) Select a name for the new transformation<p>
* 6) Create 1 transformation for the selected table<p>
*/
private void copyTableWizard()
{
ArrayList databases = getActiveDatabases();
if (databases.size()==0) return; // Nothing to do here
final CopyTableWizardPage1 page1 = new CopyTableWizardPage1("1", databases);
page1.createControl(shell);
final CopyTableWizardPage2 page2 = new CopyTableWizardPage2("2");
page2.createControl(shell);
Wizard wizard = new Wizard()
{
public boolean performFinish()
{
return copyTable(page1.getSourceDatabase(), page1.getTargetDatabase(), page2.getSelection());
}
/**
* @see org.eclipse.jface.wizard.Wizard#canFinish()
*/
public boolean canFinish()
{
return page2.canFinish();
}
};
wizard.addPage(page1);
wizard.addPage(page2);
WizardDialog wd = new WizardDialog(shell, wizard);
wd.setMinimumPageSize(700,400);
wd.open();
}
public boolean copyTable(DatabaseMeta sourceDBInfo, DatabaseMeta targetDBInfo, String tablename )
{
try
{
//
// Create a new transformation...
//
TransMeta meta = new TransMeta();
meta.addDatabase(sourceDBInfo);
meta.addDatabase(targetDBInfo);
//
// Add a note
//
String note = Messages.getString("Spoon.Message.Note.ReadInformationFromTableOnDB",tablename,sourceDBInfo.getDatabaseName() )+Const.CR;//"Reads information from table ["+tablename+"] on database ["+sourceDBInfo+"]"
note+=Messages.getString("Spoon.Message.Note.WriteInformationToTableOnDB",tablename,targetDBInfo.getDatabaseName() );//"After that, it writes the information to table ["+tablename+"] on database ["+targetDBInfo+"]"
NotePadMeta ni = new NotePadMeta(note, 150, 10, -1, -1);
meta.addNote(ni);
//
// create the source step...
//
String fromstepname = Messages.getString("Spoon.Message.Note.ReadFromTable",tablename); //"read from ["+tablename+"]";
TableInputMeta tii = new TableInputMeta();
tii.setDatabaseMeta(sourceDBInfo);
tii.setSQL("SELECT * FROM "+tablename);
StepLoader steploader = StepLoader.getInstance();
String fromstepid = steploader.getStepPluginID(tii);
StepMeta fromstep = new StepMeta(fromstepid, fromstepname, (StepMetaInterface)tii );
fromstep.setLocation(150,100);
fromstep.setDraw(true);
fromstep.setDescription(Messages.getString("Spoon.Message.Note.ReadInformationFromTableOnDB",tablename,sourceDBInfo.getDatabaseName() ));
meta.addStep(fromstep);
//
// add logic to rename fields in case any of the field names contain reserved words...
// Use metadata logic in SelectValues, use SelectValueInfo...
//
Database sourceDB = new Database(sourceDBInfo);
sourceDB.connect();
// Get the fields for the input table...
Row fields = sourceDB.getTableFields(tablename);
// See if we need to deal with reserved words...
int nrReserved = targetDBInfo.getNrReservedWords(fields);
if (nrReserved>0)
{
SelectValuesMeta svi = new SelectValuesMeta();
svi.allocate(0,0,nrReserved);
int nr = 0;
for (int i=0;i<fields.size();i++)
{
Value v = fields.getValue(i);
if (targetDBInfo.isReservedWord( v.getName() ) )
{
svi.getMetaName()[nr] = v.getName();
svi.getMetaRename()[nr] = targetDBInfo.quoteField( v.getName() );
nr++;
}
}
String selstepname =Messages.getString("Spoon.Message.Note.HandleReservedWords"); //"Handle reserved words";
String selstepid = steploader.getStepPluginID(svi);
StepMeta selstep = new StepMeta(selstepid, selstepname, (StepMetaInterface)svi );
selstep.setLocation(350,100);
selstep.setDraw(true);
selstep.setDescription(Messages.getString("Spoon.Message.Note.RenamesReservedWords",targetDBInfo.getDatabaseTypeDesc()) );//"Renames reserved words for "+targetDBInfo.getDatabaseTypeDesc()
meta.addStep(selstep);
TransHopMeta shi = new TransHopMeta(fromstep, selstep);
meta.addTransHop(shi);
fromstep = selstep;
}
//
// Create the target step...
//
//
// Add the TableOutputMeta step...
//
String tostepname = Messages.getString("Spoon.Message.Note.WriteToTable",tablename); // "write to ["+tablename+"]";
TableOutputMeta toi = new TableOutputMeta();
toi.setDatabaseMeta( targetDBInfo );
toi.setTablename( tablename );
toi.setCommitSize( 200 );
toi.setTruncateTable( true );
String tostepid = steploader.getStepPluginID(toi);
StepMeta tostep = new StepMeta(tostepid, tostepname, (StepMetaInterface)toi );
tostep.setLocation(550,100);
tostep.setDraw(true);
tostep.setDescription(Messages.getString("Spoon.Message.Note.WriteInformationToTableOnDB2",tablename,targetDBInfo.getDatabaseName() ));//"Write information to table ["+tablename+"] on database ["+targetDBInfo+"]"
meta.addStep(tostep);
//
// Add a hop between the two steps...
//
TransHopMeta hi = new TransHopMeta(fromstep, tostep);
meta.addTransHop(hi);
// OK, if we're still here: overwrite the current transformation...
// Set a name on this generated transformation
//
String name = "Copy table from ["+sourceDBInfo.getName()+"] to ["+targetDBInfo.getName()+"]";
String transName = name;
int nr=1;
if (findTransformation(transName)!=null)
{
nr++;
transName = name+" "+nr;
}
meta.setName(transName);
addSpoonGraph(meta);
refreshGraph();
refreshTree();
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.UnexpectedError.Title"), Messages.getString("Spoon.Dialog.UnexpectedError.Message"), new KettleException(e.getMessage(), e));//"Unexpected error" "An unexpected error occurred creating the new transformation"
return false;
}
return true;
}
public String toString()
{
return APP_NAME;
}
/**
* This is the main procedure for Spoon.
*
* @param a Arguments are available in the "Get System Info" step.
*/
public static void main (String [] a) throws KettleException
{
EnvUtil.environmentInit();
ArrayList args = new ArrayList();
for (int i=0;i<a.length;i++) args.add(a[i]);
Display display = new Display();
Splash splash = new Splash(display);
StringBuffer optionRepname, optionUsername, optionPassword, optionTransname, optionFilename, optionDirname, optionLogfile, optionLoglevel;
CommandLineOption options[] = new CommandLineOption[]
{
new CommandLineOption("rep", "Repository name", optionRepname=new StringBuffer()),
new CommandLineOption("user", "Repository username", optionUsername=new StringBuffer()),
new CommandLineOption("pass", "Repository password", optionPassword=new StringBuffer()),
new CommandLineOption("trans", "The name of the transformation to launch", optionTransname=new StringBuffer()),
new CommandLineOption("dir", "The directory (don't forget the leading /)", optionDirname=new StringBuffer()),
new CommandLineOption("file", "The filename (Transformation in XML) to launch", optionFilename=new StringBuffer()),
new CommandLineOption("level", "The logging level (Basic, Detailed, Debug, Rowlevel, Error, Nothing)", optionLoglevel=new StringBuffer()),
new CommandLineOption("logfile", "The logging file to write to", optionLogfile=new StringBuffer()),
new CommandLineOption("log", "The logging file to write to (deprecated)", optionLogfile=new StringBuffer(), false, true),
};
// Parse the options...
CommandLineOption.parseArguments(args, options);
String kettleRepname = Const.getEnvironmentVariable("KETTLE_REPOSITORY", null);
String kettleUsername = Const.getEnvironmentVariable("KETTLE_USER", null);
String kettlePassword = Const.getEnvironmentVariable("KETTLE_PASSWORD", null);
if (!Const.isEmpty(kettleRepname )) optionRepname = new StringBuffer(kettleRepname);
if (!Const.isEmpty(kettleUsername)) optionUsername = new StringBuffer(kettleUsername);
if (!Const.isEmpty(kettlePassword)) optionPassword = new StringBuffer(kettlePassword);
// Before anything else, check the runtime version!!!
String version = Const.JAVA_VERSION;
if ("1.4".compareToIgnoreCase(version)>0)
{
System.out.println("The System is running on Java version "+version);
System.out.println("Unfortunately, it needs version 1.4 or higher to run.");
return;
}
// Set default Locale:
Locale.setDefault(Const.DEFAULT_LOCALE);
LogWriter log;
LogWriter.setConsoleAppenderDebug();
if (Const.isEmpty(optionLogfile))
{
log=LogWriter.getInstance(Const.SPOON_LOG_FILE, false, LogWriter.LOG_LEVEL_BASIC);
}
else
{
log=LogWriter.getInstance( optionLogfile.toString(), true, LogWriter.LOG_LEVEL_BASIC );
}
if (log.getRealFilename()!=null) log.logBasic(APP_NAME, Messages.getString("Spoon.Log.LoggingToFile")+log.getRealFilename());//"Logging goes to "
if (!Const.isEmpty(optionLoglevel))
{
log.setLogLevel(optionLoglevel.toString());
log.logBasic(APP_NAME, Messages.getString("Spoon.Log.LoggingAtLevel")+log.getLogLevelDesc());//"Logging is at level : "
}
/* Load the plugins etc.*/
StepLoader stloader = StepLoader.getInstance();
if (!stloader.read())
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.ErrorLoadingAndHaltSystem"));//Error loading steps & plugins... halting Spoon!
return;
}
/* Load the plugins etc. we need to load jobentry*/
JobEntryLoader jeloader = JobEntryLoader.getInstance();
if (!jeloader.read())
{
log.logError("Spoon", "Error loading job entries & plugins... halting Kitchen!");
return;
}
final Spoon spoon = new Spoon(log, display, null);
staticSpoon = spoon;
spoon.setDestroy(true);
spoon.setArguments((String[])args.toArray(new String[args.size()]));
log.logBasic(APP_NAME, Messages.getString("Spoon.Log.MainWindowCreated"));//Main window is created.
RepositoryMeta repositoryMeta = null;
UserInfo userinfo = null;
if (Const.isEmpty(optionRepname) && Const.isEmpty(optionFilename) && spoon.props.showRepositoriesDialogAtStartup())
{
log.logBasic(APP_NAME, Messages.getString("Spoon.Log.AskingForRepository"));//"Asking for repository"
int perms[] = new int[] { PermissionMeta.TYPE_PERMISSION_TRANSFORMATION };
splash.hide();
RepositoriesDialog rd = new RepositoriesDialog(spoon.disp, SWT.NONE, perms, Messages.getString("Spoon.Application.Name"));//"Spoon"
if (rd.open())
{
repositoryMeta = rd.getRepository();
userinfo = rd.getUser();
if (!userinfo.useTransformations())
{
MessageBox mb = new MessageBox(spoon.shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("Spoon.Dialog.RepositoryUserCannotWork.Message"));//"Sorry, this repository user can't work with transformations from the repository."
mb.setText(Messages.getString("Spoon.Dialog.RepositoryUserCannotWork.Title"));//"Error!"
mb.open();
userinfo = null;
repositoryMeta = null;
}
}
else
{
// Exit point: user pressed CANCEL!
if (rd.isCancelled())
{
splash.dispose();
spoon.quitFile();
return;
}
}
}
try
{
// Read kettle transformation specified on command-line?
if (!Const.isEmpty(optionRepname) || !Const.isEmpty(optionFilename))
{
if (!Const.isEmpty(optionRepname))
{
RepositoriesMeta repsinfo = new RepositoriesMeta(log);
if (repsinfo.readData())
{
repositoryMeta = repsinfo.findRepository(optionRepname.toString());
if (repositoryMeta!=null)
{
// Define and connect to the repository...
spoon.rep = new Repository(log, repositoryMeta, userinfo);
if (spoon.rep.connect(Messages.getString("Spoon.Application.Name")))//"Spoon"
{
if (Const.isEmpty(optionDirname)) optionDirname=new StringBuffer(RepositoryDirectory.DIRECTORY_SEPARATOR);
// Check username, password
spoon.rep.userinfo = new UserInfo(spoon.rep, optionUsername.toString(), optionPassword.toString());
if (spoon.rep.userinfo.getID()>0)
{
// OK, if we have a specified transformation, try to load it...
// If not, keep the repository logged in.
if (!Const.isEmpty(optionTransname))
{
RepositoryDirectory repdir = spoon.rep.getDirectoryTree().findDirectory(optionDirname.toString());
if (repdir!=null)
{
TransMeta transMeta = new TransMeta(spoon.rep, optionTransname.toString(), repdir);
transMeta.setFilename(optionRepname.toString());
transMeta.clearChanged();
spoon.addSpoonGraph(transMeta);
}
else
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableFindDirectory",optionDirname.toString()));//"Can't find directory ["+dirname+"] in the repository."
}
}
}
else
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableVerifyUser"));//"Can't verify username and password."
spoon.rep.disconnect();
spoon.rep=null;
}
}
else
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableConnectToRepository"));//"Can't connect to the repository."
}
}
else
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.NoRepositoryRrovided"));//"No repository provided, can't load transformation."
}
}
else
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.NoRepositoriesDefined"));//"No repositories defined on this system."
}
}
else
if (!Const.isEmpty(optionFilename))
{
spoon.openFile(optionFilename.toString(), false);
}
}
else // Normal operations, nothing on the commandline...
{
// Can we connect to the repository?
if (repositoryMeta!=null && userinfo!=null)
{
spoon.rep = new Repository(log, repositoryMeta, userinfo);
if (!spoon.rep.connect(Messages.getString("Spoon.Application.Name"))) //"Spoon"
{
spoon.rep = null;
}
}
if (spoon.props.openLastFile())
{
log.logDetailed(APP_NAME, Messages.getString("Spoon.Log.TryingOpenLastUsedFile"));//"Trying to open the last file used."
List lastUsedFiles = spoon.props.getLastUsedFiles();
if (lastUsedFiles.size()>0)
{
LastUsedFile lastUsedFile = (LastUsedFile) lastUsedFiles.get(0);
spoon.loadLastUsedFile(lastUsedFile, repositoryMeta);
}
}
}
}
catch(KettleException ke)
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.ErrorOccurred")+Const.CR+ke.getMessage());//"An error occurred: "
spoon.rep=null;
// ke.printStackTrace();
}
spoon.open ();
splash.dispose();
try
{
while (!spoon.isDisposed ())
{
if (!spoon.readAndDispatch ()) spoon.sleep ();
}
}
catch(Throwable e)
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.UnexpectedErrorOccurred")+Const.CR+e.getMessage());//"An unexpected error occurred in Spoon: probable cause: please close all windows before stopping Spoon! "
e.printStackTrace();
}
spoon.dispose();
log.logBasic(APP_NAME, APP_NAME+" "+Messages.getString("Spoon.Log.AppHasEnded"));//" has ended."
// Close the logfile
log.close();
// Kill all remaining things in this VM!
System.exit(0);
}
private void loadLastUsedFile(LastUsedFile lastUsedFile, RepositoryMeta repositoryMeta) throws KettleException
{
boolean useRepository = repositoryMeta!=null;
// Perhaps we need to connect to the repository?
if (lastUsedFile.isSourceRepository())
{
if (!Const.isEmpty(lastUsedFile.getRepositoryName()))
{
if (useRepository && !lastUsedFile.getRepositoryName().equalsIgnoreCase(repositoryMeta.getName()))
{
// We just asked...
useRepository = false;
}
}
}
if (useRepository && lastUsedFile.isSourceRepository())
{
if (rep!=null) // load from this repository...
{
if (rep.getName().equalsIgnoreCase(lastUsedFile.getRepositoryName()))
{
RepositoryDirectory repdir = rep.getDirectoryTree().findDirectory(lastUsedFile.getDirectory());
if (repdir!=null)
{
// Are we loading a transformation or a job?
if (lastUsedFile.isTransformation())
{
log.logDetailed(APP_NAME, Messages.getString("Spoon.Log.AutoLoadingTransformation",lastUsedFile.getFilename(), lastUsedFile.getDirectory()));//"Auto loading transformation ["+lastfiles[0]+"] from repository directory ["+lastdirs[0]+"]"
TransLoadProgressDialog tlpd = new TransLoadProgressDialog(shell, rep, lastUsedFile.getFilename(), repdir);
TransMeta transMeta = tlpd.open(); // = new TransInfo(log, win.rep, lastfiles[0], repdir);
if (transMeta != null)
{
props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, lastUsedFile.getFilename(), repdir.getPath(), true, rep.getName());
transMeta.setFilename(lastUsedFile.getFilename());
transMeta.clearChanged();
addSpoonGraph(transMeta);
refreshTree();
}
}
else
if (lastUsedFile.isJob())
{
// TODO: use JobLoadProgressDialog
JobMeta jobMeta = new JobMeta(log, rep, lastUsedFile.getFilename(), repdir);
props.addLastFile(LastUsedFile.FILE_TYPE_JOB, lastUsedFile.getFilename(), repdir.getPath(), true, rep.getName());
jobMeta.clearChanged();
addChefGraph(jobMeta);
}
refreshTree();
}
}
}
}
if (!lastUsedFile.isSourceRepository() && !Const.isEmpty(lastUsedFile.getFilename()))
{
if (lastUsedFile.isTransformation())
{
TransMeta transMeta = new TransMeta(lastUsedFile.getFilename());
transMeta.setFilename(lastUsedFile.getFilename());
transMeta.clearChanged();
props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, lastUsedFile.getFilename(), null, false, null);
addSpoonGraph(transMeta);
}
if (lastUsedFile.isJob())
{
JobMeta jobMeta = new JobMeta(log, lastUsedFile.getFilename(), rep);
jobMeta.setFilename(lastUsedFile.getFilename());
jobMeta.clearChanged();
props.addLastFile(LastUsedFile.FILE_TYPE_JOB, lastUsedFile.getFilename(), null, false, null);
addChefGraph(jobMeta);
}
refreshTree();
}
}
/**
* Create a new SelectValues step in between this step and the previous.
* If the previous fields are not there, no mapping can be made, same with the required fields.
* @param stepMeta The target step to map against.
*/
public void generateMapping(TransMeta transMeta, StepMeta stepMeta)
{
try
{
if (stepMeta!=null)
{
StepMetaInterface smi = stepMeta.getStepMetaInterface();
Row targetFields = smi.getRequiredFields();
Row sourceFields = transMeta.getPrevStepFields(stepMeta);
// Build the mapping: let the user decide!!
String[] source = sourceFields.getFieldNames();
for (int i=0;i<source.length;i++)
{
Value v = sourceFields.getValue(i);
source[i]+=EnterMappingDialog.STRING_ORIGIN_SEPARATOR+v.getOrigin()+")";
}
String[] target = targetFields.getFieldNames();
EnterMappingDialog dialog = new EnterMappingDialog(shell, source, target);
ArrayList mappings = dialog.open();
if (mappings!=null)
{
// OK, so we now know which field maps where.
// This allows us to generate the mapping using a SelectValues Step...
SelectValuesMeta svm = new SelectValuesMeta();
svm.allocate(mappings.size(), 0, 0);
for (int i=0;i<mappings.size();i++)
{
SourceToTargetMapping mapping = (SourceToTargetMapping) mappings.get(i);
svm.getSelectName()[i] = sourceFields.getValue(mapping.getSourcePosition()).getName();
svm.getSelectRename()[i] = target[mapping.getTargetPosition()];
svm.getSelectLength()[i] = -1;
svm.getSelectPrecision()[i] = -1;
}
// Now that we have the meta-data, create a new step info object
String stepName = stepMeta.getName()+" Mapping";
stepName = transMeta.getAlternativeStepname(stepName); // if it's already there, rename it.
StepMeta newStep = new StepMeta("SelectValues", stepName, svm);
newStep.setLocation(stepMeta.getLocation().x+20, stepMeta.getLocation().y+20);
newStep.setDraw(true);
transMeta.addStep(newStep);
addUndoNew(transMeta, new StepMeta[] { newStep }, new int[] { transMeta.indexOfStep(newStep) });
// Redraw stuff...
refreshTree();
refreshGraph();
}
}
else
{
System.out.println("No target to do mapping against!");
}
}
catch(KettleException e)
{
new ErrorDialog(shell, "Error creating mapping", "There was an error when Kettle tried to generate a mapping against the target step", e);
}
}
public void editPartitioning(TransMeta transMeta, StepMeta stepMeta)
{
StepPartitioningMeta stepPartitioningMeta = stepMeta.getStepPartitioningMeta();
if (stepPartitioningMeta==null) stepPartitioningMeta = new StepPartitioningMeta();
String[] options = StepPartitioningMeta.methodDescriptions;
EnterSelectionDialog dialog = new EnterSelectionDialog(shell, options, "Partioning method", "Select the partitioning method");
String methodDescription = dialog.open(stepPartitioningMeta.getMethod());
if (methodDescription!=null)
{
int method = StepPartitioningMeta.getMethod(methodDescription);
stepPartitioningMeta.setMethod(method);
switch(method)
{
case StepPartitioningMeta.PARTITIONING_METHOD_NONE: break;
case StepPartitioningMeta.PARTITIONING_METHOD_MOD:
// ask for a fieldname
EnterStringDialog stringDialog = new EnterStringDialog(shell, props, Const.NVL(stepPartitioningMeta.getFieldName(), ""), "Fieldname", "Enter a field name to partition on");
String fieldName = stringDialog.open();
stepPartitioningMeta.setFieldName(fieldName);
// Ask for a Partitioning Schema
String schemaNames[] = transMeta.getPartitionSchemasNames();
if (schemaNames.length==0)
{
MessageBox box = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
box.setText("Create a partition schema");
box.setMessage("You first need to create one or more partition schemas in the transformation settings dialog before you can select one!");
box.open();
}
else
{
// Set the partitioning schema too.
PartitionSchema partitionSchema = stepPartitioningMeta.getPartitionSchema();
int idx = -1;
if (partitionSchema!=null)
{
idx = Const.indexOfString(partitionSchema.getName(), schemaNames);
}
EnterSelectionDialog askSchema = new EnterSelectionDialog(shell, schemaNames, "Select a partition schema", "Select the partition schema to use:");
String schemaName = askSchema.open(idx);
if (schemaName!=null)
{
idx = Const.indexOfString(schemaName, schemaNames);
stepPartitioningMeta.setPartitionSchema((PartitionSchema) transMeta.getPartitionSchemas().get(idx));
}
}
break;
}
refreshGraph();
}
}
/**
* Select a clustering schema for this step.
*
* @param stepMeta The step to set the clustering schema for.
*/
public void editClustering(TransMeta transMeta, StepMeta stepMeta)
{
int idx = -1;
if (stepMeta.getClusterSchema()!=null)
{
idx = transMeta.getClusterSchemas().indexOf( stepMeta.getClusterSchema() );
}
String[] clusterSchemaNames = transMeta.getClusterSchemaNames();
EnterSelectionDialog dialog = new EnterSelectionDialog(shell, clusterSchemaNames, "Cluster schema", "Select the cluster schema to use (cancel=clear)");
String schemaName = dialog.open(idx);
if (schemaName==null)
{
stepMeta.setClusterSchema(null);
}
else
{
ClusterSchema clusterSchema = transMeta.findClusterSchema(schemaName);
stepMeta.setClusterSchema( clusterSchema );
}
refreshTree();
refreshGraph();
}
public void createKettleArchive(TransMeta transMeta)
{
if (transMeta==null) return;
JarfileGenerator.generateJarFile(transMeta);
}
/**
* This creates a new database partitioning schema, edits it and adds it to the transformation metadata
*
*/
public void newDatabasePartitioningSchema(TransMeta transMeta)
{
PartitionSchema partitionSchema = new PartitionSchema();
PartitionSchemaDialog dialog = new PartitionSchemaDialog(shell, partitionSchema, transMeta.getDatabases());
if (dialog.open())
{
transMeta.getPartitionSchemas().add(partitionSchema);
refreshTree();
}
}
private void editPartitionSchema(HasDatabasesInterface hasDatabasesInterface, PartitionSchema partitionSchema)
{
PartitionSchemaDialog dialog = new PartitionSchemaDialog(shell, partitionSchema, hasDatabasesInterface.getDatabases());
if (dialog.open())
{
refreshTree();
}
}
private void delPartitionSchema(TransMeta transMeta, PartitionSchema partitionSchema)
{
try
{
if (rep!=null && partitionSchema.getId()>0)
{
// remove the partition schema from the repository too...
rep.delPartitionSchema(partitionSchema.getId());
}
int idx = transMeta.getPartitionSchemas().indexOf(partitionSchema);
transMeta.getPartitionSchemas().remove(idx);
refreshTree();
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorDeletingClusterSchema.Title"), Messages.getString("Spoon.Dialog.ErrorDeletingClusterSchema.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* This creates a new clustering schema, edits it and adds it to the transformation metadata
*
*/
public void newClusteringSchema(TransMeta transMeta)
{
ClusterSchema clusterSchema = new ClusterSchema();
ClusterSchemaDialog dialog = new ClusterSchemaDialog(shell, clusterSchema, transMeta.getSlaveServers());
if (dialog.open())
{
transMeta.getClusterSchemas().add(clusterSchema);
refreshTree();
}
}
private void editClusterSchema(TransMeta transMeta, ClusterSchema clusterSchema)
{
ClusterSchemaDialog dialog = new ClusterSchemaDialog(shell, clusterSchema, transMeta.getSlaveServers());
if (dialog.open())
{
refreshTree();
}
}
private void delClusterSchema(TransMeta transMeta, ClusterSchema clusterSchema)
{
try
{
if (rep!=null && clusterSchema.getId()>0)
{
// remove the partition schema from the repository too...
rep.delClusterSchema(clusterSchema.getId());
}
int idx = transMeta.getClusterSchemas().indexOf(clusterSchema);
transMeta.getClusterSchemas().remove(idx);
refreshTree();
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorDeletingPartitionSchema.Title"), Messages.getString("Spoon.Dialog.ErrorDeletingPartitionSchema.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* This creates a slave server, edits it and adds it to the transformation metadata
*
*/
public void newSlaveServer(TransMeta transMeta)
{
SlaveServer slaveServer = new SlaveServer();
SlaveServerDialog dialog = new SlaveServerDialog(shell, slaveServer);
if (dialog.open())
{
transMeta.getSlaveServers().add(slaveServer);
refreshTree();
}
}
public void delSlaveServer(TransMeta transMeta, SlaveServer slaveServer)
{
try
{
if (rep!=null && slaveServer.getId()>0)
{
// remove the slave server from the repository too...
rep.delSlave(slaveServer.getId());
}
int idx = transMeta.getSlaveServers().indexOf(slaveServer);
transMeta.getSlaveServers().remove(idx);
refreshTree();
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorDeletingSlave.Title"), Messages.getString("Spoon.Dialog.ErrorDeletingSlave.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* Sends transformation to slave server
* @param executionConfiguration
*/
public void sendXMLToSlaveServer(TransMeta transMeta, TransExecutionConfiguration executionConfiguration)
{
SlaveServer slaveServer = executionConfiguration.getRemoteServer();
try
{
if (slaveServer==null) throw new KettleException("No slave server specified");
if (Const.isEmpty(transMeta.getName())) throw new KettleException("The transformation needs a name to uniquely identify it by on the remote server.");
String reply = slaveServer.sendXML(new TransConfiguration(transMeta, executionConfiguration).getXML(), AddTransServlet.CONTEXT_PATH+"?xml=Y");
WebResult webResult = WebResult.fromXMLString(reply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("There was an error posting the transformation on the remote server: "+Const.CR+webResult.getMessage());
}
reply = slaveServer.getContentFromServer(PrepareExecutionTransHandler.CONTEXT_PATH+"?name="+transMeta.getName()+"&xml=Y");
webResult = WebResult.fromXMLString(reply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("There was an error preparing the transformation for excution on the remote server: "+Const.CR+webResult.getMessage());
}
reply = slaveServer.getContentFromServer(StartExecutionTransHandler.CONTEXT_PATH+"?name="+transMeta.getName()+"&xml=Y");
webResult = WebResult.fromXMLString(reply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("There was an error starting the transformation on the remote server: "+Const.CR+webResult.getMessage());
}
}
catch (Exception e)
{
new ErrorDialog(shell, "Error", "Error sending transformation to server", e);
}
}
private void splitTrans(TransMeta transMeta, boolean show, boolean post, boolean prepare, boolean start)
{
try
{
if (Const.isEmpty(transMeta.getName())) throw new KettleException("The transformation needs a name to uniquely identify it by on the remote server.");
TransSplitter transSplitter = new TransSplitter(transMeta);
transSplitter.splitOriginalTransformation();
// Send the transformations to the servers...
//
// First the master...
//
TransMeta master = transSplitter.getMaster();
SlaveServer masterServer = null;
List masterSteps = master.getTransHopSteps(false);
if (masterSteps.size()>0) // If there is something that needs to be done on the master...
{
masterServer = transSplitter.getMasterServer();
if (show) addSpoonGraph(master);
if (post)
{
String masterReply = masterServer.sendXML(new TransConfiguration(master, executionConfiguration).getXML(), AddTransServlet.CONTEXT_PATH+"?xml=Y");
WebResult webResult = WebResult.fromXMLString(masterReply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("An error occurred sending the master transformation: "+webResult.getMessage());
}
}
}
// Then the slaves...
//
SlaveServer slaves[] = transSplitter.getSlaveTargets();
for (int i=0;i<slaves.length;i++)
{
TransMeta slaveTrans = (TransMeta) transSplitter.getSlaveTransMap().get(slaves[i]);
if (show) addSpoonGraph(slaveTrans);
if (post)
{
String slaveReply = slaves[i].sendXML(new TransConfiguration(slaveTrans, executionConfiguration).getXML(), AddTransServlet.CONTEXT_PATH+"?xml=Y");
WebResult webResult = WebResult.fromXMLString(slaveReply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("An error occurred sending a slave transformation: "+webResult.getMessage());
}
}
}
if (post)
{
if (prepare)
{
// Prepare the master...
if (masterSteps.size()>0) // If there is something that needs to be done on the master...
{
String masterReply = masterServer.getContentFromServer(PrepareExecutionTransHandler.CONTEXT_PATH+"?name="+master.getName()+"&xml=Y");
WebResult webResult = WebResult.fromXMLString(masterReply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("An error occurred while preparing the execution of the master transformation: "+webResult.getMessage());
}
}
// Prepare the slaves
for (int i=0;i<slaves.length;i++)
{
TransMeta slaveTrans = (TransMeta) transSplitter.getSlaveTransMap().get(slaves[i]);
String slaveReply = slaves[i].getContentFromServer(PrepareExecutionTransHandler.CONTEXT_PATH+"?name="+slaveTrans.getName()+"&xml=Y");
WebResult webResult = WebResult.fromXMLString(slaveReply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("An error occurred while preparing the execution of a slave transformation: "+webResult.getMessage());
}
}
}
if (start)
{
// Start the master...
if (masterSteps.size()>0) // If there is something that needs to be done on the master...
{
String masterReply = masterServer.getContentFromServer(StartExecutionTransHandler.CONTEXT_PATH+"?name="+master.getName()+"&xml=Y");
WebResult webResult = WebResult.fromXMLString(masterReply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("An error occurred while starting the execution of the master transformation: "+webResult.getMessage());
}
}
// Start the slaves
for (int i=0;i<slaves.length;i++)
{
TransMeta slaveTrans = (TransMeta) transSplitter.getSlaveTransMap().get(slaves[i]);
String slaveReply = slaves[i].getContentFromServer(StartExecutionTransHandler.CONTEXT_PATH+"?name="+slaveTrans.getName()+"&xml=Y");
WebResult webResult = WebResult.fromXMLString(slaveReply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("An error occurred while starting the execution of a slave transformation: "+webResult.getMessage());
}
}
}
// Now add monitors for the master and all the slave servers
addSpoonSlave(masterServer);
for (int i=0;i<slaves.length;i++)
{
addSpoonSlave(slaves[i]);
}
}
}
catch(Exception e)
{
new ErrorDialog(shell, "Split transformation", "There was an error during transformation split", e);
}
}
public void executeFile(boolean local, boolean remote, boolean cluster, boolean preview, Date replayDate)
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null) executeTransformation(transMeta, local, remote, cluster, preview, replayDate);
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null) executeJob(jobMeta, local, remote, cluster, preview, replayDate);
}
public void executeTransformation(TransMeta transMeta, boolean local, boolean remote, boolean cluster, boolean preview, Date replayDate)
{
if (transMeta==null) return;
executionConfiguration.setExecutingLocally(local);
executionConfiguration.setExecutingRemotely(remote);
executionConfiguration.setExecutingClustered(cluster);
executionConfiguration.getUsedVariables(transMeta);
executionConfiguration.getUsedArguments(transMeta, arguments);
executionConfiguration.setReplayDate(replayDate);
executionConfiguration.setLocalPreviewing(preview);
executionConfiguration.setLogLevel(log.getLogLevel());
// executionConfiguration.setSafeModeEnabled( spoonLog!=null && spoonLog.isSafeModeChecked() );
TransExecutionConfigurationDialog dialog = new TransExecutionConfigurationDialog(shell, executionConfiguration, transMeta);
if (dialog.open())
{
addSpoonLog(transMeta);
SpoonLog spoonLog = getActiveSpoonLog();
if (executionConfiguration.isExecutingLocally())
{
if (executionConfiguration.isLocalPreviewing())
{
spoonLog.preview(executionConfiguration);
}
else
{
spoonLog.start(executionConfiguration);
}
}
else if(executionConfiguration.isExecutingRemotely())
{
if (executionConfiguration.getRemoteServer()!=null)
{
sendXMLToSlaveServer(transMeta, executionConfiguration);
addSpoonSlave(executionConfiguration.getRemoteServer());
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(Messages.getString("Spoon.Dialog.NoRemoteServerSpecified.Message"));
mb.setText(Messages.getString("Spoon.Dialog.NoRemoteServerSpecified.Title"));
mb.open();
}
}
else if (executionConfiguration.isExecutingClustered())
{
splitTrans( transMeta,
executionConfiguration.isClusterShowingTransformation(),
executionConfiguration.isClusterPosting(),
executionConfiguration.isClusterPreparing(),
executionConfiguration.isClusterStarting()
);
}
}
}
public void executeJob(JobMeta jobMeta, boolean local, boolean remote, boolean cluster, boolean preview, Date replayDate)
{
addChefLog(jobMeta);
ChefLog chefLog = getActiveJobLog();
chefLog.startJob(replayDate);
}
public CTabItem findCTabItem(String text)
{
CTabItem[] items = tabfolder.getItems();
for (int i=0;i<items.length;i++)
{
if (items[i].getText().equalsIgnoreCase(text)) return items[i];
}
return null;
}
private void addSpoonSlave(SlaveServer slaveServer)
{
// See if there is a SpoonSlave for this slaveServer...
String tabName = makeSlaveTabName(slaveServer);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
SpoonSlave spoonSlave = new SpoonSlave(tabfolder, SWT.NONE, this, slaveServer);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Status of slave server : "+slaveServer.getName()+" : "+slaveServer.getServerAndPort());
tabItem.setControl(spoonSlave);
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, spoonSlave));
}
int idx = tabfolder.indexOf(tabItem);
tabfolder.setSelection(idx);
}
public void addSpoonGraph(TransMeta transMeta)
{
String key = addTransformation(transMeta);
if (key!=null)
{
// See if there already is a tab for this graph
// If no, add it
// If yes, select that tab
//
String tabName = makeGraphTabName(transMeta);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
SpoonGraph spoonGraph = new SpoonGraph(tabfolder, this, transMeta);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Graphical view of Transformation : "+tabName);
tabItem.setImage(GUIResource.getInstance().getImageSpoonGraph());
tabItem.setControl(spoonGraph);
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, spoonGraph));
}
int idx = tabfolder.indexOf(tabItem);
// OK, also see if we need to open a new history window.
if (transMeta.getLogConnection()!=null && !Const.isEmpty(transMeta.getLogTable()))
{
addSpoonHistory(transMeta, false);
}
// keep the focus on the graph
tabfolder.setSelection(idx);
setUndoMenu(transMeta);
enableMenus();
}
}
public void addChefGraph(JobMeta jobMeta)
{
String key = addJob(jobMeta);
if (key!=null)
{
// See if there already is a tab for this graph
// If no, add it
// If yes, select that tab
//
String tabName = makeJobGraphTabName(jobMeta);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
ChefGraph chefGraph = new ChefGraph(tabfolder, this, jobMeta);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Graphical view of Job : "+tabName);
tabItem.setImage(GUIResource.getInstance().getImageChefGraph());
tabItem.setControl(chefGraph);
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, chefGraph));
}
int idx = tabfolder.indexOf(tabItem);
// OK, also see if we need to open a new history window.
if (jobMeta.getLogConnection()!=null && !Const.isEmpty(jobMeta.getLogTable()))
{
addChefHistory(jobMeta, false);
}
// keep the focus on the graph
tabfolder.setSelection(idx);
setUndoMenu(jobMeta);
enableMenus();
}
}
public boolean addSpoonBrowser(String name, String urlString)
{
try
{
// OK, now we have the HTML, create a new browset tab.
// See if there already is a tab for this browser
// If no, add it
// If yes, select that tab
//
CTabItem tabItem=findCTabItem(name);
if (tabItem==null)
{
SpoonBrowser browser = new SpoonBrowser(tabfolder, this, urlString);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(name);
tabItem.setControl(browser.getComposite());
tabMap.put(name, new TabMapEntry(tabItem, name, browser));
}
int idx = tabfolder.indexOf(tabItem);
// keep the focus on the graph
tabfolder.setSelection(idx);
return true;
}
catch(Throwable e)
{
return false;
}
}
public String makeLogTabName(TransMeta transMeta)
{
return "Trans log: "+makeGraphTabName(transMeta);
}
public String makeJobLogTabName(JobMeta jobMeta)
{
return "Job log: "+makeJobGraphTabName(jobMeta);
}
public String makeGraphTabName(TransMeta transMeta)
{
if (Const.isEmpty(transMeta.getName()))
{
if (Const.isEmpty(transMeta.getFilename()))
{
return STRING_TRANS_NO_NAME;
}
return transMeta.getFilename();
}
return transMeta.getName();
}
public String makeJobGraphTabName(JobMeta jobMeta)
{
if (Const.isEmpty(jobMeta.getName()))
{
if (Const.isEmpty(jobMeta.getFilename()))
{
return STRING_JOB_NO_NAME;
}
return jobMeta.getFilename();
}
return jobMeta.getName();
}
public String makeHistoryTabName(TransMeta transMeta)
{
return "Trans History: "+makeGraphTabName(transMeta);
}
public String makeJobHistoryTabName(JobMeta jobMeta)
{
return "Job History: "+makeJobGraphTabName(jobMeta);
}
public String makeSlaveTabName(SlaveServer slaveServer)
{
return "Slave server: "+slaveServer.getName();
}
public void addSpoonLog(TransMeta transMeta)
{
// See if there already is a tab for this log
// If no, add it
// If yes, select that tab
//
String tabName = makeLogTabName(transMeta);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
SpoonLog spoonLog = new SpoonLog(tabfolder, this, transMeta);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Execution log for transformation : "+makeGraphTabName(transMeta));
tabItem.setControl(spoonLog);
// If there is an associated history window, we want to keep that one up-to-date as well.
//
SpoonHistory spoonHistory = findSpoonHistoryOfTransformation(transMeta);
CTabItem historyItem = findCTabItem(makeHistoryTabName(transMeta));
if (spoonHistory!=null && historyItem!=null)
{
SpoonHistoryRefresher spoonHistoryRefresher = new SpoonHistoryRefresher(historyItem, spoonHistory);
tabfolder.addSelectionListener(spoonHistoryRefresher);
spoonLog.setSpoonHistoryRefresher(spoonHistoryRefresher);
}
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, spoonLog));
}
int idx = tabfolder.indexOf(tabItem);
tabfolder.setSelection(idx);
}
public void addChefLog(JobMeta jobMeta)
{
// See if there already is a tab for this log
// If no, add it
// If yes, select that tab
//
String tabName = makeJobLogTabName(jobMeta);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
ChefLog chefLog = new ChefLog(tabfolder, this, jobMeta);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Execution log for job: "+makeJobGraphTabName(jobMeta));
tabItem.setControl(chefLog);
// If there is an associated history window, we want to keep that one up-to-date as well.
//
ChefHistory chefHistory = findChefHistoryOfJob(jobMeta);
CTabItem historyItem = findCTabItem(makeJobHistoryTabName(jobMeta));
if (chefHistory!=null && historyItem!=null)
{
ChefHistoryRefresher chefHistoryRefresher = new ChefHistoryRefresher(historyItem, chefHistory);
tabfolder.addSelectionListener(chefHistoryRefresher);
chefLog.setChefHistoryRefresher(chefHistoryRefresher);
}
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, chefLog));
}
int idx = tabfolder.indexOf(tabItem);
tabfolder.setSelection(idx);
}
public void addSpoonHistory(TransMeta transMeta, boolean select)
{
// See if there already is a tab for this history view
// If no, add it
// If yes, select that tab
//
String tabName = makeHistoryTabName(transMeta);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
SpoonHistory spoonHistory = new SpoonHistory(tabfolder, this, transMeta);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Execution history for transformation : "+makeGraphTabName(transMeta));
tabItem.setControl(spoonHistory);
// If there is an associated log window that's open, find it and add a refresher
SpoonLog spoonLog = findSpoonLogOfTransformation(transMeta);
if (spoonLog!=null)
{
SpoonHistoryRefresher spoonHistoryRefresher = new SpoonHistoryRefresher(tabItem, spoonHistory);
tabfolder.addSelectionListener(spoonHistoryRefresher);
spoonLog.setSpoonHistoryRefresher(spoonHistoryRefresher);
}
spoonHistory.markRefreshNeeded(); // will refresh when first selected
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, spoonHistory));
}
if (select)
{
int idx = tabfolder.indexOf(tabItem);
tabfolder.setSelection(idx);
}
}
public void addChefHistory(JobMeta jobMeta, boolean select)
{
// See if there already is a tab for this history view
// If no, add it
// If yes, select that tab
//
String tabName = makeJobHistoryTabName(jobMeta);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
ChefHistory chefHistory = new ChefHistory(tabfolder, this, jobMeta);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Execution history for job : "+makeJobGraphTabName(jobMeta));
tabItem.setControl(chefHistory);
// If there is an associated log window that's open, find it and add a refresher
ChefLog chefLog = findChefLogOfJob(jobMeta);
if (chefLog!=null)
{
ChefHistoryRefresher chefHistoryRefresher = new ChefHistoryRefresher(tabItem, chefHistory);
tabfolder.addSelectionListener(chefHistoryRefresher);
chefLog.setChefHistoryRefresher(chefHistoryRefresher);
}
chefHistory.markRefreshNeeded(); // will refresh when first selected
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, chefHistory));
}
if (select)
{
int idx = tabfolder.indexOf(tabItem);
tabfolder.setSelection(idx);
}
}
/**
* Rename the tabs
*/
public void renameTabs()
{
Collection collection = tabMap.values();
List list = new ArrayList();
list.addAll(collection);
for (Iterator iter = list.iterator(); iter.hasNext();)
{
TabMapEntry entry = (TabMapEntry) iter.next();
if (entry.getTabItem().isDisposed())
{
// this should not be in the map, get rid of it.
tabMap.remove(entry.getObjectName());
continue;
}
String before = entry.getTabItem().getText();
- if (entry.getObject() instanceof SpoonGraph) entry.getTabItem().setText( makeGraphTabName( (TransMeta) entry.getObject().getManagedObject() ) );
- if (entry.getObject() instanceof SpoonLog) entry.getTabItem().setText( makeLogTabName( (TransMeta) entry.getObject().getManagedObject() ) );
- if (entry.getObject() instanceof SpoonHistory) entry.getTabItem().setText( makeHistoryTabName( (TransMeta) entry.getObject().getManagedObject() ) );
- if (entry.getObject() instanceof ChefGraph) entry.getTabItem().setText( makeJobGraphTabName( (JobMeta) entry.getObject().getManagedObject() ) );
- if (entry.getObject() instanceof ChefLog) entry.getTabItem().setText( makeJobLogTabName( (JobMeta) entry.getObject().getManagedObject() ) );
- if (entry.getObject() instanceof ChefHistory) entry.getTabItem().setText( makeJobHistoryTabName( (JobMeta) entry.getObject().getManagedObject() ) );
+ Object managedObject = entry.getObject().getManagedObject();
+ if (managedObject!=null)
+ {
+ if (entry.getObject() instanceof SpoonGraph) entry.getTabItem().setText( makeGraphTabName( (TransMeta) managedObject ) );
+ if (entry.getObject() instanceof SpoonLog) entry.getTabItem().setText( makeLogTabName( (TransMeta) managedObject ) );
+ if (entry.getObject() instanceof SpoonHistory) entry.getTabItem().setText( makeHistoryTabName( (TransMeta) managedObject ) );
+ if (entry.getObject() instanceof ChefGraph) entry.getTabItem().setText( makeJobGraphTabName( (JobMeta) managedObject ) );
+ if (entry.getObject() instanceof ChefLog) entry.getTabItem().setText( makeJobLogTabName( (JobMeta) managedObject ) );
+ if (entry.getObject() instanceof ChefHistory) entry.getTabItem().setText( makeJobHistoryTabName( (JobMeta) managedObject) );
+ }
String after = entry.getTabItem().getText();
if (!before.equals(after))
{
entry.setObjectName(after);
tabMap.remove(before);
tabMap.put(after, entry);
// Also change the transformation map
if (entry.getObject() instanceof SpoonGraph)
{
transformationMap.remove(before);
transformationMap.put(after, entry.getObject().getManagedObject());
}
}
}
}
/**
* This contains a map between the name of a transformation and the TransMeta object.
* If the transformation has no name it will be mapped under a number [1], [2] etc.
* @return the transformation map
*/
public Map getTransformationMap()
{
return transformationMap;
}
/**
* @param transformationMap the transformation map to set
*/
public void setTransformationMap(Map transformationMap)
{
this.transformationMap = transformationMap;
}
/**
* @return the tabMap
*/
public Map getTabMap()
{
return tabMap;
}
/**
* @param tabMap the tabMap to set
*/
public void setTabMap(Map tabMap)
{
this.tabMap = tabMap;
}
public void pasteSteps()
{
// Is there an active SpoonGraph?
SpoonGraph spoonGraph = getActiveSpoonGraph();
if (spoonGraph==null) return;
TransMeta transMeta = spoonGraph.getTransMeta();
String clipcontent = fromClipboard();
if (clipcontent != null)
{
Point lastMove = spoonGraph.getLastMove();
if (lastMove != null)
{
pasteXML(transMeta, clipcontent, lastMove);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//
//
//
// Job manipulation steps...
//
//
//
//////////////////////////////////////////////////////////////////////////////////////////////////
public JobEntryCopy newJobEntry(JobMeta jobMeta, String type_desc, boolean openit)
{
JobEntryLoader jobLoader = JobEntryLoader.getInstance();
JobPlugin jobPlugin = null;
try
{
jobPlugin = jobLoader.findJobEntriesWithDescription(type_desc);
if (jobPlugin==null)
{
// Check if it's not START or DUMMY
if (JobMeta.STRING_SPECIAL_START.equals(type_desc) || JobMeta.STRING_SPECIAL_DUMMY.equals(type_desc))
{
jobPlugin = jobLoader.findJobEntriesWithID(JobMeta.STRING_SPECIAL);
}
}
if (jobPlugin!=null)
{
// Determine name & number for this entry.
String basename = type_desc;
int nr = jobMeta.generateJobEntryNameNr(basename);
String entry_name = basename+" "+nr; //$NON-NLS-1$
// Generate the appropriate class...
JobEntryInterface jei = jobLoader.getJobEntryClass(jobPlugin);
jei.setName(entry_name);
if (jei.isSpecial())
{
if (JobMeta.STRING_SPECIAL_START.equals(type_desc))
{
// Check if start is already on the canvas...
if (jobMeta.findStart()!=null)
{
ChefGraph.showOnlyStartOnceMessage(shell);
return null;
}
((JobEntrySpecial)jei).setStart(true);
jei.setName("Start");
}
if (JobMeta.STRING_SPECIAL_DUMMY.equals(type_desc))
{
((JobEntrySpecial)jei).setDummy(true);
jei.setName("Dummy");
}
}
if (openit)
{
JobEntryDialogInterface d = jei.getDialog(shell,jei,jobMeta,entry_name,rep);
if (d.open()!=null)
{
JobEntryCopy jge = new JobEntryCopy();
jge.setEntry(jei);
jge.setLocation(50,50);
jge.setNr(0);
jobMeta.addJobEntry(jge);
addUndoNew(jobMeta, new JobEntryCopy[] { jge }, new int[] { jobMeta.indexOfJobEntry(jge) });
refreshGraph();
refreshTree();
return jge;
}
else
{
return null;
}
}
else
{
JobEntryCopy jge = new JobEntryCopy();
jge.setEntry(jei);
jge.setLocation(50,50);
jge.setNr(0);
jobMeta.addJobEntry(jge);
addUndoNew(jobMeta, new JobEntryCopy[] { jge }, new int[] { jobMeta.indexOfJobEntry(jge) });
refreshGraph();
refreshTree();
return jge;
}
}
else
{
return null;
}
}
catch(Throwable e)
{
new ErrorDialog(shell, Messages.getString("Spoon.ErrorDialog.UnexpectedErrorCreatingNewChefGraphEntry.Title"), Messages.getString("Spoon.ErrorDialog.UnexpectedErrorCreatingNewChefGraphEntry.Message"),new Exception(e)); //$NON-NLS-1$ //$NON-NLS-2$
return null;
}
}
public boolean saveJobFile(JobMeta jobMeta)
{
log.logDetailed(toString(), "Save file..."); //$NON-NLS-1$
boolean saved = false;
if (rep!=null)
{
saved = saveJobRepository(jobMeta);
}
else
{
if (jobMeta.getFilename()!=null)
{
saved = saveJob(jobMeta, jobMeta.getFilename());
}
else
{
saved = saveJobFileAs(jobMeta);
}
}
if (saved) // all was OK
{
saved=saveJobSharedObjects(jobMeta);
}
return saved;
}
private boolean saveJobXMLFile(JobMeta jobMeta)
{
boolean saved=false;
FileDialog dialog = new FileDialog(shell, SWT.SAVE);
dialog.setFilterExtensions(Const.STRING_JOB_FILTER_EXT);
dialog.setFilterNames(Const.STRING_JOB_FILTER_NAMES);
String fname = dialog.open();
if (fname!=null)
{
// Is the filename ending on .ktr, .xml?
boolean ending=false;
for (int i=0;i<Const.STRING_JOB_FILTER_EXT.length-1;i++)
{
if (fname.endsWith(Const.STRING_JOB_FILTER_EXT[i].substring(1)))
{
ending=true;
}
}
if (fname.endsWith(Const.STRING_JOB_DEFAULT_EXT)) ending=true;
if (!ending)
{
fname+=Const.STRING_JOB_DEFAULT_EXT;
}
// See if the file already exists...
File f = new File(fname);
int id = SWT.YES;
if (f.exists())
{
MessageBox mb = new MessageBox(shell, SWT.NO | SWT.YES | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("Spoon.Dialog.PromptOverwriteFile.Message"));//"This file already exists. Do you want to overwrite it?"
mb.setText(Messages.getString("Spoon.Dialog.PromptOverwriteFile.Title"));//"This file already exists!"
id = mb.open();
}
if (id==SWT.YES)
{
saved=saveJob(jobMeta, fname);
jobMeta.setFilename(fname);
}
}
return saved;
}
public boolean saveJobRepository(JobMeta jobMeta)
{
return saveJobRepository(jobMeta, false);
}
public boolean saveJobRepository(JobMeta jobMeta, boolean ask_name)
{
log.logDetailed(toString(), "Save to repository..."); //$NON-NLS-1$
if (rep!=null)
{
boolean answer = true;
boolean ask = ask_name;
while (answer && ( ask || jobMeta.getName()==null || jobMeta.getName().length()==0 ) )
{
if (!ask)
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("Spoon.Dialog.GiveJobANameBeforeSaving.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.GiveJobANameBeforeSaving.Title")); //$NON-NLS-1$
mb.open();
}
ask=false;
answer = editJobProperties(jobMeta);
}
if (answer && jobMeta.getName()!=null && jobMeta.getName().length()>0)
{
if (!rep.getUserInfo().isReadonly())
{
boolean saved=false;
int response = SWT.YES;
if (jobMeta.showReplaceWarning(rep))
{
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.ICON_QUESTION);
mb.setMessage(Messages.getString("Chef.Dialog.JobExistsOverwrite.Message1")+jobMeta.getName()+Messages.getString("Chef.Dialog.JobExistsOverwrite.Message2")+Const.CR+Messages.getString("Chef.Dialog.JobExistsOverwrite.Message3")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
mb.setText(Messages.getString("Chef.Dialog.JobExistsOverwrite.Title")); //$NON-NLS-1$
response = mb.open();
}
if (response == SWT.YES)
{
// Keep info on who & when this transformation was changed...
jobMeta.modifiedDate = new Value("MODIFIED_DATE", Value.VALUE_TYPE_DATE); //$NON-NLS-1$
jobMeta.modifiedDate.sysdate();
jobMeta.modifiedUser = rep.getUserInfo().getLogin();
JobSaveProgressDialog jspd = new JobSaveProgressDialog(shell, rep, jobMeta);
if (jspd.open())
{
if (!props.getSaveConfirmation())
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell,
Messages.getString("Spoon.Dialog.JobWasStoredInTheRepository.Title"), //$NON-NLS-1$
null,
Messages.getString("Spoon.Dialog.JobWasStoredInTheRepository.Message"), //$NON-NLS-1$
MessageDialog.QUESTION,
new String[] { Messages.getString("System.Button.OK") }, //$NON-NLS-1$
0,
Messages.getString("Spoon.Dialog.JobWasStoredInTheRepository.Toggle"), //$NON-NLS-1$
props.getSaveConfirmation()
);
md.open();
props.setSaveConfirmation(md.getToggleState());
}
// Handle last opened files...
props.addLastFile(LastUsedFile.FILE_TYPE_JOB, jobMeta.getName(), jobMeta.getDirectory().getPath(), true, rep.getName());
saveSettings();
addMenuLast();
setShellText();
saved=true;
}
}
return saved;
}
else
{
MessageBox mb = new MessageBox(shell, SWT.CLOSE | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("Spoon.Dialog.UserCanOnlyReadFromTheRepositoryJobNotSaved.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.UserCanOnlyReadFromTheRepositoryJobNotSaved.Title")); //$NON-NLS-1$
mb.open();
}
}
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("Spoon.Dialog.NoRepositoryConnectionAvailable.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.NoRepositoryConnectionAvailable.Title")); //$NON-NLS-1$
mb.open();
}
return false;
}
public boolean saveJobFileAs(JobMeta jobMeta)
{
boolean saved=false;
if (rep!=null)
{
jobMeta.setID(-1L);
saved=saveJobRepository(jobMeta, true);
}
else
{
saved=saveJobXMLFile(jobMeta);
}
return saved;
}
public void saveJobFileAsXML(JobMeta jobMeta)
{
log.logBasic(toString(), "Save file as..."); //$NON-NLS-1$
FileDialog dialog = new FileDialog(shell, SWT.SAVE);
//dialog.setFilterPath("C:\\Projects\\kettle\\source\\");
dialog.setFilterExtensions(Const.STRING_JOB_FILTER_EXT);
dialog.setFilterNames (Const.STRING_JOB_FILTER_NAMES);
String fname = dialog.open();
if (fname!=null)
{
// Is the filename ending on .ktr, .xml?
boolean ending=false;
for (int i=0;i<Const.STRING_JOB_FILTER_EXT.length-1;i++)
{
if (fname.endsWith(Const.STRING_JOB_FILTER_EXT[i].substring(1))) ending=true;
}
if (fname.endsWith(Const.STRING_JOB_DEFAULT_EXT)) ending=true;
if (!ending)
{
fname+=Const.STRING_JOB_DEFAULT_EXT;
}
// See if the file already exists...
File f = new File(fname);
int id = SWT.YES;
if (f.exists())
{
MessageBox mb = new MessageBox(shell, SWT.NO | SWT.YES | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("Spoon.Dialog.FileExistsOverWrite.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.FileExistsOverWrite.Title")); //$NON-NLS-1$
id = mb.open();
}
if (id==SWT.YES)
{
saveJob(jobMeta, fname);
}
}
}
private boolean saveJob(JobMeta jobMeta, String fname)
{
boolean saved = false;
String xml = XMLHandler.getXMLHeader() + jobMeta.getXML();
try
{
DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File(fname)));
dos.write(xml.getBytes(Const.XML_ENCODING));
dos.close();
saved=true;
// Handle last opened files...
props.addLastFile(LastUsedFile.FILE_TYPE_JOB, fname, RepositoryDirectory.DIRECTORY_SEPARATOR, false, ""); //$NON-NLS-1$
saveSettings();
addMenuLast();
log.logDebug(toString(), "File written to ["+fname+"]"); //$NON-NLS-1$ //$NON-NLS-2$
jobMeta.setFilename( fname );
jobMeta.clearChanged();
setShellText();
}
catch(Exception e)
{
log.logDebug(toString(), "Error opening file for writing! --> "+e.toString()); //$NON-NLS-1$
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("Spoon.Dialog.ErrorSavingFile.Message")+Const.CR+e.toString()); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.ErrorSavingFile.Title")); //$NON-NLS-1$
mb.open();
}
return saved;
}
private boolean editJobProperties(JobMeta jobMeta)
{
if (jobMeta==null) return false;
JobDialog jd = new JobDialog(shell, SWT.NONE, jobMeta, rep);
JobMeta ji = jd.open();
// In this case, load shared objects
//
if (jd.isSharedObjectsFileChanged())
{
loadJobSharedObjects(jobMeta);
}
if (jd.isSharedObjectsFileChanged() || ji!=null)
{
refreshTree();
renameTabs(); // cheap operation, might as will do it anyway
}
setShellText();
return ji!=null;
}
public void editJobEntry(JobMeta jobMeta, JobEntryCopy je)
{
try
{
log.logBasic(toString(), "edit job graph entry: "+je.getName()); //$NON-NLS-1$
JobEntryCopy before =(JobEntryCopy)je.clone_deep();
boolean entry_changed=false;
JobEntryInterface jei = je.getEntry();
if (jei.isSpecial())
{
JobEntrySpecial special = (JobEntrySpecial) jei;
if (special.isDummy()) return;
}
JobEntryDialogInterface d = jei.getDialog(shell, jei, jobMeta,je.getName(),rep);
if (d!=null)
{
if (d.open()!=null)
{
entry_changed=true;
}
if (entry_changed)
{
JobEntryCopy after = (JobEntryCopy) je.clone();
addUndoChange(jobMeta, new JobEntryCopy[] { before }, new JobEntryCopy[] { after }, new int[] { jobMeta.indexOfJobEntry(je) } );
refreshGraph();
refreshTree();
}
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(Messages.getString("Spoon.Dialog.JobEntryCanNotBeChanged.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.JobEntryCanNotBeChanged.Title")); //$NON-NLS-1$
mb.open();
}
}
catch(Exception e)
{
if (!shell.isDisposed()) new ErrorDialog(shell, Messages.getString("Chef.ErrorDialog.ErrorEditingJobEntry.Title"), Messages.getString("Chef.ErrorDialog.ErrorEditingJobEntry.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public JobEntryTrans newJobEntry(JobMeta jobMeta, int type)
{
JobEntryTrans je = new JobEntryTrans();
je.setType(type);
String basename = JobEntryTrans.typeDesc[type];
int nr = jobMeta.generateJobEntryNameNr(basename);
je.setName(basename+" "+nr); //$NON-NLS-1$
setShellText();
return je;
}
public void deleteJobEntryCopies(JobMeta jobMeta, JobEntryCopy jobEntry)
{
String name = jobEntry.getName();
// TODO Show warning "Are you sure? This operation can't be undone." + clear undo buffer.
// First delete all the hops using entry with name:
JobHopMeta hi[] = jobMeta.getAllJobHopsUsing(name);
if (hi.length>0)
{
int hix[] = new int[hi.length];
for (int i=0;i<hi.length;i++) hix[i] = jobMeta.indexOfJobHop(hi[i]);
addUndoDelete(jobMeta, hi, hix);
for (int i=hix.length-1;i>=0;i--) jobMeta.removeJobHop(hix[i]);
}
// Then delete all the entries with name:
JobEntryCopy je[] = jobMeta.getAllChefGraphEntries(name);
int jex[] = new int[je.length];
for (int i=0;i<je.length;i++) jex[i] = jobMeta.indexOfJobEntry(je[i]);
addUndoDelete(jobMeta, je, jex);
for (int i=jex.length-1;i>=0;i--) jobMeta.removeJobEntry(jex[i]);
refreshGraph();
refreshTree();
}
public void dupeJobEntry(JobMeta jobMeta, JobEntryCopy jobEntry)
{
if (jobEntry!=null && !jobEntry.isStart())
{
JobEntryCopy dupejge = (JobEntryCopy)jobEntry.clone();
dupejge.setNr( jobMeta.findUnusedNr(dupejge.getName()) );
if (dupejge.isDrawn())
{
Point p = jobEntry.getLocation();
dupejge.setLocation(p.x+10, p.y+10);
}
jobMeta.addJobEntry(dupejge);
refreshGraph();
refreshTree();
setShellText();
}
}
public void copyJobEntries(JobMeta jobMeta, JobEntryCopy jec[])
{
if (jec==null || jec.length==0) return;
String xml = XMLHandler.getXMLHeader();
xml+="<jobentries>"+Const.CR; //$NON-NLS-1$
for (int i=0;i<jec.length;i++)
{
xml+=jec[i].getXML();
}
xml+=" </jobentries>"+Const.CR; //$NON-NLS-1$
toClipboard(xml);
}
public void pasteXML(JobMeta jobMeta, String clipcontent, Point loc)
{
try
{
Document doc = XMLHandler.loadXMLString(clipcontent);
// De-select all, re-select pasted steps...
jobMeta.unselectAll();
Node entriesnode = XMLHandler.getSubNode(doc, "jobentries"); //$NON-NLS-1$
int nr = XMLHandler.countNodes(entriesnode, "entry"); //$NON-NLS-1$
log.logDebug(toString(), "I found "+nr+" job entries to paste on location: "+loc); //$NON-NLS-1$ //$NON-NLS-2$
JobEntryCopy entries[] = new JobEntryCopy[nr];
//Point min = new Point(loc.x, loc.y);
Point min = new Point(99999999,99999999);
for (int i=0;i<nr;i++)
{
Node entrynode = XMLHandler.getSubNodeByNr(entriesnode, "entry", i); //$NON-NLS-1$
entries[i] = new JobEntryCopy(entrynode, jobMeta.getDatabases(), rep);
String name = jobMeta.getAlternativeJobentryName(entries[i].getName());
entries[i].setName(name);
if (loc!=null)
{
Point p = entries[i].getLocation();
if (min.x > p.x) min.x = p.x;
if (min.y > p.y) min.y = p.y;
}
}
// What's the difference between loc and min?
// This is the offset:
Point offset = new Point(loc.x-min.x, loc.y-min.y);
// Undo/redo object positions...
int position[] = new int[entries.length];
for (int i=0;i<entries.length;i++)
{
Point p = entries[i].getLocation();
String name = entries[i].getName();
entries[i].setLocation(p.x+offset.x, p.y+offset.y);
// Check the name, find alternative...
entries[i].setName( jobMeta.getAlternativeJobentryName(name) );
jobMeta.addJobEntry(entries[i]);
position[i] = jobMeta.indexOfJobEntry(entries[i]);
}
// Save undo information too...
addUndoNew(jobMeta, entries, position);
if (jobMeta.hasChanged())
{
refreshTree();
refreshGraph();
}
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Chef.ErrorDialog.ErrorPasingJobEntries.Title"), Messages.getString("Chef.ErrorDialog.ErrorPasingJobEntries.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public void newJobHop(JobMeta jobMeta, JobEntryCopy fr, JobEntryCopy to)
{
JobHopMeta hi = new JobHopMeta(fr, to);
jobMeta.addJobHop(hi);
addUndoNew(jobMeta, new JobHopMeta[] {hi}, new int[] { jobMeta.indexOfJobHop(hi)} );
refreshGraph();
refreshTree();
}
/**
* Create a job that extracts tables & data from a database.<p><p>
*
* 0) Select the database to rip<p>
* 1) Select the tables in the database to rip<p>
* 2) Select the database to dump to<p>
* 3) Select the repository directory in which it will end up<p>
* 4) Select a name for the new job<p>
* 5) Create an empty job with the selected name.<p>
* 6) Create 1 transformation for every selected table<p>
* 7) add every created transformation to the job & evaluate<p>
*
*/
private void ripDBWizard()
{
final ArrayList databases = getActiveDatabases();
if (databases.size() == 0) return; // Nothing to do here
final RipDatabaseWizardPage1 page1 = new RipDatabaseWizardPage1("1", databases); //$NON-NLS-1$
page1.createControl(shell);
final RipDatabaseWizardPage2 page2 = new RipDatabaseWizardPage2("2"); //$NON-NLS-1$
page2.createControl(shell);
final RipDatabaseWizardPage3 page3 = new RipDatabaseWizardPage3("3", rep); //$NON-NLS-1$
page3.createControl(shell);
Wizard wizard = new Wizard()
{
public boolean performFinish()
{
JobMeta jobMeta = ripDB(databases, page3.getJobname(), page3.getDirectory(), page1.getSourceDatabase(), page1.getTargetDatabase(), page2.getSelection());
if (jobMeta==null) return false;
addChefGraph(jobMeta);
return true;
}
/**
* @see org.eclipse.jface.wizard.Wizard#canFinish()
*/
public boolean canFinish()
{
return page3.canFinish();
}
};
wizard.addPage(page1);
wizard.addPage(page2);
wizard.addPage(page3);
WizardDialog wd = new WizardDialog(shell, wizard);
wd.setMinimumPageSize(700, 400);
wd.open();
}
public JobMeta ripDB(
final ArrayList databases,
final String jobname,
final RepositoryDirectory repdir,
final DatabaseMeta sourceDbInfo,
final DatabaseMeta targetDbInfo,
final String[] tables
)
{
//
// Create a new job...
//
final JobMeta jobMeta = new JobMeta(log);
jobMeta.setDatabases(databases);
jobMeta.setFilename(null);
jobMeta.setName(jobname);
jobMeta.setDirectory(repdir);
refreshTree();
refreshGraph();
final Point location = new Point(50, 50);
// The start entry...
final JobEntryCopy start = jobMeta.findStart();
start.setLocation(new Point(location.x, location.y));
start.setDrawn();
// final Thread parentThread = Thread.currentThread();
// Create a dialog with a progress indicator!
IRunnableWithProgress op = new IRunnableWithProgress()
{
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException
{
// This is running in a new process: copy some KettleVariables info
// LocalVariables.getInstance().createKettleVariables(Thread.currentThread().getName(),
// parentThread.getName(), true);
monitor.beginTask(Messages.getString("Spoon.RipDB.Monitor.BuildingNewJob"), tables.length); //$NON-NLS-1$
monitor.worked(0);
JobEntryCopy previous = start;
// Loop over the table-names...
for (int i = 0; i < tables.length && !monitor.isCanceled(); i++)
{
monitor.setTaskName(Messages.getString("Spoon.RipDB.Monitor.ProcessingTable") + tables[i] + "]..."); //$NON-NLS-1$ //$NON-NLS-2$
//
// Create the new transformation...
//
String transname = Messages.getString("Spoon.RipDB.Monitor.Transname1") + sourceDbInfo + "].[" + tables[i] + Messages.getString("Spoon.RipDB.Monitor.Transname2") + targetDbInfo + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
TransMeta ti = new TransMeta((String) null, transname, null);
ti.setDirectory(repdir);
//
// Add a note
//
String note = Messages.getString("Spoon.RipDB.Monitor.Note1") + tables[i] + Messages.getString("Spoon.RipDB.Monitor.Note2") + sourceDbInfo + "]" + Const.CR; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
note += Messages.getString("Spoon.RipDB.Monitor.Note3") + tables[i] + Messages.getString("Spoon.RipDB.Monitor.Note4") + targetDbInfo + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
NotePadMeta ni = new NotePadMeta(note, 150, 10, -1, -1);
ti.addNote(ni);
//
// Add the TableInputMeta step...
//
String fromstepname = Messages.getString("Spoon.RipDB.Monitor.FromStep.Name") + tables[i] + "]"; //$NON-NLS-1$ //$NON-NLS-2$
TableInputMeta tii = new TableInputMeta();
tii.setDatabaseMeta(sourceDbInfo);
tii.setSQL("SELECT * FROM " + sourceDbInfo.quoteField(tables[i])); //$NON-NLS-1$
String fromstepid = StepLoader.getInstance().getStepPluginID(tii);
StepMeta fromstep = new StepMeta(fromstepid, fromstepname, (StepMetaInterface) tii);
fromstep.setLocation(150, 100);
fromstep.setDraw(true);
fromstep
.setDescription(Messages.getString("Spoon.RipDB.Monitor.FromStep.Description") + tables[i] + Messages.getString("Spoon.RipDB.Monitor.FromStep.Description2") + sourceDbInfo + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
ti.addStep(fromstep);
//
// Add the TableOutputMeta step...
//
String tostepname = Messages.getString("Spoon.RipDB.Monitor.ToStep.Name") + tables[i] + "]"; //$NON-NLS-1$ //$NON-NLS-2$
TableOutputMeta toi = new TableOutputMeta();
toi.setDatabaseMeta(targetDbInfo);
toi.setTablename(tables[i]);
toi.setCommitSize(100);
toi.setTruncateTable(true);
String tostepid = StepLoader.getInstance().getStepPluginID(toi);
StepMeta tostep = new StepMeta(tostepid, tostepname, (StepMetaInterface) toi);
tostep.setLocation(500, 100);
tostep.setDraw(true);
tostep
.setDescription(Messages.getString("Spoon.RipDB.Monitor.ToStep.Description1") + tables[i] + Messages.getString("Spoon.RipDB.Monitor.ToStep.Description2") + targetDbInfo + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
ti.addStep(tostep);
//
// Add a hop between the two steps...
//
TransHopMeta hi = new TransHopMeta(fromstep, tostep);
ti.addTransHop(hi);
//
// Now we generate the SQL needed to run for this transformation.
//
// First set the limit to 1 to speed things up!
String tmpSql = tii.getSQL();
tii.setSQL(tii.getSQL() + sourceDbInfo.getLimitClause(1));
String sql = ""; //$NON-NLS-1$
try
{
sql = ti.getSQLStatementsString();
}
catch (KettleStepException kse)
{
throw new InvocationTargetException(kse,
Messages.getString("Spoon.RipDB.Exception.ErrorGettingSQLFromTransformation") + ti + "] : " + kse.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
}
// remove the limit
tii.setSQL(tmpSql);
//
// Now, save the transformation...
//
try
{
ti.saveRep(rep);
}
catch (KettleException dbe)
{
throw new InvocationTargetException(dbe, Messages.getString("Spoon.RipDB.Exception.UnableToSaveTransformationToRepository")); //$NON-NLS-1$
}
// We can now continue with the population of the job...
// //////////////////////////////////////////////////////////////////////
location.x = 250;
if (i > 0) location.y += 100;
//
// We can continue defining the job.
//
// First the SQL, but only if needed!
// If the table exists & has the correct format, nothing is done
//
if (!Const.isEmpty(sql))
{
String jesqlname = Messages.getString("Spoon.RipDB.JobEntrySQL.Name") + tables[i] + "]"; //$NON-NLS-1$ //$NON-NLS-2$
JobEntrySQL jesql = new JobEntrySQL(jesqlname);
jesql.setDatabase(targetDbInfo);
jesql.setSQL(sql);
jesql.setDescription(Messages.getString("Spoon.RipDB.JobEntrySQL.Description") + targetDbInfo + "].[" + tables[i] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
JobEntryCopy jecsql = new JobEntryCopy();
jecsql.setEntry(jesql);
jecsql.setLocation(new Point(location.x, location.y));
jecsql.setDrawn();
jobMeta.addJobEntry(jecsql);
// Add the hop too...
JobHopMeta jhi = new JobHopMeta(previous, jecsql);
jobMeta.addJobHop(jhi);
previous = jecsql;
}
//
// Add the jobentry for the transformation too...
//
String jetransname = Messages.getString("Spoon.RipDB.JobEntryTrans.Name") + tables[i] + "]"; //$NON-NLS-1$ //$NON-NLS-2$
JobEntryTrans jetrans = new JobEntryTrans(jetransname);
jetrans.setTransname(ti.getName());
jetrans.setDirectory(ti.getDirectory());
JobEntryCopy jectrans = new JobEntryCopy(log, jetrans);
jectrans
.setDescription(Messages.getString("Spoon.RipDB.JobEntryTrans.Description1") + Const.CR + Messages.getString("Spoon.RipDB.JobEntryTrans.Description2") + sourceDbInfo + "].[" + tables[i] + "]" + Const.CR + Messages.getString("Spoon.RipDB.JobEntryTrans.Description3") + targetDbInfo + "].[" + tables[i] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
jectrans.setDrawn();
location.x += 400;
jectrans.setLocation(new Point(location.x, location.y));
jobMeta.addJobEntry(jectrans);
// Add a hop between the last 2 job entries.
JobHopMeta jhi2 = new JobHopMeta(previous, jectrans);
jobMeta.addJobHop(jhi2);
previous = jectrans;
monitor.worked(1);
}
monitor.worked(100);
monitor.done();
}
};
try
{
ProgressMonitorDialog pmd = new ProgressMonitorDialog(shell);
pmd.run(false, true, op);
}
catch (InvocationTargetException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.ErrorDialog.RipDB.ErrorRippingTheDatabase.Title"), Messages.getString("Spoon.ErrorDialog.RipDB.ErrorRippingTheDatabase.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
return null;
}
catch (InterruptedException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.ErrorDialog.RipDB.ErrorRippingTheDatabase.Title"), Messages.getString("Spoon.ErrorDialog.RipDB.ErrorRippingTheDatabase.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
return null;
}
finally
{
refreshGraph();
refreshTree();
}
return jobMeta;
}
/**
* Set the core object state.
*
* @param state
*/
public void setCoreObjectsState(int state)
{
coreObjectsState = state;
}
/**
* Get the core object state.
*
* @return state.
*/
public int getCoreObjectsState()
{
return coreObjectsState;
}
}
| true | true |
public void verifyCopyDistribute(TransMeta transMeta, StepMeta fr)
{
int nrNextSteps = transMeta.findNrNextSteps(fr);
// don't show it for 3 or more hops, by then you should have had the message
if (nrNextSteps==2)
{
boolean distributes = false;
if (props.showCopyOrDistributeWarning())
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell,
Messages.getString("System.Warning"),//"Warning!"
null,
Messages.getString("Spoon.Dialog.CopyOrDistribute.Message", fr.getName(), Integer.toString(nrNextSteps)),
MessageDialog.WARNING,
new String[] { Messages.getString("Spoon.Dialog.CopyOrDistribute.Copy"), Messages.getString("Spoon.Dialog.CopyOrDistribute.Distribute") },//"Copy Distribute
0,
Messages.getString("Spoon.Message.Warning.NotShowWarning"),//"Please, don't show this warning anymore."
!props.showCopyOrDistributeWarning()
);
int idx = md.open();
props.setShowCopyOrDistributeWarning(!md.getToggleState());
props.saveProps();
distributes = (idx&0xFF)==1;
}
if (distributes)
{
fr.setDistributes(true);
}
else
{
fr.setDistributes(false);
}
refreshTree();
refreshGraph();
}
}
public void newHop(TransMeta transMeta)
{
newHop(transMeta, null, null);
}
public void newConnection(HasDatabasesInterface hasDatabasesInterface)
{
DatabaseMeta databaseMeta = new DatabaseMeta();
DatabaseDialog con = new DatabaseDialog(shell, databaseMeta);
String con_name = con.open();
if (!Const.isEmpty(con_name))
{
databaseMeta.verifyAndModifyDatabaseName(hasDatabasesInterface.getDatabases(), null);
hasDatabasesInterface.addDatabase(databaseMeta);
addUndoNew((UndoInterface)hasDatabasesInterface, new DatabaseMeta[] { (DatabaseMeta)databaseMeta.clone() }, new int[] { hasDatabasesInterface.indexOfDatabase(databaseMeta) });
saveConnection(databaseMeta);
refreshTree();
}
}
public void saveConnection(DatabaseMeta db)
{
// Also add to repository?
if (rep!=null)
{
if (!rep.userinfo.isReadonly())
{
try
{
rep.lockRepository();
rep.insertLogEntry("Saving database '"+db.getName()+"'");
db.saveRep(rep);
log.logDetailed(toString(), Messages.getString("Spoon.Log.SavedDatabaseConnection",db.getDatabaseName()));//"Saved database connection ["+db+"] to the repository."
// Put a commit behind it!
rep.commit();
db.setChanged(false);
}
catch(KettleException ke)
{
rep.rollback(); // In case of failure: undo changes!
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorSavingConnection.Title"),Messages.getString("Spoon.Dialog.ErrorSavingConnection.Message",db.getDatabaseName()), ke);//"Can't save...","Error saving connection ["+db+"] to repository!"
}
finally
{
try
{
rep.unlockRepository();
}
catch(KettleDatabaseException e)
{
new ErrorDialog(shell, "Error", "Unexpected error unlocking the repository database", e);
}
}
}
else
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.UnableSave.Title"),Messages.getString("Spoon.Dialog.ErrorSavingConnection.Message",db.getDatabaseName()), new KettleException(Messages.getString("Spoon.Dialog.Exception.ReadOnlyRepositoryUser")));//This repository user is read-only!
}
}
}
public void openRepository()
{
int perms[] = new int[] { PermissionMeta.TYPE_PERMISSION_TRANSFORMATION };
RepositoriesDialog rd = new RepositoriesDialog(disp, SWT.NONE, perms, APP_NAME);
rd.getShell().setImage(GUIResource.getInstance().getImageSpoon());
if (rd.open())
{
// Close previous repository...
if (rep!=null)
{
rep.disconnect();
}
rep = new Repository(log, rd.getRepository(), rd.getUser());
try
{
rep.connect(APP_NAME);
}
catch(KettleException ke)
{
rep=null;
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorConnectingRepository.Title"), Messages.getString("Spoon.Dialog.ErrorConnectingRepository.Message",Const.CR), ke); //$NON-NLS-1$ //$NON-NLS-2$
}
TransMeta transMetas[] = getLoadedTransformations();
for (int t=0;t<transMetas.length;t++)
{
TransMeta transMeta = transMetas[t];
for (int i=0;i<transMeta.nrDatabases();i++)
{
transMeta.getDatabase(i).setID(-1L);
}
// Set for the existing transformation the ID at -1!
transMeta.setID(-1L);
// Keep track of the old databases for now.
ArrayList oldDatabases = transMeta.getDatabases();
// In order to re-match the databases on name (not content), we need to load the databases from the new repository.
// NOTE: for purposes such as DEVELOP - TEST - PRODUCTION sycles.
// first clear the list of databases, partition schemas, slave servers, clusters
transMeta.setDatabases(new ArrayList());
transMeta.setPartitionSchemas(new ArrayList());
transMeta.setSlaveServers(new ArrayList());
transMeta.setClusterSchemas(new ArrayList());
// Read them from the new repository.
try
{
transMeta.readSharedObjects(rep);
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", makeGraphTabName(transMeta)), e);
}
// Then we need to re-match the databases at save time...
for (int i=0;i<oldDatabases.size();i++)
{
DatabaseMeta oldDatabase = (DatabaseMeta) oldDatabases.get(i);
DatabaseMeta newDatabase = Const.findDatabase(transMeta.getDatabases(), oldDatabase.getName());
// If it exists, change the settings...
if (newDatabase!=null)
{
//
// A database connection with the same name exists in the new repository.
// Change the old connections to reflect the settings in the new repository
//
oldDatabase.setDatabaseInterface(newDatabase.getDatabaseInterface());
}
else
{
//
// The old database is not present in the new repository: simply add it to the list.
// When the transformation gets saved, it will be added to the repository.
//
transMeta.addDatabase(oldDatabase);
}
}
// For the existing transformation, change the directory too:
// Try to find the same directory in the new repository...
RepositoryDirectory redi = rep.getDirectoryTree().findDirectory(transMeta.getDirectory().getPath());
if (redi!=null)
{
transMeta.setDirectory(redi);
}
else
{
transMeta.setDirectory(rep.getDirectoryTree()); // the root is the default!
}
}
refreshTree();
setShellText();
}
else
{
// Not cancelled? --> Clear repository...
if (!rd.isCancelled())
{
closeRepository();
}
}
}
public void exploreRepository()
{
if (rep!=null)
{
RepositoryExplorerDialog erd = new RepositoryExplorerDialog(shell, SWT.NONE, rep, rep.getUserInfo());
String objname = erd.open();
if (objname!=null)
{
String object_type = erd.getObjectType();
RepositoryDirectory repdir = erd.getObjectDirectory();
// Try to open the selected transformation.
if (object_type.equals(RepositoryExplorerDialog.STRING_TRANSFORMATIONS))
{
try
{
TransMeta transMeta = new TransMeta(rep, objname, repdir);
transMeta.clearChanged();
transMeta.setFilename(objname);
addSpoonGraph(transMeta);
refreshTree();
refreshGraph();
}
catch(KettleException e)
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("Spoon.Dialog.ErrorOpening.Message")+objname+Const.CR+e.getMessage());//"Error opening : "
mb.setText(Messages.getString("Spoon.Dialog.ErrorOpening.Title"));
mb.open();
}
}
else
// Try to open the selected job.
if (object_type.equals(RepositoryExplorerDialog.STRING_JOBS))
{
try
{
JobMeta jobMeta = new JobMeta(log, rep, objname, repdir);
jobMeta.clearChanged();
jobMeta.setFilename(objname);
addChefGraph(jobMeta);
refreshTree();
refreshGraph();
}
catch(KettleException e)
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("Spoon.Dialog.ErrorOpening.Message")+objname+Const.CR+e.getMessage());//"Error opening : "
mb.setText(Messages.getString("Spoon.Dialog.ErrorOpening.Title"));
mb.open();
}
}
}
}
}
public void editRepositoryUser()
{
if (rep!=null)
{
UserInfo userinfo = rep.getUserInfo();
UserDialog ud = new UserDialog(shell, SWT.NONE, log, props, rep, userinfo);
UserInfo ui = ud.open();
if (!userinfo.isReadonly())
{
if (ui!=null)
{
try
{
ui.saveRep(rep);
}
catch(KettleException e)
{
MessageBox mb = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
mb.setMessage(Messages.getString("Spoon.Dialog.UnableChangeUser.Message")+Const.CR+e.getMessage());//Sorry, I was unable to change this user in the repository:
mb.setText(Messages.getString("Spoon.Dialog.UnableChangeUser.Title"));//"Edit user"
mb.open();
}
}
}
else
{
MessageBox mb = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
mb.setMessage(Messages.getString("Spoon.Dialog.NotAllowedChangeUser.Message"));//"Sorry, you are not allowed to change this user."
mb.setText(Messages.getString("Spoon.Dialog.NotAllowedChangeUser.Title"));
mb.open();
}
}
}
public void closeRepository()
{
if (rep!=null) rep.disconnect();
rep = null;
setShellText();
}
public void openFile(boolean importfile)
{
if (rep==null || importfile) // Load from XML
{
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(Const.STRING_TRANS_AND_JOB_FILTER_EXT);
dialog.setFilterNames(Const.STRING_TRANS_AND_JOB_FILTER_NAMES);
String fname = dialog.open();
if (fname!=null)
{
openFile(fname, importfile);
}
}
else
{
SelectObjectDialog sod = new SelectObjectDialog(shell, rep);
if (sod.open()!=null)
{
String type = sod.getObjectType();
String name = sod.getObjectName();
RepositoryDirectory repdir = sod.getDirectory();
// Load a transformation
if (RepositoryObject.STRING_OBJECT_TYPE_TRANSFORMATION.equals(type))
{
TransLoadProgressDialog tlpd = new TransLoadProgressDialog(shell, rep, name, repdir);
TransMeta transMeta = tlpd.open();
if (transMeta!=null)
{
log.logDetailed(toString(),Messages.getString("Spoon.Log.LoadToTransformation",name,repdir.getDirectoryName()) );//"Transformation ["+transname+"] in directory ["+repdir+"] loaded from the repository."
props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, name, repdir.getPath(), true, rep.getName());
addMenuLast();
transMeta.clearChanged();
transMeta.setFilename(name);
addSpoonGraph(transMeta);
}
refreshGraph();
refreshTree();
refreshHistory();
}
else
// Load a job
if (RepositoryObject.STRING_OBJECT_TYPE_JOB.equals(type))
{
JobLoadProgressDialog jlpd = new JobLoadProgressDialog(shell, rep, name, repdir);
JobMeta jobMeta = jlpd.open();
if (jobMeta!=null)
{
props.addLastFile(LastUsedFile.FILE_TYPE_JOB, name, repdir.getPath(), true, rep.getName());
saveSettings();
addMenuLast();
addChefGraph(jobMeta);
}
refreshGraph();
refreshTree();
}
}
}
}
public void openFile(String fname, boolean importfile)
{
// Open the XML and see what's in there.
// We expect a single <transformation> or <job> root at this time...
try
{
Document document = XMLHandler.loadXMLFile(fname);
boolean loaded = false;
// Check for a transformation...
Node transNode = XMLHandler.getSubNode(document, TransMeta.XML_TAG);
if (transNode!=null) // yep, found a transformation
{
TransMeta transMeta = new TransMeta();
transMeta.loadXML(transNode, rep, true);
props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, fname, null, false, null);
addMenuLast();
if (!importfile) transMeta.clearChanged();
transMeta.setFilename(fname);
addSpoonGraph(transMeta);
refreshTree();
refreshHistory();
loaded=true;
}
// Check for a job...
Node jobNode = XMLHandler.getSubNode(document, JobMeta.XML_TAG);
if (jobNode!=null) // Indeed, found a job
{
JobMeta jobMeta = new JobMeta(log);
jobMeta.loadXML(jobNode, rep);
props.addLastFile(LastUsedFile.FILE_TYPE_JOB, fname, null, false, null);
addMenuLast();
if (!importfile) jobMeta.clearChanged();
jobMeta.setFilename(fname);
addChefGraph(jobMeta);
loaded=true;
}
if (!loaded)
{
// Give error back
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("Spoon.UnknownFileType.Message", fname));
mb.setText(Messages.getString("Spoon.UnknownFileType.Title"));
mb.open();
}
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorOpening.Title"), Messages.getString("Spoon.Dialog.ErrorOpening.Message")+fname, e);
}
}
public void newFile()
{
String[] choices = new String[] { STRING_TRANSFORMATION, STRING_JOB };
EnterSelectionDialog enterSelectionDialog = new EnterSelectionDialog(shell, choices, Messages.getString("Spoon.Dialog.NewFile.Title"), Messages.getString("Spoon.Dialog.NewFile.Message"));
if (enterSelectionDialog.open()!=null)
{
switch( enterSelectionDialog.getSelectionNr() )
{
case 0: newTransFile(); break;
case 1: newJobFile(); break;
}
}
}
public void newTransFile()
{
TransMeta transMeta = new TransMeta();
try
{
transMeta.readSharedObjects(rep);
transMeta.clearChanged();
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Exception.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Exception.ErrorReadingSharedObjects.Message"), e);
}
addSpoonGraph(transMeta);
refreshTree();
}
public void newJobFile()
{
try
{
JobMeta jobMeta = new JobMeta(log);
try
{
jobMeta.readSharedObjects(rep);
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", makeJobGraphTabName(jobMeta)), e);
}
addChefGraph(jobMeta);
refreshTree();
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Exception.ErrorCreatingNewJob.Title"), Messages.getString("Spoon.Exception.ErrorCreatingNewJob.Message"), e);
}
}
public void loadRepositoryObjects(TransMeta transMeta)
{
// Load common database info from active repository...
if (rep!=null)
{
try
{
transMeta.readSharedObjects(rep);
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Error.UnableToLoadSharedObjects.Title"), Messages.getString("Spoon.Error.UnableToLoadSharedObjects.Message"), e);
}
}
}
public boolean quitFile()
{
log.logDetailed(toString(), Messages.getString("Spoon.Log.QuitApplication"));//"Quit application."
boolean exit = true;
saveSettings();
if (props.showExitWarning())
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell,
Messages.getString("System.Warning"),//"Warning!"
null,
Messages.getString("Spoon.Message.Warning.PromptExit"), // Are you sure you want to exit?
MessageDialog.WARNING,
new String[] { Messages.getString("Spoon.Message.Warning.Yes"), Messages.getString("Spoon.Message.Warning.No") },//"Yes", "No"
1,
Messages.getString("Spoon.Message.Warning.NotShowWarning"),//"Please, don't show this warning anymore."
!props.showExitWarning()
);
int idx = md.open();
props.setExitWarningShown(!md.getToggleState());
props.saveProps();
if ((idx&0xFF)==1) return false; // No selected: don't exit!
}
// Check all tabs to see if we can close them...
List list = new ArrayList();
list.addAll(tabMap.values());
for (Iterator iter = list.iterator(); iter.hasNext() && exit;)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
TabItemInterface itemInterface = mapEntry.getObject();
if (!itemInterface.canBeClosed())
{
// Show the tab
tabfolder.setSelection( mapEntry.getTabItem() );
// Unsaved work that needs to changes to be applied?
//
int reply= itemInterface.showChangedWarning();
if (reply==SWT.YES)
{
exit=itemInterface.applyChanges();
}
else
{
if (reply==SWT.CANCEL)
{
exit = false;
}
else // SWT.NO
{
exit = true;
}
}
/*
if (mapEntry.getObject() instanceof SpoonGraph)
{
TransMeta transMeta = (TransMeta) mapEntry.getObject().getManagedObject();
if (transMeta.hasChanged())
{
// Show the transformation in question
//
tabfolder.setSelection( mapEntry.getTabItem() );
// Ask if we should save it before closing...
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.CANCEL | SWT.ICON_WARNING );
mb.setMessage(Messages.getString("Spoon.Dialog.SaveChangedFile.Message", makeGraphTabName(transMeta)));//"File has changed! Do you want to save first?"
mb.setText(Messages.getString("Spoon.Dialog.SaveChangedFile.Title"));//"Warning!"
int answer = mb.open();
switch(answer)
{
case SWT.YES: exit=saveFile(transMeta); break;
case SWT.NO: exit=true; break;
case SWT.CANCEL:
exit=false;
break;
}
}
}
// A running transformation?
//
if (mapEntry.getObject() instanceof SpoonLog)
{
SpoonLog spoonLog = (SpoonLog) mapEntry.getObject();
if (spoonLog.isRunning())
{
if (reply==SWT.NO) exit=false; // No selected: don't exit!
}
}
*/
}
}
if (exit) // we have asked about it all and we're still here. Now close all the tabs, stop the running transformations
{
for (Iterator iter = list.iterator(); iter.hasNext() && exit;)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (!mapEntry.getObject().canBeClosed())
{
// Unsaved transformation?
//
if (mapEntry.getObject() instanceof SpoonGraph)
{
TransMeta transMeta = (TransMeta) mapEntry.getObject().getManagedObject();
if (transMeta.hasChanged())
{
mapEntry.getTabItem().dispose();
}
}
// A running transformation?
//
if (mapEntry.getObject() instanceof SpoonLog)
{
SpoonLog spoonLog = (SpoonLog) mapEntry.getObject();
if (spoonLog.isRunning())
{
spoonLog.stop();
mapEntry.getTabItem().dispose();
}
}
}
}
}
if (exit) dispose();
return exit;
}
public boolean saveFile()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null) return saveTransFile(transMeta);
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null) return saveJobFile(jobMeta);
return false;
}
public boolean saveTransFile(TransMeta transMeta)
{
if (transMeta==null) return false;
boolean saved=false;
log.logDetailed(toString(), Messages.getString("Spoon.Log.SaveToFileOrRepository"));//"Save to file or repository..."
if (rep!=null)
{
saved=saveTransRepository(transMeta);
}
else
{
if (transMeta.getFilename()!=null)
{
saved=save(transMeta, transMeta.getFilename());
}
else
{
saved=saveTransFileAs(transMeta);
}
}
if (saved) // all was OK
{
saved=saveTransSharedObjects(transMeta);
}
try
{
if (props.useDBCache()) transMeta.getDbCache().saveCache(log);
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorSavingDatabaseCache.Title"), Messages.getString("Spoon.Dialog.ErrorSavingDatabaseCache.Message"), e);//"An error occured saving the database cache to disk"
}
renameTabs(); // filename or name of transformation might have changed.
refreshTree();
return saved;
}
public boolean saveTransRepository(TransMeta transMeta)
{
return saveTransRepository(transMeta, false);
}
public boolean saveTransRepository(TransMeta transMeta, boolean ask_name)
{
log.logDetailed(toString(), Messages.getString("Spoon.Log.SaveToRepository"));//"Save to repository..."
if (rep!=null)
{
boolean answer = true;
boolean ask = ask_name;
while (answer && ( ask || transMeta.getName()==null || transMeta.getName().length()==0 ) )
{
if (!ask)
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("Spoon.Dialog.PromptTransformationName.Message"));//"Please give this transformation a name before saving it in the database."
mb.setText(Messages.getString("Spoon.Dialog.PromptTransformationName.Title"));//"Transformation has no name."
mb.open();
}
ask=false;
answer = editTransformationProperties(transMeta);
}
if (answer && transMeta.getName()!=null && transMeta.getName().length()>0)
{
if (!rep.getUserInfo().isReadonly())
{
int response = SWT.YES;
if (transMeta.showReplaceWarning(rep))
{
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.ICON_QUESTION);
mb.setMessage(Messages.getString("Spoon.Dialog.PromptOverwriteTransformation.Message",transMeta.getName(),Const.CR));//"There already is a transformation called ["+transMeta.getName()+"] in the repository."+Const.CR+"Do you want to overwrite the transformation?"
mb.setText(Messages.getString("Spoon.Dialog.PromptOverwriteTransformation.Title"));//"Overwrite?"
response = mb.open();
}
boolean saved=false;
if (response == SWT.YES)
{
shell.setCursor(cursor_hourglass);
// Keep info on who & when this transformation was changed...
transMeta.setModifiedDate( new Value("MODIFIED_DATE", Value.VALUE_TYPE_DATE) );
transMeta.getModifiedDate().sysdate();
transMeta.setModifiedUser( rep.getUserInfo().getLogin() );
TransSaveProgressDialog tspd = new TransSaveProgressDialog(shell, rep, transMeta);
if (tspd.open())
{
saved=true;
if (!props.getSaveConfirmation())
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell,
Messages.getString("Spoon.Message.Warning.SaveOK"), //"Save OK!"
null,
Messages.getString("Spoon.Message.Warning.TransformationWasStored"),//"This transformation was stored in repository"
MessageDialog.QUESTION,
new String[] { Messages.getString("Spoon.Message.Warning.OK") },//"OK!"
0,
Messages.getString("Spoon.Message.Warning.NotShowThisMessage"),//"Don't show this message again."
props.getSaveConfirmation()
);
md.open();
props.setSaveConfirmation(md.getToggleState());
}
// Handle last opened files...
props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, transMeta.getName(), transMeta.getDirectory().getPath(), true, getRepositoryName());
saveSettings();
addMenuLast();
setShellText();
}
shell.setCursor(null);
}
return saved;
}
else
{
MessageBox mb = new MessageBox(shell, SWT.CLOSE | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("Spoon.Dialog.OnlyreadRepository.Message"));//"Sorry, the user you're logged on with, can only read from the repository"
mb.setText(Messages.getString("Spoon.Dialog.OnlyreadRepository.Title"));//"Transformation not saved!"
mb.open();
}
}
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("Spoon.Dialog.NoRepositoryConnection.Message"));//"There is no repository connection available."
mb.setText(Messages.getString("Spoon.Dialog.NoRepositoryConnection.Title"));//"No repository available."
mb.open();
}
return false;
}
public boolean saveFileAs()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null) return saveTransFileAs(transMeta);
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null) return saveJobFileAs(jobMeta);
return false;
}
public boolean saveTransFileAs(TransMeta transMeta)
{
boolean saved=false;
log.logBasic(toString(), Messages.getString("Spoon.Log.SaveAs"));//"Save as..."
if (rep!=null)
{
transMeta.setID(-1L);
saved=saveTransRepository(transMeta, true);
renameTabs();
}
else
{
saved=saveTransXMLFile(transMeta);
renameTabs();
}
refreshTree();
return saved;
}
private void loadTransSharedObjects(TransMeta transMeta)
{
try
{
transMeta.readSharedObjects(rep);
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", makeGraphTabName(transMeta)), e);
}
}
private boolean saveTransSharedObjects(TransMeta transMeta)
{
try
{
transMeta.saveSharedObjects();
return true;
}
catch(Exception e)
{
log.logError(toString(), "Unable to save shared ojects: "+e.toString());
return false;
}
}
private void loadJobSharedObjects(JobMeta jobMeta)
{
try
{
jobMeta.readSharedObjects(rep);
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", makeJobGraphTabName(jobMeta)), e);
}
}
private boolean saveJobSharedObjects(JobMeta jobMeta)
{
try
{
jobMeta.saveSharedObjects();
return true;
}
catch(Exception e)
{
log.logError(toString(), "Unable to save shared ojects: "+e.toString());
return false;
}
}
private boolean saveXMLFile()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null) return saveTransXMLFile(transMeta);
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null) return saveJobXMLFile(jobMeta);
return false;
}
private boolean saveTransXMLFile(TransMeta transMeta)
{
boolean saved=false;
FileDialog dialog = new FileDialog(shell, SWT.SAVE);
dialog.setFilterExtensions(Const.STRING_TRANS_FILTER_EXT);
dialog.setFilterNames(Const.STRING_TRANS_FILTER_NAMES);
String fname = dialog.open();
if (fname!=null)
{
// Is the filename ending on .ktr, .xml?
boolean ending=false;
for (int i=0;i<Const.STRING_TRANS_FILTER_EXT.length-1;i++)
{
if (fname.endsWith(Const.STRING_TRANS_FILTER_EXT[i].substring(1)))
{
ending=true;
}
}
if (fname.endsWith(Const.STRING_TRANS_DEFAULT_EXT)) ending=true;
if (!ending)
{
fname+=Const.STRING_TRANS_DEFAULT_EXT;
}
// See if the file already exists...
File f = new File(fname);
int id = SWT.YES;
if (f.exists())
{
MessageBox mb = new MessageBox(shell, SWT.NO | SWT.YES | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("Spoon.Dialog.PromptOverwriteFile.Message"));//"This file already exists. Do you want to overwrite it?"
mb.setText(Messages.getString("Spoon.Dialog.PromptOverwriteFile.Title"));//"This file already exists!"
id = mb.open();
}
if (id==SWT.YES)
{
saved=save(transMeta, fname);
transMeta.setFilename(fname);
}
}
return saved;
}
private boolean save(TransMeta transMeta, String fname)
{
boolean saved = false;
String xml = XMLHandler.getXMLHeader() + transMeta.getXML();
try
{
DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File(fname)));
dos.write(xml.getBytes(Const.XML_ENCODING));
dos.close();
saved=true;
// Handle last opened files...
props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, fname, null, false, null);
saveSettings();
addMenuLast();
transMeta.clearChanged();
setShellText();
log.logDebug(toString(), Messages.getString("Spoon.Log.FileWritten")+" ["+fname+"]"); //"File written to
}
catch(Exception e)
{
log.logDebug(toString(), Messages.getString("Spoon.Log.ErrorOpeningFileForWriting")+e.toString());//"Error opening file for writing! --> "
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("Spoon.Dialog.ErrorSavingFile.Message")+Const.CR+e.toString());//"Error saving file:"
mb.setText(Messages.getString("Spoon.Dialog.ErrorSavingFile.Title"));//"ERROR"
mb.open();
}
return saved;
}
public void helpAbout()
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION | SWT.CENTER);
String mess = Messages.getString("System.ProductInfo")+Const.VERSION+Const.CR+Const.CR+Const.CR;//Kettle - Spoon version
mess+=Messages.getString("System.CompanyInfo")+Const.CR;
mess+=" "+Messages.getString("System.ProductWebsiteUrl")+Const.CR; //(c) 2001-2004 i-Bridge bvba www.kettle.be
mess+=Const.CR;
mess+=Const.CR;
mess+=Const.CR;
mess+=" Build version : "+BuildVersion.getInstance().getVersion()+Const.CR;
mess+=" Build date : "+BuildVersion.getInstance().getBuildDate()+Const.CR;
mb.setMessage(mess);
mb.setText(APP_NAME);
mb.open();
}
public void editUnselectAll(TransMeta transMeta)
{
transMeta.unselectAll();
// spoongraph.redraw();
}
public void editSelectAll(TransMeta transMeta)
{
transMeta.selectAll();
// spoongraph.redraw();
}
public void editOptions()
{
EnterOptionsDialog eod = new EnterOptionsDialog(shell, props);
if (eod.open()!=null)
{
props.saveProps();
loadSettings();
changeLooks();
MessageBox mb = new MessageBox(shell, SWT.ICON_INFORMATION);
mb.setMessage(Messages.getString("Spoon.Dialog.PleaseRestartApplication.Message"));
mb.setText(Messages.getString("Spoon.Dialog.PleaseRestartApplication.Title"));
mb.open();
}
}
/**
* Refresh the object selection tree (on the left of the screen)
* @param complete true refreshes the complete tree, false tries to do a differential update to avoid flickering.
*/
public void refreshTree()
{
if (shell.isDisposed()) return;
GUIResource guiResource = GUIResource.getInstance();
// get a list of transformations from the transformation map
Collection transformations = transformationMap.values();
TransMeta[] transMetas = (TransMeta[]) transformations.toArray(new TransMeta[transformations.size()]);
// get a list of jobs from the job map
Collection jobs = jobMap.values();
JobMeta[] jobMetas = (JobMeta[]) jobs.toArray(new JobMeta[jobs.size()]);
// Refresh the content of the tree for those transformations
//
// First remove the old ones.
tiTrans.removeAll();
tiJobs.removeAll();
// Now add the data back
//
for (int t=0;t<transMetas.length;t++)
{
TransMeta transMeta = transMetas[t];
// Add a tree item with the name of transformation
//
TreeItem tiTransName = new TreeItem(tiTrans, SWT.NONE);
String name = makeGraphTabName(transMeta);
if (Const.isEmpty(name)) name = STRING_TRANS_NO_NAME;
tiTransName.setText(name);
tiTransName.setImage(guiResource.getImageBol());
///////////////////////////////////////////////////////
//
// Now add the database connections
//
TreeItem tiDbTitle = new TreeItem(tiTransName, SWT.NONE);
tiDbTitle.setText(STRING_CONNECTIONS);
tiDbTitle.setImage(guiResource.getImageConnection());
// Draw the connections themselves below it.
for (int i=0;i<transMeta.nrDatabases();i++)
{
DatabaseMeta databaseMeta = transMeta.getDatabase(i);
TreeItem tiDb = new TreeItem(tiDbTitle, SWT.NONE);
tiDb.setText(databaseMeta.getName());
if (databaseMeta.isShared()) tiDb.setFont(guiResource.getFontBold());
tiDb.setImage(guiResource.getImageConnection());
}
///////////////////////////////////////////////////////
//
// The steps
//
TreeItem tiStepTitle = new TreeItem(tiTransName, SWT.NONE);
tiStepTitle.setText(STRING_STEPS);
tiStepTitle.setImage(guiResource.getImageBol());
// Put the steps below it.
for (int i=0;i<transMeta.nrSteps();i++)
{
StepMeta stepMeta = transMeta.getStep(i);
TreeItem tiStep = new TreeItem(tiStepTitle, SWT.NONE);
tiStep.setText(stepMeta.getName());
if (stepMeta.isShared()) tiStep.setFont(guiResource.getFontBold());
if (!stepMeta.isDrawn()) tiStep.setForeground(guiResource.getColorGray());
tiStep.setImage(guiResource.getImageBol());
}
///////////////////////////////////////////////////////
//
// The hops
//
TreeItem tiHopTitle = new TreeItem(tiTransName, SWT.NONE);
tiHopTitle.setText(STRING_HOPS);
tiHopTitle.setImage(guiResource.getImageHop());
// Put the steps below it.
for (int i=0;i<transMeta.nrTransHops();i++)
{
TransHopMeta hopMeta = transMeta.getTransHop(i);
TreeItem tiHop = new TreeItem(tiHopTitle, SWT.NONE);
tiHop.setText(hopMeta.toString());
tiHop.setImage(guiResource.getImageHop());
}
///////////////////////////////////////////////////////
//
// The partitions
//
TreeItem tiPartitionTitle = new TreeItem(tiTransName, SWT.NONE);
tiPartitionTitle.setText(STRING_PARTITIONS);
tiPartitionTitle.setImage(guiResource.getImageConnection());
// Put the steps below it.
for (int i=0;i<transMeta.getPartitionSchemas().size();i++)
{
PartitionSchema partitionSchema = (PartitionSchema) transMeta.getPartitionSchemas().get(i);
TreeItem tiPartition = new TreeItem(tiPartitionTitle, SWT.NONE);
tiPartition.setText(partitionSchema.getName());
tiPartition.setImage(guiResource.getImageBol());
if (partitionSchema.isShared()) tiPartition.setFont(guiResource.getFontBold());
}
///////////////////////////////////////////////////////
//
// The slaves
//
TreeItem tiSlaveTitle = new TreeItem(tiTransName, SWT.NONE);
tiSlaveTitle.setText(STRING_SLAVES);
tiSlaveTitle.setImage(guiResource.getImageBol());
// Put the steps below it.
for (int i=0;i<transMeta.getSlaveServers().size();i++)
{
SlaveServer slaveServer = (SlaveServer) transMeta.getSlaveServers().get(i);
TreeItem tiSlave = new TreeItem(tiSlaveTitle, SWT.NONE);
tiSlave.setText(slaveServer.getName());
tiSlave.setImage(guiResource.getImageBol());
if (slaveServer.isShared()) tiSlave.setFont(guiResource.getFontBold());
}
///////////////////////////////////////////////////////
//
// The clusters
//
TreeItem tiClusterTitle = new TreeItem(tiTransName, SWT.NONE);
tiClusterTitle.setText(STRING_CLUSTERS);
tiClusterTitle.setImage(guiResource.getImageBol());
// Put the steps below it.
for (int i=0;i<transMeta.getClusterSchemas().size();i++)
{
ClusterSchema clusterSchema = (ClusterSchema) transMeta.getClusterSchemas().get(i);
TreeItem tiCluster = new TreeItem(tiClusterTitle, SWT.NONE);
tiCluster.setText(clusterSchema.toString());
tiCluster.setImage(guiResource.getImageBol());
if (clusterSchema.isShared()) tiCluster.setFont(guiResource.getFontBold());
}
}
// Now add the jobs
//
for (int t=0;t<jobMetas.length;t++)
{
JobMeta jobMeta = jobMetas[t];
// Add a tree item with the name of job
//
TreeItem tiJobName = new TreeItem(tiJobs, SWT.NONE);
String name = makeJobGraphTabName(jobMeta);
if (Const.isEmpty(name)) name = STRING_JOB_NO_NAME;
tiJobName.setText(name);
tiJobName.setImage(guiResource.getImageBol());
///////////////////////////////////////////////////////
//
// Now add the database connections
//
TreeItem tiDbTitle = new TreeItem(tiJobName, SWT.NONE);
tiDbTitle.setText(STRING_CONNECTIONS);
tiDbTitle.setImage(guiResource.getImageConnection());
// Draw the connections themselves below it.
for (int i=0;i<jobMeta.nrDatabases();i++)
{
DatabaseMeta databaseMeta = jobMeta.getDatabase(i);
TreeItem tiDb = new TreeItem(tiDbTitle, SWT.NONE);
tiDb.setText(databaseMeta.getName());
if (databaseMeta.isShared()) tiDb.setFont(guiResource.getFontBold());
tiDb.setImage(guiResource.getImageConnection());
}
///////////////////////////////////////////////////////
//
// The job entries
//
TreeItem tiJobEntriesTitle = new TreeItem(tiJobName, SWT.NONE);
tiJobEntriesTitle.setText(STRING_JOB_ENTRIES);
tiJobEntriesTitle.setImage(guiResource.getImageBol());
// Put the steps below it.
for (int i=0;i<jobMeta.nrJobEntries();i++)
{
JobEntryCopy jobEntry = jobMeta.getJobEntry(i);
TreeItem tiJobEntry = Const.findTreeItem(tiJobEntriesTitle, jobEntry.getName());
if (tiJobEntry!=null) continue; // only show it once
tiJobEntry = new TreeItem(tiJobEntriesTitle, SWT.NONE);
tiJobEntry.setText(jobEntry.getName());
// if (jobEntry.isShared()) tiStep.setFont(guiResource.getFontBold()); TODO: allow job entries to be shared as well...
if (jobEntry.isStart())
{
tiJobEntry.setImage(GUIResource.getInstance().getImageStart());
}
else
if (jobEntry.isDummy())
{
tiJobEntry.setImage(GUIResource.getInstance().getImageDummy());
}
else
{
Image image = (Image)GUIResource.getInstance().getImagesJobentriesSmall().get(jobEntry.getTypeDesc());
tiJobEntry.setImage(image);
}
}
}
// Set the expanded state of the complete tree.
TreeMemory.setExpandedFromMemory(selectionTree, STRING_SPOON_MAIN_TREE);
selectionTree.setFocus();
setShellText();
}
public String getActiveTabText()
{
if (tabfolder.getSelection()==null) return null;
return tabfolder.getSelection().getText();
}
public void refreshGraph()
{
if (shell.isDisposed()) return;
String tabText = getActiveTabText();
if (tabText==null) return;
TabMapEntry tabMapEntry = (TabMapEntry) tabMap.get(tabText);
if (tabMapEntry.getObject() instanceof SpoonGraph)
{
SpoonGraph spoonGraph = (SpoonGraph) tabMapEntry.getObject();
spoonGraph.redraw();
}
if (tabMapEntry.getObject() instanceof ChefGraph)
{
ChefGraph chefGraph = (ChefGraph) tabMapEntry.getObject();
chefGraph.redraw();
}
setShellText();
}
public void refreshHistory()
{
final SpoonHistory spoonHistory = getActiveSpoonHistory();
if (spoonHistory!=null)
{
spoonHistory.markRefreshNeeded();
}
}
public StepMeta newStep(TransMeta transMeta)
{
return newStep(transMeta, true, true);
}
public StepMeta newStep(TransMeta transMeta, boolean openit, boolean rename)
{
if (transMeta==null) return null;
TreeItem ti[] = selectionTree.getSelection();
StepMeta inf = null;
if (ti.length==1)
{
String steptype = ti[0].getText();
log.logDebug(toString(), Messages.getString("Spoon.Log.NewStep")+steptype);//"New step: "
inf = newStep(transMeta, steptype, steptype, openit, rename);
}
return inf;
}
/**
* Allocate new step, optionally open and rename it.
*
* @param name Name of the new step
* @param description Description of the type of step
* @param openit Open the dialog for this step?
* @param rename Rename this step?
*
* @return The newly created StepMeta object.
*
*/
public StepMeta newStep(TransMeta transMeta, String name, String description, boolean openit, boolean rename)
{
StepMeta inf = null;
// See if we need to rename the step to avoid doubles!
if (rename && transMeta.findStep(name)!=null)
{
int i=2;
String newname = name+" "+i;
while (transMeta.findStep(newname)!=null)
{
i++;
newname = name+" "+i;
}
name=newname;
}
StepLoader steploader = StepLoader.getInstance();
StepPlugin stepPlugin = null;
try
{
stepPlugin = steploader.findStepPluginWithDescription(description);
if (stepPlugin!=null)
{
StepMetaInterface info = BaseStep.getStepInfo(stepPlugin, steploader);
info.setDefault();
if (openit)
{
StepDialogInterface dialog = info.getDialog(shell, info, transMeta, name);
name = dialog.open();
}
inf=new StepMeta(stepPlugin.getID()[0], name, info);
if (name!=null) // OK pressed in the dialog: we have a step-name
{
String newname=name;
StepMeta stepMeta = transMeta.findStep(newname);
int nr=2;
while (stepMeta!=null)
{
newname = name+" "+nr;
stepMeta = transMeta.findStep(newname);
nr++;
}
if (nr>2)
{
inf.setName(newname);
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(Messages.getString("Spoon.Dialog.ChangeStepname.Message",newname));//"This stepname already exists. Spoon changed the stepname to ["+newname+"]"
mb.setText(Messages.getString("Spoon.Dialog.ChangeStepname.Title"));//"Info!"
mb.open();
}
inf.setLocation(20, 20); // default location at (20,20)
transMeta.addStep(inf);
// Save for later:
// if openit is false: we drag&drop it onto the canvas!
if (openit)
{
addUndoNew(transMeta, new StepMeta[] { inf }, new int[] { transMeta.indexOfStep(inf) });
}
// Also store it in the pluginHistory list...
props.addPluginHistory(stepPlugin.getID()[0]);
refreshTree();
}
else
{
return null; // Cancel pressed in dialog.
}
setShellText();
}
}
catch(KettleException e)
{
String filename = stepPlugin.getErrorHelpFile();
if (stepPlugin!=null && filename!=null)
{
// OK, in stead of a normal error message, we give back the content of the error help file... (HTML)
try
{
StringBuffer content=new StringBuffer();
FileInputStream fis = new FileInputStream(new File(filename));
int ch = fis.read();
while (ch>=0)
{
content.append( (char)ch);
ch = fis.read();
}
ShowBrowserDialog sbd = new ShowBrowserDialog(shell, Messages.getString("Spoon.Dialog.ErrorHelpText.Title"), content.toString());//"Error help text"
sbd.open();
}
catch(Exception ex)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorShowingHelpText.Title"), Messages.getString("Spoon.Dialog.ErrorShowingHelpText.Message"), ex);//"Error showing help text"
}
}
else
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.UnableCreateNewStep.Title"),Messages.getString("Spoon.Dialog.UnableCreateNewStep.Message") , e);//"Error creating step" "I was unable to create a new step"
}
return null;
}
catch(Throwable e)
{
if (!shell.isDisposed()) new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorCreatingStep.Title"), Messages.getString("Spoon.Dialog.UnableCreateNewStep.Message"), new Exception(e));//"Error creating step"
return null;
}
return inf;
}
private void setTreeImages()
{
tiTrans.setImage(GUIResource.getInstance().getImageBol());
tiJobs.setImage(GUIResource.getInstance().getImageBol());
TreeItem tiBaseCat[]=tiTransBase.getItems();
for (int x=0;x<tiBaseCat.length;x++)
{
tiBaseCat[x].setImage(GUIResource.getInstance().getImageBol());
TreeItem ti[] = tiBaseCat[x].getItems();
for (int i=0;i<ti.length;i++)
{
TreeItem stepitem = ti[i];
String description = stepitem.getText();
StepLoader steploader = StepLoader.getInstance();
StepPlugin sp = steploader.findStepPluginWithDescription(description);
if (sp!=null)
{
Image stepimg = (Image)GUIResource.getInstance().getImagesStepsSmall().get(sp.getID()[0]);
if (stepimg!=null)
{
stepitem.setImage(stepimg);
}
}
}
}
}
public void setShellText()
{
if (shell.isDisposed()) return;
String fname = null;
String name = null;
long id = -1L;
ChangedFlagInterface changed = null;
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null)
{
changed = transMeta;
fname = transMeta.getFilename();
name = transMeta.getName();
id = transMeta.getID();
}
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null)
{
changed = jobMeta;
fname = jobMeta.getFilename();
name = jobMeta.getName();
id = jobMeta.getID();
}
String text = "";
if (rep!=null)
{
text+= APPL_TITLE+" - ["+getRepositoryName()+"] ";
}
else
{
text+= APPL_TITLE+" - ";
}
if (rep!=null && id>0)
{
if (Const.isEmpty(name))
{
text+=Messages.getString("Spoon.Various.NoName");//"[no name]"
}
else
{
text+=name;
}
}
else
{
if (!Const.isEmpty(fname))
{
text+=fname;
}
}
if (changed!=null && changed.hasChanged())
{
text+=" "+Messages.getString("Spoon.Various.Changed");
}
shell.setText(text);
enableMenus();
markTabsChanged();
}
public void enableMenus()
{
boolean enableTransMenu = getActiveTransformation()!=null;
boolean enableJobMenu = getActiveJob()!=null;
boolean enableRepositoryMenu = rep!=null;
// Only enable certain menu-items if we need to.
miFileSave.setEnabled(enableTransMenu || enableJobMenu);
miFileSaveAs.setEnabled(enableTransMenu || enableJobMenu);
miFileClose.setEnabled(enableTransMenu || enableJobMenu);
miFilePrint.setEnabled(enableTransMenu || enableJobMenu);
miEditUndo.setEnabled(enableTransMenu || enableJobMenu);
miEditRedo.setEnabled(enableTransMenu || enableJobMenu);
miEditUnselectAll.setEnabled(enableTransMenu);
miEditSelectAll.setEnabled(enableTransMenu);
miEditCopy.setEnabled(enableTransMenu);
miEditPaste.setEnabled(enableTransMenu);
// Transformations
miTransRun.setEnabled(enableTransMenu);
miTransPreview.setEnabled(enableTransMenu);
miTransCheck.setEnabled(enableTransMenu);
miTransImpact.setEnabled(enableTransMenu);
miTransSQL.setEnabled(enableTransMenu);
miLastImpact.setEnabled(enableTransMenu);
miLastCheck.setEnabled(enableTransMenu);
miLastPreview.setEnabled(enableTransMenu);
miTransCopy.setEnabled(enableTransMenu);
// miTransPaste.setEnabled(enableTransMenu);
miTransImage.setEnabled(enableTransMenu);
miTransDetails.setEnabled(enableTransMenu);
// Jobs
miJobRun.setEnabled(enableJobMenu);
miJobCopy.setEnabled(enableJobMenu);
miJobInfo.setEnabled(enableJobMenu);
miWizardNewConnection.setEnabled(enableTransMenu || enableJobMenu || enableRepositoryMenu);
miWizardCopyTable.setEnabled(enableTransMenu || enableJobMenu || enableRepositoryMenu);
miRepDisconnect.setEnabled(enableRepositoryMenu);
miRepExplore.setEnabled(enableRepositoryMenu);
miRepUser.setEnabled(enableRepositoryMenu);
// Do the bar as well
tiSQL.setEnabled(enableTransMenu || enableJobMenu);
tiImpact.setEnabled(enableTransMenu);
tiFileCheck.setEnabled(enableTransMenu);
tiFileReplay.setEnabled(enableTransMenu);
tiFilePreview.setEnabled(enableTransMenu);
tiFileRun.setEnabled(enableTransMenu || enableJobMenu);
tiFilePrint.setEnabled(enableTransMenu || enableJobMenu);
tiFileSaveAs.setEnabled(enableTransMenu || enableJobMenu);
tiFileSave.setEnabled(enableTransMenu || enableJobMenu);
// What steps & plugins to show?
refreshCoreObjectsTree();
}
private void markTabsChanged()
{
Collection c = tabMap.values();
for (Iterator iter = c.iterator(); iter.hasNext();)
{
TabMapEntry entry = (TabMapEntry) iter.next();
if (entry.getTabItem().isDisposed()) continue;
boolean changed = entry.getObject().hasContentChanged();
if (changed)
{
entry.getTabItem().setFont(GUIResource.getInstance().getFontBold());
}
else
{
entry.getTabItem().setFont(GUIResource.getInstance().getFontGraph());
}
}
}
private void printFile()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null)
{
printTransFile(transMeta);
}
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null)
{
printJobFile(jobMeta);
}
}
private void printTransFile(TransMeta transMeta)
{
SpoonGraph spoonGraph = getActiveSpoonGraph();
if (spoonGraph==null) return;
PrintSpool ps = new PrintSpool();
Printer printer = ps.getPrinter(shell);
// Create an image of the screen
Point max = transMeta.getMaximum();
Image img = spoonGraph.getTransformationImage(printer, max.x, max.y);
ps.printImage(shell, props, img);
img.dispose();
ps.dispose();
}
private void printJobFile(JobMeta jobMeta)
{
ChefGraph chefGraph = getActiveChefGraph();
if (chefGraph==null) return;
PrintSpool ps = new PrintSpool();
Printer printer = ps.getPrinter(shell);
// Create an image of the screen
Point max = jobMeta.getMaximum();
PaletteData pal = ps.getPaletteData();
ImageData imd = new ImageData(max.x, max.y, printer.getDepth(), pal);
Image img = new Image(printer, imd);
GC img_gc = new GC(img);
// Clear the background first, fill with background color...
img_gc.setForeground(GUIResource.getInstance().getColorBackground());
img_gc.fillRectangle(0,0,max.x, max.y);
// Draw the transformation...
chefGraph.drawJob(img_gc);
ps.printImage(shell, props, img);
img_gc.dispose();
img.dispose();
ps.dispose();
}
private SpoonGraph getActiveSpoonGraph()
{
TabMapEntry mapEntry = (TabMapEntry) tabMap.get(tabfolder.getSelection().getText());
if (mapEntry.getObject() instanceof SpoonGraph) return (SpoonGraph) mapEntry.getObject();
return null;
}
private ChefGraph getActiveChefGraph()
{
TabMapEntry mapEntry = (TabMapEntry) tabMap.get(tabfolder.getSelection().getText());
if (mapEntry.getObject() instanceof ChefGraph) return (ChefGraph) mapEntry.getObject();
return null;
}
/**
* @return the Log tab associated with the active transformation
*/
private SpoonLog getActiveSpoonLog()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta==null) return null; // nothing to work with.
return findSpoonLogOfTransformation(transMeta);
}
/**
* @return the Log tab associated with the active job
*/
private ChefLog getActiveJobLog()
{
JobMeta jobMeta = getActiveJob();
if (jobMeta==null) return null; // nothing to work with.
return findChefLogOfJob(jobMeta);
}
public SpoonGraph findSpoonGraphOfTransformation(TransMeta transMeta)
{
// Now loop over the entries in the tab-map
Collection collection = tabMap.values();
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (mapEntry.getObject() instanceof SpoonGraph)
{
SpoonGraph spoonGraph = (SpoonGraph) mapEntry.getObject();
if (spoonGraph.getTransMeta().equals(transMeta)) return spoonGraph;
}
}
return null;
}
public ChefGraph findChefGraphOfJob(JobMeta jobMeta)
{
// Now loop over the entries in the tab-map
Collection collection = tabMap.values();
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (mapEntry.getObject() instanceof ChefGraph)
{
ChefGraph chefGraph = (ChefGraph) mapEntry.getObject();
if (chefGraph.getJobMeta().equals(jobMeta)) return chefGraph;
}
}
return null;
}
public SpoonLog findSpoonLogOfTransformation(TransMeta transMeta)
{
// Now loop over the entries in the tab-map
Collection collection = tabMap.values();
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (mapEntry.getObject() instanceof SpoonLog)
{
SpoonLog spoonLog = (SpoonLog) mapEntry.getObject();
if (spoonLog.getTransMeta().equals(transMeta)) return spoonLog;
}
}
return null;
}
public ChefLog findChefLogOfJob(JobMeta jobMeta)
{
// Now loop over the entries in the tab-map
Collection collection = tabMap.values();
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (mapEntry.getObject() instanceof ChefLog)
{
ChefLog chefLog = (ChefLog) mapEntry.getObject();
if (chefLog.getJobMeta().equals(jobMeta)) return chefLog;
}
}
return null;
}
public SpoonHistory findSpoonHistoryOfTransformation(TransMeta transMeta)
{
if (transMeta==null) return null;
// Now loop over the entries in the tab-map
Collection collection = tabMap.values();
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (mapEntry.getObject() instanceof SpoonHistory)
{
SpoonHistory spoonHistory = (SpoonHistory) mapEntry.getObject();
if (spoonHistory.getTransMeta()!=null && spoonHistory.getTransMeta().equals(transMeta)) return spoonHistory;
}
}
return null;
}
public ChefHistory findChefHistoryOfJob(JobMeta jobMeta)
{
if (jobMeta==null) return null;
// Now loop over the entries in the tab-map
Collection collection = tabMap.values();
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (mapEntry.getObject() instanceof ChefHistory)
{
ChefHistory chefHistory = (ChefHistory) mapEntry.getObject();
if (chefHistory.getJobMeta()!=null && chefHistory.getJobMeta().equals(jobMeta)) return chefHistory;
}
}
return null;
}
/**
* @return the history tab associated with the active transformation
*/
private SpoonHistory getActiveSpoonHistory()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta==null) return null; // nothing to work with.
return findSpoonHistoryOfTransformation(transMeta);
}
/**
* @return The active TransMeta object by looking at the selected SpoonGraph, SpoonLog, SpoonHist
* If nothing valueable is selected, we return null
*/
public TransMeta getActiveTransformation()
{
if (tabfolder==null) return null;
CTabItem tabItem = tabfolder.getSelection();
if (tabItem==null) return null;
// What transformation is in the active tab?
// SpoonLog, SpoonGraph & SpoonHist contain the same transformation
//
TabMapEntry mapEntry = (TabMapEntry) tabMap.get(tabfolder.getSelection().getText());
TransMeta transMeta = null;
if (mapEntry.getObject() instanceof SpoonGraph) transMeta = ((SpoonGraph) mapEntry.getObject()).getTransMeta();
if (mapEntry.getObject() instanceof SpoonLog) transMeta = ((SpoonLog) mapEntry.getObject()).getTransMeta();
if (mapEntry.getObject() instanceof SpoonHistory) transMeta = ((SpoonHistory) mapEntry.getObject()).getTransMeta();
return transMeta;
}
/**
* @return The active JobMeta object by looking at the selected ChefGraph, ChefLog, ChefHist
* If nothing valueable is selected, we return null
*/
public JobMeta getActiveJob()
{
if (tabfolder==null) return null;
CTabItem tabItem = tabfolder.getSelection();
if (tabItem==null) return null;
// What job is in the active tab?
// ChefLog, ChefGraph & ChefHist contain the same job
//
TabMapEntry mapEntry = (TabMapEntry) tabMap.get(tabfolder.getSelection().getText());
JobMeta jobMeta = null;
if (mapEntry.getObject() instanceof ChefGraph) jobMeta = ((ChefGraph) mapEntry.getObject()).getJobMeta();
if (mapEntry.getObject() instanceof ChefLog) jobMeta = ((ChefLog) mapEntry.getObject()).getJobMeta();
if (mapEntry.getObject() instanceof ChefHistory) jobMeta = ((ChefHistory) mapEntry.getObject()).getJobMeta();
return jobMeta;
}
public UndoInterface getActiveUndoInterface()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null) return transMeta;
return getActiveJob();
}
public TransMeta findTransformation(String name)
{
return (TransMeta)transformationMap.get(name);
}
public JobMeta findJob(String name)
{
return (JobMeta)jobMap.get(name);
}
public TransMeta[] getLoadedTransformations()
{
List list = new ArrayList(transformationMap.values());
return (TransMeta[]) list.toArray(new TransMeta[list.size()]);
}
public JobMeta[] getLoadedJobs()
{
List list = new ArrayList(jobMap.values());
return (JobMeta[]) list.toArray(new JobMeta[list.size()]);
}
private boolean editTransformationProperties(TransMeta transMeta)
{
if (transMeta==null) return false;
TransDialog tid = new TransDialog(shell, SWT.NONE, transMeta, rep);
TransMeta ti = tid.open();
// In this case, load shared objects
//
if (tid.isSharedObjectsFileChanged())
{
loadTransSharedObjects(transMeta);
}
if (tid.isSharedObjectsFileChanged() || ti!=null)
{
try
{
transMeta.readSharedObjects(rep);
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", makeGraphTabName(transMeta)), e);
}
refreshTree();
renameTabs(); // cheap operation, might as will do it anyway
}
setShellText();
return ti!=null;
}
public void saveSettings()
{
WindowProperty winprop = new WindowProperty(shell);
winprop.setName(APPL_TITLE);
props.setScreen(winprop);
props.setLogLevel(log.getLogLevelDesc());
props.setLogFilter(log.getFilter());
props.setSashWeights(sashform.getWeights());
props.saveProps();
}
public void loadSettings()
{
log.setLogLevel(props.getLogLevel());
log.setFilter(props.getLogFilter());
// transMeta.setMaxUndo(props.getMaxUndo());
DBCache.getInstance().setActive(props.useDBCache());
}
public void changeLooks()
{
props.setLook(selectionTree);
props.setLook(tabfolder, Props.WIDGET_STYLE_TAB);
GUIResource.getInstance().reload();
refreshTree();
refreshGraph();
}
public void undoAction(UndoInterface undoInterface)
{
if (undoInterface==null) return;
TransAction ta = undoInterface.previousUndo();
if (ta==null) return;
setUndoMenu(undoInterface); // something changed: change the menu
if (undoInterface instanceof TransMeta) undoTransformationAction((TransMeta)undoInterface, ta);
if (undoInterface instanceof JobMeta) undoJobAction((JobMeta)undoInterface, ta);
// Put what we undo in focus
if (undoInterface instanceof TransMeta)
{
SpoonGraph spoonGraph = findSpoonGraphOfTransformation((TransMeta)undoInterface);
spoonGraph.forceFocus();
}
if (undoInterface instanceof JobMeta)
{
ChefGraph chefGraph = findChefGraphOfJob((JobMeta)undoInterface);
chefGraph.forceFocus();
}
}
private void undoTransformationAction(TransMeta transMeta, TransAction transAction)
{
switch(transAction.getType())
{
//
// NEW
//
// We created a new step : undo this...
case TransAction.TYPE_ACTION_NEW_STEP:
// Delete the step at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeStep(idx);
}
refreshTree();
refreshGraph();
break;
// We created a new connection : undo this...
case TransAction.TYPE_ACTION_NEW_CONNECTION:
// Delete the connection at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeDatabase(idx);
}
refreshTree();
refreshGraph();
break;
// We created a new note : undo this...
case TransAction.TYPE_ACTION_NEW_NOTE:
// Delete the note at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeNote(idx);
}
refreshTree();
refreshGraph();
break;
// We created a new hop : undo this...
case TransAction.TYPE_ACTION_NEW_HOP:
// Delete the hop at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeTransHop(idx);
}
refreshTree();
refreshGraph();
break;
// We created a new slave : undo this...
case TransAction.TYPE_ACTION_NEW_SLAVE:
// Delete the slave at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.getSlaveServers().remove(idx);
}
refreshTree();
refreshGraph();
break;
// We created a new slave : undo this...
case TransAction.TYPE_ACTION_NEW_CLUSTER:
// Delete the slave at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.getClusterSchemas().remove(idx);
}
refreshTree();
refreshGraph();
break;
//
// DELETE
//
// We delete a step : undo this...
case TransAction.TYPE_ACTION_DELETE_STEP:
// un-Delete the step at correct location: re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
StepMeta stepMeta = (StepMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addStep(idx, stepMeta);
}
refreshTree();
refreshGraph();
break;
// We deleted a connection : undo this...
case TransAction.TYPE_ACTION_DELETE_CONNECTION:
// re-insert the connection at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
DatabaseMeta ci = (DatabaseMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addDatabase(idx, ci);
}
refreshTree();
refreshGraph();
break;
// We delete new note : undo this...
case TransAction.TYPE_ACTION_DELETE_NOTE:
// re-insert the note at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
NotePadMeta ni = (NotePadMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addNote(idx, ni);
}
refreshTree();
refreshGraph();
break;
// We deleted a hop : undo this...
case TransAction.TYPE_ACTION_DELETE_HOP:
// re-insert the hop at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
TransHopMeta hi = (TransHopMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
// Build a new hop:
StepMeta from = transMeta.findStep(hi.getFromStep().getName());
StepMeta to = transMeta.findStep(hi.getToStep().getName());
TransHopMeta hinew = new TransHopMeta(from, to);
transMeta.addTransHop(idx, hinew);
}
refreshTree();
refreshGraph();
break;
//
// CHANGE
//
// We changed a step : undo this...
case TransAction.TYPE_ACTION_CHANGE_STEP:
// Delete the current step, insert previous version.
for (int i=0;i<transAction.getCurrent().length;i++)
{
StepMeta prev = (StepMeta) ((StepMeta)transAction.getPrevious()[i]).clone();
int idx = transAction.getCurrentIndex()[i];
transMeta.getStep(idx).replaceMeta(prev);
}
refreshTree();
refreshGraph();
break;
// We changed a connection : undo this...
case TransAction.TYPE_ACTION_CHANGE_CONNECTION:
// Delete & re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
DatabaseMeta prev = (DatabaseMeta)transAction.getPrevious()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.getDatabase(idx).replaceMeta((DatabaseMeta) prev.clone());
}
refreshTree();
refreshGraph();
break;
// We changed a note : undo this...
case TransAction.TYPE_ACTION_CHANGE_NOTE:
// Delete & re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeNote(idx);
NotePadMeta prev = (NotePadMeta)transAction.getPrevious()[i];
transMeta.addNote(idx, (NotePadMeta) prev.clone());
}
refreshTree();
refreshGraph();
break;
// We changed a hop : undo this...
case TransAction.TYPE_ACTION_CHANGE_HOP:
// Delete & re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
TransHopMeta prev = (TransHopMeta)transAction.getPrevious()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.removeTransHop(idx);
transMeta.addTransHop(idx, (TransHopMeta) prev.clone());
}
refreshTree();
refreshGraph();
break;
//
// POSITION
//
// The position of a step has changed: undo this...
case TransAction.TYPE_ACTION_POSITION_STEP:
// Find the location of the step:
for (int i = 0; i < transAction.getCurrentIndex().length; i++)
{
StepMeta stepMeta = transMeta.getStep(transAction.getCurrentIndex()[i]);
stepMeta.setLocation(transAction.getPreviousLocation()[i]);
}
refreshGraph();
break;
// The position of a note has changed: undo this...
case TransAction.TYPE_ACTION_POSITION_NOTE:
for (int i=0;i<transAction.getCurrentIndex().length;i++)
{
int idx = transAction.getCurrentIndex()[i];
NotePadMeta npi = transMeta.getNote(idx);
Point prev = transAction.getPreviousLocation()[i];
npi.setLocation(prev);
}
refreshGraph();
break;
default: break;
}
// OK, now check if we need to do this again...
if (transMeta.viewNextUndo()!=null)
{
if (transMeta.viewNextUndo().getNextAlso()) undoAction(transMeta);
}
}
private void undoJobAction(JobMeta jobMeta, TransAction transAction)
{
switch(transAction.getType())
{
//
// NEW
//
// We created a new entry : undo this...
case TransAction.TYPE_ACTION_NEW_JOB_ENTRY:
// Delete the entry at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i=idx.length-1;i>=0;i--) jobMeta.removeJobEntry(idx[i]);
refreshTree();
refreshGraph();
}
break;
// We created a new note : undo this...
case TransAction.TYPE_ACTION_NEW_NOTE:
// Delete the note at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i=idx.length-1;i>=0;i--) jobMeta.removeNote(idx[i]);
refreshTree();
refreshGraph();
}
break;
// We created a new hop : undo this...
case TransAction.TYPE_ACTION_NEW_JOB_HOP:
// Delete the hop at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i=idx.length-1;i>=0;i--) jobMeta.removeJobHop(idx[i]);
refreshTree();
refreshGraph();
}
break;
//
// DELETE
//
// We delete an entry : undo this...
case TransAction.TYPE_ACTION_DELETE_STEP:
// un-Delete the entry at correct location: re-insert
{
JobEntryCopy ce[] = (JobEntryCopy[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<ce.length;i++) jobMeta.addJobEntry(idx[i], ce[i]);
refreshTree();
refreshGraph();
}
break;
// We delete new note : undo this...
case TransAction.TYPE_ACTION_DELETE_NOTE:
// re-insert the note at correct location:
{
NotePadMeta ni[] = (NotePadMeta[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++) jobMeta.addNote(idx[i], ni[i]);
refreshTree();
refreshGraph();
}
break;
// We deleted a new hop : undo this...
case TransAction.TYPE_ACTION_DELETE_JOB_HOP:
// re-insert the hop at correct location:
{
JobHopMeta hi[] = (JobHopMeta[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<hi.length;i++)
{
jobMeta.addJobHop(idx[i], hi[i]);
}
refreshTree();
refreshGraph();
}
break;
//
// CHANGE
//
// We changed a job entry: undo this...
case TransAction.TYPE_ACTION_CHANGE_JOB_ENTRY:
// Delete the current job entry, insert previous version.
{
for (int i=0;i<transAction.getPrevious().length;i++)
{
JobEntryCopy copy = (JobEntryCopy) ((JobEntryCopy)transAction.getPrevious()[i]).clone();
jobMeta.getJobEntry(transAction.getCurrentIndex()[i]).replaceMeta(copy);
}
refreshTree();
refreshGraph();
}
break;
// We changed a note : undo this...
case TransAction.TYPE_ACTION_CHANGE_NOTE:
// Delete & re-insert
{
NotePadMeta prev[] = (NotePadMeta[])transAction.getPrevious();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++)
{
jobMeta.removeNote(idx[i]);
jobMeta.addNote(idx[i], prev[i]);
}
refreshTree();
refreshGraph();
}
break;
// We changed a hop : undo this...
case TransAction.TYPE_ACTION_CHANGE_JOB_HOP:
// Delete & re-insert
{
JobHopMeta prev[] = (JobHopMeta[])transAction.getPrevious();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++)
{
jobMeta.removeJobHop(idx[i]);
jobMeta.addJobHop(idx[i], prev[i]);
}
refreshTree();
refreshGraph();
}
break;
//
// POSITION
//
// The position of a step has changed: undo this...
case TransAction.TYPE_ACTION_POSITION_JOB_ENTRY:
// Find the location of the step:
{
int idx[] = transAction.getCurrentIndex();
Point p[] = transAction.getPreviousLocation();
for (int i = 0; i < p.length; i++)
{
JobEntryCopy entry = jobMeta.getJobEntry(idx[i]);
entry.setLocation(p[i]);
}
refreshGraph();
}
break;
// The position of a note has changed: undo this...
case TransAction.TYPE_ACTION_POSITION_NOTE:
int idx[] = transAction.getCurrentIndex();
Point prev[] = transAction.getPreviousLocation();
for (int i=0;i<idx.length;i++)
{
NotePadMeta npi = jobMeta.getNote(idx[i]);
npi.setLocation(prev[i]);
}
refreshGraph();
break;
default: break;
}
}
public void redoAction(UndoInterface undoInterface)
{
if (undoInterface==null) return;
TransAction ta = undoInterface.nextUndo();
if (ta==null) return;
setUndoMenu(undoInterface); // something changed: change the menu
if (undoInterface instanceof TransMeta) redoTransformationAction((TransMeta)undoInterface, ta);
if (undoInterface instanceof JobMeta) redoJobAction((JobMeta)undoInterface, ta);
// Put what we redo in focus
if (undoInterface instanceof TransMeta)
{
SpoonGraph spoonGraph = findSpoonGraphOfTransformation((TransMeta)undoInterface);
spoonGraph.forceFocus();
}
if (undoInterface instanceof JobMeta)
{
ChefGraph chefGraph = findChefGraphOfJob((JobMeta)undoInterface);
chefGraph.forceFocus();
}
}
private void redoTransformationAction(TransMeta transMeta, TransAction transAction)
{
switch(transAction.getType())
{
//
// NEW
//
case TransAction.TYPE_ACTION_NEW_STEP:
// re-delete the step at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
StepMeta stepMeta = (StepMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addStep(idx, stepMeta);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_NEW_CONNECTION:
// re-insert the connection at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
DatabaseMeta ci = (DatabaseMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addDatabase(idx, ci);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_NEW_NOTE:
// re-insert the note at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
NotePadMeta ni = (NotePadMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addNote(idx, ni);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_NEW_HOP:
// re-insert the hop at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
TransHopMeta hi = (TransHopMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addTransHop(idx, hi);
refreshTree();
refreshGraph();
}
break;
//
// DELETE
//
case TransAction.TYPE_ACTION_DELETE_STEP:
// re-remove the step at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeStep(idx);
}
refreshTree();
refreshGraph();
break;
case TransAction.TYPE_ACTION_DELETE_CONNECTION:
// re-remove the connection at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeDatabase(idx);
}
refreshTree();
refreshGraph();
break;
case TransAction.TYPE_ACTION_DELETE_NOTE:
// re-remove the note at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeNote(idx);
}
refreshTree();
refreshGraph();
break;
case TransAction.TYPE_ACTION_DELETE_HOP:
// re-remove the hop at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeTransHop(idx);
}
refreshTree();
refreshGraph();
break;
//
// CHANGE
//
// We changed a step : undo this...
case TransAction.TYPE_ACTION_CHANGE_STEP:
// Delete the current step, insert previous version.
for (int i=0;i<transAction.getCurrent().length;i++)
{
StepMeta stepMeta = (StepMeta) ((StepMeta)transAction.getCurrent()[i]).clone();
transMeta.getStep(transAction.getCurrentIndex()[i]).replaceMeta(stepMeta);
}
refreshTree();
refreshGraph();
break;
// We changed a connection : undo this...
case TransAction.TYPE_ACTION_CHANGE_CONNECTION:
// Delete & re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
DatabaseMeta databaseMeta = (DatabaseMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.getDatabase(idx).replaceMeta((DatabaseMeta) databaseMeta.clone());
}
refreshTree();
refreshGraph();
break;
// We changed a note : undo this...
case TransAction.TYPE_ACTION_CHANGE_NOTE:
// Delete & re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
NotePadMeta ni = (NotePadMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.removeNote(idx);
transMeta.addNote(idx, (NotePadMeta) ni.clone());
}
refreshTree();
refreshGraph();
break;
// We changed a hop : undo this...
case TransAction.TYPE_ACTION_CHANGE_HOP:
// Delete & re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
TransHopMeta hi = (TransHopMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.removeTransHop(idx);
transMeta.addTransHop(idx, (TransHopMeta) hi.clone());
}
refreshTree();
refreshGraph();
break;
//
// CHANGE POSITION
//
case TransAction.TYPE_ACTION_POSITION_STEP:
for (int i=0;i<transAction.getCurrentIndex().length;i++)
{
// Find & change the location of the step:
StepMeta stepMeta = transMeta.getStep(transAction.getCurrentIndex()[i]);
stepMeta.setLocation(transAction.getCurrentLocation()[i]);
}
refreshGraph();
break;
case TransAction.TYPE_ACTION_POSITION_NOTE:
for (int i=0;i<transAction.getCurrentIndex().length;i++)
{
int idx = transAction.getCurrentIndex()[i];
NotePadMeta npi = transMeta.getNote(idx);
Point curr = transAction.getCurrentLocation()[i];
npi.setLocation(curr);
}
refreshGraph();
break;
default: break;
}
// OK, now check if we need to do this again...
if (transMeta.viewNextUndo()!=null)
{
if (transMeta.viewNextUndo().getNextAlso()) redoAction(transMeta);
}
}
private void redoJobAction(JobMeta jobMeta, TransAction transAction)
{
switch(transAction.getType())
{
//
// NEW
//
case TransAction.TYPE_ACTION_NEW_JOB_ENTRY:
// re-delete the entry at correct location:
{
JobEntryCopy si[] = (JobEntryCopy[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++) jobMeta.addJobEntry(idx[i], si[i]);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_NEW_NOTE:
// re-insert the note at correct location:
{
NotePadMeta ni[] = (NotePadMeta[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++) jobMeta.addNote(idx[i], ni[i]);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_NEW_JOB_HOP:
// re-insert the hop at correct location:
{
JobHopMeta hi[] = (JobHopMeta[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++) jobMeta.addJobHop(idx[i], hi[i]);
refreshTree();
refreshGraph();
}
break;
//
// DELETE
//
case TransAction.TYPE_ACTION_DELETE_JOB_ENTRY:
// re-remove the entry at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i=idx.length-1;i>=0;i--) jobMeta.removeJobEntry(idx[i]);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_DELETE_NOTE:
// re-remove the note at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i=idx.length-1;i>=0;i--) jobMeta.removeNote(idx[i]);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_DELETE_JOB_HOP:
// re-remove the hop at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i=idx.length-1;i>=0;i--) jobMeta.removeJobHop(idx[i]);
refreshTree();
refreshGraph();
}
break;
//
// CHANGE
//
// We changed a step : undo this...
case TransAction.TYPE_ACTION_CHANGE_JOB_ENTRY:
// replace with "current" version.
{
for (int i=0;i<transAction.getCurrent().length;i++)
{
JobEntryCopy copy = (JobEntryCopy) ((JobEntryCopy)(transAction.getCurrent()[i])).clone_deep();
jobMeta.getJobEntry(transAction.getCurrentIndex()[i]).replaceMeta(copy);
}
refreshTree();
refreshGraph();
}
break;
// We changed a note : undo this...
case TransAction.TYPE_ACTION_CHANGE_NOTE:
// Delete & re-insert
{
NotePadMeta ni[] = (NotePadMeta[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++)
{
jobMeta.removeNote(idx[i]);
jobMeta.addNote(idx[i], ni[i]);
}
refreshTree();
refreshGraph();
}
break;
// We changed a hop : undo this...
case TransAction.TYPE_ACTION_CHANGE_JOB_HOP:
// Delete & re-insert
{
JobHopMeta hi[] = (JobHopMeta[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++)
{
jobMeta.removeJobHop(idx[i]);
jobMeta.addJobHop(idx[i], hi[i]);
}
refreshTree();
refreshGraph();
}
break;
//
// CHANGE POSITION
//
case TransAction.TYPE_ACTION_POSITION_JOB_ENTRY:
{
// Find the location of the step:
int idx[] = transAction.getCurrentIndex();
Point p[] = transAction.getCurrentLocation();
for (int i = 0; i < p.length; i++)
{
JobEntryCopy entry = jobMeta.getJobEntry(idx[i]);
entry.setLocation(p[i]);
}
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_POSITION_NOTE:
{
int idx[] = transAction.getCurrentIndex();
Point curr[] = transAction.getCurrentLocation();
for (int i=0;i<idx.length;i++)
{
NotePadMeta npi = jobMeta.getNote(idx[i]);
npi.setLocation(curr[i]);
}
refreshGraph();
}
break;
default: break;
}
}
public void setUndoMenu(UndoInterface undoInterface)
{
if (shell.isDisposed()) return;
TransAction prev = undoInterface!=null ? undoInterface.viewThisUndo() : null;
TransAction next = undoInterface!=null ? undoInterface.viewNextUndo() : null;
if (prev!=null)
{
miEditUndo.setEnabled(true);
miEditUndo.setText(Messages.getString("Spoon.Menu.Undo.Available", prev.toString()));//"Undo : "+prev.toString()+" \tCTRL-Z"
}
else
{
miEditUndo.setEnabled(false);
miEditUndo.setText(Messages.getString("Spoon.Menu.Undo.NotAvailable"));//"Undo : not available \tCTRL-Z"
}
if (next!=null)
{
miEditRedo.setEnabled(true);
miEditRedo.setText(Messages.getString("Spoon.Menu.Redo.Available",next.toString()));//"Redo : "+next.toString()+" \tCTRL-Y"
}
else
{
miEditRedo.setEnabled(false);
miEditRedo.setText(Messages.getString("Spoon.Menu.Redo.NotAvailable"));//"Redo : not available \tCTRL-Y"
}
}
public void addUndoNew(UndoInterface undoInterface, Object obj[], int position[])
{
addUndoNew(undoInterface, obj, position, false);
}
public void addUndoNew(UndoInterface undoInterface, Object obj[], int position[], boolean nextAlso)
{
undoInterface.addUndo(obj, null, position, null, null, TransMeta.TYPE_UNDO_NEW, nextAlso);
setUndoMenu(undoInterface);
}
// Undo delete object
public void addUndoDelete(UndoInterface undoInterface, Object obj[], int position[])
{
addUndoDelete(undoInterface, obj, position, false);
}
// Undo delete object
public void addUndoDelete(UndoInterface undoInterface, Object obj[], int position[], boolean nextAlso)
{
undoInterface.addUndo(obj, null, position, null, null, TransMeta.TYPE_UNDO_DELETE, nextAlso);
setUndoMenu(undoInterface);
}
// Change of step, connection, hop or note...
public void addUndoPosition(UndoInterface undoInterface, Object obj[], int pos[], Point prev[], Point curr[])
{
// It's better to store the indexes of the objects, not the objects itself!
undoInterface.addUndo(obj, null, pos, prev, curr, JobMeta.TYPE_UNDO_POSITION, false);
setUndoMenu(undoInterface);
}
// Change of step, connection, hop or note...
public void addUndoChange(UndoInterface undoInterface, Object from[], Object to[], int[] pos)
{
addUndoChange(undoInterface, from, to, pos, false);
}
// Change of step, connection, hop or note...
public void addUndoChange(UndoInterface undoInterface, Object from[], Object to[], int[] pos, boolean nextAlso)
{
undoInterface.addUndo(from, to, pos, null, null, JobMeta.TYPE_UNDO_CHANGE, nextAlso);
setUndoMenu(undoInterface);
}
/**
* Checks *all* the steps in the transformation, puts the result in remarks list
*/
public void checkTrans(TransMeta transMeta)
{
checkTrans(transMeta, false);
}
/**
* Check the steps in a transformation
*
* @param only_selected True: Check only the selected steps...
*/
public void checkTrans(TransMeta transMeta, boolean only_selected)
{
if (transMeta==null) return;
SpoonGraph spoonGraph = findSpoonGraphOfTransformation(transMeta);
if (spoonGraph==null) return;
CheckTransProgressDialog ctpd = new CheckTransProgressDialog(shell, transMeta, spoonGraph.getRemarks(), only_selected);
ctpd.open(); // manages the remarks arraylist...
showLastTransCheck();
}
/**
* Show the remarks of the last transformation check that was run.
* @see #checkTrans()
*/
public void showLastTransCheck()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta==null) return;
SpoonGraph spoonGraph = findSpoonGraphOfTransformation(transMeta);
if (spoonGraph==null) return;
CheckResultDialog crd = new CheckResultDialog(shell, SWT.NONE, spoonGraph.getRemarks());
String stepname = crd.open();
if (stepname!=null)
{
// Go to the indicated step!
StepMeta stepMeta = transMeta.findStep(stepname);
if (stepMeta!=null)
{
editStep(transMeta, stepMeta);
}
}
}
public void clearDBCache()
{
clearDBCache(null);
}
public void clearDBCache(DatabaseMeta databaseMeta)
{
if (databaseMeta!=null)
{
DBCache.getInstance().clear(databaseMeta.getName());
}
else
{
DBCache.getInstance().clear(null);
}
}
public void exploreDB(HasDatabasesInterface hasDatabasesInterface, DatabaseMeta databaseMeta)
{
DatabaseExplorerDialog std = new DatabaseExplorerDialog(shell, SWT.NONE, databaseMeta, hasDatabasesInterface.getDatabases(), true );
std.open();
}
public void analyseImpact(TransMeta transMeta)
{
if (transMeta==null) return;
SpoonGraph spoonGraph = findSpoonGraphOfTransformation(transMeta);
if (spoonGraph==null) return;
AnalyseImpactProgressDialog aipd = new AnalyseImpactProgressDialog(shell, transMeta, spoonGraph.getImpact());
spoonGraph.setImpactFinished( aipd.open() );
if (spoonGraph.isImpactFinished()) showLastImpactAnalyses(transMeta);
}
public void showLastImpactAnalyses(TransMeta transMeta)
{
if (transMeta==null) return;
SpoonGraph spoonGraph = findSpoonGraphOfTransformation(transMeta);
if (spoonGraph==null) return;
ArrayList rows = new ArrayList();
for (int i=0;i<spoonGraph.getImpact().size();i++)
{
DatabaseImpact ii = (DatabaseImpact)spoonGraph.getImpact().get(i);
rows.add(ii.getRow());
}
if (rows.size()>0)
{
// Display all the rows...
PreviewRowsDialog prd = new PreviewRowsDialog(shell, SWT.NONE, "-", rows);
prd.setTitleMessage(Messages.getString("Spoon.Dialog.ImpactAnalyses.Title"), Messages.getString("Spoon.Dialog.ImpactAnalyses.Message"));//"Impact analyses" "Result of analyses:"
prd.open();
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION );
if (spoonGraph.isImpactFinished())
{
mb.setMessage(Messages.getString("Spoon.Dialog.TransformationNoImpactOnDatabase.Message"));//"As far as I can tell, this transformation has no impact on any database."
}
else
{
mb.setMessage(Messages.getString("Spoon.Dialog.RunImpactAnalysesFirst.Message"));//"Please run the impact analyses first on this transformation."
}
mb.setText(Messages.getString("Spoon.Dialog.ImpactAnalyses.Title"));//Impact
mb.open();
}
}
public void getSQL()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null) getTransSQL(transMeta);
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null) getJobSQL(jobMeta);
}
/**
* Get & show the SQL required to run the loaded transformation...
*
*/
public void getTransSQL(TransMeta transMeta)
{
GetSQLProgressDialog pspd = new GetSQLProgressDialog(shell, transMeta);
ArrayList stats = pspd.open();
if (stats!=null) // null means error, but we already displayed the error
{
if (stats.size()>0)
{
SQLStatementsDialog ssd = new SQLStatementsDialog(shell, SWT.NONE, stats);
ssd.open();
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION );
mb.setMessage(Messages.getString("Spoon.Dialog.NoSQLNeedEexecuted.Message"));//As far as I can tell, no SQL statements need to be executed before this transformation can run.
mb.setText(Messages.getString("Spoon.Dialog.NoSQLNeedEexecuted.Title"));//"SQL"
mb.open();
}
}
}
/**
* Get & show the SQL required to run the loaded job entry...
*
*/
public void getJobSQL(JobMeta jobMeta)
{
GetJobSQLProgressDialog pspd = new GetJobSQLProgressDialog(shell, jobMeta, rep);
ArrayList stats = pspd.open();
if (stats!=null) // null means error, but we already displayed the error
{
if (stats.size()>0)
{
SQLStatementsDialog ssd = new SQLStatementsDialog(shell, SWT.NONE, stats);
ssd.open();
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION );
mb.setMessage(Messages.getString("Spoon.Dialog.JobNoSQLNeedEexecuted.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.JobNoSQLNeedEexecuted.Title")); //$NON-NLS-1$
mb.open();
}
}
}
public void toClipboard(String cliptext)
{
GUIResource.getInstance().toClipboard(cliptext);
}
public String fromClipboard()
{
return GUIResource.getInstance().fromClipboard();
}
/**
* Paste transformation from the clipboard...
*
*/
public void pasteTransformation()
{
log.logDetailed(toString(), Messages.getString("Spoon.Log.PasteTransformationFromClipboard"));//"Paste transformation from the clipboard!"
String xml = fromClipboard();
try
{
Document doc = XMLHandler.loadXMLString(xml);
TransMeta transMeta = new TransMeta(XMLHandler.getSubNode(doc, TransMeta.XML_TAG));
addSpoonGraph(transMeta); // create a new tab
refreshGraph();
refreshTree();
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorPastingTransformation.Title"), Messages.getString("Spoon.Dialog.ErrorPastingTransformation.Message"), e);//Error pasting transformation "An error occurred pasting a transformation from the clipboard"
}
}
/**
* Paste job from the clipboard...
*
*/
public void pasteJob()
{
String xml = fromClipboard();
try
{
Document doc = XMLHandler.loadXMLString(xml);
JobMeta jobMeta = new JobMeta(log, XMLHandler.getSubNode(doc, JobMeta.XML_TAG), rep);
addChefGraph(jobMeta); // create a new tab
refreshGraph();
refreshTree();
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorPastingJob.Title"), Messages.getString("Spoon.Dialog.ErrorPastingJob.Message"), e);//Error pasting transformation "An error occurred pasting a transformation from the clipboard"
}
}
public void copyTransformation(TransMeta transMeta)
{
if (transMeta==null) return;
toClipboard(XMLHandler.getXMLHeader() + transMeta.getXML());
}
public void copyJob(JobMeta jobMeta)
{
if (jobMeta==null) return;
toClipboard(XMLHandler.getXMLHeader() + jobMeta.getXML());
}
public void copyTransformationImage(TransMeta transMeta)
{
SpoonGraph spoonGraph = findSpoonGraphOfTransformation(transMeta);
if (spoonGraph==null) return;
Clipboard clipboard = GUIResource.getInstance().getNewClipboard();
Point area = transMeta.getMaximum();
Image image = spoonGraph.getTransformationImage(Display.getCurrent(), area.x, area.y);
clipboard.setContents(new Object[] { image.getImageData() }, new Transfer[]{ImageDataTransfer.getInstance()});
}
/**
* Shows a wizard that creates a new database connection...
*
*/
private void createDatabaseWizard(HasDatabasesInterface hasDatabasesInterface)
{
CreateDatabaseWizard cdw=new CreateDatabaseWizard();
DatabaseMeta newDBInfo=cdw.createAndRunDatabaseWizard(shell, props, hasDatabasesInterface.getDatabases());
if(newDBInfo!=null){ //finished
hasDatabasesInterface.addDatabase(newDBInfo);
refreshTree();
refreshGraph();
}
}
public ArrayList getActiveDatabases()
{
Map map = new Hashtable();
HasDatabasesInterface transMeta = getActiveTransformation();
if (transMeta!=null)
{
for (int i=0;i<transMeta.nrDatabases();i++)
{
map.put(transMeta.getDatabase(i).getName(), transMeta.getDatabase(i));
}
}
HasDatabasesInterface jobMeta = getActiveJob();
if (jobMeta!=null)
{
for (int i=0;i<jobMeta.nrDatabases();i++)
{
map.put(jobMeta.getDatabase(i).getName(), jobMeta.getDatabase(i));
}
}
if (rep!=null)
{
try
{
List repDBs = rep.getDatabases();
for (int i=0;i<repDBs.size();i++)
{
DatabaseMeta databaseMeta = (DatabaseMeta) repDBs.get(i);
map.put(databaseMeta.getName(), databaseMeta);
}
}
catch(Exception e)
{
log.logError(toString(), "Unexpected error reading databases from the repository: "+e.toString());
log.logError(toString(), Const.getStackTracker(e));
}
}
ArrayList databases = new ArrayList();
databases.addAll( map.values() );
return databases;
}
/**
* Create a transformation that extracts tables & data from a database.<p><p>
*
* 0) Select the database to rip<p>
* 1) Select the table in the database to copy<p>
* 2) Select the database to dump to<p>
* 3) Select the repository directory in which it will end up<p>
* 4) Select a name for the new transformation<p>
* 6) Create 1 transformation for the selected table<p>
*/
private void copyTableWizard()
{
ArrayList databases = getActiveDatabases();
if (databases.size()==0) return; // Nothing to do here
final CopyTableWizardPage1 page1 = new CopyTableWizardPage1("1", databases);
page1.createControl(shell);
final CopyTableWizardPage2 page2 = new CopyTableWizardPage2("2");
page2.createControl(shell);
Wizard wizard = new Wizard()
{
public boolean performFinish()
{
return copyTable(page1.getSourceDatabase(), page1.getTargetDatabase(), page2.getSelection());
}
/**
* @see org.eclipse.jface.wizard.Wizard#canFinish()
*/
public boolean canFinish()
{
return page2.canFinish();
}
};
wizard.addPage(page1);
wizard.addPage(page2);
WizardDialog wd = new WizardDialog(shell, wizard);
wd.setMinimumPageSize(700,400);
wd.open();
}
public boolean copyTable(DatabaseMeta sourceDBInfo, DatabaseMeta targetDBInfo, String tablename )
{
try
{
//
// Create a new transformation...
//
TransMeta meta = new TransMeta();
meta.addDatabase(sourceDBInfo);
meta.addDatabase(targetDBInfo);
//
// Add a note
//
String note = Messages.getString("Spoon.Message.Note.ReadInformationFromTableOnDB",tablename,sourceDBInfo.getDatabaseName() )+Const.CR;//"Reads information from table ["+tablename+"] on database ["+sourceDBInfo+"]"
note+=Messages.getString("Spoon.Message.Note.WriteInformationToTableOnDB",tablename,targetDBInfo.getDatabaseName() );//"After that, it writes the information to table ["+tablename+"] on database ["+targetDBInfo+"]"
NotePadMeta ni = new NotePadMeta(note, 150, 10, -1, -1);
meta.addNote(ni);
//
// create the source step...
//
String fromstepname = Messages.getString("Spoon.Message.Note.ReadFromTable",tablename); //"read from ["+tablename+"]";
TableInputMeta tii = new TableInputMeta();
tii.setDatabaseMeta(sourceDBInfo);
tii.setSQL("SELECT * FROM "+tablename);
StepLoader steploader = StepLoader.getInstance();
String fromstepid = steploader.getStepPluginID(tii);
StepMeta fromstep = new StepMeta(fromstepid, fromstepname, (StepMetaInterface)tii );
fromstep.setLocation(150,100);
fromstep.setDraw(true);
fromstep.setDescription(Messages.getString("Spoon.Message.Note.ReadInformationFromTableOnDB",tablename,sourceDBInfo.getDatabaseName() ));
meta.addStep(fromstep);
//
// add logic to rename fields in case any of the field names contain reserved words...
// Use metadata logic in SelectValues, use SelectValueInfo...
//
Database sourceDB = new Database(sourceDBInfo);
sourceDB.connect();
// Get the fields for the input table...
Row fields = sourceDB.getTableFields(tablename);
// See if we need to deal with reserved words...
int nrReserved = targetDBInfo.getNrReservedWords(fields);
if (nrReserved>0)
{
SelectValuesMeta svi = new SelectValuesMeta();
svi.allocate(0,0,nrReserved);
int nr = 0;
for (int i=0;i<fields.size();i++)
{
Value v = fields.getValue(i);
if (targetDBInfo.isReservedWord( v.getName() ) )
{
svi.getMetaName()[nr] = v.getName();
svi.getMetaRename()[nr] = targetDBInfo.quoteField( v.getName() );
nr++;
}
}
String selstepname =Messages.getString("Spoon.Message.Note.HandleReservedWords"); //"Handle reserved words";
String selstepid = steploader.getStepPluginID(svi);
StepMeta selstep = new StepMeta(selstepid, selstepname, (StepMetaInterface)svi );
selstep.setLocation(350,100);
selstep.setDraw(true);
selstep.setDescription(Messages.getString("Spoon.Message.Note.RenamesReservedWords",targetDBInfo.getDatabaseTypeDesc()) );//"Renames reserved words for "+targetDBInfo.getDatabaseTypeDesc()
meta.addStep(selstep);
TransHopMeta shi = new TransHopMeta(fromstep, selstep);
meta.addTransHop(shi);
fromstep = selstep;
}
//
// Create the target step...
//
//
// Add the TableOutputMeta step...
//
String tostepname = Messages.getString("Spoon.Message.Note.WriteToTable",tablename); // "write to ["+tablename+"]";
TableOutputMeta toi = new TableOutputMeta();
toi.setDatabaseMeta( targetDBInfo );
toi.setTablename( tablename );
toi.setCommitSize( 200 );
toi.setTruncateTable( true );
String tostepid = steploader.getStepPluginID(toi);
StepMeta tostep = new StepMeta(tostepid, tostepname, (StepMetaInterface)toi );
tostep.setLocation(550,100);
tostep.setDraw(true);
tostep.setDescription(Messages.getString("Spoon.Message.Note.WriteInformationToTableOnDB2",tablename,targetDBInfo.getDatabaseName() ));//"Write information to table ["+tablename+"] on database ["+targetDBInfo+"]"
meta.addStep(tostep);
//
// Add a hop between the two steps...
//
TransHopMeta hi = new TransHopMeta(fromstep, tostep);
meta.addTransHop(hi);
// OK, if we're still here: overwrite the current transformation...
// Set a name on this generated transformation
//
String name = "Copy table from ["+sourceDBInfo.getName()+"] to ["+targetDBInfo.getName()+"]";
String transName = name;
int nr=1;
if (findTransformation(transName)!=null)
{
nr++;
transName = name+" "+nr;
}
meta.setName(transName);
addSpoonGraph(meta);
refreshGraph();
refreshTree();
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.UnexpectedError.Title"), Messages.getString("Spoon.Dialog.UnexpectedError.Message"), new KettleException(e.getMessage(), e));//"Unexpected error" "An unexpected error occurred creating the new transformation"
return false;
}
return true;
}
public String toString()
{
return APP_NAME;
}
/**
* This is the main procedure for Spoon.
*
* @param a Arguments are available in the "Get System Info" step.
*/
public static void main (String [] a) throws KettleException
{
EnvUtil.environmentInit();
ArrayList args = new ArrayList();
for (int i=0;i<a.length;i++) args.add(a[i]);
Display display = new Display();
Splash splash = new Splash(display);
StringBuffer optionRepname, optionUsername, optionPassword, optionTransname, optionFilename, optionDirname, optionLogfile, optionLoglevel;
CommandLineOption options[] = new CommandLineOption[]
{
new CommandLineOption("rep", "Repository name", optionRepname=new StringBuffer()),
new CommandLineOption("user", "Repository username", optionUsername=new StringBuffer()),
new CommandLineOption("pass", "Repository password", optionPassword=new StringBuffer()),
new CommandLineOption("trans", "The name of the transformation to launch", optionTransname=new StringBuffer()),
new CommandLineOption("dir", "The directory (don't forget the leading /)", optionDirname=new StringBuffer()),
new CommandLineOption("file", "The filename (Transformation in XML) to launch", optionFilename=new StringBuffer()),
new CommandLineOption("level", "The logging level (Basic, Detailed, Debug, Rowlevel, Error, Nothing)", optionLoglevel=new StringBuffer()),
new CommandLineOption("logfile", "The logging file to write to", optionLogfile=new StringBuffer()),
new CommandLineOption("log", "The logging file to write to (deprecated)", optionLogfile=new StringBuffer(), false, true),
};
// Parse the options...
CommandLineOption.parseArguments(args, options);
String kettleRepname = Const.getEnvironmentVariable("KETTLE_REPOSITORY", null);
String kettleUsername = Const.getEnvironmentVariable("KETTLE_USER", null);
String kettlePassword = Const.getEnvironmentVariable("KETTLE_PASSWORD", null);
if (!Const.isEmpty(kettleRepname )) optionRepname = new StringBuffer(kettleRepname);
if (!Const.isEmpty(kettleUsername)) optionUsername = new StringBuffer(kettleUsername);
if (!Const.isEmpty(kettlePassword)) optionPassword = new StringBuffer(kettlePassword);
// Before anything else, check the runtime version!!!
String version = Const.JAVA_VERSION;
if ("1.4".compareToIgnoreCase(version)>0)
{
System.out.println("The System is running on Java version "+version);
System.out.println("Unfortunately, it needs version 1.4 or higher to run.");
return;
}
// Set default Locale:
Locale.setDefault(Const.DEFAULT_LOCALE);
LogWriter log;
LogWriter.setConsoleAppenderDebug();
if (Const.isEmpty(optionLogfile))
{
log=LogWriter.getInstance(Const.SPOON_LOG_FILE, false, LogWriter.LOG_LEVEL_BASIC);
}
else
{
log=LogWriter.getInstance( optionLogfile.toString(), true, LogWriter.LOG_LEVEL_BASIC );
}
if (log.getRealFilename()!=null) log.logBasic(APP_NAME, Messages.getString("Spoon.Log.LoggingToFile")+log.getRealFilename());//"Logging goes to "
if (!Const.isEmpty(optionLoglevel))
{
log.setLogLevel(optionLoglevel.toString());
log.logBasic(APP_NAME, Messages.getString("Spoon.Log.LoggingAtLevel")+log.getLogLevelDesc());//"Logging is at level : "
}
/* Load the plugins etc.*/
StepLoader stloader = StepLoader.getInstance();
if (!stloader.read())
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.ErrorLoadingAndHaltSystem"));//Error loading steps & plugins... halting Spoon!
return;
}
/* Load the plugins etc. we need to load jobentry*/
JobEntryLoader jeloader = JobEntryLoader.getInstance();
if (!jeloader.read())
{
log.logError("Spoon", "Error loading job entries & plugins... halting Kitchen!");
return;
}
final Spoon spoon = new Spoon(log, display, null);
staticSpoon = spoon;
spoon.setDestroy(true);
spoon.setArguments((String[])args.toArray(new String[args.size()]));
log.logBasic(APP_NAME, Messages.getString("Spoon.Log.MainWindowCreated"));//Main window is created.
RepositoryMeta repositoryMeta = null;
UserInfo userinfo = null;
if (Const.isEmpty(optionRepname) && Const.isEmpty(optionFilename) && spoon.props.showRepositoriesDialogAtStartup())
{
log.logBasic(APP_NAME, Messages.getString("Spoon.Log.AskingForRepository"));//"Asking for repository"
int perms[] = new int[] { PermissionMeta.TYPE_PERMISSION_TRANSFORMATION };
splash.hide();
RepositoriesDialog rd = new RepositoriesDialog(spoon.disp, SWT.NONE, perms, Messages.getString("Spoon.Application.Name"));//"Spoon"
if (rd.open())
{
repositoryMeta = rd.getRepository();
userinfo = rd.getUser();
if (!userinfo.useTransformations())
{
MessageBox mb = new MessageBox(spoon.shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("Spoon.Dialog.RepositoryUserCannotWork.Message"));//"Sorry, this repository user can't work with transformations from the repository."
mb.setText(Messages.getString("Spoon.Dialog.RepositoryUserCannotWork.Title"));//"Error!"
mb.open();
userinfo = null;
repositoryMeta = null;
}
}
else
{
// Exit point: user pressed CANCEL!
if (rd.isCancelled())
{
splash.dispose();
spoon.quitFile();
return;
}
}
}
try
{
// Read kettle transformation specified on command-line?
if (!Const.isEmpty(optionRepname) || !Const.isEmpty(optionFilename))
{
if (!Const.isEmpty(optionRepname))
{
RepositoriesMeta repsinfo = new RepositoriesMeta(log);
if (repsinfo.readData())
{
repositoryMeta = repsinfo.findRepository(optionRepname.toString());
if (repositoryMeta!=null)
{
// Define and connect to the repository...
spoon.rep = new Repository(log, repositoryMeta, userinfo);
if (spoon.rep.connect(Messages.getString("Spoon.Application.Name")))//"Spoon"
{
if (Const.isEmpty(optionDirname)) optionDirname=new StringBuffer(RepositoryDirectory.DIRECTORY_SEPARATOR);
// Check username, password
spoon.rep.userinfo = new UserInfo(spoon.rep, optionUsername.toString(), optionPassword.toString());
if (spoon.rep.userinfo.getID()>0)
{
// OK, if we have a specified transformation, try to load it...
// If not, keep the repository logged in.
if (!Const.isEmpty(optionTransname))
{
RepositoryDirectory repdir = spoon.rep.getDirectoryTree().findDirectory(optionDirname.toString());
if (repdir!=null)
{
TransMeta transMeta = new TransMeta(spoon.rep, optionTransname.toString(), repdir);
transMeta.setFilename(optionRepname.toString());
transMeta.clearChanged();
spoon.addSpoonGraph(transMeta);
}
else
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableFindDirectory",optionDirname.toString()));//"Can't find directory ["+dirname+"] in the repository."
}
}
}
else
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableVerifyUser"));//"Can't verify username and password."
spoon.rep.disconnect();
spoon.rep=null;
}
}
else
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableConnectToRepository"));//"Can't connect to the repository."
}
}
else
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.NoRepositoryRrovided"));//"No repository provided, can't load transformation."
}
}
else
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.NoRepositoriesDefined"));//"No repositories defined on this system."
}
}
else
if (!Const.isEmpty(optionFilename))
{
spoon.openFile(optionFilename.toString(), false);
}
}
else // Normal operations, nothing on the commandline...
{
// Can we connect to the repository?
if (repositoryMeta!=null && userinfo!=null)
{
spoon.rep = new Repository(log, repositoryMeta, userinfo);
if (!spoon.rep.connect(Messages.getString("Spoon.Application.Name"))) //"Spoon"
{
spoon.rep = null;
}
}
if (spoon.props.openLastFile())
{
log.logDetailed(APP_NAME, Messages.getString("Spoon.Log.TryingOpenLastUsedFile"));//"Trying to open the last file used."
List lastUsedFiles = spoon.props.getLastUsedFiles();
if (lastUsedFiles.size()>0)
{
LastUsedFile lastUsedFile = (LastUsedFile) lastUsedFiles.get(0);
spoon.loadLastUsedFile(lastUsedFile, repositoryMeta);
}
}
}
}
catch(KettleException ke)
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.ErrorOccurred")+Const.CR+ke.getMessage());//"An error occurred: "
spoon.rep=null;
// ke.printStackTrace();
}
spoon.open ();
splash.dispose();
try
{
while (!spoon.isDisposed ())
{
if (!spoon.readAndDispatch ()) spoon.sleep ();
}
}
catch(Throwable e)
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.UnexpectedErrorOccurred")+Const.CR+e.getMessage());//"An unexpected error occurred in Spoon: probable cause: please close all windows before stopping Spoon! "
e.printStackTrace();
}
spoon.dispose();
log.logBasic(APP_NAME, APP_NAME+" "+Messages.getString("Spoon.Log.AppHasEnded"));//" has ended."
// Close the logfile
log.close();
// Kill all remaining things in this VM!
System.exit(0);
}
private void loadLastUsedFile(LastUsedFile lastUsedFile, RepositoryMeta repositoryMeta) throws KettleException
{
boolean useRepository = repositoryMeta!=null;
// Perhaps we need to connect to the repository?
if (lastUsedFile.isSourceRepository())
{
if (!Const.isEmpty(lastUsedFile.getRepositoryName()))
{
if (useRepository && !lastUsedFile.getRepositoryName().equalsIgnoreCase(repositoryMeta.getName()))
{
// We just asked...
useRepository = false;
}
}
}
if (useRepository && lastUsedFile.isSourceRepository())
{
if (rep!=null) // load from this repository...
{
if (rep.getName().equalsIgnoreCase(lastUsedFile.getRepositoryName()))
{
RepositoryDirectory repdir = rep.getDirectoryTree().findDirectory(lastUsedFile.getDirectory());
if (repdir!=null)
{
// Are we loading a transformation or a job?
if (lastUsedFile.isTransformation())
{
log.logDetailed(APP_NAME, Messages.getString("Spoon.Log.AutoLoadingTransformation",lastUsedFile.getFilename(), lastUsedFile.getDirectory()));//"Auto loading transformation ["+lastfiles[0]+"] from repository directory ["+lastdirs[0]+"]"
TransLoadProgressDialog tlpd = new TransLoadProgressDialog(shell, rep, lastUsedFile.getFilename(), repdir);
TransMeta transMeta = tlpd.open(); // = new TransInfo(log, win.rep, lastfiles[0], repdir);
if (transMeta != null)
{
props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, lastUsedFile.getFilename(), repdir.getPath(), true, rep.getName());
transMeta.setFilename(lastUsedFile.getFilename());
transMeta.clearChanged();
addSpoonGraph(transMeta);
refreshTree();
}
}
else
if (lastUsedFile.isJob())
{
// TODO: use JobLoadProgressDialog
JobMeta jobMeta = new JobMeta(log, rep, lastUsedFile.getFilename(), repdir);
props.addLastFile(LastUsedFile.FILE_TYPE_JOB, lastUsedFile.getFilename(), repdir.getPath(), true, rep.getName());
jobMeta.clearChanged();
addChefGraph(jobMeta);
}
refreshTree();
}
}
}
}
if (!lastUsedFile.isSourceRepository() && !Const.isEmpty(lastUsedFile.getFilename()))
{
if (lastUsedFile.isTransformation())
{
TransMeta transMeta = new TransMeta(lastUsedFile.getFilename());
transMeta.setFilename(lastUsedFile.getFilename());
transMeta.clearChanged();
props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, lastUsedFile.getFilename(), null, false, null);
addSpoonGraph(transMeta);
}
if (lastUsedFile.isJob())
{
JobMeta jobMeta = new JobMeta(log, lastUsedFile.getFilename(), rep);
jobMeta.setFilename(lastUsedFile.getFilename());
jobMeta.clearChanged();
props.addLastFile(LastUsedFile.FILE_TYPE_JOB, lastUsedFile.getFilename(), null, false, null);
addChefGraph(jobMeta);
}
refreshTree();
}
}
/**
* Create a new SelectValues step in between this step and the previous.
* If the previous fields are not there, no mapping can be made, same with the required fields.
* @param stepMeta The target step to map against.
*/
public void generateMapping(TransMeta transMeta, StepMeta stepMeta)
{
try
{
if (stepMeta!=null)
{
StepMetaInterface smi = stepMeta.getStepMetaInterface();
Row targetFields = smi.getRequiredFields();
Row sourceFields = transMeta.getPrevStepFields(stepMeta);
// Build the mapping: let the user decide!!
String[] source = sourceFields.getFieldNames();
for (int i=0;i<source.length;i++)
{
Value v = sourceFields.getValue(i);
source[i]+=EnterMappingDialog.STRING_ORIGIN_SEPARATOR+v.getOrigin()+")";
}
String[] target = targetFields.getFieldNames();
EnterMappingDialog dialog = new EnterMappingDialog(shell, source, target);
ArrayList mappings = dialog.open();
if (mappings!=null)
{
// OK, so we now know which field maps where.
// This allows us to generate the mapping using a SelectValues Step...
SelectValuesMeta svm = new SelectValuesMeta();
svm.allocate(mappings.size(), 0, 0);
for (int i=0;i<mappings.size();i++)
{
SourceToTargetMapping mapping = (SourceToTargetMapping) mappings.get(i);
svm.getSelectName()[i] = sourceFields.getValue(mapping.getSourcePosition()).getName();
svm.getSelectRename()[i] = target[mapping.getTargetPosition()];
svm.getSelectLength()[i] = -1;
svm.getSelectPrecision()[i] = -1;
}
// Now that we have the meta-data, create a new step info object
String stepName = stepMeta.getName()+" Mapping";
stepName = transMeta.getAlternativeStepname(stepName); // if it's already there, rename it.
StepMeta newStep = new StepMeta("SelectValues", stepName, svm);
newStep.setLocation(stepMeta.getLocation().x+20, stepMeta.getLocation().y+20);
newStep.setDraw(true);
transMeta.addStep(newStep);
addUndoNew(transMeta, new StepMeta[] { newStep }, new int[] { transMeta.indexOfStep(newStep) });
// Redraw stuff...
refreshTree();
refreshGraph();
}
}
else
{
System.out.println("No target to do mapping against!");
}
}
catch(KettleException e)
{
new ErrorDialog(shell, "Error creating mapping", "There was an error when Kettle tried to generate a mapping against the target step", e);
}
}
public void editPartitioning(TransMeta transMeta, StepMeta stepMeta)
{
StepPartitioningMeta stepPartitioningMeta = stepMeta.getStepPartitioningMeta();
if (stepPartitioningMeta==null) stepPartitioningMeta = new StepPartitioningMeta();
String[] options = StepPartitioningMeta.methodDescriptions;
EnterSelectionDialog dialog = new EnterSelectionDialog(shell, options, "Partioning method", "Select the partitioning method");
String methodDescription = dialog.open(stepPartitioningMeta.getMethod());
if (methodDescription!=null)
{
int method = StepPartitioningMeta.getMethod(methodDescription);
stepPartitioningMeta.setMethod(method);
switch(method)
{
case StepPartitioningMeta.PARTITIONING_METHOD_NONE: break;
case StepPartitioningMeta.PARTITIONING_METHOD_MOD:
// ask for a fieldname
EnterStringDialog stringDialog = new EnterStringDialog(shell, props, Const.NVL(stepPartitioningMeta.getFieldName(), ""), "Fieldname", "Enter a field name to partition on");
String fieldName = stringDialog.open();
stepPartitioningMeta.setFieldName(fieldName);
// Ask for a Partitioning Schema
String schemaNames[] = transMeta.getPartitionSchemasNames();
if (schemaNames.length==0)
{
MessageBox box = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
box.setText("Create a partition schema");
box.setMessage("You first need to create one or more partition schemas in the transformation settings dialog before you can select one!");
box.open();
}
else
{
// Set the partitioning schema too.
PartitionSchema partitionSchema = stepPartitioningMeta.getPartitionSchema();
int idx = -1;
if (partitionSchema!=null)
{
idx = Const.indexOfString(partitionSchema.getName(), schemaNames);
}
EnterSelectionDialog askSchema = new EnterSelectionDialog(shell, schemaNames, "Select a partition schema", "Select the partition schema to use:");
String schemaName = askSchema.open(idx);
if (schemaName!=null)
{
idx = Const.indexOfString(schemaName, schemaNames);
stepPartitioningMeta.setPartitionSchema((PartitionSchema) transMeta.getPartitionSchemas().get(idx));
}
}
break;
}
refreshGraph();
}
}
/**
* Select a clustering schema for this step.
*
* @param stepMeta The step to set the clustering schema for.
*/
public void editClustering(TransMeta transMeta, StepMeta stepMeta)
{
int idx = -1;
if (stepMeta.getClusterSchema()!=null)
{
idx = transMeta.getClusterSchemas().indexOf( stepMeta.getClusterSchema() );
}
String[] clusterSchemaNames = transMeta.getClusterSchemaNames();
EnterSelectionDialog dialog = new EnterSelectionDialog(shell, clusterSchemaNames, "Cluster schema", "Select the cluster schema to use (cancel=clear)");
String schemaName = dialog.open(idx);
if (schemaName==null)
{
stepMeta.setClusterSchema(null);
}
else
{
ClusterSchema clusterSchema = transMeta.findClusterSchema(schemaName);
stepMeta.setClusterSchema( clusterSchema );
}
refreshTree();
refreshGraph();
}
public void createKettleArchive(TransMeta transMeta)
{
if (transMeta==null) return;
JarfileGenerator.generateJarFile(transMeta);
}
/**
* This creates a new database partitioning schema, edits it and adds it to the transformation metadata
*
*/
public void newDatabasePartitioningSchema(TransMeta transMeta)
{
PartitionSchema partitionSchema = new PartitionSchema();
PartitionSchemaDialog dialog = new PartitionSchemaDialog(shell, partitionSchema, transMeta.getDatabases());
if (dialog.open())
{
transMeta.getPartitionSchemas().add(partitionSchema);
refreshTree();
}
}
private void editPartitionSchema(HasDatabasesInterface hasDatabasesInterface, PartitionSchema partitionSchema)
{
PartitionSchemaDialog dialog = new PartitionSchemaDialog(shell, partitionSchema, hasDatabasesInterface.getDatabases());
if (dialog.open())
{
refreshTree();
}
}
private void delPartitionSchema(TransMeta transMeta, PartitionSchema partitionSchema)
{
try
{
if (rep!=null && partitionSchema.getId()>0)
{
// remove the partition schema from the repository too...
rep.delPartitionSchema(partitionSchema.getId());
}
int idx = transMeta.getPartitionSchemas().indexOf(partitionSchema);
transMeta.getPartitionSchemas().remove(idx);
refreshTree();
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorDeletingClusterSchema.Title"), Messages.getString("Spoon.Dialog.ErrorDeletingClusterSchema.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* This creates a new clustering schema, edits it and adds it to the transformation metadata
*
*/
public void newClusteringSchema(TransMeta transMeta)
{
ClusterSchema clusterSchema = new ClusterSchema();
ClusterSchemaDialog dialog = new ClusterSchemaDialog(shell, clusterSchema, transMeta.getSlaveServers());
if (dialog.open())
{
transMeta.getClusterSchemas().add(clusterSchema);
refreshTree();
}
}
private void editClusterSchema(TransMeta transMeta, ClusterSchema clusterSchema)
{
ClusterSchemaDialog dialog = new ClusterSchemaDialog(shell, clusterSchema, transMeta.getSlaveServers());
if (dialog.open())
{
refreshTree();
}
}
private void delClusterSchema(TransMeta transMeta, ClusterSchema clusterSchema)
{
try
{
if (rep!=null && clusterSchema.getId()>0)
{
// remove the partition schema from the repository too...
rep.delClusterSchema(clusterSchema.getId());
}
int idx = transMeta.getClusterSchemas().indexOf(clusterSchema);
transMeta.getClusterSchemas().remove(idx);
refreshTree();
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorDeletingPartitionSchema.Title"), Messages.getString("Spoon.Dialog.ErrorDeletingPartitionSchema.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* This creates a slave server, edits it and adds it to the transformation metadata
*
*/
public void newSlaveServer(TransMeta transMeta)
{
SlaveServer slaveServer = new SlaveServer();
SlaveServerDialog dialog = new SlaveServerDialog(shell, slaveServer);
if (dialog.open())
{
transMeta.getSlaveServers().add(slaveServer);
refreshTree();
}
}
public void delSlaveServer(TransMeta transMeta, SlaveServer slaveServer)
{
try
{
if (rep!=null && slaveServer.getId()>0)
{
// remove the slave server from the repository too...
rep.delSlave(slaveServer.getId());
}
int idx = transMeta.getSlaveServers().indexOf(slaveServer);
transMeta.getSlaveServers().remove(idx);
refreshTree();
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorDeletingSlave.Title"), Messages.getString("Spoon.Dialog.ErrorDeletingSlave.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* Sends transformation to slave server
* @param executionConfiguration
*/
public void sendXMLToSlaveServer(TransMeta transMeta, TransExecutionConfiguration executionConfiguration)
{
SlaveServer slaveServer = executionConfiguration.getRemoteServer();
try
{
if (slaveServer==null) throw new KettleException("No slave server specified");
if (Const.isEmpty(transMeta.getName())) throw new KettleException("The transformation needs a name to uniquely identify it by on the remote server.");
String reply = slaveServer.sendXML(new TransConfiguration(transMeta, executionConfiguration).getXML(), AddTransServlet.CONTEXT_PATH+"?xml=Y");
WebResult webResult = WebResult.fromXMLString(reply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("There was an error posting the transformation on the remote server: "+Const.CR+webResult.getMessage());
}
reply = slaveServer.getContentFromServer(PrepareExecutionTransHandler.CONTEXT_PATH+"?name="+transMeta.getName()+"&xml=Y");
webResult = WebResult.fromXMLString(reply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("There was an error preparing the transformation for excution on the remote server: "+Const.CR+webResult.getMessage());
}
reply = slaveServer.getContentFromServer(StartExecutionTransHandler.CONTEXT_PATH+"?name="+transMeta.getName()+"&xml=Y");
webResult = WebResult.fromXMLString(reply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("There was an error starting the transformation on the remote server: "+Const.CR+webResult.getMessage());
}
}
catch (Exception e)
{
new ErrorDialog(shell, "Error", "Error sending transformation to server", e);
}
}
private void splitTrans(TransMeta transMeta, boolean show, boolean post, boolean prepare, boolean start)
{
try
{
if (Const.isEmpty(transMeta.getName())) throw new KettleException("The transformation needs a name to uniquely identify it by on the remote server.");
TransSplitter transSplitter = new TransSplitter(transMeta);
transSplitter.splitOriginalTransformation();
// Send the transformations to the servers...
//
// First the master...
//
TransMeta master = transSplitter.getMaster();
SlaveServer masterServer = null;
List masterSteps = master.getTransHopSteps(false);
if (masterSteps.size()>0) // If there is something that needs to be done on the master...
{
masterServer = transSplitter.getMasterServer();
if (show) addSpoonGraph(master);
if (post)
{
String masterReply = masterServer.sendXML(new TransConfiguration(master, executionConfiguration).getXML(), AddTransServlet.CONTEXT_PATH+"?xml=Y");
WebResult webResult = WebResult.fromXMLString(masterReply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("An error occurred sending the master transformation: "+webResult.getMessage());
}
}
}
// Then the slaves...
//
SlaveServer slaves[] = transSplitter.getSlaveTargets();
for (int i=0;i<slaves.length;i++)
{
TransMeta slaveTrans = (TransMeta) transSplitter.getSlaveTransMap().get(slaves[i]);
if (show) addSpoonGraph(slaveTrans);
if (post)
{
String slaveReply = slaves[i].sendXML(new TransConfiguration(slaveTrans, executionConfiguration).getXML(), AddTransServlet.CONTEXT_PATH+"?xml=Y");
WebResult webResult = WebResult.fromXMLString(slaveReply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("An error occurred sending a slave transformation: "+webResult.getMessage());
}
}
}
if (post)
{
if (prepare)
{
// Prepare the master...
if (masterSteps.size()>0) // If there is something that needs to be done on the master...
{
String masterReply = masterServer.getContentFromServer(PrepareExecutionTransHandler.CONTEXT_PATH+"?name="+master.getName()+"&xml=Y");
WebResult webResult = WebResult.fromXMLString(masterReply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("An error occurred while preparing the execution of the master transformation: "+webResult.getMessage());
}
}
// Prepare the slaves
for (int i=0;i<slaves.length;i++)
{
TransMeta slaveTrans = (TransMeta) transSplitter.getSlaveTransMap().get(slaves[i]);
String slaveReply = slaves[i].getContentFromServer(PrepareExecutionTransHandler.CONTEXT_PATH+"?name="+slaveTrans.getName()+"&xml=Y");
WebResult webResult = WebResult.fromXMLString(slaveReply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("An error occurred while preparing the execution of a slave transformation: "+webResult.getMessage());
}
}
}
if (start)
{
// Start the master...
if (masterSteps.size()>0) // If there is something that needs to be done on the master...
{
String masterReply = masterServer.getContentFromServer(StartExecutionTransHandler.CONTEXT_PATH+"?name="+master.getName()+"&xml=Y");
WebResult webResult = WebResult.fromXMLString(masterReply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("An error occurred while starting the execution of the master transformation: "+webResult.getMessage());
}
}
// Start the slaves
for (int i=0;i<slaves.length;i++)
{
TransMeta slaveTrans = (TransMeta) transSplitter.getSlaveTransMap().get(slaves[i]);
String slaveReply = slaves[i].getContentFromServer(StartExecutionTransHandler.CONTEXT_PATH+"?name="+slaveTrans.getName()+"&xml=Y");
WebResult webResult = WebResult.fromXMLString(slaveReply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("An error occurred while starting the execution of a slave transformation: "+webResult.getMessage());
}
}
}
// Now add monitors for the master and all the slave servers
addSpoonSlave(masterServer);
for (int i=0;i<slaves.length;i++)
{
addSpoonSlave(slaves[i]);
}
}
}
catch(Exception e)
{
new ErrorDialog(shell, "Split transformation", "There was an error during transformation split", e);
}
}
public void executeFile(boolean local, boolean remote, boolean cluster, boolean preview, Date replayDate)
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null) executeTransformation(transMeta, local, remote, cluster, preview, replayDate);
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null) executeJob(jobMeta, local, remote, cluster, preview, replayDate);
}
public void executeTransformation(TransMeta transMeta, boolean local, boolean remote, boolean cluster, boolean preview, Date replayDate)
{
if (transMeta==null) return;
executionConfiguration.setExecutingLocally(local);
executionConfiguration.setExecutingRemotely(remote);
executionConfiguration.setExecutingClustered(cluster);
executionConfiguration.getUsedVariables(transMeta);
executionConfiguration.getUsedArguments(transMeta, arguments);
executionConfiguration.setReplayDate(replayDate);
executionConfiguration.setLocalPreviewing(preview);
executionConfiguration.setLogLevel(log.getLogLevel());
// executionConfiguration.setSafeModeEnabled( spoonLog!=null && spoonLog.isSafeModeChecked() );
TransExecutionConfigurationDialog dialog = new TransExecutionConfigurationDialog(shell, executionConfiguration, transMeta);
if (dialog.open())
{
addSpoonLog(transMeta);
SpoonLog spoonLog = getActiveSpoonLog();
if (executionConfiguration.isExecutingLocally())
{
if (executionConfiguration.isLocalPreviewing())
{
spoonLog.preview(executionConfiguration);
}
else
{
spoonLog.start(executionConfiguration);
}
}
else if(executionConfiguration.isExecutingRemotely())
{
if (executionConfiguration.getRemoteServer()!=null)
{
sendXMLToSlaveServer(transMeta, executionConfiguration);
addSpoonSlave(executionConfiguration.getRemoteServer());
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(Messages.getString("Spoon.Dialog.NoRemoteServerSpecified.Message"));
mb.setText(Messages.getString("Spoon.Dialog.NoRemoteServerSpecified.Title"));
mb.open();
}
}
else if (executionConfiguration.isExecutingClustered())
{
splitTrans( transMeta,
executionConfiguration.isClusterShowingTransformation(),
executionConfiguration.isClusterPosting(),
executionConfiguration.isClusterPreparing(),
executionConfiguration.isClusterStarting()
);
}
}
}
public void executeJob(JobMeta jobMeta, boolean local, boolean remote, boolean cluster, boolean preview, Date replayDate)
{
addChefLog(jobMeta);
ChefLog chefLog = getActiveJobLog();
chefLog.startJob(replayDate);
}
public CTabItem findCTabItem(String text)
{
CTabItem[] items = tabfolder.getItems();
for (int i=0;i<items.length;i++)
{
if (items[i].getText().equalsIgnoreCase(text)) return items[i];
}
return null;
}
private void addSpoonSlave(SlaveServer slaveServer)
{
// See if there is a SpoonSlave for this slaveServer...
String tabName = makeSlaveTabName(slaveServer);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
SpoonSlave spoonSlave = new SpoonSlave(tabfolder, SWT.NONE, this, slaveServer);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Status of slave server : "+slaveServer.getName()+" : "+slaveServer.getServerAndPort());
tabItem.setControl(spoonSlave);
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, spoonSlave));
}
int idx = tabfolder.indexOf(tabItem);
tabfolder.setSelection(idx);
}
public void addSpoonGraph(TransMeta transMeta)
{
String key = addTransformation(transMeta);
if (key!=null)
{
// See if there already is a tab for this graph
// If no, add it
// If yes, select that tab
//
String tabName = makeGraphTabName(transMeta);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
SpoonGraph spoonGraph = new SpoonGraph(tabfolder, this, transMeta);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Graphical view of Transformation : "+tabName);
tabItem.setImage(GUIResource.getInstance().getImageSpoonGraph());
tabItem.setControl(spoonGraph);
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, spoonGraph));
}
int idx = tabfolder.indexOf(tabItem);
// OK, also see if we need to open a new history window.
if (transMeta.getLogConnection()!=null && !Const.isEmpty(transMeta.getLogTable()))
{
addSpoonHistory(transMeta, false);
}
// keep the focus on the graph
tabfolder.setSelection(idx);
setUndoMenu(transMeta);
enableMenus();
}
}
public void addChefGraph(JobMeta jobMeta)
{
String key = addJob(jobMeta);
if (key!=null)
{
// See if there already is a tab for this graph
// If no, add it
// If yes, select that tab
//
String tabName = makeJobGraphTabName(jobMeta);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
ChefGraph chefGraph = new ChefGraph(tabfolder, this, jobMeta);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Graphical view of Job : "+tabName);
tabItem.setImage(GUIResource.getInstance().getImageChefGraph());
tabItem.setControl(chefGraph);
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, chefGraph));
}
int idx = tabfolder.indexOf(tabItem);
// OK, also see if we need to open a new history window.
if (jobMeta.getLogConnection()!=null && !Const.isEmpty(jobMeta.getLogTable()))
{
addChefHistory(jobMeta, false);
}
// keep the focus on the graph
tabfolder.setSelection(idx);
setUndoMenu(jobMeta);
enableMenus();
}
}
public boolean addSpoonBrowser(String name, String urlString)
{
try
{
// OK, now we have the HTML, create a new browset tab.
// See if there already is a tab for this browser
// If no, add it
// If yes, select that tab
//
CTabItem tabItem=findCTabItem(name);
if (tabItem==null)
{
SpoonBrowser browser = new SpoonBrowser(tabfolder, this, urlString);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(name);
tabItem.setControl(browser.getComposite());
tabMap.put(name, new TabMapEntry(tabItem, name, browser));
}
int idx = tabfolder.indexOf(tabItem);
// keep the focus on the graph
tabfolder.setSelection(idx);
return true;
}
catch(Throwable e)
{
return false;
}
}
public String makeLogTabName(TransMeta transMeta)
{
return "Trans log: "+makeGraphTabName(transMeta);
}
public String makeJobLogTabName(JobMeta jobMeta)
{
return "Job log: "+makeJobGraphTabName(jobMeta);
}
public String makeGraphTabName(TransMeta transMeta)
{
if (Const.isEmpty(transMeta.getName()))
{
if (Const.isEmpty(transMeta.getFilename()))
{
return STRING_TRANS_NO_NAME;
}
return transMeta.getFilename();
}
return transMeta.getName();
}
public String makeJobGraphTabName(JobMeta jobMeta)
{
if (Const.isEmpty(jobMeta.getName()))
{
if (Const.isEmpty(jobMeta.getFilename()))
{
return STRING_JOB_NO_NAME;
}
return jobMeta.getFilename();
}
return jobMeta.getName();
}
public String makeHistoryTabName(TransMeta transMeta)
{
return "Trans History: "+makeGraphTabName(transMeta);
}
public String makeJobHistoryTabName(JobMeta jobMeta)
{
return "Job History: "+makeJobGraphTabName(jobMeta);
}
public String makeSlaveTabName(SlaveServer slaveServer)
{
return "Slave server: "+slaveServer.getName();
}
public void addSpoonLog(TransMeta transMeta)
{
// See if there already is a tab for this log
// If no, add it
// If yes, select that tab
//
String tabName = makeLogTabName(transMeta);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
SpoonLog spoonLog = new SpoonLog(tabfolder, this, transMeta);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Execution log for transformation : "+makeGraphTabName(transMeta));
tabItem.setControl(spoonLog);
// If there is an associated history window, we want to keep that one up-to-date as well.
//
SpoonHistory spoonHistory = findSpoonHistoryOfTransformation(transMeta);
CTabItem historyItem = findCTabItem(makeHistoryTabName(transMeta));
if (spoonHistory!=null && historyItem!=null)
{
SpoonHistoryRefresher spoonHistoryRefresher = new SpoonHistoryRefresher(historyItem, spoonHistory);
tabfolder.addSelectionListener(spoonHistoryRefresher);
spoonLog.setSpoonHistoryRefresher(spoonHistoryRefresher);
}
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, spoonLog));
}
int idx = tabfolder.indexOf(tabItem);
tabfolder.setSelection(idx);
}
public void addChefLog(JobMeta jobMeta)
{
// See if there already is a tab for this log
// If no, add it
// If yes, select that tab
//
String tabName = makeJobLogTabName(jobMeta);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
ChefLog chefLog = new ChefLog(tabfolder, this, jobMeta);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Execution log for job: "+makeJobGraphTabName(jobMeta));
tabItem.setControl(chefLog);
// If there is an associated history window, we want to keep that one up-to-date as well.
//
ChefHistory chefHistory = findChefHistoryOfJob(jobMeta);
CTabItem historyItem = findCTabItem(makeJobHistoryTabName(jobMeta));
if (chefHistory!=null && historyItem!=null)
{
ChefHistoryRefresher chefHistoryRefresher = new ChefHistoryRefresher(historyItem, chefHistory);
tabfolder.addSelectionListener(chefHistoryRefresher);
chefLog.setChefHistoryRefresher(chefHistoryRefresher);
}
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, chefLog));
}
int idx = tabfolder.indexOf(tabItem);
tabfolder.setSelection(idx);
}
public void addSpoonHistory(TransMeta transMeta, boolean select)
{
// See if there already is a tab for this history view
// If no, add it
// If yes, select that tab
//
String tabName = makeHistoryTabName(transMeta);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
SpoonHistory spoonHistory = new SpoonHistory(tabfolder, this, transMeta);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Execution history for transformation : "+makeGraphTabName(transMeta));
tabItem.setControl(spoonHistory);
// If there is an associated log window that's open, find it and add a refresher
SpoonLog spoonLog = findSpoonLogOfTransformation(transMeta);
if (spoonLog!=null)
{
SpoonHistoryRefresher spoonHistoryRefresher = new SpoonHistoryRefresher(tabItem, spoonHistory);
tabfolder.addSelectionListener(spoonHistoryRefresher);
spoonLog.setSpoonHistoryRefresher(spoonHistoryRefresher);
}
spoonHistory.markRefreshNeeded(); // will refresh when first selected
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, spoonHistory));
}
if (select)
{
int idx = tabfolder.indexOf(tabItem);
tabfolder.setSelection(idx);
}
}
public void addChefHistory(JobMeta jobMeta, boolean select)
{
// See if there already is a tab for this history view
// If no, add it
// If yes, select that tab
//
String tabName = makeJobHistoryTabName(jobMeta);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
ChefHistory chefHistory = new ChefHistory(tabfolder, this, jobMeta);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Execution history for job : "+makeJobGraphTabName(jobMeta));
tabItem.setControl(chefHistory);
// If there is an associated log window that's open, find it and add a refresher
ChefLog chefLog = findChefLogOfJob(jobMeta);
if (chefLog!=null)
{
ChefHistoryRefresher chefHistoryRefresher = new ChefHistoryRefresher(tabItem, chefHistory);
tabfolder.addSelectionListener(chefHistoryRefresher);
chefLog.setChefHistoryRefresher(chefHistoryRefresher);
}
chefHistory.markRefreshNeeded(); // will refresh when first selected
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, chefHistory));
}
if (select)
{
int idx = tabfolder.indexOf(tabItem);
tabfolder.setSelection(idx);
}
}
/**
* Rename the tabs
*/
public void renameTabs()
{
Collection collection = tabMap.values();
List list = new ArrayList();
list.addAll(collection);
for (Iterator iter = list.iterator(); iter.hasNext();)
{
TabMapEntry entry = (TabMapEntry) iter.next();
if (entry.getTabItem().isDisposed())
{
// this should not be in the map, get rid of it.
tabMap.remove(entry.getObjectName());
continue;
}
String before = entry.getTabItem().getText();
if (entry.getObject() instanceof SpoonGraph) entry.getTabItem().setText( makeGraphTabName( (TransMeta) entry.getObject().getManagedObject() ) );
if (entry.getObject() instanceof SpoonLog) entry.getTabItem().setText( makeLogTabName( (TransMeta) entry.getObject().getManagedObject() ) );
if (entry.getObject() instanceof SpoonHistory) entry.getTabItem().setText( makeHistoryTabName( (TransMeta) entry.getObject().getManagedObject() ) );
if (entry.getObject() instanceof ChefGraph) entry.getTabItem().setText( makeJobGraphTabName( (JobMeta) entry.getObject().getManagedObject() ) );
if (entry.getObject() instanceof ChefLog) entry.getTabItem().setText( makeJobLogTabName( (JobMeta) entry.getObject().getManagedObject() ) );
if (entry.getObject() instanceof ChefHistory) entry.getTabItem().setText( makeJobHistoryTabName( (JobMeta) entry.getObject().getManagedObject() ) );
String after = entry.getTabItem().getText();
if (!before.equals(after))
{
entry.setObjectName(after);
tabMap.remove(before);
tabMap.put(after, entry);
// Also change the transformation map
if (entry.getObject() instanceof SpoonGraph)
{
transformationMap.remove(before);
transformationMap.put(after, entry.getObject().getManagedObject());
}
}
}
}
/**
* This contains a map between the name of a transformation and the TransMeta object.
* If the transformation has no name it will be mapped under a number [1], [2] etc.
* @return the transformation map
*/
public Map getTransformationMap()
{
return transformationMap;
}
/**
* @param transformationMap the transformation map to set
*/
public void setTransformationMap(Map transformationMap)
{
this.transformationMap = transformationMap;
}
/**
* @return the tabMap
*/
public Map getTabMap()
{
return tabMap;
}
/**
* @param tabMap the tabMap to set
*/
public void setTabMap(Map tabMap)
{
this.tabMap = tabMap;
}
public void pasteSteps()
{
// Is there an active SpoonGraph?
SpoonGraph spoonGraph = getActiveSpoonGraph();
if (spoonGraph==null) return;
TransMeta transMeta = spoonGraph.getTransMeta();
String clipcontent = fromClipboard();
if (clipcontent != null)
{
Point lastMove = spoonGraph.getLastMove();
if (lastMove != null)
{
pasteXML(transMeta, clipcontent, lastMove);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//
//
//
// Job manipulation steps...
//
//
//
//////////////////////////////////////////////////////////////////////////////////////////////////
public JobEntryCopy newJobEntry(JobMeta jobMeta, String type_desc, boolean openit)
{
JobEntryLoader jobLoader = JobEntryLoader.getInstance();
JobPlugin jobPlugin = null;
try
{
jobPlugin = jobLoader.findJobEntriesWithDescription(type_desc);
if (jobPlugin==null)
{
// Check if it's not START or DUMMY
if (JobMeta.STRING_SPECIAL_START.equals(type_desc) || JobMeta.STRING_SPECIAL_DUMMY.equals(type_desc))
{
jobPlugin = jobLoader.findJobEntriesWithID(JobMeta.STRING_SPECIAL);
}
}
if (jobPlugin!=null)
{
// Determine name & number for this entry.
String basename = type_desc;
int nr = jobMeta.generateJobEntryNameNr(basename);
String entry_name = basename+" "+nr; //$NON-NLS-1$
// Generate the appropriate class...
JobEntryInterface jei = jobLoader.getJobEntryClass(jobPlugin);
jei.setName(entry_name);
if (jei.isSpecial())
{
if (JobMeta.STRING_SPECIAL_START.equals(type_desc))
{
// Check if start is already on the canvas...
if (jobMeta.findStart()!=null)
{
ChefGraph.showOnlyStartOnceMessage(shell);
return null;
}
((JobEntrySpecial)jei).setStart(true);
jei.setName("Start");
}
if (JobMeta.STRING_SPECIAL_DUMMY.equals(type_desc))
{
((JobEntrySpecial)jei).setDummy(true);
jei.setName("Dummy");
}
}
if (openit)
{
JobEntryDialogInterface d = jei.getDialog(shell,jei,jobMeta,entry_name,rep);
if (d.open()!=null)
{
JobEntryCopy jge = new JobEntryCopy();
jge.setEntry(jei);
jge.setLocation(50,50);
jge.setNr(0);
jobMeta.addJobEntry(jge);
addUndoNew(jobMeta, new JobEntryCopy[] { jge }, new int[] { jobMeta.indexOfJobEntry(jge) });
refreshGraph();
refreshTree();
return jge;
}
else
{
return null;
}
}
else
{
JobEntryCopy jge = new JobEntryCopy();
jge.setEntry(jei);
jge.setLocation(50,50);
jge.setNr(0);
jobMeta.addJobEntry(jge);
addUndoNew(jobMeta, new JobEntryCopy[] { jge }, new int[] { jobMeta.indexOfJobEntry(jge) });
refreshGraph();
refreshTree();
return jge;
}
}
else
{
return null;
}
}
catch(Throwable e)
{
new ErrorDialog(shell, Messages.getString("Spoon.ErrorDialog.UnexpectedErrorCreatingNewChefGraphEntry.Title"), Messages.getString("Spoon.ErrorDialog.UnexpectedErrorCreatingNewChefGraphEntry.Message"),new Exception(e)); //$NON-NLS-1$ //$NON-NLS-2$
return null;
}
}
public boolean saveJobFile(JobMeta jobMeta)
{
log.logDetailed(toString(), "Save file..."); //$NON-NLS-1$
boolean saved = false;
if (rep!=null)
{
saved = saveJobRepository(jobMeta);
}
else
{
if (jobMeta.getFilename()!=null)
{
saved = saveJob(jobMeta, jobMeta.getFilename());
}
else
{
saved = saveJobFileAs(jobMeta);
}
}
if (saved) // all was OK
{
saved=saveJobSharedObjects(jobMeta);
}
return saved;
}
private boolean saveJobXMLFile(JobMeta jobMeta)
{
boolean saved=false;
FileDialog dialog = new FileDialog(shell, SWT.SAVE);
dialog.setFilterExtensions(Const.STRING_JOB_FILTER_EXT);
dialog.setFilterNames(Const.STRING_JOB_FILTER_NAMES);
String fname = dialog.open();
if (fname!=null)
{
// Is the filename ending on .ktr, .xml?
boolean ending=false;
for (int i=0;i<Const.STRING_JOB_FILTER_EXT.length-1;i++)
{
if (fname.endsWith(Const.STRING_JOB_FILTER_EXT[i].substring(1)))
{
ending=true;
}
}
if (fname.endsWith(Const.STRING_JOB_DEFAULT_EXT)) ending=true;
if (!ending)
{
fname+=Const.STRING_JOB_DEFAULT_EXT;
}
// See if the file already exists...
File f = new File(fname);
int id = SWT.YES;
if (f.exists())
{
MessageBox mb = new MessageBox(shell, SWT.NO | SWT.YES | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("Spoon.Dialog.PromptOverwriteFile.Message"));//"This file already exists. Do you want to overwrite it?"
mb.setText(Messages.getString("Spoon.Dialog.PromptOverwriteFile.Title"));//"This file already exists!"
id = mb.open();
}
if (id==SWT.YES)
{
saved=saveJob(jobMeta, fname);
jobMeta.setFilename(fname);
}
}
return saved;
}
public boolean saveJobRepository(JobMeta jobMeta)
{
return saveJobRepository(jobMeta, false);
}
public boolean saveJobRepository(JobMeta jobMeta, boolean ask_name)
{
log.logDetailed(toString(), "Save to repository..."); //$NON-NLS-1$
if (rep!=null)
{
boolean answer = true;
boolean ask = ask_name;
while (answer && ( ask || jobMeta.getName()==null || jobMeta.getName().length()==0 ) )
{
if (!ask)
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("Spoon.Dialog.GiveJobANameBeforeSaving.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.GiveJobANameBeforeSaving.Title")); //$NON-NLS-1$
mb.open();
}
ask=false;
answer = editJobProperties(jobMeta);
}
if (answer && jobMeta.getName()!=null && jobMeta.getName().length()>0)
{
if (!rep.getUserInfo().isReadonly())
{
boolean saved=false;
int response = SWT.YES;
if (jobMeta.showReplaceWarning(rep))
{
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.ICON_QUESTION);
mb.setMessage(Messages.getString("Chef.Dialog.JobExistsOverwrite.Message1")+jobMeta.getName()+Messages.getString("Chef.Dialog.JobExistsOverwrite.Message2")+Const.CR+Messages.getString("Chef.Dialog.JobExistsOverwrite.Message3")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
mb.setText(Messages.getString("Chef.Dialog.JobExistsOverwrite.Title")); //$NON-NLS-1$
response = mb.open();
}
if (response == SWT.YES)
{
// Keep info on who & when this transformation was changed...
jobMeta.modifiedDate = new Value("MODIFIED_DATE", Value.VALUE_TYPE_DATE); //$NON-NLS-1$
jobMeta.modifiedDate.sysdate();
jobMeta.modifiedUser = rep.getUserInfo().getLogin();
JobSaveProgressDialog jspd = new JobSaveProgressDialog(shell, rep, jobMeta);
if (jspd.open())
{
if (!props.getSaveConfirmation())
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell,
Messages.getString("Spoon.Dialog.JobWasStoredInTheRepository.Title"), //$NON-NLS-1$
null,
Messages.getString("Spoon.Dialog.JobWasStoredInTheRepository.Message"), //$NON-NLS-1$
MessageDialog.QUESTION,
new String[] { Messages.getString("System.Button.OK") }, //$NON-NLS-1$
0,
Messages.getString("Spoon.Dialog.JobWasStoredInTheRepository.Toggle"), //$NON-NLS-1$
props.getSaveConfirmation()
);
md.open();
props.setSaveConfirmation(md.getToggleState());
}
// Handle last opened files...
props.addLastFile(LastUsedFile.FILE_TYPE_JOB, jobMeta.getName(), jobMeta.getDirectory().getPath(), true, rep.getName());
saveSettings();
addMenuLast();
setShellText();
saved=true;
}
}
return saved;
}
else
{
MessageBox mb = new MessageBox(shell, SWT.CLOSE | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("Spoon.Dialog.UserCanOnlyReadFromTheRepositoryJobNotSaved.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.UserCanOnlyReadFromTheRepositoryJobNotSaved.Title")); //$NON-NLS-1$
mb.open();
}
}
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("Spoon.Dialog.NoRepositoryConnectionAvailable.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.NoRepositoryConnectionAvailable.Title")); //$NON-NLS-1$
mb.open();
}
return false;
}
public boolean saveJobFileAs(JobMeta jobMeta)
{
boolean saved=false;
if (rep!=null)
{
jobMeta.setID(-1L);
saved=saveJobRepository(jobMeta, true);
}
else
{
saved=saveJobXMLFile(jobMeta);
}
return saved;
}
public void saveJobFileAsXML(JobMeta jobMeta)
{
log.logBasic(toString(), "Save file as..."); //$NON-NLS-1$
FileDialog dialog = new FileDialog(shell, SWT.SAVE);
//dialog.setFilterPath("C:\\Projects\\kettle\\source\\");
dialog.setFilterExtensions(Const.STRING_JOB_FILTER_EXT);
dialog.setFilterNames (Const.STRING_JOB_FILTER_NAMES);
String fname = dialog.open();
if (fname!=null)
{
// Is the filename ending on .ktr, .xml?
boolean ending=false;
for (int i=0;i<Const.STRING_JOB_FILTER_EXT.length-1;i++)
{
if (fname.endsWith(Const.STRING_JOB_FILTER_EXT[i].substring(1))) ending=true;
}
if (fname.endsWith(Const.STRING_JOB_DEFAULT_EXT)) ending=true;
if (!ending)
{
fname+=Const.STRING_JOB_DEFAULT_EXT;
}
// See if the file already exists...
File f = new File(fname);
int id = SWT.YES;
if (f.exists())
{
MessageBox mb = new MessageBox(shell, SWT.NO | SWT.YES | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("Spoon.Dialog.FileExistsOverWrite.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.FileExistsOverWrite.Title")); //$NON-NLS-1$
id = mb.open();
}
if (id==SWT.YES)
{
saveJob(jobMeta, fname);
}
}
}
private boolean saveJob(JobMeta jobMeta, String fname)
{
boolean saved = false;
String xml = XMLHandler.getXMLHeader() + jobMeta.getXML();
try
{
DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File(fname)));
dos.write(xml.getBytes(Const.XML_ENCODING));
dos.close();
saved=true;
// Handle last opened files...
props.addLastFile(LastUsedFile.FILE_TYPE_JOB, fname, RepositoryDirectory.DIRECTORY_SEPARATOR, false, ""); //$NON-NLS-1$
saveSettings();
addMenuLast();
log.logDebug(toString(), "File written to ["+fname+"]"); //$NON-NLS-1$ //$NON-NLS-2$
jobMeta.setFilename( fname );
jobMeta.clearChanged();
setShellText();
}
catch(Exception e)
{
log.logDebug(toString(), "Error opening file for writing! --> "+e.toString()); //$NON-NLS-1$
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("Spoon.Dialog.ErrorSavingFile.Message")+Const.CR+e.toString()); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.ErrorSavingFile.Title")); //$NON-NLS-1$
mb.open();
}
return saved;
}
private boolean editJobProperties(JobMeta jobMeta)
{
if (jobMeta==null) return false;
JobDialog jd = new JobDialog(shell, SWT.NONE, jobMeta, rep);
JobMeta ji = jd.open();
// In this case, load shared objects
//
if (jd.isSharedObjectsFileChanged())
{
loadJobSharedObjects(jobMeta);
}
if (jd.isSharedObjectsFileChanged() || ji!=null)
{
refreshTree();
renameTabs(); // cheap operation, might as will do it anyway
}
setShellText();
return ji!=null;
}
public void editJobEntry(JobMeta jobMeta, JobEntryCopy je)
{
try
{
log.logBasic(toString(), "edit job graph entry: "+je.getName()); //$NON-NLS-1$
JobEntryCopy before =(JobEntryCopy)je.clone_deep();
boolean entry_changed=false;
JobEntryInterface jei = je.getEntry();
if (jei.isSpecial())
{
JobEntrySpecial special = (JobEntrySpecial) jei;
if (special.isDummy()) return;
}
JobEntryDialogInterface d = jei.getDialog(shell, jei, jobMeta,je.getName(),rep);
if (d!=null)
{
if (d.open()!=null)
{
entry_changed=true;
}
if (entry_changed)
{
JobEntryCopy after = (JobEntryCopy) je.clone();
addUndoChange(jobMeta, new JobEntryCopy[] { before }, new JobEntryCopy[] { after }, new int[] { jobMeta.indexOfJobEntry(je) } );
refreshGraph();
refreshTree();
}
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(Messages.getString("Spoon.Dialog.JobEntryCanNotBeChanged.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.JobEntryCanNotBeChanged.Title")); //$NON-NLS-1$
mb.open();
}
}
catch(Exception e)
{
if (!shell.isDisposed()) new ErrorDialog(shell, Messages.getString("Chef.ErrorDialog.ErrorEditingJobEntry.Title"), Messages.getString("Chef.ErrorDialog.ErrorEditingJobEntry.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public JobEntryTrans newJobEntry(JobMeta jobMeta, int type)
{
JobEntryTrans je = new JobEntryTrans();
je.setType(type);
String basename = JobEntryTrans.typeDesc[type];
int nr = jobMeta.generateJobEntryNameNr(basename);
je.setName(basename+" "+nr); //$NON-NLS-1$
setShellText();
return je;
}
public void deleteJobEntryCopies(JobMeta jobMeta, JobEntryCopy jobEntry)
{
String name = jobEntry.getName();
// TODO Show warning "Are you sure? This operation can't be undone." + clear undo buffer.
// First delete all the hops using entry with name:
JobHopMeta hi[] = jobMeta.getAllJobHopsUsing(name);
if (hi.length>0)
{
int hix[] = new int[hi.length];
for (int i=0;i<hi.length;i++) hix[i] = jobMeta.indexOfJobHop(hi[i]);
addUndoDelete(jobMeta, hi, hix);
for (int i=hix.length-1;i>=0;i--) jobMeta.removeJobHop(hix[i]);
}
// Then delete all the entries with name:
JobEntryCopy je[] = jobMeta.getAllChefGraphEntries(name);
int jex[] = new int[je.length];
for (int i=0;i<je.length;i++) jex[i] = jobMeta.indexOfJobEntry(je[i]);
addUndoDelete(jobMeta, je, jex);
for (int i=jex.length-1;i>=0;i--) jobMeta.removeJobEntry(jex[i]);
refreshGraph();
refreshTree();
}
public void dupeJobEntry(JobMeta jobMeta, JobEntryCopy jobEntry)
{
if (jobEntry!=null && !jobEntry.isStart())
{
JobEntryCopy dupejge = (JobEntryCopy)jobEntry.clone();
dupejge.setNr( jobMeta.findUnusedNr(dupejge.getName()) );
if (dupejge.isDrawn())
{
Point p = jobEntry.getLocation();
dupejge.setLocation(p.x+10, p.y+10);
}
jobMeta.addJobEntry(dupejge);
refreshGraph();
refreshTree();
setShellText();
}
}
public void copyJobEntries(JobMeta jobMeta, JobEntryCopy jec[])
{
if (jec==null || jec.length==0) return;
String xml = XMLHandler.getXMLHeader();
xml+="<jobentries>"+Const.CR; //$NON-NLS-1$
for (int i=0;i<jec.length;i++)
{
xml+=jec[i].getXML();
}
xml+=" </jobentries>"+Const.CR; //$NON-NLS-1$
toClipboard(xml);
}
public void pasteXML(JobMeta jobMeta, String clipcontent, Point loc)
{
try
{
Document doc = XMLHandler.loadXMLString(clipcontent);
// De-select all, re-select pasted steps...
jobMeta.unselectAll();
Node entriesnode = XMLHandler.getSubNode(doc, "jobentries"); //$NON-NLS-1$
int nr = XMLHandler.countNodes(entriesnode, "entry"); //$NON-NLS-1$
log.logDebug(toString(), "I found "+nr+" job entries to paste on location: "+loc); //$NON-NLS-1$ //$NON-NLS-2$
JobEntryCopy entries[] = new JobEntryCopy[nr];
//Point min = new Point(loc.x, loc.y);
Point min = new Point(99999999,99999999);
for (int i=0;i<nr;i++)
{
Node entrynode = XMLHandler.getSubNodeByNr(entriesnode, "entry", i); //$NON-NLS-1$
entries[i] = new JobEntryCopy(entrynode, jobMeta.getDatabases(), rep);
String name = jobMeta.getAlternativeJobentryName(entries[i].getName());
entries[i].setName(name);
if (loc!=null)
{
Point p = entries[i].getLocation();
if (min.x > p.x) min.x = p.x;
if (min.y > p.y) min.y = p.y;
}
}
// What's the difference between loc and min?
// This is the offset:
Point offset = new Point(loc.x-min.x, loc.y-min.y);
// Undo/redo object positions...
int position[] = new int[entries.length];
for (int i=0;i<entries.length;i++)
{
Point p = entries[i].getLocation();
String name = entries[i].getName();
entries[i].setLocation(p.x+offset.x, p.y+offset.y);
// Check the name, find alternative...
entries[i].setName( jobMeta.getAlternativeJobentryName(name) );
jobMeta.addJobEntry(entries[i]);
position[i] = jobMeta.indexOfJobEntry(entries[i]);
}
// Save undo information too...
addUndoNew(jobMeta, entries, position);
if (jobMeta.hasChanged())
{
refreshTree();
refreshGraph();
}
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Chef.ErrorDialog.ErrorPasingJobEntries.Title"), Messages.getString("Chef.ErrorDialog.ErrorPasingJobEntries.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public void newJobHop(JobMeta jobMeta, JobEntryCopy fr, JobEntryCopy to)
{
JobHopMeta hi = new JobHopMeta(fr, to);
jobMeta.addJobHop(hi);
addUndoNew(jobMeta, new JobHopMeta[] {hi}, new int[] { jobMeta.indexOfJobHop(hi)} );
refreshGraph();
refreshTree();
}
/**
* Create a job that extracts tables & data from a database.<p><p>
*
* 0) Select the database to rip<p>
* 1) Select the tables in the database to rip<p>
* 2) Select the database to dump to<p>
* 3) Select the repository directory in which it will end up<p>
* 4) Select a name for the new job<p>
* 5) Create an empty job with the selected name.<p>
* 6) Create 1 transformation for every selected table<p>
* 7) add every created transformation to the job & evaluate<p>
*
*/
private void ripDBWizard()
{
final ArrayList databases = getActiveDatabases();
if (databases.size() == 0) return; // Nothing to do here
final RipDatabaseWizardPage1 page1 = new RipDatabaseWizardPage1("1", databases); //$NON-NLS-1$
page1.createControl(shell);
final RipDatabaseWizardPage2 page2 = new RipDatabaseWizardPage2("2"); //$NON-NLS-1$
page2.createControl(shell);
final RipDatabaseWizardPage3 page3 = new RipDatabaseWizardPage3("3", rep); //$NON-NLS-1$
page3.createControl(shell);
Wizard wizard = new Wizard()
{
public boolean performFinish()
{
JobMeta jobMeta = ripDB(databases, page3.getJobname(), page3.getDirectory(), page1.getSourceDatabase(), page1.getTargetDatabase(), page2.getSelection());
if (jobMeta==null) return false;
addChefGraph(jobMeta);
return true;
}
/**
* @see org.eclipse.jface.wizard.Wizard#canFinish()
*/
public boolean canFinish()
{
return page3.canFinish();
}
};
wizard.addPage(page1);
wizard.addPage(page2);
wizard.addPage(page3);
WizardDialog wd = new WizardDialog(shell, wizard);
wd.setMinimumPageSize(700, 400);
wd.open();
}
public JobMeta ripDB(
final ArrayList databases,
final String jobname,
final RepositoryDirectory repdir,
final DatabaseMeta sourceDbInfo,
final DatabaseMeta targetDbInfo,
final String[] tables
)
{
//
// Create a new job...
//
final JobMeta jobMeta = new JobMeta(log);
jobMeta.setDatabases(databases);
jobMeta.setFilename(null);
jobMeta.setName(jobname);
jobMeta.setDirectory(repdir);
refreshTree();
refreshGraph();
final Point location = new Point(50, 50);
// The start entry...
final JobEntryCopy start = jobMeta.findStart();
start.setLocation(new Point(location.x, location.y));
start.setDrawn();
// final Thread parentThread = Thread.currentThread();
// Create a dialog with a progress indicator!
IRunnableWithProgress op = new IRunnableWithProgress()
{
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException
{
// This is running in a new process: copy some KettleVariables info
// LocalVariables.getInstance().createKettleVariables(Thread.currentThread().getName(),
// parentThread.getName(), true);
monitor.beginTask(Messages.getString("Spoon.RipDB.Monitor.BuildingNewJob"), tables.length); //$NON-NLS-1$
monitor.worked(0);
JobEntryCopy previous = start;
// Loop over the table-names...
for (int i = 0; i < tables.length && !monitor.isCanceled(); i++)
{
monitor.setTaskName(Messages.getString("Spoon.RipDB.Monitor.ProcessingTable") + tables[i] + "]..."); //$NON-NLS-1$ //$NON-NLS-2$
//
// Create the new transformation...
//
String transname = Messages.getString("Spoon.RipDB.Monitor.Transname1") + sourceDbInfo + "].[" + tables[i] + Messages.getString("Spoon.RipDB.Monitor.Transname2") + targetDbInfo + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
TransMeta ti = new TransMeta((String) null, transname, null);
ti.setDirectory(repdir);
//
// Add a note
//
String note = Messages.getString("Spoon.RipDB.Monitor.Note1") + tables[i] + Messages.getString("Spoon.RipDB.Monitor.Note2") + sourceDbInfo + "]" + Const.CR; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
note += Messages.getString("Spoon.RipDB.Monitor.Note3") + tables[i] + Messages.getString("Spoon.RipDB.Monitor.Note4") + targetDbInfo + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
NotePadMeta ni = new NotePadMeta(note, 150, 10, -1, -1);
ti.addNote(ni);
//
// Add the TableInputMeta step...
//
String fromstepname = Messages.getString("Spoon.RipDB.Monitor.FromStep.Name") + tables[i] + "]"; //$NON-NLS-1$ //$NON-NLS-2$
TableInputMeta tii = new TableInputMeta();
tii.setDatabaseMeta(sourceDbInfo);
tii.setSQL("SELECT * FROM " + sourceDbInfo.quoteField(tables[i])); //$NON-NLS-1$
String fromstepid = StepLoader.getInstance().getStepPluginID(tii);
StepMeta fromstep = new StepMeta(fromstepid, fromstepname, (StepMetaInterface) tii);
fromstep.setLocation(150, 100);
fromstep.setDraw(true);
fromstep
.setDescription(Messages.getString("Spoon.RipDB.Monitor.FromStep.Description") + tables[i] + Messages.getString("Spoon.RipDB.Monitor.FromStep.Description2") + sourceDbInfo + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
ti.addStep(fromstep);
//
// Add the TableOutputMeta step...
//
String tostepname = Messages.getString("Spoon.RipDB.Monitor.ToStep.Name") + tables[i] + "]"; //$NON-NLS-1$ //$NON-NLS-2$
TableOutputMeta toi = new TableOutputMeta();
toi.setDatabaseMeta(targetDbInfo);
toi.setTablename(tables[i]);
toi.setCommitSize(100);
toi.setTruncateTable(true);
String tostepid = StepLoader.getInstance().getStepPluginID(toi);
StepMeta tostep = new StepMeta(tostepid, tostepname, (StepMetaInterface) toi);
tostep.setLocation(500, 100);
tostep.setDraw(true);
tostep
.setDescription(Messages.getString("Spoon.RipDB.Monitor.ToStep.Description1") + tables[i] + Messages.getString("Spoon.RipDB.Monitor.ToStep.Description2") + targetDbInfo + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
ti.addStep(tostep);
//
// Add a hop between the two steps...
//
TransHopMeta hi = new TransHopMeta(fromstep, tostep);
ti.addTransHop(hi);
//
// Now we generate the SQL needed to run for this transformation.
//
// First set the limit to 1 to speed things up!
String tmpSql = tii.getSQL();
tii.setSQL(tii.getSQL() + sourceDbInfo.getLimitClause(1));
String sql = ""; //$NON-NLS-1$
try
{
sql = ti.getSQLStatementsString();
}
catch (KettleStepException kse)
{
throw new InvocationTargetException(kse,
Messages.getString("Spoon.RipDB.Exception.ErrorGettingSQLFromTransformation") + ti + "] : " + kse.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
}
// remove the limit
tii.setSQL(tmpSql);
//
// Now, save the transformation...
//
try
{
ti.saveRep(rep);
}
catch (KettleException dbe)
{
throw new InvocationTargetException(dbe, Messages.getString("Spoon.RipDB.Exception.UnableToSaveTransformationToRepository")); //$NON-NLS-1$
}
// We can now continue with the population of the job...
// //////////////////////////////////////////////////////////////////////
location.x = 250;
if (i > 0) location.y += 100;
//
// We can continue defining the job.
//
// First the SQL, but only if needed!
// If the table exists & has the correct format, nothing is done
//
if (!Const.isEmpty(sql))
{
String jesqlname = Messages.getString("Spoon.RipDB.JobEntrySQL.Name") + tables[i] + "]"; //$NON-NLS-1$ //$NON-NLS-2$
JobEntrySQL jesql = new JobEntrySQL(jesqlname);
jesql.setDatabase(targetDbInfo);
jesql.setSQL(sql);
jesql.setDescription(Messages.getString("Spoon.RipDB.JobEntrySQL.Description") + targetDbInfo + "].[" + tables[i] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
JobEntryCopy jecsql = new JobEntryCopy();
jecsql.setEntry(jesql);
jecsql.setLocation(new Point(location.x, location.y));
jecsql.setDrawn();
jobMeta.addJobEntry(jecsql);
// Add the hop too...
JobHopMeta jhi = new JobHopMeta(previous, jecsql);
jobMeta.addJobHop(jhi);
previous = jecsql;
}
//
// Add the jobentry for the transformation too...
//
String jetransname = Messages.getString("Spoon.RipDB.JobEntryTrans.Name") + tables[i] + "]"; //$NON-NLS-1$ //$NON-NLS-2$
JobEntryTrans jetrans = new JobEntryTrans(jetransname);
jetrans.setTransname(ti.getName());
jetrans.setDirectory(ti.getDirectory());
JobEntryCopy jectrans = new JobEntryCopy(log, jetrans);
jectrans
.setDescription(Messages.getString("Spoon.RipDB.JobEntryTrans.Description1") + Const.CR + Messages.getString("Spoon.RipDB.JobEntryTrans.Description2") + sourceDbInfo + "].[" + tables[i] + "]" + Const.CR + Messages.getString("Spoon.RipDB.JobEntryTrans.Description3") + targetDbInfo + "].[" + tables[i] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
jectrans.setDrawn();
location.x += 400;
jectrans.setLocation(new Point(location.x, location.y));
jobMeta.addJobEntry(jectrans);
// Add a hop between the last 2 job entries.
JobHopMeta jhi2 = new JobHopMeta(previous, jectrans);
jobMeta.addJobHop(jhi2);
previous = jectrans;
monitor.worked(1);
}
monitor.worked(100);
monitor.done();
}
};
try
{
ProgressMonitorDialog pmd = new ProgressMonitorDialog(shell);
pmd.run(false, true, op);
}
catch (InvocationTargetException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.ErrorDialog.RipDB.ErrorRippingTheDatabase.Title"), Messages.getString("Spoon.ErrorDialog.RipDB.ErrorRippingTheDatabase.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
return null;
}
catch (InterruptedException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.ErrorDialog.RipDB.ErrorRippingTheDatabase.Title"), Messages.getString("Spoon.ErrorDialog.RipDB.ErrorRippingTheDatabase.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
return null;
}
finally
{
refreshGraph();
refreshTree();
}
return jobMeta;
}
/**
* Set the core object state.
*
* @param state
*/
public void setCoreObjectsState(int state)
{
coreObjectsState = state;
}
/**
* Get the core object state.
*
* @return state.
*/
public int getCoreObjectsState()
{
return coreObjectsState;
}
}
|
public void verifyCopyDistribute(TransMeta transMeta, StepMeta fr)
{
int nrNextSteps = transMeta.findNrNextSteps(fr);
// don't show it for 3 or more hops, by then you should have had the message
if (nrNextSteps==2)
{
boolean distributes = false;
if (props.showCopyOrDistributeWarning())
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell,
Messages.getString("System.Warning"),//"Warning!"
null,
Messages.getString("Spoon.Dialog.CopyOrDistribute.Message", fr.getName(), Integer.toString(nrNextSteps)),
MessageDialog.WARNING,
new String[] { Messages.getString("Spoon.Dialog.CopyOrDistribute.Copy"), Messages.getString("Spoon.Dialog.CopyOrDistribute.Distribute") },//"Copy Distribute
0,
Messages.getString("Spoon.Message.Warning.NotShowWarning"),//"Please, don't show this warning anymore."
!props.showCopyOrDistributeWarning()
);
int idx = md.open();
props.setShowCopyOrDistributeWarning(!md.getToggleState());
props.saveProps();
distributes = (idx&0xFF)==1;
}
if (distributes)
{
fr.setDistributes(true);
}
else
{
fr.setDistributes(false);
}
refreshTree();
refreshGraph();
}
}
public void newHop(TransMeta transMeta)
{
newHop(transMeta, null, null);
}
public void newConnection(HasDatabasesInterface hasDatabasesInterface)
{
DatabaseMeta databaseMeta = new DatabaseMeta();
DatabaseDialog con = new DatabaseDialog(shell, databaseMeta);
String con_name = con.open();
if (!Const.isEmpty(con_name))
{
databaseMeta.verifyAndModifyDatabaseName(hasDatabasesInterface.getDatabases(), null);
hasDatabasesInterface.addDatabase(databaseMeta);
addUndoNew((UndoInterface)hasDatabasesInterface, new DatabaseMeta[] { (DatabaseMeta)databaseMeta.clone() }, new int[] { hasDatabasesInterface.indexOfDatabase(databaseMeta) });
saveConnection(databaseMeta);
refreshTree();
}
}
public void saveConnection(DatabaseMeta db)
{
// Also add to repository?
if (rep!=null)
{
if (!rep.userinfo.isReadonly())
{
try
{
rep.lockRepository();
rep.insertLogEntry("Saving database '"+db.getName()+"'");
db.saveRep(rep);
log.logDetailed(toString(), Messages.getString("Spoon.Log.SavedDatabaseConnection",db.getDatabaseName()));//"Saved database connection ["+db+"] to the repository."
// Put a commit behind it!
rep.commit();
db.setChanged(false);
}
catch(KettleException ke)
{
rep.rollback(); // In case of failure: undo changes!
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorSavingConnection.Title"),Messages.getString("Spoon.Dialog.ErrorSavingConnection.Message",db.getDatabaseName()), ke);//"Can't save...","Error saving connection ["+db+"] to repository!"
}
finally
{
try
{
rep.unlockRepository();
}
catch(KettleDatabaseException e)
{
new ErrorDialog(shell, "Error", "Unexpected error unlocking the repository database", e);
}
}
}
else
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.UnableSave.Title"),Messages.getString("Spoon.Dialog.ErrorSavingConnection.Message",db.getDatabaseName()), new KettleException(Messages.getString("Spoon.Dialog.Exception.ReadOnlyRepositoryUser")));//This repository user is read-only!
}
}
}
public void openRepository()
{
int perms[] = new int[] { PermissionMeta.TYPE_PERMISSION_TRANSFORMATION };
RepositoriesDialog rd = new RepositoriesDialog(disp, SWT.NONE, perms, APP_NAME);
rd.getShell().setImage(GUIResource.getInstance().getImageSpoon());
if (rd.open())
{
// Close previous repository...
if (rep!=null)
{
rep.disconnect();
}
rep = new Repository(log, rd.getRepository(), rd.getUser());
try
{
rep.connect(APP_NAME);
}
catch(KettleException ke)
{
rep=null;
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorConnectingRepository.Title"), Messages.getString("Spoon.Dialog.ErrorConnectingRepository.Message",Const.CR), ke); //$NON-NLS-1$ //$NON-NLS-2$
}
TransMeta transMetas[] = getLoadedTransformations();
for (int t=0;t<transMetas.length;t++)
{
TransMeta transMeta = transMetas[t];
for (int i=0;i<transMeta.nrDatabases();i++)
{
transMeta.getDatabase(i).setID(-1L);
}
// Set for the existing transformation the ID at -1!
transMeta.setID(-1L);
// Keep track of the old databases for now.
ArrayList oldDatabases = transMeta.getDatabases();
// In order to re-match the databases on name (not content), we need to load the databases from the new repository.
// NOTE: for purposes such as DEVELOP - TEST - PRODUCTION sycles.
// first clear the list of databases, partition schemas, slave servers, clusters
transMeta.setDatabases(new ArrayList());
transMeta.setPartitionSchemas(new ArrayList());
transMeta.setSlaveServers(new ArrayList());
transMeta.setClusterSchemas(new ArrayList());
// Read them from the new repository.
try
{
transMeta.readSharedObjects(rep);
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", makeGraphTabName(transMeta)), e);
}
// Then we need to re-match the databases at save time...
for (int i=0;i<oldDatabases.size();i++)
{
DatabaseMeta oldDatabase = (DatabaseMeta) oldDatabases.get(i);
DatabaseMeta newDatabase = Const.findDatabase(transMeta.getDatabases(), oldDatabase.getName());
// If it exists, change the settings...
if (newDatabase!=null)
{
//
// A database connection with the same name exists in the new repository.
// Change the old connections to reflect the settings in the new repository
//
oldDatabase.setDatabaseInterface(newDatabase.getDatabaseInterface());
}
else
{
//
// The old database is not present in the new repository: simply add it to the list.
// When the transformation gets saved, it will be added to the repository.
//
transMeta.addDatabase(oldDatabase);
}
}
// For the existing transformation, change the directory too:
// Try to find the same directory in the new repository...
RepositoryDirectory redi = rep.getDirectoryTree().findDirectory(transMeta.getDirectory().getPath());
if (redi!=null)
{
transMeta.setDirectory(redi);
}
else
{
transMeta.setDirectory(rep.getDirectoryTree()); // the root is the default!
}
}
refreshTree();
setShellText();
}
else
{
// Not cancelled? --> Clear repository...
if (!rd.isCancelled())
{
closeRepository();
}
}
}
public void exploreRepository()
{
if (rep!=null)
{
RepositoryExplorerDialog erd = new RepositoryExplorerDialog(shell, SWT.NONE, rep, rep.getUserInfo());
String objname = erd.open();
if (objname!=null)
{
String object_type = erd.getObjectType();
RepositoryDirectory repdir = erd.getObjectDirectory();
// Try to open the selected transformation.
if (object_type.equals(RepositoryExplorerDialog.STRING_TRANSFORMATIONS))
{
try
{
TransMeta transMeta = new TransMeta(rep, objname, repdir);
transMeta.clearChanged();
transMeta.setFilename(objname);
addSpoonGraph(transMeta);
refreshTree();
refreshGraph();
}
catch(KettleException e)
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("Spoon.Dialog.ErrorOpening.Message")+objname+Const.CR+e.getMessage());//"Error opening : "
mb.setText(Messages.getString("Spoon.Dialog.ErrorOpening.Title"));
mb.open();
}
}
else
// Try to open the selected job.
if (object_type.equals(RepositoryExplorerDialog.STRING_JOBS))
{
try
{
JobMeta jobMeta = new JobMeta(log, rep, objname, repdir);
jobMeta.clearChanged();
jobMeta.setFilename(objname);
addChefGraph(jobMeta);
refreshTree();
refreshGraph();
}
catch(KettleException e)
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("Spoon.Dialog.ErrorOpening.Message")+objname+Const.CR+e.getMessage());//"Error opening : "
mb.setText(Messages.getString("Spoon.Dialog.ErrorOpening.Title"));
mb.open();
}
}
}
}
}
public void editRepositoryUser()
{
if (rep!=null)
{
UserInfo userinfo = rep.getUserInfo();
UserDialog ud = new UserDialog(shell, SWT.NONE, log, props, rep, userinfo);
UserInfo ui = ud.open();
if (!userinfo.isReadonly())
{
if (ui!=null)
{
try
{
ui.saveRep(rep);
}
catch(KettleException e)
{
MessageBox mb = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
mb.setMessage(Messages.getString("Spoon.Dialog.UnableChangeUser.Message")+Const.CR+e.getMessage());//Sorry, I was unable to change this user in the repository:
mb.setText(Messages.getString("Spoon.Dialog.UnableChangeUser.Title"));//"Edit user"
mb.open();
}
}
}
else
{
MessageBox mb = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
mb.setMessage(Messages.getString("Spoon.Dialog.NotAllowedChangeUser.Message"));//"Sorry, you are not allowed to change this user."
mb.setText(Messages.getString("Spoon.Dialog.NotAllowedChangeUser.Title"));
mb.open();
}
}
}
public void closeRepository()
{
if (rep!=null) rep.disconnect();
rep = null;
setShellText();
}
public void openFile(boolean importfile)
{
if (rep==null || importfile) // Load from XML
{
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(Const.STRING_TRANS_AND_JOB_FILTER_EXT);
dialog.setFilterNames(Const.STRING_TRANS_AND_JOB_FILTER_NAMES);
String fname = dialog.open();
if (fname!=null)
{
openFile(fname, importfile);
}
}
else
{
SelectObjectDialog sod = new SelectObjectDialog(shell, rep);
if (sod.open()!=null)
{
String type = sod.getObjectType();
String name = sod.getObjectName();
RepositoryDirectory repdir = sod.getDirectory();
// Load a transformation
if (RepositoryObject.STRING_OBJECT_TYPE_TRANSFORMATION.equals(type))
{
TransLoadProgressDialog tlpd = new TransLoadProgressDialog(shell, rep, name, repdir);
TransMeta transMeta = tlpd.open();
if (transMeta!=null)
{
log.logDetailed(toString(),Messages.getString("Spoon.Log.LoadToTransformation",name,repdir.getDirectoryName()) );//"Transformation ["+transname+"] in directory ["+repdir+"] loaded from the repository."
props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, name, repdir.getPath(), true, rep.getName());
addMenuLast();
transMeta.clearChanged();
transMeta.setFilename(name);
addSpoonGraph(transMeta);
}
refreshGraph();
refreshTree();
refreshHistory();
}
else
// Load a job
if (RepositoryObject.STRING_OBJECT_TYPE_JOB.equals(type))
{
JobLoadProgressDialog jlpd = new JobLoadProgressDialog(shell, rep, name, repdir);
JobMeta jobMeta = jlpd.open();
if (jobMeta!=null)
{
props.addLastFile(LastUsedFile.FILE_TYPE_JOB, name, repdir.getPath(), true, rep.getName());
saveSettings();
addMenuLast();
addChefGraph(jobMeta);
}
refreshGraph();
refreshTree();
}
}
}
}
public void openFile(String fname, boolean importfile)
{
// Open the XML and see what's in there.
// We expect a single <transformation> or <job> root at this time...
try
{
Document document = XMLHandler.loadXMLFile(fname);
boolean loaded = false;
// Check for a transformation...
Node transNode = XMLHandler.getSubNode(document, TransMeta.XML_TAG);
if (transNode!=null) // yep, found a transformation
{
TransMeta transMeta = new TransMeta();
transMeta.loadXML(transNode, rep, true);
props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, fname, null, false, null);
addMenuLast();
if (!importfile) transMeta.clearChanged();
transMeta.setFilename(fname);
addSpoonGraph(transMeta);
refreshTree();
refreshHistory();
loaded=true;
}
// Check for a job...
Node jobNode = XMLHandler.getSubNode(document, JobMeta.XML_TAG);
if (jobNode!=null) // Indeed, found a job
{
JobMeta jobMeta = new JobMeta(log);
jobMeta.loadXML(jobNode, rep);
props.addLastFile(LastUsedFile.FILE_TYPE_JOB, fname, null, false, null);
addMenuLast();
if (!importfile) jobMeta.clearChanged();
jobMeta.setFilename(fname);
addChefGraph(jobMeta);
loaded=true;
}
if (!loaded)
{
// Give error back
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("Spoon.UnknownFileType.Message", fname));
mb.setText(Messages.getString("Spoon.UnknownFileType.Title"));
mb.open();
}
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorOpening.Title"), Messages.getString("Spoon.Dialog.ErrorOpening.Message")+fname, e);
}
}
public void newFile()
{
String[] choices = new String[] { STRING_TRANSFORMATION, STRING_JOB };
EnterSelectionDialog enterSelectionDialog = new EnterSelectionDialog(shell, choices, Messages.getString("Spoon.Dialog.NewFile.Title"), Messages.getString("Spoon.Dialog.NewFile.Message"));
if (enterSelectionDialog.open()!=null)
{
switch( enterSelectionDialog.getSelectionNr() )
{
case 0: newTransFile(); break;
case 1: newJobFile(); break;
}
}
}
public void newTransFile()
{
TransMeta transMeta = new TransMeta();
try
{
transMeta.readSharedObjects(rep);
transMeta.clearChanged();
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Exception.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Exception.ErrorReadingSharedObjects.Message"), e);
}
addSpoonGraph(transMeta);
refreshTree();
}
public void newJobFile()
{
try
{
JobMeta jobMeta = new JobMeta(log);
try
{
jobMeta.readSharedObjects(rep);
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", makeJobGraphTabName(jobMeta)), e);
}
addChefGraph(jobMeta);
refreshTree();
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Exception.ErrorCreatingNewJob.Title"), Messages.getString("Spoon.Exception.ErrorCreatingNewJob.Message"), e);
}
}
public void loadRepositoryObjects(TransMeta transMeta)
{
// Load common database info from active repository...
if (rep!=null)
{
try
{
transMeta.readSharedObjects(rep);
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Error.UnableToLoadSharedObjects.Title"), Messages.getString("Spoon.Error.UnableToLoadSharedObjects.Message"), e);
}
}
}
public boolean quitFile()
{
log.logDetailed(toString(), Messages.getString("Spoon.Log.QuitApplication"));//"Quit application."
boolean exit = true;
saveSettings();
if (props.showExitWarning())
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell,
Messages.getString("System.Warning"),//"Warning!"
null,
Messages.getString("Spoon.Message.Warning.PromptExit"), // Are you sure you want to exit?
MessageDialog.WARNING,
new String[] { Messages.getString("Spoon.Message.Warning.Yes"), Messages.getString("Spoon.Message.Warning.No") },//"Yes", "No"
1,
Messages.getString("Spoon.Message.Warning.NotShowWarning"),//"Please, don't show this warning anymore."
!props.showExitWarning()
);
int idx = md.open();
props.setExitWarningShown(!md.getToggleState());
props.saveProps();
if ((idx&0xFF)==1) return false; // No selected: don't exit!
}
// Check all tabs to see if we can close them...
List list = new ArrayList();
list.addAll(tabMap.values());
for (Iterator iter = list.iterator(); iter.hasNext() && exit;)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
TabItemInterface itemInterface = mapEntry.getObject();
if (!itemInterface.canBeClosed())
{
// Show the tab
tabfolder.setSelection( mapEntry.getTabItem() );
// Unsaved work that needs to changes to be applied?
//
int reply= itemInterface.showChangedWarning();
if (reply==SWT.YES)
{
exit=itemInterface.applyChanges();
}
else
{
if (reply==SWT.CANCEL)
{
exit = false;
}
else // SWT.NO
{
exit = true;
}
}
/*
if (mapEntry.getObject() instanceof SpoonGraph)
{
TransMeta transMeta = (TransMeta) mapEntry.getObject().getManagedObject();
if (transMeta.hasChanged())
{
// Show the transformation in question
//
tabfolder.setSelection( mapEntry.getTabItem() );
// Ask if we should save it before closing...
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.CANCEL | SWT.ICON_WARNING );
mb.setMessage(Messages.getString("Spoon.Dialog.SaveChangedFile.Message", makeGraphTabName(transMeta)));//"File has changed! Do you want to save first?"
mb.setText(Messages.getString("Spoon.Dialog.SaveChangedFile.Title"));//"Warning!"
int answer = mb.open();
switch(answer)
{
case SWT.YES: exit=saveFile(transMeta); break;
case SWT.NO: exit=true; break;
case SWT.CANCEL:
exit=false;
break;
}
}
}
// A running transformation?
//
if (mapEntry.getObject() instanceof SpoonLog)
{
SpoonLog spoonLog = (SpoonLog) mapEntry.getObject();
if (spoonLog.isRunning())
{
if (reply==SWT.NO) exit=false; // No selected: don't exit!
}
}
*/
}
}
if (exit) // we have asked about it all and we're still here. Now close all the tabs, stop the running transformations
{
for (Iterator iter = list.iterator(); iter.hasNext() && exit;)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (!mapEntry.getObject().canBeClosed())
{
// Unsaved transformation?
//
if (mapEntry.getObject() instanceof SpoonGraph)
{
TransMeta transMeta = (TransMeta) mapEntry.getObject().getManagedObject();
if (transMeta.hasChanged())
{
mapEntry.getTabItem().dispose();
}
}
// A running transformation?
//
if (mapEntry.getObject() instanceof SpoonLog)
{
SpoonLog spoonLog = (SpoonLog) mapEntry.getObject();
if (spoonLog.isRunning())
{
spoonLog.stop();
mapEntry.getTabItem().dispose();
}
}
}
}
}
if (exit) dispose();
return exit;
}
public boolean saveFile()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null) return saveTransFile(transMeta);
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null) return saveJobFile(jobMeta);
return false;
}
public boolean saveTransFile(TransMeta transMeta)
{
if (transMeta==null) return false;
boolean saved=false;
log.logDetailed(toString(), Messages.getString("Spoon.Log.SaveToFileOrRepository"));//"Save to file or repository..."
if (rep!=null)
{
saved=saveTransRepository(transMeta);
}
else
{
if (transMeta.getFilename()!=null)
{
saved=save(transMeta, transMeta.getFilename());
}
else
{
saved=saveTransFileAs(transMeta);
}
}
if (saved) // all was OK
{
saved=saveTransSharedObjects(transMeta);
}
try
{
if (props.useDBCache()) transMeta.getDbCache().saveCache(log);
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorSavingDatabaseCache.Title"), Messages.getString("Spoon.Dialog.ErrorSavingDatabaseCache.Message"), e);//"An error occured saving the database cache to disk"
}
renameTabs(); // filename or name of transformation might have changed.
refreshTree();
return saved;
}
public boolean saveTransRepository(TransMeta transMeta)
{
return saveTransRepository(transMeta, false);
}
public boolean saveTransRepository(TransMeta transMeta, boolean ask_name)
{
log.logDetailed(toString(), Messages.getString("Spoon.Log.SaveToRepository"));//"Save to repository..."
if (rep!=null)
{
boolean answer = true;
boolean ask = ask_name;
while (answer && ( ask || transMeta.getName()==null || transMeta.getName().length()==0 ) )
{
if (!ask)
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("Spoon.Dialog.PromptTransformationName.Message"));//"Please give this transformation a name before saving it in the database."
mb.setText(Messages.getString("Spoon.Dialog.PromptTransformationName.Title"));//"Transformation has no name."
mb.open();
}
ask=false;
answer = editTransformationProperties(transMeta);
}
if (answer && transMeta.getName()!=null && transMeta.getName().length()>0)
{
if (!rep.getUserInfo().isReadonly())
{
int response = SWT.YES;
if (transMeta.showReplaceWarning(rep))
{
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.ICON_QUESTION);
mb.setMessage(Messages.getString("Spoon.Dialog.PromptOverwriteTransformation.Message",transMeta.getName(),Const.CR));//"There already is a transformation called ["+transMeta.getName()+"] in the repository."+Const.CR+"Do you want to overwrite the transformation?"
mb.setText(Messages.getString("Spoon.Dialog.PromptOverwriteTransformation.Title"));//"Overwrite?"
response = mb.open();
}
boolean saved=false;
if (response == SWT.YES)
{
shell.setCursor(cursor_hourglass);
// Keep info on who & when this transformation was changed...
transMeta.setModifiedDate( new Value("MODIFIED_DATE", Value.VALUE_TYPE_DATE) );
transMeta.getModifiedDate().sysdate();
transMeta.setModifiedUser( rep.getUserInfo().getLogin() );
TransSaveProgressDialog tspd = new TransSaveProgressDialog(shell, rep, transMeta);
if (tspd.open())
{
saved=true;
if (!props.getSaveConfirmation())
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell,
Messages.getString("Spoon.Message.Warning.SaveOK"), //"Save OK!"
null,
Messages.getString("Spoon.Message.Warning.TransformationWasStored"),//"This transformation was stored in repository"
MessageDialog.QUESTION,
new String[] { Messages.getString("Spoon.Message.Warning.OK") },//"OK!"
0,
Messages.getString("Spoon.Message.Warning.NotShowThisMessage"),//"Don't show this message again."
props.getSaveConfirmation()
);
md.open();
props.setSaveConfirmation(md.getToggleState());
}
// Handle last opened files...
props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, transMeta.getName(), transMeta.getDirectory().getPath(), true, getRepositoryName());
saveSettings();
addMenuLast();
setShellText();
}
shell.setCursor(null);
}
return saved;
}
else
{
MessageBox mb = new MessageBox(shell, SWT.CLOSE | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("Spoon.Dialog.OnlyreadRepository.Message"));//"Sorry, the user you're logged on with, can only read from the repository"
mb.setText(Messages.getString("Spoon.Dialog.OnlyreadRepository.Title"));//"Transformation not saved!"
mb.open();
}
}
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("Spoon.Dialog.NoRepositoryConnection.Message"));//"There is no repository connection available."
mb.setText(Messages.getString("Spoon.Dialog.NoRepositoryConnection.Title"));//"No repository available."
mb.open();
}
return false;
}
public boolean saveFileAs()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null) return saveTransFileAs(transMeta);
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null) return saveJobFileAs(jobMeta);
return false;
}
public boolean saveTransFileAs(TransMeta transMeta)
{
boolean saved=false;
log.logBasic(toString(), Messages.getString("Spoon.Log.SaveAs"));//"Save as..."
if (rep!=null)
{
transMeta.setID(-1L);
saved=saveTransRepository(transMeta, true);
renameTabs();
}
else
{
saved=saveTransXMLFile(transMeta);
renameTabs();
}
refreshTree();
return saved;
}
private void loadTransSharedObjects(TransMeta transMeta)
{
try
{
transMeta.readSharedObjects(rep);
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", makeGraphTabName(transMeta)), e);
}
}
private boolean saveTransSharedObjects(TransMeta transMeta)
{
try
{
transMeta.saveSharedObjects();
return true;
}
catch(Exception e)
{
log.logError(toString(), "Unable to save shared ojects: "+e.toString());
return false;
}
}
private void loadJobSharedObjects(JobMeta jobMeta)
{
try
{
jobMeta.readSharedObjects(rep);
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", makeJobGraphTabName(jobMeta)), e);
}
}
private boolean saveJobSharedObjects(JobMeta jobMeta)
{
try
{
jobMeta.saveSharedObjects();
return true;
}
catch(Exception e)
{
log.logError(toString(), "Unable to save shared ojects: "+e.toString());
return false;
}
}
private boolean saveXMLFile()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null) return saveTransXMLFile(transMeta);
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null) return saveJobXMLFile(jobMeta);
return false;
}
private boolean saveTransXMLFile(TransMeta transMeta)
{
boolean saved=false;
FileDialog dialog = new FileDialog(shell, SWT.SAVE);
dialog.setFilterExtensions(Const.STRING_TRANS_FILTER_EXT);
dialog.setFilterNames(Const.STRING_TRANS_FILTER_NAMES);
String fname = dialog.open();
if (fname!=null)
{
// Is the filename ending on .ktr, .xml?
boolean ending=false;
for (int i=0;i<Const.STRING_TRANS_FILTER_EXT.length-1;i++)
{
if (fname.endsWith(Const.STRING_TRANS_FILTER_EXT[i].substring(1)))
{
ending=true;
}
}
if (fname.endsWith(Const.STRING_TRANS_DEFAULT_EXT)) ending=true;
if (!ending)
{
fname+=Const.STRING_TRANS_DEFAULT_EXT;
}
// See if the file already exists...
File f = new File(fname);
int id = SWT.YES;
if (f.exists())
{
MessageBox mb = new MessageBox(shell, SWT.NO | SWT.YES | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("Spoon.Dialog.PromptOverwriteFile.Message"));//"This file already exists. Do you want to overwrite it?"
mb.setText(Messages.getString("Spoon.Dialog.PromptOverwriteFile.Title"));//"This file already exists!"
id = mb.open();
}
if (id==SWT.YES)
{
saved=save(transMeta, fname);
transMeta.setFilename(fname);
}
}
return saved;
}
private boolean save(TransMeta transMeta, String fname)
{
boolean saved = false;
String xml = XMLHandler.getXMLHeader() + transMeta.getXML();
try
{
DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File(fname)));
dos.write(xml.getBytes(Const.XML_ENCODING));
dos.close();
saved=true;
// Handle last opened files...
props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, fname, null, false, null);
saveSettings();
addMenuLast();
transMeta.clearChanged();
setShellText();
log.logDebug(toString(), Messages.getString("Spoon.Log.FileWritten")+" ["+fname+"]"); //"File written to
}
catch(Exception e)
{
log.logDebug(toString(), Messages.getString("Spoon.Log.ErrorOpeningFileForWriting")+e.toString());//"Error opening file for writing! --> "
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("Spoon.Dialog.ErrorSavingFile.Message")+Const.CR+e.toString());//"Error saving file:"
mb.setText(Messages.getString("Spoon.Dialog.ErrorSavingFile.Title"));//"ERROR"
mb.open();
}
return saved;
}
public void helpAbout()
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION | SWT.CENTER);
String mess = Messages.getString("System.ProductInfo")+Const.VERSION+Const.CR+Const.CR+Const.CR;//Kettle - Spoon version
mess+=Messages.getString("System.CompanyInfo")+Const.CR;
mess+=" "+Messages.getString("System.ProductWebsiteUrl")+Const.CR; //(c) 2001-2004 i-Bridge bvba www.kettle.be
mess+=Const.CR;
mess+=Const.CR;
mess+=Const.CR;
mess+=" Build version : "+BuildVersion.getInstance().getVersion()+Const.CR;
mess+=" Build date : "+BuildVersion.getInstance().getBuildDate()+Const.CR;
mb.setMessage(mess);
mb.setText(APP_NAME);
mb.open();
}
public void editUnselectAll(TransMeta transMeta)
{
transMeta.unselectAll();
// spoongraph.redraw();
}
public void editSelectAll(TransMeta transMeta)
{
transMeta.selectAll();
// spoongraph.redraw();
}
public void editOptions()
{
EnterOptionsDialog eod = new EnterOptionsDialog(shell, props);
if (eod.open()!=null)
{
props.saveProps();
loadSettings();
changeLooks();
MessageBox mb = new MessageBox(shell, SWT.ICON_INFORMATION);
mb.setMessage(Messages.getString("Spoon.Dialog.PleaseRestartApplication.Message"));
mb.setText(Messages.getString("Spoon.Dialog.PleaseRestartApplication.Title"));
mb.open();
}
}
/**
* Refresh the object selection tree (on the left of the screen)
* @param complete true refreshes the complete tree, false tries to do a differential update to avoid flickering.
*/
public void refreshTree()
{
if (shell.isDisposed()) return;
GUIResource guiResource = GUIResource.getInstance();
// get a list of transformations from the transformation map
Collection transformations = transformationMap.values();
TransMeta[] transMetas = (TransMeta[]) transformations.toArray(new TransMeta[transformations.size()]);
// get a list of jobs from the job map
Collection jobs = jobMap.values();
JobMeta[] jobMetas = (JobMeta[]) jobs.toArray(new JobMeta[jobs.size()]);
// Refresh the content of the tree for those transformations
//
// First remove the old ones.
tiTrans.removeAll();
tiJobs.removeAll();
// Now add the data back
//
for (int t=0;t<transMetas.length;t++)
{
TransMeta transMeta = transMetas[t];
// Add a tree item with the name of transformation
//
TreeItem tiTransName = new TreeItem(tiTrans, SWT.NONE);
String name = makeGraphTabName(transMeta);
if (Const.isEmpty(name)) name = STRING_TRANS_NO_NAME;
tiTransName.setText(name);
tiTransName.setImage(guiResource.getImageBol());
///////////////////////////////////////////////////////
//
// Now add the database connections
//
TreeItem tiDbTitle = new TreeItem(tiTransName, SWT.NONE);
tiDbTitle.setText(STRING_CONNECTIONS);
tiDbTitle.setImage(guiResource.getImageConnection());
// Draw the connections themselves below it.
for (int i=0;i<transMeta.nrDatabases();i++)
{
DatabaseMeta databaseMeta = transMeta.getDatabase(i);
TreeItem tiDb = new TreeItem(tiDbTitle, SWT.NONE);
tiDb.setText(databaseMeta.getName());
if (databaseMeta.isShared()) tiDb.setFont(guiResource.getFontBold());
tiDb.setImage(guiResource.getImageConnection());
}
///////////////////////////////////////////////////////
//
// The steps
//
TreeItem tiStepTitle = new TreeItem(tiTransName, SWT.NONE);
tiStepTitle.setText(STRING_STEPS);
tiStepTitle.setImage(guiResource.getImageBol());
// Put the steps below it.
for (int i=0;i<transMeta.nrSteps();i++)
{
StepMeta stepMeta = transMeta.getStep(i);
TreeItem tiStep = new TreeItem(tiStepTitle, SWT.NONE);
tiStep.setText(stepMeta.getName());
if (stepMeta.isShared()) tiStep.setFont(guiResource.getFontBold());
if (!stepMeta.isDrawn()) tiStep.setForeground(guiResource.getColorGray());
tiStep.setImage(guiResource.getImageBol());
}
///////////////////////////////////////////////////////
//
// The hops
//
TreeItem tiHopTitle = new TreeItem(tiTransName, SWT.NONE);
tiHopTitle.setText(STRING_HOPS);
tiHopTitle.setImage(guiResource.getImageHop());
// Put the steps below it.
for (int i=0;i<transMeta.nrTransHops();i++)
{
TransHopMeta hopMeta = transMeta.getTransHop(i);
TreeItem tiHop = new TreeItem(tiHopTitle, SWT.NONE);
tiHop.setText(hopMeta.toString());
tiHop.setImage(guiResource.getImageHop());
}
///////////////////////////////////////////////////////
//
// The partitions
//
TreeItem tiPartitionTitle = new TreeItem(tiTransName, SWT.NONE);
tiPartitionTitle.setText(STRING_PARTITIONS);
tiPartitionTitle.setImage(guiResource.getImageConnection());
// Put the steps below it.
for (int i=0;i<transMeta.getPartitionSchemas().size();i++)
{
PartitionSchema partitionSchema = (PartitionSchema) transMeta.getPartitionSchemas().get(i);
TreeItem tiPartition = new TreeItem(tiPartitionTitle, SWT.NONE);
tiPartition.setText(partitionSchema.getName());
tiPartition.setImage(guiResource.getImageBol());
if (partitionSchema.isShared()) tiPartition.setFont(guiResource.getFontBold());
}
///////////////////////////////////////////////////////
//
// The slaves
//
TreeItem tiSlaveTitle = new TreeItem(tiTransName, SWT.NONE);
tiSlaveTitle.setText(STRING_SLAVES);
tiSlaveTitle.setImage(guiResource.getImageBol());
// Put the steps below it.
for (int i=0;i<transMeta.getSlaveServers().size();i++)
{
SlaveServer slaveServer = (SlaveServer) transMeta.getSlaveServers().get(i);
TreeItem tiSlave = new TreeItem(tiSlaveTitle, SWT.NONE);
tiSlave.setText(slaveServer.getName());
tiSlave.setImage(guiResource.getImageBol());
if (slaveServer.isShared()) tiSlave.setFont(guiResource.getFontBold());
}
///////////////////////////////////////////////////////
//
// The clusters
//
TreeItem tiClusterTitle = new TreeItem(tiTransName, SWT.NONE);
tiClusterTitle.setText(STRING_CLUSTERS);
tiClusterTitle.setImage(guiResource.getImageBol());
// Put the steps below it.
for (int i=0;i<transMeta.getClusterSchemas().size();i++)
{
ClusterSchema clusterSchema = (ClusterSchema) transMeta.getClusterSchemas().get(i);
TreeItem tiCluster = new TreeItem(tiClusterTitle, SWT.NONE);
tiCluster.setText(clusterSchema.toString());
tiCluster.setImage(guiResource.getImageBol());
if (clusterSchema.isShared()) tiCluster.setFont(guiResource.getFontBold());
}
}
// Now add the jobs
//
for (int t=0;t<jobMetas.length;t++)
{
JobMeta jobMeta = jobMetas[t];
// Add a tree item with the name of job
//
TreeItem tiJobName = new TreeItem(tiJobs, SWT.NONE);
String name = makeJobGraphTabName(jobMeta);
if (Const.isEmpty(name)) name = STRING_JOB_NO_NAME;
tiJobName.setText(name);
tiJobName.setImage(guiResource.getImageBol());
///////////////////////////////////////////////////////
//
// Now add the database connections
//
TreeItem tiDbTitle = new TreeItem(tiJobName, SWT.NONE);
tiDbTitle.setText(STRING_CONNECTIONS);
tiDbTitle.setImage(guiResource.getImageConnection());
// Draw the connections themselves below it.
for (int i=0;i<jobMeta.nrDatabases();i++)
{
DatabaseMeta databaseMeta = jobMeta.getDatabase(i);
TreeItem tiDb = new TreeItem(tiDbTitle, SWT.NONE);
tiDb.setText(databaseMeta.getName());
if (databaseMeta.isShared()) tiDb.setFont(guiResource.getFontBold());
tiDb.setImage(guiResource.getImageConnection());
}
///////////////////////////////////////////////////////
//
// The job entries
//
TreeItem tiJobEntriesTitle = new TreeItem(tiJobName, SWT.NONE);
tiJobEntriesTitle.setText(STRING_JOB_ENTRIES);
tiJobEntriesTitle.setImage(guiResource.getImageBol());
// Put the steps below it.
for (int i=0;i<jobMeta.nrJobEntries();i++)
{
JobEntryCopy jobEntry = jobMeta.getJobEntry(i);
TreeItem tiJobEntry = Const.findTreeItem(tiJobEntriesTitle, jobEntry.getName());
if (tiJobEntry!=null) continue; // only show it once
tiJobEntry = new TreeItem(tiJobEntriesTitle, SWT.NONE);
tiJobEntry.setText(jobEntry.getName());
// if (jobEntry.isShared()) tiStep.setFont(guiResource.getFontBold()); TODO: allow job entries to be shared as well...
if (jobEntry.isStart())
{
tiJobEntry.setImage(GUIResource.getInstance().getImageStart());
}
else
if (jobEntry.isDummy())
{
tiJobEntry.setImage(GUIResource.getInstance().getImageDummy());
}
else
{
Image image = (Image)GUIResource.getInstance().getImagesJobentriesSmall().get(jobEntry.getTypeDesc());
tiJobEntry.setImage(image);
}
}
}
// Set the expanded state of the complete tree.
TreeMemory.setExpandedFromMemory(selectionTree, STRING_SPOON_MAIN_TREE);
selectionTree.setFocus();
setShellText();
}
public String getActiveTabText()
{
if (tabfolder.getSelection()==null) return null;
return tabfolder.getSelection().getText();
}
public void refreshGraph()
{
if (shell.isDisposed()) return;
String tabText = getActiveTabText();
if (tabText==null) return;
TabMapEntry tabMapEntry = (TabMapEntry) tabMap.get(tabText);
if (tabMapEntry.getObject() instanceof SpoonGraph)
{
SpoonGraph spoonGraph = (SpoonGraph) tabMapEntry.getObject();
spoonGraph.redraw();
}
if (tabMapEntry.getObject() instanceof ChefGraph)
{
ChefGraph chefGraph = (ChefGraph) tabMapEntry.getObject();
chefGraph.redraw();
}
setShellText();
}
public void refreshHistory()
{
final SpoonHistory spoonHistory = getActiveSpoonHistory();
if (spoonHistory!=null)
{
spoonHistory.markRefreshNeeded();
}
}
public StepMeta newStep(TransMeta transMeta)
{
return newStep(transMeta, true, true);
}
public StepMeta newStep(TransMeta transMeta, boolean openit, boolean rename)
{
if (transMeta==null) return null;
TreeItem ti[] = selectionTree.getSelection();
StepMeta inf = null;
if (ti.length==1)
{
String steptype = ti[0].getText();
log.logDebug(toString(), Messages.getString("Spoon.Log.NewStep")+steptype);//"New step: "
inf = newStep(transMeta, steptype, steptype, openit, rename);
}
return inf;
}
/**
* Allocate new step, optionally open and rename it.
*
* @param name Name of the new step
* @param description Description of the type of step
* @param openit Open the dialog for this step?
* @param rename Rename this step?
*
* @return The newly created StepMeta object.
*
*/
public StepMeta newStep(TransMeta transMeta, String name, String description, boolean openit, boolean rename)
{
StepMeta inf = null;
// See if we need to rename the step to avoid doubles!
if (rename && transMeta.findStep(name)!=null)
{
int i=2;
String newname = name+" "+i;
while (transMeta.findStep(newname)!=null)
{
i++;
newname = name+" "+i;
}
name=newname;
}
StepLoader steploader = StepLoader.getInstance();
StepPlugin stepPlugin = null;
try
{
stepPlugin = steploader.findStepPluginWithDescription(description);
if (stepPlugin!=null)
{
StepMetaInterface info = BaseStep.getStepInfo(stepPlugin, steploader);
info.setDefault();
if (openit)
{
StepDialogInterface dialog = info.getDialog(shell, info, transMeta, name);
name = dialog.open();
}
inf=new StepMeta(stepPlugin.getID()[0], name, info);
if (name!=null) // OK pressed in the dialog: we have a step-name
{
String newname=name;
StepMeta stepMeta = transMeta.findStep(newname);
int nr=2;
while (stepMeta!=null)
{
newname = name+" "+nr;
stepMeta = transMeta.findStep(newname);
nr++;
}
if (nr>2)
{
inf.setName(newname);
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(Messages.getString("Spoon.Dialog.ChangeStepname.Message",newname));//"This stepname already exists. Spoon changed the stepname to ["+newname+"]"
mb.setText(Messages.getString("Spoon.Dialog.ChangeStepname.Title"));//"Info!"
mb.open();
}
inf.setLocation(20, 20); // default location at (20,20)
transMeta.addStep(inf);
// Save for later:
// if openit is false: we drag&drop it onto the canvas!
if (openit)
{
addUndoNew(transMeta, new StepMeta[] { inf }, new int[] { transMeta.indexOfStep(inf) });
}
// Also store it in the pluginHistory list...
props.addPluginHistory(stepPlugin.getID()[0]);
refreshTree();
}
else
{
return null; // Cancel pressed in dialog.
}
setShellText();
}
}
catch(KettleException e)
{
String filename = stepPlugin.getErrorHelpFile();
if (stepPlugin!=null && filename!=null)
{
// OK, in stead of a normal error message, we give back the content of the error help file... (HTML)
try
{
StringBuffer content=new StringBuffer();
FileInputStream fis = new FileInputStream(new File(filename));
int ch = fis.read();
while (ch>=0)
{
content.append( (char)ch);
ch = fis.read();
}
ShowBrowserDialog sbd = new ShowBrowserDialog(shell, Messages.getString("Spoon.Dialog.ErrorHelpText.Title"), content.toString());//"Error help text"
sbd.open();
}
catch(Exception ex)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorShowingHelpText.Title"), Messages.getString("Spoon.Dialog.ErrorShowingHelpText.Message"), ex);//"Error showing help text"
}
}
else
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.UnableCreateNewStep.Title"),Messages.getString("Spoon.Dialog.UnableCreateNewStep.Message") , e);//"Error creating step" "I was unable to create a new step"
}
return null;
}
catch(Throwable e)
{
if (!shell.isDisposed()) new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorCreatingStep.Title"), Messages.getString("Spoon.Dialog.UnableCreateNewStep.Message"), new Exception(e));//"Error creating step"
return null;
}
return inf;
}
private void setTreeImages()
{
tiTrans.setImage(GUIResource.getInstance().getImageBol());
tiJobs.setImage(GUIResource.getInstance().getImageBol());
TreeItem tiBaseCat[]=tiTransBase.getItems();
for (int x=0;x<tiBaseCat.length;x++)
{
tiBaseCat[x].setImage(GUIResource.getInstance().getImageBol());
TreeItem ti[] = tiBaseCat[x].getItems();
for (int i=0;i<ti.length;i++)
{
TreeItem stepitem = ti[i];
String description = stepitem.getText();
StepLoader steploader = StepLoader.getInstance();
StepPlugin sp = steploader.findStepPluginWithDescription(description);
if (sp!=null)
{
Image stepimg = (Image)GUIResource.getInstance().getImagesStepsSmall().get(sp.getID()[0]);
if (stepimg!=null)
{
stepitem.setImage(stepimg);
}
}
}
}
}
public void setShellText()
{
if (shell.isDisposed()) return;
String fname = null;
String name = null;
long id = -1L;
ChangedFlagInterface changed = null;
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null)
{
changed = transMeta;
fname = transMeta.getFilename();
name = transMeta.getName();
id = transMeta.getID();
}
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null)
{
changed = jobMeta;
fname = jobMeta.getFilename();
name = jobMeta.getName();
id = jobMeta.getID();
}
String text = "";
if (rep!=null)
{
text+= APPL_TITLE+" - ["+getRepositoryName()+"] ";
}
else
{
text+= APPL_TITLE+" - ";
}
if (rep!=null && id>0)
{
if (Const.isEmpty(name))
{
text+=Messages.getString("Spoon.Various.NoName");//"[no name]"
}
else
{
text+=name;
}
}
else
{
if (!Const.isEmpty(fname))
{
text+=fname;
}
}
if (changed!=null && changed.hasChanged())
{
text+=" "+Messages.getString("Spoon.Various.Changed");
}
shell.setText(text);
enableMenus();
markTabsChanged();
}
public void enableMenus()
{
boolean enableTransMenu = getActiveTransformation()!=null;
boolean enableJobMenu = getActiveJob()!=null;
boolean enableRepositoryMenu = rep!=null;
// Only enable certain menu-items if we need to.
miFileSave.setEnabled(enableTransMenu || enableJobMenu);
miFileSaveAs.setEnabled(enableTransMenu || enableJobMenu);
miFileClose.setEnabled(enableTransMenu || enableJobMenu);
miFilePrint.setEnabled(enableTransMenu || enableJobMenu);
miEditUndo.setEnabled(enableTransMenu || enableJobMenu);
miEditRedo.setEnabled(enableTransMenu || enableJobMenu);
miEditUnselectAll.setEnabled(enableTransMenu);
miEditSelectAll.setEnabled(enableTransMenu);
miEditCopy.setEnabled(enableTransMenu);
miEditPaste.setEnabled(enableTransMenu);
// Transformations
miTransRun.setEnabled(enableTransMenu);
miTransPreview.setEnabled(enableTransMenu);
miTransCheck.setEnabled(enableTransMenu);
miTransImpact.setEnabled(enableTransMenu);
miTransSQL.setEnabled(enableTransMenu);
miLastImpact.setEnabled(enableTransMenu);
miLastCheck.setEnabled(enableTransMenu);
miLastPreview.setEnabled(enableTransMenu);
miTransCopy.setEnabled(enableTransMenu);
// miTransPaste.setEnabled(enableTransMenu);
miTransImage.setEnabled(enableTransMenu);
miTransDetails.setEnabled(enableTransMenu);
// Jobs
miJobRun.setEnabled(enableJobMenu);
miJobCopy.setEnabled(enableJobMenu);
miJobInfo.setEnabled(enableJobMenu);
miWizardNewConnection.setEnabled(enableTransMenu || enableJobMenu || enableRepositoryMenu);
miWizardCopyTable.setEnabled(enableTransMenu || enableJobMenu || enableRepositoryMenu);
miRepDisconnect.setEnabled(enableRepositoryMenu);
miRepExplore.setEnabled(enableRepositoryMenu);
miRepUser.setEnabled(enableRepositoryMenu);
// Do the bar as well
tiSQL.setEnabled(enableTransMenu || enableJobMenu);
tiImpact.setEnabled(enableTransMenu);
tiFileCheck.setEnabled(enableTransMenu);
tiFileReplay.setEnabled(enableTransMenu);
tiFilePreview.setEnabled(enableTransMenu);
tiFileRun.setEnabled(enableTransMenu || enableJobMenu);
tiFilePrint.setEnabled(enableTransMenu || enableJobMenu);
tiFileSaveAs.setEnabled(enableTransMenu || enableJobMenu);
tiFileSave.setEnabled(enableTransMenu || enableJobMenu);
// What steps & plugins to show?
refreshCoreObjectsTree();
}
private void markTabsChanged()
{
Collection c = tabMap.values();
for (Iterator iter = c.iterator(); iter.hasNext();)
{
TabMapEntry entry = (TabMapEntry) iter.next();
if (entry.getTabItem().isDisposed()) continue;
boolean changed = entry.getObject().hasContentChanged();
if (changed)
{
entry.getTabItem().setFont(GUIResource.getInstance().getFontBold());
}
else
{
entry.getTabItem().setFont(GUIResource.getInstance().getFontGraph());
}
}
}
private void printFile()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null)
{
printTransFile(transMeta);
}
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null)
{
printJobFile(jobMeta);
}
}
private void printTransFile(TransMeta transMeta)
{
SpoonGraph spoonGraph = getActiveSpoonGraph();
if (spoonGraph==null) return;
PrintSpool ps = new PrintSpool();
Printer printer = ps.getPrinter(shell);
// Create an image of the screen
Point max = transMeta.getMaximum();
Image img = spoonGraph.getTransformationImage(printer, max.x, max.y);
ps.printImage(shell, props, img);
img.dispose();
ps.dispose();
}
private void printJobFile(JobMeta jobMeta)
{
ChefGraph chefGraph = getActiveChefGraph();
if (chefGraph==null) return;
PrintSpool ps = new PrintSpool();
Printer printer = ps.getPrinter(shell);
// Create an image of the screen
Point max = jobMeta.getMaximum();
PaletteData pal = ps.getPaletteData();
ImageData imd = new ImageData(max.x, max.y, printer.getDepth(), pal);
Image img = new Image(printer, imd);
GC img_gc = new GC(img);
// Clear the background first, fill with background color...
img_gc.setForeground(GUIResource.getInstance().getColorBackground());
img_gc.fillRectangle(0,0,max.x, max.y);
// Draw the transformation...
chefGraph.drawJob(img_gc);
ps.printImage(shell, props, img);
img_gc.dispose();
img.dispose();
ps.dispose();
}
private SpoonGraph getActiveSpoonGraph()
{
TabMapEntry mapEntry = (TabMapEntry) tabMap.get(tabfolder.getSelection().getText());
if (mapEntry.getObject() instanceof SpoonGraph) return (SpoonGraph) mapEntry.getObject();
return null;
}
private ChefGraph getActiveChefGraph()
{
TabMapEntry mapEntry = (TabMapEntry) tabMap.get(tabfolder.getSelection().getText());
if (mapEntry.getObject() instanceof ChefGraph) return (ChefGraph) mapEntry.getObject();
return null;
}
/**
* @return the Log tab associated with the active transformation
*/
private SpoonLog getActiveSpoonLog()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta==null) return null; // nothing to work with.
return findSpoonLogOfTransformation(transMeta);
}
/**
* @return the Log tab associated with the active job
*/
private ChefLog getActiveJobLog()
{
JobMeta jobMeta = getActiveJob();
if (jobMeta==null) return null; // nothing to work with.
return findChefLogOfJob(jobMeta);
}
public SpoonGraph findSpoonGraphOfTransformation(TransMeta transMeta)
{
// Now loop over the entries in the tab-map
Collection collection = tabMap.values();
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (mapEntry.getObject() instanceof SpoonGraph)
{
SpoonGraph spoonGraph = (SpoonGraph) mapEntry.getObject();
if (spoonGraph.getTransMeta().equals(transMeta)) return spoonGraph;
}
}
return null;
}
public ChefGraph findChefGraphOfJob(JobMeta jobMeta)
{
// Now loop over the entries in the tab-map
Collection collection = tabMap.values();
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (mapEntry.getObject() instanceof ChefGraph)
{
ChefGraph chefGraph = (ChefGraph) mapEntry.getObject();
if (chefGraph.getJobMeta().equals(jobMeta)) return chefGraph;
}
}
return null;
}
public SpoonLog findSpoonLogOfTransformation(TransMeta transMeta)
{
// Now loop over the entries in the tab-map
Collection collection = tabMap.values();
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (mapEntry.getObject() instanceof SpoonLog)
{
SpoonLog spoonLog = (SpoonLog) mapEntry.getObject();
if (spoonLog.getTransMeta().equals(transMeta)) return spoonLog;
}
}
return null;
}
public ChefLog findChefLogOfJob(JobMeta jobMeta)
{
// Now loop over the entries in the tab-map
Collection collection = tabMap.values();
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (mapEntry.getObject() instanceof ChefLog)
{
ChefLog chefLog = (ChefLog) mapEntry.getObject();
if (chefLog.getJobMeta().equals(jobMeta)) return chefLog;
}
}
return null;
}
public SpoonHistory findSpoonHistoryOfTransformation(TransMeta transMeta)
{
if (transMeta==null) return null;
// Now loop over the entries in the tab-map
Collection collection = tabMap.values();
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (mapEntry.getObject() instanceof SpoonHistory)
{
SpoonHistory spoonHistory = (SpoonHistory) mapEntry.getObject();
if (spoonHistory.getTransMeta()!=null && spoonHistory.getTransMeta().equals(transMeta)) return spoonHistory;
}
}
return null;
}
public ChefHistory findChefHistoryOfJob(JobMeta jobMeta)
{
if (jobMeta==null) return null;
// Now loop over the entries in the tab-map
Collection collection = tabMap.values();
for (Iterator iter = collection.iterator(); iter.hasNext();)
{
TabMapEntry mapEntry = (TabMapEntry) iter.next();
if (mapEntry.getObject() instanceof ChefHistory)
{
ChefHistory chefHistory = (ChefHistory) mapEntry.getObject();
if (chefHistory.getJobMeta()!=null && chefHistory.getJobMeta().equals(jobMeta)) return chefHistory;
}
}
return null;
}
/**
* @return the history tab associated with the active transformation
*/
private SpoonHistory getActiveSpoonHistory()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta==null) return null; // nothing to work with.
return findSpoonHistoryOfTransformation(transMeta);
}
/**
* @return The active TransMeta object by looking at the selected SpoonGraph, SpoonLog, SpoonHist
* If nothing valueable is selected, we return null
*/
public TransMeta getActiveTransformation()
{
if (tabfolder==null) return null;
CTabItem tabItem = tabfolder.getSelection();
if (tabItem==null) return null;
// What transformation is in the active tab?
// SpoonLog, SpoonGraph & SpoonHist contain the same transformation
//
TabMapEntry mapEntry = (TabMapEntry) tabMap.get(tabfolder.getSelection().getText());
TransMeta transMeta = null;
if (mapEntry.getObject() instanceof SpoonGraph) transMeta = ((SpoonGraph) mapEntry.getObject()).getTransMeta();
if (mapEntry.getObject() instanceof SpoonLog) transMeta = ((SpoonLog) mapEntry.getObject()).getTransMeta();
if (mapEntry.getObject() instanceof SpoonHistory) transMeta = ((SpoonHistory) mapEntry.getObject()).getTransMeta();
return transMeta;
}
/**
* @return The active JobMeta object by looking at the selected ChefGraph, ChefLog, ChefHist
* If nothing valueable is selected, we return null
*/
public JobMeta getActiveJob()
{
if (tabfolder==null) return null;
CTabItem tabItem = tabfolder.getSelection();
if (tabItem==null) return null;
// What job is in the active tab?
// ChefLog, ChefGraph & ChefHist contain the same job
//
TabMapEntry mapEntry = (TabMapEntry) tabMap.get(tabfolder.getSelection().getText());
JobMeta jobMeta = null;
if (mapEntry.getObject() instanceof ChefGraph) jobMeta = ((ChefGraph) mapEntry.getObject()).getJobMeta();
if (mapEntry.getObject() instanceof ChefLog) jobMeta = ((ChefLog) mapEntry.getObject()).getJobMeta();
if (mapEntry.getObject() instanceof ChefHistory) jobMeta = ((ChefHistory) mapEntry.getObject()).getJobMeta();
return jobMeta;
}
public UndoInterface getActiveUndoInterface()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null) return transMeta;
return getActiveJob();
}
public TransMeta findTransformation(String name)
{
return (TransMeta)transformationMap.get(name);
}
public JobMeta findJob(String name)
{
return (JobMeta)jobMap.get(name);
}
public TransMeta[] getLoadedTransformations()
{
List list = new ArrayList(transformationMap.values());
return (TransMeta[]) list.toArray(new TransMeta[list.size()]);
}
public JobMeta[] getLoadedJobs()
{
List list = new ArrayList(jobMap.values());
return (JobMeta[]) list.toArray(new JobMeta[list.size()]);
}
private boolean editTransformationProperties(TransMeta transMeta)
{
if (transMeta==null) return false;
TransDialog tid = new TransDialog(shell, SWT.NONE, transMeta, rep);
TransMeta ti = tid.open();
// In this case, load shared objects
//
if (tid.isSharedObjectsFileChanged())
{
loadTransSharedObjects(transMeta);
}
if (tid.isSharedObjectsFileChanged() || ti!=null)
{
try
{
transMeta.readSharedObjects(rep);
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", makeGraphTabName(transMeta)), e);
}
refreshTree();
renameTabs(); // cheap operation, might as will do it anyway
}
setShellText();
return ti!=null;
}
public void saveSettings()
{
WindowProperty winprop = new WindowProperty(shell);
winprop.setName(APPL_TITLE);
props.setScreen(winprop);
props.setLogLevel(log.getLogLevelDesc());
props.setLogFilter(log.getFilter());
props.setSashWeights(sashform.getWeights());
props.saveProps();
}
public void loadSettings()
{
log.setLogLevel(props.getLogLevel());
log.setFilter(props.getLogFilter());
// transMeta.setMaxUndo(props.getMaxUndo());
DBCache.getInstance().setActive(props.useDBCache());
}
public void changeLooks()
{
props.setLook(selectionTree);
props.setLook(tabfolder, Props.WIDGET_STYLE_TAB);
GUIResource.getInstance().reload();
refreshTree();
refreshGraph();
}
public void undoAction(UndoInterface undoInterface)
{
if (undoInterface==null) return;
TransAction ta = undoInterface.previousUndo();
if (ta==null) return;
setUndoMenu(undoInterface); // something changed: change the menu
if (undoInterface instanceof TransMeta) undoTransformationAction((TransMeta)undoInterface, ta);
if (undoInterface instanceof JobMeta) undoJobAction((JobMeta)undoInterface, ta);
// Put what we undo in focus
if (undoInterface instanceof TransMeta)
{
SpoonGraph spoonGraph = findSpoonGraphOfTransformation((TransMeta)undoInterface);
spoonGraph.forceFocus();
}
if (undoInterface instanceof JobMeta)
{
ChefGraph chefGraph = findChefGraphOfJob((JobMeta)undoInterface);
chefGraph.forceFocus();
}
}
private void undoTransformationAction(TransMeta transMeta, TransAction transAction)
{
switch(transAction.getType())
{
//
// NEW
//
// We created a new step : undo this...
case TransAction.TYPE_ACTION_NEW_STEP:
// Delete the step at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeStep(idx);
}
refreshTree();
refreshGraph();
break;
// We created a new connection : undo this...
case TransAction.TYPE_ACTION_NEW_CONNECTION:
// Delete the connection at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeDatabase(idx);
}
refreshTree();
refreshGraph();
break;
// We created a new note : undo this...
case TransAction.TYPE_ACTION_NEW_NOTE:
// Delete the note at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeNote(idx);
}
refreshTree();
refreshGraph();
break;
// We created a new hop : undo this...
case TransAction.TYPE_ACTION_NEW_HOP:
// Delete the hop at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeTransHop(idx);
}
refreshTree();
refreshGraph();
break;
// We created a new slave : undo this...
case TransAction.TYPE_ACTION_NEW_SLAVE:
// Delete the slave at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.getSlaveServers().remove(idx);
}
refreshTree();
refreshGraph();
break;
// We created a new slave : undo this...
case TransAction.TYPE_ACTION_NEW_CLUSTER:
// Delete the slave at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.getClusterSchemas().remove(idx);
}
refreshTree();
refreshGraph();
break;
//
// DELETE
//
// We delete a step : undo this...
case TransAction.TYPE_ACTION_DELETE_STEP:
// un-Delete the step at correct location: re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
StepMeta stepMeta = (StepMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addStep(idx, stepMeta);
}
refreshTree();
refreshGraph();
break;
// We deleted a connection : undo this...
case TransAction.TYPE_ACTION_DELETE_CONNECTION:
// re-insert the connection at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
DatabaseMeta ci = (DatabaseMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addDatabase(idx, ci);
}
refreshTree();
refreshGraph();
break;
// We delete new note : undo this...
case TransAction.TYPE_ACTION_DELETE_NOTE:
// re-insert the note at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
NotePadMeta ni = (NotePadMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addNote(idx, ni);
}
refreshTree();
refreshGraph();
break;
// We deleted a hop : undo this...
case TransAction.TYPE_ACTION_DELETE_HOP:
// re-insert the hop at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
TransHopMeta hi = (TransHopMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
// Build a new hop:
StepMeta from = transMeta.findStep(hi.getFromStep().getName());
StepMeta to = transMeta.findStep(hi.getToStep().getName());
TransHopMeta hinew = new TransHopMeta(from, to);
transMeta.addTransHop(idx, hinew);
}
refreshTree();
refreshGraph();
break;
//
// CHANGE
//
// We changed a step : undo this...
case TransAction.TYPE_ACTION_CHANGE_STEP:
// Delete the current step, insert previous version.
for (int i=0;i<transAction.getCurrent().length;i++)
{
StepMeta prev = (StepMeta) ((StepMeta)transAction.getPrevious()[i]).clone();
int idx = transAction.getCurrentIndex()[i];
transMeta.getStep(idx).replaceMeta(prev);
}
refreshTree();
refreshGraph();
break;
// We changed a connection : undo this...
case TransAction.TYPE_ACTION_CHANGE_CONNECTION:
// Delete & re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
DatabaseMeta prev = (DatabaseMeta)transAction.getPrevious()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.getDatabase(idx).replaceMeta((DatabaseMeta) prev.clone());
}
refreshTree();
refreshGraph();
break;
// We changed a note : undo this...
case TransAction.TYPE_ACTION_CHANGE_NOTE:
// Delete & re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeNote(idx);
NotePadMeta prev = (NotePadMeta)transAction.getPrevious()[i];
transMeta.addNote(idx, (NotePadMeta) prev.clone());
}
refreshTree();
refreshGraph();
break;
// We changed a hop : undo this...
case TransAction.TYPE_ACTION_CHANGE_HOP:
// Delete & re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
TransHopMeta prev = (TransHopMeta)transAction.getPrevious()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.removeTransHop(idx);
transMeta.addTransHop(idx, (TransHopMeta) prev.clone());
}
refreshTree();
refreshGraph();
break;
//
// POSITION
//
// The position of a step has changed: undo this...
case TransAction.TYPE_ACTION_POSITION_STEP:
// Find the location of the step:
for (int i = 0; i < transAction.getCurrentIndex().length; i++)
{
StepMeta stepMeta = transMeta.getStep(transAction.getCurrentIndex()[i]);
stepMeta.setLocation(transAction.getPreviousLocation()[i]);
}
refreshGraph();
break;
// The position of a note has changed: undo this...
case TransAction.TYPE_ACTION_POSITION_NOTE:
for (int i=0;i<transAction.getCurrentIndex().length;i++)
{
int idx = transAction.getCurrentIndex()[i];
NotePadMeta npi = transMeta.getNote(idx);
Point prev = transAction.getPreviousLocation()[i];
npi.setLocation(prev);
}
refreshGraph();
break;
default: break;
}
// OK, now check if we need to do this again...
if (transMeta.viewNextUndo()!=null)
{
if (transMeta.viewNextUndo().getNextAlso()) undoAction(transMeta);
}
}
private void undoJobAction(JobMeta jobMeta, TransAction transAction)
{
switch(transAction.getType())
{
//
// NEW
//
// We created a new entry : undo this...
case TransAction.TYPE_ACTION_NEW_JOB_ENTRY:
// Delete the entry at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i=idx.length-1;i>=0;i--) jobMeta.removeJobEntry(idx[i]);
refreshTree();
refreshGraph();
}
break;
// We created a new note : undo this...
case TransAction.TYPE_ACTION_NEW_NOTE:
// Delete the note at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i=idx.length-1;i>=0;i--) jobMeta.removeNote(idx[i]);
refreshTree();
refreshGraph();
}
break;
// We created a new hop : undo this...
case TransAction.TYPE_ACTION_NEW_JOB_HOP:
// Delete the hop at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i=idx.length-1;i>=0;i--) jobMeta.removeJobHop(idx[i]);
refreshTree();
refreshGraph();
}
break;
//
// DELETE
//
// We delete an entry : undo this...
case TransAction.TYPE_ACTION_DELETE_STEP:
// un-Delete the entry at correct location: re-insert
{
JobEntryCopy ce[] = (JobEntryCopy[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<ce.length;i++) jobMeta.addJobEntry(idx[i], ce[i]);
refreshTree();
refreshGraph();
}
break;
// We delete new note : undo this...
case TransAction.TYPE_ACTION_DELETE_NOTE:
// re-insert the note at correct location:
{
NotePadMeta ni[] = (NotePadMeta[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++) jobMeta.addNote(idx[i], ni[i]);
refreshTree();
refreshGraph();
}
break;
// We deleted a new hop : undo this...
case TransAction.TYPE_ACTION_DELETE_JOB_HOP:
// re-insert the hop at correct location:
{
JobHopMeta hi[] = (JobHopMeta[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<hi.length;i++)
{
jobMeta.addJobHop(idx[i], hi[i]);
}
refreshTree();
refreshGraph();
}
break;
//
// CHANGE
//
// We changed a job entry: undo this...
case TransAction.TYPE_ACTION_CHANGE_JOB_ENTRY:
// Delete the current job entry, insert previous version.
{
for (int i=0;i<transAction.getPrevious().length;i++)
{
JobEntryCopy copy = (JobEntryCopy) ((JobEntryCopy)transAction.getPrevious()[i]).clone();
jobMeta.getJobEntry(transAction.getCurrentIndex()[i]).replaceMeta(copy);
}
refreshTree();
refreshGraph();
}
break;
// We changed a note : undo this...
case TransAction.TYPE_ACTION_CHANGE_NOTE:
// Delete & re-insert
{
NotePadMeta prev[] = (NotePadMeta[])transAction.getPrevious();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++)
{
jobMeta.removeNote(idx[i]);
jobMeta.addNote(idx[i], prev[i]);
}
refreshTree();
refreshGraph();
}
break;
// We changed a hop : undo this...
case TransAction.TYPE_ACTION_CHANGE_JOB_HOP:
// Delete & re-insert
{
JobHopMeta prev[] = (JobHopMeta[])transAction.getPrevious();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++)
{
jobMeta.removeJobHop(idx[i]);
jobMeta.addJobHop(idx[i], prev[i]);
}
refreshTree();
refreshGraph();
}
break;
//
// POSITION
//
// The position of a step has changed: undo this...
case TransAction.TYPE_ACTION_POSITION_JOB_ENTRY:
// Find the location of the step:
{
int idx[] = transAction.getCurrentIndex();
Point p[] = transAction.getPreviousLocation();
for (int i = 0; i < p.length; i++)
{
JobEntryCopy entry = jobMeta.getJobEntry(idx[i]);
entry.setLocation(p[i]);
}
refreshGraph();
}
break;
// The position of a note has changed: undo this...
case TransAction.TYPE_ACTION_POSITION_NOTE:
int idx[] = transAction.getCurrentIndex();
Point prev[] = transAction.getPreviousLocation();
for (int i=0;i<idx.length;i++)
{
NotePadMeta npi = jobMeta.getNote(idx[i]);
npi.setLocation(prev[i]);
}
refreshGraph();
break;
default: break;
}
}
public void redoAction(UndoInterface undoInterface)
{
if (undoInterface==null) return;
TransAction ta = undoInterface.nextUndo();
if (ta==null) return;
setUndoMenu(undoInterface); // something changed: change the menu
if (undoInterface instanceof TransMeta) redoTransformationAction((TransMeta)undoInterface, ta);
if (undoInterface instanceof JobMeta) redoJobAction((JobMeta)undoInterface, ta);
// Put what we redo in focus
if (undoInterface instanceof TransMeta)
{
SpoonGraph spoonGraph = findSpoonGraphOfTransformation((TransMeta)undoInterface);
spoonGraph.forceFocus();
}
if (undoInterface instanceof JobMeta)
{
ChefGraph chefGraph = findChefGraphOfJob((JobMeta)undoInterface);
chefGraph.forceFocus();
}
}
private void redoTransformationAction(TransMeta transMeta, TransAction transAction)
{
switch(transAction.getType())
{
//
// NEW
//
case TransAction.TYPE_ACTION_NEW_STEP:
// re-delete the step at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
StepMeta stepMeta = (StepMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addStep(idx, stepMeta);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_NEW_CONNECTION:
// re-insert the connection at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
DatabaseMeta ci = (DatabaseMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addDatabase(idx, ci);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_NEW_NOTE:
// re-insert the note at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
NotePadMeta ni = (NotePadMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addNote(idx, ni);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_NEW_HOP:
// re-insert the hop at correct location:
for (int i=0;i<transAction.getCurrent().length;i++)
{
TransHopMeta hi = (TransHopMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.addTransHop(idx, hi);
refreshTree();
refreshGraph();
}
break;
//
// DELETE
//
case TransAction.TYPE_ACTION_DELETE_STEP:
// re-remove the step at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeStep(idx);
}
refreshTree();
refreshGraph();
break;
case TransAction.TYPE_ACTION_DELETE_CONNECTION:
// re-remove the connection at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeDatabase(idx);
}
refreshTree();
refreshGraph();
break;
case TransAction.TYPE_ACTION_DELETE_NOTE:
// re-remove the note at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeNote(idx);
}
refreshTree();
refreshGraph();
break;
case TransAction.TYPE_ACTION_DELETE_HOP:
// re-remove the hop at correct location:
for (int i=transAction.getCurrent().length-1;i>=0;i--)
{
int idx = transAction.getCurrentIndex()[i];
transMeta.removeTransHop(idx);
}
refreshTree();
refreshGraph();
break;
//
// CHANGE
//
// We changed a step : undo this...
case TransAction.TYPE_ACTION_CHANGE_STEP:
// Delete the current step, insert previous version.
for (int i=0;i<transAction.getCurrent().length;i++)
{
StepMeta stepMeta = (StepMeta) ((StepMeta)transAction.getCurrent()[i]).clone();
transMeta.getStep(transAction.getCurrentIndex()[i]).replaceMeta(stepMeta);
}
refreshTree();
refreshGraph();
break;
// We changed a connection : undo this...
case TransAction.TYPE_ACTION_CHANGE_CONNECTION:
// Delete & re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
DatabaseMeta databaseMeta = (DatabaseMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.getDatabase(idx).replaceMeta((DatabaseMeta) databaseMeta.clone());
}
refreshTree();
refreshGraph();
break;
// We changed a note : undo this...
case TransAction.TYPE_ACTION_CHANGE_NOTE:
// Delete & re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
NotePadMeta ni = (NotePadMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.removeNote(idx);
transMeta.addNote(idx, (NotePadMeta) ni.clone());
}
refreshTree();
refreshGraph();
break;
// We changed a hop : undo this...
case TransAction.TYPE_ACTION_CHANGE_HOP:
// Delete & re-insert
for (int i=0;i<transAction.getCurrent().length;i++)
{
TransHopMeta hi = (TransHopMeta)transAction.getCurrent()[i];
int idx = transAction.getCurrentIndex()[i];
transMeta.removeTransHop(idx);
transMeta.addTransHop(idx, (TransHopMeta) hi.clone());
}
refreshTree();
refreshGraph();
break;
//
// CHANGE POSITION
//
case TransAction.TYPE_ACTION_POSITION_STEP:
for (int i=0;i<transAction.getCurrentIndex().length;i++)
{
// Find & change the location of the step:
StepMeta stepMeta = transMeta.getStep(transAction.getCurrentIndex()[i]);
stepMeta.setLocation(transAction.getCurrentLocation()[i]);
}
refreshGraph();
break;
case TransAction.TYPE_ACTION_POSITION_NOTE:
for (int i=0;i<transAction.getCurrentIndex().length;i++)
{
int idx = transAction.getCurrentIndex()[i];
NotePadMeta npi = transMeta.getNote(idx);
Point curr = transAction.getCurrentLocation()[i];
npi.setLocation(curr);
}
refreshGraph();
break;
default: break;
}
// OK, now check if we need to do this again...
if (transMeta.viewNextUndo()!=null)
{
if (transMeta.viewNextUndo().getNextAlso()) redoAction(transMeta);
}
}
private void redoJobAction(JobMeta jobMeta, TransAction transAction)
{
switch(transAction.getType())
{
//
// NEW
//
case TransAction.TYPE_ACTION_NEW_JOB_ENTRY:
// re-delete the entry at correct location:
{
JobEntryCopy si[] = (JobEntryCopy[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++) jobMeta.addJobEntry(idx[i], si[i]);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_NEW_NOTE:
// re-insert the note at correct location:
{
NotePadMeta ni[] = (NotePadMeta[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++) jobMeta.addNote(idx[i], ni[i]);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_NEW_JOB_HOP:
// re-insert the hop at correct location:
{
JobHopMeta hi[] = (JobHopMeta[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++) jobMeta.addJobHop(idx[i], hi[i]);
refreshTree();
refreshGraph();
}
break;
//
// DELETE
//
case TransAction.TYPE_ACTION_DELETE_JOB_ENTRY:
// re-remove the entry at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i=idx.length-1;i>=0;i--) jobMeta.removeJobEntry(idx[i]);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_DELETE_NOTE:
// re-remove the note at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i=idx.length-1;i>=0;i--) jobMeta.removeNote(idx[i]);
refreshTree();
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_DELETE_JOB_HOP:
// re-remove the hop at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i=idx.length-1;i>=0;i--) jobMeta.removeJobHop(idx[i]);
refreshTree();
refreshGraph();
}
break;
//
// CHANGE
//
// We changed a step : undo this...
case TransAction.TYPE_ACTION_CHANGE_JOB_ENTRY:
// replace with "current" version.
{
for (int i=0;i<transAction.getCurrent().length;i++)
{
JobEntryCopy copy = (JobEntryCopy) ((JobEntryCopy)(transAction.getCurrent()[i])).clone_deep();
jobMeta.getJobEntry(transAction.getCurrentIndex()[i]).replaceMeta(copy);
}
refreshTree();
refreshGraph();
}
break;
// We changed a note : undo this...
case TransAction.TYPE_ACTION_CHANGE_NOTE:
// Delete & re-insert
{
NotePadMeta ni[] = (NotePadMeta[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++)
{
jobMeta.removeNote(idx[i]);
jobMeta.addNote(idx[i], ni[i]);
}
refreshTree();
refreshGraph();
}
break;
// We changed a hop : undo this...
case TransAction.TYPE_ACTION_CHANGE_JOB_HOP:
// Delete & re-insert
{
JobHopMeta hi[] = (JobHopMeta[])transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i=0;i<idx.length;i++)
{
jobMeta.removeJobHop(idx[i]);
jobMeta.addJobHop(idx[i], hi[i]);
}
refreshTree();
refreshGraph();
}
break;
//
// CHANGE POSITION
//
case TransAction.TYPE_ACTION_POSITION_JOB_ENTRY:
{
// Find the location of the step:
int idx[] = transAction.getCurrentIndex();
Point p[] = transAction.getCurrentLocation();
for (int i = 0; i < p.length; i++)
{
JobEntryCopy entry = jobMeta.getJobEntry(idx[i]);
entry.setLocation(p[i]);
}
refreshGraph();
}
break;
case TransAction.TYPE_ACTION_POSITION_NOTE:
{
int idx[] = transAction.getCurrentIndex();
Point curr[] = transAction.getCurrentLocation();
for (int i=0;i<idx.length;i++)
{
NotePadMeta npi = jobMeta.getNote(idx[i]);
npi.setLocation(curr[i]);
}
refreshGraph();
}
break;
default: break;
}
}
public void setUndoMenu(UndoInterface undoInterface)
{
if (shell.isDisposed()) return;
TransAction prev = undoInterface!=null ? undoInterface.viewThisUndo() : null;
TransAction next = undoInterface!=null ? undoInterface.viewNextUndo() : null;
if (prev!=null)
{
miEditUndo.setEnabled(true);
miEditUndo.setText(Messages.getString("Spoon.Menu.Undo.Available", prev.toString()));//"Undo : "+prev.toString()+" \tCTRL-Z"
}
else
{
miEditUndo.setEnabled(false);
miEditUndo.setText(Messages.getString("Spoon.Menu.Undo.NotAvailable"));//"Undo : not available \tCTRL-Z"
}
if (next!=null)
{
miEditRedo.setEnabled(true);
miEditRedo.setText(Messages.getString("Spoon.Menu.Redo.Available",next.toString()));//"Redo : "+next.toString()+" \tCTRL-Y"
}
else
{
miEditRedo.setEnabled(false);
miEditRedo.setText(Messages.getString("Spoon.Menu.Redo.NotAvailable"));//"Redo : not available \tCTRL-Y"
}
}
public void addUndoNew(UndoInterface undoInterface, Object obj[], int position[])
{
addUndoNew(undoInterface, obj, position, false);
}
public void addUndoNew(UndoInterface undoInterface, Object obj[], int position[], boolean nextAlso)
{
undoInterface.addUndo(obj, null, position, null, null, TransMeta.TYPE_UNDO_NEW, nextAlso);
setUndoMenu(undoInterface);
}
// Undo delete object
public void addUndoDelete(UndoInterface undoInterface, Object obj[], int position[])
{
addUndoDelete(undoInterface, obj, position, false);
}
// Undo delete object
public void addUndoDelete(UndoInterface undoInterface, Object obj[], int position[], boolean nextAlso)
{
undoInterface.addUndo(obj, null, position, null, null, TransMeta.TYPE_UNDO_DELETE, nextAlso);
setUndoMenu(undoInterface);
}
// Change of step, connection, hop or note...
public void addUndoPosition(UndoInterface undoInterface, Object obj[], int pos[], Point prev[], Point curr[])
{
// It's better to store the indexes of the objects, not the objects itself!
undoInterface.addUndo(obj, null, pos, prev, curr, JobMeta.TYPE_UNDO_POSITION, false);
setUndoMenu(undoInterface);
}
// Change of step, connection, hop or note...
public void addUndoChange(UndoInterface undoInterface, Object from[], Object to[], int[] pos)
{
addUndoChange(undoInterface, from, to, pos, false);
}
// Change of step, connection, hop or note...
public void addUndoChange(UndoInterface undoInterface, Object from[], Object to[], int[] pos, boolean nextAlso)
{
undoInterface.addUndo(from, to, pos, null, null, JobMeta.TYPE_UNDO_CHANGE, nextAlso);
setUndoMenu(undoInterface);
}
/**
* Checks *all* the steps in the transformation, puts the result in remarks list
*/
public void checkTrans(TransMeta transMeta)
{
checkTrans(transMeta, false);
}
/**
* Check the steps in a transformation
*
* @param only_selected True: Check only the selected steps...
*/
public void checkTrans(TransMeta transMeta, boolean only_selected)
{
if (transMeta==null) return;
SpoonGraph spoonGraph = findSpoonGraphOfTransformation(transMeta);
if (spoonGraph==null) return;
CheckTransProgressDialog ctpd = new CheckTransProgressDialog(shell, transMeta, spoonGraph.getRemarks(), only_selected);
ctpd.open(); // manages the remarks arraylist...
showLastTransCheck();
}
/**
* Show the remarks of the last transformation check that was run.
* @see #checkTrans()
*/
public void showLastTransCheck()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta==null) return;
SpoonGraph spoonGraph = findSpoonGraphOfTransformation(transMeta);
if (spoonGraph==null) return;
CheckResultDialog crd = new CheckResultDialog(shell, SWT.NONE, spoonGraph.getRemarks());
String stepname = crd.open();
if (stepname!=null)
{
// Go to the indicated step!
StepMeta stepMeta = transMeta.findStep(stepname);
if (stepMeta!=null)
{
editStep(transMeta, stepMeta);
}
}
}
public void clearDBCache()
{
clearDBCache(null);
}
public void clearDBCache(DatabaseMeta databaseMeta)
{
if (databaseMeta!=null)
{
DBCache.getInstance().clear(databaseMeta.getName());
}
else
{
DBCache.getInstance().clear(null);
}
}
public void exploreDB(HasDatabasesInterface hasDatabasesInterface, DatabaseMeta databaseMeta)
{
DatabaseExplorerDialog std = new DatabaseExplorerDialog(shell, SWT.NONE, databaseMeta, hasDatabasesInterface.getDatabases(), true );
std.open();
}
public void analyseImpact(TransMeta transMeta)
{
if (transMeta==null) return;
SpoonGraph spoonGraph = findSpoonGraphOfTransformation(transMeta);
if (spoonGraph==null) return;
AnalyseImpactProgressDialog aipd = new AnalyseImpactProgressDialog(shell, transMeta, spoonGraph.getImpact());
spoonGraph.setImpactFinished( aipd.open() );
if (spoonGraph.isImpactFinished()) showLastImpactAnalyses(transMeta);
}
public void showLastImpactAnalyses(TransMeta transMeta)
{
if (transMeta==null) return;
SpoonGraph spoonGraph = findSpoonGraphOfTransformation(transMeta);
if (spoonGraph==null) return;
ArrayList rows = new ArrayList();
for (int i=0;i<spoonGraph.getImpact().size();i++)
{
DatabaseImpact ii = (DatabaseImpact)spoonGraph.getImpact().get(i);
rows.add(ii.getRow());
}
if (rows.size()>0)
{
// Display all the rows...
PreviewRowsDialog prd = new PreviewRowsDialog(shell, SWT.NONE, "-", rows);
prd.setTitleMessage(Messages.getString("Spoon.Dialog.ImpactAnalyses.Title"), Messages.getString("Spoon.Dialog.ImpactAnalyses.Message"));//"Impact analyses" "Result of analyses:"
prd.open();
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION );
if (spoonGraph.isImpactFinished())
{
mb.setMessage(Messages.getString("Spoon.Dialog.TransformationNoImpactOnDatabase.Message"));//"As far as I can tell, this transformation has no impact on any database."
}
else
{
mb.setMessage(Messages.getString("Spoon.Dialog.RunImpactAnalysesFirst.Message"));//"Please run the impact analyses first on this transformation."
}
mb.setText(Messages.getString("Spoon.Dialog.ImpactAnalyses.Title"));//Impact
mb.open();
}
}
public void getSQL()
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null) getTransSQL(transMeta);
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null) getJobSQL(jobMeta);
}
/**
* Get & show the SQL required to run the loaded transformation...
*
*/
public void getTransSQL(TransMeta transMeta)
{
GetSQLProgressDialog pspd = new GetSQLProgressDialog(shell, transMeta);
ArrayList stats = pspd.open();
if (stats!=null) // null means error, but we already displayed the error
{
if (stats.size()>0)
{
SQLStatementsDialog ssd = new SQLStatementsDialog(shell, SWT.NONE, stats);
ssd.open();
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION );
mb.setMessage(Messages.getString("Spoon.Dialog.NoSQLNeedEexecuted.Message"));//As far as I can tell, no SQL statements need to be executed before this transformation can run.
mb.setText(Messages.getString("Spoon.Dialog.NoSQLNeedEexecuted.Title"));//"SQL"
mb.open();
}
}
}
/**
* Get & show the SQL required to run the loaded job entry...
*
*/
public void getJobSQL(JobMeta jobMeta)
{
GetJobSQLProgressDialog pspd = new GetJobSQLProgressDialog(shell, jobMeta, rep);
ArrayList stats = pspd.open();
if (stats!=null) // null means error, but we already displayed the error
{
if (stats.size()>0)
{
SQLStatementsDialog ssd = new SQLStatementsDialog(shell, SWT.NONE, stats);
ssd.open();
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION );
mb.setMessage(Messages.getString("Spoon.Dialog.JobNoSQLNeedEexecuted.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.JobNoSQLNeedEexecuted.Title")); //$NON-NLS-1$
mb.open();
}
}
}
public void toClipboard(String cliptext)
{
GUIResource.getInstance().toClipboard(cliptext);
}
public String fromClipboard()
{
return GUIResource.getInstance().fromClipboard();
}
/**
* Paste transformation from the clipboard...
*
*/
public void pasteTransformation()
{
log.logDetailed(toString(), Messages.getString("Spoon.Log.PasteTransformationFromClipboard"));//"Paste transformation from the clipboard!"
String xml = fromClipboard();
try
{
Document doc = XMLHandler.loadXMLString(xml);
TransMeta transMeta = new TransMeta(XMLHandler.getSubNode(doc, TransMeta.XML_TAG));
addSpoonGraph(transMeta); // create a new tab
refreshGraph();
refreshTree();
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorPastingTransformation.Title"), Messages.getString("Spoon.Dialog.ErrorPastingTransformation.Message"), e);//Error pasting transformation "An error occurred pasting a transformation from the clipboard"
}
}
/**
* Paste job from the clipboard...
*
*/
public void pasteJob()
{
String xml = fromClipboard();
try
{
Document doc = XMLHandler.loadXMLString(xml);
JobMeta jobMeta = new JobMeta(log, XMLHandler.getSubNode(doc, JobMeta.XML_TAG), rep);
addChefGraph(jobMeta); // create a new tab
refreshGraph();
refreshTree();
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorPastingJob.Title"), Messages.getString("Spoon.Dialog.ErrorPastingJob.Message"), e);//Error pasting transformation "An error occurred pasting a transformation from the clipboard"
}
}
public void copyTransformation(TransMeta transMeta)
{
if (transMeta==null) return;
toClipboard(XMLHandler.getXMLHeader() + transMeta.getXML());
}
public void copyJob(JobMeta jobMeta)
{
if (jobMeta==null) return;
toClipboard(XMLHandler.getXMLHeader() + jobMeta.getXML());
}
public void copyTransformationImage(TransMeta transMeta)
{
SpoonGraph spoonGraph = findSpoonGraphOfTransformation(transMeta);
if (spoonGraph==null) return;
Clipboard clipboard = GUIResource.getInstance().getNewClipboard();
Point area = transMeta.getMaximum();
Image image = spoonGraph.getTransformationImage(Display.getCurrent(), area.x, area.y);
clipboard.setContents(new Object[] { image.getImageData() }, new Transfer[]{ImageDataTransfer.getInstance()});
}
/**
* Shows a wizard that creates a new database connection...
*
*/
private void createDatabaseWizard(HasDatabasesInterface hasDatabasesInterface)
{
CreateDatabaseWizard cdw=new CreateDatabaseWizard();
DatabaseMeta newDBInfo=cdw.createAndRunDatabaseWizard(shell, props, hasDatabasesInterface.getDatabases());
if(newDBInfo!=null){ //finished
hasDatabasesInterface.addDatabase(newDBInfo);
refreshTree();
refreshGraph();
}
}
public ArrayList getActiveDatabases()
{
Map map = new Hashtable();
HasDatabasesInterface transMeta = getActiveTransformation();
if (transMeta!=null)
{
for (int i=0;i<transMeta.nrDatabases();i++)
{
map.put(transMeta.getDatabase(i).getName(), transMeta.getDatabase(i));
}
}
HasDatabasesInterface jobMeta = getActiveJob();
if (jobMeta!=null)
{
for (int i=0;i<jobMeta.nrDatabases();i++)
{
map.put(jobMeta.getDatabase(i).getName(), jobMeta.getDatabase(i));
}
}
if (rep!=null)
{
try
{
List repDBs = rep.getDatabases();
for (int i=0;i<repDBs.size();i++)
{
DatabaseMeta databaseMeta = (DatabaseMeta) repDBs.get(i);
map.put(databaseMeta.getName(), databaseMeta);
}
}
catch(Exception e)
{
log.logError(toString(), "Unexpected error reading databases from the repository: "+e.toString());
log.logError(toString(), Const.getStackTracker(e));
}
}
ArrayList databases = new ArrayList();
databases.addAll( map.values() );
return databases;
}
/**
* Create a transformation that extracts tables & data from a database.<p><p>
*
* 0) Select the database to rip<p>
* 1) Select the table in the database to copy<p>
* 2) Select the database to dump to<p>
* 3) Select the repository directory in which it will end up<p>
* 4) Select a name for the new transformation<p>
* 6) Create 1 transformation for the selected table<p>
*/
private void copyTableWizard()
{
ArrayList databases = getActiveDatabases();
if (databases.size()==0) return; // Nothing to do here
final CopyTableWizardPage1 page1 = new CopyTableWizardPage1("1", databases);
page1.createControl(shell);
final CopyTableWizardPage2 page2 = new CopyTableWizardPage2("2");
page2.createControl(shell);
Wizard wizard = new Wizard()
{
public boolean performFinish()
{
return copyTable(page1.getSourceDatabase(), page1.getTargetDatabase(), page2.getSelection());
}
/**
* @see org.eclipse.jface.wizard.Wizard#canFinish()
*/
public boolean canFinish()
{
return page2.canFinish();
}
};
wizard.addPage(page1);
wizard.addPage(page2);
WizardDialog wd = new WizardDialog(shell, wizard);
wd.setMinimumPageSize(700,400);
wd.open();
}
public boolean copyTable(DatabaseMeta sourceDBInfo, DatabaseMeta targetDBInfo, String tablename )
{
try
{
//
// Create a new transformation...
//
TransMeta meta = new TransMeta();
meta.addDatabase(sourceDBInfo);
meta.addDatabase(targetDBInfo);
//
// Add a note
//
String note = Messages.getString("Spoon.Message.Note.ReadInformationFromTableOnDB",tablename,sourceDBInfo.getDatabaseName() )+Const.CR;//"Reads information from table ["+tablename+"] on database ["+sourceDBInfo+"]"
note+=Messages.getString("Spoon.Message.Note.WriteInformationToTableOnDB",tablename,targetDBInfo.getDatabaseName() );//"After that, it writes the information to table ["+tablename+"] on database ["+targetDBInfo+"]"
NotePadMeta ni = new NotePadMeta(note, 150, 10, -1, -1);
meta.addNote(ni);
//
// create the source step...
//
String fromstepname = Messages.getString("Spoon.Message.Note.ReadFromTable",tablename); //"read from ["+tablename+"]";
TableInputMeta tii = new TableInputMeta();
tii.setDatabaseMeta(sourceDBInfo);
tii.setSQL("SELECT * FROM "+tablename);
StepLoader steploader = StepLoader.getInstance();
String fromstepid = steploader.getStepPluginID(tii);
StepMeta fromstep = new StepMeta(fromstepid, fromstepname, (StepMetaInterface)tii );
fromstep.setLocation(150,100);
fromstep.setDraw(true);
fromstep.setDescription(Messages.getString("Spoon.Message.Note.ReadInformationFromTableOnDB",tablename,sourceDBInfo.getDatabaseName() ));
meta.addStep(fromstep);
//
// add logic to rename fields in case any of the field names contain reserved words...
// Use metadata logic in SelectValues, use SelectValueInfo...
//
Database sourceDB = new Database(sourceDBInfo);
sourceDB.connect();
// Get the fields for the input table...
Row fields = sourceDB.getTableFields(tablename);
// See if we need to deal with reserved words...
int nrReserved = targetDBInfo.getNrReservedWords(fields);
if (nrReserved>0)
{
SelectValuesMeta svi = new SelectValuesMeta();
svi.allocate(0,0,nrReserved);
int nr = 0;
for (int i=0;i<fields.size();i++)
{
Value v = fields.getValue(i);
if (targetDBInfo.isReservedWord( v.getName() ) )
{
svi.getMetaName()[nr] = v.getName();
svi.getMetaRename()[nr] = targetDBInfo.quoteField( v.getName() );
nr++;
}
}
String selstepname =Messages.getString("Spoon.Message.Note.HandleReservedWords"); //"Handle reserved words";
String selstepid = steploader.getStepPluginID(svi);
StepMeta selstep = new StepMeta(selstepid, selstepname, (StepMetaInterface)svi );
selstep.setLocation(350,100);
selstep.setDraw(true);
selstep.setDescription(Messages.getString("Spoon.Message.Note.RenamesReservedWords",targetDBInfo.getDatabaseTypeDesc()) );//"Renames reserved words for "+targetDBInfo.getDatabaseTypeDesc()
meta.addStep(selstep);
TransHopMeta shi = new TransHopMeta(fromstep, selstep);
meta.addTransHop(shi);
fromstep = selstep;
}
//
// Create the target step...
//
//
// Add the TableOutputMeta step...
//
String tostepname = Messages.getString("Spoon.Message.Note.WriteToTable",tablename); // "write to ["+tablename+"]";
TableOutputMeta toi = new TableOutputMeta();
toi.setDatabaseMeta( targetDBInfo );
toi.setTablename( tablename );
toi.setCommitSize( 200 );
toi.setTruncateTable( true );
String tostepid = steploader.getStepPluginID(toi);
StepMeta tostep = new StepMeta(tostepid, tostepname, (StepMetaInterface)toi );
tostep.setLocation(550,100);
tostep.setDraw(true);
tostep.setDescription(Messages.getString("Spoon.Message.Note.WriteInformationToTableOnDB2",tablename,targetDBInfo.getDatabaseName() ));//"Write information to table ["+tablename+"] on database ["+targetDBInfo+"]"
meta.addStep(tostep);
//
// Add a hop between the two steps...
//
TransHopMeta hi = new TransHopMeta(fromstep, tostep);
meta.addTransHop(hi);
// OK, if we're still here: overwrite the current transformation...
// Set a name on this generated transformation
//
String name = "Copy table from ["+sourceDBInfo.getName()+"] to ["+targetDBInfo.getName()+"]";
String transName = name;
int nr=1;
if (findTransformation(transName)!=null)
{
nr++;
transName = name+" "+nr;
}
meta.setName(transName);
addSpoonGraph(meta);
refreshGraph();
refreshTree();
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.UnexpectedError.Title"), Messages.getString("Spoon.Dialog.UnexpectedError.Message"), new KettleException(e.getMessage(), e));//"Unexpected error" "An unexpected error occurred creating the new transformation"
return false;
}
return true;
}
public String toString()
{
return APP_NAME;
}
/**
* This is the main procedure for Spoon.
*
* @param a Arguments are available in the "Get System Info" step.
*/
public static void main (String [] a) throws KettleException
{
EnvUtil.environmentInit();
ArrayList args = new ArrayList();
for (int i=0;i<a.length;i++) args.add(a[i]);
Display display = new Display();
Splash splash = new Splash(display);
StringBuffer optionRepname, optionUsername, optionPassword, optionTransname, optionFilename, optionDirname, optionLogfile, optionLoglevel;
CommandLineOption options[] = new CommandLineOption[]
{
new CommandLineOption("rep", "Repository name", optionRepname=new StringBuffer()),
new CommandLineOption("user", "Repository username", optionUsername=new StringBuffer()),
new CommandLineOption("pass", "Repository password", optionPassword=new StringBuffer()),
new CommandLineOption("trans", "The name of the transformation to launch", optionTransname=new StringBuffer()),
new CommandLineOption("dir", "The directory (don't forget the leading /)", optionDirname=new StringBuffer()),
new CommandLineOption("file", "The filename (Transformation in XML) to launch", optionFilename=new StringBuffer()),
new CommandLineOption("level", "The logging level (Basic, Detailed, Debug, Rowlevel, Error, Nothing)", optionLoglevel=new StringBuffer()),
new CommandLineOption("logfile", "The logging file to write to", optionLogfile=new StringBuffer()),
new CommandLineOption("log", "The logging file to write to (deprecated)", optionLogfile=new StringBuffer(), false, true),
};
// Parse the options...
CommandLineOption.parseArguments(args, options);
String kettleRepname = Const.getEnvironmentVariable("KETTLE_REPOSITORY", null);
String kettleUsername = Const.getEnvironmentVariable("KETTLE_USER", null);
String kettlePassword = Const.getEnvironmentVariable("KETTLE_PASSWORD", null);
if (!Const.isEmpty(kettleRepname )) optionRepname = new StringBuffer(kettleRepname);
if (!Const.isEmpty(kettleUsername)) optionUsername = new StringBuffer(kettleUsername);
if (!Const.isEmpty(kettlePassword)) optionPassword = new StringBuffer(kettlePassword);
// Before anything else, check the runtime version!!!
String version = Const.JAVA_VERSION;
if ("1.4".compareToIgnoreCase(version)>0)
{
System.out.println("The System is running on Java version "+version);
System.out.println("Unfortunately, it needs version 1.4 or higher to run.");
return;
}
// Set default Locale:
Locale.setDefault(Const.DEFAULT_LOCALE);
LogWriter log;
LogWriter.setConsoleAppenderDebug();
if (Const.isEmpty(optionLogfile))
{
log=LogWriter.getInstance(Const.SPOON_LOG_FILE, false, LogWriter.LOG_LEVEL_BASIC);
}
else
{
log=LogWriter.getInstance( optionLogfile.toString(), true, LogWriter.LOG_LEVEL_BASIC );
}
if (log.getRealFilename()!=null) log.logBasic(APP_NAME, Messages.getString("Spoon.Log.LoggingToFile")+log.getRealFilename());//"Logging goes to "
if (!Const.isEmpty(optionLoglevel))
{
log.setLogLevel(optionLoglevel.toString());
log.logBasic(APP_NAME, Messages.getString("Spoon.Log.LoggingAtLevel")+log.getLogLevelDesc());//"Logging is at level : "
}
/* Load the plugins etc.*/
StepLoader stloader = StepLoader.getInstance();
if (!stloader.read())
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.ErrorLoadingAndHaltSystem"));//Error loading steps & plugins... halting Spoon!
return;
}
/* Load the plugins etc. we need to load jobentry*/
JobEntryLoader jeloader = JobEntryLoader.getInstance();
if (!jeloader.read())
{
log.logError("Spoon", "Error loading job entries & plugins... halting Kitchen!");
return;
}
final Spoon spoon = new Spoon(log, display, null);
staticSpoon = spoon;
spoon.setDestroy(true);
spoon.setArguments((String[])args.toArray(new String[args.size()]));
log.logBasic(APP_NAME, Messages.getString("Spoon.Log.MainWindowCreated"));//Main window is created.
RepositoryMeta repositoryMeta = null;
UserInfo userinfo = null;
if (Const.isEmpty(optionRepname) && Const.isEmpty(optionFilename) && spoon.props.showRepositoriesDialogAtStartup())
{
log.logBasic(APP_NAME, Messages.getString("Spoon.Log.AskingForRepository"));//"Asking for repository"
int perms[] = new int[] { PermissionMeta.TYPE_PERMISSION_TRANSFORMATION };
splash.hide();
RepositoriesDialog rd = new RepositoriesDialog(spoon.disp, SWT.NONE, perms, Messages.getString("Spoon.Application.Name"));//"Spoon"
if (rd.open())
{
repositoryMeta = rd.getRepository();
userinfo = rd.getUser();
if (!userinfo.useTransformations())
{
MessageBox mb = new MessageBox(spoon.shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(Messages.getString("Spoon.Dialog.RepositoryUserCannotWork.Message"));//"Sorry, this repository user can't work with transformations from the repository."
mb.setText(Messages.getString("Spoon.Dialog.RepositoryUserCannotWork.Title"));//"Error!"
mb.open();
userinfo = null;
repositoryMeta = null;
}
}
else
{
// Exit point: user pressed CANCEL!
if (rd.isCancelled())
{
splash.dispose();
spoon.quitFile();
return;
}
}
}
try
{
// Read kettle transformation specified on command-line?
if (!Const.isEmpty(optionRepname) || !Const.isEmpty(optionFilename))
{
if (!Const.isEmpty(optionRepname))
{
RepositoriesMeta repsinfo = new RepositoriesMeta(log);
if (repsinfo.readData())
{
repositoryMeta = repsinfo.findRepository(optionRepname.toString());
if (repositoryMeta!=null)
{
// Define and connect to the repository...
spoon.rep = new Repository(log, repositoryMeta, userinfo);
if (spoon.rep.connect(Messages.getString("Spoon.Application.Name")))//"Spoon"
{
if (Const.isEmpty(optionDirname)) optionDirname=new StringBuffer(RepositoryDirectory.DIRECTORY_SEPARATOR);
// Check username, password
spoon.rep.userinfo = new UserInfo(spoon.rep, optionUsername.toString(), optionPassword.toString());
if (spoon.rep.userinfo.getID()>0)
{
// OK, if we have a specified transformation, try to load it...
// If not, keep the repository logged in.
if (!Const.isEmpty(optionTransname))
{
RepositoryDirectory repdir = spoon.rep.getDirectoryTree().findDirectory(optionDirname.toString());
if (repdir!=null)
{
TransMeta transMeta = new TransMeta(spoon.rep, optionTransname.toString(), repdir);
transMeta.setFilename(optionRepname.toString());
transMeta.clearChanged();
spoon.addSpoonGraph(transMeta);
}
else
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableFindDirectory",optionDirname.toString()));//"Can't find directory ["+dirname+"] in the repository."
}
}
}
else
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableVerifyUser"));//"Can't verify username and password."
spoon.rep.disconnect();
spoon.rep=null;
}
}
else
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableConnectToRepository"));//"Can't connect to the repository."
}
}
else
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.NoRepositoryRrovided"));//"No repository provided, can't load transformation."
}
}
else
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.NoRepositoriesDefined"));//"No repositories defined on this system."
}
}
else
if (!Const.isEmpty(optionFilename))
{
spoon.openFile(optionFilename.toString(), false);
}
}
else // Normal operations, nothing on the commandline...
{
// Can we connect to the repository?
if (repositoryMeta!=null && userinfo!=null)
{
spoon.rep = new Repository(log, repositoryMeta, userinfo);
if (!spoon.rep.connect(Messages.getString("Spoon.Application.Name"))) //"Spoon"
{
spoon.rep = null;
}
}
if (spoon.props.openLastFile())
{
log.logDetailed(APP_NAME, Messages.getString("Spoon.Log.TryingOpenLastUsedFile"));//"Trying to open the last file used."
List lastUsedFiles = spoon.props.getLastUsedFiles();
if (lastUsedFiles.size()>0)
{
LastUsedFile lastUsedFile = (LastUsedFile) lastUsedFiles.get(0);
spoon.loadLastUsedFile(lastUsedFile, repositoryMeta);
}
}
}
}
catch(KettleException ke)
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.ErrorOccurred")+Const.CR+ke.getMessage());//"An error occurred: "
spoon.rep=null;
// ke.printStackTrace();
}
spoon.open ();
splash.dispose();
try
{
while (!spoon.isDisposed ())
{
if (!spoon.readAndDispatch ()) spoon.sleep ();
}
}
catch(Throwable e)
{
log.logError(APP_NAME, Messages.getString("Spoon.Log.UnexpectedErrorOccurred")+Const.CR+e.getMessage());//"An unexpected error occurred in Spoon: probable cause: please close all windows before stopping Spoon! "
e.printStackTrace();
}
spoon.dispose();
log.logBasic(APP_NAME, APP_NAME+" "+Messages.getString("Spoon.Log.AppHasEnded"));//" has ended."
// Close the logfile
log.close();
// Kill all remaining things in this VM!
System.exit(0);
}
private void loadLastUsedFile(LastUsedFile lastUsedFile, RepositoryMeta repositoryMeta) throws KettleException
{
boolean useRepository = repositoryMeta!=null;
// Perhaps we need to connect to the repository?
if (lastUsedFile.isSourceRepository())
{
if (!Const.isEmpty(lastUsedFile.getRepositoryName()))
{
if (useRepository && !lastUsedFile.getRepositoryName().equalsIgnoreCase(repositoryMeta.getName()))
{
// We just asked...
useRepository = false;
}
}
}
if (useRepository && lastUsedFile.isSourceRepository())
{
if (rep!=null) // load from this repository...
{
if (rep.getName().equalsIgnoreCase(lastUsedFile.getRepositoryName()))
{
RepositoryDirectory repdir = rep.getDirectoryTree().findDirectory(lastUsedFile.getDirectory());
if (repdir!=null)
{
// Are we loading a transformation or a job?
if (lastUsedFile.isTransformation())
{
log.logDetailed(APP_NAME, Messages.getString("Spoon.Log.AutoLoadingTransformation",lastUsedFile.getFilename(), lastUsedFile.getDirectory()));//"Auto loading transformation ["+lastfiles[0]+"] from repository directory ["+lastdirs[0]+"]"
TransLoadProgressDialog tlpd = new TransLoadProgressDialog(shell, rep, lastUsedFile.getFilename(), repdir);
TransMeta transMeta = tlpd.open(); // = new TransInfo(log, win.rep, lastfiles[0], repdir);
if (transMeta != null)
{
props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, lastUsedFile.getFilename(), repdir.getPath(), true, rep.getName());
transMeta.setFilename(lastUsedFile.getFilename());
transMeta.clearChanged();
addSpoonGraph(transMeta);
refreshTree();
}
}
else
if (lastUsedFile.isJob())
{
// TODO: use JobLoadProgressDialog
JobMeta jobMeta = new JobMeta(log, rep, lastUsedFile.getFilename(), repdir);
props.addLastFile(LastUsedFile.FILE_TYPE_JOB, lastUsedFile.getFilename(), repdir.getPath(), true, rep.getName());
jobMeta.clearChanged();
addChefGraph(jobMeta);
}
refreshTree();
}
}
}
}
if (!lastUsedFile.isSourceRepository() && !Const.isEmpty(lastUsedFile.getFilename()))
{
if (lastUsedFile.isTransformation())
{
TransMeta transMeta = new TransMeta(lastUsedFile.getFilename());
transMeta.setFilename(lastUsedFile.getFilename());
transMeta.clearChanged();
props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, lastUsedFile.getFilename(), null, false, null);
addSpoonGraph(transMeta);
}
if (lastUsedFile.isJob())
{
JobMeta jobMeta = new JobMeta(log, lastUsedFile.getFilename(), rep);
jobMeta.setFilename(lastUsedFile.getFilename());
jobMeta.clearChanged();
props.addLastFile(LastUsedFile.FILE_TYPE_JOB, lastUsedFile.getFilename(), null, false, null);
addChefGraph(jobMeta);
}
refreshTree();
}
}
/**
* Create a new SelectValues step in between this step and the previous.
* If the previous fields are not there, no mapping can be made, same with the required fields.
* @param stepMeta The target step to map against.
*/
public void generateMapping(TransMeta transMeta, StepMeta stepMeta)
{
try
{
if (stepMeta!=null)
{
StepMetaInterface smi = stepMeta.getStepMetaInterface();
Row targetFields = smi.getRequiredFields();
Row sourceFields = transMeta.getPrevStepFields(stepMeta);
// Build the mapping: let the user decide!!
String[] source = sourceFields.getFieldNames();
for (int i=0;i<source.length;i++)
{
Value v = sourceFields.getValue(i);
source[i]+=EnterMappingDialog.STRING_ORIGIN_SEPARATOR+v.getOrigin()+")";
}
String[] target = targetFields.getFieldNames();
EnterMappingDialog dialog = new EnterMappingDialog(shell, source, target);
ArrayList mappings = dialog.open();
if (mappings!=null)
{
// OK, so we now know which field maps where.
// This allows us to generate the mapping using a SelectValues Step...
SelectValuesMeta svm = new SelectValuesMeta();
svm.allocate(mappings.size(), 0, 0);
for (int i=0;i<mappings.size();i++)
{
SourceToTargetMapping mapping = (SourceToTargetMapping) mappings.get(i);
svm.getSelectName()[i] = sourceFields.getValue(mapping.getSourcePosition()).getName();
svm.getSelectRename()[i] = target[mapping.getTargetPosition()];
svm.getSelectLength()[i] = -1;
svm.getSelectPrecision()[i] = -1;
}
// Now that we have the meta-data, create a new step info object
String stepName = stepMeta.getName()+" Mapping";
stepName = transMeta.getAlternativeStepname(stepName); // if it's already there, rename it.
StepMeta newStep = new StepMeta("SelectValues", stepName, svm);
newStep.setLocation(stepMeta.getLocation().x+20, stepMeta.getLocation().y+20);
newStep.setDraw(true);
transMeta.addStep(newStep);
addUndoNew(transMeta, new StepMeta[] { newStep }, new int[] { transMeta.indexOfStep(newStep) });
// Redraw stuff...
refreshTree();
refreshGraph();
}
}
else
{
System.out.println("No target to do mapping against!");
}
}
catch(KettleException e)
{
new ErrorDialog(shell, "Error creating mapping", "There was an error when Kettle tried to generate a mapping against the target step", e);
}
}
public void editPartitioning(TransMeta transMeta, StepMeta stepMeta)
{
StepPartitioningMeta stepPartitioningMeta = stepMeta.getStepPartitioningMeta();
if (stepPartitioningMeta==null) stepPartitioningMeta = new StepPartitioningMeta();
String[] options = StepPartitioningMeta.methodDescriptions;
EnterSelectionDialog dialog = new EnterSelectionDialog(shell, options, "Partioning method", "Select the partitioning method");
String methodDescription = dialog.open(stepPartitioningMeta.getMethod());
if (methodDescription!=null)
{
int method = StepPartitioningMeta.getMethod(methodDescription);
stepPartitioningMeta.setMethod(method);
switch(method)
{
case StepPartitioningMeta.PARTITIONING_METHOD_NONE: break;
case StepPartitioningMeta.PARTITIONING_METHOD_MOD:
// ask for a fieldname
EnterStringDialog stringDialog = new EnterStringDialog(shell, props, Const.NVL(stepPartitioningMeta.getFieldName(), ""), "Fieldname", "Enter a field name to partition on");
String fieldName = stringDialog.open();
stepPartitioningMeta.setFieldName(fieldName);
// Ask for a Partitioning Schema
String schemaNames[] = transMeta.getPartitionSchemasNames();
if (schemaNames.length==0)
{
MessageBox box = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
box.setText("Create a partition schema");
box.setMessage("You first need to create one or more partition schemas in the transformation settings dialog before you can select one!");
box.open();
}
else
{
// Set the partitioning schema too.
PartitionSchema partitionSchema = stepPartitioningMeta.getPartitionSchema();
int idx = -1;
if (partitionSchema!=null)
{
idx = Const.indexOfString(partitionSchema.getName(), schemaNames);
}
EnterSelectionDialog askSchema = new EnterSelectionDialog(shell, schemaNames, "Select a partition schema", "Select the partition schema to use:");
String schemaName = askSchema.open(idx);
if (schemaName!=null)
{
idx = Const.indexOfString(schemaName, schemaNames);
stepPartitioningMeta.setPartitionSchema((PartitionSchema) transMeta.getPartitionSchemas().get(idx));
}
}
break;
}
refreshGraph();
}
}
/**
* Select a clustering schema for this step.
*
* @param stepMeta The step to set the clustering schema for.
*/
public void editClustering(TransMeta transMeta, StepMeta stepMeta)
{
int idx = -1;
if (stepMeta.getClusterSchema()!=null)
{
idx = transMeta.getClusterSchemas().indexOf( stepMeta.getClusterSchema() );
}
String[] clusterSchemaNames = transMeta.getClusterSchemaNames();
EnterSelectionDialog dialog = new EnterSelectionDialog(shell, clusterSchemaNames, "Cluster schema", "Select the cluster schema to use (cancel=clear)");
String schemaName = dialog.open(idx);
if (schemaName==null)
{
stepMeta.setClusterSchema(null);
}
else
{
ClusterSchema clusterSchema = transMeta.findClusterSchema(schemaName);
stepMeta.setClusterSchema( clusterSchema );
}
refreshTree();
refreshGraph();
}
public void createKettleArchive(TransMeta transMeta)
{
if (transMeta==null) return;
JarfileGenerator.generateJarFile(transMeta);
}
/**
* This creates a new database partitioning schema, edits it and adds it to the transformation metadata
*
*/
public void newDatabasePartitioningSchema(TransMeta transMeta)
{
PartitionSchema partitionSchema = new PartitionSchema();
PartitionSchemaDialog dialog = new PartitionSchemaDialog(shell, partitionSchema, transMeta.getDatabases());
if (dialog.open())
{
transMeta.getPartitionSchemas().add(partitionSchema);
refreshTree();
}
}
private void editPartitionSchema(HasDatabasesInterface hasDatabasesInterface, PartitionSchema partitionSchema)
{
PartitionSchemaDialog dialog = new PartitionSchemaDialog(shell, partitionSchema, hasDatabasesInterface.getDatabases());
if (dialog.open())
{
refreshTree();
}
}
private void delPartitionSchema(TransMeta transMeta, PartitionSchema partitionSchema)
{
try
{
if (rep!=null && partitionSchema.getId()>0)
{
// remove the partition schema from the repository too...
rep.delPartitionSchema(partitionSchema.getId());
}
int idx = transMeta.getPartitionSchemas().indexOf(partitionSchema);
transMeta.getPartitionSchemas().remove(idx);
refreshTree();
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorDeletingClusterSchema.Title"), Messages.getString("Spoon.Dialog.ErrorDeletingClusterSchema.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* This creates a new clustering schema, edits it and adds it to the transformation metadata
*
*/
public void newClusteringSchema(TransMeta transMeta)
{
ClusterSchema clusterSchema = new ClusterSchema();
ClusterSchemaDialog dialog = new ClusterSchemaDialog(shell, clusterSchema, transMeta.getSlaveServers());
if (dialog.open())
{
transMeta.getClusterSchemas().add(clusterSchema);
refreshTree();
}
}
private void editClusterSchema(TransMeta transMeta, ClusterSchema clusterSchema)
{
ClusterSchemaDialog dialog = new ClusterSchemaDialog(shell, clusterSchema, transMeta.getSlaveServers());
if (dialog.open())
{
refreshTree();
}
}
private void delClusterSchema(TransMeta transMeta, ClusterSchema clusterSchema)
{
try
{
if (rep!=null && clusterSchema.getId()>0)
{
// remove the partition schema from the repository too...
rep.delClusterSchema(clusterSchema.getId());
}
int idx = transMeta.getClusterSchemas().indexOf(clusterSchema);
transMeta.getClusterSchemas().remove(idx);
refreshTree();
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorDeletingPartitionSchema.Title"), Messages.getString("Spoon.Dialog.ErrorDeletingPartitionSchema.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* This creates a slave server, edits it and adds it to the transformation metadata
*
*/
public void newSlaveServer(TransMeta transMeta)
{
SlaveServer slaveServer = new SlaveServer();
SlaveServerDialog dialog = new SlaveServerDialog(shell, slaveServer);
if (dialog.open())
{
transMeta.getSlaveServers().add(slaveServer);
refreshTree();
}
}
public void delSlaveServer(TransMeta transMeta, SlaveServer slaveServer)
{
try
{
if (rep!=null && slaveServer.getId()>0)
{
// remove the slave server from the repository too...
rep.delSlave(slaveServer.getId());
}
int idx = transMeta.getSlaveServers().indexOf(slaveServer);
transMeta.getSlaveServers().remove(idx);
refreshTree();
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.Dialog.ErrorDeletingSlave.Title"), Messages.getString("Spoon.Dialog.ErrorDeletingSlave.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* Sends transformation to slave server
* @param executionConfiguration
*/
public void sendXMLToSlaveServer(TransMeta transMeta, TransExecutionConfiguration executionConfiguration)
{
SlaveServer slaveServer = executionConfiguration.getRemoteServer();
try
{
if (slaveServer==null) throw new KettleException("No slave server specified");
if (Const.isEmpty(transMeta.getName())) throw new KettleException("The transformation needs a name to uniquely identify it by on the remote server.");
String reply = slaveServer.sendXML(new TransConfiguration(transMeta, executionConfiguration).getXML(), AddTransServlet.CONTEXT_PATH+"?xml=Y");
WebResult webResult = WebResult.fromXMLString(reply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("There was an error posting the transformation on the remote server: "+Const.CR+webResult.getMessage());
}
reply = slaveServer.getContentFromServer(PrepareExecutionTransHandler.CONTEXT_PATH+"?name="+transMeta.getName()+"&xml=Y");
webResult = WebResult.fromXMLString(reply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("There was an error preparing the transformation for excution on the remote server: "+Const.CR+webResult.getMessage());
}
reply = slaveServer.getContentFromServer(StartExecutionTransHandler.CONTEXT_PATH+"?name="+transMeta.getName()+"&xml=Y");
webResult = WebResult.fromXMLString(reply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("There was an error starting the transformation on the remote server: "+Const.CR+webResult.getMessage());
}
}
catch (Exception e)
{
new ErrorDialog(shell, "Error", "Error sending transformation to server", e);
}
}
private void splitTrans(TransMeta transMeta, boolean show, boolean post, boolean prepare, boolean start)
{
try
{
if (Const.isEmpty(transMeta.getName())) throw new KettleException("The transformation needs a name to uniquely identify it by on the remote server.");
TransSplitter transSplitter = new TransSplitter(transMeta);
transSplitter.splitOriginalTransformation();
// Send the transformations to the servers...
//
// First the master...
//
TransMeta master = transSplitter.getMaster();
SlaveServer masterServer = null;
List masterSteps = master.getTransHopSteps(false);
if (masterSteps.size()>0) // If there is something that needs to be done on the master...
{
masterServer = transSplitter.getMasterServer();
if (show) addSpoonGraph(master);
if (post)
{
String masterReply = masterServer.sendXML(new TransConfiguration(master, executionConfiguration).getXML(), AddTransServlet.CONTEXT_PATH+"?xml=Y");
WebResult webResult = WebResult.fromXMLString(masterReply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("An error occurred sending the master transformation: "+webResult.getMessage());
}
}
}
// Then the slaves...
//
SlaveServer slaves[] = transSplitter.getSlaveTargets();
for (int i=0;i<slaves.length;i++)
{
TransMeta slaveTrans = (TransMeta) transSplitter.getSlaveTransMap().get(slaves[i]);
if (show) addSpoonGraph(slaveTrans);
if (post)
{
String slaveReply = slaves[i].sendXML(new TransConfiguration(slaveTrans, executionConfiguration).getXML(), AddTransServlet.CONTEXT_PATH+"?xml=Y");
WebResult webResult = WebResult.fromXMLString(slaveReply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("An error occurred sending a slave transformation: "+webResult.getMessage());
}
}
}
if (post)
{
if (prepare)
{
// Prepare the master...
if (masterSteps.size()>0) // If there is something that needs to be done on the master...
{
String masterReply = masterServer.getContentFromServer(PrepareExecutionTransHandler.CONTEXT_PATH+"?name="+master.getName()+"&xml=Y");
WebResult webResult = WebResult.fromXMLString(masterReply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("An error occurred while preparing the execution of the master transformation: "+webResult.getMessage());
}
}
// Prepare the slaves
for (int i=0;i<slaves.length;i++)
{
TransMeta slaveTrans = (TransMeta) transSplitter.getSlaveTransMap().get(slaves[i]);
String slaveReply = slaves[i].getContentFromServer(PrepareExecutionTransHandler.CONTEXT_PATH+"?name="+slaveTrans.getName()+"&xml=Y");
WebResult webResult = WebResult.fromXMLString(slaveReply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("An error occurred while preparing the execution of a slave transformation: "+webResult.getMessage());
}
}
}
if (start)
{
// Start the master...
if (masterSteps.size()>0) // If there is something that needs to be done on the master...
{
String masterReply = masterServer.getContentFromServer(StartExecutionTransHandler.CONTEXT_PATH+"?name="+master.getName()+"&xml=Y");
WebResult webResult = WebResult.fromXMLString(masterReply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("An error occurred while starting the execution of the master transformation: "+webResult.getMessage());
}
}
// Start the slaves
for (int i=0;i<slaves.length;i++)
{
TransMeta slaveTrans = (TransMeta) transSplitter.getSlaveTransMap().get(slaves[i]);
String slaveReply = slaves[i].getContentFromServer(StartExecutionTransHandler.CONTEXT_PATH+"?name="+slaveTrans.getName()+"&xml=Y");
WebResult webResult = WebResult.fromXMLString(slaveReply);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK))
{
throw new KettleException("An error occurred while starting the execution of a slave transformation: "+webResult.getMessage());
}
}
}
// Now add monitors for the master and all the slave servers
addSpoonSlave(masterServer);
for (int i=0;i<slaves.length;i++)
{
addSpoonSlave(slaves[i]);
}
}
}
catch(Exception e)
{
new ErrorDialog(shell, "Split transformation", "There was an error during transformation split", e);
}
}
public void executeFile(boolean local, boolean remote, boolean cluster, boolean preview, Date replayDate)
{
TransMeta transMeta = getActiveTransformation();
if (transMeta!=null) executeTransformation(transMeta, local, remote, cluster, preview, replayDate);
JobMeta jobMeta = getActiveJob();
if (jobMeta!=null) executeJob(jobMeta, local, remote, cluster, preview, replayDate);
}
public void executeTransformation(TransMeta transMeta, boolean local, boolean remote, boolean cluster, boolean preview, Date replayDate)
{
if (transMeta==null) return;
executionConfiguration.setExecutingLocally(local);
executionConfiguration.setExecutingRemotely(remote);
executionConfiguration.setExecutingClustered(cluster);
executionConfiguration.getUsedVariables(transMeta);
executionConfiguration.getUsedArguments(transMeta, arguments);
executionConfiguration.setReplayDate(replayDate);
executionConfiguration.setLocalPreviewing(preview);
executionConfiguration.setLogLevel(log.getLogLevel());
// executionConfiguration.setSafeModeEnabled( spoonLog!=null && spoonLog.isSafeModeChecked() );
TransExecutionConfigurationDialog dialog = new TransExecutionConfigurationDialog(shell, executionConfiguration, transMeta);
if (dialog.open())
{
addSpoonLog(transMeta);
SpoonLog spoonLog = getActiveSpoonLog();
if (executionConfiguration.isExecutingLocally())
{
if (executionConfiguration.isLocalPreviewing())
{
spoonLog.preview(executionConfiguration);
}
else
{
spoonLog.start(executionConfiguration);
}
}
else if(executionConfiguration.isExecutingRemotely())
{
if (executionConfiguration.getRemoteServer()!=null)
{
sendXMLToSlaveServer(transMeta, executionConfiguration);
addSpoonSlave(executionConfiguration.getRemoteServer());
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(Messages.getString("Spoon.Dialog.NoRemoteServerSpecified.Message"));
mb.setText(Messages.getString("Spoon.Dialog.NoRemoteServerSpecified.Title"));
mb.open();
}
}
else if (executionConfiguration.isExecutingClustered())
{
splitTrans( transMeta,
executionConfiguration.isClusterShowingTransformation(),
executionConfiguration.isClusterPosting(),
executionConfiguration.isClusterPreparing(),
executionConfiguration.isClusterStarting()
);
}
}
}
public void executeJob(JobMeta jobMeta, boolean local, boolean remote, boolean cluster, boolean preview, Date replayDate)
{
addChefLog(jobMeta);
ChefLog chefLog = getActiveJobLog();
chefLog.startJob(replayDate);
}
public CTabItem findCTabItem(String text)
{
CTabItem[] items = tabfolder.getItems();
for (int i=0;i<items.length;i++)
{
if (items[i].getText().equalsIgnoreCase(text)) return items[i];
}
return null;
}
private void addSpoonSlave(SlaveServer slaveServer)
{
// See if there is a SpoonSlave for this slaveServer...
String tabName = makeSlaveTabName(slaveServer);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
SpoonSlave spoonSlave = new SpoonSlave(tabfolder, SWT.NONE, this, slaveServer);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Status of slave server : "+slaveServer.getName()+" : "+slaveServer.getServerAndPort());
tabItem.setControl(spoonSlave);
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, spoonSlave));
}
int idx = tabfolder.indexOf(tabItem);
tabfolder.setSelection(idx);
}
public void addSpoonGraph(TransMeta transMeta)
{
String key = addTransformation(transMeta);
if (key!=null)
{
// See if there already is a tab for this graph
// If no, add it
// If yes, select that tab
//
String tabName = makeGraphTabName(transMeta);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
SpoonGraph spoonGraph = new SpoonGraph(tabfolder, this, transMeta);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Graphical view of Transformation : "+tabName);
tabItem.setImage(GUIResource.getInstance().getImageSpoonGraph());
tabItem.setControl(spoonGraph);
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, spoonGraph));
}
int idx = tabfolder.indexOf(tabItem);
// OK, also see if we need to open a new history window.
if (transMeta.getLogConnection()!=null && !Const.isEmpty(transMeta.getLogTable()))
{
addSpoonHistory(transMeta, false);
}
// keep the focus on the graph
tabfolder.setSelection(idx);
setUndoMenu(transMeta);
enableMenus();
}
}
public void addChefGraph(JobMeta jobMeta)
{
String key = addJob(jobMeta);
if (key!=null)
{
// See if there already is a tab for this graph
// If no, add it
// If yes, select that tab
//
String tabName = makeJobGraphTabName(jobMeta);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
ChefGraph chefGraph = new ChefGraph(tabfolder, this, jobMeta);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Graphical view of Job : "+tabName);
tabItem.setImage(GUIResource.getInstance().getImageChefGraph());
tabItem.setControl(chefGraph);
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, chefGraph));
}
int idx = tabfolder.indexOf(tabItem);
// OK, also see if we need to open a new history window.
if (jobMeta.getLogConnection()!=null && !Const.isEmpty(jobMeta.getLogTable()))
{
addChefHistory(jobMeta, false);
}
// keep the focus on the graph
tabfolder.setSelection(idx);
setUndoMenu(jobMeta);
enableMenus();
}
}
public boolean addSpoonBrowser(String name, String urlString)
{
try
{
// OK, now we have the HTML, create a new browset tab.
// See if there already is a tab for this browser
// If no, add it
// If yes, select that tab
//
CTabItem tabItem=findCTabItem(name);
if (tabItem==null)
{
SpoonBrowser browser = new SpoonBrowser(tabfolder, this, urlString);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(name);
tabItem.setControl(browser.getComposite());
tabMap.put(name, new TabMapEntry(tabItem, name, browser));
}
int idx = tabfolder.indexOf(tabItem);
// keep the focus on the graph
tabfolder.setSelection(idx);
return true;
}
catch(Throwable e)
{
return false;
}
}
public String makeLogTabName(TransMeta transMeta)
{
return "Trans log: "+makeGraphTabName(transMeta);
}
public String makeJobLogTabName(JobMeta jobMeta)
{
return "Job log: "+makeJobGraphTabName(jobMeta);
}
public String makeGraphTabName(TransMeta transMeta)
{
if (Const.isEmpty(transMeta.getName()))
{
if (Const.isEmpty(transMeta.getFilename()))
{
return STRING_TRANS_NO_NAME;
}
return transMeta.getFilename();
}
return transMeta.getName();
}
public String makeJobGraphTabName(JobMeta jobMeta)
{
if (Const.isEmpty(jobMeta.getName()))
{
if (Const.isEmpty(jobMeta.getFilename()))
{
return STRING_JOB_NO_NAME;
}
return jobMeta.getFilename();
}
return jobMeta.getName();
}
public String makeHistoryTabName(TransMeta transMeta)
{
return "Trans History: "+makeGraphTabName(transMeta);
}
public String makeJobHistoryTabName(JobMeta jobMeta)
{
return "Job History: "+makeJobGraphTabName(jobMeta);
}
public String makeSlaveTabName(SlaveServer slaveServer)
{
return "Slave server: "+slaveServer.getName();
}
public void addSpoonLog(TransMeta transMeta)
{
// See if there already is a tab for this log
// If no, add it
// If yes, select that tab
//
String tabName = makeLogTabName(transMeta);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
SpoonLog spoonLog = new SpoonLog(tabfolder, this, transMeta);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Execution log for transformation : "+makeGraphTabName(transMeta));
tabItem.setControl(spoonLog);
// If there is an associated history window, we want to keep that one up-to-date as well.
//
SpoonHistory spoonHistory = findSpoonHistoryOfTransformation(transMeta);
CTabItem historyItem = findCTabItem(makeHistoryTabName(transMeta));
if (spoonHistory!=null && historyItem!=null)
{
SpoonHistoryRefresher spoonHistoryRefresher = new SpoonHistoryRefresher(historyItem, spoonHistory);
tabfolder.addSelectionListener(spoonHistoryRefresher);
spoonLog.setSpoonHistoryRefresher(spoonHistoryRefresher);
}
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, spoonLog));
}
int idx = tabfolder.indexOf(tabItem);
tabfolder.setSelection(idx);
}
public void addChefLog(JobMeta jobMeta)
{
// See if there already is a tab for this log
// If no, add it
// If yes, select that tab
//
String tabName = makeJobLogTabName(jobMeta);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
ChefLog chefLog = new ChefLog(tabfolder, this, jobMeta);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Execution log for job: "+makeJobGraphTabName(jobMeta));
tabItem.setControl(chefLog);
// If there is an associated history window, we want to keep that one up-to-date as well.
//
ChefHistory chefHistory = findChefHistoryOfJob(jobMeta);
CTabItem historyItem = findCTabItem(makeJobHistoryTabName(jobMeta));
if (chefHistory!=null && historyItem!=null)
{
ChefHistoryRefresher chefHistoryRefresher = new ChefHistoryRefresher(historyItem, chefHistory);
tabfolder.addSelectionListener(chefHistoryRefresher);
chefLog.setChefHistoryRefresher(chefHistoryRefresher);
}
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, chefLog));
}
int idx = tabfolder.indexOf(tabItem);
tabfolder.setSelection(idx);
}
public void addSpoonHistory(TransMeta transMeta, boolean select)
{
// See if there already is a tab for this history view
// If no, add it
// If yes, select that tab
//
String tabName = makeHistoryTabName(transMeta);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
SpoonHistory spoonHistory = new SpoonHistory(tabfolder, this, transMeta);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Execution history for transformation : "+makeGraphTabName(transMeta));
tabItem.setControl(spoonHistory);
// If there is an associated log window that's open, find it and add a refresher
SpoonLog spoonLog = findSpoonLogOfTransformation(transMeta);
if (spoonLog!=null)
{
SpoonHistoryRefresher spoonHistoryRefresher = new SpoonHistoryRefresher(tabItem, spoonHistory);
tabfolder.addSelectionListener(spoonHistoryRefresher);
spoonLog.setSpoonHistoryRefresher(spoonHistoryRefresher);
}
spoonHistory.markRefreshNeeded(); // will refresh when first selected
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, spoonHistory));
}
if (select)
{
int idx = tabfolder.indexOf(tabItem);
tabfolder.setSelection(idx);
}
}
public void addChefHistory(JobMeta jobMeta, boolean select)
{
// See if there already is a tab for this history view
// If no, add it
// If yes, select that tab
//
String tabName = makeJobHistoryTabName(jobMeta);
CTabItem tabItem=findCTabItem(tabName);
if (tabItem==null)
{
ChefHistory chefHistory = new ChefHistory(tabfolder, this, jobMeta);
tabItem = new CTabItem(tabfolder, SWT.CLOSE);
tabItem.setText(tabName);
tabItem.setToolTipText("Execution history for job : "+makeJobGraphTabName(jobMeta));
tabItem.setControl(chefHistory);
// If there is an associated log window that's open, find it and add a refresher
ChefLog chefLog = findChefLogOfJob(jobMeta);
if (chefLog!=null)
{
ChefHistoryRefresher chefHistoryRefresher = new ChefHistoryRefresher(tabItem, chefHistory);
tabfolder.addSelectionListener(chefHistoryRefresher);
chefLog.setChefHistoryRefresher(chefHistoryRefresher);
}
chefHistory.markRefreshNeeded(); // will refresh when first selected
tabMap.put(tabName, new TabMapEntry(tabItem, tabName, chefHistory));
}
if (select)
{
int idx = tabfolder.indexOf(tabItem);
tabfolder.setSelection(idx);
}
}
/**
* Rename the tabs
*/
public void renameTabs()
{
Collection collection = tabMap.values();
List list = new ArrayList();
list.addAll(collection);
for (Iterator iter = list.iterator(); iter.hasNext();)
{
TabMapEntry entry = (TabMapEntry) iter.next();
if (entry.getTabItem().isDisposed())
{
// this should not be in the map, get rid of it.
tabMap.remove(entry.getObjectName());
continue;
}
String before = entry.getTabItem().getText();
Object managedObject = entry.getObject().getManagedObject();
if (managedObject!=null)
{
if (entry.getObject() instanceof SpoonGraph) entry.getTabItem().setText( makeGraphTabName( (TransMeta) managedObject ) );
if (entry.getObject() instanceof SpoonLog) entry.getTabItem().setText( makeLogTabName( (TransMeta) managedObject ) );
if (entry.getObject() instanceof SpoonHistory) entry.getTabItem().setText( makeHistoryTabName( (TransMeta) managedObject ) );
if (entry.getObject() instanceof ChefGraph) entry.getTabItem().setText( makeJobGraphTabName( (JobMeta) managedObject ) );
if (entry.getObject() instanceof ChefLog) entry.getTabItem().setText( makeJobLogTabName( (JobMeta) managedObject ) );
if (entry.getObject() instanceof ChefHistory) entry.getTabItem().setText( makeJobHistoryTabName( (JobMeta) managedObject) );
}
String after = entry.getTabItem().getText();
if (!before.equals(after))
{
entry.setObjectName(after);
tabMap.remove(before);
tabMap.put(after, entry);
// Also change the transformation map
if (entry.getObject() instanceof SpoonGraph)
{
transformationMap.remove(before);
transformationMap.put(after, entry.getObject().getManagedObject());
}
}
}
}
/**
* This contains a map between the name of a transformation and the TransMeta object.
* If the transformation has no name it will be mapped under a number [1], [2] etc.
* @return the transformation map
*/
public Map getTransformationMap()
{
return transformationMap;
}
/**
* @param transformationMap the transformation map to set
*/
public void setTransformationMap(Map transformationMap)
{
this.transformationMap = transformationMap;
}
/**
* @return the tabMap
*/
public Map getTabMap()
{
return tabMap;
}
/**
* @param tabMap the tabMap to set
*/
public void setTabMap(Map tabMap)
{
this.tabMap = tabMap;
}
public void pasteSteps()
{
// Is there an active SpoonGraph?
SpoonGraph spoonGraph = getActiveSpoonGraph();
if (spoonGraph==null) return;
TransMeta transMeta = spoonGraph.getTransMeta();
String clipcontent = fromClipboard();
if (clipcontent != null)
{
Point lastMove = spoonGraph.getLastMove();
if (lastMove != null)
{
pasteXML(transMeta, clipcontent, lastMove);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//
//
//
// Job manipulation steps...
//
//
//
//////////////////////////////////////////////////////////////////////////////////////////////////
public JobEntryCopy newJobEntry(JobMeta jobMeta, String type_desc, boolean openit)
{
JobEntryLoader jobLoader = JobEntryLoader.getInstance();
JobPlugin jobPlugin = null;
try
{
jobPlugin = jobLoader.findJobEntriesWithDescription(type_desc);
if (jobPlugin==null)
{
// Check if it's not START or DUMMY
if (JobMeta.STRING_SPECIAL_START.equals(type_desc) || JobMeta.STRING_SPECIAL_DUMMY.equals(type_desc))
{
jobPlugin = jobLoader.findJobEntriesWithID(JobMeta.STRING_SPECIAL);
}
}
if (jobPlugin!=null)
{
// Determine name & number for this entry.
String basename = type_desc;
int nr = jobMeta.generateJobEntryNameNr(basename);
String entry_name = basename+" "+nr; //$NON-NLS-1$
// Generate the appropriate class...
JobEntryInterface jei = jobLoader.getJobEntryClass(jobPlugin);
jei.setName(entry_name);
if (jei.isSpecial())
{
if (JobMeta.STRING_SPECIAL_START.equals(type_desc))
{
// Check if start is already on the canvas...
if (jobMeta.findStart()!=null)
{
ChefGraph.showOnlyStartOnceMessage(shell);
return null;
}
((JobEntrySpecial)jei).setStart(true);
jei.setName("Start");
}
if (JobMeta.STRING_SPECIAL_DUMMY.equals(type_desc))
{
((JobEntrySpecial)jei).setDummy(true);
jei.setName("Dummy");
}
}
if (openit)
{
JobEntryDialogInterface d = jei.getDialog(shell,jei,jobMeta,entry_name,rep);
if (d.open()!=null)
{
JobEntryCopy jge = new JobEntryCopy();
jge.setEntry(jei);
jge.setLocation(50,50);
jge.setNr(0);
jobMeta.addJobEntry(jge);
addUndoNew(jobMeta, new JobEntryCopy[] { jge }, new int[] { jobMeta.indexOfJobEntry(jge) });
refreshGraph();
refreshTree();
return jge;
}
else
{
return null;
}
}
else
{
JobEntryCopy jge = new JobEntryCopy();
jge.setEntry(jei);
jge.setLocation(50,50);
jge.setNr(0);
jobMeta.addJobEntry(jge);
addUndoNew(jobMeta, new JobEntryCopy[] { jge }, new int[] { jobMeta.indexOfJobEntry(jge) });
refreshGraph();
refreshTree();
return jge;
}
}
else
{
return null;
}
}
catch(Throwable e)
{
new ErrorDialog(shell, Messages.getString("Spoon.ErrorDialog.UnexpectedErrorCreatingNewChefGraphEntry.Title"), Messages.getString("Spoon.ErrorDialog.UnexpectedErrorCreatingNewChefGraphEntry.Message"),new Exception(e)); //$NON-NLS-1$ //$NON-NLS-2$
return null;
}
}
public boolean saveJobFile(JobMeta jobMeta)
{
log.logDetailed(toString(), "Save file..."); //$NON-NLS-1$
boolean saved = false;
if (rep!=null)
{
saved = saveJobRepository(jobMeta);
}
else
{
if (jobMeta.getFilename()!=null)
{
saved = saveJob(jobMeta, jobMeta.getFilename());
}
else
{
saved = saveJobFileAs(jobMeta);
}
}
if (saved) // all was OK
{
saved=saveJobSharedObjects(jobMeta);
}
return saved;
}
private boolean saveJobXMLFile(JobMeta jobMeta)
{
boolean saved=false;
FileDialog dialog = new FileDialog(shell, SWT.SAVE);
dialog.setFilterExtensions(Const.STRING_JOB_FILTER_EXT);
dialog.setFilterNames(Const.STRING_JOB_FILTER_NAMES);
String fname = dialog.open();
if (fname!=null)
{
// Is the filename ending on .ktr, .xml?
boolean ending=false;
for (int i=0;i<Const.STRING_JOB_FILTER_EXT.length-1;i++)
{
if (fname.endsWith(Const.STRING_JOB_FILTER_EXT[i].substring(1)))
{
ending=true;
}
}
if (fname.endsWith(Const.STRING_JOB_DEFAULT_EXT)) ending=true;
if (!ending)
{
fname+=Const.STRING_JOB_DEFAULT_EXT;
}
// See if the file already exists...
File f = new File(fname);
int id = SWT.YES;
if (f.exists())
{
MessageBox mb = new MessageBox(shell, SWT.NO | SWT.YES | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("Spoon.Dialog.PromptOverwriteFile.Message"));//"This file already exists. Do you want to overwrite it?"
mb.setText(Messages.getString("Spoon.Dialog.PromptOverwriteFile.Title"));//"This file already exists!"
id = mb.open();
}
if (id==SWT.YES)
{
saved=saveJob(jobMeta, fname);
jobMeta.setFilename(fname);
}
}
return saved;
}
public boolean saveJobRepository(JobMeta jobMeta)
{
return saveJobRepository(jobMeta, false);
}
public boolean saveJobRepository(JobMeta jobMeta, boolean ask_name)
{
log.logDetailed(toString(), "Save to repository..."); //$NON-NLS-1$
if (rep!=null)
{
boolean answer = true;
boolean ask = ask_name;
while (answer && ( ask || jobMeta.getName()==null || jobMeta.getName().length()==0 ) )
{
if (!ask)
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("Spoon.Dialog.GiveJobANameBeforeSaving.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.GiveJobANameBeforeSaving.Title")); //$NON-NLS-1$
mb.open();
}
ask=false;
answer = editJobProperties(jobMeta);
}
if (answer && jobMeta.getName()!=null && jobMeta.getName().length()>0)
{
if (!rep.getUserInfo().isReadonly())
{
boolean saved=false;
int response = SWT.YES;
if (jobMeta.showReplaceWarning(rep))
{
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.ICON_QUESTION);
mb.setMessage(Messages.getString("Chef.Dialog.JobExistsOverwrite.Message1")+jobMeta.getName()+Messages.getString("Chef.Dialog.JobExistsOverwrite.Message2")+Const.CR+Messages.getString("Chef.Dialog.JobExistsOverwrite.Message3")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
mb.setText(Messages.getString("Chef.Dialog.JobExistsOverwrite.Title")); //$NON-NLS-1$
response = mb.open();
}
if (response == SWT.YES)
{
// Keep info on who & when this transformation was changed...
jobMeta.modifiedDate = new Value("MODIFIED_DATE", Value.VALUE_TYPE_DATE); //$NON-NLS-1$
jobMeta.modifiedDate.sysdate();
jobMeta.modifiedUser = rep.getUserInfo().getLogin();
JobSaveProgressDialog jspd = new JobSaveProgressDialog(shell, rep, jobMeta);
if (jspd.open())
{
if (!props.getSaveConfirmation())
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell,
Messages.getString("Spoon.Dialog.JobWasStoredInTheRepository.Title"), //$NON-NLS-1$
null,
Messages.getString("Spoon.Dialog.JobWasStoredInTheRepository.Message"), //$NON-NLS-1$
MessageDialog.QUESTION,
new String[] { Messages.getString("System.Button.OK") }, //$NON-NLS-1$
0,
Messages.getString("Spoon.Dialog.JobWasStoredInTheRepository.Toggle"), //$NON-NLS-1$
props.getSaveConfirmation()
);
md.open();
props.setSaveConfirmation(md.getToggleState());
}
// Handle last opened files...
props.addLastFile(LastUsedFile.FILE_TYPE_JOB, jobMeta.getName(), jobMeta.getDirectory().getPath(), true, rep.getName());
saveSettings();
addMenuLast();
setShellText();
saved=true;
}
}
return saved;
}
else
{
MessageBox mb = new MessageBox(shell, SWT.CLOSE | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("Spoon.Dialog.UserCanOnlyReadFromTheRepositoryJobNotSaved.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.UserCanOnlyReadFromTheRepositoryJobNotSaved.Title")); //$NON-NLS-1$
mb.open();
}
}
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("Spoon.Dialog.NoRepositoryConnectionAvailable.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.NoRepositoryConnectionAvailable.Title")); //$NON-NLS-1$
mb.open();
}
return false;
}
public boolean saveJobFileAs(JobMeta jobMeta)
{
boolean saved=false;
if (rep!=null)
{
jobMeta.setID(-1L);
saved=saveJobRepository(jobMeta, true);
}
else
{
saved=saveJobXMLFile(jobMeta);
}
return saved;
}
public void saveJobFileAsXML(JobMeta jobMeta)
{
log.logBasic(toString(), "Save file as..."); //$NON-NLS-1$
FileDialog dialog = new FileDialog(shell, SWT.SAVE);
//dialog.setFilterPath("C:\\Projects\\kettle\\source\\");
dialog.setFilterExtensions(Const.STRING_JOB_FILTER_EXT);
dialog.setFilterNames (Const.STRING_JOB_FILTER_NAMES);
String fname = dialog.open();
if (fname!=null)
{
// Is the filename ending on .ktr, .xml?
boolean ending=false;
for (int i=0;i<Const.STRING_JOB_FILTER_EXT.length-1;i++)
{
if (fname.endsWith(Const.STRING_JOB_FILTER_EXT[i].substring(1))) ending=true;
}
if (fname.endsWith(Const.STRING_JOB_DEFAULT_EXT)) ending=true;
if (!ending)
{
fname+=Const.STRING_JOB_DEFAULT_EXT;
}
// See if the file already exists...
File f = new File(fname);
int id = SWT.YES;
if (f.exists())
{
MessageBox mb = new MessageBox(shell, SWT.NO | SWT.YES | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("Spoon.Dialog.FileExistsOverWrite.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.FileExistsOverWrite.Title")); //$NON-NLS-1$
id = mb.open();
}
if (id==SWT.YES)
{
saveJob(jobMeta, fname);
}
}
}
private boolean saveJob(JobMeta jobMeta, String fname)
{
boolean saved = false;
String xml = XMLHandler.getXMLHeader() + jobMeta.getXML();
try
{
DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File(fname)));
dos.write(xml.getBytes(Const.XML_ENCODING));
dos.close();
saved=true;
// Handle last opened files...
props.addLastFile(LastUsedFile.FILE_TYPE_JOB, fname, RepositoryDirectory.DIRECTORY_SEPARATOR, false, ""); //$NON-NLS-1$
saveSettings();
addMenuLast();
log.logDebug(toString(), "File written to ["+fname+"]"); //$NON-NLS-1$ //$NON-NLS-2$
jobMeta.setFilename( fname );
jobMeta.clearChanged();
setShellText();
}
catch(Exception e)
{
log.logDebug(toString(), "Error opening file for writing! --> "+e.toString()); //$NON-NLS-1$
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("Spoon.Dialog.ErrorSavingFile.Message")+Const.CR+e.toString()); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.ErrorSavingFile.Title")); //$NON-NLS-1$
mb.open();
}
return saved;
}
private boolean editJobProperties(JobMeta jobMeta)
{
if (jobMeta==null) return false;
JobDialog jd = new JobDialog(shell, SWT.NONE, jobMeta, rep);
JobMeta ji = jd.open();
// In this case, load shared objects
//
if (jd.isSharedObjectsFileChanged())
{
loadJobSharedObjects(jobMeta);
}
if (jd.isSharedObjectsFileChanged() || ji!=null)
{
refreshTree();
renameTabs(); // cheap operation, might as will do it anyway
}
setShellText();
return ji!=null;
}
public void editJobEntry(JobMeta jobMeta, JobEntryCopy je)
{
try
{
log.logBasic(toString(), "edit job graph entry: "+je.getName()); //$NON-NLS-1$
JobEntryCopy before =(JobEntryCopy)je.clone_deep();
boolean entry_changed=false;
JobEntryInterface jei = je.getEntry();
if (jei.isSpecial())
{
JobEntrySpecial special = (JobEntrySpecial) jei;
if (special.isDummy()) return;
}
JobEntryDialogInterface d = jei.getDialog(shell, jei, jobMeta,je.getName(),rep);
if (d!=null)
{
if (d.open()!=null)
{
entry_changed=true;
}
if (entry_changed)
{
JobEntryCopy after = (JobEntryCopy) je.clone();
addUndoChange(jobMeta, new JobEntryCopy[] { before }, new JobEntryCopy[] { after }, new int[] { jobMeta.indexOfJobEntry(je) } );
refreshGraph();
refreshTree();
}
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(Messages.getString("Spoon.Dialog.JobEntryCanNotBeChanged.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.JobEntryCanNotBeChanged.Title")); //$NON-NLS-1$
mb.open();
}
}
catch(Exception e)
{
if (!shell.isDisposed()) new ErrorDialog(shell, Messages.getString("Chef.ErrorDialog.ErrorEditingJobEntry.Title"), Messages.getString("Chef.ErrorDialog.ErrorEditingJobEntry.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public JobEntryTrans newJobEntry(JobMeta jobMeta, int type)
{
JobEntryTrans je = new JobEntryTrans();
je.setType(type);
String basename = JobEntryTrans.typeDesc[type];
int nr = jobMeta.generateJobEntryNameNr(basename);
je.setName(basename+" "+nr); //$NON-NLS-1$
setShellText();
return je;
}
public void deleteJobEntryCopies(JobMeta jobMeta, JobEntryCopy jobEntry)
{
String name = jobEntry.getName();
// TODO Show warning "Are you sure? This operation can't be undone." + clear undo buffer.
// First delete all the hops using entry with name:
JobHopMeta hi[] = jobMeta.getAllJobHopsUsing(name);
if (hi.length>0)
{
int hix[] = new int[hi.length];
for (int i=0;i<hi.length;i++) hix[i] = jobMeta.indexOfJobHop(hi[i]);
addUndoDelete(jobMeta, hi, hix);
for (int i=hix.length-1;i>=0;i--) jobMeta.removeJobHop(hix[i]);
}
// Then delete all the entries with name:
JobEntryCopy je[] = jobMeta.getAllChefGraphEntries(name);
int jex[] = new int[je.length];
for (int i=0;i<je.length;i++) jex[i] = jobMeta.indexOfJobEntry(je[i]);
addUndoDelete(jobMeta, je, jex);
for (int i=jex.length-1;i>=0;i--) jobMeta.removeJobEntry(jex[i]);
refreshGraph();
refreshTree();
}
public void dupeJobEntry(JobMeta jobMeta, JobEntryCopy jobEntry)
{
if (jobEntry!=null && !jobEntry.isStart())
{
JobEntryCopy dupejge = (JobEntryCopy)jobEntry.clone();
dupejge.setNr( jobMeta.findUnusedNr(dupejge.getName()) );
if (dupejge.isDrawn())
{
Point p = jobEntry.getLocation();
dupejge.setLocation(p.x+10, p.y+10);
}
jobMeta.addJobEntry(dupejge);
refreshGraph();
refreshTree();
setShellText();
}
}
public void copyJobEntries(JobMeta jobMeta, JobEntryCopy jec[])
{
if (jec==null || jec.length==0) return;
String xml = XMLHandler.getXMLHeader();
xml+="<jobentries>"+Const.CR; //$NON-NLS-1$
for (int i=0;i<jec.length;i++)
{
xml+=jec[i].getXML();
}
xml+=" </jobentries>"+Const.CR; //$NON-NLS-1$
toClipboard(xml);
}
public void pasteXML(JobMeta jobMeta, String clipcontent, Point loc)
{
try
{
Document doc = XMLHandler.loadXMLString(clipcontent);
// De-select all, re-select pasted steps...
jobMeta.unselectAll();
Node entriesnode = XMLHandler.getSubNode(doc, "jobentries"); //$NON-NLS-1$
int nr = XMLHandler.countNodes(entriesnode, "entry"); //$NON-NLS-1$
log.logDebug(toString(), "I found "+nr+" job entries to paste on location: "+loc); //$NON-NLS-1$ //$NON-NLS-2$
JobEntryCopy entries[] = new JobEntryCopy[nr];
//Point min = new Point(loc.x, loc.y);
Point min = new Point(99999999,99999999);
for (int i=0;i<nr;i++)
{
Node entrynode = XMLHandler.getSubNodeByNr(entriesnode, "entry", i); //$NON-NLS-1$
entries[i] = new JobEntryCopy(entrynode, jobMeta.getDatabases(), rep);
String name = jobMeta.getAlternativeJobentryName(entries[i].getName());
entries[i].setName(name);
if (loc!=null)
{
Point p = entries[i].getLocation();
if (min.x > p.x) min.x = p.x;
if (min.y > p.y) min.y = p.y;
}
}
// What's the difference between loc and min?
// This is the offset:
Point offset = new Point(loc.x-min.x, loc.y-min.y);
// Undo/redo object positions...
int position[] = new int[entries.length];
for (int i=0;i<entries.length;i++)
{
Point p = entries[i].getLocation();
String name = entries[i].getName();
entries[i].setLocation(p.x+offset.x, p.y+offset.y);
// Check the name, find alternative...
entries[i].setName( jobMeta.getAlternativeJobentryName(name) );
jobMeta.addJobEntry(entries[i]);
position[i] = jobMeta.indexOfJobEntry(entries[i]);
}
// Save undo information too...
addUndoNew(jobMeta, entries, position);
if (jobMeta.hasChanged())
{
refreshTree();
refreshGraph();
}
}
catch(KettleException e)
{
new ErrorDialog(shell, Messages.getString("Chef.ErrorDialog.ErrorPasingJobEntries.Title"), Messages.getString("Chef.ErrorDialog.ErrorPasingJobEntries.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public void newJobHop(JobMeta jobMeta, JobEntryCopy fr, JobEntryCopy to)
{
JobHopMeta hi = new JobHopMeta(fr, to);
jobMeta.addJobHop(hi);
addUndoNew(jobMeta, new JobHopMeta[] {hi}, new int[] { jobMeta.indexOfJobHop(hi)} );
refreshGraph();
refreshTree();
}
/**
* Create a job that extracts tables & data from a database.<p><p>
*
* 0) Select the database to rip<p>
* 1) Select the tables in the database to rip<p>
* 2) Select the database to dump to<p>
* 3) Select the repository directory in which it will end up<p>
* 4) Select a name for the new job<p>
* 5) Create an empty job with the selected name.<p>
* 6) Create 1 transformation for every selected table<p>
* 7) add every created transformation to the job & evaluate<p>
*
*/
private void ripDBWizard()
{
final ArrayList databases = getActiveDatabases();
if (databases.size() == 0) return; // Nothing to do here
final RipDatabaseWizardPage1 page1 = new RipDatabaseWizardPage1("1", databases); //$NON-NLS-1$
page1.createControl(shell);
final RipDatabaseWizardPage2 page2 = new RipDatabaseWizardPage2("2"); //$NON-NLS-1$
page2.createControl(shell);
final RipDatabaseWizardPage3 page3 = new RipDatabaseWizardPage3("3", rep); //$NON-NLS-1$
page3.createControl(shell);
Wizard wizard = new Wizard()
{
public boolean performFinish()
{
JobMeta jobMeta = ripDB(databases, page3.getJobname(), page3.getDirectory(), page1.getSourceDatabase(), page1.getTargetDatabase(), page2.getSelection());
if (jobMeta==null) return false;
addChefGraph(jobMeta);
return true;
}
/**
* @see org.eclipse.jface.wizard.Wizard#canFinish()
*/
public boolean canFinish()
{
return page3.canFinish();
}
};
wizard.addPage(page1);
wizard.addPage(page2);
wizard.addPage(page3);
WizardDialog wd = new WizardDialog(shell, wizard);
wd.setMinimumPageSize(700, 400);
wd.open();
}
public JobMeta ripDB(
final ArrayList databases,
final String jobname,
final RepositoryDirectory repdir,
final DatabaseMeta sourceDbInfo,
final DatabaseMeta targetDbInfo,
final String[] tables
)
{
//
// Create a new job...
//
final JobMeta jobMeta = new JobMeta(log);
jobMeta.setDatabases(databases);
jobMeta.setFilename(null);
jobMeta.setName(jobname);
jobMeta.setDirectory(repdir);
refreshTree();
refreshGraph();
final Point location = new Point(50, 50);
// The start entry...
final JobEntryCopy start = jobMeta.findStart();
start.setLocation(new Point(location.x, location.y));
start.setDrawn();
// final Thread parentThread = Thread.currentThread();
// Create a dialog with a progress indicator!
IRunnableWithProgress op = new IRunnableWithProgress()
{
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException
{
// This is running in a new process: copy some KettleVariables info
// LocalVariables.getInstance().createKettleVariables(Thread.currentThread().getName(),
// parentThread.getName(), true);
monitor.beginTask(Messages.getString("Spoon.RipDB.Monitor.BuildingNewJob"), tables.length); //$NON-NLS-1$
monitor.worked(0);
JobEntryCopy previous = start;
// Loop over the table-names...
for (int i = 0; i < tables.length && !monitor.isCanceled(); i++)
{
monitor.setTaskName(Messages.getString("Spoon.RipDB.Monitor.ProcessingTable") + tables[i] + "]..."); //$NON-NLS-1$ //$NON-NLS-2$
//
// Create the new transformation...
//
String transname = Messages.getString("Spoon.RipDB.Monitor.Transname1") + sourceDbInfo + "].[" + tables[i] + Messages.getString("Spoon.RipDB.Monitor.Transname2") + targetDbInfo + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
TransMeta ti = new TransMeta((String) null, transname, null);
ti.setDirectory(repdir);
//
// Add a note
//
String note = Messages.getString("Spoon.RipDB.Monitor.Note1") + tables[i] + Messages.getString("Spoon.RipDB.Monitor.Note2") + sourceDbInfo + "]" + Const.CR; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
note += Messages.getString("Spoon.RipDB.Monitor.Note3") + tables[i] + Messages.getString("Spoon.RipDB.Monitor.Note4") + targetDbInfo + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
NotePadMeta ni = new NotePadMeta(note, 150, 10, -1, -1);
ti.addNote(ni);
//
// Add the TableInputMeta step...
//
String fromstepname = Messages.getString("Spoon.RipDB.Monitor.FromStep.Name") + tables[i] + "]"; //$NON-NLS-1$ //$NON-NLS-2$
TableInputMeta tii = new TableInputMeta();
tii.setDatabaseMeta(sourceDbInfo);
tii.setSQL("SELECT * FROM " + sourceDbInfo.quoteField(tables[i])); //$NON-NLS-1$
String fromstepid = StepLoader.getInstance().getStepPluginID(tii);
StepMeta fromstep = new StepMeta(fromstepid, fromstepname, (StepMetaInterface) tii);
fromstep.setLocation(150, 100);
fromstep.setDraw(true);
fromstep
.setDescription(Messages.getString("Spoon.RipDB.Monitor.FromStep.Description") + tables[i] + Messages.getString("Spoon.RipDB.Monitor.FromStep.Description2") + sourceDbInfo + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
ti.addStep(fromstep);
//
// Add the TableOutputMeta step...
//
String tostepname = Messages.getString("Spoon.RipDB.Monitor.ToStep.Name") + tables[i] + "]"; //$NON-NLS-1$ //$NON-NLS-2$
TableOutputMeta toi = new TableOutputMeta();
toi.setDatabaseMeta(targetDbInfo);
toi.setTablename(tables[i]);
toi.setCommitSize(100);
toi.setTruncateTable(true);
String tostepid = StepLoader.getInstance().getStepPluginID(toi);
StepMeta tostep = new StepMeta(tostepid, tostepname, (StepMetaInterface) toi);
tostep.setLocation(500, 100);
tostep.setDraw(true);
tostep
.setDescription(Messages.getString("Spoon.RipDB.Monitor.ToStep.Description1") + tables[i] + Messages.getString("Spoon.RipDB.Monitor.ToStep.Description2") + targetDbInfo + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
ti.addStep(tostep);
//
// Add a hop between the two steps...
//
TransHopMeta hi = new TransHopMeta(fromstep, tostep);
ti.addTransHop(hi);
//
// Now we generate the SQL needed to run for this transformation.
//
// First set the limit to 1 to speed things up!
String tmpSql = tii.getSQL();
tii.setSQL(tii.getSQL() + sourceDbInfo.getLimitClause(1));
String sql = ""; //$NON-NLS-1$
try
{
sql = ti.getSQLStatementsString();
}
catch (KettleStepException kse)
{
throw new InvocationTargetException(kse,
Messages.getString("Spoon.RipDB.Exception.ErrorGettingSQLFromTransformation") + ti + "] : " + kse.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
}
// remove the limit
tii.setSQL(tmpSql);
//
// Now, save the transformation...
//
try
{
ti.saveRep(rep);
}
catch (KettleException dbe)
{
throw new InvocationTargetException(dbe, Messages.getString("Spoon.RipDB.Exception.UnableToSaveTransformationToRepository")); //$NON-NLS-1$
}
// We can now continue with the population of the job...
// //////////////////////////////////////////////////////////////////////
location.x = 250;
if (i > 0) location.y += 100;
//
// We can continue defining the job.
//
// First the SQL, but only if needed!
// If the table exists & has the correct format, nothing is done
//
if (!Const.isEmpty(sql))
{
String jesqlname = Messages.getString("Spoon.RipDB.JobEntrySQL.Name") + tables[i] + "]"; //$NON-NLS-1$ //$NON-NLS-2$
JobEntrySQL jesql = new JobEntrySQL(jesqlname);
jesql.setDatabase(targetDbInfo);
jesql.setSQL(sql);
jesql.setDescription(Messages.getString("Spoon.RipDB.JobEntrySQL.Description") + targetDbInfo + "].[" + tables[i] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
JobEntryCopy jecsql = new JobEntryCopy();
jecsql.setEntry(jesql);
jecsql.setLocation(new Point(location.x, location.y));
jecsql.setDrawn();
jobMeta.addJobEntry(jecsql);
// Add the hop too...
JobHopMeta jhi = new JobHopMeta(previous, jecsql);
jobMeta.addJobHop(jhi);
previous = jecsql;
}
//
// Add the jobentry for the transformation too...
//
String jetransname = Messages.getString("Spoon.RipDB.JobEntryTrans.Name") + tables[i] + "]"; //$NON-NLS-1$ //$NON-NLS-2$
JobEntryTrans jetrans = new JobEntryTrans(jetransname);
jetrans.setTransname(ti.getName());
jetrans.setDirectory(ti.getDirectory());
JobEntryCopy jectrans = new JobEntryCopy(log, jetrans);
jectrans
.setDescription(Messages.getString("Spoon.RipDB.JobEntryTrans.Description1") + Const.CR + Messages.getString("Spoon.RipDB.JobEntryTrans.Description2") + sourceDbInfo + "].[" + tables[i] + "]" + Const.CR + Messages.getString("Spoon.RipDB.JobEntryTrans.Description3") + targetDbInfo + "].[" + tables[i] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
jectrans.setDrawn();
location.x += 400;
jectrans.setLocation(new Point(location.x, location.y));
jobMeta.addJobEntry(jectrans);
// Add a hop between the last 2 job entries.
JobHopMeta jhi2 = new JobHopMeta(previous, jectrans);
jobMeta.addJobHop(jhi2);
previous = jectrans;
monitor.worked(1);
}
monitor.worked(100);
monitor.done();
}
};
try
{
ProgressMonitorDialog pmd = new ProgressMonitorDialog(shell);
pmd.run(false, true, op);
}
catch (InvocationTargetException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.ErrorDialog.RipDB.ErrorRippingTheDatabase.Title"), Messages.getString("Spoon.ErrorDialog.RipDB.ErrorRippingTheDatabase.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
return null;
}
catch (InterruptedException e)
{
new ErrorDialog(shell, Messages.getString("Spoon.ErrorDialog.RipDB.ErrorRippingTheDatabase.Title"), Messages.getString("Spoon.ErrorDialog.RipDB.ErrorRippingTheDatabase.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
return null;
}
finally
{
refreshGraph();
refreshTree();
}
return jobMeta;
}
/**
* Set the core object state.
*
* @param state
*/
public void setCoreObjectsState(int state)
{
coreObjectsState = state;
}
/**
* Get the core object state.
*
* @return state.
*/
public int getCoreObjectsState()
{
return coreObjectsState;
}
}
|
diff --git a/52n-wps-sextante/src/main/java/org/n52/wps/server/sextante/SextanteProcessDescriptionCreator.java b/52n-wps-sextante/src/main/java/org/n52/wps/server/sextante/SextanteProcessDescriptionCreator.java
index af2187a2..cd6b529f 100644
--- a/52n-wps-sextante/src/main/java/org/n52/wps/server/sextante/SextanteProcessDescriptionCreator.java
+++ b/52n-wps-sextante/src/main/java/org/n52/wps/server/sextante/SextanteProcessDescriptionCreator.java
@@ -1,362 +1,364 @@
package org.n52.wps.server.sextante;
import java.math.BigInteger;
import org.n52.wps.io.IOHandler;
import net.opengis.ows.x11.DomainMetadataType;
import net.opengis.ows.x11.RangeType;
import net.opengis.ows.x11.AllowedValuesDocument.AllowedValues;
import net.opengis.wps.x100.ComplexDataCombinationsType;
import net.opengis.wps.x100.ComplexDataDescriptionType;
import net.opengis.wps.x100.InputDescriptionType;
import net.opengis.wps.x100.LiteralInputType;
import net.opengis.wps.x100.OutputDescriptionType;
import net.opengis.wps.x100.ProcessDescriptionType;
import net.opengis.wps.x100.SupportedComplexDataInputType;
import net.opengis.wps.x100.SupportedComplexDataType;
import net.opengis.wps.x100.ProcessDescriptionType.DataInputs;
import net.opengis.wps.x100.ProcessDescriptionType.ProcessOutputs;
import es.unex.sextante.additionalInfo.AdditionalInfoMultipleInput;
import es.unex.sextante.additionalInfo.AdditionalInfoNumericalValue;
import es.unex.sextante.additionalInfo.AdditionalInfoRasterLayer;
import es.unex.sextante.additionalInfo.AdditionalInfoSelection;
import es.unex.sextante.additionalInfo.AdditionalInfoVectorLayer;
import es.unex.sextante.core.GeoAlgorithm;
import es.unex.sextante.core.OutputObjectsSet;
import es.unex.sextante.core.ParametersSet;
import es.unex.sextante.core.Sextante;
import es.unex.sextante.exceptions.NullParameterAdditionalInfoException;
import es.unex.sextante.outputs.Output;
import es.unex.sextante.outputs.OutputChart;
import es.unex.sextante.outputs.OutputRasterLayer;
import es.unex.sextante.outputs.OutputTable;
import es.unex.sextante.outputs.OutputText;
import es.unex.sextante.outputs.OutputVectorLayer;
import es.unex.sextante.parameters.Parameter;
import es.unex.sextante.parameters.ParameterBand;
import es.unex.sextante.parameters.ParameterBoolean;
import es.unex.sextante.parameters.ParameterFixedTable;
import es.unex.sextante.parameters.ParameterMultipleInput;
import es.unex.sextante.parameters.ParameterNumericalValue;
import es.unex.sextante.parameters.ParameterPoint;
import es.unex.sextante.parameters.ParameterRasterLayer;
import es.unex.sextante.parameters.ParameterSelection;
import es.unex.sextante.parameters.ParameterString;
import es.unex.sextante.parameters.ParameterTableField;
import es.unex.sextante.parameters.ParameterVectorLayer;
public class SextanteProcessDescriptionCreator implements SextanteConstants{
public ProcessDescriptionType createDescribeProcessType(GeoAlgorithm algorithm) throws NullParameterAdditionalInfoException, UnsupportedGeoAlgorithmException{
ProcessDescriptionType pdt = ProcessDescriptionType.Factory.newInstance();
pdt.setStatusSupported(true);
pdt.setStoreSupported(true);
/*XmlCursor c = pdt.newCursor();
c.toFirstChild();
c.toLastAttribute();
c.setAttributeText(new QName(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "schemaLocation"), "http://www.opengis.net/wps/1.0.0 http://schemas.opengis.net/wps/1.0.0/wpsDescribeProcess_response.xsd");
*/
pdt.addNewAbstract().setStringValue(algorithm.getName());
pdt.addNewTitle().setStringValue(algorithm.getName());
pdt.addNewIdentifier().setStringValue(algorithm.getCommandLineName());
pdt.setProcessVersion("1.0.0");
//inputs
DataInputs inputs = pdt.addNewDataInputs();
ParametersSet params = algorithm.getParameters();
for (int i = 0; i < params.getNumberOfParameters(); i++) {
Parameter param = params.getParameter(i);
addParameter(inputs, param);
}
//grid extent for raster layers (if needed)
if (algorithm.generatesUserDefinedRasterOutput()){
addGridExtent(inputs, algorithm.requiresRasterLayers());
}
//outputs
ProcessOutputs outputs = pdt.addNewProcessOutputs();
OutputObjectsSet ooset = algorithm.getOutputObjects();
for (int i = 0; i < ooset.getOutputObjectsCount(); i++) {
Output out = ooset.getOutput(i);
addOutput(outputs, out);
}
return pdt;
}
private void addGridExtent(DataInputs inputs, boolean bOptional){
addDoubleValue(inputs, GRID_EXTENT_X_MIN, "xMin", bOptional);
addDoubleValue(inputs, GRID_EXTENT_X_MAX, "xMax", bOptional);
addDoubleValue(inputs, GRID_EXTENT_Y_MIN, "yMin", bOptional);
addDoubleValue(inputs, GRID_EXTENT_Y_MAX, "yMax", bOptional);
addDoubleValue(inputs, GRID_EXTENT_CELLSIZE, "cellsize", bOptional);
}
private void addDoubleValue(DataInputs inputs, String name, String description, boolean bOptional){
int iMinOccurs = 1;
if (bOptional){
iMinOccurs = 0;
}
InputDescriptionType input = inputs.addNewInput();
input.addNewAbstract().setStringValue(description);
input.addNewTitle().setStringValue(description);
input.addNewIdentifier().setStringValue(name);
LiteralInputType literal = input.addNewLiteralData();
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:double");
literal.setDataType(dataType);
input.setMinOccurs(BigInteger.valueOf(iMinOccurs));
input.setMaxOccurs(BigInteger.valueOf(1));
literal.setDefaultValue("0");
}
private void addOutput(ProcessOutputs outputs, Output out) {
OutputDescriptionType output = outputs.addNewOutput();
output.addNewAbstract().setStringValue(out.getDescription());
output.addNewIdentifier().setStringValue(out.getName());
output.addNewTitle().setStringValue(out.getDescription());
if (out instanceof OutputRasterLayer){
SupportedComplexDataType complexOutput = output.addNewComplexOutput();
complexOutput.addNewDefault().addNewFormat().setMimeType("image/tiff");
complexOutput.addNewSupported().addNewFormat().setMimeType("image/tiff");
}
else if (out instanceof OutputVectorLayer){
SupportedComplexDataType complexOutput = output.addNewComplexOutput();
ComplexDataDescriptionType deafult = complexOutput.addNewDefault().addNewFormat();
deafult.setMimeType(IOHandler.DEFAULT_MIMETYPE);
deafult.setSchema("http://geoserver.itc.nl:8080/wps/schemas/gml/2.1.2/gmlpacket.xsd");
ComplexDataCombinationsType supported = complexOutput.addNewSupported();
ComplexDataDescriptionType supportedFormat = supported.addNewFormat();
supportedFormat.setMimeType(IOHandler.DEFAULT_MIMETYPE);
supportedFormat.setSchema("http://schemas.opengis.net/gml/2.1.2/feature.xsd");
supportedFormat = supported.addNewFormat();
supportedFormat.setMimeType(IOHandler.MIME_TYPE_ZIPPED_SHP);
supportedFormat.setEncoding(IOHandler.ENCODING_BASE64);
}
else if (out instanceof OutputTable){
//TODO:
}
else if (out instanceof OutputText){
output.addNewComplexOutput().addNewDefault().addNewFormat().setMimeType("text/html");
}
else if (out instanceof OutputChart){
//TODO:
}
}
private void addParameter(DataInputs inputs, Parameter param) throws NullParameterAdditionalInfoException,
UnsupportedGeoAlgorithmException {
InputDescriptionType input = inputs.addNewInput();
input.addNewAbstract().setStringValue(param.getParameterDescription());
input.addNewTitle().setStringValue(param.getParameterDescription());
input.addNewIdentifier().setStringValue(param.getParameterName());
if (param instanceof ParameterRasterLayer){
AdditionalInfoRasterLayer ai = (AdditionalInfoRasterLayer) param.getParameterAdditionalInfo();
SupportedComplexDataInputType complex = input.addNewComplexData();
ComplexDataCombinationsType supported = complex.addNewSupported();
ComplexDataDescriptionType format = supported.addNewFormat();
format.setMimeType("image/tiff");
format = supported.addNewFormat();
format.setMimeType("image/tiff");
format.setEncoding(IOHandler.ENCODING_BASE64);
ComplexDataDescriptionType defaultFormat = complex.addNewDefault().addNewFormat();
defaultFormat.setMimeType("image/tiff");
if (ai.getIsMandatory()){
input.setMinOccurs(BigInteger.valueOf(1));
}
else{
input.setMinOccurs(BigInteger.valueOf(0));
}
input.setMaxOccurs(BigInteger.valueOf(1));
}
if (param instanceof ParameterVectorLayer){
//TODO:add shape type
AdditionalInfoVectorLayer ai = (AdditionalInfoVectorLayer) param.getParameterAdditionalInfo();
SupportedComplexDataInputType complex = input.addNewComplexData();
ComplexDataCombinationsType supported = complex.addNewSupported();
ComplexDataDescriptionType format = supported.addNewFormat();
format.setMimeType(IOHandler.DEFAULT_MIMETYPE);
format.setSchema("http://schemas.opengis.net/gml/2.1.2/feature.xsd");
format = supported.addNewFormat();
format.setEncoding(IOHandler.ENCODING_BASE64);
format.setMimeType(IOHandler.MIME_TYPE_ZIPPED_SHP);
ComplexDataDescriptionType defaultFormat = complex.addNewDefault().addNewFormat();
defaultFormat.setMimeType(IOHandler.DEFAULT_MIMETYPE);
defaultFormat.setSchema("http://geoserver.itc.nl:8080/wps/schemas/gml/2.1.2/gmlpacket.xsd");
if (ai.getIsMandatory()){
input.setMinOccurs(BigInteger.valueOf(1));
}
else{
input.setMinOccurs(BigInteger.valueOf(0));
}
input.setMaxOccurs(BigInteger.valueOf(1));
}
else if (param instanceof ParameterNumericalValue){
AdditionalInfoNumericalValue ai = (AdditionalInfoNumericalValue) param.getParameterAdditionalInfo();
LiteralInputType literal = input.addNewLiteralData();
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:double");
literal.setDataType(dataType);
input.setMinOccurs(BigInteger.valueOf(1));
input.setMaxOccurs(BigInteger.valueOf(1));
RangeType range = literal.addNewAllowedValues().addNewRange();
- range.addNewMaximumValue().setStringValue(Double.toString(ai.getMaxValue()));
- range.addNewMinimumValue().setStringValue(Double.toString(ai.getMinValue()));
+ range.addNewMaximumValue().setStringValue("+Infinity");
+ range.addNewMinimumValue().setStringValue("-Infinity");
literal.setDefaultValue(Double.toString(ai.getDefaultValue()));
}
else if (param instanceof ParameterString){
LiteralInputType literal = input.addNewLiteralData();
input.setMinOccurs(BigInteger.valueOf(1));
literal.addNewAnyValue();
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:string");
literal.setDataType(dataType);
}
else if (param instanceof ParameterMultipleInput){
AdditionalInfoMultipleInput ai = (AdditionalInfoMultipleInput) param.getParameterAdditionalInfo();
SupportedComplexDataInputType complex = input.addNewComplexData();
switch (ai.getDataType()){
case AdditionalInfoMultipleInput.DATA_TYPE_RASTER:
complex.addNewDefault().addNewFormat().setMimeType("image/tiff");
if (ai.getIsMandatory()){
input.setMinOccurs(BigInteger.valueOf(1));
}
else{
input.setMinOccurs(BigInteger.valueOf(0));
}
break;
case AdditionalInfoMultipleInput.DATA_TYPE_VECTOR_ANY:
case AdditionalInfoMultipleInput.DATA_TYPE_VECTOR_LINE:
case AdditionalInfoMultipleInput.DATA_TYPE_VECTOR_POINT:
case AdditionalInfoMultipleInput.DATA_TYPE_VECTOR_POLYGON:
//TODO:add shape type
ComplexDataDescriptionType format = complex.addNewDefault().addNewFormat();
format.setMimeType(IOHandler.DEFAULT_MIMETYPE);
format.setSchema("http://schemas.opengis.net/gml/2.1.2/feature.xsd");
ComplexDataDescriptionType supportedFormat1 = complex.addNewSupported().addNewFormat();
supportedFormat1.setEncoding(IOHandler.ENCODING_BASE64);
supportedFormat1.setMimeType(IOHandler.MIME_TYPE_ZIPPED_SHP);
ComplexDataDescriptionType supportedFormat2 = complex.addNewSupported().addNewFormat();
supportedFormat2.setMimeType(IOHandler.DEFAULT_MIMETYPE);
supportedFormat2.setSchema("http://geoserver.itc.nl:8080/wps/schemas/gml/2.1.2/gmlpacket.xsd");
if (ai.getIsMandatory()){
input.setMinOccurs(BigInteger.valueOf(1));
}
else{
input.setMinOccurs(BigInteger.valueOf(0));
}
break;
default:
throw new UnsupportedGeoAlgorithmException();
}
}
else if (param instanceof ParameterSelection){
AdditionalInfoSelection ai = (AdditionalInfoSelection) param.getParameterAdditionalInfo();
String[] values = ai.getValues();
LiteralInputType literal = input.addNewLiteralData();
input.setMinOccurs(BigInteger.valueOf(1));
input.setMaxOccurs(BigInteger.valueOf(1));
AllowedValues allowedValues = literal.addNewAllowedValues();
for (int i = 0; i < values.length; i++) {
allowedValues.addNewValue().setStringValue(values[i]);
}
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:string");
}
else if (param instanceof ParameterTableField ){
//This has to be improved, to add the information about the parent parameter
//the value is the zero-based index of the field
LiteralInputType literal = input.addNewLiteralData();
input.setMinOccurs(BigInteger.valueOf(1));
input.setMaxOccurs(BigInteger.valueOf(1));
RangeType range = literal.addNewAllowedValues().addNewRange();
range.addNewMinimumValue().setStringValue("0");
+ range.addNewMaximumValue().setStringValue("+Infinity");
literal.setDefaultValue("0");
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:int");
}
else if (param instanceof ParameterBand){
//This has to be improved, to add the information about the parent parameter
LiteralInputType literal = input.addNewLiteralData();
input.setMinOccurs(BigInteger.valueOf(1));
input.setMaxOccurs(BigInteger.valueOf(1));
RangeType range = literal.addNewAllowedValues().addNewRange();
range.addNewMinimumValue().setStringValue("0");
+ range.addNewMaximumValue().setStringValue("+Infinity");
literal.setDefaultValue("0");
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:int");
}
else if (param instanceof ParameterPoint){
//points are entered as x and y coordinates separated by a comma (any idea
//about how to better do this?)
LiteralInputType literal = input.addNewLiteralData();
input.setMinOccurs(BigInteger.valueOf(1));
input.setMaxOccurs(BigInteger.valueOf(1));
literal.setDefaultValue("0, 0");
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:string");
}
else if (param instanceof ParameterBoolean){
LiteralInputType literal = input.addNewLiteralData();
input.setMinOccurs(BigInteger.valueOf(1));
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:boolean");
literal.setDataType(dataType);
literal.addNewAnyValue();
input.setMinOccurs(BigInteger.valueOf(1));
input.setMaxOccurs(BigInteger.valueOf(1));
literal.setDefaultValue("false");
}
else if (param instanceof ParameterFixedTable){
//TODO:
throw new UnsupportedGeoAlgorithmException();
}
}
//This class is thrown when there is any problem creating the XML
//WPS file from a geoalgorithm, due to some yet unsupported feature
//or parameter
public class UnsupportedGeoAlgorithmException extends Exception{
}
public static void main(String[] args){
Sextante.initialize();
GeoAlgorithm algorithm = Sextante.getAlgorithmFromCommandLineName("buffer");
SextanteProcessDescriptionCreator geoAlgorithm = new SextanteProcessDescriptionCreator();
ProcessDescriptionType processDescription = null;
try {
processDescription = geoAlgorithm.createDescribeProcessType(algorithm);
System.out.println(processDescription);
} catch (NullParameterAdditionalInfoException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (UnsupportedGeoAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
| false | true |
private void addParameter(DataInputs inputs, Parameter param) throws NullParameterAdditionalInfoException,
UnsupportedGeoAlgorithmException {
InputDescriptionType input = inputs.addNewInput();
input.addNewAbstract().setStringValue(param.getParameterDescription());
input.addNewTitle().setStringValue(param.getParameterDescription());
input.addNewIdentifier().setStringValue(param.getParameterName());
if (param instanceof ParameterRasterLayer){
AdditionalInfoRasterLayer ai = (AdditionalInfoRasterLayer) param.getParameterAdditionalInfo();
SupportedComplexDataInputType complex = input.addNewComplexData();
ComplexDataCombinationsType supported = complex.addNewSupported();
ComplexDataDescriptionType format = supported.addNewFormat();
format.setMimeType("image/tiff");
format = supported.addNewFormat();
format.setMimeType("image/tiff");
format.setEncoding(IOHandler.ENCODING_BASE64);
ComplexDataDescriptionType defaultFormat = complex.addNewDefault().addNewFormat();
defaultFormat.setMimeType("image/tiff");
if (ai.getIsMandatory()){
input.setMinOccurs(BigInteger.valueOf(1));
}
else{
input.setMinOccurs(BigInteger.valueOf(0));
}
input.setMaxOccurs(BigInteger.valueOf(1));
}
if (param instanceof ParameterVectorLayer){
//TODO:add shape type
AdditionalInfoVectorLayer ai = (AdditionalInfoVectorLayer) param.getParameterAdditionalInfo();
SupportedComplexDataInputType complex = input.addNewComplexData();
ComplexDataCombinationsType supported = complex.addNewSupported();
ComplexDataDescriptionType format = supported.addNewFormat();
format.setMimeType(IOHandler.DEFAULT_MIMETYPE);
format.setSchema("http://schemas.opengis.net/gml/2.1.2/feature.xsd");
format = supported.addNewFormat();
format.setEncoding(IOHandler.ENCODING_BASE64);
format.setMimeType(IOHandler.MIME_TYPE_ZIPPED_SHP);
ComplexDataDescriptionType defaultFormat = complex.addNewDefault().addNewFormat();
defaultFormat.setMimeType(IOHandler.DEFAULT_MIMETYPE);
defaultFormat.setSchema("http://geoserver.itc.nl:8080/wps/schemas/gml/2.1.2/gmlpacket.xsd");
if (ai.getIsMandatory()){
input.setMinOccurs(BigInteger.valueOf(1));
}
else{
input.setMinOccurs(BigInteger.valueOf(0));
}
input.setMaxOccurs(BigInteger.valueOf(1));
}
else if (param instanceof ParameterNumericalValue){
AdditionalInfoNumericalValue ai = (AdditionalInfoNumericalValue) param.getParameterAdditionalInfo();
LiteralInputType literal = input.addNewLiteralData();
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:double");
literal.setDataType(dataType);
input.setMinOccurs(BigInteger.valueOf(1));
input.setMaxOccurs(BigInteger.valueOf(1));
RangeType range = literal.addNewAllowedValues().addNewRange();
range.addNewMaximumValue().setStringValue(Double.toString(ai.getMaxValue()));
range.addNewMinimumValue().setStringValue(Double.toString(ai.getMinValue()));
literal.setDefaultValue(Double.toString(ai.getDefaultValue()));
}
else if (param instanceof ParameterString){
LiteralInputType literal = input.addNewLiteralData();
input.setMinOccurs(BigInteger.valueOf(1));
literal.addNewAnyValue();
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:string");
literal.setDataType(dataType);
}
else if (param instanceof ParameterMultipleInput){
AdditionalInfoMultipleInput ai = (AdditionalInfoMultipleInput) param.getParameterAdditionalInfo();
SupportedComplexDataInputType complex = input.addNewComplexData();
switch (ai.getDataType()){
case AdditionalInfoMultipleInput.DATA_TYPE_RASTER:
complex.addNewDefault().addNewFormat().setMimeType("image/tiff");
if (ai.getIsMandatory()){
input.setMinOccurs(BigInteger.valueOf(1));
}
else{
input.setMinOccurs(BigInteger.valueOf(0));
}
break;
case AdditionalInfoMultipleInput.DATA_TYPE_VECTOR_ANY:
case AdditionalInfoMultipleInput.DATA_TYPE_VECTOR_LINE:
case AdditionalInfoMultipleInput.DATA_TYPE_VECTOR_POINT:
case AdditionalInfoMultipleInput.DATA_TYPE_VECTOR_POLYGON:
//TODO:add shape type
ComplexDataDescriptionType format = complex.addNewDefault().addNewFormat();
format.setMimeType(IOHandler.DEFAULT_MIMETYPE);
format.setSchema("http://schemas.opengis.net/gml/2.1.2/feature.xsd");
ComplexDataDescriptionType supportedFormat1 = complex.addNewSupported().addNewFormat();
supportedFormat1.setEncoding(IOHandler.ENCODING_BASE64);
supportedFormat1.setMimeType(IOHandler.MIME_TYPE_ZIPPED_SHP);
ComplexDataDescriptionType supportedFormat2 = complex.addNewSupported().addNewFormat();
supportedFormat2.setMimeType(IOHandler.DEFAULT_MIMETYPE);
supportedFormat2.setSchema("http://geoserver.itc.nl:8080/wps/schemas/gml/2.1.2/gmlpacket.xsd");
if (ai.getIsMandatory()){
input.setMinOccurs(BigInteger.valueOf(1));
}
else{
input.setMinOccurs(BigInteger.valueOf(0));
}
break;
default:
throw new UnsupportedGeoAlgorithmException();
}
}
else if (param instanceof ParameterSelection){
AdditionalInfoSelection ai = (AdditionalInfoSelection) param.getParameterAdditionalInfo();
String[] values = ai.getValues();
LiteralInputType literal = input.addNewLiteralData();
input.setMinOccurs(BigInteger.valueOf(1));
input.setMaxOccurs(BigInteger.valueOf(1));
AllowedValues allowedValues = literal.addNewAllowedValues();
for (int i = 0; i < values.length; i++) {
allowedValues.addNewValue().setStringValue(values[i]);
}
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:string");
}
else if (param instanceof ParameterTableField ){
//This has to be improved, to add the information about the parent parameter
//the value is the zero-based index of the field
LiteralInputType literal = input.addNewLiteralData();
input.setMinOccurs(BigInteger.valueOf(1));
input.setMaxOccurs(BigInteger.valueOf(1));
RangeType range = literal.addNewAllowedValues().addNewRange();
range.addNewMinimumValue().setStringValue("0");
literal.setDefaultValue("0");
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:int");
}
else if (param instanceof ParameterBand){
//This has to be improved, to add the information about the parent parameter
LiteralInputType literal = input.addNewLiteralData();
input.setMinOccurs(BigInteger.valueOf(1));
input.setMaxOccurs(BigInteger.valueOf(1));
RangeType range = literal.addNewAllowedValues().addNewRange();
range.addNewMinimumValue().setStringValue("0");
literal.setDefaultValue("0");
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:int");
}
else if (param instanceof ParameterPoint){
//points are entered as x and y coordinates separated by a comma (any idea
//about how to better do this?)
LiteralInputType literal = input.addNewLiteralData();
input.setMinOccurs(BigInteger.valueOf(1));
input.setMaxOccurs(BigInteger.valueOf(1));
literal.setDefaultValue("0, 0");
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:string");
}
else if (param instanceof ParameterBoolean){
LiteralInputType literal = input.addNewLiteralData();
input.setMinOccurs(BigInteger.valueOf(1));
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:boolean");
literal.setDataType(dataType);
literal.addNewAnyValue();
input.setMinOccurs(BigInteger.valueOf(1));
input.setMaxOccurs(BigInteger.valueOf(1));
literal.setDefaultValue("false");
}
else if (param instanceof ParameterFixedTable){
//TODO:
throw new UnsupportedGeoAlgorithmException();
}
}
|
private void addParameter(DataInputs inputs, Parameter param) throws NullParameterAdditionalInfoException,
UnsupportedGeoAlgorithmException {
InputDescriptionType input = inputs.addNewInput();
input.addNewAbstract().setStringValue(param.getParameterDescription());
input.addNewTitle().setStringValue(param.getParameterDescription());
input.addNewIdentifier().setStringValue(param.getParameterName());
if (param instanceof ParameterRasterLayer){
AdditionalInfoRasterLayer ai = (AdditionalInfoRasterLayer) param.getParameterAdditionalInfo();
SupportedComplexDataInputType complex = input.addNewComplexData();
ComplexDataCombinationsType supported = complex.addNewSupported();
ComplexDataDescriptionType format = supported.addNewFormat();
format.setMimeType("image/tiff");
format = supported.addNewFormat();
format.setMimeType("image/tiff");
format.setEncoding(IOHandler.ENCODING_BASE64);
ComplexDataDescriptionType defaultFormat = complex.addNewDefault().addNewFormat();
defaultFormat.setMimeType("image/tiff");
if (ai.getIsMandatory()){
input.setMinOccurs(BigInteger.valueOf(1));
}
else{
input.setMinOccurs(BigInteger.valueOf(0));
}
input.setMaxOccurs(BigInteger.valueOf(1));
}
if (param instanceof ParameterVectorLayer){
//TODO:add shape type
AdditionalInfoVectorLayer ai = (AdditionalInfoVectorLayer) param.getParameterAdditionalInfo();
SupportedComplexDataInputType complex = input.addNewComplexData();
ComplexDataCombinationsType supported = complex.addNewSupported();
ComplexDataDescriptionType format = supported.addNewFormat();
format.setMimeType(IOHandler.DEFAULT_MIMETYPE);
format.setSchema("http://schemas.opengis.net/gml/2.1.2/feature.xsd");
format = supported.addNewFormat();
format.setEncoding(IOHandler.ENCODING_BASE64);
format.setMimeType(IOHandler.MIME_TYPE_ZIPPED_SHP);
ComplexDataDescriptionType defaultFormat = complex.addNewDefault().addNewFormat();
defaultFormat.setMimeType(IOHandler.DEFAULT_MIMETYPE);
defaultFormat.setSchema("http://geoserver.itc.nl:8080/wps/schemas/gml/2.1.2/gmlpacket.xsd");
if (ai.getIsMandatory()){
input.setMinOccurs(BigInteger.valueOf(1));
}
else{
input.setMinOccurs(BigInteger.valueOf(0));
}
input.setMaxOccurs(BigInteger.valueOf(1));
}
else if (param instanceof ParameterNumericalValue){
AdditionalInfoNumericalValue ai = (AdditionalInfoNumericalValue) param.getParameterAdditionalInfo();
LiteralInputType literal = input.addNewLiteralData();
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:double");
literal.setDataType(dataType);
input.setMinOccurs(BigInteger.valueOf(1));
input.setMaxOccurs(BigInteger.valueOf(1));
RangeType range = literal.addNewAllowedValues().addNewRange();
range.addNewMaximumValue().setStringValue("+Infinity");
range.addNewMinimumValue().setStringValue("-Infinity");
literal.setDefaultValue(Double.toString(ai.getDefaultValue()));
}
else if (param instanceof ParameterString){
LiteralInputType literal = input.addNewLiteralData();
input.setMinOccurs(BigInteger.valueOf(1));
literal.addNewAnyValue();
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:string");
literal.setDataType(dataType);
}
else if (param instanceof ParameterMultipleInput){
AdditionalInfoMultipleInput ai = (AdditionalInfoMultipleInput) param.getParameterAdditionalInfo();
SupportedComplexDataInputType complex = input.addNewComplexData();
switch (ai.getDataType()){
case AdditionalInfoMultipleInput.DATA_TYPE_RASTER:
complex.addNewDefault().addNewFormat().setMimeType("image/tiff");
if (ai.getIsMandatory()){
input.setMinOccurs(BigInteger.valueOf(1));
}
else{
input.setMinOccurs(BigInteger.valueOf(0));
}
break;
case AdditionalInfoMultipleInput.DATA_TYPE_VECTOR_ANY:
case AdditionalInfoMultipleInput.DATA_TYPE_VECTOR_LINE:
case AdditionalInfoMultipleInput.DATA_TYPE_VECTOR_POINT:
case AdditionalInfoMultipleInput.DATA_TYPE_VECTOR_POLYGON:
//TODO:add shape type
ComplexDataDescriptionType format = complex.addNewDefault().addNewFormat();
format.setMimeType(IOHandler.DEFAULT_MIMETYPE);
format.setSchema("http://schemas.opengis.net/gml/2.1.2/feature.xsd");
ComplexDataDescriptionType supportedFormat1 = complex.addNewSupported().addNewFormat();
supportedFormat1.setEncoding(IOHandler.ENCODING_BASE64);
supportedFormat1.setMimeType(IOHandler.MIME_TYPE_ZIPPED_SHP);
ComplexDataDescriptionType supportedFormat2 = complex.addNewSupported().addNewFormat();
supportedFormat2.setMimeType(IOHandler.DEFAULT_MIMETYPE);
supportedFormat2.setSchema("http://geoserver.itc.nl:8080/wps/schemas/gml/2.1.2/gmlpacket.xsd");
if (ai.getIsMandatory()){
input.setMinOccurs(BigInteger.valueOf(1));
}
else{
input.setMinOccurs(BigInteger.valueOf(0));
}
break;
default:
throw new UnsupportedGeoAlgorithmException();
}
}
else if (param instanceof ParameterSelection){
AdditionalInfoSelection ai = (AdditionalInfoSelection) param.getParameterAdditionalInfo();
String[] values = ai.getValues();
LiteralInputType literal = input.addNewLiteralData();
input.setMinOccurs(BigInteger.valueOf(1));
input.setMaxOccurs(BigInteger.valueOf(1));
AllowedValues allowedValues = literal.addNewAllowedValues();
for (int i = 0; i < values.length; i++) {
allowedValues.addNewValue().setStringValue(values[i]);
}
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:string");
}
else if (param instanceof ParameterTableField ){
//This has to be improved, to add the information about the parent parameter
//the value is the zero-based index of the field
LiteralInputType literal = input.addNewLiteralData();
input.setMinOccurs(BigInteger.valueOf(1));
input.setMaxOccurs(BigInteger.valueOf(1));
RangeType range = literal.addNewAllowedValues().addNewRange();
range.addNewMinimumValue().setStringValue("0");
range.addNewMaximumValue().setStringValue("+Infinity");
literal.setDefaultValue("0");
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:int");
}
else if (param instanceof ParameterBand){
//This has to be improved, to add the information about the parent parameter
LiteralInputType literal = input.addNewLiteralData();
input.setMinOccurs(BigInteger.valueOf(1));
input.setMaxOccurs(BigInteger.valueOf(1));
RangeType range = literal.addNewAllowedValues().addNewRange();
range.addNewMinimumValue().setStringValue("0");
range.addNewMaximumValue().setStringValue("+Infinity");
literal.setDefaultValue("0");
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:int");
}
else if (param instanceof ParameterPoint){
//points are entered as x and y coordinates separated by a comma (any idea
//about how to better do this?)
LiteralInputType literal = input.addNewLiteralData();
input.setMinOccurs(BigInteger.valueOf(1));
input.setMaxOccurs(BigInteger.valueOf(1));
literal.setDefaultValue("0, 0");
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:string");
}
else if (param instanceof ParameterBoolean){
LiteralInputType literal = input.addNewLiteralData();
input.setMinOccurs(BigInteger.valueOf(1));
DomainMetadataType dataType = literal.addNewDataType();
dataType.setReference("xs:boolean");
literal.setDataType(dataType);
literal.addNewAnyValue();
input.setMinOccurs(BigInteger.valueOf(1));
input.setMaxOccurs(BigInteger.valueOf(1));
literal.setDefaultValue("false");
}
else if (param instanceof ParameterFixedTable){
//TODO:
throw new UnsupportedGeoAlgorithmException();
}
}
|
diff --git a/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/main/java/org/xwiki/rendering/internal/transformation/macro/MacroTransformation.java b/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/main/java/org/xwiki/rendering/internal/transformation/macro/MacroTransformation.java
index f7fccfb75..cea777b2c 100644
--- a/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/main/java/org/xwiki/rendering/internal/transformation/macro/MacroTransformation.java
+++ b/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/main/java/org/xwiki/rendering/internal/transformation/macro/MacroTransformation.java
@@ -1,269 +1,273 @@
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.rendering.internal.transformation.macro;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.slf4j.Logger;
import org.xwiki.component.annotation.Component;
import org.xwiki.properties.BeanManager;
import org.xwiki.rendering.block.Block;
import org.xwiki.rendering.block.MacroBlock;
import org.xwiki.rendering.block.MacroMarkerBlock;
import org.xwiki.rendering.block.match.ClassBlockMatcher;
import org.xwiki.rendering.macro.Macro;
import org.xwiki.rendering.macro.MacroId;
import org.xwiki.rendering.macro.MacroLookupException;
import org.xwiki.rendering.macro.MacroManager;
import org.xwiki.rendering.macro.MacroNotFoundException;
import org.xwiki.rendering.transformation.MacroTransformationContext;
import org.xwiki.rendering.syntax.Syntax;
import org.xwiki.rendering.transformation.AbstractTransformation;
import org.xwiki.rendering.transformation.TransformationContext;
import org.xwiki.rendering.transformation.TransformationException;
/**
* Look for all {@link org.xwiki.rendering.block.MacroBlock} blocks in the passed {@link Block} and iteratively execute
* each Macro in the correct order. Macros can:
* <ul>
* <li>provide a hint specifying when they should run (priority)</li>
* <li>generate other Macros</li>
* </ul>
*
* @version $Id$
* @since 1.5M2
*/
@Component
@Named("macro")
@Singleton
public class MacroTransformation extends AbstractTransformation
{
/**
* Number of times a macro can generate another macro before considering that we are in a loop.
* Such a loop can happen if a macro generates itself for example.
*/
private int maxRecursions = 1000;
/**
* Handles macro registration and macro lookups. Injected by the Component Manager.
*/
@Inject
private MacroManager macroManager;
/**
* Used to populate automatically macros parameters classes with parameters specified in the Macro Block.
*/
@Inject
private BeanManager beanManager;
/**
* The logger to log.
*/
@Inject
private Logger logger;
/**
* Used to generate Macro error blocks when a Macro fails to execute.
*/
private MacroErrorManager macroErrorManager = new MacroErrorManager();
private class MacroHolder implements Comparable<MacroHolder>
{
Macro< ? > macro;
MacroBlock macroBlock;
public MacroHolder(Macro< ? > macro, MacroBlock macroBlock)
{
this.macro = macro;
this.macroBlock = macroBlock;
}
@Override
public int compareTo(MacroHolder holder)
{
return this.macro.compareTo(holder.macro);
}
}
@Override
public int getPriority()
{
// Make it one of the transformations that's executed first so that other transformations run on the executed
// macros.
return 100;
}
@Override
public void transform(Block rootBlock, TransformationContext context) throws TransformationException
{
// Create a macro execution context with all the information required for macros.
MacroTransformationContext macroContext = new MacroTransformationContext(context);
macroContext.setTransformation(this);
// Counter to prevent infinite recursion if a macro generates the same macro for example.
int recursions = 0;
List<MacroBlock> macroBlocks =
rootBlock.getBlocks(new ClassBlockMatcher(MacroBlock.class), Block.Axes.DESCENDANT);
while (!macroBlocks.isEmpty() && recursions < this.maxRecursions) {
if (transformOnce(rootBlock, macroContext, context.getSyntax())) {
recursions++;
}
// TODO: Make this less inefficient by caching the blocks list.
macroBlocks = rootBlock.getBlocks(new ClassBlockMatcher(MacroBlock.class), Block.Axes.DESCENDANT);
}
}
private boolean transformOnce(Block rootBlock, MacroTransformationContext context, Syntax syntax)
{
// 1) Get highest priority macro to execute
MacroHolder macroHolder = getHighestPriorityMacro(rootBlock, syntax);
if (macroHolder == null) {
return false;
}
boolean result = macroHolder.macroBlock.getParent() instanceof MacroMarkerBlock;
List<Block> newBlocks;
try {
// 2) Verify if we're in macro inline mode and if the macro supports it. If not, send an error.
if (macroHolder.macroBlock.isInline()) {
context.setInline(true);
if (!macroHolder.macro.supportsInlineMode()) {
// The macro doesn't support inline mode, raise a warning but continue.
// The macro will not be executed and we generate an error message instead of the macro
// execution result.
- this.macroErrorManager.generateError(macroHolder.macroBlock, "Not an inline macro",
- "This macro can only be used by itself on a new line");
+ this.macroErrorManager.generateError(macroHolder.macroBlock,
+ "This is a standalone macro only and it cannot be used inline",
+ "This macro generates standalone content. As a consequence you need to make sure to use a "
+ + "syntax that separates your macro from the content before and after it so that it's on a "
+ + "line by itself. For example in XWiki Syntax 2.0+ this means having 2 newline characters "
+ + "(a.k.a line breaks) separating your macro from the content before and after it.");
this.logger.debug("The [{}] macro doesn't support inline mode.", macroHolder.macroBlock.getId());
return false;
}
} else {
context.setInline(false);
}
// 3) Execute the highest priority macro
context.setCurrentMacroBlock(macroHolder.macroBlock);
// Populate and validate macro parameters.
Object macroParameters = macroHolder.macro.getDescriptor().getParametersBeanClass().newInstance();
try {
this.beanManager.populate(macroParameters, macroHolder.macroBlock.getParameters());
} catch (Throwable e) {
// One macro parameter was invalid.
// The macro will not be executed and we generate an error message instead of the macro
// execution result.
this.macroErrorManager.generateError(macroHolder.macroBlock, String.format(
"Invalid macro parameters used for the \"%s\" macro", macroHolder.macroBlock.getId()), e);
this.logger.debug("Invalid macro parameter for the [{}] macro. Internal error: [{}]",
macroHolder.macroBlock.getId(), e.getMessage());
return false;
}
newBlocks = ((Macro<Object>) macroHolder.macro).execute(
macroParameters, macroHolder.macroBlock.getContent(), context);
} catch (Throwable e) {
// The Macro failed to execute.
// The macro will not be executed and we generate an error message instead of the macro
// execution result.
// Note: We catch any Exception because we want to never break the whole rendering.
this.macroErrorManager.generateError(macroHolder.macroBlock,
String.format("Failed to execute the [%s] macro", macroHolder.macroBlock.getId()), e);
this.logger.debug("Failed to execute the [{}] macro. Internal error [{}]", macroHolder.macroBlock.getId(),
e.getMessage());
return false;
}
// We wrap the blocks generated by the macro execution with MacroMarker blocks so that listeners/renderers
// who wish to know the group of blocks that makes up the executed macro can. For example this is useful for
// the XWiki Syntax renderer so that it can reconstruct the macros from the transformed XDOM.
Block resultBlock = wrapInMacroMarker(macroHolder.macroBlock, newBlocks);
// 4) Replace the MacroBlock by the Blocks generated by the execution of the Macro
macroHolder.macroBlock.getParent().replaceChild(resultBlock, macroHolder.macroBlock);
return result;
}
/**
* @return the macro with the highest priority for the passed syntax or null if no macro is found
*/
private MacroHolder getHighestPriorityMacro(Block rootBlock, Syntax syntax)
{
List<MacroHolder> macroHolders = new ArrayList<MacroHolder>();
// 1) Sort the macros by priority to find the highest priority macro to execute
List<MacroBlock> macroBlocks =
rootBlock.getBlocks(new ClassBlockMatcher(MacroBlock.class), Block.Axes.DESCENDANT);
for (MacroBlock macroBlock : macroBlocks) {
try {
Macro< ? > macro = this.macroManager.getMacro(new MacroId(macroBlock.getId(), syntax));
macroHolders.add(new MacroHolder(macro, macroBlock));
} catch (MacroNotFoundException e) {
// Macro cannot be found. Generate an error message instead of the macro execution result.
// TODO: make it internationalized
this.macroErrorManager.generateError(macroBlock,
String.format("Unknown macro: %s", macroBlock.getId()),
String.format(
"The \"%s\" macro is not in the list of registered macros. Verify the spelling or "
+ "contact your administrator.", macroBlock.getId()));
this.logger.debug("Failed to locate the [{}] macro. Ignoring it.", macroBlock.getId());
} catch (MacroLookupException e) {
// TODO: make it internationalized
this.macroErrorManager.generateError(macroBlock,
String.format("Invalid macro: %s", macroBlock.getId()), e);
this.logger.debug("Failed to instantiate the [{}] macro. Ignoring it.", macroBlock.getId());
}
}
// Sort the Macros by priority
Collections.sort(macroHolders);
return macroHolders.size() > 0 ? macroHolders.get(0) : null;
}
/**
* Wrap the output of a macro block with a {@link MacroMarkerBlock}.
*
* @param macroBlockToWrap the block that should be replaced
* @param newBlocks list of blocks to wrap
* @return the wrapper
*/
private Block wrapInMacroMarker(MacroBlock macroBlockToWrap, List<Block> newBlocks)
{
return new MacroMarkerBlock(macroBlockToWrap.getId(), macroBlockToWrap.getParameters(), macroBlockToWrap
.getContent(), newBlocks, macroBlockToWrap.isInline());
}
/**
* @param maxRecursions the max numnber of recursion allowed before we stop transformations
*/
public void setMaxRecursions(int maxRecursions)
{
this.maxRecursions = maxRecursions;
}
}
| true | true |
private boolean transformOnce(Block rootBlock, MacroTransformationContext context, Syntax syntax)
{
// 1) Get highest priority macro to execute
MacroHolder macroHolder = getHighestPriorityMacro(rootBlock, syntax);
if (macroHolder == null) {
return false;
}
boolean result = macroHolder.macroBlock.getParent() instanceof MacroMarkerBlock;
List<Block> newBlocks;
try {
// 2) Verify if we're in macro inline mode and if the macro supports it. If not, send an error.
if (macroHolder.macroBlock.isInline()) {
context.setInline(true);
if (!macroHolder.macro.supportsInlineMode()) {
// The macro doesn't support inline mode, raise a warning but continue.
// The macro will not be executed and we generate an error message instead of the macro
// execution result.
this.macroErrorManager.generateError(macroHolder.macroBlock, "Not an inline macro",
"This macro can only be used by itself on a new line");
this.logger.debug("The [{}] macro doesn't support inline mode.", macroHolder.macroBlock.getId());
return false;
}
} else {
context.setInline(false);
}
// 3) Execute the highest priority macro
context.setCurrentMacroBlock(macroHolder.macroBlock);
// Populate and validate macro parameters.
Object macroParameters = macroHolder.macro.getDescriptor().getParametersBeanClass().newInstance();
try {
this.beanManager.populate(macroParameters, macroHolder.macroBlock.getParameters());
} catch (Throwable e) {
// One macro parameter was invalid.
// The macro will not be executed and we generate an error message instead of the macro
// execution result.
this.macroErrorManager.generateError(macroHolder.macroBlock, String.format(
"Invalid macro parameters used for the \"%s\" macro", macroHolder.macroBlock.getId()), e);
this.logger.debug("Invalid macro parameter for the [{}] macro. Internal error: [{}]",
macroHolder.macroBlock.getId(), e.getMessage());
return false;
}
newBlocks = ((Macro<Object>) macroHolder.macro).execute(
macroParameters, macroHolder.macroBlock.getContent(), context);
} catch (Throwable e) {
// The Macro failed to execute.
// The macro will not be executed and we generate an error message instead of the macro
// execution result.
// Note: We catch any Exception because we want to never break the whole rendering.
this.macroErrorManager.generateError(macroHolder.macroBlock,
String.format("Failed to execute the [%s] macro", macroHolder.macroBlock.getId()), e);
this.logger.debug("Failed to execute the [{}] macro. Internal error [{}]", macroHolder.macroBlock.getId(),
e.getMessage());
return false;
}
// We wrap the blocks generated by the macro execution with MacroMarker blocks so that listeners/renderers
// who wish to know the group of blocks that makes up the executed macro can. For example this is useful for
// the XWiki Syntax renderer so that it can reconstruct the macros from the transformed XDOM.
Block resultBlock = wrapInMacroMarker(macroHolder.macroBlock, newBlocks);
// 4) Replace the MacroBlock by the Blocks generated by the execution of the Macro
macroHolder.macroBlock.getParent().replaceChild(resultBlock, macroHolder.macroBlock);
return result;
}
|
private boolean transformOnce(Block rootBlock, MacroTransformationContext context, Syntax syntax)
{
// 1) Get highest priority macro to execute
MacroHolder macroHolder = getHighestPriorityMacro(rootBlock, syntax);
if (macroHolder == null) {
return false;
}
boolean result = macroHolder.macroBlock.getParent() instanceof MacroMarkerBlock;
List<Block> newBlocks;
try {
// 2) Verify if we're in macro inline mode and if the macro supports it. If not, send an error.
if (macroHolder.macroBlock.isInline()) {
context.setInline(true);
if (!macroHolder.macro.supportsInlineMode()) {
// The macro doesn't support inline mode, raise a warning but continue.
// The macro will not be executed and we generate an error message instead of the macro
// execution result.
this.macroErrorManager.generateError(macroHolder.macroBlock,
"This is a standalone macro only and it cannot be used inline",
"This macro generates standalone content. As a consequence you need to make sure to use a "
+ "syntax that separates your macro from the content before and after it so that it's on a "
+ "line by itself. For example in XWiki Syntax 2.0+ this means having 2 newline characters "
+ "(a.k.a line breaks) separating your macro from the content before and after it.");
this.logger.debug("The [{}] macro doesn't support inline mode.", macroHolder.macroBlock.getId());
return false;
}
} else {
context.setInline(false);
}
// 3) Execute the highest priority macro
context.setCurrentMacroBlock(macroHolder.macroBlock);
// Populate and validate macro parameters.
Object macroParameters = macroHolder.macro.getDescriptor().getParametersBeanClass().newInstance();
try {
this.beanManager.populate(macroParameters, macroHolder.macroBlock.getParameters());
} catch (Throwable e) {
// One macro parameter was invalid.
// The macro will not be executed and we generate an error message instead of the macro
// execution result.
this.macroErrorManager.generateError(macroHolder.macroBlock, String.format(
"Invalid macro parameters used for the \"%s\" macro", macroHolder.macroBlock.getId()), e);
this.logger.debug("Invalid macro parameter for the [{}] macro. Internal error: [{}]",
macroHolder.macroBlock.getId(), e.getMessage());
return false;
}
newBlocks = ((Macro<Object>) macroHolder.macro).execute(
macroParameters, macroHolder.macroBlock.getContent(), context);
} catch (Throwable e) {
// The Macro failed to execute.
// The macro will not be executed and we generate an error message instead of the macro
// execution result.
// Note: We catch any Exception because we want to never break the whole rendering.
this.macroErrorManager.generateError(macroHolder.macroBlock,
String.format("Failed to execute the [%s] macro", macroHolder.macroBlock.getId()), e);
this.logger.debug("Failed to execute the [{}] macro. Internal error [{}]", macroHolder.macroBlock.getId(),
e.getMessage());
return false;
}
// We wrap the blocks generated by the macro execution with MacroMarker blocks so that listeners/renderers
// who wish to know the group of blocks that makes up the executed macro can. For example this is useful for
// the XWiki Syntax renderer so that it can reconstruct the macros from the transformed XDOM.
Block resultBlock = wrapInMacroMarker(macroHolder.macroBlock, newBlocks);
// 4) Replace the MacroBlock by the Blocks generated by the execution of the Macro
macroHolder.macroBlock.getParent().replaceChild(resultBlock, macroHolder.macroBlock);
return result;
}
|
diff --git a/src/VASSAL/build/module/map/SetupStack.java b/src/VASSAL/build/module/map/SetupStack.java
index 77cf65e9..92513262 100644
--- a/src/VASSAL/build/module/map/SetupStack.java
+++ b/src/VASSAL/build/module/map/SetupStack.java
@@ -1,1166 +1,1168 @@
/*
* $Id$
*
* Copyright (c) 2004 by Rodney Kinney
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, copies are available
* at http://www.opensource.org.
*/
package VASSAL.build.module.map;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.datatransfer.StringSelection;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DragSourceMotionListener;
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.dnd.InvalidDnDOperationException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import VASSAL.build.AbstractConfigurable;
import VASSAL.build.AutoConfigurable;
import VASSAL.build.BadDataReport;
import VASSAL.build.Buildable;
import VASSAL.build.Configurable;
import VASSAL.build.GameModule;
import VASSAL.build.module.GameComponent;
import VASSAL.build.module.Map;
import VASSAL.build.module.NewGameIndicator;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.build.module.map.boardPicker.Board;
import VASSAL.build.module.map.boardPicker.board.MapGrid;
import VASSAL.build.module.map.boardPicker.board.MapGrid.BadCoords;
import VASSAL.build.widget.PieceSlot;
import VASSAL.command.Command;
import VASSAL.configure.AutoConfigurer;
import VASSAL.configure.Configurer;
import VASSAL.configure.StringEnum;
import VASSAL.configure.ValidationReport;
import VASSAL.configure.VisibilityCondition;
import VASSAL.counters.GamePiece;
import VASSAL.counters.PieceCloner;
import VASSAL.counters.Properties;
import VASSAL.counters.Stack;
import VASSAL.i18n.Resources;
import VASSAL.tools.AdjustableSpeedScrollPane;
import VASSAL.tools.ErrorDialog;
import VASSAL.tools.UniqueIdManager;
import VASSAL.tools.image.ImageUtils;
import VASSAL.tools.menu.MenuManager;
/**
* This is the "At-Start Stack" component, which initializes a Map or Board with a specified stack.
* Because it uses a regular stack, this component is better suited for limited-force-pool collections
* of counters than a {@link DrawPile}
*
*/
public class SetupStack extends AbstractConfigurable implements GameComponent, UniqueIdManager.Identifyable {
private static UniqueIdManager idMgr = new UniqueIdManager("SetupStack");
public static final String COMMAND_PREFIX = "SETUP_STACK\t";
protected Point pos = new Point();
public static final String OWNING_BOARD = "owningBoard";
public final static String X_POSITION = "x";
public final static String Y_POSITION = "y";
protected Map map;
protected String owningBoardName;
protected String id;
public static final String NAME = "name";
protected static NewGameIndicator indicator;
protected StackConfigurer stackConfigurer;
protected JButton configureButton;
protected String location;
protected boolean useGridLocation;
public static final String LOCATION = "location";
public static final String USE_GRID_LOCATION = "useGridLocation";
@Override
public VisibilityCondition getAttributeVisibility(String name) {
if (USE_GRID_LOCATION.equals(name)) {
return new VisibilityCondition() {
public boolean shouldBeVisible() {
Board b = getConfigureBoard();
if (b == null)
return false;
else
return b.getGrid() != null;
}
};
}
else if (LOCATION.equals(name)) {
return new VisibilityCondition() {
public boolean shouldBeVisible() {
return isUseGridLocation();
}
};
}
else if (X_POSITION.equals(name) || Y_POSITION.equals(name)) {
return new VisibilityCondition() {
public boolean shouldBeVisible() {
return !isUseGridLocation();
}
};
}
else
return super.getAttributeVisibility(name);
}
// must have a useable board with a grid
protected boolean isUseGridLocation() {
if (!useGridLocation)
return false;
Board b = getConfigureBoard();
if (b == null)
return false;
MapGrid g = b.getGrid();
if (g == null)
return false;
else
return true;
}
// only update the position if we're using the location name
protected void updatePosition() {
if (isUseGridLocation() && location != null && !location.equals("")) {
try {
pos = getConfigureBoard().getGrid().getLocation(location);
}
catch (BadCoords e) {
ErrorDialog.dataError(new BadDataReport("Invalid board location",location,e));
}
}
}
@Override
public void validate(Buildable target, ValidationReport report) {
if (isUseGridLocation()) {
if (location == null)
report.addWarning(getConfigureName() + Resources.getString("SetupStack.null_location"));
else {
try {
getConfigureBoard().getGrid().getLocation(location);
}
catch (BadCoords e) {
String msg = "Bad location name "+location+" in "+getConfigureName();
if (e.getMessage() != null) {
msg += ": "+e.getMessage();
}
report.addWarning(msg);
}
}
}
super.validate(target, report);
}
protected void updateLocation() {
Board b = getConfigureBoard();
if (b != null) {
MapGrid g = b.getGrid();
if (g != null)
location = g.locationName(pos);
}
}
public void setup(boolean gameStarting) {
if (gameStarting && indicator.isNewGame() && isOwningBoardActive()) {
Stack s = initializeContents();
updatePosition();
Point p = new Point(pos);
if (owningBoardName != null) {
Rectangle r = map.getBoardByName(owningBoardName).bounds();
p.translate(r.x, r.y);
}
if (placeNonStackingSeparately()) {
for (int i=0;i<s.getPieceCount();++i) {
GamePiece piece = s.getPieceAt(i);
if (Boolean.TRUE.equals(piece.getProperty(Properties.NO_STACK))) {
s.remove(piece);
map.placeAt(piece,p);
i--;
}
}
}
map.placeAt(s, p);
}
}
protected boolean placeNonStackingSeparately() {
return true;
}
public Command getRestoreCommand() {
return null;
}
public String[] getAttributeDescriptions() {
return new String[]{
"Name: ",
"Belongs to Board: ",
"Use Grid Location: ",
"Location: ",
"X position: ",
"Y position: "
};
}
public Class<?>[] getAttributeTypes() {
return new Class<?>[]{
String.class,
OwningBoardPrompt.class,
Boolean.class,
String.class,
Integer.class,
Integer.class
};
}
public String[] getAttributeNames() {
return new String[]{
NAME,
OWNING_BOARD,
USE_GRID_LOCATION,
LOCATION,
X_POSITION,
Y_POSITION
};
}
public String getAttributeValueString(String key) {
if (NAME.equals(key)) {
return getConfigureName();
}
else if (OWNING_BOARD.equals(key)) {
return owningBoardName;
}
else if (USE_GRID_LOCATION.equals(key)) {
return Boolean.toString(useGridLocation);
}
else if (LOCATION.equals(key)) {
return location;
}
else if (X_POSITION.equals(key)) {
return String.valueOf(pos.x);
}
else if (Y_POSITION.equals(key)) {
return String.valueOf(pos.y);
}
else {
return null;
}
}
public void setAttribute(String key, Object value) {
if (NAME.equals(key)) {
setConfigureName((String) value);
}
else if (OWNING_BOARD.equals(key)) {
if (OwningBoardPrompt.ANY.equals(value)) {
owningBoardName = null;
}
else {
owningBoardName = (String) value;
}
updateConfigureButton();
}
else if (USE_GRID_LOCATION.equals(key)) {
if (value instanceof String) {
value = new Boolean((String) value);
}
useGridLocation = ((Boolean) value).booleanValue();
}
else if (LOCATION.equals(key)) {
location = (String) value;
}
else if (X_POSITION.equals(key)) {
if (value instanceof String) {
value = new Integer((String) value);
}
pos.x = ((Integer) value).intValue();
}
else if (Y_POSITION.equals(key)) {
if (value instanceof String) {
value = new Integer((String) value);
}
pos.y = ((Integer) value).intValue();
}
}
public void add(Buildable child) {
super.add(child);
updateConfigureButton();
}
public void addTo(Buildable parent) {
if (indicator == null) {
indicator = new NewGameIndicator(COMMAND_PREFIX);
}
map = (Map) parent;
idMgr.add(this);
GameModule.getGameModule().getGameState().addGameComponent(this);
setAttributeTranslatable(NAME, false);
}
public Class<?>[] getAllowableConfigureComponents() {
return new Class<?>[]{PieceSlot.class};
}
public HelpFile getHelpFile() {
return HelpFile.getReferenceManualPage("SetupStack.htm");
}
public static String getConfigureTypeName() {
return "At-Start Stack";
}
public void removeFrom(Buildable parent) {
idMgr.remove(this);
GameModule.getGameModule().getGameState().removeGameComponent(this);
}
protected boolean isOwningBoardActive() {
boolean active = false;
if (owningBoardName == null) {
active = true;
}
else if (map.getBoardByName(owningBoardName) != null) {
active = true;
}
return active;
}
protected Stack initializeContents() {
Stack s = createStack();
Configurable[] c = getConfigureComponents();
for (int i = 0; i < c.length; ++i) {
if (c[i] instanceof PieceSlot) {
PieceSlot slot = (PieceSlot) c[i];
GamePiece p = slot.getPiece();
p = PieceCloner.getInstance().clonePiece(p);
GameModule.getGameModule().getGameState().addPiece(p);
s.add(p);
}
}
GameModule.getGameModule().getGameState().addPiece(s);
return s;
}
protected Stack createStack() {
Stack s = new Stack();
return s;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
// public static class GridPrompt extends StringEnum {
// public static final String NONE = "<none>";
// public static final String ZONE = "(Zone)";
// public static final String BOARD = "(Board)";
//
// public GridPrompt() {
// }
//
// @Override
// public String[] getValidValues(AutoConfigurable target) {
// ArrayList<String> values = new ArrayList<String>();
// values.add(NONE);
// if (target instanceof SetupStack) {
// SetupStack stack = (SetupStack) target;
// BoardPicker bp = stack.map.getBoardPicker();
// if (stack.owningBoardName != null) {
// Board b = bp.getBoard(stack.owningBoardName);
// MapGrid grid = b.getGrid();
// if (grid != null) {
// GridNumbering gn = grid.getGridNumbering();
// if (gn != null)
// values.add(BOARD + " " + b.getName());
// if (grid instanceof ZonedGrid) {
// ZonedGrid zg = (ZonedGrid) grid;
// for (Iterator i = zg.getZones(); i.hasNext(); ) {
// Zone z = (Zone) i.next();
// if (!z.isUseParentGrid() && z.getGrid() != null && z.getGrid().getGridNumbering() != null)
// values.add(ZONE + " " + z.getName());
// }
// }
// }
// }
// }
// return values.toArray(new String[values.size()]);
// }
// }
//
public static class OwningBoardPrompt extends StringEnum {
public static final String ANY = "<any>";
public OwningBoardPrompt() {
}
public String[] getValidValues(AutoConfigurable target) {
String[] values;
if (target instanceof SetupStack) {
ArrayList<String> l = new ArrayList<String>();
l.add(ANY);
Map m = ((SetupStack) target).map;
if (m != null) {
l.addAll(Arrays.asList(m.getBoardPicker().getAllowableBoardNames()));
}
else {
for (Map m2 : Map.getMapList()) {
l.addAll(
Arrays.asList(m2.getBoardPicker().getAllowableBoardNames()));
}
}
values = l.toArray(new String[l.size()]);
}
else {
values = new String[]{ANY};
}
return values;
}
}
/*
* GUI Stack Placement Configurer
*/
protected Configurer xConfig, yConfig, locationConfig;
public Configurer getConfigurer() {
config = null; // Don't cache the Configurer so that the list of available boards won't go stale
Configurer c = super.getConfigurer();
xConfig = ((AutoConfigurer) c).getConfigurer(X_POSITION);
yConfig = ((AutoConfigurer) c).getConfigurer(Y_POSITION);
locationConfig = ((AutoConfigurer) c).getConfigurer(LOCATION);
updateConfigureButton();
((Container) c.getControls()).add(configureButton);
return c;
}
protected void updateConfigureButton() {
if (configureButton == null) {
configureButton = new JButton("Reposition Stack");
configureButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
configureStack();
}
});
}
configureButton.setEnabled(getConfigureBoard() != null && buildComponents.size() > 0);
}
protected void configureStack() {
stackConfigurer = new StackConfigurer(this);
stackConfigurer.init();
stackConfigurer.setVisible(true);
}
protected PieceSlot getTopPiece() {
Iterator<PieceSlot> i =
getAllDescendantComponentsOf(PieceSlot.class).iterator();
return i.hasNext() ? i.next() : null;
}
/*
* Return a board to configure the stack on.
*/
protected Board getConfigureBoard() {
Board board = null;
if (map != null && !OwningBoardPrompt.ANY.equals(owningBoardName)) {
board = map.getBoardPicker().getBoard(owningBoardName);
}
if (board == null && map != null) {
String[] allBoards = map.getBoardPicker().getAllowableBoardNames();
if (allBoards.length > 0) {
board = map.getBoardPicker().getBoard(allBoards[0]);
}
}
return board;
}
protected static final Dimension DEFAULT_SIZE = new Dimension(800, 600);
protected static final int DELTA = 1;
protected static final int FAST = 10;
protected static final int FASTER = 5;
protected static final int DEFAULT_DUMMY_SIZE = 50;
public class StackConfigurer extends JFrame implements ActionListener, KeyListener, MouseListener {
private static final long serialVersionUID = 1L;
protected Board board;
protected View view;
protected JScrollPane scroll;
protected SetupStack myStack;
protected PieceSlot mySlot;
protected GamePiece myPiece;
protected Point savePosition;
protected Dimension dummySize;
protected BufferedImage dummyImage;
public StackConfigurer(SetupStack stack) {
super("Adjust At-Start Stack");
setJMenuBar(MenuManager.getInstance().getMenuBarFor(this));
myStack = stack;
mySlot = stack.getTopPiece();
if (mySlot != null) {
myPiece = mySlot.getPiece();
}
myStack.updatePosition();
savePosition = new Point(myStack.pos);
if (stack instanceof DrawPile) {
dummySize = new Dimension(((DrawPile) stack).getSize());
}
else {
dummySize = new Dimension(DEFAULT_DUMMY_SIZE, DEFAULT_DUMMY_SIZE);
}
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
cancel();
}
});
}
// Main Entry Point
protected void init() {
board = getConfigureBoard();
view = new View(board, myStack);
view.addKeyListener(this);
view.addMouseListener(this);
view.setFocusable(true);
scroll =
new AdjustableSpeedScrollPane(
view,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll.setPreferredSize(DEFAULT_SIZE);
add(scroll, BorderLayout.CENTER);
Box textPanel = Box.createVerticalBox();
textPanel.add(new JLabel("Arrow Keys - Move Stack"));
textPanel.add(new JLabel("Ctrl/Shift Keys - Move Stack Faster "));
Box displayPanel = Box.createHorizontalBox();
Box buttonPanel = Box.createHorizontalBox();
JButton snapButton = new JButton("Snap to grid");
snapButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
snap();
view.grabFocus();
}
});
buttonPanel.add(snapButton);
JButton okButton = new JButton("Ok");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
StackConfigurer.this.setVisible(false);
// Update the Component configurer to reflect the change
xConfig.setValue(String.valueOf(myStack.pos.x));
yConfig.setValue(String.valueOf(myStack.pos.y));
- updateLocation();
- locationConfig.setValue(location);
+ if (locationConfig != null) { // DrawPile's do not have a location
+ updateLocation();
+ locationConfig.setValue(location);
+ }
}
});
JPanel okPanel = new JPanel();
okPanel.add(okButton);
JButton canButton = new JButton("Cancel");
canButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancel();
StackConfigurer.this.setVisible(false);
}
});
okPanel.add(canButton);
Box controlPanel = Box.createHorizontalBox();
controlPanel.add(textPanel);
controlPanel.add(displayPanel);
controlPanel.add(buttonPanel);
Box mainPanel = Box.createVerticalBox();
mainPanel.add(controlPanel);
mainPanel.add(okPanel);
add(mainPanel, BorderLayout.SOUTH);
scroll.revalidate();
updateDisplay();
pack();
repaint();
}
protected void cancel() {
myStack.pos.x = savePosition.x;
myStack.pos.y = savePosition.y;
}
public void updateDisplay() {
if (!view.getVisibleRect().contains(myStack.pos)) {
view.center(new Point(myStack.pos.x, myStack.pos.y));
}
}
protected void snap() {
MapGrid grid = board.getGrid();
if (grid != null) {
Point snapTo = grid.snapTo(pos);
pos.x = snapTo.x;
pos.y = snapTo.y;
updateDisplay();
repaint();
}
}
public JScrollPane getScroll() {
return scroll;
}
/*
* If the piece to be displayed does not have an Image, then we
* need to supply a dummy one.
*/
public BufferedImage getDummyImage() {
if (dummyImage == null) {
dummyImage = ImageUtils.createCompatibleTranslucentImage(
dummySize.width*2, dummySize.height*2);
final Graphics2D g = dummyImage.createGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, dummySize.width, dummySize.height);
g.setColor(Color.black);
g.drawRect(0, 0, dummySize.width, dummySize.height);
g.dispose();
}
return dummyImage;
}
public void drawDummyImage(Graphics g, int x, int y) {
drawDummyImage(g, x-dummySize.width/2, y-dummySize.height/2, null, 1.0);
}
public void drawDummyImage(Graphics g, int x, int y, Component obs, double zoom) {
g.drawImage(getDummyImage(), x, y, obs);
}
public void drawImage(Graphics g, int x, int y, Component obs, double zoom) {
Rectangle r = myPiece == null ? null : myPiece.boundingBox();
if (r == null || r.width == 0 || r.height == 0) {
drawDummyImage(g, x, y);
}
else {
myPiece.draw(g, x, y, obs, zoom);
}
}
public Rectangle getPieceBoundingBox() {
Rectangle r = myPiece == null ? new Rectangle() : myPiece.getShape().getBounds();
if (r == null || r.width == 0 || r.height == 0) {
r.x = 0 - dummySize.width/2;
r.y = 0 - dummySize.height/2;
r.width = dummySize.width;
r.height = dummySize.height;
}
return r;
}
public void actionPerformed(ActionEvent e) {
}
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
adjustY(-1, e);
break;
case KeyEvent.VK_DOWN:
adjustY(1, e);
break;
case KeyEvent.VK_LEFT:
adjustX(-1, e);
break;
case KeyEvent.VK_RIGHT:
adjustX(1, e);
break;
default :
if (myPiece != null) {
myPiece.keyEvent(KeyStroke.getKeyStrokeForEvent(e));
}
break;
}
updateDisplay();
repaint();
e.consume();
}
protected void adjustX(int direction, KeyEvent e) {
int delta = direction * DELTA;
if (e.isShiftDown()) {
delta *= FAST;
}
if (e.isControlDown()) {
delta *= FASTER;
}
int newX = myStack.pos.x + delta;
if (newX < 0) newX = 0;
if (newX >= board.getSize().getWidth()) newX = (int) board.getSize().getWidth() - 1;
myStack.pos.x = newX;
}
protected void adjustY(int direction, KeyEvent e) {
int delta = direction * DELTA;
if (e.isShiftDown()) {
delta *= FAST;
}
if (e.isControlDown()) {
delta *= FASTER;
}
int newY = myStack.pos.y + delta;
if (newY < 0) newY = 0;
if (newY >= board.getSize().getHeight()) newY = (int) board.getSize().getHeight() - 1;
myStack.pos.y = newY;
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
Rectangle r = getPieceBoundingBox();
r.translate(pos.x, pos.y);
if (myPiece != null && e.isMetaDown() && r.contains(e.getPoint())) {
JPopupMenu popup = MenuDisplayer.createPopup(myPiece);
popup.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
view.repaint();
}
public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
view.repaint();
}
public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
}
});
popup.show(view, e.getX(), e.getY());
}
}
public void mouseReleased(MouseEvent e) {
}
}
// FIXME: check for duplication with PieceMover
public static class View extends JPanel implements DropTargetListener, DragGestureListener, DragSourceListener, DragSourceMotionListener {
private static final long serialVersionUID = 1L;
final int CURSOR_ALPHA = 127;
final int EXTRA_BORDER = 4;
protected Board myBoard;
protected MapGrid myGrid;
protected SetupStack myStack;
protected GamePiece myPiece;
protected PieceSlot slot;
protected DragSource ds = DragSource.getDefaultDragSource();
protected boolean isDragging = false;
protected JLabel dragCursor;
protected JLayeredPane drawWin;
protected Point drawOffset = new Point();
protected Rectangle boundingBox;
protected int currentPieceOffsetX;
protected int currentPieceOffsetY;
protected int originalPieceOffsetX;
protected int originalPieceOffsetY;
protected Point lastDragLocation = new Point();
public View(Board b, SetupStack s) {
myBoard = b;
myGrid = b.getGrid();
myStack = s;
slot = myStack.getTopPiece();
if (slot != null) {
myPiece = slot.getPiece();
}
new DropTarget(this, DnDConstants.ACTION_MOVE, this);
ds.createDefaultDragGestureRecognizer(this,
DnDConstants.ACTION_MOVE, this);
setFocusTraversalKeysEnabled(false);
}
public void paint(Graphics g) {
myBoard.draw(g, 0, 0, 1.0, this);
Rectangle bounds = new Rectangle(new Point(),myBoard.bounds().getSize());
if (myGrid != null) {
myGrid.draw(g,bounds,bounds,1.0,false);
}
int x = myStack.pos.x;
int y = myStack.pos.y;
myStack.stackConfigurer.drawImage(g, x, y, this, 1.0);
}
public void update(Graphics g) {
// To avoid flicker, don't clear the display first *
paint(g);
}
public Dimension getPreferredSize() {
return new Dimension(
myBoard.bounds().width,
myBoard.bounds().height);
}
public void center(Point p) {
Rectangle r = this.getVisibleRect();
if (r.width == 0) {
r.width = DEFAULT_SIZE.width;
r.height = DEFAULT_SIZE.height;
}
int x = p.x-r.width/2;
int y = p.y-r.height/2;
if (x < 0) x = 0;
if (y < 0) y = 0;
scrollRectToVisible(new Rectangle(x, y, r.width, r.height));
}
public void dragEnter(DropTargetDragEvent arg0) {
return;
}
public void dragOver(DropTargetDragEvent e) {
scrollAtEdge(e.getLocation(), 15);
}
public void scrollAtEdge(Point evtPt, int dist) {
JScrollPane scroll = myStack.stackConfigurer.getScroll();
Point p = new Point(evtPt.x - scroll.getViewport().getViewPosition().x,
evtPt.y - scroll.getViewport().getViewPosition().y);
int dx = 0, dy = 0;
if (p.x < dist && p.x >= 0)
dx = -1;
if (p.x >= scroll.getViewport().getSize().width - dist
&& p.x < scroll.getViewport().getSize().width)
dx = 1;
if (p.y < dist && p.y >= 0)
dy = -1;
if (p.y >= scroll.getViewport().getSize().height - dist
&& p.y < scroll.getViewport().getSize().height)
dy = 1;
if (dx != 0 || dy != 0) {
Rectangle r = new Rectangle(scroll.getViewport().getViewRect());
r.translate(2 * dist * dx, 2 * dist * dy);
r = r.intersection(new Rectangle(new Point(0, 0), getPreferredSize()));
scrollRectToVisible(r);
}
}
public void dropActionChanged(DropTargetDragEvent arg0) {
return;
}
public void drop(DropTargetDropEvent event) {
removeDragCursor();
Point pos = event.getLocation();
pos.translate(currentPieceOffsetX, currentPieceOffsetY);
myStack.pos.x = pos.x;
myStack.pos.y = pos.y;
myStack.stackConfigurer.updateDisplay();
repaint();
return;
}
public void dragExit(DropTargetEvent arg0) {
return;
}
public void dragEnter(DragSourceDragEvent arg0) {
return;
}
public void dragOver(DragSourceDragEvent arg0) {
return;
}
public void dropActionChanged(DragSourceDragEvent arg0) {
return;
}
public void dragDropEnd(DragSourceDropEvent arg0) {
removeDragCursor();
return;
}
public void dragExit(DragSourceEvent arg0) {
return;
}
public void dragGestureRecognized(DragGestureEvent dge) {
Point mousePosition = dge.getDragOrigin();
Point piecePosition = new Point(myStack.pos);
// Check drag starts inside piece
Rectangle r = myStack.stackConfigurer.getPieceBoundingBox();
r.translate(piecePosition.x, piecePosition.y);
if (!r.contains(mousePosition)) {
return;
}
originalPieceOffsetX = piecePosition.x - mousePosition.x;
originalPieceOffsetY = piecePosition.y - mousePosition.y;
drawWin = null;
makeDragCursor();
setDragCursor();
SwingUtilities.convertPointToScreen(mousePosition, drawWin);
moveDragCursor(mousePosition.x, mousePosition.y);
// begin dragging
try {
dge.startDrag(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR),
new StringSelection(""), this); // DEBUG
dge.getDragSource().addDragSourceMotionListener(this);
}
catch (InvalidDnDOperationException e) {
ErrorDialog.bug(e);
}
}
protected void setDragCursor() {
JRootPane rootWin = SwingUtilities.getRootPane(this);
if (rootWin != null) {
// remove cursor from old window
if (dragCursor.getParent() != null) {
dragCursor.getParent().remove(dragCursor);
}
drawWin = rootWin.getLayeredPane();
calcDrawOffset();
dragCursor.setVisible(true);
drawWin.add(dragCursor, JLayeredPane.DRAG_LAYER);
}
}
/** Moves the drag cursor on the current draw window */
protected void moveDragCursor(int dragX, int dragY) {
if (drawWin != null) {
dragCursor.setLocation(dragX - drawOffset.x, dragY - drawOffset.y);
}
}
private void removeDragCursor() {
if (drawWin != null) {
if (dragCursor != null) {
dragCursor.setVisible(false);
drawWin.remove(dragCursor);
}
drawWin = null;
}
}
/** calculates the offset between cursor dragCursor positions */
private void calcDrawOffset() {
if (drawWin != null) {
// drawOffset is the offset between the mouse location during a drag
// and the upper-left corner of the cursor
// accounts for difference betwen event point (screen coords)
// and Layered Pane position, boundingBox and off-center drag
drawOffset.x = -boundingBox.x - currentPieceOffsetX + EXTRA_BORDER;
drawOffset.y = -boundingBox.y - currentPieceOffsetY + EXTRA_BORDER;
SwingUtilities.convertPointToScreen(drawOffset, drawWin);
}
}
private void makeDragCursor() {
//double zoom = 1.0;
// create the cursor if necessary
if (dragCursor == null) {
dragCursor = new JLabel();
dragCursor.setVisible(false);
}
//dragCursorZoom = zoom;
currentPieceOffsetX = originalPieceOffsetX;
currentPieceOffsetY = originalPieceOffsetY;
// Record sizing info and resize our cursor
boundingBox = myStack.stackConfigurer.getPieceBoundingBox();
calcDrawOffset();
int width = boundingBox.width + EXTRA_BORDER * 2;
int height = boundingBox.height + EXTRA_BORDER * 2;
final BufferedImage cursorImage =
ImageUtils.createCompatibleTranslucentImage(width, height);
final Graphics2D graphics = cursorImage.createGraphics();
myStack.stackConfigurer.drawImage(graphics, EXTRA_BORDER - boundingBox.x, EXTRA_BORDER - boundingBox.y, dragCursor, 1.0);
dragCursor.setSize(width, height);
// FIXME: this code is duplicated from PieceMover
// FIXME: this unmanages the image!
// Make bitmap 50% transparent
WritableRaster alphaRaster = cursorImage.getAlphaRaster();
int size = width * height;
int[] alphaArray = new int[size];
alphaArray = alphaRaster.getPixels(0, 0, width, height, alphaArray);
for (int i = 0; i < size; ++i) {
if (alphaArray[i] == 255)
alphaArray[i] = CURSOR_ALPHA;
}
// ... feather the cursor, since traits can extend arbitraily far out from
// bounds
final int FEATHER_WIDTH = EXTRA_BORDER;
for (int f = 0; f < FEATHER_WIDTH; ++f) {
int alpha = CURSOR_ALPHA * (f + 1) / FEATHER_WIDTH;
int limRow = (f + 1) * width - f; // for horizontal runs
for (int i = f * (width + 1); i < limRow; ++i) {
if (alphaArray[i] > 0) // North
alphaArray[i] = alpha;
if (alphaArray[size - i - 1] > 0) // South
alphaArray[size - i - 1] = alpha;
}
int limVert = size - (f + 1) * width; // for vertical runs
for (int i = (f + 1) * width + f; i < limVert; i += width) {
if (alphaArray[i] > 0) // West
alphaArray[i] = alpha;
if (alphaArray[size - i - 1] > 0) // East
alphaArray[size - i - 1] = alpha;
}
}
// ... apply the alpha to the image
alphaRaster.setPixels(0, 0, width, height, alphaArray);
// store the bitmap in the cursor
dragCursor.setIcon(new ImageIcon(cursorImage));
}
public void dragMouseMoved(DragSourceDragEvent event) {
if (!event.getLocation().equals(lastDragLocation)) {
lastDragLocation = event.getLocation();
moveDragCursor(event.getX(), event.getY());
if (dragCursor != null && !dragCursor.isVisible()) {
dragCursor.setVisible(true);
}
}
}
}
}
| true | true |
protected void init() {
board = getConfigureBoard();
view = new View(board, myStack);
view.addKeyListener(this);
view.addMouseListener(this);
view.setFocusable(true);
scroll =
new AdjustableSpeedScrollPane(
view,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll.setPreferredSize(DEFAULT_SIZE);
add(scroll, BorderLayout.CENTER);
Box textPanel = Box.createVerticalBox();
textPanel.add(new JLabel("Arrow Keys - Move Stack"));
textPanel.add(new JLabel("Ctrl/Shift Keys - Move Stack Faster "));
Box displayPanel = Box.createHorizontalBox();
Box buttonPanel = Box.createHorizontalBox();
JButton snapButton = new JButton("Snap to grid");
snapButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
snap();
view.grabFocus();
}
});
buttonPanel.add(snapButton);
JButton okButton = new JButton("Ok");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
StackConfigurer.this.setVisible(false);
// Update the Component configurer to reflect the change
xConfig.setValue(String.valueOf(myStack.pos.x));
yConfig.setValue(String.valueOf(myStack.pos.y));
updateLocation();
locationConfig.setValue(location);
}
});
JPanel okPanel = new JPanel();
okPanel.add(okButton);
JButton canButton = new JButton("Cancel");
canButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancel();
StackConfigurer.this.setVisible(false);
}
});
okPanel.add(canButton);
Box controlPanel = Box.createHorizontalBox();
controlPanel.add(textPanel);
controlPanel.add(displayPanel);
controlPanel.add(buttonPanel);
Box mainPanel = Box.createVerticalBox();
mainPanel.add(controlPanel);
mainPanel.add(okPanel);
add(mainPanel, BorderLayout.SOUTH);
scroll.revalidate();
updateDisplay();
pack();
repaint();
}
|
protected void init() {
board = getConfigureBoard();
view = new View(board, myStack);
view.addKeyListener(this);
view.addMouseListener(this);
view.setFocusable(true);
scroll =
new AdjustableSpeedScrollPane(
view,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll.setPreferredSize(DEFAULT_SIZE);
add(scroll, BorderLayout.CENTER);
Box textPanel = Box.createVerticalBox();
textPanel.add(new JLabel("Arrow Keys - Move Stack"));
textPanel.add(new JLabel("Ctrl/Shift Keys - Move Stack Faster "));
Box displayPanel = Box.createHorizontalBox();
Box buttonPanel = Box.createHorizontalBox();
JButton snapButton = new JButton("Snap to grid");
snapButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
snap();
view.grabFocus();
}
});
buttonPanel.add(snapButton);
JButton okButton = new JButton("Ok");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
StackConfigurer.this.setVisible(false);
// Update the Component configurer to reflect the change
xConfig.setValue(String.valueOf(myStack.pos.x));
yConfig.setValue(String.valueOf(myStack.pos.y));
if (locationConfig != null) { // DrawPile's do not have a location
updateLocation();
locationConfig.setValue(location);
}
}
});
JPanel okPanel = new JPanel();
okPanel.add(okButton);
JButton canButton = new JButton("Cancel");
canButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancel();
StackConfigurer.this.setVisible(false);
}
});
okPanel.add(canButton);
Box controlPanel = Box.createHorizontalBox();
controlPanel.add(textPanel);
controlPanel.add(displayPanel);
controlPanel.add(buttonPanel);
Box mainPanel = Box.createVerticalBox();
mainPanel.add(controlPanel);
mainPanel.add(okPanel);
add(mainPanel, BorderLayout.SOUTH);
scroll.revalidate();
updateDisplay();
pack();
repaint();
}
|
diff --git a/exchange2/src/com/android/exchange/provider/ExchangeDirectoryProvider.java b/exchange2/src/com/android/exchange/provider/ExchangeDirectoryProvider.java
index 6d725ff4..5843c463 100644
--- a/exchange2/src/com/android/exchange/provider/ExchangeDirectoryProvider.java
+++ b/exchange2/src/com/android/exchange/provider/ExchangeDirectoryProvider.java
@@ -1,441 +1,441 @@
/*
* 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.exchange.provider;
import com.android.emailcommon.Configuration;
import com.android.emailcommon.mail.PackedString;
import com.android.emailcommon.provider.Account;
import com.android.emailcommon.provider.EmailContent;
import com.android.emailcommon.provider.EmailContent.AccountColumns;
import com.android.emailcommon.service.AccountServiceProxy;
import com.android.emailcommon.utility.Utility;
import com.android.exchange.Eas;
import com.android.exchange.EasSyncService;
import com.android.exchange.R;
import com.android.exchange.provider.GalResult.GalData;
import android.accounts.AccountManager;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Contacts.Data;
import android.provider.ContactsContract.Directory;
import android.provider.ContactsContract.RawContacts;
import android.text.TextUtils;
import java.util.HashMap;
import java.util.List;
/**
* ExchangeDirectoryProvider provides real-time data from the Exchange server; at the moment, it is
* used solely to provide GAL (Global Address Lookup) service to email address adapters
*/
public class ExchangeDirectoryProvider extends ContentProvider {
public static final String EXCHANGE_GAL_AUTHORITY = "com.android.exchange.directory.provider";
private static final int DEFAULT_CONTACT_ID = 1;
private static final int DEFAULT_LOOKUP_LIMIT = 20;
private static final int GAL_BASE = 0;
private static final int GAL_DIRECTORIES = GAL_BASE;
private static final int GAL_FILTER = GAL_BASE + 1;
private static final int GAL_CONTACT = GAL_BASE + 2;
private static final int GAL_CONTACT_WITH_ID = GAL_BASE + 3;
private static final int GAL_EMAIL_FILTER = GAL_BASE + 4;
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
/*package*/ final HashMap<String, Long> mAccountIdMap = new HashMap<String, Long>();
static {
sURIMatcher.addURI(EXCHANGE_GAL_AUTHORITY, "directories", GAL_DIRECTORIES);
sURIMatcher.addURI(EXCHANGE_GAL_AUTHORITY, "contacts/filter/*", GAL_FILTER);
sURIMatcher.addURI(EXCHANGE_GAL_AUTHORITY, "contacts/lookup/*/entities", GAL_CONTACT);
sURIMatcher.addURI(EXCHANGE_GAL_AUTHORITY, "contacts/lookup/*/#/entities",
GAL_CONTACT_WITH_ID);
sURIMatcher.addURI(EXCHANGE_GAL_AUTHORITY, "data/emails/filter/*", GAL_EMAIL_FILTER);
}
@Override
public boolean onCreate() {
return true;
}
static class GalProjection {
final int size;
final HashMap<String, Integer> columnMap = new HashMap<String, Integer>();
GalProjection(String[] projection) {
size = projection.length;
for (int i = 0; i < projection.length; i++) {
columnMap.put(projection[i], i);
}
}
}
static class GalContactRow {
private final GalProjection mProjection;
private Object[] row;
static long dataId = 1;
GalContactRow(GalProjection projection, long contactId, String lookupKey,
String accountName, String displayName) {
this.mProjection = projection;
row = new Object[projection.size];
put(Contacts.Entity.CONTACT_ID, contactId);
// We only have one raw contact per aggregate, so they can have the same ID
put(Contacts.Entity.RAW_CONTACT_ID, contactId);
put(Contacts.Entity.DATA_ID, dataId++);
put(Contacts.DISPLAY_NAME, displayName);
// TODO alternative display name
put(Contacts.DISPLAY_NAME_ALTERNATIVE, displayName);
put(RawContacts.ACCOUNT_TYPE, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE);
put(RawContacts.ACCOUNT_NAME, accountName);
put(RawContacts.RAW_CONTACT_IS_READ_ONLY, 1);
put(Data.IS_READ_ONLY, 1);
}
Object[] getRow () {
return row;
}
void put(String columnName, Object value) {
Integer integer = mProjection.columnMap.get(columnName);
if (integer != null) {
row[integer] = value;
} else {
System.out.println("Unsupported column: " + columnName);
}
}
static void addEmailAddress(MatrixCursor cursor, GalProjection galProjection,
long contactId, String lookupKey, String accountName, String displayName,
String address) {
if (!TextUtils.isEmpty(address)) {
GalContactRow r = new GalContactRow(
galProjection, contactId, lookupKey, accountName, displayName);
r.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);
r.put(Email.TYPE, Email.TYPE_WORK);
r.put(Email.ADDRESS, address);
cursor.addRow(r.getRow());
}
}
static void addPhoneRow(MatrixCursor cursor, GalProjection projection, long contactId,
String lookupKey, String accountName, String displayName, int type, String number) {
if (!TextUtils.isEmpty(number)) {
GalContactRow r = new GalContactRow(
projection, contactId, lookupKey, accountName, displayName);
r.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
r.put(Phone.TYPE, type);
r.put(Phone.NUMBER, number);
cursor.addRow(r.getRow());
}
}
public static void addNameRow(MatrixCursor cursor, GalProjection galProjection,
long contactId, String lookupKey, String accountName, String displayName,
String firstName, String lastName) {
GalContactRow r = new GalContactRow(
galProjection, contactId, lookupKey, accountName, displayName);
r.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
r.put(StructuredName.GIVEN_NAME, firstName);
r.put(StructuredName.FAMILY_NAME, lastName);
r.put(StructuredName.DISPLAY_NAME, displayName);
cursor.addRow(r.getRow());
}
}
/**
* Find the record id of an Account, given its name (email address)
* @param accountName the name of the account
* @return the record id of the Account, or -1 if not found
*/
/*package*/ long getAccountIdByName(Context context, String accountName) {
Long accountId = mAccountIdMap.get(accountName);
if (accountId == null) {
accountId = Utility.getFirstRowLong(context, Account.CONTENT_URI,
EmailContent.ID_PROJECTION, AccountColumns.EMAIL_ADDRESS + "=?",
new String[] {accountName}, null, EmailContent.ID_PROJECTION_COLUMN , -1L);
if (accountId != -1) {
mAccountIdMap.put(accountName, accountId);
}
}
return accountId;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
int match = sURIMatcher.match(uri);
MatrixCursor cursor;
Object[] row;
PackedString ps;
String lookupKey;
switch (match) {
case GAL_DIRECTORIES: {
// Assuming that GAL can be used with all exchange accounts
android.accounts.Account[] accounts = AccountManager.get(getContext())
.getAccountsByType(Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE);
cursor = new MatrixCursor(projection);
if (accounts != null) {
for (android.accounts.Account account : accounts) {
row = new Object[projection.length];
for (int i = 0; i < projection.length; i++) {
String column = projection[i];
if (column.equals(Directory.ACCOUNT_NAME)) {
row[i] = account.name;
} else if (column.equals(Directory.ACCOUNT_TYPE)) {
row[i] = account.type;
} else if (column.equals(Directory.TYPE_RESOURCE_ID)) {
Bundle bundle = null;
String accountType = Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE;
bundle = new AccountServiceProxy(getContext())
.getConfigurationData(accountType);
// Default to the alternative name, erring on the conservative side
int exchangeName = R.string.exchange_name_alternate;
if (bundle != null && !bundle.getBoolean(
Configuration.EXCHANGE_CONFIGURATION_USE_ALTERNATE_STRINGS,
true)) {
exchangeName = R.string.exchange_name;
}
row[i] = exchangeName;
} else if (column.equals(Directory.DISPLAY_NAME)) {
// If the account name is an email address, extract
// the domain name and use it as the directory display name
final String accountName = account.name;
int atIndex = accountName.indexOf('@');
if (atIndex != -1 && atIndex < accountName.length() - 2) {
final char firstLetter = Character.toUpperCase(
accountName.charAt(atIndex + 1));
row[i] = firstLetter + accountName.substring(atIndex + 2);
} else {
row[i] = account.name;
}
} else if (column.equals(Directory.EXPORT_SUPPORT)) {
row[i] = Directory.EXPORT_SUPPORT_SAME_ACCOUNT_ONLY;
} else if (column.equals(Directory.SHORTCUT_SUPPORT)) {
row[i] = Directory.SHORTCUT_SUPPORT_NONE;
}
}
cursor.addRow(row);
}
}
return cursor;
}
case GAL_FILTER:
case GAL_EMAIL_FILTER: {
String filter = uri.getLastPathSegment();
// We should have at least two characters before doing a GAL search
if (filter == null || filter.length() < 2) {
return null;
}
String accountName = uri.getQueryParameter(RawContacts.ACCOUNT_NAME);
if (accountName == null) {
return null;
}
// Enforce a limit on the number of lookup responses
String limitString = uri.getQueryParameter(ContactsContract.LIMIT_PARAM_KEY);
int limit = DEFAULT_LOOKUP_LIMIT;
if (limitString != null) {
try {
limit = Integer.parseInt(limitString);
} catch (NumberFormatException e) {
limit = 0;
}
if (limit <= 0) {
throw new IllegalArgumentException("Limit not valid: " + limitString);
}
}
long callingId = Binder.clearCallingIdentity();
try {
// Find the account id to pass along to EasSyncService
long accountId = getAccountIdByName(getContext(), accountName);
if (accountId == -1) {
// The account was deleted?
return null;
}
// Get results from the Exchange account
GalResult galResult = EasSyncService.searchGal(getContext(), accountId,
filter, limit);
if (galResult != null) {
return buildGalResultCursor(projection, galResult);
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
break;
}
case GAL_CONTACT:
case GAL_CONTACT_WITH_ID: {
String accountName = uri.getQueryParameter(RawContacts.ACCOUNT_NAME);
if (accountName == null) {
return null;
}
GalProjection galProjection = new GalProjection(projection);
cursor = new MatrixCursor(projection);
// Handle the decomposition of the key into rows suitable for CP2
List<String> pathSegments = uri.getPathSegments();
lookupKey = pathSegments.get(2);
long contactId = (match == GAL_CONTACT_WITH_ID)
? Long.parseLong(pathSegments.get(3))
: DEFAULT_CONTACT_ID;
ps = new PackedString(lookupKey);
String displayName = ps.get(GalData.DISPLAY_NAME);
GalContactRow.addEmailAddress(cursor, galProjection, contactId, lookupKey,
accountName, displayName, ps.get(GalData.EMAIL_ADDRESS));
GalContactRow.addPhoneRow(cursor, galProjection, contactId, accountName,
displayName, displayName, Phone.TYPE_HOME, ps.get(GalData.HOME_PHONE));
GalContactRow.addPhoneRow(cursor, galProjection, contactId, accountName,
displayName, displayName, Phone.TYPE_WORK, ps.get(GalData.WORK_PHONE));
GalContactRow.addPhoneRow(cursor, galProjection, contactId, accountName,
displayName, displayName, Phone.TYPE_MOBILE, ps.get(GalData.MOBILE_PHONE));
- GalContactRow.addNameRow(cursor, galProjection, contactId, accountName, displayName,
- ps.get(GalData.FIRST_NAME), ps.get(GalData.LAST_NAME), displayName);
+ GalContactRow.addNameRow(cursor, galProjection, contactId, displayName, accountName,
+ displayName, ps.get(GalData.FIRST_NAME), ps.get(GalData.LAST_NAME));
return cursor;
}
}
return null;
}
/*package*/ Cursor buildGalResultCursor(String[] projection, GalResult galResult) {
int displayNameIndex = -1;
int alternateDisplayNameIndex = -1;;
int emailIndex = -1;
int idIndex = -1;
int lookupIndex = -1;
for (int i = 0; i < projection.length; i++) {
String column = projection[i];
if (Contacts.DISPLAY_NAME.equals(column) ||
Contacts.DISPLAY_NAME_PRIMARY.equals(column)) {
displayNameIndex = i;
} else if (Contacts.DISPLAY_NAME_ALTERNATIVE.equals(column)) {
alternateDisplayNameIndex = i;
} else if (CommonDataKinds.Email.ADDRESS.equals(column)) {
emailIndex = i;
} else if (Contacts._ID.equals(column)) {
idIndex = i;
} else if (Contacts.LOOKUP_KEY.equals(column)) {
lookupIndex = i;
}
}
Object[] row = new Object[projection.length];
/*
* ContactsProvider will ensure that every request has a non-null projection.
*/
MatrixCursor cursor = new MatrixCursor(projection);
int count = galResult.galData.size();
for (int i = 0; i < count; i++) {
GalData galDataRow = galResult.galData.get(i);
String firstName = galDataRow.get(GalData.FIRST_NAME);
String lastName = galDataRow.get(GalData.LAST_NAME);
String displayName = galDataRow.get(GalData.DISPLAY_NAME);
// If we don't have a display name, try to create one using first and last name
if (displayName == null) {
if (firstName != null && lastName != null) {
displayName = firstName + " " + lastName;
} else if (firstName != null) {
displayName = firstName;
} else if (lastName != null) {
displayName = lastName;
}
}
galDataRow.put(GalData.DISPLAY_NAME, displayName);
if (displayNameIndex != -1) {
row[displayNameIndex] = displayName;
}
if (alternateDisplayNameIndex != -1) {
// Try to create an alternate display name, using first and last name
// TODO: Check with Contacts team to make sure we're using this properly
if (firstName != null && lastName != null) {
row[alternateDisplayNameIndex] = lastName + " " + firstName;
} else {
row[alternateDisplayNameIndex] = displayName;
}
}
if (emailIndex != -1) {
row[emailIndex] = galDataRow.get(GalData.EMAIL_ADDRESS);
}
if (idIndex != -1) {
row[idIndex] = i + 1; // Let's be 1 based
}
if (lookupIndex != -1) {
// We use the packed string as our lookup key; it contains ALL of the gal data
// We do this because we are not able to provide a stable id to ContactsProvider
row[lookupIndex] = Uri.encode(galDataRow.toPackedString());
}
cursor.addRow(row);
}
return cursor;
}
@Override
public String getType(Uri uri) {
int match = sURIMatcher.match(uri);
switch (match) {
case GAL_FILTER:
return Contacts.CONTENT_ITEM_TYPE;
}
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException();
}
@Override
public Uri insert(Uri uri, ContentValues values) {
throw new UnsupportedOperationException();
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException();
}
}
| true | true |
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
int match = sURIMatcher.match(uri);
MatrixCursor cursor;
Object[] row;
PackedString ps;
String lookupKey;
switch (match) {
case GAL_DIRECTORIES: {
// Assuming that GAL can be used with all exchange accounts
android.accounts.Account[] accounts = AccountManager.get(getContext())
.getAccountsByType(Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE);
cursor = new MatrixCursor(projection);
if (accounts != null) {
for (android.accounts.Account account : accounts) {
row = new Object[projection.length];
for (int i = 0; i < projection.length; i++) {
String column = projection[i];
if (column.equals(Directory.ACCOUNT_NAME)) {
row[i] = account.name;
} else if (column.equals(Directory.ACCOUNT_TYPE)) {
row[i] = account.type;
} else if (column.equals(Directory.TYPE_RESOURCE_ID)) {
Bundle bundle = null;
String accountType = Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE;
bundle = new AccountServiceProxy(getContext())
.getConfigurationData(accountType);
// Default to the alternative name, erring on the conservative side
int exchangeName = R.string.exchange_name_alternate;
if (bundle != null && !bundle.getBoolean(
Configuration.EXCHANGE_CONFIGURATION_USE_ALTERNATE_STRINGS,
true)) {
exchangeName = R.string.exchange_name;
}
row[i] = exchangeName;
} else if (column.equals(Directory.DISPLAY_NAME)) {
// If the account name is an email address, extract
// the domain name and use it as the directory display name
final String accountName = account.name;
int atIndex = accountName.indexOf('@');
if (atIndex != -1 && atIndex < accountName.length() - 2) {
final char firstLetter = Character.toUpperCase(
accountName.charAt(atIndex + 1));
row[i] = firstLetter + accountName.substring(atIndex + 2);
} else {
row[i] = account.name;
}
} else if (column.equals(Directory.EXPORT_SUPPORT)) {
row[i] = Directory.EXPORT_SUPPORT_SAME_ACCOUNT_ONLY;
} else if (column.equals(Directory.SHORTCUT_SUPPORT)) {
row[i] = Directory.SHORTCUT_SUPPORT_NONE;
}
}
cursor.addRow(row);
}
}
return cursor;
}
case GAL_FILTER:
case GAL_EMAIL_FILTER: {
String filter = uri.getLastPathSegment();
// We should have at least two characters before doing a GAL search
if (filter == null || filter.length() < 2) {
return null;
}
String accountName = uri.getQueryParameter(RawContacts.ACCOUNT_NAME);
if (accountName == null) {
return null;
}
// Enforce a limit on the number of lookup responses
String limitString = uri.getQueryParameter(ContactsContract.LIMIT_PARAM_KEY);
int limit = DEFAULT_LOOKUP_LIMIT;
if (limitString != null) {
try {
limit = Integer.parseInt(limitString);
} catch (NumberFormatException e) {
limit = 0;
}
if (limit <= 0) {
throw new IllegalArgumentException("Limit not valid: " + limitString);
}
}
long callingId = Binder.clearCallingIdentity();
try {
// Find the account id to pass along to EasSyncService
long accountId = getAccountIdByName(getContext(), accountName);
if (accountId == -1) {
// The account was deleted?
return null;
}
// Get results from the Exchange account
GalResult galResult = EasSyncService.searchGal(getContext(), accountId,
filter, limit);
if (galResult != null) {
return buildGalResultCursor(projection, galResult);
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
break;
}
case GAL_CONTACT:
case GAL_CONTACT_WITH_ID: {
String accountName = uri.getQueryParameter(RawContacts.ACCOUNT_NAME);
if (accountName == null) {
return null;
}
GalProjection galProjection = new GalProjection(projection);
cursor = new MatrixCursor(projection);
// Handle the decomposition of the key into rows suitable for CP2
List<String> pathSegments = uri.getPathSegments();
lookupKey = pathSegments.get(2);
long contactId = (match == GAL_CONTACT_WITH_ID)
? Long.parseLong(pathSegments.get(3))
: DEFAULT_CONTACT_ID;
ps = new PackedString(lookupKey);
String displayName = ps.get(GalData.DISPLAY_NAME);
GalContactRow.addEmailAddress(cursor, galProjection, contactId, lookupKey,
accountName, displayName, ps.get(GalData.EMAIL_ADDRESS));
GalContactRow.addPhoneRow(cursor, galProjection, contactId, accountName,
displayName, displayName, Phone.TYPE_HOME, ps.get(GalData.HOME_PHONE));
GalContactRow.addPhoneRow(cursor, galProjection, contactId, accountName,
displayName, displayName, Phone.TYPE_WORK, ps.get(GalData.WORK_PHONE));
GalContactRow.addPhoneRow(cursor, galProjection, contactId, accountName,
displayName, displayName, Phone.TYPE_MOBILE, ps.get(GalData.MOBILE_PHONE));
GalContactRow.addNameRow(cursor, galProjection, contactId, accountName, displayName,
ps.get(GalData.FIRST_NAME), ps.get(GalData.LAST_NAME), displayName);
return cursor;
}
}
return null;
}
|
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
int match = sURIMatcher.match(uri);
MatrixCursor cursor;
Object[] row;
PackedString ps;
String lookupKey;
switch (match) {
case GAL_DIRECTORIES: {
// Assuming that GAL can be used with all exchange accounts
android.accounts.Account[] accounts = AccountManager.get(getContext())
.getAccountsByType(Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE);
cursor = new MatrixCursor(projection);
if (accounts != null) {
for (android.accounts.Account account : accounts) {
row = new Object[projection.length];
for (int i = 0; i < projection.length; i++) {
String column = projection[i];
if (column.equals(Directory.ACCOUNT_NAME)) {
row[i] = account.name;
} else if (column.equals(Directory.ACCOUNT_TYPE)) {
row[i] = account.type;
} else if (column.equals(Directory.TYPE_RESOURCE_ID)) {
Bundle bundle = null;
String accountType = Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE;
bundle = new AccountServiceProxy(getContext())
.getConfigurationData(accountType);
// Default to the alternative name, erring on the conservative side
int exchangeName = R.string.exchange_name_alternate;
if (bundle != null && !bundle.getBoolean(
Configuration.EXCHANGE_CONFIGURATION_USE_ALTERNATE_STRINGS,
true)) {
exchangeName = R.string.exchange_name;
}
row[i] = exchangeName;
} else if (column.equals(Directory.DISPLAY_NAME)) {
// If the account name is an email address, extract
// the domain name and use it as the directory display name
final String accountName = account.name;
int atIndex = accountName.indexOf('@');
if (atIndex != -1 && atIndex < accountName.length() - 2) {
final char firstLetter = Character.toUpperCase(
accountName.charAt(atIndex + 1));
row[i] = firstLetter + accountName.substring(atIndex + 2);
} else {
row[i] = account.name;
}
} else if (column.equals(Directory.EXPORT_SUPPORT)) {
row[i] = Directory.EXPORT_SUPPORT_SAME_ACCOUNT_ONLY;
} else if (column.equals(Directory.SHORTCUT_SUPPORT)) {
row[i] = Directory.SHORTCUT_SUPPORT_NONE;
}
}
cursor.addRow(row);
}
}
return cursor;
}
case GAL_FILTER:
case GAL_EMAIL_FILTER: {
String filter = uri.getLastPathSegment();
// We should have at least two characters before doing a GAL search
if (filter == null || filter.length() < 2) {
return null;
}
String accountName = uri.getQueryParameter(RawContacts.ACCOUNT_NAME);
if (accountName == null) {
return null;
}
// Enforce a limit on the number of lookup responses
String limitString = uri.getQueryParameter(ContactsContract.LIMIT_PARAM_KEY);
int limit = DEFAULT_LOOKUP_LIMIT;
if (limitString != null) {
try {
limit = Integer.parseInt(limitString);
} catch (NumberFormatException e) {
limit = 0;
}
if (limit <= 0) {
throw new IllegalArgumentException("Limit not valid: " + limitString);
}
}
long callingId = Binder.clearCallingIdentity();
try {
// Find the account id to pass along to EasSyncService
long accountId = getAccountIdByName(getContext(), accountName);
if (accountId == -1) {
// The account was deleted?
return null;
}
// Get results from the Exchange account
GalResult galResult = EasSyncService.searchGal(getContext(), accountId,
filter, limit);
if (galResult != null) {
return buildGalResultCursor(projection, galResult);
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
break;
}
case GAL_CONTACT:
case GAL_CONTACT_WITH_ID: {
String accountName = uri.getQueryParameter(RawContacts.ACCOUNT_NAME);
if (accountName == null) {
return null;
}
GalProjection galProjection = new GalProjection(projection);
cursor = new MatrixCursor(projection);
// Handle the decomposition of the key into rows suitable for CP2
List<String> pathSegments = uri.getPathSegments();
lookupKey = pathSegments.get(2);
long contactId = (match == GAL_CONTACT_WITH_ID)
? Long.parseLong(pathSegments.get(3))
: DEFAULT_CONTACT_ID;
ps = new PackedString(lookupKey);
String displayName = ps.get(GalData.DISPLAY_NAME);
GalContactRow.addEmailAddress(cursor, galProjection, contactId, lookupKey,
accountName, displayName, ps.get(GalData.EMAIL_ADDRESS));
GalContactRow.addPhoneRow(cursor, galProjection, contactId, accountName,
displayName, displayName, Phone.TYPE_HOME, ps.get(GalData.HOME_PHONE));
GalContactRow.addPhoneRow(cursor, galProjection, contactId, accountName,
displayName, displayName, Phone.TYPE_WORK, ps.get(GalData.WORK_PHONE));
GalContactRow.addPhoneRow(cursor, galProjection, contactId, accountName,
displayName, displayName, Phone.TYPE_MOBILE, ps.get(GalData.MOBILE_PHONE));
GalContactRow.addNameRow(cursor, galProjection, contactId, displayName, accountName,
displayName, ps.get(GalData.FIRST_NAME), ps.get(GalData.LAST_NAME));
return cursor;
}
}
return null;
}
|
diff --git a/src/main/java/com/cloudbees/gasp/gcm/GCMIntentService.java b/src/main/java/com/cloudbees/gasp/gcm/GCMIntentService.java
index 4bb9fe5..4e92ae4 100644
--- a/src/main/java/com/cloudbees/gasp/gcm/GCMIntentService.java
+++ b/src/main/java/com/cloudbees/gasp/gcm/GCMIntentService.java
@@ -1,157 +1,154 @@
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cloudbees.gasp.gcm;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import com.cloudbees.gasp.activity.MainActivity;
import com.cloudbees.gasp.service.RestaurantUpdateService;
import com.cloudbees.gasp.service.ReviewUpdateService;
import com.cloudbees.gasp.service.SyncIntentParams;
import com.cloudbees.gasp.service.UserUpdateService;
import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.gcm.GCMRegistrar;
import static com.cloudbees.gasp.gcm.CommonUtilities.SENDER_ID;
import static com.cloudbees.gasp.gcm.CommonUtilities.displayMessage;
/**
* IntentService responsible for handling GCM messages.
*/
public class GCMIntentService extends GCMBaseIntentService {
@SuppressWarnings("hiding")
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super(SENDER_ID);
}
@Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
displayMessage(context, getString(R.string.gcm_registered));
ServerUtilities.register(context, registrationId);
}
@Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
displayMessage(context, getString(R.string.gcm_unregistered));
if (GCMRegistrar.isRegisteredOnServer(context)) {
ServerUtilities.unregister(context, registrationId);
} else {
// This callback results from the call to unregister made on
// ServerUtilities when the registration to the server failed.
Log.i(TAG, "Ignoring unregister callback");
}
}
@Override
protected void onMessage(Context context, Intent intent) {
int index = Integer.parseInt(intent.getStringExtra("id"));
String table = intent.getStringExtra("table");
- Log.i(TAG, "New" + table + ": " + index);
+ Log.i(TAG, "New " + table + " update (" + index + ")");
Intent updateIntent;
try {
if (table.matches("reviews")) {
- updateIntent = new Intent(this, ReviewUpdateService.class);
- updateIntent.putExtra(SyncIntentParams.PARAM_ID, index);
- startService(updateIntent);
+ startService(new Intent(getApplicationContext(), ReviewUpdateService.class)
+ .putExtra(SyncIntentParams.PARAM_ID, index));
}
else if (table.matches("restaurants")) {
- updateIntent = new Intent(this, RestaurantUpdateService.class);
- updateIntent.putExtra(SyncIntentParams.PARAM_ID, index);
- startService(updateIntent);
+ startService(new Intent(getApplicationContext(), RestaurantUpdateService.class)
+ .putExtra(SyncIntentParams.PARAM_ID, index));
}
else if (table.matches("users")) {
- updateIntent = new Intent(this, UserUpdateService.class);
- updateIntent.putExtra(SyncIntentParams.PARAM_ID, index);
- startService(updateIntent);
+ startService(new Intent(getApplicationContext(), UserUpdateService.class)
+ .putExtra(SyncIntentParams.PARAM_ID, index));
}
else {
Log.e(TAG, "Error: unknown table: " + table);
return;
}
// Send notification message for message bar display etc
- generateNotification(context, "New" + table + ": " + index);
+ generateNotification(context, "New " + table + ": " + index);
} catch (Exception e) {
Log.e(TAG, e.getStackTrace().toString());
}
}
@Override
protected void onDeletedMessages(Context context, int total) {
Log.i(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
displayMessage(context, message);
generateNotification(context, message);
}
@Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
displayMessage(context, getString(R.string.gcm_error, errorId));
}
@Override
protected boolean onRecoverableError(Context context, String errorId) {
// log message
Log.i(TAG, "Received recoverable error: " + errorId);
displayMessage(context, getString(R.string.gcm_recoverable_error,
errorId));
return super.onRecoverableError(context, errorId);
}
/**
* Issues a notification to inform the user that server has sent a message.
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
// TODO Fix Notification version issues
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_stat_gcm;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification.
Builder(context).
setContentTitle("New Gasp! Update").
setSmallIcon(R.drawable.ic_stat_gcm).
build();
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
}
| false | true |
protected void onMessage(Context context, Intent intent) {
int index = Integer.parseInt(intent.getStringExtra("id"));
String table = intent.getStringExtra("table");
Log.i(TAG, "New" + table + ": " + index);
Intent updateIntent;
try {
if (table.matches("reviews")) {
updateIntent = new Intent(this, ReviewUpdateService.class);
updateIntent.putExtra(SyncIntentParams.PARAM_ID, index);
startService(updateIntent);
}
else if (table.matches("restaurants")) {
updateIntent = new Intent(this, RestaurantUpdateService.class);
updateIntent.putExtra(SyncIntentParams.PARAM_ID, index);
startService(updateIntent);
}
else if (table.matches("users")) {
updateIntent = new Intent(this, UserUpdateService.class);
updateIntent.putExtra(SyncIntentParams.PARAM_ID, index);
startService(updateIntent);
}
else {
Log.e(TAG, "Error: unknown table: " + table);
return;
}
// Send notification message for message bar display etc
generateNotification(context, "New" + table + ": " + index);
} catch (Exception e) {
Log.e(TAG, e.getStackTrace().toString());
}
}
|
protected void onMessage(Context context, Intent intent) {
int index = Integer.parseInt(intent.getStringExtra("id"));
String table = intent.getStringExtra("table");
Log.i(TAG, "New " + table + " update (" + index + ")");
Intent updateIntent;
try {
if (table.matches("reviews")) {
startService(new Intent(getApplicationContext(), ReviewUpdateService.class)
.putExtra(SyncIntentParams.PARAM_ID, index));
}
else if (table.matches("restaurants")) {
startService(new Intent(getApplicationContext(), RestaurantUpdateService.class)
.putExtra(SyncIntentParams.PARAM_ID, index));
}
else if (table.matches("users")) {
startService(new Intent(getApplicationContext(), UserUpdateService.class)
.putExtra(SyncIntentParams.PARAM_ID, index));
}
else {
Log.e(TAG, "Error: unknown table: " + table);
return;
}
// Send notification message for message bar display etc
generateNotification(context, "New " + table + ": " + index);
} catch (Exception e) {
Log.e(TAG, e.getStackTrace().toString());
}
}
|
diff --git a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/Role.java b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/Role.java
index e1f1efd5..6dc192c6 100644
--- a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/Role.java
+++ b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/Role.java
@@ -1,64 +1,66 @@
package pt.ist.expenditureTrackingSystem.domain;
import myorg.domain.User;
import pt.ist.expenditureTrackingSystem.domain.organization.Person;
import pt.ist.fenixWebFramework.services.Service;
import dml.runtime.RelationAdapter;
public class Role extends Role_Base {
public static class RolePersonListener extends RelationAdapter<Role, Person> {
@Override
public void afterAdd(final Role role, final Person person) {
super.afterAdd(role, person);
if (role.getSystemRole() != null) {
role.getSystemRole().addUsers(person.getUser());
}
}
@Override
public void afterRemove(final Role role, Person person) {
if (role.getSystemRole() != null) {
role.getSystemRole().removeUsers(person.getUser());
}
}
}
static {
Role.PersonRole.addListener(new RolePersonListener());
}
public Role(final RoleType type) {
super();
setRoleType(type);
setExpenditureTrackingSystem(ExpenditureTrackingSystem.getInstance());
setSystemRole(myorg.domain.groups.Role.getRole(type));
}
@Service
public static Role createRole(final RoleType type) {
final Role role = new Role(type);
role.setSystemRole(myorg.domain.groups.Role.getRole(type));
return role;
}
@Service
public static Role getRole(final RoleType roleType) {
for (final Role role : ExpenditureTrackingSystem.getInstance().getRoles()) {
if (role.getRoleType().equals(roleType)) {
if (!role.hasSystemRole()) {
role.setSystemRole(myorg.domain.groups.Role.getRole(roleType));
}
for (final Person person : role.getPersonSet()) {
final User user = person.getUser();
- role.getSystemRole().addUsers(user);
+ if (user != null) {
+ role.getSystemRole().addUsers(user);
+ }
}
return role;
}
}
return createRole(roleType);
}
}
| true | true |
public static Role getRole(final RoleType roleType) {
for (final Role role : ExpenditureTrackingSystem.getInstance().getRoles()) {
if (role.getRoleType().equals(roleType)) {
if (!role.hasSystemRole()) {
role.setSystemRole(myorg.domain.groups.Role.getRole(roleType));
}
for (final Person person : role.getPersonSet()) {
final User user = person.getUser();
role.getSystemRole().addUsers(user);
}
return role;
}
}
return createRole(roleType);
}
|
public static Role getRole(final RoleType roleType) {
for (final Role role : ExpenditureTrackingSystem.getInstance().getRoles()) {
if (role.getRoleType().equals(roleType)) {
if (!role.hasSystemRole()) {
role.setSystemRole(myorg.domain.groups.Role.getRole(roleType));
}
for (final Person person : role.getPersonSet()) {
final User user = person.getUser();
if (user != null) {
role.getSystemRole().addUsers(user);
}
}
return role;
}
}
return createRole(roleType);
}
|
diff --git a/src/org/opensuse/android/obs/Client.java b/src/org/opensuse/android/obs/Client.java
index 48db848..5a6af59 100644
--- a/src/org/opensuse/android/obs/Client.java
+++ b/src/org/opensuse/android/obs/Client.java
@@ -1,140 +1,141 @@
package org.opensuse.android.obs;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import org.opensuse.android.HttpCoreConnection;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import zipwire.rest.ApacheRestConnection;
import zipwire.text.CamelCase;
import zipwire.xml.XmlNamingRule;
public class Client extends HttpCoreConnection {
public static final String PREFERENCES = "preferences";
private static final String DEFAULT_API_HOST = "api.opensuse.org";
private static final String DEFAULT_USERNAME = "";
private static final String DEFAULT_PASSWORD = "";
/* Standard Rails-like naming rule */
static XmlNamingRule xmlNamingRule = new XmlNamingRule(){
public String transform(String method) {
return new CamelCase(method).separateWith("-").toLowerCase();
}
};
/*
* Constructor from context, which allows the client to access the preferences of
* the application
*/
public Client(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// then you use
String username = prefs.getString("username", DEFAULT_USERNAME);
String password = prefs.getString("password", DEFAULT_PASSWORD);
setProtocol("https://");
setUsername(username);
setPassword(password);
setHost(DEFAULT_API_HOST);
setXmlNamingRule(xmlNamingRule);
}
public List<Project> getProjects() {
return getProjectsMatching("");
}
public List<ProjectId> getProjectIds() {
return getProjectIdsMatching("");
}
public List<ProjectId> getProjectIdsMatching(String match) {
String path = "search/project_id" + "?match=" + encodeMatch(match);
Log.i("OBSCLIENT", "Retrieving: " + path);
return get(path)
.asList(ProjectId.class, "project");
}
public List<Project> getProjectsMatching(String match) {
String path = "search/project" + "?match=" + encodeMatch(match);
Log.i("OBSCLIENT", "Retrieving: " + path);
return get(path)
.asList(Project.class, "project");
}
public List<Package> getPackagesMatching(String match) {
String path = "search/package" + "?match=" + encodeMatch(match);
Log.i("OBSCLIENT", "Retrieving: " + path);
return get(path)
.asList(Package.class, "package");
}
public List<PackageId> getPackageIdsMatching(String match) {
String path = "search/package_id" + "?match=" + encodeMatch(match);
Log.i("OBSCLIENT", "Retrieving: " + path);
return get(path)
.asList(PackageId.class, "package");
}
public List<Distribution> getDistributions() {
return get("distributions").asList(Distribution.class, "distribution");
}
public List<Request> getRequestsMatching(String match) {
String path = "search/request";
path = path + "?match=" + encodeMatch(match);
Log.i("OBSCLIENT", "Retrieving: " + path);
return get(path)
.asList(Request.class, "request");
}
public List<Request> getRequests() {
return getRequestsMatching("");
}
public List<Request> getMyRequests() {
List<String> xpaths = new ArrayList<String>();
List<String> projects = new ArrayList<String>();
String query = "(state/@name='new') and (";
List<ProjectId> projectIds = getProjectIdsMatching("person/@userid = '" + getUsername() + "' and person/@role = 'maintainer'");
for (ProjectId project: projectIds) {
+ projects.add(project.getName());
xpaths.add("action/target/@project='" + project.getName() + "'");
}
/*
List<PackageId> packages = getPackageIdsMatching("person/@userid = '" + getUsername() + "' and person/@role = 'maintainer'");
for (PackageId pkg: packages) {
// if the project is already in the list, no need to add this clause
// replace this with a real xPath join
if (projects.contains(pkg.getProject()))
continue;
xpaths.add("(action/target/@project='" + pkg.getProject() + "' and " + "action/target/@package='" + pkg.getName() + "')");
}
*/
Log.i("OBSCLIENT", String.valueOf(xpaths.size()));
query += TextUtils.join(" or ", xpaths);
query += ")";
return getRequestsMatching(query);
}
/* Encode or return the same if not possible */
private String encodeMatch(String match) {
try {
return URLEncoder.encode(match, "UTF-8");
} catch (UnsupportedEncodingException e) {
Log.w("URI", "Can't encode: " + match);
return match;
}
}
}
| true | true |
public List<Request> getMyRequests() {
List<String> xpaths = new ArrayList<String>();
List<String> projects = new ArrayList<String>();
String query = "(state/@name='new') and (";
List<ProjectId> projectIds = getProjectIdsMatching("person/@userid = '" + getUsername() + "' and person/@role = 'maintainer'");
for (ProjectId project: projectIds) {
xpaths.add("action/target/@project='" + project.getName() + "'");
}
/*
List<PackageId> packages = getPackageIdsMatching("person/@userid = '" + getUsername() + "' and person/@role = 'maintainer'");
for (PackageId pkg: packages) {
// if the project is already in the list, no need to add this clause
// replace this with a real xPath join
if (projects.contains(pkg.getProject()))
continue;
xpaths.add("(action/target/@project='" + pkg.getProject() + "' and " + "action/target/@package='" + pkg.getName() + "')");
}
*/
Log.i("OBSCLIENT", String.valueOf(xpaths.size()));
query += TextUtils.join(" or ", xpaths);
query += ")";
return getRequestsMatching(query);
}
|
public List<Request> getMyRequests() {
List<String> xpaths = new ArrayList<String>();
List<String> projects = new ArrayList<String>();
String query = "(state/@name='new') and (";
List<ProjectId> projectIds = getProjectIdsMatching("person/@userid = '" + getUsername() + "' and person/@role = 'maintainer'");
for (ProjectId project: projectIds) {
projects.add(project.getName());
xpaths.add("action/target/@project='" + project.getName() + "'");
}
/*
List<PackageId> packages = getPackageIdsMatching("person/@userid = '" + getUsername() + "' and person/@role = 'maintainer'");
for (PackageId pkg: packages) {
// if the project is already in the list, no need to add this clause
// replace this with a real xPath join
if (projects.contains(pkg.getProject()))
continue;
xpaths.add("(action/target/@project='" + pkg.getProject() + "' and " + "action/target/@package='" + pkg.getName() + "')");
}
*/
Log.i("OBSCLIENT", String.valueOf(xpaths.size()));
query += TextUtils.join(" or ", xpaths);
query += ")";
return getRequestsMatching(query);
}
|
diff --git a/src/main/java/edu/berkeley/sparrow/daemon/scheduler/Scheduler.java b/src/main/java/edu/berkeley/sparrow/daemon/scheduler/Scheduler.java
index 6133a6c..d8ac5c4 100644
--- a/src/main/java/edu/berkeley/sparrow/daemon/scheduler/Scheduler.java
+++ b/src/main/java/edu/berkeley/sparrow/daemon/scheduler/Scheduler.java
@@ -1,315 +1,315 @@
package edu.berkeley.sparrow.daemon.scheduler;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.configuration.Configuration;
import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import edu.berkeley.sparrow.daemon.SparrowConf;
import edu.berkeley.sparrow.daemon.util.Logging;
import edu.berkeley.sparrow.daemon.util.Network;
import edu.berkeley.sparrow.daemon.util.Serialization;
import edu.berkeley.sparrow.daemon.util.ThriftClientPool;
import edu.berkeley.sparrow.thrift.FrontendService;
import edu.berkeley.sparrow.thrift.FrontendService.AsyncClient.frontendMessage_call;
import edu.berkeley.sparrow.thrift.InternalService;
import edu.berkeley.sparrow.thrift.InternalService.AsyncClient.enqueueTaskReservations_call;
import edu.berkeley.sparrow.thrift.TEnqueueTaskReservationsRequest;
import edu.berkeley.sparrow.thrift.TFullTaskId;
import edu.berkeley.sparrow.thrift.THostPort;
import edu.berkeley.sparrow.thrift.TSchedulingRequest;
import edu.berkeley.sparrow.thrift.TTaskLaunchSpec;
import edu.berkeley.sparrow.thrift.TTaskSpec;
/**
* This class implements the Sparrow scheduler functionality.
*/
public class Scheduler {
private final static Logger LOG = Logger.getLogger(Scheduler.class);
private final static Logger AUDIT_LOG = Logging.getAuditLogger(Scheduler.class);
/** Used to uniquely identify requests arriving at this scheduler. */
private int counter = 0;
private THostPort address;
/** Socket addresses for each frontend. */
HashMap<String, InetSocketAddress> frontendSockets =
new HashMap<String, InetSocketAddress>();
/** Thrift client pool for communicating with node monitors */
ThriftClientPool<InternalService.AsyncClient> nodeMonitorClientPool =
new ThriftClientPool<InternalService.AsyncClient>(
new ThriftClientPool.InternalServiceMakerFactory());
/** Thrift client pool for communicating with front ends. */
private ThriftClientPool<FrontendService.AsyncClient> frontendClientPool =
new ThriftClientPool<FrontendService.AsyncClient>(
new ThriftClientPool.FrontendServiceMakerFactory());
/** Information about cluster workload due to other schedulers. */
private SchedulerState state;
/** Probe ratios to use if the probe ratio is not explicitly set in the request. */
private double defaultProbeRatioUnconstrained;
private double defaultProbeRatioConstrained;
/**
* For each request, the task placer that should be used to place the request's tasks. Indexed
* by the request ID.
*/
private Map<String, TaskPlacer> requestTaskPlacers;
private Configuration conf;
public void initialize(Configuration conf, InetSocketAddress socket) throws IOException {
address = Network.socketAddressToThrift(socket);
String mode = conf.getString(SparrowConf.DEPLYOMENT_MODE, "unspecified");
this.conf = conf;
if (mode.equals("standalone")) {
state = new StandaloneSchedulerState();
} else if (mode.equals("configbased")) {
state = new ConfigSchedulerState();
} else if (mode.equals("production")) {
state = new StateStoreSchedulerState();
} else {
throw new RuntimeException("Unsupported deployment mode: " + mode);
}
state.initialize(conf);
defaultProbeRatioUnconstrained = conf.getDouble(SparrowConf.SAMPLE_RATIO,
SparrowConf.DEFAULT_SAMPLE_RATIO);
defaultProbeRatioConstrained = conf.getDouble(SparrowConf.SAMPLE_RATIO_CONSTRAINED,
SparrowConf.DEFAULT_SAMPLE_RATIO_CONSTRAINED);
requestTaskPlacers = Maps.newConcurrentMap();
}
public boolean registerFrontend(String appId, String addr) {
LOG.debug(Logging.functionCall(appId, addr));
Optional<InetSocketAddress> socketAddress = Serialization.strToSocket(addr);
if (!socketAddress.isPresent()) {
LOG.error("Bad address from frontend: " + addr);
return false;
}
frontendSockets.put(appId, socketAddress.get());
return state.watchApplication(appId);
}
/**
* Callback for enqueueTaskReservations() that does nothing (needed because Thrift can't handle
* null callbacks).
*/
private class EnqueueTaskReservationsCallback
implements AsyncMethodCallback<enqueueTaskReservations_call> {
public void onComplete(enqueueTaskReservations_call response) {
return;
}
public void onError(Exception exception) {
// Do not return error client to pool
LOG.error(exception);
}
}
public void submitJob(TSchedulingRequest request) throws TException {
LOG.debug(Logging.functionCall(request));
long start = System.currentTimeMillis();
String requestId = getRequestId();
// Logging the address here is somewhat redundant, since all of the
// messages in this particular log file come from the same address.
// However, it simplifies the process of aggregating the logs, and will
// also be useful when we support multiple daemons running on a single
// machine.
AUDIT_LOG.info(Logging.auditEventString("arrived", requestId,
request.getTasks().size(),
address.getHost(), address.getPort()));
String app = request.getApp();
List<TTaskSpec> tasks = request.getTasks();
Set<InetSocketAddress> backends = state.getBackends(app).keySet();
boolean constrained = false;
for (TTaskSpec task : tasks) {
constrained = constrained || (
task.preference != null &&
task.preference.nodes != null &&
!task.preference.nodes.isEmpty());
}
TaskPlacer taskPlacer;
if (constrained) {
if (request.isSetProbeRatio()) {
taskPlacer = new ConstrainedTaskPlacer(requestId, request.getProbeRatio());
} else {
taskPlacer = new ConstrainedTaskPlacer(requestId, defaultProbeRatioConstrained);
}
} else {
if (request.isSetProbeRatio()) {
taskPlacer = new UnconstrainedTaskPlacer(requestId, request.getProbeRatio());
} else {
taskPlacer = new UnconstrainedTaskPlacer(requestId, defaultProbeRatioUnconstrained);
}
}
requestTaskPlacers.put(requestId, taskPlacer);
Map<InetSocketAddress, TEnqueueTaskReservationsRequest> enqueueTaskReservationsRequests;
if (request.isSetProbeRatio() && request.getProbeRatio() == 3 &&
tasks.get(0).preference.nodes != null &&
(tasks.get(0).preference.nodes.size() == 1 || tasks.get(0).preference.nodes.size() == 2)) {
// This is a hack to force Spark to cache data on multiple machines. If a Spark job runs
// on a machine where the input data is not already cached in memory, Spark will
// automatically caches the data on those machines. So, we run a few dummy jobs at the
// beginning of each experiment to force the data for each job to be cached in three places.
// To do this, we need to explicitly avoid the nodes where data is already cached.
List<InetSocketAddress> subBackends = Lists.newArrayList(backends);
List<InetSocketAddress> toRemove = Lists.newArrayList();
for (TTaskSpec task : tasks) {
for (String node : task.preference.nodes) {
try {
InetAddress addr = InetAddress.getByName(node);
for (InetSocketAddress backend : subBackends) {
if (backend.getAddress().equals(addr)) {
toRemove.add(backend);
break;
}
}
} catch (UnknownHostException e) {
LOG.error(e);
}
}
}
subBackends.removeAll(toRemove);
enqueueTaskReservationsRequests = taskPlacer.getEnqueueTaskReservationsRequests(
request, requestId, subBackends, address);
} else {
enqueueTaskReservationsRequests = taskPlacer.getEnqueueTaskReservationsRequests(
request, requestId, backends, address);
}
// Request to enqueue a task at each of the selected nodes.
for (Entry<InetSocketAddress, TEnqueueTaskReservationsRequest> entry :
enqueueTaskReservationsRequests.entrySet()) {
try {
InternalService.AsyncClient client = nodeMonitorClientPool.borrowClient(entry.getKey());
LOG.debug("Launching enqueueTask for request on node: " + entry.getKey());
// Pass in null callback because the RPC doesn't return anything.
AUDIT_LOG.debug(Logging.auditEventString(
- "node_monitor_launch_enqueue_task", entry.getValue().requestId,
+ "scheduler_launch_enqueue_task", entry.getValue().requestId,
entry.getKey().toString()));
client.enqueueTaskReservations(entry.getValue(), new EnqueueTaskReservationsCallback());
AUDIT_LOG.debug(Logging.auditEventString(
- "node_monitor_complete_enqueue_task", entry.getValue().requestId,
+ "scheduler_complete_enqueue_task", entry.getValue().requestId,
entry.getKey().toString()));
} catch (Exception e) {
LOG.error(e);
}
}
long end = System.currentTimeMillis();
LOG.debug("All tasks enqueued; returning. Total time: " + (end - start) + " milliseconds");
}
public synchronized List<TTaskLaunchSpec> getTask(
String requestId, THostPort nodeMonitorAddress) {
LOG.debug(Logging.functionCall(requestId, nodeMonitorAddress));
if (!requestTaskPlacers.containsKey(requestId)) {
LOG.error("Received getTask() request for request " + requestId + " which had no more " +
"pending reservations");
return Lists.newArrayList();
}
TaskPlacer taskPlacer = requestTaskPlacers.get(requestId);
List<TTaskLaunchSpec> taskLaunchSpecs = taskPlacer.assignTask(nodeMonitorAddress);
if (taskLaunchSpecs == null || taskLaunchSpecs.size() > 1) {
LOG.error("Received invalid task placement: " + taskLaunchSpecs.toString());
return Lists.newArrayList();
} else if (taskLaunchSpecs.size() == 1) {
AUDIT_LOG.info(Logging.auditEventString("assigned_task", requestId,
taskLaunchSpecs.get(0).taskId));
} else {
AUDIT_LOG.info(Logging.auditEventString("get_task_no_task", requestId));
}
if (taskPlacer.allResponsesReceived()) {
LOG.debug("All responses received for request " + requestId);
// Remove the entry in requestTaskPlacers once all tasks have been placed, so that
// requestTaskPlacers doesn't grow to be unbounded.
requestTaskPlacers.remove(requestId);
}
return taskLaunchSpecs;
}
/**
* Returns an ID that identifies a request uniquely (across all Sparrow schedulers).
*
* This should only be called once for each request (it will return a different
* identifier if called a second time).
*
* TODO: Include the port number, so this works when there are multiple schedulers
* running on a single machine (as there will be when we do large scale testing).
*/
private String getRequestId() {
/* The request id is a string that includes the IP address of this scheduler followed
* by the counter. We use a counter rather than a hash of the request because there
* may be multiple requests to run an identical job. */
return String.format("%s_%d", Network.getIPAddress(conf), counter++);
}
private class sendFrontendMessageCallback implements
AsyncMethodCallback<frontendMessage_call> {
private InetSocketAddress frontendSocket;
private FrontendService.AsyncClient client;
public sendFrontendMessageCallback(InetSocketAddress socket, FrontendService.AsyncClient client) {
frontendSocket = socket;
this.client = client;
}
public void onComplete(frontendMessage_call response) {
try { frontendClientPool.returnClient(frontendSocket, client); }
catch (Exception e) { LOG.error(e); }
}
public void onError(Exception exception) {
// Do not return error client to pool
LOG.error(exception);
}
}
public void sendFrontendMessage(String app, TFullTaskId taskId,
int status, ByteBuffer message) {
LOG.debug(Logging.functionCall(app, taskId, message));
InetSocketAddress frontend = frontendSockets.get(app);
if (frontend == null) {
LOG.error("Requested message sent to unregistered app: " + app);
}
try {
FrontendService.AsyncClient client = frontendClientPool.borrowClient(frontend);
client.frontendMessage(taskId, status, message,
new sendFrontendMessageCallback(frontend, client));
} catch (IOException e) {
LOG.error("Error launching message on frontend: " + app, e);
} catch (TException e) {
LOG.error("Error launching message on frontend: " + app, e);
} catch (Exception e) {
LOG.error("Error launching message on frontend: " + app, e);
}
}
}
| false | true |
public void submitJob(TSchedulingRequest request) throws TException {
LOG.debug(Logging.functionCall(request));
long start = System.currentTimeMillis();
String requestId = getRequestId();
// Logging the address here is somewhat redundant, since all of the
// messages in this particular log file come from the same address.
// However, it simplifies the process of aggregating the logs, and will
// also be useful when we support multiple daemons running on a single
// machine.
AUDIT_LOG.info(Logging.auditEventString("arrived", requestId,
request.getTasks().size(),
address.getHost(), address.getPort()));
String app = request.getApp();
List<TTaskSpec> tasks = request.getTasks();
Set<InetSocketAddress> backends = state.getBackends(app).keySet();
boolean constrained = false;
for (TTaskSpec task : tasks) {
constrained = constrained || (
task.preference != null &&
task.preference.nodes != null &&
!task.preference.nodes.isEmpty());
}
TaskPlacer taskPlacer;
if (constrained) {
if (request.isSetProbeRatio()) {
taskPlacer = new ConstrainedTaskPlacer(requestId, request.getProbeRatio());
} else {
taskPlacer = new ConstrainedTaskPlacer(requestId, defaultProbeRatioConstrained);
}
} else {
if (request.isSetProbeRatio()) {
taskPlacer = new UnconstrainedTaskPlacer(requestId, request.getProbeRatio());
} else {
taskPlacer = new UnconstrainedTaskPlacer(requestId, defaultProbeRatioUnconstrained);
}
}
requestTaskPlacers.put(requestId, taskPlacer);
Map<InetSocketAddress, TEnqueueTaskReservationsRequest> enqueueTaskReservationsRequests;
if (request.isSetProbeRatio() && request.getProbeRatio() == 3 &&
tasks.get(0).preference.nodes != null &&
(tasks.get(0).preference.nodes.size() == 1 || tasks.get(0).preference.nodes.size() == 2)) {
// This is a hack to force Spark to cache data on multiple machines. If a Spark job runs
// on a machine where the input data is not already cached in memory, Spark will
// automatically caches the data on those machines. So, we run a few dummy jobs at the
// beginning of each experiment to force the data for each job to be cached in three places.
// To do this, we need to explicitly avoid the nodes where data is already cached.
List<InetSocketAddress> subBackends = Lists.newArrayList(backends);
List<InetSocketAddress> toRemove = Lists.newArrayList();
for (TTaskSpec task : tasks) {
for (String node : task.preference.nodes) {
try {
InetAddress addr = InetAddress.getByName(node);
for (InetSocketAddress backend : subBackends) {
if (backend.getAddress().equals(addr)) {
toRemove.add(backend);
break;
}
}
} catch (UnknownHostException e) {
LOG.error(e);
}
}
}
subBackends.removeAll(toRemove);
enqueueTaskReservationsRequests = taskPlacer.getEnqueueTaskReservationsRequests(
request, requestId, subBackends, address);
} else {
enqueueTaskReservationsRequests = taskPlacer.getEnqueueTaskReservationsRequests(
request, requestId, backends, address);
}
// Request to enqueue a task at each of the selected nodes.
for (Entry<InetSocketAddress, TEnqueueTaskReservationsRequest> entry :
enqueueTaskReservationsRequests.entrySet()) {
try {
InternalService.AsyncClient client = nodeMonitorClientPool.borrowClient(entry.getKey());
LOG.debug("Launching enqueueTask for request on node: " + entry.getKey());
// Pass in null callback because the RPC doesn't return anything.
AUDIT_LOG.debug(Logging.auditEventString(
"node_monitor_launch_enqueue_task", entry.getValue().requestId,
entry.getKey().toString()));
client.enqueueTaskReservations(entry.getValue(), new EnqueueTaskReservationsCallback());
AUDIT_LOG.debug(Logging.auditEventString(
"node_monitor_complete_enqueue_task", entry.getValue().requestId,
entry.getKey().toString()));
} catch (Exception e) {
LOG.error(e);
}
}
long end = System.currentTimeMillis();
LOG.debug("All tasks enqueued; returning. Total time: " + (end - start) + " milliseconds");
}
|
public void submitJob(TSchedulingRequest request) throws TException {
LOG.debug(Logging.functionCall(request));
long start = System.currentTimeMillis();
String requestId = getRequestId();
// Logging the address here is somewhat redundant, since all of the
// messages in this particular log file come from the same address.
// However, it simplifies the process of aggregating the logs, and will
// also be useful when we support multiple daemons running on a single
// machine.
AUDIT_LOG.info(Logging.auditEventString("arrived", requestId,
request.getTasks().size(),
address.getHost(), address.getPort()));
String app = request.getApp();
List<TTaskSpec> tasks = request.getTasks();
Set<InetSocketAddress> backends = state.getBackends(app).keySet();
boolean constrained = false;
for (TTaskSpec task : tasks) {
constrained = constrained || (
task.preference != null &&
task.preference.nodes != null &&
!task.preference.nodes.isEmpty());
}
TaskPlacer taskPlacer;
if (constrained) {
if (request.isSetProbeRatio()) {
taskPlacer = new ConstrainedTaskPlacer(requestId, request.getProbeRatio());
} else {
taskPlacer = new ConstrainedTaskPlacer(requestId, defaultProbeRatioConstrained);
}
} else {
if (request.isSetProbeRatio()) {
taskPlacer = new UnconstrainedTaskPlacer(requestId, request.getProbeRatio());
} else {
taskPlacer = new UnconstrainedTaskPlacer(requestId, defaultProbeRatioUnconstrained);
}
}
requestTaskPlacers.put(requestId, taskPlacer);
Map<InetSocketAddress, TEnqueueTaskReservationsRequest> enqueueTaskReservationsRequests;
if (request.isSetProbeRatio() && request.getProbeRatio() == 3 &&
tasks.get(0).preference.nodes != null &&
(tasks.get(0).preference.nodes.size() == 1 || tasks.get(0).preference.nodes.size() == 2)) {
// This is a hack to force Spark to cache data on multiple machines. If a Spark job runs
// on a machine where the input data is not already cached in memory, Spark will
// automatically caches the data on those machines. So, we run a few dummy jobs at the
// beginning of each experiment to force the data for each job to be cached in three places.
// To do this, we need to explicitly avoid the nodes where data is already cached.
List<InetSocketAddress> subBackends = Lists.newArrayList(backends);
List<InetSocketAddress> toRemove = Lists.newArrayList();
for (TTaskSpec task : tasks) {
for (String node : task.preference.nodes) {
try {
InetAddress addr = InetAddress.getByName(node);
for (InetSocketAddress backend : subBackends) {
if (backend.getAddress().equals(addr)) {
toRemove.add(backend);
break;
}
}
} catch (UnknownHostException e) {
LOG.error(e);
}
}
}
subBackends.removeAll(toRemove);
enqueueTaskReservationsRequests = taskPlacer.getEnqueueTaskReservationsRequests(
request, requestId, subBackends, address);
} else {
enqueueTaskReservationsRequests = taskPlacer.getEnqueueTaskReservationsRequests(
request, requestId, backends, address);
}
// Request to enqueue a task at each of the selected nodes.
for (Entry<InetSocketAddress, TEnqueueTaskReservationsRequest> entry :
enqueueTaskReservationsRequests.entrySet()) {
try {
InternalService.AsyncClient client = nodeMonitorClientPool.borrowClient(entry.getKey());
LOG.debug("Launching enqueueTask for request on node: " + entry.getKey());
// Pass in null callback because the RPC doesn't return anything.
AUDIT_LOG.debug(Logging.auditEventString(
"scheduler_launch_enqueue_task", entry.getValue().requestId,
entry.getKey().toString()));
client.enqueueTaskReservations(entry.getValue(), new EnqueueTaskReservationsCallback());
AUDIT_LOG.debug(Logging.auditEventString(
"scheduler_complete_enqueue_task", entry.getValue().requestId,
entry.getKey().toString()));
} catch (Exception e) {
LOG.error(e);
}
}
long end = System.currentTimeMillis();
LOG.debug("All tasks enqueued; returning. Total time: " + (end - start) + " milliseconds");
}
|
diff --git a/ttools/src/main/uk/ac/starlink/ttools/plot/Drawing.java b/ttools/src/main/uk/ac/starlink/ttools/plot/Drawing.java
index 135ddad17..b71ea19d6 100755
--- a/ttools/src/main/uk/ac/starlink/ttools/plot/Drawing.java
+++ b/ttools/src/main/uk/ac/starlink/ttools/plot/Drawing.java
@@ -1,489 +1,489 @@
package uk.ac.starlink.ttools.plot;
import java.awt.BasicStroke;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.Stroke;
import java.util.BitSet;
import java.util.Iterator;
/**
* Provides drawing primitives on a pixel map.
* This is a bit like a {@link java.awt.Graphics}, but renders only to
* a one-bit-per-pixel bitmap. After drawings have been done, the
* object can be used as a {@link Pixellator} to get a list of the pixels
* which have been hit at least once by one of the drawing methods called
* during the life of the object. Pixels will not be repeated in this list.
*
* <p>The drawing methods are intended to be as efficient as possible.
* Bounds checking is done, so it is generally not problematic (or
* inefficient) to attempt drawing operations with coordinates far outside
* the drawing's range.
*
* @author Mark Taylor
* @since 20 Mar 2007
*/
public class Drawing implements Pixellator {
private final BitSet pixelMask_;
private final Rectangle bounds_;
private int nextPointKey_ = Integer.MAX_VALUE;
private Point point_;
private static final Stroke STROKE = new BasicStroke();
/**
* Constructs a drawing with given pixel bounds.
*
* @param bounds rectangle giving the region in which pixels may be
* plotted
*/
public Drawing( Rectangle bounds ) {
bounds_ = bounds;
pixelMask_ = new BitSet( bounds.width * bounds.height );
}
public Rectangle getBounds() {
return new Rectangle( bounds_ );
}
/**
* Adds a single pixel to the list of pixels which have been plotted.
* Calling it with coordinates which have already been plotted,
* or which are outside this drawing's bounds, has no effect.
*
* @param x X coordinate
* @param y Y coordinate
*/
public void addPixel( int x, int y ) {
if ( bounds_.contains( x, y ) ) {
int xoff = x - bounds_.x;
int yoff = y - bounds_.y;
int packed = xoff + bounds_.width * yoff;
assert packed >= 0 && packed < bounds_.width * bounds_.height;
pixelMask_.set( packed );
}
}
/**
* Draws a straight line between two points.
*
* @param x0 X coordinate of first point
* @param y0 Y coordinate of first point
* @param x1 X coordinate of second point
* @param y1 Y coordinate of second point
* @see java.awt.Graphics#drawLine
*/
public void drawLine( int x0, int y0, int x1, int y1 ) {
/* Vertical line. */
if ( x0 == x1 ) {
int x = x0;
if ( y0 > y1 ) {
int y2 = y1;
y1 = y0;
y0 = y2;
}
- y0 = Math.max( y0, bounds_.y );
- y1 = Math.min( y1, bounds_.y + bounds_.height );
- for ( int y = y0; y <= y1; y++ ) {
+ int ya = Math.max( y0, bounds_.y );
+ int yb = Math.min( y1, bounds_.y + bounds_.height );
+ for ( int y = ya; y <= yb; y++ ) {
addPixel( x, y );
}
}
/* Horizontal line. */
else if ( y0 == y1 ) {
int y = y0;
if ( x0 > x1 ) {
int x2 = x1;
x1 = x0;
x0 = x2;
}
- x0 = Math.max( x0, bounds_.x );
- x1 = Math.min( x1, bounds_.x + bounds_.width );
- for ( int x = x0; x <= x1; x++ ) {
+ int xa = Math.max( x0, bounds_.x );
+ int xb = Math.min( x1, bounds_.x + bounds_.width );
+ for ( int x = xa; x <= xb; x++ ) {
addPixel( x, y );
}
}
/* Diagonal line, more horizontal than vertical. */
else if ( Math.abs( x1 - x0 ) > Math.abs( y1 - y0 ) ) {
if ( x0 > x1 ) {
int x2 = x1;
int y2 = y1;
x1 = x0;
y1 = y0;
x0 = x2;
y0 = y2;
}
double slope = (double) ( y1 - y0 ) / (double) ( x1 - x0 );
- x0 = Math.max( x0, bounds_.x );
- x1 = Math.min( x1, bounds_.x + bounds_.width );
- for ( int x = x0; x <= x1; x++ ) {
+ int xa = Math.max( x0, bounds_.x );
+ int xb = Math.min( x1, bounds_.x + bounds_.width );
+ for ( int x = xa; x <= xb; x++ ) {
addPixel( x, y0 + (int) Math.round( ( x - x0 ) * slope ) );
}
}
/* Diagonal line, more vertical than horizontal. */
else {
assert Math.abs( x1 - x0 ) <= Math.abs( y1 - y0 );
if ( y0 > y1 ) {
int x2 = x1;
int y2 = y1;
x1 = x0;
y1 = y0;
x0 = x2;
y0 = y2;
}
double slope = (double) ( x1 - x0 ) / (double) ( y1 - y0 );
- y0 = Math.max( y0, bounds_.y );
- y1 = Math.min( y1, bounds_.y + bounds_.height );
- for ( int y = y0; y <= y1; y++ ) {
+ int ya = Math.max( y0, bounds_.y );
+ int yb = Math.min( y1, bounds_.y + bounds_.height );
+ for ( int y = ya; y <= yb; y++ ) {
addPixel( x0 + (int) Math.round( ( y - y0 ) * slope ), y );
}
}
}
/**
* Fills a rectangle.
*
* @param x X coordinate of top left corner
* @param y Y coordinate of top left corner
* @param width width
* @param height height
* @see java.awt.Graphics#fillRect
*/
public void fillRect( int x, int y, int width, int height ) {
int xlo = Math.max( bounds_.x, x );
int xhi = Math.min( bounds_.x + bounds_.width, x + width );
int ylo = Math.max( bounds_.y, y );
int yhi = Math.min( bounds_.y + bounds_.height, y + height );
if ( xlo < xhi && ylo < yhi ) {
for ( int ix = xlo; ix < xhi; ix++ ) {
for ( int iy = ylo; iy < yhi; iy++ ) {
addPixel( ix, iy );
}
}
}
}
/**
* Draws the outline of an ellipse with horizontal/vertical axes.
*
* @param x X coordinate of top left corner of enclosing rectangle
* @param y Y coordinate of top left corner of enclosing rectangle
* @param width width of enclosing rectangle
* @param height height of enclosing rectangle
* @see java.awt.Graphics#drawOval
*/
public void drawOval( int x, int y, int width, int height ) {
int a = width / 2;
int b = height / 2;
double a2r = 1.0 / ( (double) a * a );
double b2r = 1.0 / ( (double) b * b );
int x0 = x + a;
int y0 = y + b;
int xmin;
int xmax;
int xp = x0 - bounds_.x;
int xq = bounds_.x + bounds_.width - x0;
if ( xp < 0 ) {
xmin = - xp;
xmax = + xq;
}
else if ( xq < 0 ) {
xmin = - xq;
xmax = + xp;
}
else {
xmin = 0;
xmax = Math.min( a, Math.max( xp, xq ) );
}
int lasty = 0;
for ( int ix = xmin; ix < xmax; ix++ ) {
int iy = (int) Math.round( b * Math.sqrt( 1.0 - a2r * ix * ix ) );
addPixel( x0 + ix, y0 + iy );
addPixel( x0 + ix, y0 - iy );
addPixel( x0 - ix, y0 + iy );
addPixel( x0 - ix, y0 - iy );
if ( lasty - iy > 1 ) {
break;
}
lasty = iy;
}
int ymin;
int ymax;
int yp = y0 - bounds_.y;
int yq = bounds_.y + bounds_.height - y0;
if ( yp < 0 ) {
ymin = - yp;
ymax = + yq;
}
else if ( yq < 0 ) {
ymin = - yq;
ymax = + yp;
}
else {
ymin = 0;
ymax = Math.min( b, Math.max( yp, yq ) );
}
int lastx = 0;
for ( int iy = ymin; iy < ymax; iy++ ) {
int ix = (int) Math.round( a * Math.sqrt( 1.0 - b2r * iy * iy ) );
addPixel( x0 + ix, y0 + iy );
addPixel( x0 + ix, y0 - iy );
addPixel( x0 - ix, y0 + iy );
addPixel( x0 - ix, y0 - iy );
if ( lastx - ix > 1 ) {
break;
}
lastx = ix;
}
}
/**
* Fills an ellipse with horizontal/vertical axes.
*
* @param x X coordinate of top left corner of enclosing rectangle
* @param y Y coordinate of top left corner of enclosing rectangle
* @param width width of enclosing rectangle
* @param height height of enclosing rectangle
* @see java.awt.Graphics#drawOval
*/
public void fillOval( int x, int y, int width, int height ) {
int a = width / 2;
int b = height / 2;
int x0 = x + a;
int y0 = y + b;
int xlo = Math.max( bounds_.x, x );
int xhi = Math.min( bounds_.x + bounds_.width, x + width );
int ylo = Math.max( bounds_.y, y );
int yhi = Math.min( bounds_.y + bounds_.height, y + height );
double a2 = (double) a * a;
double b2 = (double) b * b;
double a2b2 = a2 * b2;
for ( int ix = xlo; ix <= xhi; ix++ ) {
int jx = ix - x0;
double jxb2 = b2 * jx * jx;
for ( int iy = ylo; iy <= yhi; iy++ ) {
int jy = iy - y0;
double jya2 = a2 * jy * jy;
if ( jxb2 + jya2 <= a2b2 ) {
addPixel( ix, iy );
}
}
}
}
/**
* Draws the outline of an ellipse with no restrictions on the alignment
* of its axes.
*
* @param x0 X coordinate of ellipse centre
* @param y0 Y coordinate of ellipse centre
* @param ax X component of semi-major (or -minor) axis
* @param ay Y component of semi-major (or -minor) axis
* @param bx X component of semi-minor (or -major) axis
* @param by Y component of semi-minor (Or -major) axis
*/
public void drawEllipse( int x0, int y0, int ax, int ay, int bx, int by ) {
int xmax = Math.abs( ax ) + Math.abs( bx );
int ymax = Math.abs( ay ) + Math.abs( by );
int xlo = Math.max( x0 - xmax, bounds_.x );
int xhi = Math.min( x0 + xmax, bounds_.x + bounds_.width );
int ylo = Math.max( y0 - ymax, bounds_.y );
int yhi = Math.min( y0 + ymax, bounds_.y + bounds_.height );
double kxx = (double) ay * ay + (double) by * by;
double kxy = -2 * ( (double) ax * ay + (double) bx * by );
double kyy = (double) ax * ax + (double) bx * bx;
double r1 = (double) ax * by - (double) bx * ay;
double r2 = r1 * r1;
for ( int x = xlo; x <= xhi; x++ ) {
double x1 = x - x0;
double x2 = x1 * x1;
double cA = kyy;
double cB = kxy * x1;
double cC = kxx * x2 - r2;
double a2r = 0.5 / cA;
double yz = y0 - cB * a2r;
double yd = Math.sqrt( cB * cB - 4 * cA * cC ) * a2r;
if ( ! Double.isNaN( yd ) ) {
addPixel( x, (int) Math.round( yz - yd ) );
addPixel( x, (int) Math.round( yz + yd ) );
}
}
for ( int y = ylo; y <= yhi; y++ ) {
double y1 = y - y0;
double y2 = y1 * y1;
double cA = kxx;
double cB = kxy * y1;
double cC = kyy * y2 - r2;
double a2r = 0.5 / cA;
double xz = x0 - cB * a2r;
double xd = Math.sqrt( cB * cB - 4 * cA * cC ) * a2r;
if ( ! Double.isNaN( xd ) ) {
addPixel( (int) Math.round( xz - xd ), y );
addPixel( (int) Math.round( xz + xd ), y );
}
}
}
/**
* Fills an ellipse with no restrictions on the alignment of its axes.
*
* @param x0 X coordinate of ellipse centre
* @param y0 Y coordinate of ellipse centre
* @param ax X component of semi-major (or -minor) axis
* @param ay Y component of semi-major (or -minor) axis
* @param bx X component of semi-minor (or -major) axis
* @param by Y component of semi-minor (Or -major) axis
*/
public void fillEllipse( int x0, int y0, int ax, int ay, int bx, int by ) {
int xmax = Math.abs( ax ) + Math.abs( bx );
int ymax = Math.abs( ay ) + Math.abs( by );
int xlo = Math.max( x0 - xmax, bounds_.x );
int xhi = Math.min( x0 + xmax, bounds_.x + bounds_.width );
int ylo = Math.max( y0 - ymax, bounds_.y );
int yhi = Math.min( y0 + ymax, bounds_.y + bounds_.height );
double kxx = (double) ay * ay + (double) by * by;
double kxy = -2 * ( (double) ax * ay + (double) bx * by );
double kyy = (double) ax * ax + (double) bx * bx;
double r = (double) ax * by - (double) bx * ay;
double r2 = r * r;
if ( xhi - xlo > 0 && yhi - ylo > 0 ) {
for ( int x = xlo; x <= xhi; x++ ) {
double x1 = x - x0;
double x2 = x1 * x1;
for ( int y = ylo; y <= yhi; y++ ) {
double y1 = y - y0;
double y2 = y1 * y1;
if ( kxx * x2 + kxy * x1 * y1 + kyy * y2 <= r2 ) {
addPixel( x, y );
}
}
}
}
}
/**
* Fills an arbitrary shape.
*
* @param shape shape to fill
* @see java.awt.Graphics2#fill
*/
public void fill( Shape shape ) {
Rectangle box = shape.getBounds();
int xlo = Math.max( bounds_.x, box.x );
int xhi = Math.min( bounds_.x + bounds_.width, box.x + box.width );
int ylo = Math.max( bounds_.y, box.y );
int yhi = Math.min( bounds_.y + bounds_.height, box.y + box.height );
if ( xhi >= xlo && yhi >= ylo ) {
for ( int x = xlo; x <= xhi; x++ ) {
double px = (double) x;
for ( int y = ylo; y <= yhi; y++ ) {
double py = (double) y;
if ( shape.contains( px, py ) ) {
addPixel( x, y );
}
}
}
}
}
/**
* Draws the outline of an arbitrary shape.
* May not be that efficient.
*
* @param shape shape to draw
* @see java.awt.Graphics2#draw
*/
public void draw( Shape shape ) {
fill( STROKE.createStrokedShape( shape ) );
}
/**
* Adds all the pixels from the given Pixellator to this drawing.
*
* @param pixellator iterator over pixels to add
*/
public void addPixels( Pixellator pixellator ) {
for ( pixellator.start(); pixellator.next(); ) {
addPixel( pixellator.getX(), pixellator.getY() );
}
}
//
// Pixellator interface.
//
public void start() {
point_ = new Point();
nextPointKey_ = -1;
}
public boolean next() {
nextPointKey_ = pixelMask_.nextSetBit( nextPointKey_ + 1 );
if ( nextPointKey_ >= 0 ) {
point_.x = nextPointKey_ % bounds_.width + bounds_.x;
point_.y = nextPointKey_ / bounds_.width + bounds_.y;
return true;
}
else {
point_ = null;
nextPointKey_ = Integer.MAX_VALUE;
return false;
}
}
public int getX() {
return point_.x;
}
public int getY() {
return point_.y;
}
/**
* Combines an array of given pixellators to produce a single one which
* iterates over all the pixels. It is tempting just to provide a
* new Pixellator implementation which iterates over its consituent
* ones to do this, but that would risk returning some pixels multiple
* times, which we don't want.
*
* @param pixers array of pixellators to combine
* @return pixellator comprising the union of the supplied ones
*/
public static Pixellator combinePixellators( Pixellator[] pixers ) {
Rectangle bounds = null;
for ( int is = 0; is < pixers.length; is++ ) {
Rectangle sbounds = pixers[ is ].getBounds();
if ( bounds != null ) {
if ( sbounds != null ) {
bounds.add( new Rectangle( sbounds ) );
}
}
else {
bounds = new Rectangle( sbounds );
}
}
if ( bounds == null ) {
return new Drawing( new Rectangle( 0, 0, 0, 0 ) ) {
public Rectangle getBounds() {
return null;
}
};
}
Drawing union = new Drawing( bounds );
for ( int is = 0; is < pixers.length; is++ ) {
union.addPixels( pixers[ is ] );
}
return union;
}
}
| false | true |
public void drawLine( int x0, int y0, int x1, int y1 ) {
/* Vertical line. */
if ( x0 == x1 ) {
int x = x0;
if ( y0 > y1 ) {
int y2 = y1;
y1 = y0;
y0 = y2;
}
y0 = Math.max( y0, bounds_.y );
y1 = Math.min( y1, bounds_.y + bounds_.height );
for ( int y = y0; y <= y1; y++ ) {
addPixel( x, y );
}
}
/* Horizontal line. */
else if ( y0 == y1 ) {
int y = y0;
if ( x0 > x1 ) {
int x2 = x1;
x1 = x0;
x0 = x2;
}
x0 = Math.max( x0, bounds_.x );
x1 = Math.min( x1, bounds_.x + bounds_.width );
for ( int x = x0; x <= x1; x++ ) {
addPixel( x, y );
}
}
/* Diagonal line, more horizontal than vertical. */
else if ( Math.abs( x1 - x0 ) > Math.abs( y1 - y0 ) ) {
if ( x0 > x1 ) {
int x2 = x1;
int y2 = y1;
x1 = x0;
y1 = y0;
x0 = x2;
y0 = y2;
}
double slope = (double) ( y1 - y0 ) / (double) ( x1 - x0 );
x0 = Math.max( x0, bounds_.x );
x1 = Math.min( x1, bounds_.x + bounds_.width );
for ( int x = x0; x <= x1; x++ ) {
addPixel( x, y0 + (int) Math.round( ( x - x0 ) * slope ) );
}
}
/* Diagonal line, more vertical than horizontal. */
else {
assert Math.abs( x1 - x0 ) <= Math.abs( y1 - y0 );
if ( y0 > y1 ) {
int x2 = x1;
int y2 = y1;
x1 = x0;
y1 = y0;
x0 = x2;
y0 = y2;
}
double slope = (double) ( x1 - x0 ) / (double) ( y1 - y0 );
y0 = Math.max( y0, bounds_.y );
y1 = Math.min( y1, bounds_.y + bounds_.height );
for ( int y = y0; y <= y1; y++ ) {
addPixel( x0 + (int) Math.round( ( y - y0 ) * slope ), y );
}
}
}
|
public void drawLine( int x0, int y0, int x1, int y1 ) {
/* Vertical line. */
if ( x0 == x1 ) {
int x = x0;
if ( y0 > y1 ) {
int y2 = y1;
y1 = y0;
y0 = y2;
}
int ya = Math.max( y0, bounds_.y );
int yb = Math.min( y1, bounds_.y + bounds_.height );
for ( int y = ya; y <= yb; y++ ) {
addPixel( x, y );
}
}
/* Horizontal line. */
else if ( y0 == y1 ) {
int y = y0;
if ( x0 > x1 ) {
int x2 = x1;
x1 = x0;
x0 = x2;
}
int xa = Math.max( x0, bounds_.x );
int xb = Math.min( x1, bounds_.x + bounds_.width );
for ( int x = xa; x <= xb; x++ ) {
addPixel( x, y );
}
}
/* Diagonal line, more horizontal than vertical. */
else if ( Math.abs( x1 - x0 ) > Math.abs( y1 - y0 ) ) {
if ( x0 > x1 ) {
int x2 = x1;
int y2 = y1;
x1 = x0;
y1 = y0;
x0 = x2;
y0 = y2;
}
double slope = (double) ( y1 - y0 ) / (double) ( x1 - x0 );
int xa = Math.max( x0, bounds_.x );
int xb = Math.min( x1, bounds_.x + bounds_.width );
for ( int x = xa; x <= xb; x++ ) {
addPixel( x, y0 + (int) Math.round( ( x - x0 ) * slope ) );
}
}
/* Diagonal line, more vertical than horizontal. */
else {
assert Math.abs( x1 - x0 ) <= Math.abs( y1 - y0 );
if ( y0 > y1 ) {
int x2 = x1;
int y2 = y1;
x1 = x0;
y1 = y0;
x0 = x2;
y0 = y2;
}
double slope = (double) ( x1 - x0 ) / (double) ( y1 - y0 );
int ya = Math.max( y0, bounds_.y );
int yb = Math.min( y1, bounds_.y + bounds_.height );
for ( int y = ya; y <= yb; y++ ) {
addPixel( x0 + (int) Math.round( ( y - y0 ) * slope ), y );
}
}
}
|
diff --git a/tests/tests/view/src/android/view/cts/KeyCharacterMapTest.java b/tests/tests/view/src/android/view/cts/KeyCharacterMapTest.java
index 38d6dfb7..4ab38df8 100644
--- a/tests/tests/view/src/android/view/cts/KeyCharacterMapTest.java
+++ b/tests/tests/view/src/android/view/cts/KeyCharacterMapTest.java
@@ -1,305 +1,304 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.view.cts;
import android.test.AndroidTestCase;
import android.text.TextUtils;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.KeyCharacterMap.KeyData;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestTargets;
@TestTargetClass(KeyCharacterMap.class)
public class KeyCharacterMapTest extends AndroidTestCase {
private KeyCharacterMap mKeyCharacterMap;
private final char[] chars = {'A', 'B', 'C'};
@Override
protected void setUp() throws Exception {
super.setUp();
mKeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "isPrintingKey",
args = {int.class}
)
public void testIsPrintingKey() throws Exception {
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_UNKNOWN));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SOFT_LEFT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SOFT_RIGHT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_HOME));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BACK));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CALL));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ENDCALL));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_0));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_1));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_2));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_3));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_4));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_5));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_6));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_7));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_8));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_9));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_STAR));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_POUND));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_DPAD_UP));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_DPAD_DOWN));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_DPAD_LEFT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_DPAD_RIGHT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_DPAD_CENTER));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_VOLUME_UP));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_VOLUME_DOWN));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_POWER));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CAMERA));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CLEAR));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_A));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_B));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_C));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_D));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_E));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_G));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_H));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_I));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_J));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_K));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_L));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_M));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_N));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_O));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_P));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_Q));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_R));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_S));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_T));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_U));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_V));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_W));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_X));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_Y));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_Z));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_COMMA));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PERIOD));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ALT_LEFT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ALT_RIGHT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SHIFT_LEFT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SHIFT_RIGHT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_TAB));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SPACE));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUM));
- assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SYM));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_EXPLORER));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ENVELOPE));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ENTER));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_DEL));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_GRAVE));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MINUS));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_EQUALS));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_LEFT_BRACKET));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_RIGHT_BRACKET));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BACKSLASH));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SEMICOLON));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_APOSTROPHE));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SLASH));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_AT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUM));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_HEADSETHOOK));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PLUS));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MENU));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NOTIFICATION));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SEARCH));
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "load",
args = {int.class}
)
public void testLoad() throws Exception {
mKeyCharacterMap = null;
mKeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
assertNotNull(mKeyCharacterMap);
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getNumber",
args = {int.class}
)
public void testGetNumber() throws Exception {
assertEquals('0', mKeyCharacterMap.getNumber(KeyEvent.KEYCODE_0));
assertEquals('1', mKeyCharacterMap.getNumber(KeyEvent.KEYCODE_1));
assertEquals('2', mKeyCharacterMap.getNumber(KeyEvent.KEYCODE_2));
assertEquals('3', mKeyCharacterMap.getNumber(KeyEvent.KEYCODE_3));
assertEquals('4', mKeyCharacterMap.getNumber(KeyEvent.KEYCODE_4));
assertEquals('5', mKeyCharacterMap.getNumber(KeyEvent.KEYCODE_5));
assertEquals('6', mKeyCharacterMap.getNumber(KeyEvent.KEYCODE_6));
assertEquals('7', mKeyCharacterMap.getNumber(KeyEvent.KEYCODE_7));
assertEquals('8', mKeyCharacterMap.getNumber(KeyEvent.KEYCODE_8));
assertEquals('9', mKeyCharacterMap.getNumber(KeyEvent.KEYCODE_9));
assertEquals('*', mKeyCharacterMap.getNumber(KeyEvent.KEYCODE_STAR));
assertEquals('#', mKeyCharacterMap.getNumber(KeyEvent.KEYCODE_POUND));
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getMatch",
args = {int.class, char[].class}
)
public void testGetMatch1() throws Exception {
try {
mKeyCharacterMap.getMatch(KeyEvent.KEYCODE_0, null);
fail("should throw exception");
} catch (Exception e) {
}
assertEquals('\0', mKeyCharacterMap.getMatch(getCharacterKeyCode('E'), chars));
assertEquals('A', mKeyCharacterMap.getMatch(getCharacterKeyCode('A'), chars));
assertEquals('B', mKeyCharacterMap.getMatch(getCharacterKeyCode('B'), chars));
}
private int getCharacterKeyCode(char oneChar) {
// Lowercase the character to avoid getting modifiers in the KeyEvent array.
char[] chars = new char[] {Character.toLowerCase(oneChar)};
KeyEvent[] events = mKeyCharacterMap.getEvents(chars);
return events[0].getKeyCode();
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getMatch",
args = {int.class, char[].class, int.class}
)
public void testGetMatch2() throws Exception {
try {
mKeyCharacterMap.getMatch(KeyEvent.KEYCODE_0, null, 1);
fail("should throw exception");
} catch (Exception e) {
}
assertEquals('\0', mKeyCharacterMap.getMatch(1000, chars, 2));
assertEquals('\0', mKeyCharacterMap.getMatch(10000, chars, 2));
assertEquals('\0', mKeyCharacterMap.getMatch(getCharacterKeyCode('E'), chars));
assertEquals('A', mKeyCharacterMap.getMatch(getCharacterKeyCode('A'), chars));
assertEquals('B', mKeyCharacterMap.getMatch(getCharacterKeyCode('B'), chars));
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getKeyboardType",
args = {}
)
public void testGetKeyboardType() throws Exception {
mKeyCharacterMap.getKeyboardType();
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getEvents",
args = {char[].class}
),
@TestTargetNew(
level = TestLevel.NOT_FEASIBLE,
method = "getDisplayLabel",
args = {int.class}
)
})
public void testGetEvents() {
try {
mKeyCharacterMap.getEvents(null);
fail("should throw exception");
} catch (Exception e) {
}
CharSequence mCharSequence = "TestMessage123";
int len = mCharSequence.length();
char[] charsArray = new char[len];
TextUtils.getChars(mCharSequence, 1, len, charsArray, 0);
mKeyCharacterMap.getEvents(charsArray);
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getKeyData",
args = {int.class, android.view.KeyCharacterMap.KeyData.class}
),
@TestTargetNew(
level = TestLevel.NOT_FEASIBLE,
method = "get",
args = {int.class, int.class}
),
@TestTargetNew(
level = TestLevel.NOT_FEASIBLE,
method = "finalize",
args = {}
),
@TestTargetNew(
level = TestLevel.NOT_FEASIBLE,
method = "getDeadChar",
args = {int.class, int.class}
),
@TestTargetNew(
level = TestLevel.SUFFICIENT,
method = "deviceHasKey",
args = {int.class}
),
@TestTargetNew(
level = TestLevel.SUFFICIENT,
method = "deviceHasKeys",
args = {int[].class}
)
})
public void testGetKeyData() throws Exception {
KeyData result = new KeyData();
result.meta = new char[2];
try {
mKeyCharacterMap.getKeyData(KeyEvent.KEYCODE_HOME, result);
fail("should throw exception");
} catch (Exception e) {
}
result.meta = new char[4];
assertFalse(mKeyCharacterMap.getKeyData(KeyEvent.KEYCODE_HOME, result));
assertTrue(mKeyCharacterMap.getKeyData(KeyEvent.KEYCODE_0, result));
assertEquals(48, result.meta[0]);
// here just call deviceHasKey and deviceHasKeys.
KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_0);
final int[] keyChar = new int[] {
KeyEvent.KEYCODE_0, KeyEvent.KEYCODE_1, KeyEvent.KEYCODE_3
};
boolean[] keys = KeyCharacterMap.deviceHasKeys(keyChar);
assertEquals(keyChar.length, keys.length);
}
}
| true | true |
public void testIsPrintingKey() throws Exception {
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_UNKNOWN));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SOFT_LEFT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SOFT_RIGHT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_HOME));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BACK));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CALL));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ENDCALL));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_0));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_1));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_2));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_3));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_4));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_5));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_6));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_7));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_8));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_9));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_STAR));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_POUND));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_DPAD_UP));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_DPAD_DOWN));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_DPAD_LEFT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_DPAD_RIGHT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_DPAD_CENTER));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_VOLUME_UP));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_VOLUME_DOWN));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_POWER));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CAMERA));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CLEAR));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_A));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_B));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_C));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_D));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_E));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_G));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_H));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_I));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_J));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_K));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_L));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_M));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_N));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_O));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_P));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_Q));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_R));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_S));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_T));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_U));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_V));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_W));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_X));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_Y));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_Z));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_COMMA));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PERIOD));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ALT_LEFT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ALT_RIGHT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SHIFT_LEFT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SHIFT_RIGHT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_TAB));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SPACE));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUM));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SYM));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_EXPLORER));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ENVELOPE));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ENTER));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_DEL));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_GRAVE));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MINUS));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_EQUALS));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_LEFT_BRACKET));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_RIGHT_BRACKET));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BACKSLASH));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SEMICOLON));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_APOSTROPHE));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SLASH));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_AT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUM));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_HEADSETHOOK));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PLUS));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MENU));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NOTIFICATION));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SEARCH));
}
|
public void testIsPrintingKey() throws Exception {
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_UNKNOWN));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SOFT_LEFT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SOFT_RIGHT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_HOME));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BACK));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CALL));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ENDCALL));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_0));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_1));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_2));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_3));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_4));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_5));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_6));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_7));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_8));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_9));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_STAR));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_POUND));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_DPAD_UP));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_DPAD_DOWN));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_DPAD_LEFT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_DPAD_RIGHT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_DPAD_CENTER));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_VOLUME_UP));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_VOLUME_DOWN));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_POWER));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CAMERA));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CLEAR));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_A));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_B));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_C));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_D));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_E));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_G));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_H));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_I));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_J));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_K));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_L));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_M));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_N));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_O));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_P));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_Q));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_R));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_S));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_T));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_U));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_V));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_W));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_X));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_Y));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_Z));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_COMMA));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PERIOD));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ALT_LEFT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ALT_RIGHT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SHIFT_LEFT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SHIFT_RIGHT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_TAB));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SPACE));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUM));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_EXPLORER));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ENVELOPE));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ENTER));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_DEL));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_GRAVE));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MINUS));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_EQUALS));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_LEFT_BRACKET));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_RIGHT_BRACKET));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BACKSLASH));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SEMICOLON));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_APOSTROPHE));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SLASH));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_AT));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUM));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_HEADSETHOOK));
assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PLUS));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MENU));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NOTIFICATION));
assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SEARCH));
}
|
diff --git a/Hog/src/front_end/ConsoleLexer.java b/Hog/src/front_end/ConsoleLexer.java
index cd3fc12..d942bb6 100644
--- a/Hog/src/front_end/ConsoleLexer.java
+++ b/Hog/src/front_end/ConsoleLexer.java
@@ -1,71 +1,71 @@
package front_end;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import util.ast.AbstractSyntaxTree;
import util.ast.UntypedAbstractSyntaxTree;
import util.ast.node.BiOpNode;
import util.ast.node.ExpressionNode;
import util.ast.node.IdNode;
import util.ast.node.MockExpressionNode;
import util.ast.node.MockNode;
import util.ast.node.Node;
import util.ast.node.ProgramNode;
import util.type.Types;
import java_cup.parser;
import java_cup.runtime.Scanner;
import java_cup.runtime.Symbol;
import front_end.*;
import java.util.logging.*;
/**
* A console front-end to the Lexer class for dynamically testing the Lexer.
*
* @author sam
*
*/
@SuppressWarnings("unused")
public class ConsoleLexer {
private final static Logger LOGGER = Logger.getLogger(ConsoleLexer.class.getName());
/**
* @param args
* */
public static void main(String[] args) throws IOException {
LOGGER.info("Entering ConsoleLexer main()");
String filename = "WordCount.hog";
ProgramNode root = null;
FileReader fileReader = new FileReader(new File(filename));
try {
// Parser p = new Parser(new Lexer(System.in));
Parser p = new Parser(new Lexer(fileReader));
- root = (ProgramNode) p.parse().value;
+ root = (ProgramNode) p.debug_parse().value;
}
catch (FileNotFoundException e) {
System.out.println("file not found.");
}
catch (Exception ex) {
ex.printStackTrace();
}
AbstractSyntaxTree ast = new UntypedAbstractSyntaxTree(root);
String latexString = ast.toLatex();
FileWriter fstream = new FileWriter("AST_output.tex");
BufferedWriter bout = new BufferedWriter(fstream);
bout.write(latexString);
bout.close();
}
}
| true | true |
public static void main(String[] args) throws IOException {
LOGGER.info("Entering ConsoleLexer main()");
String filename = "WordCount.hog";
ProgramNode root = null;
FileReader fileReader = new FileReader(new File(filename));
try {
// Parser p = new Parser(new Lexer(System.in));
Parser p = new Parser(new Lexer(fileReader));
root = (ProgramNode) p.parse().value;
}
catch (FileNotFoundException e) {
System.out.println("file not found.");
}
catch (Exception ex) {
ex.printStackTrace();
}
AbstractSyntaxTree ast = new UntypedAbstractSyntaxTree(root);
String latexString = ast.toLatex();
FileWriter fstream = new FileWriter("AST_output.tex");
BufferedWriter bout = new BufferedWriter(fstream);
bout.write(latexString);
bout.close();
}
|
public static void main(String[] args) throws IOException {
LOGGER.info("Entering ConsoleLexer main()");
String filename = "WordCount.hog";
ProgramNode root = null;
FileReader fileReader = new FileReader(new File(filename));
try {
// Parser p = new Parser(new Lexer(System.in));
Parser p = new Parser(new Lexer(fileReader));
root = (ProgramNode) p.debug_parse().value;
}
catch (FileNotFoundException e) {
System.out.println("file not found.");
}
catch (Exception ex) {
ex.printStackTrace();
}
AbstractSyntaxTree ast = new UntypedAbstractSyntaxTree(root);
String latexString = ast.toLatex();
FileWriter fstream = new FileWriter("AST_output.tex");
BufferedWriter bout = new BufferedWriter(fstream);
bout.write(latexString);
bout.close();
}
|
diff --git a/Chat/src/info/tregmine/chat/ChatPlayer.java b/Chat/src/info/tregmine/chat/ChatPlayer.java
index ffac1a1..70836bd 100644
--- a/Chat/src/info/tregmine/chat/ChatPlayer.java
+++ b/Chat/src/info/tregmine/chat/ChatPlayer.java
@@ -1,97 +1,97 @@
package info.tregmine.chat;
//import java.util.HashMap;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerChatEvent;
public class ChatPlayer implements Listener {
private final Chat plugin;
public ChatPlayer(Chat instance) {
plugin = instance;
plugin.getServer();
}
@EventHandler
public void onPlayerChat(PlayerChatEvent event) {
Player sender = event.getPlayer();
info.tregmine.api.TregminePlayer tregminePlayer = this.plugin.tregmine.tregminePlayer.get(sender.getName());
Player[] players = plugin.getServer().getOnlinePlayers();
if ( !this.plugin.lasttime.containsKey(tregminePlayer.getId())) {
this.plugin.lasttime.put(tregminePlayer.getId(), 0L);
} else {
- if (this.plugin.lasttime.get(tregminePlayer.getId()) <= this.plugin.lasttime.get(tregminePlayer.getId()) + 3000 ) {
+ if (this.plugin.lasttime.get(tregminePlayer.getId()) <= System.currentTimeMillis() + 3000 ) {
tregminePlayer.sendMessage("SPAMBLOCK TEST *IGNORE IT*, its not yet tuned");
}
}
// if (event.getMessage().equals(this.plugin.lastline.get(sender.getName())) ) {
// }
// if (event.getMessage().equals(this.plugin.lastline.get(sender.getName())) ) {
// sender.getPlayer().sendMessage("No need to repeat yourself!");
// sender.getPlayer().kickPlayer("Don't spam");
// event.setCancelled(true);
// return;
// }
this.plugin.lastline.put(sender.getName(), event.getMessage());
if (!this.plugin.channel.containsKey(sender.getName())) {
this.plugin.channel.put(sender.getName(), "global".toUpperCase());
}
for (Player player : players) {
ChatColor txtColor = ChatColor.WHITE;
if(sender == player) {
txtColor = ChatColor.GRAY;
}
if (!this.plugin.channel.containsKey(player.getName())) {
this.plugin.channel.put(player.getName(), "global".toUpperCase());
}
if (this.plugin.channel.get(sender.getName()).toUpperCase().equals(this.plugin.channel.get(player.getName()).toUpperCase())) {
String channel = this.plugin.channel.get(sender.getName()) + " ";
if (this.plugin.channel.get(sender.getName()).matches("GLOBAL")) {
channel = "";
}
if (event.getMessage().length() > 53) {
int nameLenght = event.getPlayer().getName().length()+5 + channel.length();
String firstMessage = event.getMessage().substring(0, 54 - nameLenght);
String spaces = "";
int firstInt = firstMessage.lastIndexOf(" ");
firstMessage = event.getMessage().substring(0, firstInt);
String lastMessage = event.getMessage().substring (firstInt+1);
for (int i=0; i<nameLenght; i++) {
spaces = spaces + " ";
}
firstMessage = ChatColor.stripColor(firstMessage);
lastMessage = ChatColor.stripColor(lastMessage);
player.sendMessage(channel+"<" + tregminePlayer.getChatName() + ChatColor.WHITE + "> "+ txtColor + firstMessage );
player.sendMessage(txtColor + spaces + lastMessage);
} else {
player.sendMessage(channel+"<" + tregminePlayer.getChatName() + ChatColor.WHITE + "> " + txtColor + event.getMessage().replace(" ", ""));
}
}
}
this.plugin.lasttime.put(tregminePlayer.getId(), System.currentTimeMillis());
plugin.log.info("["+ sender.getWorld().getName() + "]["+ this.plugin.channel.get(sender.getName()) +"]<" + sender.getName() + "> " + event.getMessage() );
event.setCancelled(true);
this.plugin.lasttime.put(tregminePlayer.getId(), 0L);
}
}
| true | true |
public void onPlayerChat(PlayerChatEvent event) {
Player sender = event.getPlayer();
info.tregmine.api.TregminePlayer tregminePlayer = this.plugin.tregmine.tregminePlayer.get(sender.getName());
Player[] players = plugin.getServer().getOnlinePlayers();
if ( !this.plugin.lasttime.containsKey(tregminePlayer.getId())) {
this.plugin.lasttime.put(tregminePlayer.getId(), 0L);
} else {
if (this.plugin.lasttime.get(tregminePlayer.getId()) <= this.plugin.lasttime.get(tregminePlayer.getId()) + 3000 ) {
tregminePlayer.sendMessage("SPAMBLOCK TEST *IGNORE IT*, its not yet tuned");
}
}
// if (event.getMessage().equals(this.plugin.lastline.get(sender.getName())) ) {
// }
// if (event.getMessage().equals(this.plugin.lastline.get(sender.getName())) ) {
// sender.getPlayer().sendMessage("No need to repeat yourself!");
// sender.getPlayer().kickPlayer("Don't spam");
// event.setCancelled(true);
// return;
// }
this.plugin.lastline.put(sender.getName(), event.getMessage());
if (!this.plugin.channel.containsKey(sender.getName())) {
this.plugin.channel.put(sender.getName(), "global".toUpperCase());
}
for (Player player : players) {
ChatColor txtColor = ChatColor.WHITE;
if(sender == player) {
txtColor = ChatColor.GRAY;
}
if (!this.plugin.channel.containsKey(player.getName())) {
this.plugin.channel.put(player.getName(), "global".toUpperCase());
}
if (this.plugin.channel.get(sender.getName()).toUpperCase().equals(this.plugin.channel.get(player.getName()).toUpperCase())) {
String channel = this.plugin.channel.get(sender.getName()) + " ";
if (this.plugin.channel.get(sender.getName()).matches("GLOBAL")) {
channel = "";
}
if (event.getMessage().length() > 53) {
int nameLenght = event.getPlayer().getName().length()+5 + channel.length();
String firstMessage = event.getMessage().substring(0, 54 - nameLenght);
String spaces = "";
int firstInt = firstMessage.lastIndexOf(" ");
firstMessage = event.getMessage().substring(0, firstInt);
String lastMessage = event.getMessage().substring (firstInt+1);
for (int i=0; i<nameLenght; i++) {
spaces = spaces + " ";
}
firstMessage = ChatColor.stripColor(firstMessage);
lastMessage = ChatColor.stripColor(lastMessage);
player.sendMessage(channel+"<" + tregminePlayer.getChatName() + ChatColor.WHITE + "> "+ txtColor + firstMessage );
player.sendMessage(txtColor + spaces + lastMessage);
} else {
player.sendMessage(channel+"<" + tregminePlayer.getChatName() + ChatColor.WHITE + "> " + txtColor + event.getMessage().replace(" ", ""));
}
}
}
this.plugin.lasttime.put(tregminePlayer.getId(), System.currentTimeMillis());
plugin.log.info("["+ sender.getWorld().getName() + "]["+ this.plugin.channel.get(sender.getName()) +"]<" + sender.getName() + "> " + event.getMessage() );
event.setCancelled(true);
this.plugin.lasttime.put(tregminePlayer.getId(), 0L);
}
|
public void onPlayerChat(PlayerChatEvent event) {
Player sender = event.getPlayer();
info.tregmine.api.TregminePlayer tregminePlayer = this.plugin.tregmine.tregminePlayer.get(sender.getName());
Player[] players = plugin.getServer().getOnlinePlayers();
if ( !this.plugin.lasttime.containsKey(tregminePlayer.getId())) {
this.plugin.lasttime.put(tregminePlayer.getId(), 0L);
} else {
if (this.plugin.lasttime.get(tregminePlayer.getId()) <= System.currentTimeMillis() + 3000 ) {
tregminePlayer.sendMessage("SPAMBLOCK TEST *IGNORE IT*, its not yet tuned");
}
}
// if (event.getMessage().equals(this.plugin.lastline.get(sender.getName())) ) {
// }
// if (event.getMessage().equals(this.plugin.lastline.get(sender.getName())) ) {
// sender.getPlayer().sendMessage("No need to repeat yourself!");
// sender.getPlayer().kickPlayer("Don't spam");
// event.setCancelled(true);
// return;
// }
this.plugin.lastline.put(sender.getName(), event.getMessage());
if (!this.plugin.channel.containsKey(sender.getName())) {
this.plugin.channel.put(sender.getName(), "global".toUpperCase());
}
for (Player player : players) {
ChatColor txtColor = ChatColor.WHITE;
if(sender == player) {
txtColor = ChatColor.GRAY;
}
if (!this.plugin.channel.containsKey(player.getName())) {
this.plugin.channel.put(player.getName(), "global".toUpperCase());
}
if (this.plugin.channel.get(sender.getName()).toUpperCase().equals(this.plugin.channel.get(player.getName()).toUpperCase())) {
String channel = this.plugin.channel.get(sender.getName()) + " ";
if (this.plugin.channel.get(sender.getName()).matches("GLOBAL")) {
channel = "";
}
if (event.getMessage().length() > 53) {
int nameLenght = event.getPlayer().getName().length()+5 + channel.length();
String firstMessage = event.getMessage().substring(0, 54 - nameLenght);
String spaces = "";
int firstInt = firstMessage.lastIndexOf(" ");
firstMessage = event.getMessage().substring(0, firstInt);
String lastMessage = event.getMessage().substring (firstInt+1);
for (int i=0; i<nameLenght; i++) {
spaces = spaces + " ";
}
firstMessage = ChatColor.stripColor(firstMessage);
lastMessage = ChatColor.stripColor(lastMessage);
player.sendMessage(channel+"<" + tregminePlayer.getChatName() + ChatColor.WHITE + "> "+ txtColor + firstMessage );
player.sendMessage(txtColor + spaces + lastMessage);
} else {
player.sendMessage(channel+"<" + tregminePlayer.getChatName() + ChatColor.WHITE + "> " + txtColor + event.getMessage().replace(" ", ""));
}
}
}
this.plugin.lasttime.put(tregminePlayer.getId(), System.currentTimeMillis());
plugin.log.info("["+ sender.getWorld().getName() + "]["+ this.plugin.channel.get(sender.getName()) +"]<" + sender.getName() + "> " + event.getMessage() );
event.setCancelled(true);
this.plugin.lasttime.put(tregminePlayer.getId(), 0L);
}
|
diff --git a/cmds/monkey/src/com/android/commands/monkey/Monkey.java b/cmds/monkey/src/com/android/commands/monkey/Monkey.java
index 43103236..bb0663fd 100644
--- a/cmds/monkey/src/com/android/commands/monkey/Monkey.java
+++ b/cmds/monkey/src/com/android/commands/monkey/Monkey.java
@@ -1,992 +1,992 @@
/*
* Copyright 2007, 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.commands.monkey;
import android.app.ActivityManagerNative;
import android.app.IActivityManager;
import android.app.IActivityController;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.IPackageManager;
import android.content.pm.ResolveInfo;
import android.os.Debug;
import android.os.Process;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.server.data.CrashData;
import android.view.IWindowManager;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
/**
* Application that injects random key events and other actions into the system.
*/
public class Monkey {
/**
* Monkey Debugging/Dev Support
* <p>
* All values should be zero when checking in.
*/
private final static int DEBUG_ALLOW_ANY_STARTS = 0;
private final static int DEBUG_ALLOW_ANY_RESTARTS = 0;
private IActivityManager mAm;
private IWindowManager mWm;
private IPackageManager mPm;
/** Command line arguments */
private String[] mArgs;
/** Current argument being parsed */
private int mNextArg;
/** Data of current argument */
private String mCurArgData;
/** Running in verbose output mode? 1= verbose, 2=very verbose */
private int mVerbose;
/** Ignore any application crashes while running? */
private boolean mIgnoreCrashes;
/** Ignore any not responding timeouts while running? */
private boolean mIgnoreTimeouts;
/** Ignore security exceptions when launching activities */
/** (The activity launch still fails, but we keep pluggin' away) */
private boolean mIgnoreSecurityExceptions;
/** Monitor /data/tombstones and stop the monkey if new files appear. */
private boolean mMonitorNativeCrashes;
/** Send no events. Use with long throttle-time to watch user operations */
private boolean mSendNoEvents;
/** This is set when we would like to abort the running of the monkey. */
private boolean mAbort;
/**
* Count each event as a cycle. Set to false for scripts so that each time
* through the script increments the count.
*/
private boolean mCountEvents = true;
/**
* This is set by the ActivityController thread to request collection of ANR
* trace files
*/
private boolean mRequestAnrTraces = false;
/**
* This is set by the ActivityController thread to request a
* "dumpsys meminfo"
*/
private boolean mRequestDumpsysMemInfo = false;
/** Kill the process after a timeout or crash. */
private boolean mKillProcessAfterError;
/** Generate hprof reports before/after monkey runs */
private boolean mGenerateHprof;
/** Packages we are allowed to run, or empty if no restriction. */
private HashSet<String> mValidPackages = new HashSet<String>();
/** Categories we are allowed to launch **/
private ArrayList<String> mMainCategories = new ArrayList<String>();
/** Applications we can switch to. */
private ArrayList<ComponentName> mMainApps = new ArrayList<ComponentName>();
/** The delay between event inputs **/
long mThrottle = 0;
/** The number of iterations **/
int mCount = 1000;
/** The random number seed **/
long mSeed = 0;
/** Dropped-event statistics **/
long mDroppedKeyEvents = 0;
long mDroppedPointerEvents = 0;
long mDroppedTrackballEvents = 0;
long mDroppedFlipEvents = 0;
/** a filename to the setup script (if any) */
private String mSetupFileName = null;
/** filenames of the script (if any) */
private ArrayList<String> mScriptFileNames = new ArrayList<String>();
/** a TCP port to listen on for remote commands. */
private int mServerPort = -1;
private static final File TOMBSTONES_PATH = new File("/data/tombstones");
private HashSet<String> mTombstones = null;
float[] mFactors = new float[MonkeySourceRandom.FACTORZ_COUNT];
MonkeyEventSource mEventSource;
private MonkeyNetworkMonitor mNetworkMonitor = new MonkeyNetworkMonitor();
// information on the current activity.
public static Intent currentIntent;
public static String currentPackage;
/**
* Monitor operations happening in the system.
*/
private class ActivityController extends IActivityController.Stub {
public boolean activityStarting(Intent intent, String pkg) {
boolean allow = checkEnteringPackage(pkg) || (DEBUG_ALLOW_ANY_STARTS != 0);
if (mVerbose > 0) {
System.out.println(" // " + (allow ? "Allowing" : "Rejecting") + " start of "
+ intent + " in package " + pkg);
}
currentPackage = pkg;
currentIntent = intent;
return allow;
}
public boolean activityResuming(String pkg) {
System.out.println(" // activityResuming(" + pkg + ")");
boolean allow = checkEnteringPackage(pkg) || (DEBUG_ALLOW_ANY_RESTARTS != 0);
if (!allow) {
if (mVerbose > 0) {
System.out.println(" // " + (allow ? "Allowing" : "Rejecting")
+ " resume of package " + pkg);
}
}
currentPackage = pkg;
return allow;
}
private boolean checkEnteringPackage(String pkg) {
if (pkg == null) {
return true;
}
// preflight the hash lookup to avoid the cost of hash key
// generation
if (mValidPackages.size() == 0) {
return true;
} else {
return mValidPackages.contains(pkg);
}
}
public boolean appCrashed(String processName, int pid, String shortMsg, String longMsg,
byte[] crashData) {
System.err.println("// CRASH: " + processName + " (pid " + pid + ")");
System.err.println("// Short Msg: " + shortMsg);
System.err.println("// Long Msg: " + longMsg);
if (crashData != null) {
try {
CrashData cd = new CrashData(new DataInputStream(new ByteArrayInputStream(
crashData)));
System.err.println("// Build Label: " + cd.getBuildData().getFingerprint());
System.err.println("// Build Changelist: "
+ cd.getBuildData().getIncrementalVersion());
System.err.println("// Build Time: " + cd.getBuildData().getTime());
System.err.println("// ID: " + cd.getId());
System.err.println("// Tag: " + cd.getActivity());
System.err.println(cd.getThrowableData().toString("// "));
} catch (IOException e) {
System.err.println("// BAD STACK CRAWL");
}
}
if (!mIgnoreCrashes) {
synchronized (Monkey.this) {
mAbort = true;
}
return !mKillProcessAfterError;
}
return false;
}
public int appNotResponding(String processName, int pid, String processStats) {
System.err.println("// NOT RESPONDING: " + processName + " (pid " + pid + ")");
System.err.println(processStats);
reportProcRank();
synchronized (Monkey.this) {
mRequestAnrTraces = true;
mRequestDumpsysMemInfo = true;
}
if (!mIgnoreTimeouts) {
synchronized (Monkey.this) {
mAbort = true;
}
return (mKillProcessAfterError) ? -1 : 1;
}
return 1;
}
}
/**
* Run the procrank tool to insert system status information into the debug
* report.
*/
private void reportProcRank() {
commandLineReport("procrank", "procrank");
}
/**
* Run "cat /data/anr/traces.txt". Wait about 5 seconds first, to let the
* asynchronous report writing complete.
*/
private void reportAnrTraces() {
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
}
commandLineReport("anr traces", "cat /data/anr/traces.txt");
}
/**
* Run "dumpsys meminfo"
* <p>
* NOTE: You cannot perform a dumpsys call from the ActivityController
* callback, as it will deadlock. This should only be called from the main
* loop of the monkey.
*/
private void reportDumpsysMemInfo() {
commandLineReport("meminfo", "dumpsys meminfo");
}
/**
* Print report from a single command line.
* <p>
* TODO: Use ProcessBuilder & redirectErrorStream(true) to capture both
* streams (might be important for some command lines)
*
* @param reportName Simple tag that will print before the report and in
* various annotations.
* @param command Command line to execute.
*/
private void commandLineReport(String reportName, String command) {
System.err.println(reportName + ":");
Runtime rt = Runtime.getRuntime();
try {
// Process must be fully qualified here because android.os.Process
// is used elsewhere
java.lang.Process p = Runtime.getRuntime().exec(command);
// pipe everything from process stdout -> System.err
InputStream inStream = p.getInputStream();
InputStreamReader inReader = new InputStreamReader(inStream);
BufferedReader inBuffer = new BufferedReader(inReader);
String s;
while ((s = inBuffer.readLine()) != null) {
System.err.println(s);
}
int status = p.waitFor();
System.err.println("// " + reportName + " status was " + status);
} catch (Exception e) {
System.err.println("// Exception from " + reportName + ":");
System.err.println(e.toString());
}
}
/**
* Command-line entry point.
*
* @param args The command-line arguments
*/
public static void main(String[] args) {
int resultCode = (new Monkey()).run(args);
System.exit(resultCode);
}
/**
* Run the command!
*
* @param args The command-line arguments
* @return Returns a posix-style result code. 0 for no error.
*/
private int run(String[] args) {
// Super-early debugger wait
for (String s : args) {
if ("--wait-dbg".equals(s)) {
Debug.waitForDebugger();
}
}
// Default values for some command-line options
mVerbose = 0;
mCount = 1000;
mSeed = 0;
mThrottle = 0;
// prepare for command-line processing
mArgs = args;
mNextArg = 0;
// set a positive value, indicating none of the factors is provided yet
for (int i = 0; i < MonkeySourceRandom.FACTORZ_COUNT; i++) {
mFactors[i] = 1.0f;
}
if (!processOptions()) {
return -1;
}
// now set up additional data in preparation for launch
if (mMainCategories.size() == 0) {
mMainCategories.add(Intent.CATEGORY_LAUNCHER);
mMainCategories.add(Intent.CATEGORY_MONKEY);
}
if (mVerbose > 0) {
System.out.println(":Monkey: seed=" + mSeed + " count=" + mCount);
if (mValidPackages.size() > 0) {
Iterator<String> it = mValidPackages.iterator();
while (it.hasNext()) {
System.out.println(":AllowPackage: " + it.next());
}
}
if (mMainCategories.size() != 0) {
Iterator<String> it = mMainCategories.iterator();
while (it.hasNext()) {
System.out.println(":IncludeCategory: " + it.next());
}
}
}
if (!checkInternalConfiguration()) {
return -2;
}
if (!getSystemInterfaces()) {
return -3;
}
if (!getMainApps()) {
return -4;
}
if (mScriptFileNames != null && mScriptFileNames.size() == 1) {
// script mode, ignore other options
mEventSource = new MonkeySourceScript(mScriptFileNames.get(0), mThrottle);
mEventSource.setVerbose(mVerbose);
mCountEvents = false;
- } else if (mScriptFileNames != null) {
+ } else if (mScriptFileNames != null && mScriptFileNames.size() > 1) {
if (mSetupFileName != null) {
mEventSource = new MonkeySourceRandomScript(mSetupFileName, mScriptFileNames,
mThrottle, mSeed);
mCount++;
} else {
mEventSource = new MonkeySourceRandomScript(mScriptFileNames, mThrottle, mSeed);
}
mEventSource.setVerbose(mVerbose);
mCountEvents = false;
} else if (mServerPort != -1) {
try {
mEventSource = new MonkeySourceNetwork(mServerPort);
} catch (IOException e) {
System.out.println("Error binding to network socket.");
return -5;
}
mCount = Integer.MAX_VALUE;
} else {
// random source by default
if (mVerbose >= 2) { // check seeding performance
System.out.println("// Seeded: " + mSeed);
}
mEventSource = new MonkeySourceRandom(mSeed, mMainApps, mThrottle);
mEventSource.setVerbose(mVerbose);
// set any of the factors that has been set
for (int i = 0; i < MonkeySourceRandom.FACTORZ_COUNT; i++) {
if (mFactors[i] <= 0.0f) {
((MonkeySourceRandom) mEventSource).setFactors(i, mFactors[i]);
}
}
// in random mode, we start with a random activity
((MonkeySourceRandom) mEventSource).generateActivity();
}
// validate source generator
if (!mEventSource.validate()) {
return -5;
}
// If we're profiling, do it immediately before/after the main monkey
// loop
if (mGenerateHprof) {
signalPersistentProcesses();
}
mNetworkMonitor.start();
int crashedAtCycle = runMonkeyCycles();
mNetworkMonitor.stop();
synchronized (this) {
if (mRequestAnrTraces) {
reportAnrTraces();
mRequestAnrTraces = false;
}
if (mRequestDumpsysMemInfo) {
reportDumpsysMemInfo();
mRequestDumpsysMemInfo = false;
}
}
if (mGenerateHprof) {
signalPersistentProcesses();
if (mVerbose > 0) {
System.out.println("// Generated profiling reports in /data/misc");
}
}
try {
mAm.setActivityController(null);
mNetworkMonitor.unregister(mAm);
} catch (RemoteException e) {
// just in case this was latent (after mCount cycles), make sure
// we report it
if (crashedAtCycle >= mCount) {
crashedAtCycle = mCount - 1;
}
}
// report dropped event stats
if (mVerbose > 0) {
System.out.print(":Dropped: keys=");
System.out.print(mDroppedKeyEvents);
System.out.print(" pointers=");
System.out.print(mDroppedPointerEvents);
System.out.print(" trackballs=");
System.out.print(mDroppedTrackballEvents);
System.out.print(" flips=");
System.out.println(mDroppedFlipEvents);
}
// report network stats
mNetworkMonitor.dump();
if (crashedAtCycle < mCount - 1) {
System.err.println("** System appears to have crashed at event " + crashedAtCycle
+ " of " + mCount + " using seed " + mSeed);
return crashedAtCycle;
} else {
if (mVerbose > 0) {
System.out.println("// Monkey finished");
}
return 0;
}
}
/**
* Process the command-line options
*
* @return Returns true if options were parsed with no apparent errors.
*/
private boolean processOptions() {
// quick (throwaway) check for unadorned command
if (mArgs.length < 1) {
showUsage();
return false;
}
try {
String opt;
while ((opt = nextOption()) != null) {
if (opt.equals("-s")) {
mSeed = nextOptionLong("Seed");
} else if (opt.equals("-p")) {
mValidPackages.add(nextOptionData());
} else if (opt.equals("-c")) {
mMainCategories.add(nextOptionData());
} else if (opt.equals("-v")) {
mVerbose += 1;
} else if (opt.equals("--ignore-crashes")) {
mIgnoreCrashes = true;
} else if (opt.equals("--ignore-timeouts")) {
mIgnoreTimeouts = true;
} else if (opt.equals("--ignore-security-exceptions")) {
mIgnoreSecurityExceptions = true;
} else if (opt.equals("--monitor-native-crashes")) {
mMonitorNativeCrashes = true;
} else if (opt.equals("--kill-process-after-error")) {
mKillProcessAfterError = true;
} else if (opt.equals("--hprof")) {
mGenerateHprof = true;
} else if (opt.equals("--pct-touch")) {
int i = MonkeySourceRandom.FACTOR_TOUCH;
mFactors[i] = -nextOptionLong("touch events percentage");
} else if (opt.equals("--pct-motion")) {
int i = MonkeySourceRandom.FACTOR_MOTION;
mFactors[i] = -nextOptionLong("motion events percentage");
} else if (opt.equals("--pct-trackball")) {
int i = MonkeySourceRandom.FACTOR_TRACKBALL;
mFactors[i] = -nextOptionLong("trackball events percentage");
} else if (opt.equals("--pct-nav")) {
int i = MonkeySourceRandom.FACTOR_NAV;
mFactors[i] = -nextOptionLong("nav events percentage");
} else if (opt.equals("--pct-majornav")) {
int i = MonkeySourceRandom.FACTOR_MAJORNAV;
mFactors[i] = -nextOptionLong("major nav events percentage");
} else if (opt.equals("--pct-appswitch")) {
int i = MonkeySourceRandom.FACTOR_APPSWITCH;
mFactors[i] = -nextOptionLong("app switch events percentage");
} else if (opt.equals("--pct-flip")) {
int i = MonkeySourceRandom.FACTOR_FLIP;
mFactors[i] = -nextOptionLong("keyboard flip percentage");
} else if (opt.equals("--pct-anyevent")) {
int i = MonkeySourceRandom.FACTOR_ANYTHING;
mFactors[i] = -nextOptionLong("any events percentage");
} else if (opt.equals("--throttle")) {
mThrottle = nextOptionLong("delay (in milliseconds) to wait between events");
} else if (opt.equals("--wait-dbg")) {
// do nothing - it's caught at the very start of run()
} else if (opt.equals("--dbg-no-events")) {
mSendNoEvents = true;
} else if (opt.equals("--port")) {
mServerPort = (int) nextOptionLong("Server port to listen on for commands");
} else if (opt.equals("--setup")) {
mSetupFileName = nextOptionData();
} else if (opt.equals("-f")) {
mScriptFileNames.add(nextOptionData());
} else if (opt.equals("-h")) {
showUsage();
return false;
} else {
System.err.println("** Error: Unknown option: " + opt);
showUsage();
return false;
}
}
} catch (RuntimeException ex) {
System.err.println("** Error: " + ex.toString());
showUsage();
return false;
}
// If a server port hasn't been specified, we need to specify
// a count
if (mServerPort == -1) {
String countStr = nextArg();
if (countStr == null) {
System.err.println("** Error: Count not specified");
showUsage();
return false;
}
try {
mCount = Integer.parseInt(countStr);
} catch (NumberFormatException e) {
System.err.println("** Error: Count is not a number");
showUsage();
return false;
}
}
return true;
}
/**
* Check for any internal configuration (primarily build-time) errors.
*
* @return Returns true if ready to rock.
*/
private boolean checkInternalConfiguration() {
// Check KEYCODE name array, make sure it's up to date.
String lastKeyName = null;
try {
lastKeyName = MonkeySourceRandom.getLastKeyName();
} catch (RuntimeException e) {
}
if (!"TAG_LAST_KEYCODE".equals(lastKeyName)) {
System.err.println("** Error: Key names array malformed (internal error).");
return false;
}
return true;
}
/**
* Attach to the required system interfaces.
*
* @return Returns true if all system interfaces were available.
*/
private boolean getSystemInterfaces() {
mAm = ActivityManagerNative.getDefault();
if (mAm == null) {
System.err.println("** Error: Unable to connect to activity manager; is the system "
+ "running?");
return false;
}
mWm = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
if (mWm == null) {
System.err.println("** Error: Unable to connect to window manager; is the system "
+ "running?");
return false;
}
mPm = IPackageManager.Stub.asInterface(ServiceManager.getService("package"));
if (mPm == null) {
System.err.println("** Error: Unable to connect to package manager; is the system "
+ "running?");
return false;
}
try {
mAm.setActivityController(new ActivityController());
mNetworkMonitor.register(mAm);
} catch (RemoteException e) {
System.err.println("** Failed talking with activity manager!");
return false;
}
return true;
}
/**
* Using the restrictions provided (categories & packages), generate a list
* of activities that we can actually switch to.
*
* @return Returns true if it could successfully build a list of target
* activities
*/
private boolean getMainApps() {
try {
final int N = mMainCategories.size();
for (int i = 0; i < N; i++) {
Intent intent = new Intent(Intent.ACTION_MAIN);
String category = mMainCategories.get(i);
if (category.length() > 0) {
intent.addCategory(category);
}
List<ResolveInfo> mainApps = mPm.queryIntentActivities(intent, null, 0);
if (mainApps == null || mainApps.size() == 0) {
System.err.println("// Warning: no activities found for category " + category);
continue;
}
if (mVerbose >= 2) { // very verbose
System.out.println("// Selecting main activities from category " + category);
}
final int NA = mainApps.size();
for (int a = 0; a < NA; a++) {
ResolveInfo r = mainApps.get(a);
if (mValidPackages.size() == 0
|| mValidPackages.contains(r.activityInfo.applicationInfo.packageName)) {
if (mVerbose >= 2) { // very verbose
System.out.println("// + Using main activity " + r.activityInfo.name
+ " (from package "
+ r.activityInfo.applicationInfo.packageName + ")");
}
mMainApps.add(new ComponentName(r.activityInfo.applicationInfo.packageName,
r.activityInfo.name));
} else {
if (mVerbose >= 3) { // very very verbose
System.out.println("// - NOT USING main activity "
+ r.activityInfo.name + " (from package "
+ r.activityInfo.applicationInfo.packageName + ")");
}
}
}
}
} catch (RemoteException e) {
System.err.println("** Failed talking with package manager!");
return false;
}
if (mMainApps.size() == 0) {
System.out.println("** No activities found to run, monkey aborted.");
return false;
}
return true;
}
/**
* Run mCount cycles and see if we hit any crashers.
* <p>
* TODO: Meta state on keys
*
* @return Returns the last cycle which executed. If the value == mCount, no
* errors detected.
*/
private int runMonkeyCycles() {
int eventCounter = 0;
int cycleCounter = 0;
boolean systemCrashed = false;
while (!systemCrashed && cycleCounter < mCount) {
synchronized (this) {
if (mRequestAnrTraces) {
reportAnrTraces();
mRequestAnrTraces = false;
}
if (mRequestDumpsysMemInfo) {
reportDumpsysMemInfo();
mRequestDumpsysMemInfo = false;
}
if (mMonitorNativeCrashes) {
// first time through, when eventCounter == 0, just set up
// the watcher (ignore the error)
if (checkNativeCrashes() && (eventCounter > 0)) {
System.out.println("** New native crash detected.");
mAbort = mAbort || mKillProcessAfterError;
}
}
if (mAbort) {
System.out.println("** Monkey aborted due to error.");
System.out.println("Events injected: " + eventCounter);
return eventCounter;
}
}
// In this debugging mode, we never send any events. This is
// primarily here so you can manually test the package or category
// limits, while manually exercising the system.
if (mSendNoEvents) {
eventCounter++;
cycleCounter++;
continue;
}
if ((mVerbose > 0) && (eventCounter % 100) == 0 && eventCounter != 0) {
System.out.println(" // Sending event #" + eventCounter);
}
MonkeyEvent ev = mEventSource.getNextEvent();
if (ev != null) {
int injectCode = ev.injectEvent(mWm, mAm, mVerbose);
if (injectCode == MonkeyEvent.INJECT_FAIL) {
if (ev instanceof MonkeyKeyEvent) {
mDroppedKeyEvents++;
} else if (ev instanceof MonkeyMotionEvent) {
mDroppedPointerEvents++;
} else if (ev instanceof MonkeyFlipEvent) {
mDroppedFlipEvents++;
}
} else if (injectCode == MonkeyEvent.INJECT_ERROR_REMOTE_EXCEPTION) {
systemCrashed = true;
} else if (injectCode == MonkeyEvent.INJECT_ERROR_SECURITY_EXCEPTION) {
systemCrashed = !mIgnoreSecurityExceptions;
}
// Don't count throttling as an event.
if (!(ev instanceof MonkeyThrottleEvent)) {
eventCounter++;
if (mCountEvents) {
cycleCounter++;
}
}
} else {
if (!mCountEvents) {
cycleCounter++;
} else {
break;
}
}
}
// If we got this far, we succeeded!
return eventCounter;
}
/**
* Send SIGNAL_USR1 to all processes. This will generate large (5mb)
* profiling reports in data/misc, so use with care.
*/
private void signalPersistentProcesses() {
try {
mAm.signalPersistentProcesses(Process.SIGNAL_USR1);
synchronized (this) {
wait(2000);
}
} catch (RemoteException e) {
System.err.println("** Failed talking with activity manager!");
} catch (InterruptedException e) {
}
}
/**
* Watch for appearance of new tombstone files, which indicate native
* crashes.
*
* @return Returns true if new files have appeared in the list
*/
private boolean checkNativeCrashes() {
String[] tombstones = TOMBSTONES_PATH.list();
// shortcut path for usually empty directory, so we don't waste even
// more objects
if ((tombstones == null) || (tombstones.length == 0)) {
mTombstones = null;
return false;
}
// use set logic to look for new files
HashSet<String> newStones = new HashSet<String>();
for (String x : tombstones) {
newStones.add(x);
}
boolean result = (mTombstones == null) || !mTombstones.containsAll(newStones);
// keep the new list for the next time
mTombstones = newStones;
return result;
}
/**
* Return the next command line option. This has a number of special cases
* which closely, but not exactly, follow the POSIX command line options
* patterns:
*
* <pre>
* -- means to stop processing additional options
* -z means option z
* -z ARGS means option z with (non-optional) arguments ARGS
* -zARGS means option z with (optional) arguments ARGS
* --zz means option zz
* --zz ARGS means option zz with (non-optional) arguments ARGS
* </pre>
*
* Note that you cannot combine single letter options; -abc != -a -b -c
*
* @return Returns the option string, or null if there are no more options.
*/
private String nextOption() {
if (mNextArg >= mArgs.length) {
return null;
}
String arg = mArgs[mNextArg];
if (!arg.startsWith("-")) {
return null;
}
mNextArg++;
if (arg.equals("--")) {
return null;
}
if (arg.length() > 1 && arg.charAt(1) != '-') {
if (arg.length() > 2) {
mCurArgData = arg.substring(2);
return arg.substring(0, 2);
} else {
mCurArgData = null;
return arg;
}
}
mCurArgData = null;
return arg;
}
/**
* Return the next data associated with the current option.
*
* @return Returns the data string, or null of there are no more arguments.
*/
private String nextOptionData() {
if (mCurArgData != null) {
return mCurArgData;
}
if (mNextArg >= mArgs.length) {
return null;
}
String data = mArgs[mNextArg];
mNextArg++;
return data;
}
/**
* Returns a long converted from the next data argument, with error handling
* if not available.
*
* @param opt The name of the option.
* @return Returns a long converted from the argument.
*/
private long nextOptionLong(final String opt) {
long result;
try {
result = Long.parseLong(nextOptionData());
} catch (NumberFormatException e) {
System.err.println("** Error: " + opt + " is not a number");
throw e;
}
return result;
}
/**
* Return the next argument on the command line.
*
* @return Returns the argument string, or null if we have reached the end.
*/
private String nextArg() {
if (mNextArg >= mArgs.length) {
return null;
}
String arg = mArgs[mNextArg];
mNextArg++;
return arg;
}
/**
* Print how to use this command.
*/
private void showUsage() {
StringBuffer usage = new StringBuffer();
usage.append("usage: monkey [-p ALLOWED_PACKAGE [-p ALLOWED_PACKAGE] ...]\n");
usage.append(" [-c MAIN_CATEGORY [-c MAIN_CATEGORY] ...]\n");
usage.append(" [--ignore-crashes] [--ignore-timeouts]\n");
usage.append(" [--ignore-security-exceptions] [--monitor-native-crashes]\n");
usage.append(" [--kill-process-after-error] [--hprof]\n");
usage.append(" [--pct-touch PERCENT] [--pct-motion PERCENT]\n");
usage.append(" [--pct-trackball PERCENT] [--pct-syskeys PERCENT]\n");
usage.append(" [--pct-nav PERCENT] [--pct-majornav PERCENT]\n");
usage.append(" [--pct-appswitch PERCENT] [--pct-flip PERCENT]\n");
usage.append(" [--pct-anyevent PERCENT]\n");
usage.append(" [--wait-dbg] [--dbg-no-events]\n");
usage.append(" [--setup scriptfile] [-f scriptfile [-f scriptfile] ...]\n");
usage.append(" [--port port]\n");
usage.append(" [-s SEED] [-v [-v] ...] [--throttle MILLISEC]\n");
usage.append(" COUNT");
System.err.println(usage.toString());
}
}
| true | true |
private int run(String[] args) {
// Super-early debugger wait
for (String s : args) {
if ("--wait-dbg".equals(s)) {
Debug.waitForDebugger();
}
}
// Default values for some command-line options
mVerbose = 0;
mCount = 1000;
mSeed = 0;
mThrottle = 0;
// prepare for command-line processing
mArgs = args;
mNextArg = 0;
// set a positive value, indicating none of the factors is provided yet
for (int i = 0; i < MonkeySourceRandom.FACTORZ_COUNT; i++) {
mFactors[i] = 1.0f;
}
if (!processOptions()) {
return -1;
}
// now set up additional data in preparation for launch
if (mMainCategories.size() == 0) {
mMainCategories.add(Intent.CATEGORY_LAUNCHER);
mMainCategories.add(Intent.CATEGORY_MONKEY);
}
if (mVerbose > 0) {
System.out.println(":Monkey: seed=" + mSeed + " count=" + mCount);
if (mValidPackages.size() > 0) {
Iterator<String> it = mValidPackages.iterator();
while (it.hasNext()) {
System.out.println(":AllowPackage: " + it.next());
}
}
if (mMainCategories.size() != 0) {
Iterator<String> it = mMainCategories.iterator();
while (it.hasNext()) {
System.out.println(":IncludeCategory: " + it.next());
}
}
}
if (!checkInternalConfiguration()) {
return -2;
}
if (!getSystemInterfaces()) {
return -3;
}
if (!getMainApps()) {
return -4;
}
if (mScriptFileNames != null && mScriptFileNames.size() == 1) {
// script mode, ignore other options
mEventSource = new MonkeySourceScript(mScriptFileNames.get(0), mThrottle);
mEventSource.setVerbose(mVerbose);
mCountEvents = false;
} else if (mScriptFileNames != null) {
if (mSetupFileName != null) {
mEventSource = new MonkeySourceRandomScript(mSetupFileName, mScriptFileNames,
mThrottle, mSeed);
mCount++;
} else {
mEventSource = new MonkeySourceRandomScript(mScriptFileNames, mThrottle, mSeed);
}
mEventSource.setVerbose(mVerbose);
mCountEvents = false;
} else if (mServerPort != -1) {
try {
mEventSource = new MonkeySourceNetwork(mServerPort);
} catch (IOException e) {
System.out.println("Error binding to network socket.");
return -5;
}
mCount = Integer.MAX_VALUE;
} else {
// random source by default
if (mVerbose >= 2) { // check seeding performance
System.out.println("// Seeded: " + mSeed);
}
mEventSource = new MonkeySourceRandom(mSeed, mMainApps, mThrottle);
mEventSource.setVerbose(mVerbose);
// set any of the factors that has been set
for (int i = 0; i < MonkeySourceRandom.FACTORZ_COUNT; i++) {
if (mFactors[i] <= 0.0f) {
((MonkeySourceRandom) mEventSource).setFactors(i, mFactors[i]);
}
}
// in random mode, we start with a random activity
((MonkeySourceRandom) mEventSource).generateActivity();
}
// validate source generator
if (!mEventSource.validate()) {
return -5;
}
// If we're profiling, do it immediately before/after the main monkey
// loop
if (mGenerateHprof) {
signalPersistentProcesses();
}
mNetworkMonitor.start();
int crashedAtCycle = runMonkeyCycles();
mNetworkMonitor.stop();
synchronized (this) {
if (mRequestAnrTraces) {
reportAnrTraces();
mRequestAnrTraces = false;
}
if (mRequestDumpsysMemInfo) {
reportDumpsysMemInfo();
mRequestDumpsysMemInfo = false;
}
}
if (mGenerateHprof) {
signalPersistentProcesses();
if (mVerbose > 0) {
System.out.println("// Generated profiling reports in /data/misc");
}
}
try {
mAm.setActivityController(null);
mNetworkMonitor.unregister(mAm);
} catch (RemoteException e) {
// just in case this was latent (after mCount cycles), make sure
// we report it
if (crashedAtCycle >= mCount) {
crashedAtCycle = mCount - 1;
}
}
// report dropped event stats
if (mVerbose > 0) {
System.out.print(":Dropped: keys=");
System.out.print(mDroppedKeyEvents);
System.out.print(" pointers=");
System.out.print(mDroppedPointerEvents);
System.out.print(" trackballs=");
System.out.print(mDroppedTrackballEvents);
System.out.print(" flips=");
System.out.println(mDroppedFlipEvents);
}
// report network stats
mNetworkMonitor.dump();
if (crashedAtCycle < mCount - 1) {
System.err.println("** System appears to have crashed at event " + crashedAtCycle
+ " of " + mCount + " using seed " + mSeed);
return crashedAtCycle;
} else {
if (mVerbose > 0) {
System.out.println("// Monkey finished");
}
return 0;
}
}
|
private int run(String[] args) {
// Super-early debugger wait
for (String s : args) {
if ("--wait-dbg".equals(s)) {
Debug.waitForDebugger();
}
}
// Default values for some command-line options
mVerbose = 0;
mCount = 1000;
mSeed = 0;
mThrottle = 0;
// prepare for command-line processing
mArgs = args;
mNextArg = 0;
// set a positive value, indicating none of the factors is provided yet
for (int i = 0; i < MonkeySourceRandom.FACTORZ_COUNT; i++) {
mFactors[i] = 1.0f;
}
if (!processOptions()) {
return -1;
}
// now set up additional data in preparation for launch
if (mMainCategories.size() == 0) {
mMainCategories.add(Intent.CATEGORY_LAUNCHER);
mMainCategories.add(Intent.CATEGORY_MONKEY);
}
if (mVerbose > 0) {
System.out.println(":Monkey: seed=" + mSeed + " count=" + mCount);
if (mValidPackages.size() > 0) {
Iterator<String> it = mValidPackages.iterator();
while (it.hasNext()) {
System.out.println(":AllowPackage: " + it.next());
}
}
if (mMainCategories.size() != 0) {
Iterator<String> it = mMainCategories.iterator();
while (it.hasNext()) {
System.out.println(":IncludeCategory: " + it.next());
}
}
}
if (!checkInternalConfiguration()) {
return -2;
}
if (!getSystemInterfaces()) {
return -3;
}
if (!getMainApps()) {
return -4;
}
if (mScriptFileNames != null && mScriptFileNames.size() == 1) {
// script mode, ignore other options
mEventSource = new MonkeySourceScript(mScriptFileNames.get(0), mThrottle);
mEventSource.setVerbose(mVerbose);
mCountEvents = false;
} else if (mScriptFileNames != null && mScriptFileNames.size() > 1) {
if (mSetupFileName != null) {
mEventSource = new MonkeySourceRandomScript(mSetupFileName, mScriptFileNames,
mThrottle, mSeed);
mCount++;
} else {
mEventSource = new MonkeySourceRandomScript(mScriptFileNames, mThrottle, mSeed);
}
mEventSource.setVerbose(mVerbose);
mCountEvents = false;
} else if (mServerPort != -1) {
try {
mEventSource = new MonkeySourceNetwork(mServerPort);
} catch (IOException e) {
System.out.println("Error binding to network socket.");
return -5;
}
mCount = Integer.MAX_VALUE;
} else {
// random source by default
if (mVerbose >= 2) { // check seeding performance
System.out.println("// Seeded: " + mSeed);
}
mEventSource = new MonkeySourceRandom(mSeed, mMainApps, mThrottle);
mEventSource.setVerbose(mVerbose);
// set any of the factors that has been set
for (int i = 0; i < MonkeySourceRandom.FACTORZ_COUNT; i++) {
if (mFactors[i] <= 0.0f) {
((MonkeySourceRandom) mEventSource).setFactors(i, mFactors[i]);
}
}
// in random mode, we start with a random activity
((MonkeySourceRandom) mEventSource).generateActivity();
}
// validate source generator
if (!mEventSource.validate()) {
return -5;
}
// If we're profiling, do it immediately before/after the main monkey
// loop
if (mGenerateHprof) {
signalPersistentProcesses();
}
mNetworkMonitor.start();
int crashedAtCycle = runMonkeyCycles();
mNetworkMonitor.stop();
synchronized (this) {
if (mRequestAnrTraces) {
reportAnrTraces();
mRequestAnrTraces = false;
}
if (mRequestDumpsysMemInfo) {
reportDumpsysMemInfo();
mRequestDumpsysMemInfo = false;
}
}
if (mGenerateHprof) {
signalPersistentProcesses();
if (mVerbose > 0) {
System.out.println("// Generated profiling reports in /data/misc");
}
}
try {
mAm.setActivityController(null);
mNetworkMonitor.unregister(mAm);
} catch (RemoteException e) {
// just in case this was latent (after mCount cycles), make sure
// we report it
if (crashedAtCycle >= mCount) {
crashedAtCycle = mCount - 1;
}
}
// report dropped event stats
if (mVerbose > 0) {
System.out.print(":Dropped: keys=");
System.out.print(mDroppedKeyEvents);
System.out.print(" pointers=");
System.out.print(mDroppedPointerEvents);
System.out.print(" trackballs=");
System.out.print(mDroppedTrackballEvents);
System.out.print(" flips=");
System.out.println(mDroppedFlipEvents);
}
// report network stats
mNetworkMonitor.dump();
if (crashedAtCycle < mCount - 1) {
System.err.println("** System appears to have crashed at event " + crashedAtCycle
+ " of " + mCount + " using seed " + mSeed);
return crashedAtCycle;
} else {
if (mVerbose > 0) {
System.out.println("// Monkey finished");
}
return 0;
}
}
|
diff --git a/jaxrs/server-adapters/resteasy-netty4/src/main/java/org/jboss/resteasy/plugins/server/netty/RequestHandler.java b/jaxrs/server-adapters/resteasy-netty4/src/main/java/org/jboss/resteasy/plugins/server/netty/RequestHandler.java
index 757a32b02..a9418bc21 100755
--- a/jaxrs/server-adapters/resteasy-netty4/src/main/java/org/jboss/resteasy/plugins/server/netty/RequestHandler.java
+++ b/jaxrs/server-adapters/resteasy-netty4/src/main/java/org/jboss/resteasy/plugins/server/netty/RequestHandler.java
@@ -1,110 +1,108 @@
package org.jboss.resteasy.plugins.server.netty;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.TooLongFrameException;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpResponse;
import org.jboss.resteasy.logging.Logger;
import org.jboss.resteasy.spi.Failure;
import static io.netty.handler.codec.http.HttpResponseStatus.CONTINUE;
import static io.netty.handler.codec.http.HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
/**
* {@link SimpleChannelInboundHandler} which handles the requests and dispatch them.
*
* This class is {@link Sharable}.
*
* @author <a href="http://www.jboss.org/netty/">The Netty Project</a>
* @author Andy Taylor ([email protected])
* @author <a href="http://gleamynode.net/">Trustin Lee</a>
* @author Norman Maurer
* @version $Rev: 2368 $, $Date: 2010-10-18 17:19:03 +0900 (Mon, 18 Oct 2010) $
*/
@Sharable
public class RequestHandler extends SimpleChannelInboundHandler
{
protected final RequestDispatcher dispatcher;
private final static Logger logger = Logger.getLogger(RequestHandler.class);
public RequestHandler(RequestDispatcher dispatcher)
{
this.dispatcher = dispatcher;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception
{
if (msg instanceof NettyHttpRequest) {
NettyHttpRequest request = (NettyHttpRequest) msg;
if (request.is100ContinueExpected())
{
send100Continue(ctx);
}
NettyHttpResponse response = request.getResponse();
try
{
dispatcher.service(request, response, true);
}
catch (Failure e1)
{
response.reset();
response.setStatus(e1.getErrorCode());
- return;
}
catch (Exception ex)
{
response.reset();
response.setStatus(500);
logger.error("Unexpected", ex);
- return;
}
ChannelFuture future = null;
if (!request.getAsyncContext().isSuspended()) {
// Write and flush the response.
future = ctx.writeAndFlush(response);
} else {
// Write an empty response
//future = ctx.write(response);
// retain buffer since it was automatically
// reference counted by the write operation above
//response.retain();
}
// Close the non-keep-alive connection after the write operation is done.
if (!request.isKeepAlive())
{
future.addListener(ChannelFutureListener.CLOSE);
}
}
}
private void send100Continue(ChannelHandlerContext ctx)
{
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, CONTINUE);
ctx.writeAndFlush(response);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e)
throws Exception
{
// handle the case of to big requests.
if (e.getCause() instanceof TooLongFrameException)
{
DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, REQUEST_ENTITY_TOO_LARGE);
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
}
else
{
e.getCause().printStackTrace();
ctx.close();
}
}
}
| false | true |
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception
{
if (msg instanceof NettyHttpRequest) {
NettyHttpRequest request = (NettyHttpRequest) msg;
if (request.is100ContinueExpected())
{
send100Continue(ctx);
}
NettyHttpResponse response = request.getResponse();
try
{
dispatcher.service(request, response, true);
}
catch (Failure e1)
{
response.reset();
response.setStatus(e1.getErrorCode());
return;
}
catch (Exception ex)
{
response.reset();
response.setStatus(500);
logger.error("Unexpected", ex);
return;
}
ChannelFuture future = null;
if (!request.getAsyncContext().isSuspended()) {
// Write and flush the response.
future = ctx.writeAndFlush(response);
} else {
// Write an empty response
//future = ctx.write(response);
// retain buffer since it was automatically
// reference counted by the write operation above
//response.retain();
}
// Close the non-keep-alive connection after the write operation is done.
if (!request.isKeepAlive())
{
future.addListener(ChannelFutureListener.CLOSE);
}
}
}
|
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception
{
if (msg instanceof NettyHttpRequest) {
NettyHttpRequest request = (NettyHttpRequest) msg;
if (request.is100ContinueExpected())
{
send100Continue(ctx);
}
NettyHttpResponse response = request.getResponse();
try
{
dispatcher.service(request, response, true);
}
catch (Failure e1)
{
response.reset();
response.setStatus(e1.getErrorCode());
}
catch (Exception ex)
{
response.reset();
response.setStatus(500);
logger.error("Unexpected", ex);
}
ChannelFuture future = null;
if (!request.getAsyncContext().isSuspended()) {
// Write and flush the response.
future = ctx.writeAndFlush(response);
} else {
// Write an empty response
//future = ctx.write(response);
// retain buffer since it was automatically
// reference counted by the write operation above
//response.retain();
}
// Close the non-keep-alive connection after the write operation is done.
if (!request.isKeepAlive())
{
future.addListener(ChannelFutureListener.CLOSE);
}
}
}
|
diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/search/lucene/LuceneSetup.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/search/lucene/LuceneSetup.java
index 37b4100dc..ac4cfcca4 100644
--- a/webapp/src/edu/cornell/mannlib/vitro/webapp/search/lucene/LuceneSetup.java
+++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/search/lucene/LuceneSetup.java
@@ -1,230 +1,232 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.search.lucene;
import static edu.cornell.mannlib.vitro.webapp.search.lucene.Entity2LuceneDoc.VitroLuceneTermNames.ALLTEXT;
import static edu.cornell.mannlib.vitro.webapp.search.lucene.Entity2LuceneDoc.VitroLuceneTermNames.ALLTEXTUNSTEMMED;
import static edu.cornell.mannlib.vitro.webapp.search.lucene.Entity2LuceneDoc.VitroLuceneTermNames.NAME;
import static edu.cornell.mannlib.vitro.webapp.search.lucene.Entity2LuceneDoc.VitroLuceneTermNames.NAMEUNSTEMMED;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.KeywordAnalyzer;
import org.apache.lucene.analysis.PerFieldAnalyzerWrapper;
import org.apache.lucene.search.BooleanQuery;
import com.hp.hpl.jena.ontology.OntModel;
import edu.cornell.mannlib.vitro.webapp.ConfigurationProperties;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.filtering.WebappDaoFactoryFiltering;
import edu.cornell.mannlib.vitro.webapp.dao.filtering.filters.VitroFilterUtils;
import edu.cornell.mannlib.vitro.webapp.dao.filtering.filters.VitroFilters;
import edu.cornell.mannlib.vitro.webapp.dao.jena.SearchReindexingListener;
import edu.cornell.mannlib.vitro.webapp.search.beans.ObjectSourceIface;
import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch;
import edu.cornell.mannlib.vitro.webapp.search.beans.Searcher;
import edu.cornell.mannlib.vitro.webapp.search.indexing.IndexBuilder;
import edu.cornell.mannlib.vitro.webapp.web.DisplayVocabulary;
/**
* Setup objects for lucene searching and indexing.
*
* The indexing and search objects, IndexBuilder and Searcher are found by the
* controllers IndexController and SearchController through the servletContext.
* This object will have the method contextInitialized() called when the tomcat
* server starts this webapp.
*
* The contextInitialized() will try to find the lucene index directory,
* make a LueceneIndexer and a LuceneSearcher. The LuceneIndexer will
* also get a list of Obj2Doc objects so it can translate object to lucene docs.
*
* To execute this at context creation put this in web.xml:
<listener>
<listener-class>
edu.cornell.mannlib.vitro.search.setup.LuceneSetup
</listener-class>
</listener>
* @author bdc34
*
*/
public class LuceneSetup implements javax.servlet.ServletContextListener {
private static String indexDir = null;
private static final Log log = LogFactory.getLog(LuceneSetup.class.getName());
/**
* Gets run to set up DataSource when the webapp servlet context gets
* created.
*/
public void contextInitialized(ServletContextEvent sce) {
try {
ServletContext context = sce.getServletContext();
log.debug("**** Running " + this.getClass().getName() + ".contextInitialized()");
indexDir = getIndexDirName();
log.info("Directory of full text index: " + indexDir);
setBoolMax();
// these should really be set as annotation properties.
HashSet<String> dataPropertyBlacklist = new HashSet<String>();
context.setAttribute(SEARCH_DATAPROPERTY_BLACKLIST, dataPropertyBlacklist);
HashSet<String> objectPropertyBlacklist = new HashSet<String>();
objectPropertyBlacklist.add("http://www.w3.org/2002/07/owl#differentFrom");
context.setAttribute(SEARCH_OBJECTPROPERTY_BLACKLIST, objectPropertyBlacklist);
// Here we want to put the LuceneIndex object into the application scope.
// This will attempt to create a new directory and empty index if there is none.
LuceneIndexer indexer = new LuceneIndexer(indexDir, null, getAnalyzer());
context.setAttribute(ANALYZER, getAnalyzer());
context.setAttribute(INDEX_DIR, indexDir);
indexer.addObj2Doc(new Entity2LuceneDoc());
context.setAttribute(LuceneIndexer.class.getName(), indexer);
// Here we want to put the LuceneSearcher in the application scope.
// the queries need to know the analyzer to use so that the same one can be used
// to analyze the fields in the incoming user query terms.
LuceneSearcher searcher = new LuceneSearcher(
new LuceneQueryFactory(getAnalyzer(), ALLTEXT), indexDir);
searcher.addObj2Doc(new Entity2LuceneDoc());
context.setAttribute(Searcher.class.getName(), searcher);
indexer.addSearcher(searcher);
// This is where the builder gets the list of places to try to
// get objects to index. It is filtered so that non-public text
// does not get into the search index.
WebappDaoFactory wadf = (WebappDaoFactory) context.getAttribute("webappDaoFactory");
VitroFilters vf = VitroFilterUtils.getDisplayFilterByRoleLevel(RoleLevel.PUBLIC, wadf);
wadf = new WebappDaoFactoryFiltering(wadf, vf);
List<ObjectSourceIface> sources = new ArrayList<ObjectSourceIface>();
sources.add(wadf.getIndividualDao());
IndexBuilder builder = new IndexBuilder(context, indexer, sources);
// here we add the IndexBuilder with the LuceneIndexer
// to the servlet context so we can access it later in the webapp.
context.setAttribute(IndexBuilder.class.getName(), builder);
// set up listeners so search index builder is notified of changes to model
OntModel baseOntModel = (OntModel) sce.getServletContext().getAttribute("baseOntModel");
OntModel jenaOntModel = (OntModel) sce.getServletContext().getAttribute("jenaOntModel");
OntModel inferenceModel = (OntModel) sce.getServletContext().getAttribute("inferenceOntModel");
SearchReindexingListener srl = new SearchReindexingListener(builder);
baseOntModel.getBaseModel().register(srl);
jenaOntModel.getBaseModel().register(srl);
inferenceModel.register(srl);
// set the classes that the indexBuilder ignores
OntModel displayOntModel = (OntModel) sce.getServletContext().getAttribute("displayOntModel");
builder.setClassesProhibitedFromSearch(
new ProhibitedFromSearch(DisplayVocabulary.PRIMARY_LUCENE_INDEX_URI, displayOntModel));
if( (Boolean)sce.getServletContext().getAttribute(INDEX_REBUILD_REQUESTED_AT_STARTUP) instanceof Boolean &&
(Boolean)sce.getServletContext().getAttribute(INDEX_REBUILD_REQUESTED_AT_STARTUP) ){
builder.doIndexRebuild();
log.info("Rebuild of search index required before startup.");
+ int n = 0;
while( builder.isIndexing() ){
- Thread.currentThread().sleep(200);
- log.info("Still rebulding search index");
+ Thread.currentThread().sleep(500);
+ if( n % 20 == 0 ) //output message every 10 sec.
+ log.info("Still rebulding search index");
}
log.info("Search index rebuild completed.");
}
log.debug("**** End of " + this.getClass().getName() + ".contextInitialized()");
} catch (Throwable t) {
log.error("***** Error setting up Lucene search *****", t);
}
}
/**
* Gets run when the webApp Context gets destroyed.
*/
public void contextDestroyed(ServletContextEvent sce) {
log.debug("**** Running " + this.getClass().getName() + ".contextDestroyed()");
IndexBuilder builder = (IndexBuilder) sce.getServletContext().getAttribute(IndexBuilder.class.getName());
builder.killIndexingThread();
}
/**
* In wild card searches the query is first broken into many boolean
* searches OR'ed together. So if there is a query that would match a lot of
* records we need a high max boolean limit for the lucene search.
*
* This sets some static method in the lucene library to achieve this.
*/
public static void setBoolMax() {
BooleanQuery.setMaxClauseCount(16384);
}
/**
* Gets the name of the directory to store the lucene index in. The
* {@link ConfigurationProperties} should have a property named
* 'LuceneSetup.indexDir' which has the directory to store the lucene index
* for this clone in. If the property is not found, an exception will be
* thrown.
*
* @return a string that is the directory to store the lucene index.
* @throws IllegalStateException
* if the property is not found.
* @throws IOException
* if the directory doesn't exist and we fail to create it.
*/
private String getIndexDirName()
throws IOException {
String dirName = ConfigurationProperties
.getProperty("LuceneSetup.indexDir");
if (dirName == null) {
throw new IllegalStateException(
"LuceneSetup.indexDir not found in properties file.");
}
File dir = new File(dirName);
if (!dir.exists()) {
boolean created = dir.mkdir();
if (!created) {
throw new IOException(
"Unable to create Lucene index directory at '" + dir
+ "'");
}
}
return dirName;
}
/**
* Gets the analyzer that will be used when building the indexing
* and when analyzing the incoming search terms.
*
* @return
*/
private Analyzer getAnalyzer() {
PerFieldAnalyzerWrapper analyzer = new PerFieldAnalyzerWrapper( new KeywordAnalyzer());
analyzer.addAnalyzer(ALLTEXT, new HtmlLowerStopStemAnalyzer());
analyzer.addAnalyzer(NAME, new HtmlLowerStopStemAnalyzer());
analyzer.addAnalyzer(ALLTEXTUNSTEMMED, new HtmlLowerStopAnalyzer());
analyzer.addAnalyzer(NAMEUNSTEMMED, new HtmlLowerStopAnalyzer());
return analyzer;
}
public static final String INDEX_REBUILD_REQUESTED_AT_STARTUP = "LuceneSetup.indexRebuildRequestedAtStarup";
public static final String ANALYZER= "lucene.analyzer";
public static final String INDEX_DIR = "lucene.indexDir";
public static final String SEARCH_DATAPROPERTY_BLACKLIST =
"search.dataproperty.blacklist";
public static final String SEARCH_OBJECTPROPERTY_BLACKLIST =
"search.objectproperty.blacklist";
}
| false | true |
public void contextInitialized(ServletContextEvent sce) {
try {
ServletContext context = sce.getServletContext();
log.debug("**** Running " + this.getClass().getName() + ".contextInitialized()");
indexDir = getIndexDirName();
log.info("Directory of full text index: " + indexDir);
setBoolMax();
// these should really be set as annotation properties.
HashSet<String> dataPropertyBlacklist = new HashSet<String>();
context.setAttribute(SEARCH_DATAPROPERTY_BLACKLIST, dataPropertyBlacklist);
HashSet<String> objectPropertyBlacklist = new HashSet<String>();
objectPropertyBlacklist.add("http://www.w3.org/2002/07/owl#differentFrom");
context.setAttribute(SEARCH_OBJECTPROPERTY_BLACKLIST, objectPropertyBlacklist);
// Here we want to put the LuceneIndex object into the application scope.
// This will attempt to create a new directory and empty index if there is none.
LuceneIndexer indexer = new LuceneIndexer(indexDir, null, getAnalyzer());
context.setAttribute(ANALYZER, getAnalyzer());
context.setAttribute(INDEX_DIR, indexDir);
indexer.addObj2Doc(new Entity2LuceneDoc());
context.setAttribute(LuceneIndexer.class.getName(), indexer);
// Here we want to put the LuceneSearcher in the application scope.
// the queries need to know the analyzer to use so that the same one can be used
// to analyze the fields in the incoming user query terms.
LuceneSearcher searcher = new LuceneSearcher(
new LuceneQueryFactory(getAnalyzer(), ALLTEXT), indexDir);
searcher.addObj2Doc(new Entity2LuceneDoc());
context.setAttribute(Searcher.class.getName(), searcher);
indexer.addSearcher(searcher);
// This is where the builder gets the list of places to try to
// get objects to index. It is filtered so that non-public text
// does not get into the search index.
WebappDaoFactory wadf = (WebappDaoFactory) context.getAttribute("webappDaoFactory");
VitroFilters vf = VitroFilterUtils.getDisplayFilterByRoleLevel(RoleLevel.PUBLIC, wadf);
wadf = new WebappDaoFactoryFiltering(wadf, vf);
List<ObjectSourceIface> sources = new ArrayList<ObjectSourceIface>();
sources.add(wadf.getIndividualDao());
IndexBuilder builder = new IndexBuilder(context, indexer, sources);
// here we add the IndexBuilder with the LuceneIndexer
// to the servlet context so we can access it later in the webapp.
context.setAttribute(IndexBuilder.class.getName(), builder);
// set up listeners so search index builder is notified of changes to model
OntModel baseOntModel = (OntModel) sce.getServletContext().getAttribute("baseOntModel");
OntModel jenaOntModel = (OntModel) sce.getServletContext().getAttribute("jenaOntModel");
OntModel inferenceModel = (OntModel) sce.getServletContext().getAttribute("inferenceOntModel");
SearchReindexingListener srl = new SearchReindexingListener(builder);
baseOntModel.getBaseModel().register(srl);
jenaOntModel.getBaseModel().register(srl);
inferenceModel.register(srl);
// set the classes that the indexBuilder ignores
OntModel displayOntModel = (OntModel) sce.getServletContext().getAttribute("displayOntModel");
builder.setClassesProhibitedFromSearch(
new ProhibitedFromSearch(DisplayVocabulary.PRIMARY_LUCENE_INDEX_URI, displayOntModel));
if( (Boolean)sce.getServletContext().getAttribute(INDEX_REBUILD_REQUESTED_AT_STARTUP) instanceof Boolean &&
(Boolean)sce.getServletContext().getAttribute(INDEX_REBUILD_REQUESTED_AT_STARTUP) ){
builder.doIndexRebuild();
log.info("Rebuild of search index required before startup.");
while( builder.isIndexing() ){
Thread.currentThread().sleep(200);
log.info("Still rebulding search index");
}
log.info("Search index rebuild completed.");
}
log.debug("**** End of " + this.getClass().getName() + ".contextInitialized()");
} catch (Throwable t) {
log.error("***** Error setting up Lucene search *****", t);
}
}
|
public void contextInitialized(ServletContextEvent sce) {
try {
ServletContext context = sce.getServletContext();
log.debug("**** Running " + this.getClass().getName() + ".contextInitialized()");
indexDir = getIndexDirName();
log.info("Directory of full text index: " + indexDir);
setBoolMax();
// these should really be set as annotation properties.
HashSet<String> dataPropertyBlacklist = new HashSet<String>();
context.setAttribute(SEARCH_DATAPROPERTY_BLACKLIST, dataPropertyBlacklist);
HashSet<String> objectPropertyBlacklist = new HashSet<String>();
objectPropertyBlacklist.add("http://www.w3.org/2002/07/owl#differentFrom");
context.setAttribute(SEARCH_OBJECTPROPERTY_BLACKLIST, objectPropertyBlacklist);
// Here we want to put the LuceneIndex object into the application scope.
// This will attempt to create a new directory and empty index if there is none.
LuceneIndexer indexer = new LuceneIndexer(indexDir, null, getAnalyzer());
context.setAttribute(ANALYZER, getAnalyzer());
context.setAttribute(INDEX_DIR, indexDir);
indexer.addObj2Doc(new Entity2LuceneDoc());
context.setAttribute(LuceneIndexer.class.getName(), indexer);
// Here we want to put the LuceneSearcher in the application scope.
// the queries need to know the analyzer to use so that the same one can be used
// to analyze the fields in the incoming user query terms.
LuceneSearcher searcher = new LuceneSearcher(
new LuceneQueryFactory(getAnalyzer(), ALLTEXT), indexDir);
searcher.addObj2Doc(new Entity2LuceneDoc());
context.setAttribute(Searcher.class.getName(), searcher);
indexer.addSearcher(searcher);
// This is where the builder gets the list of places to try to
// get objects to index. It is filtered so that non-public text
// does not get into the search index.
WebappDaoFactory wadf = (WebappDaoFactory) context.getAttribute("webappDaoFactory");
VitroFilters vf = VitroFilterUtils.getDisplayFilterByRoleLevel(RoleLevel.PUBLIC, wadf);
wadf = new WebappDaoFactoryFiltering(wadf, vf);
List<ObjectSourceIface> sources = new ArrayList<ObjectSourceIface>();
sources.add(wadf.getIndividualDao());
IndexBuilder builder = new IndexBuilder(context, indexer, sources);
// here we add the IndexBuilder with the LuceneIndexer
// to the servlet context so we can access it later in the webapp.
context.setAttribute(IndexBuilder.class.getName(), builder);
// set up listeners so search index builder is notified of changes to model
OntModel baseOntModel = (OntModel) sce.getServletContext().getAttribute("baseOntModel");
OntModel jenaOntModel = (OntModel) sce.getServletContext().getAttribute("jenaOntModel");
OntModel inferenceModel = (OntModel) sce.getServletContext().getAttribute("inferenceOntModel");
SearchReindexingListener srl = new SearchReindexingListener(builder);
baseOntModel.getBaseModel().register(srl);
jenaOntModel.getBaseModel().register(srl);
inferenceModel.register(srl);
// set the classes that the indexBuilder ignores
OntModel displayOntModel = (OntModel) sce.getServletContext().getAttribute("displayOntModel");
builder.setClassesProhibitedFromSearch(
new ProhibitedFromSearch(DisplayVocabulary.PRIMARY_LUCENE_INDEX_URI, displayOntModel));
if( (Boolean)sce.getServletContext().getAttribute(INDEX_REBUILD_REQUESTED_AT_STARTUP) instanceof Boolean &&
(Boolean)sce.getServletContext().getAttribute(INDEX_REBUILD_REQUESTED_AT_STARTUP) ){
builder.doIndexRebuild();
log.info("Rebuild of search index required before startup.");
int n = 0;
while( builder.isIndexing() ){
Thread.currentThread().sleep(500);
if( n % 20 == 0 ) //output message every 10 sec.
log.info("Still rebulding search index");
}
log.info("Search index rebuild completed.");
}
log.debug("**** End of " + this.getClass().getName() + ".contextInitialized()");
} catch (Throwable t) {
log.error("***** Error setting up Lucene search *****", t);
}
}
|
diff --git a/src/com/android/calendar/EventInfoActivity.java b/src/com/android/calendar/EventInfoActivity.java
index 02951b6f..19fb8193 100644
--- a/src/com/android/calendar/EventInfoActivity.java
+++ b/src/com/android/calendar/EventInfoActivity.java
@@ -1,1251 +1,1254 @@
/*
* Copyright (C) 2007 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.calendar;
import static android.provider.Calendar.EVENT_BEGIN_TIME;
import static android.provider.Calendar.EVENT_END_TIME;
import static android.provider.Calendar.AttendeesColumns.ATTENDEE_STATUS;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.AsyncQueryHandler;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.pim.EventRecurrence;
import android.provider.Calendar;
import android.provider.Calendar.Attendees;
import android.provider.Calendar.Calendars;
import android.provider.Calendar.Events;
import android.provider.Calendar.Reminders;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Intents;
import android.provider.ContactsContract.Presence;
import android.provider.ContactsContract.QuickContact;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.text.util.Linkify;
import android.text.util.Rfc822Token;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.QuickContactBadge;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.TimeZone;
import java.util.regex.Pattern;
public class EventInfoActivity extends Activity implements View.OnClickListener,
AdapterView.OnItemSelectedListener {
public static final boolean DEBUG = false;
public static final String TAG = "EventInfoActivity";
private static final int MAX_REMINDERS = 5;
/**
* These are the corresponding indices into the array of strings
* "R.array.change_response_labels" in the resource file.
*/
static final int UPDATE_SINGLE = 0;
static final int UPDATE_ALL = 1;
private static final String[] EVENT_PROJECTION = new String[] {
Events._ID, // 0 do not remove; used in DeleteEventHelper
Events.TITLE, // 1 do not remove; used in DeleteEventHelper
Events.RRULE, // 2 do not remove; used in DeleteEventHelper
Events.ALL_DAY, // 3 do not remove; used in DeleteEventHelper
Events.CALENDAR_ID, // 4 do not remove; used in DeleteEventHelper
Events.DTSTART, // 5 do not remove; used in DeleteEventHelper
Events._SYNC_ID, // 6 do not remove; used in DeleteEventHelper
Events.EVENT_TIMEZONE, // 7 do not remove; used in DeleteEventHelper
Events.DESCRIPTION, // 8
Events.EVENT_LOCATION, // 9
Events.HAS_ALARM, // 10
Events.ACCESS_LEVEL, // 11
Events.COLOR, // 12
Events.HAS_ATTENDEE_DATA, // 13
Events.GUESTS_CAN_MODIFY, // 14
// TODO Events.GUESTS_CAN_INVITE_OTHERS has not been implemented in calendar provider
Events.GUESTS_CAN_INVITE_OTHERS, // 15
Events.ORGANIZER, // 16
};
private static final int EVENT_INDEX_ID = 0;
private static final int EVENT_INDEX_TITLE = 1;
private static final int EVENT_INDEX_RRULE = 2;
private static final int EVENT_INDEX_ALL_DAY = 3;
private static final int EVENT_INDEX_CALENDAR_ID = 4;
private static final int EVENT_INDEX_SYNC_ID = 6;
private static final int EVENT_INDEX_EVENT_TIMEZONE = 7;
private static final int EVENT_INDEX_DESCRIPTION = 8;
private static final int EVENT_INDEX_EVENT_LOCATION = 9;
private static final int EVENT_INDEX_HAS_ALARM = 10;
private static final int EVENT_INDEX_ACCESS_LEVEL = 11;
private static final int EVENT_INDEX_COLOR = 12;
private static final int EVENT_INDEX_HAS_ATTENDEE_DATA = 13;
private static final int EVENT_INDEX_GUESTS_CAN_MODIFY = 14;
private static final int EVENT_INDEX_CAN_INVITE_OTHERS = 15;
private static final int EVENT_INDEX_ORGANIZER = 16;
private static final String[] ATTENDEES_PROJECTION = new String[] {
Attendees._ID, // 0
Attendees.ATTENDEE_NAME, // 1
Attendees.ATTENDEE_EMAIL, // 2
Attendees.ATTENDEE_RELATIONSHIP, // 3
Attendees.ATTENDEE_STATUS, // 4
};
private static final int ATTENDEES_INDEX_ID = 0;
private static final int ATTENDEES_INDEX_NAME = 1;
private static final int ATTENDEES_INDEX_EMAIL = 2;
private static final int ATTENDEES_INDEX_RELATIONSHIP = 3;
private static final int ATTENDEES_INDEX_STATUS = 4;
private static final String ATTENDEES_WHERE = Attendees.EVENT_ID + "=%d";
private static final String ATTENDEES_SORT_ORDER = Attendees.ATTENDEE_NAME + " ASC, "
+ Attendees.ATTENDEE_EMAIL + " ASC";
static final String[] CALENDARS_PROJECTION = new String[] {
Calendars._ID, // 0
Calendars.DISPLAY_NAME, // 1
Calendars.OWNER_ACCOUNT, // 2
Calendars.ORGANIZER_CAN_RESPOND // 3
};
static final int CALENDARS_INDEX_DISPLAY_NAME = 1;
static final int CALENDARS_INDEX_OWNER_ACCOUNT = 2;
static final int CALENDARS_INDEX_OWNER_CAN_RESPOND = 3;
static final String CALENDARS_WHERE = Calendars._ID + "=%d";
static final String CALENDARS_DUPLICATE_NAME_WHERE = Calendars.DISPLAY_NAME + "=?";
private static final String[] REMINDERS_PROJECTION = new String[] {
Reminders._ID, // 0
Reminders.MINUTES, // 1
};
private static final int REMINDERS_INDEX_MINUTES = 1;
private static final String REMINDERS_WHERE = Reminders.EVENT_ID + "=%d AND (" +
Reminders.METHOD + "=" + Reminders.METHOD_ALERT + " OR " + Reminders.METHOD + "=" +
Reminders.METHOD_DEFAULT + ")";
private static final String REMINDERS_SORT = Reminders.MINUTES;
private static final int MENU_GROUP_REMINDER = 1;
private static final int MENU_GROUP_EDIT = 2;
private static final int MENU_GROUP_DELETE = 3;
private static final int MENU_ADD_REMINDER = 1;
private static final int MENU_EDIT = 2;
private static final int MENU_DELETE = 3;
private static final int ATTENDEE_ID_NONE = -1;
private static final int ATTENDEE_NO_RESPONSE = -1;
private static final int[] ATTENDEE_VALUES = {
ATTENDEE_NO_RESPONSE,
Attendees.ATTENDEE_STATUS_ACCEPTED,
Attendees.ATTENDEE_STATUS_TENTATIVE,
Attendees.ATTENDEE_STATUS_DECLINED,
};
private LinearLayout mRemindersContainer;
private LinearLayout mOrganizerContainer;
private TextView mOrganizerView;
private Uri mUri;
private long mEventId;
private Cursor mEventCursor;
private Cursor mAttendeesCursor;
private Cursor mCalendarsCursor;
private long mStartMillis;
private long mEndMillis;
private boolean mHasAttendeeData;
private boolean mIsOrganizer;
private long mCalendarOwnerAttendeeId = ATTENDEE_ID_NONE;
private boolean mOrganizerCanRespond;
private String mCalendarOwnerAccount;
private boolean mCanModifyCalendar;
private boolean mIsBusyFreeCalendar;
private boolean mCanModifyEvent;
private int mNumOfAttendees;
private String mOrganizer;
private ArrayList<Integer> mOriginalMinutes = new ArrayList<Integer>();
private ArrayList<LinearLayout> mReminderItems = new ArrayList<LinearLayout>(0);
private ArrayList<Integer> mReminderValues;
private ArrayList<String> mReminderLabels;
private int mDefaultReminderMinutes;
private boolean mOriginalHasAlarm;
private DeleteEventHelper mDeleteEventHelper;
private EditResponseHelper mEditResponseHelper;
private int mResponseOffset;
private int mOriginalAttendeeResponse;
private int mAttendeeResponseFromIntent = ATTENDEE_NO_RESPONSE;
private boolean mIsRepeating;
private boolean mIsDuplicateName;
private Pattern mWildcardPattern = Pattern.compile("^.*$");
private LayoutInflater mLayoutInflater;
private LinearLayout mReminderAdder;
// TODO This can be removed when the contacts content provider doesn't return duplicates
private int mUpdateCounts;
private static class ViewHolder {
QuickContactBadge badge;
ImageView presence;
int updateCounts;
}
private HashMap<String, ViewHolder> mViewHolders = new HashMap<String, ViewHolder>();
private PresenceQueryHandler mPresenceQueryHandler;
private static final Uri CONTACT_DATA_WITH_PRESENCE_URI = Data.CONTENT_URI;
int PRESENCE_PROJECTION_CONTACT_ID_INDEX = 0;
int PRESENCE_PROJECTION_PRESENCE_INDEX = 1;
int PRESENCE_PROJECTION_EMAIL_INDEX = 2;
int PRESENCE_PROJECTION_PHOTO_ID_INDEX = 3;
private static final String[] PRESENCE_PROJECTION = new String[] {
Email.CONTACT_ID, // 0
Email.CONTACT_PRESENCE, // 1
Email.DATA, // 2
Email.PHOTO_ID, // 3
};
ArrayList<Attendee> mAcceptedAttendees = new ArrayList<Attendee>();
ArrayList<Attendee> mDeclinedAttendees = new ArrayList<Attendee>();
ArrayList<Attendee> mTentativeAttendees = new ArrayList<Attendee>();
ArrayList<Attendee> mNoResponseAttendees = new ArrayList<Attendee>();
private int mColor;
// This gets run if the time zone is updated in the db
private Runnable mUpdateTZ = new Runnable() {
@Override
public void run() {
if (EventInfoActivity.this.isFinishing()) {
return;
}
updateView();
}
};
// This is called when one of the "remove reminder" buttons is selected.
public void onClick(View v) {
LinearLayout reminderItem = (LinearLayout) v.getParent();
if (reminderItem == null) {
return;
}
LinearLayout parent = (LinearLayout) reminderItem.getParent();
if (parent == null) {
return;
}
parent.removeView(reminderItem);
mReminderItems.remove(reminderItem);
updateRemindersVisibility();
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
// If they selected the "No response" option, then don't display the
// dialog asking which events to change.
if (id == 0 && mResponseOffset == 0) {
return;
}
// If this is not a repeating event, then don't display the dialog
// asking which events to change.
if (!mIsRepeating) {
return;
}
// If the selection is the same as the original, then don't display the
// dialog asking which events to change.
int index = findResponseIndexFor(mOriginalAttendeeResponse);
if (position == index + mResponseOffset) {
return;
}
// This is a repeating event. We need to ask the user if they mean to
// change just this one instance or all instances.
mEditResponseHelper.showDialog(mEditResponseHelper.getWhichEvents());
}
public void onNothingSelected(AdapterView<?> parent) {
}
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Event cursor
Intent intent = getIntent();
mUri = intent.getData();
ContentResolver cr = getContentResolver();
mStartMillis = intent.getLongExtra(EVENT_BEGIN_TIME, 0);
mEndMillis = intent.getLongExtra(EVENT_END_TIME, 0);
mAttendeeResponseFromIntent = intent.getIntExtra(ATTENDEE_STATUS, ATTENDEE_NO_RESPONSE);
mEventCursor = managedQuery(mUri, EVENT_PROJECTION, null, null, null);
if (initEventCursor()) {
// The cursor is empty. This can happen if the event was deleted.
finish();
return;
}
setContentView(R.layout.event_info_activity);
mPresenceQueryHandler = new PresenceQueryHandler(this, cr);
mLayoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRemindersContainer = (LinearLayout) findViewById(R.id.reminders_container);
mOrganizerContainer = (LinearLayout) findViewById(R.id.organizer_container);
mOrganizerView = (TextView) findViewById(R.id.organizer);
// Calendars cursor
Uri uri = Calendars.CONTENT_URI;
String where = String.format(CALENDARS_WHERE, mEventCursor.getLong(EVENT_INDEX_CALENDAR_ID));
mCalendarsCursor = managedQuery(uri, CALENDARS_PROJECTION, where, null, null);
mCalendarOwnerAccount = "";
if (mCalendarsCursor != null) {
mCalendarsCursor.moveToFirst();
mCalendarOwnerAccount = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
mOrganizerCanRespond = mCalendarsCursor.getInt(CALENDARS_INDEX_OWNER_CAN_RESPOND) != 0;
String displayName = mCalendarsCursor.getString(CALENDARS_INDEX_DISPLAY_NAME);
mIsDuplicateName = isDuplicateName(displayName);
}
String eventOrganizer = mEventCursor.getString(EVENT_INDEX_ORGANIZER);
mIsOrganizer = mCalendarOwnerAccount.equalsIgnoreCase(eventOrganizer);
mHasAttendeeData = mEventCursor.getInt(EVENT_INDEX_HAS_ATTENDEE_DATA) != 0;
updateView();
// Attendees cursor
uri = Attendees.CONTENT_URI;
where = String.format(ATTENDEES_WHERE, mEventId);
mAttendeesCursor = managedQuery(uri, ATTENDEES_PROJECTION, where, null,
ATTENDEES_SORT_ORDER);
initAttendeesCursor();
mOrganizer = eventOrganizer;
mCanModifyCalendar =
mEventCursor.getInt(EVENT_INDEX_ACCESS_LEVEL) >= Calendars.CONTRIBUTOR_ACCESS;
mIsBusyFreeCalendar =
mEventCursor.getInt(EVENT_INDEX_ACCESS_LEVEL) == Calendars.FREEBUSY_ACCESS;
mCanModifyEvent = mCanModifyCalendar
&& (mIsOrganizer || (mEventCursor.getInt(EVENT_INDEX_GUESTS_CAN_MODIFY) != 0));
// Initialize the reminder values array.
Resources r = getResources();
String[] strings = r.getStringArray(R.array.reminder_minutes_values);
int size = strings.length;
ArrayList<Integer> list = new ArrayList<Integer>(size);
for (int i = 0 ; i < size ; i++) {
list.add(Integer.parseInt(strings[i]));
}
mReminderValues = list;
String[] labels = r.getStringArray(R.array.reminder_minutes_labels);
mReminderLabels = new ArrayList<String>(Arrays.asList(labels));
SharedPreferences prefs = CalendarPreferenceActivity.getSharedPreferences(this);
String durationString =
prefs.getString(CalendarPreferenceActivity.KEY_DEFAULT_REMINDER, "0");
mDefaultReminderMinutes = Integer.parseInt(durationString);
// Reminders cursor
boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0;
if (hasAlarm) {
uri = Reminders.CONTENT_URI;
where = String.format(REMINDERS_WHERE, mEventId);
Cursor reminderCursor = cr.query(uri, REMINDERS_PROJECTION, where, null,
REMINDERS_SORT);
try {
// First pass: collect all the custom reminder minutes (e.g.,
// a reminder of 8 minutes) into a global list.
while (reminderCursor.moveToNext()) {
int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
EditEvent.addMinutesToList(this, mReminderValues, mReminderLabels, minutes);
}
// Second pass: create the reminder spinners
reminderCursor.moveToPosition(-1);
while (reminderCursor.moveToNext()) {
int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
mOriginalMinutes.add(minutes);
EditEvent.addReminder(this, this, mReminderItems, mReminderValues,
mReminderLabels, minutes);
}
} finally {
reminderCursor.close();
}
}
mOriginalHasAlarm = hasAlarm;
// Setup the + Add Reminder Button
View.OnClickListener addReminderOnClickListener = new View.OnClickListener() {
public void onClick(View v) {
addReminder();
}
};
ImageButton reminderAddButton = (ImageButton) findViewById(R.id.reminder_add);
reminderAddButton.setOnClickListener(addReminderOnClickListener);
mReminderAdder = (LinearLayout) findViewById(R.id.reminder_adder);
updateRemindersVisibility();
mDeleteEventHelper = new DeleteEventHelper(this, true /* exit when done */);
mEditResponseHelper = new EditResponseHelper(this);
}
@Override
protected void onResume() {
super.onResume();
if (initEventCursor()) {
// The cursor is empty. This can happen if the event was deleted.
finish();
return;
}
initCalendarsCursor();
updateResponse();
updateTitle();
}
private void updateTitle() {
Resources res = getResources();
if (mCanModifyCalendar && !mIsOrganizer) {
setTitle(res.getString(R.string.event_info_title_invite));
} else {
setTitle(res.getString(R.string.event_info_title));
}
}
boolean isDuplicateName(String displayName) {
Cursor dupNameCursor = managedQuery(Calendars.CONTENT_URI, CALENDARS_PROJECTION,
CALENDARS_DUPLICATE_NAME_WHERE, new String[] {displayName}, null);
boolean isDuplicateName = false;
if(dupNameCursor != null) {
if (dupNameCursor.getCount() > 1) {
isDuplicateName = true;
}
dupNameCursor.close();
}
return isDuplicateName;
}
/**
* Initializes the event cursor, which is expected to point to the first
* (and only) result from a query.
* @return true if the cursor is empty.
*/
private boolean initEventCursor() {
if ((mEventCursor == null) || (mEventCursor.getCount() == 0)) {
return true;
}
mEventCursor.moveToFirst();
mEventId = mEventCursor.getInt(EVENT_INDEX_ID);
String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
mIsRepeating = !TextUtils.isEmpty(rRule);
return false;
}
private static class Attendee {
String mName;
String mEmail;
Attendee(String name, String email) {
mName = name;
mEmail = email;
}
}
@SuppressWarnings("fallthrough")
private void initAttendeesCursor() {
mOriginalAttendeeResponse = ATTENDEE_NO_RESPONSE;
mCalendarOwnerAttendeeId = ATTENDEE_ID_NONE;
mNumOfAttendees = 0;
if (mAttendeesCursor != null) {
mNumOfAttendees = mAttendeesCursor.getCount();
if (mAttendeesCursor.moveToFirst()) {
mAcceptedAttendees.clear();
mDeclinedAttendees.clear();
mTentativeAttendees.clear();
mNoResponseAttendees.clear();
do {
int status = mAttendeesCursor.getInt(ATTENDEES_INDEX_STATUS);
String name = mAttendeesCursor.getString(ATTENDEES_INDEX_NAME);
String email = mAttendeesCursor.getString(ATTENDEES_INDEX_EMAIL);
if (mAttendeesCursor.getInt(ATTENDEES_INDEX_RELATIONSHIP) ==
Attendees.RELATIONSHIP_ORGANIZER) {
// Overwrites the one from Event table if available
if (name != null && name.length() > 0) {
mOrganizer = name;
} else if (email != null && email.length() > 0) {
mOrganizer = email;
}
}
if (mCalendarOwnerAttendeeId == ATTENDEE_ID_NONE &&
mCalendarOwnerAccount.equalsIgnoreCase(email)) {
mCalendarOwnerAttendeeId = mAttendeesCursor.getInt(ATTENDEES_INDEX_ID);
mOriginalAttendeeResponse = mAttendeesCursor.getInt(ATTENDEES_INDEX_STATUS);
} else {
// Don't show your own status in the list because:
// 1) it doesn't make sense for event without other guests.
// 2) there's a spinner for that for events with guests.
switch(status) {
case Attendees.ATTENDEE_STATUS_ACCEPTED:
mAcceptedAttendees.add(new Attendee(name, email));
break;
case Attendees.ATTENDEE_STATUS_DECLINED:
mDeclinedAttendees.add(new Attendee(name, email));
break;
case Attendees.ATTENDEE_STATUS_NONE:
mNoResponseAttendees.add(new Attendee(name, email));
// Fallthrough so that no response is a subset of tentative
default:
mTentativeAttendees.add(new Attendee(name, email));
}
}
} while (mAttendeesCursor.moveToNext());
mAttendeesCursor.moveToFirst();
updateAttendees();
}
}
// only show the organizer if we're not the organizer and if
// we have attendee data (might have been removed by the server
// for events with a lot of attendees).
if (!mIsOrganizer && mHasAttendeeData) {
mOrganizerContainer.setVisibility(View.VISIBLE);
mOrganizerView.setText(mOrganizer);
} else {
mOrganizerContainer.setVisibility(View.GONE);
}
}
private void initCalendarsCursor() {
if (mCalendarsCursor != null) {
mCalendarsCursor.moveToFirst();
}
}
@Override
public void onPause() {
super.onPause();
ContentResolver cr = getContentResolver();
ArrayList<Integer> reminderMinutes = EditEvent.reminderItemsToMinutes(mReminderItems,
mReminderValues);
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(3);
boolean changed = EditEvent.saveReminders(ops, mEventId, reminderMinutes, mOriginalMinutes,
false /* no force save */);
try {
// TODO Run this in a background process.
cr.applyBatch(Calendars.CONTENT_URI.getAuthority(), ops);
// Update the "hasAlarm" field for the event
Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId);
int len = reminderMinutes.size();
boolean hasAlarm = len > 0;
if (hasAlarm != mOriginalHasAlarm) {
ContentValues values = new ContentValues();
values.put(Events.HAS_ALARM, hasAlarm ? 1 : 0);
cr.update(uri, values, null, null);
}
} catch (RemoteException e) {
Log.w(TAG, "Ignoring exception: ", e);
} catch (OperationApplicationException e) {
Log.w(TAG, "Ignoring exception: ", e);
}
changed |= saveResponse(cr);
if (changed) {
Toast.makeText(this, R.string.saving_event, Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item;
item = menu.add(MENU_GROUP_REMINDER, MENU_ADD_REMINDER, 0,
R.string.add_new_reminder);
item.setIcon(R.drawable.ic_menu_reminder);
item.setAlphabeticShortcut('r');
item = menu.add(MENU_GROUP_EDIT, MENU_EDIT, 0, R.string.edit_event_label);
item.setIcon(android.R.drawable.ic_menu_edit);
item.setAlphabeticShortcut('e');
item = menu.add(MENU_GROUP_DELETE, MENU_DELETE, 0, R.string.delete_event_label);
item.setIcon(android.R.drawable.ic_menu_delete);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean canAddReminders = canAddReminders();
menu.setGroupVisible(MENU_GROUP_REMINDER, canAddReminders);
menu.setGroupEnabled(MENU_GROUP_REMINDER, canAddReminders);
menu.setGroupVisible(MENU_GROUP_EDIT, mCanModifyEvent);
menu.setGroupEnabled(MENU_GROUP_EDIT, mCanModifyEvent);
menu.setGroupVisible(MENU_GROUP_DELETE, mCanModifyCalendar);
menu.setGroupEnabled(MENU_GROUP_DELETE, mCanModifyCalendar);
return super.onPrepareOptionsMenu(menu);
}
private boolean canAddReminders() {
return !mIsBusyFreeCalendar && mReminderItems.size() < MAX_REMINDERS;
}
private void addReminder() {
// TODO: when adding a new reminder, make it different from the
// last one in the list (if any).
if (mDefaultReminderMinutes == 0) {
EditEvent.addReminder(this, this, mReminderItems,
mReminderValues, mReminderLabels, 10 /* minutes */);
} else {
EditEvent.addReminder(this, this, mReminderItems,
mReminderValues, mReminderLabels, mDefaultReminderMinutes);
}
updateRemindersVisibility();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case MENU_ADD_REMINDER:
addReminder();
break;
case MENU_EDIT:
doEdit();
break;
case MENU_DELETE:
doDelete();
break;
}
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL) {
doDelete();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void updateRemindersVisibility() {
if (mIsBusyFreeCalendar) {
mRemindersContainer.setVisibility(View.GONE);
} else {
mRemindersContainer.setVisibility(View.VISIBLE);
mReminderAdder.setVisibility(canAddReminders() ? View.VISIBLE : View.GONE);
}
}
/**
* Saves the response to an invitation if the user changed the response.
* Returns true if the database was updated.
*
* @param cr the ContentResolver
* @return true if the database was changed
*/
private boolean saveResponse(ContentResolver cr) {
if (mAttendeesCursor == null || mEventCursor == null) {
return false;
}
Spinner spinner = (Spinner) findViewById(R.id.response_value);
int position = spinner.getSelectedItemPosition() - mResponseOffset;
if (position <= 0) {
return false;
}
int status = ATTENDEE_VALUES[position];
// If the status has not changed, then don't update the database
if (status == mOriginalAttendeeResponse) {
return false;
}
// If we never got an owner attendee id we can't set the status
if (mCalendarOwnerAttendeeId == ATTENDEE_ID_NONE) {
return false;
}
// Update the locally cached values
mAttendeeResponseFromIntent = mOriginalAttendeeResponse = status;
if (!mIsRepeating) {
// This is a non-repeating event
updateResponse(cr, mEventId, mCalendarOwnerAttendeeId, status);
return true;
}
// This is a repeating event
int whichEvents = mEditResponseHelper.getWhichEvents();
switch (whichEvents) {
case -1:
return false;
case UPDATE_SINGLE:
createExceptionResponse(cr, mEventId, mCalendarOwnerAttendeeId, status);
return true;
case UPDATE_ALL:
updateResponse(cr, mEventId, mCalendarOwnerAttendeeId, status);
return true;
default:
Log.e(TAG, "Unexpected choice for updating invitation response");
break;
}
return false;
}
private void updateResponse(ContentResolver cr, long eventId, long attendeeId, int status) {
// Update the attendee status in the attendees table. the provider
// takes care of updating the self attendance status.
ContentValues values = new ContentValues();
if (!TextUtils.isEmpty(mCalendarOwnerAccount)) {
values.put(Attendees.ATTENDEE_EMAIL, mCalendarOwnerAccount);
}
values.put(Attendees.ATTENDEE_STATUS, status);
values.put(Attendees.EVENT_ID, eventId);
Uri uri = ContentUris.withAppendedId(Attendees.CONTENT_URI, attendeeId);
cr.update(uri, values, null /* where */, null /* selection args */);
}
private void createExceptionResponse(ContentResolver cr, long eventId,
long attendeeId, int status) {
// Fetch information about the repeating event.
Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, eventId);
Cursor cursor = cr.query(uri, EVENT_PROJECTION, null, null, null);
if (cursor == null) {
return;
}
if(!cursor.moveToFirst()) {
cursor.close();
return;
}
try {
ContentValues values = new ContentValues();
String title = cursor.getString(EVENT_INDEX_TITLE);
String timezone = cursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
int calendarId = cursor.getInt(EVENT_INDEX_CALENDAR_ID);
boolean allDay = cursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
String syncId = cursor.getString(EVENT_INDEX_SYNC_ID);
values.put(Events.TITLE, title);
values.put(Events.EVENT_TIMEZONE, timezone);
values.put(Events.ALL_DAY, allDay ? 1 : 0);
values.put(Events.CALENDAR_ID, calendarId);
values.put(Events.DTSTART, mStartMillis);
values.put(Events.DTEND, mEndMillis);
values.put(Events.ORIGINAL_EVENT, syncId);
values.put(Events.ORIGINAL_INSTANCE_TIME, mStartMillis);
values.put(Events.ORIGINAL_ALL_DAY, allDay ? 1 : 0);
values.put(Events.STATUS, Events.STATUS_CONFIRMED);
values.put(Events.SELF_ATTENDEE_STATUS, status);
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int eventIdIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(
values).build());
if (mHasAttendeeData) {
ContentProviderOperation.Builder b;
// Insert the new attendees
for (Attendee attendee : mAcceptedAttendees) {
addAttendee(values, ops, eventIdIndex, attendee,
Attendees.ATTENDEE_STATUS_ACCEPTED);
}
for (Attendee attendee : mDeclinedAttendees) {
addAttendee(values, ops, eventIdIndex, attendee,
Attendees.ATTENDEE_STATUS_DECLINED);
}
for (Attendee attendee : mTentativeAttendees) {
addAttendee(values, ops, eventIdIndex, attendee,
Attendees.ATTENDEE_STATUS_TENTATIVE);
}
for (Attendee attendee : mNoResponseAttendees) {
addAttendee(
values, ops, eventIdIndex, attendee, Attendees.ATTENDEE_STATUS_NONE);
}
}
// Create a recurrence exception
cr.applyBatch(Calendar.AUTHORITY, ops);
} catch (RemoteException e) {
Log.w(TAG, "Ignoring exception: ", e);
} catch (OperationApplicationException e) {
Log.w(TAG, "Ignoring exception: ", e);
} finally {
cursor.close();
}
}
/**
* Adds an attendee to the list of operations
*
* @param values an initialized ContentValues
* @param ops the list of ops being added to
* @param eventIdIndex The back ref value
* @param attendee the attendee to add
* @param attendeeStatus their status
*/
private void addAttendee(ContentValues values, ArrayList<ContentProviderOperation> ops,
int eventIdIndex, Attendee attendee, int attendeeStatus) {
ContentProviderOperation.Builder b;
values.clear();
values.put(Attendees.ATTENDEE_NAME, attendee.mName);
values.put(Attendees.ATTENDEE_EMAIL, attendee.mEmail);
values.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ATTENDEE);
values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE);
values.put(Attendees.ATTENDEE_STATUS, attendeeStatus);
b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI).withValues(values);
b.withValueBackReference(Attendees.EVENT_ID, eventIdIndex);
ops.add(b.build());
}
private int findResponseIndexFor(int response) {
int size = ATTENDEE_VALUES.length;
for (int index = 0; index < size; index++) {
if (ATTENDEE_VALUES[index] == response) {
return index;
}
}
return 0;
}
private void doEdit() {
Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId);
Intent intent = new Intent(Intent.ACTION_EDIT, uri);
intent.putExtra(Calendar.EVENT_BEGIN_TIME, mStartMillis);
intent.putExtra(Calendar.EVENT_END_TIME, mEndMillis);
intent.setClass(EventInfoActivity.this, EditEvent.class);
startActivity(intent);
finish();
}
private void doDelete() {
mDeleteEventHelper.delete(mStartMillis, mEndMillis, mEventCursor, -1);
}
private void updateView() {
if (mEventCursor == null) {
return;
}
String eventName = mEventCursor.getString(EVENT_INDEX_TITLE);
if (eventName == null || eventName.length() == 0) {
Resources res = getResources();
eventName = res.getString(R.string.no_title_label);
}
boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
String location = mEventCursor.getString(EVENT_INDEX_EVENT_LOCATION);
String description = mEventCursor.getString(EVENT_INDEX_DESCRIPTION);
String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0;
String eventTimezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
mColor = mEventCursor.getInt(EVENT_INDEX_COLOR) & 0xbbffffff;
View calBackground = findViewById(R.id.cal_background);
calBackground.setBackgroundColor(mColor);
TextView title = (TextView) findViewById(R.id.title);
title.setTextColor(mColor);
View divider = findViewById(R.id.divider);
divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
// What
if (eventName != null) {
setTextCommon(R.id.title, eventName);
}
// When
String when;
int flags;
if (allDay) {
flags = DateUtils.FORMAT_UTC | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE;
} else {
flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE;
if (DateFormat.is24HourFormat(this)) {
flags |= DateUtils.FORMAT_24HOUR;
}
}
when = Utils.formatDateRange(this, mStartMillis, mEndMillis, flags);
setTextCommon(R.id.when, when);
// Show the event timezone if it is different from the local timezone
String localTimezone = Utils.getTimeZone(this, mUpdateTZ);
if (allDay) {
localTimezone = Time.TIMEZONE_UTC;
}
if (eventTimezone != null && !allDay &&
(!TextUtils.equals(localTimezone, eventTimezone) ||
!TextUtils.equals(localTimezone, Time.getCurrentTimezone()))) {
String displayName;
TimeZone tz = TimeZone.getTimeZone(localTimezone);
if (tz == null || tz.getID().equals("GMT")) {
displayName = localTimezone;
} else {
displayName = tz.getDisplayName();
}
setTextCommon(R.id.timezone, displayName);
} else {
setVisibilityCommon(R.id.timezone_container, View.GONE);
}
// Repeat
if (!TextUtils.isEmpty(rRule)) {
EventRecurrence eventRecurrence = new EventRecurrence();
eventRecurrence.parse(rRule);
Time date = new Time(Utils.getTimeZone(this, mUpdateTZ));
if (allDay) {
date.timezone = Time.TIMEZONE_UTC;
}
date.set(mStartMillis);
eventRecurrence.setStartDate(date);
String repeatString = EventRecurrenceFormatter.getRepeatString(getResources(),
eventRecurrence);
setTextCommon(R.id.repeat, repeatString);
} else {
setVisibilityCommon(R.id.repeat_container, View.GONE);
}
// Where
if (location == null || location.length() == 0) {
setVisibilityCommon(R.id.where, View.GONE);
} else {
final TextView textView = (TextView) findViewById(R.id.where);
if (textView != null) {
textView.setAutoLinkMask(0);
textView.setText(location);
- Linkify.addLinks(textView, mWildcardPattern, "geo:0,0?q=");
+ if (!Linkify.addLinks(textView, Linkify.WEB_URLS |
+ Linkify.EMAIL_ADDRESSES | Linkify.MAP_ADDRESSES)) {
+ Linkify.addLinks(textView, mWildcardPattern, "geo:0,0?q=");
+ }
textView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
try {
return v.onTouchEvent(event);
} catch (ActivityNotFoundException e) {
// ignore
return true;
}
}
});
}
}
// Description
if (description == null || description.length() == 0) {
setVisibilityCommon(R.id.description, View.GONE);
} else {
setTextCommon(R.id.description, description);
}
// Calendar
if (mCalendarsCursor != null) {
String calendarName = mCalendarsCursor.getString(CALENDARS_INDEX_DISPLAY_NAME);
String ownerAccount = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
if (mIsDuplicateName && !calendarName.equalsIgnoreCase(ownerAccount)) {
Resources res = getResources();
TextView ownerText = (TextView) findViewById(R.id.owner);
ownerText.setText(ownerAccount);
ownerText.setTextColor(res.getColor(R.color.calendar_owner_text_color));
} else {
setVisibilityCommon(R.id.owner, View.GONE);
}
setTextCommon(R.id.calendar, calendarName);
} else {
setVisibilityCommon(R.id.calendar_container, View.GONE);
}
}
private void updateAttendees() {
LinearLayout attendeesLayout = (LinearLayout) findViewById(R.id.attendee_list);
attendeesLayout.removeAllViewsInLayout();
++mUpdateCounts;
if(mAcceptedAttendees.size() == 0 && mDeclinedAttendees.size() == 0 &&
mTentativeAttendees.size() == mNoResponseAttendees.size()) {
// If all guests have no response just list them as guests,
CharSequence guestsLabel = getResources().getText(R.string.attendees_label);
addAttendeesToLayout(mNoResponseAttendees, attendeesLayout, guestsLabel);
} else {
// If we have any responses then divide them up by response
CharSequence[] entries;
entries = getResources().getTextArray(R.array.response_labels2);
addAttendeesToLayout(mAcceptedAttendees, attendeesLayout, entries[0]);
addAttendeesToLayout(mDeclinedAttendees, attendeesLayout, entries[2]);
addAttendeesToLayout(mTentativeAttendees, attendeesLayout, entries[1]);
}
}
private void addAttendeesToLayout(ArrayList<Attendee> attendees, LinearLayout attendeeList,
CharSequence sectionTitle) {
if (attendees.size() == 0) {
return;
}
// Yes/No/Maybe Title
View titleView = mLayoutInflater.inflate(R.layout.contact_item, null);
titleView.findViewById(R.id.badge).setVisibility(View.GONE);
View divider = titleView.findViewById(R.id.separator);
divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
TextView title = (TextView) titleView.findViewById(R.id.name);
title.setText(getString(R.string.response_label, sectionTitle, attendees.size()));
title.setTextAppearance(this, R.style.TextAppearance_EventInfo_Label);
attendeeList.addView(titleView);
// Attendees
int numOfAttendees = attendees.size();
StringBuilder selection = new StringBuilder(Email.DATA + " IN (");
String[] selectionArgs = new String[numOfAttendees];
for (int i = 0; i < numOfAttendees; ++i) {
Attendee attendee = attendees.get(i);
selectionArgs[i] = attendee.mEmail;
View v = mLayoutInflater.inflate(R.layout.contact_item, null);
v.setTag(attendee);
View separator = v.findViewById(R.id.separator);
separator.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
// Text
TextView tv = (TextView) v.findViewById(R.id.name);
String name = attendee.mName;
if (name == null || name.length() == 0) {
name = attendee.mEmail;
}
tv.setText(name);
ViewHolder vh = new ViewHolder();
vh.badge = (QuickContactBadge) v.findViewById(R.id.badge);
vh.badge.assignContactFromEmail(attendee.mEmail, true);
vh.presence = (ImageView) v.findViewById(R.id.presence);
mViewHolders.put(attendee.mEmail, vh);
if (i == 0) {
selection.append('?');
} else {
selection.append(", ?");
}
attendeeList.addView(v);
}
selection.append(')');
mPresenceQueryHandler.startQuery(mUpdateCounts, attendees, CONTACT_DATA_WITH_PRESENCE_URI,
PRESENCE_PROJECTION, selection.toString(), selectionArgs, null);
}
private class PresenceQueryHandler extends AsyncQueryHandler {
Context mContext;
public PresenceQueryHandler(Context context, ContentResolver cr) {
super(cr);
mContext = context;
}
@Override
protected void onQueryComplete(int queryIndex, Object cookie, Cursor cursor) {
if (cursor == null) {
if (DEBUG) {
Log.e(TAG, "onQueryComplete: cursor == null");
}
return;
}
try {
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
String email = cursor.getString(PRESENCE_PROJECTION_EMAIL_INDEX);
int contactId = cursor.getInt(PRESENCE_PROJECTION_CONTACT_ID_INDEX);
ViewHolder vh = mViewHolders.get(email);
int photoId = cursor.getInt(PRESENCE_PROJECTION_PHOTO_ID_INDEX);
if (DEBUG) {
Log.e(TAG, "onQueryComplete Id: " + contactId + " PhotoId: " + photoId
+ " Email: " + email);
}
if (vh == null) {
continue;
}
ImageView presenceView = vh.presence;
if (presenceView != null) {
int status = cursor.getInt(PRESENCE_PROJECTION_PRESENCE_INDEX);
presenceView.setImageResource(Presence.getPresenceIconResourceId(status));
presenceView.setVisibility(View.VISIBLE);
}
if (photoId > 0 && vh.updateCounts < queryIndex) {
vh.updateCounts = queryIndex;
Uri personUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
// TODO, modify to batch queries together
ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext, vh.badge,
personUri, R.drawable.ic_contact_picture);
}
}
} finally {
cursor.close();
}
}
}
void updateResponse() {
// we only let the user accept/reject/etc. a meeting if:
// a) you can edit the event's containing calendar AND
// b) you're not the organizer and only attendee AND
// c) organizerCanRespond is enabled for the calendar
// (if the attendee data has been hidden, the visible number of attendees
// will be 1 -- the calendar owner's).
// (there are more cases involved to be 100% accurate, such as
// paying attention to whether or not an attendee status was
// included in the feed, but we're currently omitting those corner cases
// for simplicity).
if (!mCanModifyCalendar || (mHasAttendeeData && mIsOrganizer && mNumOfAttendees <= 1) ||
(mIsOrganizer && !mOrganizerCanRespond)) {
setVisibilityCommon(R.id.response_container, View.GONE);
return;
}
setVisibilityCommon(R.id.response_container, View.VISIBLE);
Spinner spinner = (Spinner) findViewById(R.id.response_value);
mResponseOffset = 0;
/* If the user has previously responded to this event
* we should not allow them to select no response again.
* Switch the entries to a set of entries without the
* no response option.
*/
if ((mOriginalAttendeeResponse != Attendees.ATTENDEE_STATUS_INVITED)
&& (mOriginalAttendeeResponse != ATTENDEE_NO_RESPONSE)
&& (mOriginalAttendeeResponse != Attendees.ATTENDEE_STATUS_NONE)) {
CharSequence[] entries;
entries = getResources().getTextArray(R.array.response_labels2);
mResponseOffset = -1;
ArrayAdapter<CharSequence> adapter =
new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item, entries);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
int index;
if (mAttendeeResponseFromIntent != ATTENDEE_NO_RESPONSE) {
index = findResponseIndexFor(mAttendeeResponseFromIntent);
} else {
index = findResponseIndexFor(mOriginalAttendeeResponse);
}
spinner.setSelection(index + mResponseOffset);
spinner.setOnItemSelectedListener(this);
}
private void setTextCommon(int id, CharSequence text) {
TextView textView = (TextView) findViewById(id);
if (textView == null)
return;
textView.setText(text);
}
private void setVisibilityCommon(int id, int visibility) {
View v = findViewById(id);
if (v != null) {
v.setVisibility(visibility);
}
return;
}
/**
* Taken from com.google.android.gm.HtmlConversationActivity
*
* Send the intent that shows the Contact info corresponding to the email address.
*/
public void showContactInfo(Attendee attendee, Rect rect) {
// First perform lookup query to find existing contact
final ContentResolver resolver = getContentResolver();
final String address = attendee.mEmail;
final Uri dataUri = Uri.withAppendedPath(CommonDataKinds.Email.CONTENT_FILTER_URI,
Uri.encode(address));
final Uri lookupUri = ContactsContract.Data.getContactLookupUri(resolver, dataUri);
if (lookupUri != null) {
// Found matching contact, trigger QuickContact
QuickContact.showQuickContact(this, rect, lookupUri, QuickContact.MODE_MEDIUM, null);
} else {
// No matching contact, ask user to create one
final Uri mailUri = Uri.fromParts("mailto", address, null);
final Intent intent = new Intent(Intents.SHOW_OR_CREATE_CONTACT, mailUri);
// Pass along full E-mail string for possible create dialog
Rfc822Token sender = new Rfc822Token(attendee.mName, attendee.mEmail, null);
intent.putExtra(Intents.EXTRA_CREATE_DESCRIPTION, sender.toString());
// Only provide personal name hint if we have one
final String senderPersonal = attendee.mName;
if (!TextUtils.isEmpty(senderPersonal)) {
intent.putExtra(Intents.Insert.NAME, senderPersonal);
}
startActivity(intent);
}
}
}
| true | true |
private void updateView() {
if (mEventCursor == null) {
return;
}
String eventName = mEventCursor.getString(EVENT_INDEX_TITLE);
if (eventName == null || eventName.length() == 0) {
Resources res = getResources();
eventName = res.getString(R.string.no_title_label);
}
boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
String location = mEventCursor.getString(EVENT_INDEX_EVENT_LOCATION);
String description = mEventCursor.getString(EVENT_INDEX_DESCRIPTION);
String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0;
String eventTimezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
mColor = mEventCursor.getInt(EVENT_INDEX_COLOR) & 0xbbffffff;
View calBackground = findViewById(R.id.cal_background);
calBackground.setBackgroundColor(mColor);
TextView title = (TextView) findViewById(R.id.title);
title.setTextColor(mColor);
View divider = findViewById(R.id.divider);
divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
// What
if (eventName != null) {
setTextCommon(R.id.title, eventName);
}
// When
String when;
int flags;
if (allDay) {
flags = DateUtils.FORMAT_UTC | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE;
} else {
flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE;
if (DateFormat.is24HourFormat(this)) {
flags |= DateUtils.FORMAT_24HOUR;
}
}
when = Utils.formatDateRange(this, mStartMillis, mEndMillis, flags);
setTextCommon(R.id.when, when);
// Show the event timezone if it is different from the local timezone
String localTimezone = Utils.getTimeZone(this, mUpdateTZ);
if (allDay) {
localTimezone = Time.TIMEZONE_UTC;
}
if (eventTimezone != null && !allDay &&
(!TextUtils.equals(localTimezone, eventTimezone) ||
!TextUtils.equals(localTimezone, Time.getCurrentTimezone()))) {
String displayName;
TimeZone tz = TimeZone.getTimeZone(localTimezone);
if (tz == null || tz.getID().equals("GMT")) {
displayName = localTimezone;
} else {
displayName = tz.getDisplayName();
}
setTextCommon(R.id.timezone, displayName);
} else {
setVisibilityCommon(R.id.timezone_container, View.GONE);
}
// Repeat
if (!TextUtils.isEmpty(rRule)) {
EventRecurrence eventRecurrence = new EventRecurrence();
eventRecurrence.parse(rRule);
Time date = new Time(Utils.getTimeZone(this, mUpdateTZ));
if (allDay) {
date.timezone = Time.TIMEZONE_UTC;
}
date.set(mStartMillis);
eventRecurrence.setStartDate(date);
String repeatString = EventRecurrenceFormatter.getRepeatString(getResources(),
eventRecurrence);
setTextCommon(R.id.repeat, repeatString);
} else {
setVisibilityCommon(R.id.repeat_container, View.GONE);
}
// Where
if (location == null || location.length() == 0) {
setVisibilityCommon(R.id.where, View.GONE);
} else {
final TextView textView = (TextView) findViewById(R.id.where);
if (textView != null) {
textView.setAutoLinkMask(0);
textView.setText(location);
Linkify.addLinks(textView, mWildcardPattern, "geo:0,0?q=");
textView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
try {
return v.onTouchEvent(event);
} catch (ActivityNotFoundException e) {
// ignore
return true;
}
}
});
}
}
// Description
if (description == null || description.length() == 0) {
setVisibilityCommon(R.id.description, View.GONE);
} else {
setTextCommon(R.id.description, description);
}
// Calendar
if (mCalendarsCursor != null) {
String calendarName = mCalendarsCursor.getString(CALENDARS_INDEX_DISPLAY_NAME);
String ownerAccount = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
if (mIsDuplicateName && !calendarName.equalsIgnoreCase(ownerAccount)) {
Resources res = getResources();
TextView ownerText = (TextView) findViewById(R.id.owner);
ownerText.setText(ownerAccount);
ownerText.setTextColor(res.getColor(R.color.calendar_owner_text_color));
} else {
setVisibilityCommon(R.id.owner, View.GONE);
}
setTextCommon(R.id.calendar, calendarName);
} else {
setVisibilityCommon(R.id.calendar_container, View.GONE);
}
}
|
private void updateView() {
if (mEventCursor == null) {
return;
}
String eventName = mEventCursor.getString(EVENT_INDEX_TITLE);
if (eventName == null || eventName.length() == 0) {
Resources res = getResources();
eventName = res.getString(R.string.no_title_label);
}
boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
String location = mEventCursor.getString(EVENT_INDEX_EVENT_LOCATION);
String description = mEventCursor.getString(EVENT_INDEX_DESCRIPTION);
String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0;
String eventTimezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
mColor = mEventCursor.getInt(EVENT_INDEX_COLOR) & 0xbbffffff;
View calBackground = findViewById(R.id.cal_background);
calBackground.setBackgroundColor(mColor);
TextView title = (TextView) findViewById(R.id.title);
title.setTextColor(mColor);
View divider = findViewById(R.id.divider);
divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
// What
if (eventName != null) {
setTextCommon(R.id.title, eventName);
}
// When
String when;
int flags;
if (allDay) {
flags = DateUtils.FORMAT_UTC | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE;
} else {
flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE;
if (DateFormat.is24HourFormat(this)) {
flags |= DateUtils.FORMAT_24HOUR;
}
}
when = Utils.formatDateRange(this, mStartMillis, mEndMillis, flags);
setTextCommon(R.id.when, when);
// Show the event timezone if it is different from the local timezone
String localTimezone = Utils.getTimeZone(this, mUpdateTZ);
if (allDay) {
localTimezone = Time.TIMEZONE_UTC;
}
if (eventTimezone != null && !allDay &&
(!TextUtils.equals(localTimezone, eventTimezone) ||
!TextUtils.equals(localTimezone, Time.getCurrentTimezone()))) {
String displayName;
TimeZone tz = TimeZone.getTimeZone(localTimezone);
if (tz == null || tz.getID().equals("GMT")) {
displayName = localTimezone;
} else {
displayName = tz.getDisplayName();
}
setTextCommon(R.id.timezone, displayName);
} else {
setVisibilityCommon(R.id.timezone_container, View.GONE);
}
// Repeat
if (!TextUtils.isEmpty(rRule)) {
EventRecurrence eventRecurrence = new EventRecurrence();
eventRecurrence.parse(rRule);
Time date = new Time(Utils.getTimeZone(this, mUpdateTZ));
if (allDay) {
date.timezone = Time.TIMEZONE_UTC;
}
date.set(mStartMillis);
eventRecurrence.setStartDate(date);
String repeatString = EventRecurrenceFormatter.getRepeatString(getResources(),
eventRecurrence);
setTextCommon(R.id.repeat, repeatString);
} else {
setVisibilityCommon(R.id.repeat_container, View.GONE);
}
// Where
if (location == null || location.length() == 0) {
setVisibilityCommon(R.id.where, View.GONE);
} else {
final TextView textView = (TextView) findViewById(R.id.where);
if (textView != null) {
textView.setAutoLinkMask(0);
textView.setText(location);
if (!Linkify.addLinks(textView, Linkify.WEB_URLS |
Linkify.EMAIL_ADDRESSES | Linkify.MAP_ADDRESSES)) {
Linkify.addLinks(textView, mWildcardPattern, "geo:0,0?q=");
}
textView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
try {
return v.onTouchEvent(event);
} catch (ActivityNotFoundException e) {
// ignore
return true;
}
}
});
}
}
// Description
if (description == null || description.length() == 0) {
setVisibilityCommon(R.id.description, View.GONE);
} else {
setTextCommon(R.id.description, description);
}
// Calendar
if (mCalendarsCursor != null) {
String calendarName = mCalendarsCursor.getString(CALENDARS_INDEX_DISPLAY_NAME);
String ownerAccount = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
if (mIsDuplicateName && !calendarName.equalsIgnoreCase(ownerAccount)) {
Resources res = getResources();
TextView ownerText = (TextView) findViewById(R.id.owner);
ownerText.setText(ownerAccount);
ownerText.setTextColor(res.getColor(R.color.calendar_owner_text_color));
} else {
setVisibilityCommon(R.id.owner, View.GONE);
}
setTextCommon(R.id.calendar, calendarName);
} else {
setVisibilityCommon(R.id.calendar_container, View.GONE);
}
}
|
diff --git a/src/main/java/org/mvel/MVELRuntime.java b/src/main/java/org/mvel/MVELRuntime.java
index 083a4cbc..32739d04 100644
--- a/src/main/java/org/mvel/MVELRuntime.java
+++ b/src/main/java/org/mvel/MVELRuntime.java
@@ -1,284 +1,285 @@
package org.mvel;
import static org.mvel.DataConversion.canConvert;
import static org.mvel.Operator.*;
import static org.mvel.Soundex.soundex;
import org.mvel.ast.LineLabel;
import org.mvel.debug.Debugger;
import org.mvel.debug.DebuggerContext;
import org.mvel.integration.VariableResolverFactory;
import org.mvel.util.ExecutionStack;
import static org.mvel.util.ParseTools.containsCheck;
import static org.mvel.util.PropertyTools.isEmpty;
import static org.mvel.util.PropertyTools.similarity;
import org.mvel.util.Stack;
import org.mvel.util.StringAppender;
import static java.lang.Class.forName;
import static java.lang.String.valueOf;
/**
* This class contains the runtime for running compiled MVEL expressions.
*/
public class MVELRuntime {
// private static ThreadLocal<Map<String, Set<Integer>>> threadBreakpoints;
// private static ThreadLocal<Debugger> threadDebugger;
private static ThreadLocal<DebuggerContext> debuggerContext;
/**
* Main interpreter.
*
* @param debugger -
* @param expression -
* @param ctx -
* @param variableFactory -
* @return -
* @see org.mvel.MVEL
*/
public static Object execute(boolean debugger, CompiledExpression expression, Object ctx, VariableResolverFactory variableFactory) {
final ASTLinkedList node = new ASTLinkedList(expression.getTokens().firstNode());
Stack stk = new ExecutionStack();
Object v1, v2;
ASTNode tk = null;
Integer operator;
try {
while ((tk = node.nextNode()) != null) {
if (tk.fields == -1) {
/**
* This may seem silly and redundant, however, when an MVEL script recurses into a block
* or substatement, a new runtime loop is entered. Since the debugger state is not
* passed through the AST, it is not possible to forward the state directly. So when we
* encounter a debugging symbol, we check the thread local to see if there is are registered
* breakpoints. If we find them, we assume that we are debugging.
*
* The consequence of this of course, is that it's not ideal to compile expressions with
* debugging symbols which you plan to use in a production enviroment.
*/
if (!debugger && hasDebuggerContext()) {
debugger = true;
}
/**
* If we're not debugging, we'll just skip over this.
*/
if (debugger) {
LineLabel label = (LineLabel) tk;
DebuggerContext context = debuggerContext.get();
try {
context.checkBreak(label, variableFactory, expression);
+ tk = node.nextNode();
// if (context.checkBreak(label, variableFactory, expression) == Debugger.STEP_OVER) {
// node.nextNode();
// }
}
catch (NullPointerException e) {
// do nothing for now. this isn't as calus as it seems.
}
}
continue;
}
if (stk.isEmpty()) {
stk.push(tk.getReducedValueAccelerated(ctx, ctx, variableFactory));
}
if (!tk.isOperator()) {
continue;
}
switch (operator = tk.getOperator()) {
case TERNARY:
if (!(Boolean) stk.pop()) {
//noinspection StatementWithEmptyBody
while (node.hasMoreNodes() && !node.nextNode().isOperator(Operator.TERNARY_ELSE)) ;
}
stk.clear();
continue;
case TERNARY_ELSE:
return stk.pop();
case END_OF_STMT:
/**
* If the program doesn't end here then we wipe anything off the stack that remains.
* Althought it may seem like intuitive stack optimizations could be leveraged by
* leaving hanging values on the stack, trust me it's not a good idea.
*/
if (node.hasMoreNodes()) {
stk.clear();
}
continue;
}
stk.push(node.nextNode().getReducedValueAccelerated(ctx, ctx, variableFactory), operator);
try {
while (stk.size() > 1) {
operator = (Integer) stk.pop();
v1 = stk.pop();
v2 = stk.pop();
switch (operator) {
case CHOR:
if (!isEmpty(v2) || !isEmpty(v1)) {
stk.clear();
stk.push(!isEmpty(v2) ? v2 : v1);
}
else stk.push(null);
break;
case INSTANCEOF:
if (v1 instanceof Class)
stk.push(((Class) v1).isInstance(v2));
else
stk.push(forName(valueOf(v1)).isInstance(v2));
break;
case CONVERTABLE_TO:
if (v1 instanceof Class)
stk.push(canConvert(v2.getClass(), (Class) v1));
else
stk.push(canConvert(v2.getClass(), forName(valueOf(v1))));
break;
case CONTAINS:
stk.push(containsCheck(v2, v1));
break;
case BW_AND:
stk.push((Integer) v2 & (Integer) v1);
break;
case BW_OR:
stk.push((Integer) v2 | (Integer) v1);
break;
case BW_XOR:
stk.push((Integer) v2 ^ (Integer) v1);
break;
case BW_SHIFT_LEFT:
stk.push((Integer) v2 << (Integer) v1);
break;
case BW_USHIFT_LEFT:
int iv2 = (Integer) v2;
if (iv2 < 0) iv2 *= -1;
stk.push(iv2 << (Integer) v1);
break;
case BW_SHIFT_RIGHT:
stk.push((Integer) v2 >> (Integer) v1);
break;
case BW_USHIFT_RIGHT:
stk.push((Integer) v2 >>> (Integer) v1);
break;
case STR_APPEND:
stk.push(new StringAppender(valueOf(v2)).append(valueOf(v1)).toString());
break;
case SOUNDEX:
stk.push(soundex(valueOf(v1)).equals(soundex(valueOf(v2))));
break;
case SIMILARITY:
stk.push(similarity(valueOf(v1), valueOf(v2)));
break;
}
}
}
catch (ClassCastException e) {
throw new CompileException("syntax error or incomptable types", e);
}
catch (Exception e) {
throw new CompileException("failed to subEval expression", e);
}
}
return stk.peek();
}
catch (NullPointerException e) {
if (tk != null && tk.isOperator() && !node.hasMoreNodes()) {
throw new CompileException("incomplete statement: "
+ tk.getName() + " (possible use of reserved keyword as identifier: " + tk.getName() + ")");
}
else {
throw e;
}
}
}
/**
* Register a debugger breakpoint.
*
* @param source - the source file the breakpoint is registered in
* @param line - the line number of the breakpoint
*/
public static void registerBreakpoint(String source, int line) {
ensureDebuggerContext();
debuggerContext.get().registerBreakpoint(source, line);
}
/**
* Remove a specific breakpoint.
*
* @param source - the source file the breakpoint is registered in
* @param line - the line number of the breakpoint to be removed
*/
public static void removeBreakpoint(String source, int line) {
if (hasDebuggerContext()) {
debuggerContext.get().removeBreakpoint(source, line);
}
}
private static boolean hasDebuggerContext() {
return debuggerContext != null && debuggerContext.get() != null;
}
private static void ensureDebuggerContext() {
if (debuggerContext == null) debuggerContext = new ThreadLocal<DebuggerContext>();
if (debuggerContext.get() == null) debuggerContext.set(new DebuggerContext());
}
/**
* Reset all the currently registered breakpoints.
*/
public static void clearAllBreakpoints() {
if (hasDebuggerContext()) {
debuggerContext.get().clearAllBreakpoints();
}
}
public static boolean hasBreakpoints() {
return hasDebuggerContext() && debuggerContext.get().hasBreakpoints();
}
/**
* Sets the Debugger instance to handle breakpoints. A debugger may only be registered once per thread.
* Calling this method more than once will result in the second and subsequent calls to simply fail silently.
* To re-register the Debugger, you must call {@link #resetDebugger}
* @param debugger - debugger instance
*/
public static void setThreadDebugger(Debugger debugger) {
ensureDebuggerContext();
debuggerContext.get().setDebugger(debugger);
}
/**
* Reset all information registered in the debugger, including the actual attached Debugger and registered
* breakpoints.
*/
public static void resetDebugger() {
debuggerContext = null;
}
}
| true | true |
public static Object execute(boolean debugger, CompiledExpression expression, Object ctx, VariableResolverFactory variableFactory) {
final ASTLinkedList node = new ASTLinkedList(expression.getTokens().firstNode());
Stack stk = new ExecutionStack();
Object v1, v2;
ASTNode tk = null;
Integer operator;
try {
while ((tk = node.nextNode()) != null) {
if (tk.fields == -1) {
/**
* This may seem silly and redundant, however, when an MVEL script recurses into a block
* or substatement, a new runtime loop is entered. Since the debugger state is not
* passed through the AST, it is not possible to forward the state directly. So when we
* encounter a debugging symbol, we check the thread local to see if there is are registered
* breakpoints. If we find them, we assume that we are debugging.
*
* The consequence of this of course, is that it's not ideal to compile expressions with
* debugging symbols which you plan to use in a production enviroment.
*/
if (!debugger && hasDebuggerContext()) {
debugger = true;
}
/**
* If we're not debugging, we'll just skip over this.
*/
if (debugger) {
LineLabel label = (LineLabel) tk;
DebuggerContext context = debuggerContext.get();
try {
context.checkBreak(label, variableFactory, expression);
// if (context.checkBreak(label, variableFactory, expression) == Debugger.STEP_OVER) {
// node.nextNode();
// }
}
catch (NullPointerException e) {
// do nothing for now. this isn't as calus as it seems.
}
}
continue;
}
if (stk.isEmpty()) {
stk.push(tk.getReducedValueAccelerated(ctx, ctx, variableFactory));
}
if (!tk.isOperator()) {
continue;
}
switch (operator = tk.getOperator()) {
case TERNARY:
if (!(Boolean) stk.pop()) {
//noinspection StatementWithEmptyBody
while (node.hasMoreNodes() && !node.nextNode().isOperator(Operator.TERNARY_ELSE)) ;
}
stk.clear();
continue;
case TERNARY_ELSE:
return stk.pop();
case END_OF_STMT:
/**
* If the program doesn't end here then we wipe anything off the stack that remains.
* Althought it may seem like intuitive stack optimizations could be leveraged by
* leaving hanging values on the stack, trust me it's not a good idea.
*/
if (node.hasMoreNodes()) {
stk.clear();
}
continue;
}
stk.push(node.nextNode().getReducedValueAccelerated(ctx, ctx, variableFactory), operator);
try {
while (stk.size() > 1) {
operator = (Integer) stk.pop();
v1 = stk.pop();
v2 = stk.pop();
switch (operator) {
case CHOR:
if (!isEmpty(v2) || !isEmpty(v1)) {
stk.clear();
stk.push(!isEmpty(v2) ? v2 : v1);
}
else stk.push(null);
break;
case INSTANCEOF:
if (v1 instanceof Class)
stk.push(((Class) v1).isInstance(v2));
else
stk.push(forName(valueOf(v1)).isInstance(v2));
break;
case CONVERTABLE_TO:
if (v1 instanceof Class)
stk.push(canConvert(v2.getClass(), (Class) v1));
else
stk.push(canConvert(v2.getClass(), forName(valueOf(v1))));
break;
case CONTAINS:
stk.push(containsCheck(v2, v1));
break;
case BW_AND:
stk.push((Integer) v2 & (Integer) v1);
break;
case BW_OR:
stk.push((Integer) v2 | (Integer) v1);
break;
case BW_XOR:
stk.push((Integer) v2 ^ (Integer) v1);
break;
case BW_SHIFT_LEFT:
stk.push((Integer) v2 << (Integer) v1);
break;
case BW_USHIFT_LEFT:
int iv2 = (Integer) v2;
if (iv2 < 0) iv2 *= -1;
stk.push(iv2 << (Integer) v1);
break;
case BW_SHIFT_RIGHT:
stk.push((Integer) v2 >> (Integer) v1);
break;
case BW_USHIFT_RIGHT:
stk.push((Integer) v2 >>> (Integer) v1);
break;
case STR_APPEND:
stk.push(new StringAppender(valueOf(v2)).append(valueOf(v1)).toString());
break;
case SOUNDEX:
stk.push(soundex(valueOf(v1)).equals(soundex(valueOf(v2))));
break;
case SIMILARITY:
stk.push(similarity(valueOf(v1), valueOf(v2)));
break;
}
}
}
catch (ClassCastException e) {
throw new CompileException("syntax error or incomptable types", e);
}
catch (Exception e) {
throw new CompileException("failed to subEval expression", e);
}
}
return stk.peek();
}
catch (NullPointerException e) {
if (tk != null && tk.isOperator() && !node.hasMoreNodes()) {
throw new CompileException("incomplete statement: "
+ tk.getName() + " (possible use of reserved keyword as identifier: " + tk.getName() + ")");
}
else {
throw e;
}
}
}
|
public static Object execute(boolean debugger, CompiledExpression expression, Object ctx, VariableResolverFactory variableFactory) {
final ASTLinkedList node = new ASTLinkedList(expression.getTokens().firstNode());
Stack stk = new ExecutionStack();
Object v1, v2;
ASTNode tk = null;
Integer operator;
try {
while ((tk = node.nextNode()) != null) {
if (tk.fields == -1) {
/**
* This may seem silly and redundant, however, when an MVEL script recurses into a block
* or substatement, a new runtime loop is entered. Since the debugger state is not
* passed through the AST, it is not possible to forward the state directly. So when we
* encounter a debugging symbol, we check the thread local to see if there is are registered
* breakpoints. If we find them, we assume that we are debugging.
*
* The consequence of this of course, is that it's not ideal to compile expressions with
* debugging symbols which you plan to use in a production enviroment.
*/
if (!debugger && hasDebuggerContext()) {
debugger = true;
}
/**
* If we're not debugging, we'll just skip over this.
*/
if (debugger) {
LineLabel label = (LineLabel) tk;
DebuggerContext context = debuggerContext.get();
try {
context.checkBreak(label, variableFactory, expression);
tk = node.nextNode();
// if (context.checkBreak(label, variableFactory, expression) == Debugger.STEP_OVER) {
// node.nextNode();
// }
}
catch (NullPointerException e) {
// do nothing for now. this isn't as calus as it seems.
}
}
continue;
}
if (stk.isEmpty()) {
stk.push(tk.getReducedValueAccelerated(ctx, ctx, variableFactory));
}
if (!tk.isOperator()) {
continue;
}
switch (operator = tk.getOperator()) {
case TERNARY:
if (!(Boolean) stk.pop()) {
//noinspection StatementWithEmptyBody
while (node.hasMoreNodes() && !node.nextNode().isOperator(Operator.TERNARY_ELSE)) ;
}
stk.clear();
continue;
case TERNARY_ELSE:
return stk.pop();
case END_OF_STMT:
/**
* If the program doesn't end here then we wipe anything off the stack that remains.
* Althought it may seem like intuitive stack optimizations could be leveraged by
* leaving hanging values on the stack, trust me it's not a good idea.
*/
if (node.hasMoreNodes()) {
stk.clear();
}
continue;
}
stk.push(node.nextNode().getReducedValueAccelerated(ctx, ctx, variableFactory), operator);
try {
while (stk.size() > 1) {
operator = (Integer) stk.pop();
v1 = stk.pop();
v2 = stk.pop();
switch (operator) {
case CHOR:
if (!isEmpty(v2) || !isEmpty(v1)) {
stk.clear();
stk.push(!isEmpty(v2) ? v2 : v1);
}
else stk.push(null);
break;
case INSTANCEOF:
if (v1 instanceof Class)
stk.push(((Class) v1).isInstance(v2));
else
stk.push(forName(valueOf(v1)).isInstance(v2));
break;
case CONVERTABLE_TO:
if (v1 instanceof Class)
stk.push(canConvert(v2.getClass(), (Class) v1));
else
stk.push(canConvert(v2.getClass(), forName(valueOf(v1))));
break;
case CONTAINS:
stk.push(containsCheck(v2, v1));
break;
case BW_AND:
stk.push((Integer) v2 & (Integer) v1);
break;
case BW_OR:
stk.push((Integer) v2 | (Integer) v1);
break;
case BW_XOR:
stk.push((Integer) v2 ^ (Integer) v1);
break;
case BW_SHIFT_LEFT:
stk.push((Integer) v2 << (Integer) v1);
break;
case BW_USHIFT_LEFT:
int iv2 = (Integer) v2;
if (iv2 < 0) iv2 *= -1;
stk.push(iv2 << (Integer) v1);
break;
case BW_SHIFT_RIGHT:
stk.push((Integer) v2 >> (Integer) v1);
break;
case BW_USHIFT_RIGHT:
stk.push((Integer) v2 >>> (Integer) v1);
break;
case STR_APPEND:
stk.push(new StringAppender(valueOf(v2)).append(valueOf(v1)).toString());
break;
case SOUNDEX:
stk.push(soundex(valueOf(v1)).equals(soundex(valueOf(v2))));
break;
case SIMILARITY:
stk.push(similarity(valueOf(v1), valueOf(v2)));
break;
}
}
}
catch (ClassCastException e) {
throw new CompileException("syntax error or incomptable types", e);
}
catch (Exception e) {
throw new CompileException("failed to subEval expression", e);
}
}
return stk.peek();
}
catch (NullPointerException e) {
if (tk != null && tk.isOperator() && !node.hasMoreNodes()) {
throw new CompileException("incomplete statement: "
+ tk.getName() + " (possible use of reserved keyword as identifier: " + tk.getName() + ")");
}
else {
throw e;
}
}
}
|
diff --git a/src/contributions/resources/search/src/java/org/wyona/yanel/impl/resources/search/SearchResource.java b/src/contributions/resources/search/src/java/org/wyona/yanel/impl/resources/search/SearchResource.java
index 67fe23961..816aac40a 100644
--- a/src/contributions/resources/search/src/java/org/wyona/yanel/impl/resources/search/SearchResource.java
+++ b/src/contributions/resources/search/src/java/org/wyona/yanel/impl/resources/search/SearchResource.java
@@ -1,226 +1,226 @@
/*
* Copyright 2009 Wyona
*/
package org.wyona.yanel.impl.resources.search;
import org.wyona.yanel.core.attributes.viewable.View;
import org.wyona.yanel.impl.resources.BasicXMLResource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.apache.log4j.Logger;
import org.wyona.meguni.parser.Parser;
import org.wyona.meguni.util.ResultSet;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationUtil;
/**
* Search resource
*/
public class SearchResource extends BasicXMLResource {
private static Logger log = Logger.getLogger(SearchResource.class);
private static String PROVIDER_NAME = "provider";
private static String QUERY_NAME = "q";
private static String DOMAIN_NAME = "domain";
private static String DEFAULT_PROVIDER = "yanel";
/**
* @see org.wyona.yanel.core.api.attributes.ViewableV2#getView(String)
*/
public View getView(String viewId) throws Exception {
String provider = getRequest().getParameter(PROVIDER_NAME);
if (provider != null && !provider.equals(DEFAULT_PROVIDER)) {
ExternalSearchProvider esp = getExternalSearchProvider(provider);
if (esp != null) {
View view = new View();
view.setResponse(false); // this resource writes the response itself
javax.servlet.http.HttpServletResponse response = getResponse();
response.setStatus(307);
String query = getRequest().getParameter(QUERY_NAME);
String domain = getRequest().getParameter(DOMAIN_NAME);
String site="";
if (domain != null) site = "+site:" + domain; // TODO: This will work for Google and bing, but is this true for all search engines?
response.setHeader("Location", esp.getURL() + query + site);
return view;
}
}
return super.getView(viewId);
}
/*
* @see org.wyona.yanel.impl.resources.BasicXMLResource#getContentXML(String)
*/
protected InputStream getContentXML(String viewId) throws Exception {
if (log.isDebugEnabled()) {
log.debug("requested viewId: " + viewId);
}
StringBuilder sb = new StringBuilder("<?xml version=\"1.0\"?>");
sb.append("<y:search xmlns:y=\"http://www.wyona.org/yanel/search/1.0\">");
String provider = getRequest().getParameter(PROVIDER_NAME);
if (provider == null) {
provider = DEFAULT_PROVIDER;
log.warn("No search provider specified! Default provider will be used: " + provider);
}
sb.append("<y:provider id=\"" + provider + "\">" + provider + "</y:provider>");
String query = getRequest().getParameter(QUERY_NAME);
if (query != null && query.length() > 0) {
sb.append("<y:query>" + query + "</y:query>");
try {
Result[] results;
if (provider.equals(DEFAULT_PROVIDER)) {
results = getLocalResults(query);
- } else if (provider.equals("google")) {
+ } else if (provider.equals("yanelproxy-google")) {
results = getGoogleResults(query);
- } else if (provider.equals("bing")) {
+ } else if (provider.equals("yanelproxy-msn")) {
results = getMSNResults(query);
} else {
results = new Result[0];
String eMessage = "No such provider: " + provider;
log.warn(eMessage);
sb.append("<y:exception>" + eMessage + "</y:exception>");
}
if (results != null && results.length > 0) {
sb.append("<y:results>");
for (int i = 0; i < results.length; i++) {
sb.append("<y:result url=\"" + results[i].getURL() + "\">");
if (results[i].getTitle() != null) {
sb.append(" <y:title>" + results[i].getTitle() + "</y:title>");
} else {
sb.append(" <y:no-title/>");
}
sb.append("</y:result>");
}
sb.append("</y:results>");
}
} catch(org.wyona.yarep.core.search.SearchException e) {
log.error(e, e);
sb.append("<y:exception>" + e.getMessage() + "</y:exception>");
}
} else {
sb.append("<y:no-query/>");
}
sb.append("</y:search>");
return new ByteArrayInputStream(sb.toString().getBytes());
}
/**
*
*/
private Result[] getLocalResults(String query) throws Exception {
if (query != null && query.length() > 0) {
org.wyona.yarep.core.Node[] nodes = getRealm().getRepository().getSearcher().search(query);
if (nodes != null && nodes.length > 0) {
Result[] results = new Result[nodes.length];
for (int i = 0; i < nodes.length; i++) {
results[i] = new Result(nodes[i].getPath(), null, null, nodes[i].getMimeType());
}
return results;
} else {
log.info("Nothing found for query: " + query);
return new Result[0];
}
}
log.warn("No query specified!");
return new Result[0];
}
/**
*
*/
private Result[] getGoogleResults(String query) throws Exception {
String className = getResourceConfigProperty("parser");
if (className == null) className = "org.wyona.meguni.parser.impl.GoogleParser";
//if (className == null) className = "org.wyona.meguni.parser.impl.MSNParser";
Parser parser = (Parser) Class.forName(className).newInstance();
ResultSet rs = parser.parse(query);
if (rs != null && rs.size() > 0) {
Result[] results = new Result[rs.size()];
for (int i = 0; i < rs.size(); i++) {
results[i] = new Result(rs.get(i).url.toString(), null, null, null);
}
return results;
} else {
return new Result[0];
}
}
/**
*
*/
private Result[] getMSNResults(String query) throws Exception {
String className = getResourceConfigProperty("parser");
if (className == null) className = "org.wyona.meguni.parser.impl.MSNParser";
Parser parser = (Parser) Class.forName(className).newInstance();
ResultSet rs = parser.parse(query);
if (rs != null && rs.size() > 0) {
Result[] results = new Result[rs.size()];
for (int i = 0; i < rs.size(); i++) {
results[i] = new Result(rs.get(i).url.toString(), null, null, null);
}
return results;
} else {
return new Result[0];
}
}
/**
* @see org.wyona.yanel.core.api.attributes.ViewableV2#exists()
*/
public boolean exists() throws Exception {
return true;
}
/**
*
*/
private ExternalSearchProvider getExternalSearchProvider(String providerId) throws Exception {
org.w3c.dom.Document customConfigDoc = getConfiguration().getCustomConfiguration();
if (customConfigDoc != null) {
Configuration config = ConfigurationUtil.toConfiguration(customConfigDoc.getDocumentElement());
Configuration externalSearchProvidersConfig = config.getChild("external-search-providers");
Configuration[] searchProviders = externalSearchProvidersConfig.getChildren("provider");
for (int i = 0; i < searchProviders.length; i++) {
if (searchProviders[i].getAttribute("id").equals(providerId)) {
return new ExternalSearchProvider(providerId, searchProviders[i].getAttribute("url"), null);
}
}
}
return null;
}
}
/**
*
*/
class ExternalSearchProvider {
private String url;
/**
*
*/
public ExternalSearchProvider(String id, String url, String label) {
this.url = url;
}
/**
*
*/
public String getURL() {
return url;
}
}
| false | true |
protected InputStream getContentXML(String viewId) throws Exception {
if (log.isDebugEnabled()) {
log.debug("requested viewId: " + viewId);
}
StringBuilder sb = new StringBuilder("<?xml version=\"1.0\"?>");
sb.append("<y:search xmlns:y=\"http://www.wyona.org/yanel/search/1.0\">");
String provider = getRequest().getParameter(PROVIDER_NAME);
if (provider == null) {
provider = DEFAULT_PROVIDER;
log.warn("No search provider specified! Default provider will be used: " + provider);
}
sb.append("<y:provider id=\"" + provider + "\">" + provider + "</y:provider>");
String query = getRequest().getParameter(QUERY_NAME);
if (query != null && query.length() > 0) {
sb.append("<y:query>" + query + "</y:query>");
try {
Result[] results;
if (provider.equals(DEFAULT_PROVIDER)) {
results = getLocalResults(query);
} else if (provider.equals("google")) {
results = getGoogleResults(query);
} else if (provider.equals("bing")) {
results = getMSNResults(query);
} else {
results = new Result[0];
String eMessage = "No such provider: " + provider;
log.warn(eMessage);
sb.append("<y:exception>" + eMessage + "</y:exception>");
}
if (results != null && results.length > 0) {
sb.append("<y:results>");
for (int i = 0; i < results.length; i++) {
sb.append("<y:result url=\"" + results[i].getURL() + "\">");
if (results[i].getTitle() != null) {
sb.append(" <y:title>" + results[i].getTitle() + "</y:title>");
} else {
sb.append(" <y:no-title/>");
}
sb.append("</y:result>");
}
sb.append("</y:results>");
}
} catch(org.wyona.yarep.core.search.SearchException e) {
log.error(e, e);
sb.append("<y:exception>" + e.getMessage() + "</y:exception>");
}
} else {
sb.append("<y:no-query/>");
}
sb.append("</y:search>");
return new ByteArrayInputStream(sb.toString().getBytes());
}
|
protected InputStream getContentXML(String viewId) throws Exception {
if (log.isDebugEnabled()) {
log.debug("requested viewId: " + viewId);
}
StringBuilder sb = new StringBuilder("<?xml version=\"1.0\"?>");
sb.append("<y:search xmlns:y=\"http://www.wyona.org/yanel/search/1.0\">");
String provider = getRequest().getParameter(PROVIDER_NAME);
if (provider == null) {
provider = DEFAULT_PROVIDER;
log.warn("No search provider specified! Default provider will be used: " + provider);
}
sb.append("<y:provider id=\"" + provider + "\">" + provider + "</y:provider>");
String query = getRequest().getParameter(QUERY_NAME);
if (query != null && query.length() > 0) {
sb.append("<y:query>" + query + "</y:query>");
try {
Result[] results;
if (provider.equals(DEFAULT_PROVIDER)) {
results = getLocalResults(query);
} else if (provider.equals("yanelproxy-google")) {
results = getGoogleResults(query);
} else if (provider.equals("yanelproxy-msn")) {
results = getMSNResults(query);
} else {
results = new Result[0];
String eMessage = "No such provider: " + provider;
log.warn(eMessage);
sb.append("<y:exception>" + eMessage + "</y:exception>");
}
if (results != null && results.length > 0) {
sb.append("<y:results>");
for (int i = 0; i < results.length; i++) {
sb.append("<y:result url=\"" + results[i].getURL() + "\">");
if (results[i].getTitle() != null) {
sb.append(" <y:title>" + results[i].getTitle() + "</y:title>");
} else {
sb.append(" <y:no-title/>");
}
sb.append("</y:result>");
}
sb.append("</y:results>");
}
} catch(org.wyona.yarep.core.search.SearchException e) {
log.error(e, e);
sb.append("<y:exception>" + e.getMessage() + "</y:exception>");
}
} else {
sb.append("<y:no-query/>");
}
sb.append("</y:search>");
return new ByteArrayInputStream(sb.toString().getBytes());
}
|
diff --git a/src/test/java/no/niths/infrastructure/CommitteeRepositoryTest.java b/src/test/java/no/niths/infrastructure/CommitteeRepositoryTest.java
index e8d2b75d..233116c6 100644
--- a/src/test/java/no/niths/infrastructure/CommitteeRepositoryTest.java
+++ b/src/test/java/no/niths/infrastructure/CommitteeRepositoryTest.java
@@ -1,108 +1,108 @@
package no.niths.infrastructure;
import static org.junit.Assert.assertEquals;
import no.niths.common.config.HibernateConfig;
import no.niths.common.config.TestAppConfig;
import no.niths.domain.Committee;
import no.niths.domain.Event;
import no.niths.domain.Student;
import no.niths.infrastructure.interfaces.CommitteeRepositorty;
import no.niths.infrastructure.interfaces.StudentRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes= { TestAppConfig.class, HibernateConfig.class})
@Transactional
@TransactionConfiguration(transactionManager = "transactionManager")
public class CommitteeRepositoryTest {
@Autowired
private CommitteeRepositorty committeeRepo;
@Autowired
private StudentRepository studentRepo;
@Test
public void testAddLeader(){
Student s1 = new Student("John", "Doe");
- s1.setEmail("[email protected]");
+ s1.setEmail("[email protected]");
Student s2 = new Student("Jane", "Doe");
- s2.setEmail("[email protected]");
+ s2.setEmail("[email protected]");
studentRepo.create(s1);
studentRepo.create(s2);
Committee c1 = new Committee("Linux", "1337");
c1.getLeaders().add(s1);
committeeRepo.create(c1);
assertEquals(1, c1.getLeaders().size());
Student s3 = studentRepo.getById(s1.getId());
assertEquals(0, s3.getCommittees().size());
}
@Test
public void testCRUD() {
int size = committeeRepo.getAll(null).size();
Committee committee = new Committee("LUG", "Linux");
committee.setId(committeeRepo.create(committee));
assertEquals(size + 1, committeeRepo.getAll(null).size());
assertEquals(committee, committeeRepo.getById(committee.getId()));
committee.setName("LINUXs");
committeeRepo.update(committee);
assertEquals(committee, committeeRepo.getById(committee.getId()));
committeeRepo.delete(committee.getId());
assertEquals(size, committeeRepo.getAll(null).size());
}
@Test
public void testGetAllWithCreateCritera(){
Committee c1 = new Committee("LUG", "23");
Committee c2 = new Committee("LAG", "Linux");
Committee c3 = new Committee("ads", "Linux");
committeeRepo.create(c1);
committeeRepo.create(c2);
committeeRepo.create(c3);
c1.setDescription(null);
assertEquals(1, committeeRepo.getAll(c1).size());
c3.setName(null);
assertEquals(2, committeeRepo.getAll(c3).size());
}
@Test
public void testEventJoin(){
Event event = new Event();
event.setName("Joe");
Committee committee = new Committee("LUG", "Linux");
committee.getEvents().add(event);
committeeRepo.create(committee);
Committee temp = committeeRepo.getById(committee.getId());
assertEquals(committee, temp);
assertEquals(1, temp.getEvents().size());
}
}
| false | true |
public void testAddLeader(){
Student s1 = new Student("John", "Doe");
s1.setEmail("[email protected]");
Student s2 = new Student("Jane", "Doe");
s2.setEmail("[email protected]");
studentRepo.create(s1);
studentRepo.create(s2);
Committee c1 = new Committee("Linux", "1337");
c1.getLeaders().add(s1);
committeeRepo.create(c1);
assertEquals(1, c1.getLeaders().size());
Student s3 = studentRepo.getById(s1.getId());
assertEquals(0, s3.getCommittees().size());
}
|
public void testAddLeader(){
Student s1 = new Student("John", "Doe");
s1.setEmail("[email protected]");
Student s2 = new Student("Jane", "Doe");
s2.setEmail("[email protected]");
studentRepo.create(s1);
studentRepo.create(s2);
Committee c1 = new Committee("Linux", "1337");
c1.getLeaders().add(s1);
committeeRepo.create(c1);
assertEquals(1, c1.getLeaders().size());
Student s3 = studentRepo.getById(s1.getId());
assertEquals(0, s3.getCommittees().size());
}
|
diff --git a/oak-core/src/test/java/org/apache/jackrabbit/oak/kernel/KernelNodeStateEditorFuzzTest.java b/oak-core/src/test/java/org/apache/jackrabbit/oak/kernel/KernelNodeStateEditorFuzzTest.java
index fa648e4c34..253333f6b0 100644
--- a/oak-core/src/test/java/org/apache/jackrabbit/oak/kernel/KernelNodeStateEditorFuzzTest.java
+++ b/oak-core/src/test/java/org/apache/jackrabbit/oak/kernel/KernelNodeStateEditorFuzzTest.java
@@ -1,448 +1,447 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.jackrabbit.oak.kernel;
import org.apache.jackrabbit.mk.api.MicroKernel;
import org.apache.jackrabbit.mk.model.ChildNodeEntry;
import org.apache.jackrabbit.mk.model.PropertyState;
import org.apache.jackrabbit.mk.model.Scalar;
import org.apache.jackrabbit.mk.model.ScalarImpl;
import org.apache.jackrabbit.mk.simple.SimpleKernelImpl;
import org.apache.jackrabbit.mk.util.PathUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import static org.apache.jackrabbit.oak.kernel.KernelNodeStateEditorFuzzTest.Operation.AddNode;
import static org.apache.jackrabbit.oak.kernel.KernelNodeStateEditorFuzzTest.Operation.MoveNode;
import static org.apache.jackrabbit.oak.kernel.KernelNodeStateEditorFuzzTest.Operation.CopyNode;
import static org.apache.jackrabbit.oak.kernel.KernelNodeStateEditorFuzzTest.Operation.RemoveNode;
import static org.apache.jackrabbit.oak.kernel.KernelNodeStateEditorFuzzTest.Operation.RemoveProperty;
import static org.apache.jackrabbit.oak.kernel.KernelNodeStateEditorFuzzTest.Operation.Save;
import static org.apache.jackrabbit.oak.kernel.KernelNodeStateEditorFuzzTest.Operation.SetProperty;
import static org.junit.Assert.assertEquals;
@RunWith(Parameterized.class)
public class KernelNodeStateEditorFuzzTest {
static final Logger log = LoggerFactory.getLogger(KernelNodeStateEditorFuzzTest.class);
private static final int OP_COUNT = 5000;
private final Random random;
private MicroKernel mk1;
private MicroKernel mk2;
@Parameters
public static List<Object[]> seeds() {
return Arrays.asList(new Object[][] {
{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9},
{10}, {11}, {12}, {13}, {14}, {15}, {16}, {17}, {18}, {19},
{20}, {21}, {22}, {23}, {24}, {25}, {26}, {27}, {28}, {29},
{30}, {31}, {32}, {33}, {34}, {35}, {36}, {37}, {38}, {39},
});
}
public KernelNodeStateEditorFuzzTest(int seed) {
log.info("Seed = {}", seed);
random = new Random(seed);
}
@Before
public void setup() {
mk1 = new SimpleKernelImpl("mem:mk1");
mk1.commit("", "+\"/root\":{}", mk1.getHeadRevision(), "");
mk2 = new SimpleKernelImpl("mem:mk2");
mk2.commit("", "+\"/root\":{}", mk2.getHeadRevision(), "");
}
@After
public void tearDown() {
mk1.dispose();
mk2.dispose();
}
@Test
public void fuzzTest() throws Exception {
KernelNodeState state1 = new KernelNodeState(mk1, "/", mk1.getHeadRevision());
KernelNodeStateEditor editor1 = new KernelNodeStateEditor(state1);
KernelNodeState state2 = new KernelNodeState(mk1, "/", mk2.getHeadRevision());
KernelNodeStateEditor editor2 = new KernelNodeStateEditor(state2);
for (Operation op : operations(OP_COUNT)) {
log.info("{}", op);
op.apply(editor1);
op.apply(editor2);
checkEqual(editor1.getTransientState(), editor2.getTransientState());
state1 = editor1.mergeInto(mk1, state1);
editor1 = new KernelNodeStateEditor(state1);
if (op instanceof Save) {
state2 = editor2.mergeInto(mk2, state2);
editor2 = new KernelNodeStateEditor(state1);
assertEquals(state1, state2);
}
}
}
private Iterable<Operation> operations(final int count) {
return new Iterable<Operation>() {
int k = count;
@Override
public Iterator<Operation> iterator() {
return new Iterator<Operation>() {
@Override
public boolean hasNext() {
return k-- > 0;
}
@Override
public Operation next() {
return createOperation();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
abstract static class Operation {
abstract void apply(KernelNodeStateEditor editor);
static class AddNode extends Operation {
private final String parentPath;
private final String name;
AddNode(String parentPath, String name) {
this.parentPath = parentPath;
this.name = name;
}
@Override
void apply(KernelNodeStateEditor editor) {
for (String element : PathUtils.elements(parentPath)) {
editor = editor.edit(element);
}
editor.addNode(name);
}
@Override
public String toString() {
return '+' + PathUtils.concat(parentPath, name) + ":{}";
}
}
static class RemoveNode extends Operation {
private final String path;
RemoveNode(String path) {
this.path = path;
}
@Override
void apply(KernelNodeStateEditor editor) {
for (String element : PathUtils.elements(PathUtils.getParentPath(path))) {
editor = editor.edit(element);
}
editor.removeNode(PathUtils.getName(path));
}
@Override
public String toString() {
return '-' + path;
}
}
static class MoveNode extends Operation {
private final String source;
private final String destination;
MoveNode(String source, String destParent, String destName) {
this.source = source;
destination = PathUtils.concat(destParent, destName);
}
@Override
void apply(KernelNodeStateEditor editor) {
editor.move(source.substring(1), destination.substring(1));
}
@Override
public String toString() {
return '>' + source + ':' + destination;
}
}
static class CopyNode extends Operation {
private final String source;
private final String destination;
CopyNode(String source, String destParent, String destName) {
this.source = source;
destination = PathUtils.concat(destParent, destName);
}
@Override
void apply(KernelNodeStateEditor editor) {
editor.copy(source.substring(1), destination.substring(1));
}
@Override
public String toString() {
return '*' + source + ':' + destination;
}
}
static class SetProperty extends Operation {
private final String parentPath;
private KernelPropertyState propertyState;
SetProperty(String parentPath, String name, Scalar value) {
this.parentPath = parentPath;
this.propertyState = new KernelPropertyState(name, value);
}
@Override
void apply(KernelNodeStateEditor editor) {
for (String element : PathUtils.elements(parentPath)) {
editor = editor.edit(element);
}
editor.setProperty(propertyState);
}
@Override
public String toString() {
return '^' + PathUtils.concat(parentPath, propertyState.getName()) + ':'
+ propertyState.getEncodedValue();
}
}
static class RemoveProperty extends Operation {
private final String parentPath;
private final String name;
RemoveProperty(String parentPath, String name) {
this.parentPath = parentPath;
this.name = name;
}
@Override
void apply(KernelNodeStateEditor editor) {
for (String element : PathUtils.elements(parentPath)) {
editor = editor.edit(element);
}
editor.removeProperty(name);
}
@Override
public String toString() {
return '^' + PathUtils.concat(parentPath, name) + ":null";
}
}
static class Save extends Operation {
@Override
void apply(KernelNodeStateEditor editor) {
// empty
}
@Override
public String toString() {
return "save";
}
}
}
private Operation createOperation() {
Operation op;
do {
switch (random.nextInt(10)) {
case 0:
case 1:
case 2:
op = createAddNode();
break;
case 3:
op = createRemoveNode();
break;
case 4:
op = createMoveNode();
break;
case 5:
- // todo: copy is currently broken due to OAK-47
- // op = createCopyNode();
- op = null;
+ // Too many copy ops make the test way slow
+ op = random.nextInt(10) == 0 ? createCopyNode() : null;
break;
case 6:
op = createAddProperty();
break;
case 7:
op = createSetProperty();
break;
case 8:
op = createRemoveProperty();
break;
case 9:
op = new Save();
break;
default:
throw new IllegalStateException();
}
} while (op == null);
return op;
}
private Operation createAddNode() {
String parentPath = chooseNodePath();
String name = createNodeName();
return new AddNode(parentPath, name);
}
private Operation createRemoveNode() {
String path = chooseNodePath();
return "/root".equals(path) ? null : new RemoveNode(path);
}
private Operation createMoveNode() {
String source = chooseNodePath();
String destParent = chooseNodePath();
String destName = createNodeName();
return "/root".equals(source) || destParent.startsWith(source)
? null
: new MoveNode(source, destParent, destName);
}
private Operation createCopyNode() {
String source = chooseNodePath();
String destParent = chooseNodePath();
String destName = createNodeName();
return "/root".equals(source)
? null
: new CopyNode(source, destParent, destName);
}
private Operation createAddProperty() {
String parent = chooseNodePath();
String name = createPropertyName();
Scalar value = createValue();
return new SetProperty(parent, name, value);
}
private Operation createSetProperty() {
String path = choosePropertyPath();
if (path == null) {
return null;
}
Scalar value = createValue();
return new SetProperty(PathUtils.getParentPath(path), PathUtils.getName(path), value);
}
private Operation createRemoveProperty() {
String path = choosePropertyPath();
if (path == null) {
return null;
}
return new RemoveProperty(PathUtils.getParentPath(path), PathUtils.getName(path));
}
private int counter;
private String createNodeName() {
return "N" + counter++;
}
private String createPropertyName() {
return "P" + counter++;
}
private String chooseNodePath() {
String path = "/root";
String next;
while ((next = chooseNode(path)) != null) {
path = next;
}
return path;
}
private String choosePropertyPath() {
return chooseProperty(chooseNodePath());
}
private String chooseNode(String parentPath) {
KernelNodeState state = new KernelNodeState(mk1, parentPath, mk1.getHeadRevision());
int k = random.nextInt((int) (state.getChildNodeCount() + 1));
int c = 0;
for (ChildNodeEntry entry : state.getChildNodeEntries(0, -1)) {
if (c++ == k) {
return PathUtils.concat(parentPath, entry.getName());
}
}
return null;
}
private String chooseProperty(String parentPath) {
KernelNodeState state = new KernelNodeState(mk1, parentPath, mk1.getHeadRevision());
int k = random.nextInt((int) (state.getPropertyCount() + 1));
int c = 0;
for (PropertyState entry : state.getProperties()) {
if (c++ == k) {
return PathUtils.concat(parentPath, entry.getName());
}
}
return null;
}
private Scalar createValue() {
return ScalarImpl.stringScalar("V" + counter++);
}
private static void checkEqual(TransientNodeState state1, TransientNodeState state2) {
assertEquals(state1.getPath(), state2.getPath());
assertEquals(state1.getChildNodeCount(), state2.getChildNodeCount());
assertEquals(state1.getPropertyCount(), state2.getPropertyCount());
for (PropertyState property1 : state1.getProperties()) {
assertEquals(property1, state2.getProperty(property1.getName()));
}
for (TransientNodeState node1 : state1.getChildNodes(0, -1)) {
checkEqual(node1, state2.getChildNode(node1.getName()));
}
}
}
| true | true |
private Operation createOperation() {
Operation op;
do {
switch (random.nextInt(10)) {
case 0:
case 1:
case 2:
op = createAddNode();
break;
case 3:
op = createRemoveNode();
break;
case 4:
op = createMoveNode();
break;
case 5:
// todo: copy is currently broken due to OAK-47
// op = createCopyNode();
op = null;
break;
case 6:
op = createAddProperty();
break;
case 7:
op = createSetProperty();
break;
case 8:
op = createRemoveProperty();
break;
case 9:
op = new Save();
break;
default:
throw new IllegalStateException();
}
} while (op == null);
return op;
}
|
private Operation createOperation() {
Operation op;
do {
switch (random.nextInt(10)) {
case 0:
case 1:
case 2:
op = createAddNode();
break;
case 3:
op = createRemoveNode();
break;
case 4:
op = createMoveNode();
break;
case 5:
// Too many copy ops make the test way slow
op = random.nextInt(10) == 0 ? createCopyNode() : null;
break;
case 6:
op = createAddProperty();
break;
case 7:
op = createSetProperty();
break;
case 8:
op = createRemoveProperty();
break;
case 9:
op = new Save();
break;
default:
throw new IllegalStateException();
}
} while (op == null);
return op;
}
|
diff --git a/org.python.pydev.parser/src/org/python/pydev/parser/grammar25/TreeBuilder25.java b/org.python.pydev.parser/src/org/python/pydev/parser/grammar25/TreeBuilder25.java
index 56ae6a1a8..506a8ca44 100644
--- a/org.python.pydev.parser/src/org/python/pydev/parser/grammar25/TreeBuilder25.java
+++ b/org.python.pydev.parser/src/org/python/pydev/parser/grammar25/TreeBuilder25.java
@@ -1,1259 +1,1261 @@
package org.python.pydev.parser.grammar25;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import org.python.pydev.parser.jython.ParseException;
import org.python.pydev.parser.jython.SimpleNode;
import org.python.pydev.parser.jython.Visitor;
import org.python.pydev.parser.jython.ast.Assert;
import org.python.pydev.parser.jython.ast.Assign;
import org.python.pydev.parser.jython.ast.Attribute;
import org.python.pydev.parser.jython.ast.AugAssign;
import org.python.pydev.parser.jython.ast.BinOp;
import org.python.pydev.parser.jython.ast.BoolOp;
import org.python.pydev.parser.jython.ast.Break;
import org.python.pydev.parser.jython.ast.Call;
import org.python.pydev.parser.jython.ast.ClassDef;
import org.python.pydev.parser.jython.ast.Compare;
import org.python.pydev.parser.jython.ast.Comprehension;
import org.python.pydev.parser.jython.ast.Continue;
import org.python.pydev.parser.jython.ast.Delete;
import org.python.pydev.parser.jython.ast.Dict;
import org.python.pydev.parser.jython.ast.Ellipsis;
import org.python.pydev.parser.jython.ast.Exec;
import org.python.pydev.parser.jython.ast.Expr;
import org.python.pydev.parser.jython.ast.Expression;
import org.python.pydev.parser.jython.ast.ExtSlice;
import org.python.pydev.parser.jython.ast.For;
import org.python.pydev.parser.jython.ast.FunctionDef;
import org.python.pydev.parser.jython.ast.Global;
import org.python.pydev.parser.jython.ast.If;
import org.python.pydev.parser.jython.ast.IfExp;
import org.python.pydev.parser.jython.ast.Import;
import org.python.pydev.parser.jython.ast.ImportFrom;
import org.python.pydev.parser.jython.ast.Index;
import org.python.pydev.parser.jython.ast.Interactive;
import org.python.pydev.parser.jython.ast.Lambda;
import org.python.pydev.parser.jython.ast.List;
import org.python.pydev.parser.jython.ast.ListComp;
import org.python.pydev.parser.jython.ast.Module;
import org.python.pydev.parser.jython.ast.Name;
import org.python.pydev.parser.jython.ast.NameTok;
import org.python.pydev.parser.jython.ast.NameTokType;
import org.python.pydev.parser.jython.ast.Num;
import org.python.pydev.parser.jython.ast.Pass;
import org.python.pydev.parser.jython.ast.Print;
import org.python.pydev.parser.jython.ast.Raise;
import org.python.pydev.parser.jython.ast.Repr;
import org.python.pydev.parser.jython.ast.Return;
import org.python.pydev.parser.jython.ast.Slice;
import org.python.pydev.parser.jython.ast.Str;
import org.python.pydev.parser.jython.ast.StrJoin;
import org.python.pydev.parser.jython.ast.Subscript;
import org.python.pydev.parser.jython.ast.Suite;
import org.python.pydev.parser.jython.ast.TryExcept;
import org.python.pydev.parser.jython.ast.TryFinally;
import org.python.pydev.parser.jython.ast.Tuple;
import org.python.pydev.parser.jython.ast.UnaryOp;
import org.python.pydev.parser.jython.ast.While;
import org.python.pydev.parser.jython.ast.With;
import org.python.pydev.parser.jython.ast.Yield;
import org.python.pydev.parser.jython.ast.aliasType;
import org.python.pydev.parser.jython.ast.argumentsType;
import org.python.pydev.parser.jython.ast.comprehensionType;
import org.python.pydev.parser.jython.ast.decoratorsType;
import org.python.pydev.parser.jython.ast.excepthandlerType;
import org.python.pydev.parser.jython.ast.exprType;
import org.python.pydev.parser.jython.ast.expr_contextType;
import org.python.pydev.parser.jython.ast.keywordType;
import org.python.pydev.parser.jython.ast.sliceType;
import org.python.pydev.parser.jython.ast.stmtType;
import org.python.pydev.parser.jython.ast.suiteType;
public final class TreeBuilder25 implements PythonGrammar25TreeConstants {
private JJTPythonGrammar25State stack;
private CtxVisitor ctx;
private SimpleNode lastPop;
public TreeBuilder25(JJTPythonGrammar25State stack) {
this.stack = stack;
this.ctx = new CtxVisitor();
}
private stmtType[] makeStmts(int l) {
stmtType[] stmts = new stmtType[l];
for (int i = l-1; i >= 0; i--) {
stmts[i] = (stmtType) stack.popNode();
}
return stmts;
}
private stmtType[] popSuite() {
return getBodyAndSpecials();
}
private exprType[] makeExprs() {
if (stack.nodeArity() > 0 && stack.peekNode().getId() == JJTCOMMA)
stack.popNode();
return makeExprs(stack.nodeArity());
}
private exprType[] makeExprs(int l) {
exprType[] exprs = new exprType[l];
for (int i = l-1; i >= 0; i--) {
lastPop = stack.popNode();
exprs[i] = (exprType) lastPop;
}
return exprs;
}
private NameTok makeName(int ctx) {
Name name = (Name) stack.popNode();
NameTok n = new NameTok(name.id, ctx);
n.beginColumn = name.beginColumn;
n.beginLine = name.beginLine;
addSpecials(name, n);
name.specialsBefore = n.getSpecialsBefore();
name.specialsAfter = n.getSpecialsAfter();
return n;
}
private NameTok[] makeIdentifiers(int ctx) {
int l = stack.nodeArity();
NameTok[] ids = new NameTok[l];
for (int i = l - 1; i >= 0; i--) {
ids[i] = makeName(ctx);
}
return ids;
}
private aliasType[] makeAliases(int l) {
aliasType[] aliases = new aliasType[l];
for (int i = l-1; i >= 0; i--) {
aliases[i] = (aliasType) stack.popNode();
}
return aliases;
}
private static SimpleNode[] nodes = new SimpleNode[PythonGrammar25TreeConstants.jjtNodeName.length];
public SimpleNode openNode(int id) {
if (nodes[id] == null)
nodes[id] = new IdentityNode(id);
return nodes[id];
}
public SimpleNode closeNode(SimpleNode n, int arity) throws Exception {
exprType value;
exprType[] exprs;
int l;
switch (n.getId()) {
case -1:
System.out.println("Illegal node");
case JJTSINGLE_INPUT:
return new Interactive(makeStmts(arity));
case JJTFILE_INPUT:
return new Module(makeStmts(arity));
case JJTEVAL_INPUT:
return new Expression(((exprType) stack.popNode()));
case JJTNAME:
Name name = new Name(n.getImage().toString(), Name.Load);
addSpecialsAndClearOriginal(n, name);
return name;
case JJTNUM:
//throw new RuntimeException("how to handle this? -- fabio")
return new Num(n.getImage());
case JJTUNICODE:
case JJTSTRING:
Object[] image = (Object[]) n.getImage();
return new Str((String)image[0], (Integer)image[3], (Boolean)image[1], (Boolean)image[2]);
case JJTSUITE:
stmtType[] stmts = new stmtType[arity];
for (int i = arity-1; i >= 0; i--) {
SimpleNode yield_or_stmt = stack.popNode();
if(yield_or_stmt instanceof Yield){
stmts[i] = new Expr((Yield)yield_or_stmt);
}else{
stmts[i] = (stmtType) yield_or_stmt;
}
}
return new Suite(stmts);
case JJTEXPR_STMT:
value = (exprType) stack.popNode();
if (arity > 1) {
exprs = makeExprs(arity-1);
ctx.setStore(exprs);
return new Assign(exprs, value);
} else {
return new Expr(value);
}
case JJTINDEX_OP:
sliceType slice = (sliceType) stack.popNode();
value = (exprType) stack.popNode();
return new Subscript(value, slice, Subscript.Load);
case JJTDOT_OP:
NameTok attr = makeName(NameTok.Attrib);
value = (exprType) stack.popNode();
return new Attribute(value, attr, Attribute.Load);
case JJTBEGIN_DEL_STMT:
return new Delete(null);
case JJTDEL_STMT:
exprs = makeExprs(arity-1);
ctx.setDelete(exprs);
Delete d = (Delete) stack.popNode();
d.targets = exprs;
return d;
case JJTPRINT_STMT:
boolean nl = true;
if (stack.nodeArity() == 0){
Print p = new Print(null, null, true);
p.getSpecialsBefore().add(0, "print ");
return p;
}
if (stack.peekNode().getId() == JJTCOMMA) {
stack.popNode();
nl = false;
}
Print p = new Print(null, makeExprs(), nl);
p.getSpecialsBefore().add(0, "print ");
return p;
case JJTPRINTEXT_STMT:
nl = true;
if (stack.peekNode().getId() == JJTCOMMA) {
stack.popNode();
nl = false;
}
exprs = makeExprs(stack.nodeArity()-1);
p = new Print(((exprType) stack.popNode()), exprs, nl);
p.getSpecialsBefore().add(0, ">> ");
p.getSpecialsBefore().add(0, "print ");
return p;
case JJTBEGIN_FOR_STMT:
return new For(null,null,null,null);
case JJTFOR_STMT:
suiteType orelseSuite = null;
if (stack.nodeArity() == 6){
orelseSuite = popSuiteAndSuiteType();
}
stmtType[] body = popSuite();
exprType iter = (exprType) stack.popNode();
exprType target = (exprType) stack.popNode();
ctx.setStore(target);
For forStmt = (For) stack.popNode();
forStmt.target = target;
forStmt.iter = iter;
forStmt.body = body;
forStmt.orelse = orelseSuite;
return forStmt;
case JJTBEGIN_FOR_ELSE_STMT:
return new suiteType(null);
case JJTBEGIN_ELSE_STMT:
return new suiteType(null);
case JJTBEGIN_WHILE_STMT:
return new While(null, null, null);
case JJTWHILE_STMT:
orelseSuite = null;
if (stack.nodeArity() == 5){
orelseSuite = popSuiteAndSuiteType();
}
body = popSuite();
exprType test = (exprType) stack.popNode();
While w = (While) stack.popNode();
w.test = test;
w.body = body;
w.orelse = orelseSuite;
return w;
case JJTBEGIN_IF_STMT:
return new If(null, null, null);
case JJTBEGIN_ELIF_STMT:
return new If(null, null, null);
case JJTIF_STMT:
stmtType[] orelse = null;
//arity--;//because of the beg if stmt
if (arity % 3 == 1){
orelse = getBodyAndSpecials();
}
//make the suite
Suite suite = (Suite)stack.popNode();
body = suite.body;
test = (exprType) stack.popNode();
//make the if
If last = (If) stack.popNode();
last.test = test;
last.body = body;
last.orelse = orelse;
addSpecialsAndClearOriginal(suite, last);
for (int i = 0; i < (arity / 3)-1; i++) {
//arity--;//because of the beg if stmt
suite = (Suite)stack.popNode();
body = suite.body;
test = (exprType) stack.popNode();
stmtType[] newOrElse = new stmtType[] { last };
last = (If) stack.popNode();
last.test = test;
last.body = body;
last.orelse = newOrElse;
addSpecialsAndClearOriginal(suite, last);
}
return last;
case JJTPASS_STMT:
return new Pass();
case JJTBREAK_STMT:
return new Break();
case JJTCONTINUE_STMT:
return new Continue();
case JJTBEGIN_DECORATOR:
return new decoratorsType(null,null,null,null, null);
case JJTDECORATORS:
ArrayList<SimpleNode> list2 = new ArrayList<SimpleNode>();
ArrayList<SimpleNode> listArgs = new ArrayList<SimpleNode>();
while(stack.nodeArity() > 0){
SimpleNode node = stack.popNode();
while(!(node instanceof decoratorsType)){
if(node instanceof ComprehensionCollection){
listArgs.add(((ComprehensionCollection)node).getGenerators()[0]);
listArgs.add(stack.popNode()); //target
}else{
listArgs.add(node);
}
node = stack.popNode();
}
listArgs.add(node);//the decoratorsType
list2.add(0,makeDecorator(listArgs));
listArgs.clear();
}
return new Decorators((decoratorsType[]) list2.toArray(new decoratorsType[0]), JJTDECORATORS);
case JJTCALL_OP:
exprType starargs = null;
exprType kwargs = null;
l = arity - 1;
if (l > 0 && stack.peekNode().getId() == JJTEXTRAKEYWORDVALUELIST) {
ExtraArgValue nkwargs = (ExtraArgValue) stack.popNode();
kwargs = nkwargs.value;
this.addSpecialsAndClearOriginal(nkwargs, kwargs);
l--;
}
if (l > 0 && stack.peekNode().getId() == JJTEXTRAARGVALUELIST) {
ExtraArgValue nstarargs = (ExtraArgValue) stack.popNode();
starargs = nstarargs.value;
this.addSpecialsAndClearOriginal(nstarargs, starargs);
l--;
}
int nargs = l;
SimpleNode[] tmparr = new SimpleNode[l];
for (int i = l - 1; i >= 0; i--) {
tmparr[i] = stack.popNode();
if (tmparr[i] instanceof keywordType) {
nargs = i;
}
}
exprType[] args = new exprType[nargs];
for (int i = 0; i < nargs; i++) {
//what can happen is something like print sum(x for x in y), where we have already passed x in the args, and then get 'for x in y'
if(tmparr[i] instanceof ComprehensionCollection){
args = new exprType[]{
new ListComp(args[0], ((ComprehensionCollection)tmparr[i]).getGenerators())};
}else{
args[i] = (exprType) tmparr[i];
}
}
keywordType[] keywords = new keywordType[l - nargs];
for (int i = nargs; i < l; i++) {
if (!(tmparr[i] instanceof keywordType))
throw new ParseException(
"non-keyword argument following keyword", tmparr[i]);
keywords[i - nargs] = (keywordType) tmparr[i];
}
exprType func = (exprType) stack.popNode();
Call c = new Call(func, args, keywords, starargs, kwargs);
addSpecialsAndClearOriginal(n, c);
return c;
case JJTFUNCDEF:
//get the decorators
//and clear them for the next call (they always must be before a function def)
suite = (Suite) stack.popNode();
body = suite.body;
argumentsType arguments = makeArguments(stack.nodeArity() - 2);
NameTok nameTok = makeName(NameTok.FunctionName);
Decorators decs = (Decorators) stack.popNode() ;
decoratorsType[] decsexp = decs.exp;
FunctionDef funcDef = new FunctionDef(nameTok, arguments, body, decsexp);
if(decs.exp.length == 0){
addSpecialsBefore(decs, funcDef);
}
addSpecialsAndClearOriginal(suite, funcDef);
return funcDef;
case JJTDEFAULTARG:
value = (arity == 1) ? null : ((exprType) stack.popNode());
return new DefaultArg(((exprType) stack.popNode()), value);
case JJTEXTRAARGLIST:
return new ExtraArg(makeName(NameTok.VarArg), JJTEXTRAARGLIST);
case JJTEXTRAKEYWORDLIST:
return new ExtraArg(makeName(NameTok.KwArg), JJTEXTRAKEYWORDLIST);
case JJTCLASSDEF:
suite = (Suite) stack.popNode();
body = suite.body;
exprType[] bases = makeExprs(stack.nodeArity() - 1);
nameTok = makeName(NameTok.ClassName);
ClassDef classDef = new ClassDef(nameTok, bases, body);
addSpecialsAndClearOriginal(suite, classDef);
return classDef;
case JJTBEGIN_RETURN_STMT:
return new Return(null);
case JJTRETURN_STMT:
value = arity == 2 ? ((exprType) stack.popNode()) : null;
Return ret = (Return) stack.popNode();
ret.value = value;
return ret;
case JJTYIELD_STMT:
return stack.popNode();
case JJTYIELD_EXPR:
exprType yieldExpr = null;
if(arity > 0){
//we may have an empty yield, so, we have to check it before
yieldExpr = (exprType) stack.popNode();
}
return new Yield(yieldExpr);
case JJTRAISE_STMT:
exprType tback = arity >= 3 ? ((exprType) stack.popNode()) : null;
exprType inst = arity >= 2 ? ((exprType) stack.popNode()) : null;
exprType type = arity >= 1 ? ((exprType) stack.popNode()) : null;
return new Raise(type, inst, tback);
case JJTGLOBAL_STMT:
Global global = new Global(makeIdentifiers(NameTok.GlobalName));
return global;
case JJTEXEC_STMT:
exprType globals = arity >= 3 ? ((exprType) stack.popNode()) : null;
exprType locals = arity >= 2 ? ((exprType) stack.popNode()) : null;
value = (exprType) stack.popNode();
return new Exec(value, locals, globals);
case JJTASSERT_STMT:
exprType msg = arity == 2 ? ((exprType) stack.popNode()) : null;
test = (exprType) stack.popNode();
return new Assert(test, msg);
case JJTBEGIN_TRY_STMT:
//we do that just to get the specials
return new TryExcept(null, null, null);
case JJTTRYELSE_STMT:
orelseSuite = popSuiteAndSuiteType();
return orelseSuite;
case JJTTRYFINALLY_OUTER_STMT:
orelseSuite = popSuiteAndSuiteType();
return new TryFinally(null, orelseSuite); //it does not have a body at this time... it will be filled with the inner try..except
case JJTTRY_STMT:
TryFinally outer = null;
if(stack.peekNode() instanceof TryFinally){
outer = (TryFinally) stack.popNode();
arity--;
}
orelseSuite = null;
if(stack.peekNode() instanceof suiteType){
orelseSuite = (suiteType) stack.popNode();
arity--;
}
l = arity ;
excepthandlerType[] handlers = new excepthandlerType[l];
for (int i = l - 1; i >= 0; i--) {
handlers[i] = (excepthandlerType) stack.popNode();
}
suite = (Suite)stack.popNode();
TryExcept tryExc = (TryExcept) stack.popNode();
tryExc.body = suite.body;
tryExc.handlers = handlers;
tryExc.orelse = orelseSuite;
addSpecials(suite, tryExc);
if (outer == null){
return tryExc;
}else{
if(outer.body != null){
throw new RuntimeException("Error. Expecting null body to be filled on try..except..finally");
}
outer.body = new stmtType[]{tryExc};
return outer;
}
case JJTBEGIN_TRY_ELSE_STMT:
//we do that just to get the specials
return new suiteType(null);
case JJTBEGIN_EXCEPT_CLAUSE:
return new excepthandlerType(null,null,null);
case JJTEXCEPT_CLAUSE:
suite = (Suite) stack.popNode();
body = suite.body;
exprType excname = arity == 4 ? ((exprType) stack.popNode()) : null;
if (excname != null){
ctx.setStore(excname);
}
type = arity >= 3 ? ((exprType) stack.popNode()) : null;
excepthandlerType handler = (excepthandlerType) stack.popNode();
handler.type = type;
handler.name = excname;
handler.body = body;
addSpecials(suite, handler);
return handler;
case JJTBEGIN_FINALLY_STMT:
//we do that just to get the specials
return new suiteType(null);
case JJTTRYFINALLY_STMT:
suiteType finalBody = popSuiteAndSuiteType();
body = popSuite();
//We have a try..except in the stack, but we will change it for a try..finally
//This is because we recognize a try..except in the 'try:' token, but actually end up with a try..finally
TryExcept tryExcept = (TryExcept) stack.popNode();
TryFinally tryFinally = new TryFinally(body, finalBody);
+ tryFinally.beginLine = tryExcept.beginLine;
+ tryFinally.beginColumn = tryExcept.beginColumn;
addSpecialsAndClearOriginal(tryExcept, tryFinally);
return tryFinally;
case JJTWITH_STMT:
suite = (Suite) stack.popNode();
arity--;
exprType asOrExpr = (exprType) stack.popNode();
arity--;
exprType expr=null;
if(arity > 0){
expr = (exprType) stack.popNode();
arity--;
}else{
expr = asOrExpr;
asOrExpr = null;
}
suiteType s = new suiteType(suite.body);
addSpecialsAndClearOriginal(suite, s);
return new With(expr, asOrExpr, s);
case JJTWITH_VAR:
expr = (exprType) stack.popNode(); //expr
if (expr != null){
ctx.setStore(expr);
}
return expr;
case JJTOR_BOOLEAN:
return new BoolOp(BoolOp.Or, makeExprs());
case JJTAND_BOOLEAN:
return new BoolOp(BoolOp.And, makeExprs());
case JJTCOMPARISION:
l = arity / 2;
exprType[] comparators = new exprType[l];
int[] ops = new int[l];
for (int i = l-1; i >= 0; i--) {
comparators[i] = (exprType) stack.popNode();
SimpleNode op = stack.popNode();
switch (op.getId()) {
case JJTLESS_CMP: ops[i] = Compare.Lt; break;
case JJTGREATER_CMP: ops[i] = Compare.Gt; break;
case JJTEQUAL_CMP: ops[i] = Compare.Eq; break;
case JJTGREATER_EQUAL_CMP: ops[i] = Compare.GtE; break;
case JJTLESS_EQUAL_CMP: ops[i] = Compare.LtE; break;
case JJTNOTEQUAL_CMP: ops[i] = Compare.NotEq; break;
case JJTIN_CMP: ops[i] = Compare.In; break;
case JJTNOT_IN_CMP: ops[i] = Compare.NotIn; break;
case JJTIS_NOT_CMP: ops[i] = Compare.IsNot; break;
case JJTIS_CMP: ops[i] = Compare.Is; break;
default:
throw new RuntimeException("Unknown cmp op:" + op.getId());
}
}
return new Compare(((exprType) stack.popNode()), ops, comparators);
case JJTLESS_CMP:
case JJTGREATER_CMP:
case JJTEQUAL_CMP:
case JJTGREATER_EQUAL_CMP:
case JJTLESS_EQUAL_CMP:
case JJTNOTEQUAL_CMP:
case JJTIN_CMP:
case JJTNOT_IN_CMP:
case JJTIS_NOT_CMP:
case JJTIS_CMP:
return n;
case JJTOR_2OP:
return makeBinOp(BinOp.BitOr);
case JJTXOR_2OP:
return makeBinOp(BinOp.BitXor);
case JJTAND_2OP:
return makeBinOp(BinOp.BitAnd);
case JJTLSHIFT_2OP:
return makeBinOp(BinOp.LShift);
case JJTRSHIFT_2OP:
return makeBinOp(BinOp.RShift);
case JJTADD_2OP:
return makeBinOp(BinOp.Add);
case JJTSUB_2OP:
return makeBinOp(BinOp.Sub);
case JJTMUL_2OP:
return makeBinOp(BinOp.Mult);
case JJTDIV_2OP:
return makeBinOp(BinOp.Div);
case JJTMOD_2OP:
return makeBinOp(BinOp.Mod);
case JJTPOW_2OP:
return makeBinOp(BinOp.Pow);
case JJTFLOORDIV_2OP:
return makeBinOp(BinOp.FloorDiv);
case JJTPOS_1OP:
return new UnaryOp(UnaryOp.UAdd, ((exprType) stack.popNode()));
case JJTNEG_1OP:
return new UnaryOp(UnaryOp.USub, ((exprType) stack.popNode()));
case JJTINVERT_1OP:
return new UnaryOp(UnaryOp.Invert, ((exprType) stack.popNode()));
case JJTNOT_1OP:
return new UnaryOp(UnaryOp.Not, ((exprType) stack.popNode()));
case JJTEXTRAKEYWORDVALUELIST:
return new ExtraArgValue(((exprType) stack.popNode()), JJTEXTRAKEYWORDVALUELIST);
case JJTEXTRAARGVALUELIST:
return new ExtraArgValue(((exprType) stack.popNode()), JJTEXTRAARGVALUELIST);
case JJTKEYWORD:
value = (exprType) stack.popNode();
nameTok = makeName(NameTok.KeywordName);
return new keywordType(nameTok, value);
case JJTTUPLE:
if (stack.nodeArity() > 0) {
SimpleNode peeked = stack.peekNode();
if(peeked instanceof ComprehensionCollection){
ComprehensionCollection col = (ComprehensionCollection) stack.popNode();
return new ListComp(((exprType) stack.popNode()), col.getGenerators());
}
}
try {
exprType[] exp = makeExprs();
Tuple t = new Tuple(exp, Tuple.Load);
addSpecialsAndClearOriginal(n, t);
return t;
} catch (ClassCastException e) {
if(e.getMessage().equals(ExtraArgValue.class.getName())){
throw new ParseException("Token: '*' is not expected inside tuples.", lastPop);
}
e.printStackTrace();
throw new ParseException("Syntax error while detecting tuple.", lastPop);
}
case JJTLIST:
if (stack.nodeArity() > 0 && stack.peekNode() instanceof ComprehensionCollection) {
ComprehensionCollection col = (ComprehensionCollection) stack.popNode();
return new ListComp(((exprType) stack.popNode()), col.getGenerators());
}
return new List(makeExprs(), List.Load);
case JJTDICTIONARY:
l = arity / 2;
exprType[] keys = new exprType[l];
exprType[] vals = new exprType[l];
for (int i = l - 1; i >= 0; i--) {
vals[i] = (exprType) stack.popNode();
keys[i] = (exprType) stack.popNode();
}
return new Dict(keys, vals);
case JJTSTR_1OP:
return new Repr(((exprType) stack.popNode()));
case JJTSTRJOIN:
Str str2 = (Str) stack.popNode();
Object o = stack.popNode();
if(o instanceof Str){
Str str1 = (Str) o;
return new StrJoin(new exprType[]{str1, str2});
}else{
StrJoin strJ = (StrJoin) o;
exprType[] newStrs = new exprType[strJ.strs.length +1];
System.arraycopy(strJ.strs, 0, newStrs, 0, strJ.strs.length);
newStrs[strJ.strs.length] = str2;
strJ.strs = newStrs;
return strJ;
}
case JJTTEST:
if(arity == 2){
IfExp node = (IfExp) stack.popNode();
node.body = (exprType) stack.popNode();
return node;
}else{
return stack.popNode();
}
case JJTIF_EXP:
exprType ifExprOrelse=(exprType) stack.popNode();
exprType ifExprTest=(exprType) stack.popNode();
return new IfExp(ifExprTest,null,ifExprOrelse);
case JJTOLD_LAMBDEF:
case JJTLAMBDEF:
test = (exprType) stack.popNode();
arguments = makeArguments(arity - 1);
Lambda lambda = new Lambda(arguments, test);
if(arguments == null || arguments.args == null || arguments.args.length == 0){
lambda.getSpecialsBefore().add("lambda");
}else{
lambda.getSpecialsBefore().add("lambda ");
}
return lambda;
case JJTELLIPSES:
return new Ellipsis();
case JJTSLICE:
SimpleNode[] arr = new SimpleNode[arity];
for (int i = arity-1; i >= 0; i--) {
arr[i] = stack.popNode();
}
exprType[] values = new exprType[3];
int k = 0;
java.util.List<Object> specialsBefore = new ArrayList<Object>();
java.util.List<Object> specialsAfter = new ArrayList<Object>();
for (int j = 0; j < arity; j++) {
if (arr[j].getId() == JJTCOLON){
if(arr[j].specialsBefore != null){
specialsBefore.addAll(arr[j].specialsBefore);
arr[j].specialsBefore.clear(); //this nodes may be reused among parses, so, we have to erase the specials
}
if(arr[j].specialsAfter != null){
specialsAfter.addAll(arr[j].specialsAfter);
arr[j].specialsAfter.clear();
}
k++;
}else{
values[k] = (exprType) arr[j];
if(specialsBefore.size() > 0){
values[k].getSpecialsBefore().addAll(specialsBefore);
specialsBefore.clear();
}
if(specialsAfter.size() > 0){
values[k].getSpecialsBefore().addAll(specialsAfter);
specialsAfter.clear();
}
}
}
SimpleNode sliceRet;
if (k == 0) {
sliceRet = new Index(values[0]);
} else {
sliceRet = new Slice(values[0], values[1], values[2]);
}
//this may happen if we have no values
sliceRet.getSpecialsBefore().addAll(specialsBefore);
sliceRet.getSpecialsAfter().addAll(specialsAfter);
specialsBefore.clear();
specialsAfter.clear();
return sliceRet;
case JJTSUBSCRIPTLIST:
sliceType[] dims = new sliceType[arity];
for (int i = arity - 1; i >= 0; i--) {
SimpleNode sliceNode = stack.popNode();
if(sliceNode instanceof sliceType){
dims[i] = (sliceType) sliceNode;
}else if(sliceNode instanceof IdentityNode){
//this should be ignored...
//this happens when parsing something like a[1,], whereas a[1,2] would not have this.
}else{
throw new RuntimeException("Expected a sliceType or an IdentityNode. Received :"+sliceNode.getClass());
}
}
return new ExtSlice(dims);
case JJTAUG_PLUS:
return makeAugAssign(AugAssign.Add);
case JJTAUG_MINUS:
return makeAugAssign(AugAssign.Sub);
case JJTAUG_MULTIPLY:
return makeAugAssign(AugAssign.Mult);
case JJTAUG_DIVIDE:
return makeAugAssign(AugAssign.Div);
case JJTAUG_MODULO:
return makeAugAssign(AugAssign.Mod);
case JJTAUG_AND:
return makeAugAssign(AugAssign.BitAnd);
case JJTAUG_OR:
return makeAugAssign(AugAssign.BitOr);
case JJTAUG_XOR:
return makeAugAssign(AugAssign.BitXor);
case JJTAUG_LSHIFT:
return makeAugAssign(AugAssign.LShift);
case JJTAUG_RSHIFT:
return makeAugAssign(AugAssign.RShift);
case JJTAUG_POWER:
return makeAugAssign(AugAssign.Pow);
case JJTAUG_FLOORDIVIDE:
return makeAugAssign(AugAssign.FloorDiv);
case JJTLIST_FOR:
ComprehensionCollection col = null;
if(stack.peekNode() instanceof ComprehensionCollection){
col = (ComprehensionCollection) stack.popNode();
arity--;
}else{
col = new ComprehensionCollection();
}
ArrayList<exprType> ifs = new ArrayList<exprType>();
for (int i = arity-3; i >= 0; i--) {
SimpleNode ifsNode = stack.popNode();
ifs.add((exprType) ifsNode);
}
iter = (exprType) stack.popNode();
target = (exprType) stack.popNode();
ctx.setStore(target);
col.added.add(new Comprehension(target, iter, ifs.toArray(new exprType[0])));
return col;
case JJTIMPORTFROM:
ArrayList<aliasType> aliastL = new ArrayList<aliasType>();
while(arity > 0 && stack.peekNode() instanceof aliasType){
aliastL.add(0, (aliasType) stack.popNode());
arity--;
}
NameTok nT;
if(arity > 0){
nT = makeName(NameTok.ImportModule);
}else{
nT = new NameTok("", NameTok.ImportModule);
}
return new ImportFrom((NameTokType)nT, aliastL.toArray(new aliasType[0]), 0);
case JJTIMPORT:
return new Import(makeAliases(arity));
case JJTDOTTED_NAME:
name = new Name(null, Name.Load);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arity; i++) {
if (i > 0){
sb.insert(0, '.');
}
Name name0 = (Name) stack.popNode();
sb.insert(0, name0.id);
addSpecials(name0, name);
//we have to set that, because if we later add things to the previous Name, we will now want it to be added to
//the new name (comments will only appear later and may be added to the previous name -- so, we replace the previous
//name specials list).
name0.specialsBefore = name.getSpecialsBefore();
name0.specialsAfter = name.getSpecialsAfter();
}
name.id = sb.toString();
return name;
case JJTDOTTED_AS_NAME:
NameTok asname = null;
if (arity > 1){
asname = makeName(NameTok.ImportName);
}
return new aliasType(makeName(NameTok.ImportName), asname);
case JJTIMPORT_AS_NAME:
asname = null;
if (arity > 1){
asname = makeName(NameTok.ImportName);
}
return new aliasType(makeName(NameTok.ImportName), asname);
case JJTCOMMA:
case JJTCOLON:
return n;
default:
System.out.println("Error at TreeBuilder: default not treated:"+n.getId());
return null;
}
}
private suiteType popSuiteAndSuiteType() {
Suite s = (Suite) stack.popNode();
suiteType orelseSuite = (suiteType) stack.popNode();
orelseSuite.body = s.body;
addSpecialsAndClearOriginal(s, orelseSuite);
return orelseSuite;
}
private void addSpecialsAndClearOriginal(SimpleNode from, SimpleNode to) {
addSpecials(from, to);
if(from.specialsBefore != null){
from.specialsBefore.clear();
}
if(from.specialsAfter != null){
from.specialsAfter.clear();
}
}
private void addSpecials(SimpleNode from, SimpleNode to) {
if(from.specialsBefore != null && from.specialsBefore.size() > 0){
to.getSpecialsBefore().addAll(from.specialsBefore);
}
if(from.specialsAfter != null && from.specialsAfter.size() > 0){
to.getSpecialsAfter().addAll(from.specialsAfter);
}
}
private void addSpecialsBefore(SimpleNode from, SimpleNode to) {
if(from.specialsBefore != null && from.specialsBefore.size() > 0){
to.getSpecialsBefore().addAll(from.specialsBefore);
}
if(from.specialsAfter != null && from.specialsAfter.size() > 0){
to.getSpecialsBefore().addAll(from.specialsAfter);
}
}
/**
* @param suite
* @return
*/
private stmtType[] getBodyAndSpecials() {
Suite suite = (Suite)stack.popNode();
stmtType[] body;
body = suite.body;
if(suite.specialsBefore != null && suite.specialsBefore.size() > 0){
body[0].getSpecialsBefore().addAll(suite.specialsBefore);
}
if(suite.specialsAfter != null && suite.specialsAfter.size() > 0){
body[body.length-1].getSpecialsAfter().addAll(suite.specialsAfter);
}
return body;
}
SimpleNode makeDecorator(java.util.List<SimpleNode> nodes){
exprType starargs = null;
exprType kwargs = null;
exprType func = null;
ArrayList<SimpleNode> keywordsl = new ArrayList<SimpleNode>();
ArrayList<SimpleNode> argsl = new ArrayList<SimpleNode>();
for (Iterator<SimpleNode> iter = nodes.iterator(); iter.hasNext();) {
SimpleNode node = iter.next();
if (node.getId() == JJTEXTRAKEYWORDVALUELIST) {
final ExtraArgValue extraArg = (ExtraArgValue) node;
kwargs = (extraArg).value;
this.addSpecialsAndClearOriginal(extraArg, kwargs);
extraArg.specialsBefore = kwargs.getSpecialsBefore();
extraArg.specialsAfter = kwargs.getSpecialsAfter();
} else if (node.getId() == JJTEXTRAARGVALUELIST) {
final ExtraArgValue extraArg = (ExtraArgValue) node;
starargs = extraArg.value;
this.addSpecialsAndClearOriginal(extraArg, starargs);
extraArg.specialsBefore = starargs.getSpecialsBefore();
extraArg.specialsAfter = starargs.getSpecialsAfter();
} else if(node instanceof keywordType){
//keyword
keywordsl.add(node);
} else if(isArg(node)){
//default
argsl.add(node);
} else if(node instanceof Comprehension){
argsl.add( new ListComp((exprType)iter.next(), new comprehensionType[]{(comprehensionType) node}) );
} else if(node instanceof ComprehensionCollection){
//list comp (2 nodes: comp type and the elt -- what does elt mean by the way?)
argsl.add( new ListComp((exprType)iter.next(), ((ComprehensionCollection)node).getGenerators()));
} else if(node instanceof decoratorsType){
func = (exprType) stack.popNode();//the func is the last thing in the stack
decoratorsType d = (decoratorsType) node;
d.func = func;
d.args = (exprType[]) argsl.toArray(new exprType[0]);
d.keywords = (keywordType[]) keywordsl.toArray(new keywordType[0]);
d.starargs = starargs;
d.kwargs = kwargs;
return d;
} else {
argsl.add(node);
}
}
throw new RuntimeException("Something wrong happened while making the decorators...");
}
private stmtType makeAugAssign(int op) throws Exception {
exprType value = (exprType) stack.popNode();
exprType target = (exprType) stack.popNode();
ctx.setAugStore(target);
return new AugAssign(target, op, value);
}
BinOp makeBinOp(int op) {
exprType right = (exprType) stack.popNode();
exprType left = (exprType) stack.popNode();
return new BinOp(left, op, right);
}
boolean isArg(SimpleNode n){
if (n instanceof ExtraArg)
return true;
if (n instanceof DefaultArg)
return true;
if (n instanceof keywordType)
return true;
return false;
}
NameTok[] getVargAndKwarg(java.util.List<SimpleNode> args) throws Exception {
NameTok varg = null;
NameTok kwarg = null;
for (Iterator<SimpleNode> iter = args.iterator(); iter.hasNext();) {
SimpleNode node = iter.next();
if(node.getId() == JJTEXTRAKEYWORDLIST){
ExtraArg a = (ExtraArg)node;
kwarg = a.tok;
addSpecialsAndClearOriginal(a, kwarg);
}else if(node.getId() == JJTEXTRAARGLIST){
ExtraArg a = (ExtraArg)node;
varg = a.tok;
addSpecialsAndClearOriginal(a, varg);
}
}
return new NameTok[]{varg, kwarg};
}
private argumentsType makeArguments(DefaultArg[] def, NameTok varg, NameTok kwarg) throws Exception {
exprType fpargs[] = new exprType[def.length];
exprType defaults[] = new exprType[def.length];
int startofdefaults = 0;
boolean defaultsSet = false;
for(int i = 0 ; i< def.length; i++){
DefaultArg node = def[i];
exprType parameter = node.parameter;
fpargs[i] = parameter;
if(node.specialsBefore != null && node.specialsBefore.size() > 0){
parameter.getSpecialsBefore().addAll(node.specialsBefore);
}
if(node.specialsAfter != null && node.specialsAfter.size() > 0){
parameter.getSpecialsAfter().addAll(node.specialsAfter);
}
ctx.setParam(fpargs[i]);
defaults[i] = node.value;
if (node.value != null && defaultsSet == false){
defaultsSet = true;
startofdefaults = i;
}
}
// System.out.println("start "+ startofdefaults + " " + l);
exprType[] newdefs = new exprType[def.length - startofdefaults];
System.arraycopy(defaults, startofdefaults, newdefs, 0, newdefs.length);
return new argumentsType(fpargs, varg, kwarg, newdefs);
}
private argumentsType makeArguments(int l) throws Exception {
NameTok kwarg = null;
NameTok stararg = null;
if (l > 0 && stack.peekNode().getId() == JJTEXTRAKEYWORDLIST) {
ExtraArg node = (ExtraArg) stack.popNode();
kwarg = node.tok;
l--;
addSpecialsAndClearOriginal(node, kwarg);
}
if (l > 0 && stack.peekNode().getId() == JJTEXTRAARGLIST) {
ExtraArg node = (ExtraArg) stack.popNode();
stararg = node.tok;
l--;
addSpecialsAndClearOriginal(node, stararg);
}
ArrayList<SimpleNode> list = new ArrayList<SimpleNode>();
for (int i = l-1; i >= 0; i--) {
SimpleNode popped = null;
try{
popped = stack.popNode();
list.add((DefaultArg) popped);
}catch(ClassCastException e){
throw new ParseException("Internal error (ClassCastException):"+e.getMessage()+"\n"+popped, popped);
}
}
Collections.reverse(list);//we get them in reverse order in the stack
return makeArguments((DefaultArg[]) list.toArray(new DefaultArg[0]), stararg, kwarg);
}
}
class ComprehensionCollection extends SimpleNode{
public ArrayList<Comprehension> added = new ArrayList<Comprehension>();
public comprehensionType[] getGenerators() {
ArrayList<Comprehension> f = added;
added = null;
Collections.reverse(f);
return f.toArray(new comprehensionType[0]);
}
}
class Decorators extends SimpleNode {
public decoratorsType[] exp;
private int id;
Decorators(decoratorsType[] exp, int id) {
this.exp = exp;
this.id = id;
}
public int getId() {
return id;
}
}
class DefaultArg extends SimpleNode {
public exprType parameter;
public exprType value;
DefaultArg(exprType parameter, exprType value) {
this.parameter = parameter;
this.value = value;
}
}
class ExtraArg extends SimpleNode {
public int id;
NameTok tok;
ExtraArg(NameTok tok, int id) {
this.tok = tok;
this.id = id;
}
public int getId() {
return id;
}
}
class ExtraArgValue extends SimpleNode {
public exprType value;
public int id;
ExtraArgValue(exprType value, int id) {
this.value = value;
this.id = id;
}
public int getId() {
return id;
}
}
class IdentityNode extends SimpleNode {
public int id;
public Object image;
IdentityNode(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setImage(Object image) {
this.image = image;
}
public Object getImage() {
return image;
}
public String toString() {
return "IdNode[" + PythonGrammar25TreeConstants.jjtNodeName[id] + ", " +
image + "]";
}
}
class CtxVisitor extends Visitor {
private int ctx;
public CtxVisitor() { }
public void setParam(SimpleNode node) throws Exception {
this.ctx = expr_contextType.Param;
visit(node);
}
public void setStore(SimpleNode node) throws Exception {
this.ctx = expr_contextType.Store;
visit(node);
}
public void setStore(SimpleNode[] nodes) throws Exception {
for (int i = 0; i < nodes.length; i++)
setStore(nodes[i]);
}
public void setDelete(SimpleNode node) throws Exception {
this.ctx = expr_contextType.Del;
visit(node);
}
public void setDelete(SimpleNode[] nodes) throws Exception {
for (int i = 0; i < nodes.length; i++)
setDelete(nodes[i]);
}
public void setAugStore(SimpleNode node) throws Exception {
this.ctx = expr_contextType.AugStore;
visit(node);
}
public Object visitName(Name node) throws Exception {
node.ctx = ctx;
return null;
}
public Object visitAttribute(Attribute node) throws Exception {
node.ctx = ctx;
return null;
}
public Object visitSubscript(Subscript node) throws Exception {
node.ctx = ctx;
return null;
}
public Object visitList(List node) throws Exception {
if (ctx == expr_contextType.AugStore) {
throw new ParseException(
"augmented assign to list not possible", node);
}
node.ctx = ctx;
traverse(node);
return null;
}
public Object visitTuple(Tuple node) throws Exception {
if (ctx == expr_contextType.AugStore) {
throw new ParseException(
"augmented assign to tuple not possible", node);
}
node.ctx = ctx;
traverse(node);
return null;
}
public Object visitCall(Call node) throws Exception {
throw new ParseException("can't assign to function call", node);
}
public Object visitListComp(Call node) throws Exception {
throw new ParseException("can't assign to list comprehension call",
node);
}
public Object unhandled_node(SimpleNode node) throws Exception {
throw new ParseException("can't assign to operator", node);
}
}
| true | true |
public SimpleNode closeNode(SimpleNode n, int arity) throws Exception {
exprType value;
exprType[] exprs;
int l;
switch (n.getId()) {
case -1:
System.out.println("Illegal node");
case JJTSINGLE_INPUT:
return new Interactive(makeStmts(arity));
case JJTFILE_INPUT:
return new Module(makeStmts(arity));
case JJTEVAL_INPUT:
return new Expression(((exprType) stack.popNode()));
case JJTNAME:
Name name = new Name(n.getImage().toString(), Name.Load);
addSpecialsAndClearOriginal(n, name);
return name;
case JJTNUM:
//throw new RuntimeException("how to handle this? -- fabio")
return new Num(n.getImage());
case JJTUNICODE:
case JJTSTRING:
Object[] image = (Object[]) n.getImage();
return new Str((String)image[0], (Integer)image[3], (Boolean)image[1], (Boolean)image[2]);
case JJTSUITE:
stmtType[] stmts = new stmtType[arity];
for (int i = arity-1; i >= 0; i--) {
SimpleNode yield_or_stmt = stack.popNode();
if(yield_or_stmt instanceof Yield){
stmts[i] = new Expr((Yield)yield_or_stmt);
}else{
stmts[i] = (stmtType) yield_or_stmt;
}
}
return new Suite(stmts);
case JJTEXPR_STMT:
value = (exprType) stack.popNode();
if (arity > 1) {
exprs = makeExprs(arity-1);
ctx.setStore(exprs);
return new Assign(exprs, value);
} else {
return new Expr(value);
}
case JJTINDEX_OP:
sliceType slice = (sliceType) stack.popNode();
value = (exprType) stack.popNode();
return new Subscript(value, slice, Subscript.Load);
case JJTDOT_OP:
NameTok attr = makeName(NameTok.Attrib);
value = (exprType) stack.popNode();
return new Attribute(value, attr, Attribute.Load);
case JJTBEGIN_DEL_STMT:
return new Delete(null);
case JJTDEL_STMT:
exprs = makeExprs(arity-1);
ctx.setDelete(exprs);
Delete d = (Delete) stack.popNode();
d.targets = exprs;
return d;
case JJTPRINT_STMT:
boolean nl = true;
if (stack.nodeArity() == 0){
Print p = new Print(null, null, true);
p.getSpecialsBefore().add(0, "print ");
return p;
}
if (stack.peekNode().getId() == JJTCOMMA) {
stack.popNode();
nl = false;
}
Print p = new Print(null, makeExprs(), nl);
p.getSpecialsBefore().add(0, "print ");
return p;
case JJTPRINTEXT_STMT:
nl = true;
if (stack.peekNode().getId() == JJTCOMMA) {
stack.popNode();
nl = false;
}
exprs = makeExprs(stack.nodeArity()-1);
p = new Print(((exprType) stack.popNode()), exprs, nl);
p.getSpecialsBefore().add(0, ">> ");
p.getSpecialsBefore().add(0, "print ");
return p;
case JJTBEGIN_FOR_STMT:
return new For(null,null,null,null);
case JJTFOR_STMT:
suiteType orelseSuite = null;
if (stack.nodeArity() == 6){
orelseSuite = popSuiteAndSuiteType();
}
stmtType[] body = popSuite();
exprType iter = (exprType) stack.popNode();
exprType target = (exprType) stack.popNode();
ctx.setStore(target);
For forStmt = (For) stack.popNode();
forStmt.target = target;
forStmt.iter = iter;
forStmt.body = body;
forStmt.orelse = orelseSuite;
return forStmt;
case JJTBEGIN_FOR_ELSE_STMT:
return new suiteType(null);
case JJTBEGIN_ELSE_STMT:
return new suiteType(null);
case JJTBEGIN_WHILE_STMT:
return new While(null, null, null);
case JJTWHILE_STMT:
orelseSuite = null;
if (stack.nodeArity() == 5){
orelseSuite = popSuiteAndSuiteType();
}
body = popSuite();
exprType test = (exprType) stack.popNode();
While w = (While) stack.popNode();
w.test = test;
w.body = body;
w.orelse = orelseSuite;
return w;
case JJTBEGIN_IF_STMT:
return new If(null, null, null);
case JJTBEGIN_ELIF_STMT:
return new If(null, null, null);
case JJTIF_STMT:
stmtType[] orelse = null;
//arity--;//because of the beg if stmt
if (arity % 3 == 1){
orelse = getBodyAndSpecials();
}
//make the suite
Suite suite = (Suite)stack.popNode();
body = suite.body;
test = (exprType) stack.popNode();
//make the if
If last = (If) stack.popNode();
last.test = test;
last.body = body;
last.orelse = orelse;
addSpecialsAndClearOriginal(suite, last);
for (int i = 0; i < (arity / 3)-1; i++) {
//arity--;//because of the beg if stmt
suite = (Suite)stack.popNode();
body = suite.body;
test = (exprType) stack.popNode();
stmtType[] newOrElse = new stmtType[] { last };
last = (If) stack.popNode();
last.test = test;
last.body = body;
last.orelse = newOrElse;
addSpecialsAndClearOriginal(suite, last);
}
return last;
case JJTPASS_STMT:
return new Pass();
case JJTBREAK_STMT:
return new Break();
case JJTCONTINUE_STMT:
return new Continue();
case JJTBEGIN_DECORATOR:
return new decoratorsType(null,null,null,null, null);
case JJTDECORATORS:
ArrayList<SimpleNode> list2 = new ArrayList<SimpleNode>();
ArrayList<SimpleNode> listArgs = new ArrayList<SimpleNode>();
while(stack.nodeArity() > 0){
SimpleNode node = stack.popNode();
while(!(node instanceof decoratorsType)){
if(node instanceof ComprehensionCollection){
listArgs.add(((ComprehensionCollection)node).getGenerators()[0]);
listArgs.add(stack.popNode()); //target
}else{
listArgs.add(node);
}
node = stack.popNode();
}
listArgs.add(node);//the decoratorsType
list2.add(0,makeDecorator(listArgs));
listArgs.clear();
}
return new Decorators((decoratorsType[]) list2.toArray(new decoratorsType[0]), JJTDECORATORS);
case JJTCALL_OP:
exprType starargs = null;
exprType kwargs = null;
l = arity - 1;
if (l > 0 && stack.peekNode().getId() == JJTEXTRAKEYWORDVALUELIST) {
ExtraArgValue nkwargs = (ExtraArgValue) stack.popNode();
kwargs = nkwargs.value;
this.addSpecialsAndClearOriginal(nkwargs, kwargs);
l--;
}
if (l > 0 && stack.peekNode().getId() == JJTEXTRAARGVALUELIST) {
ExtraArgValue nstarargs = (ExtraArgValue) stack.popNode();
starargs = nstarargs.value;
this.addSpecialsAndClearOriginal(nstarargs, starargs);
l--;
}
int nargs = l;
SimpleNode[] tmparr = new SimpleNode[l];
for (int i = l - 1; i >= 0; i--) {
tmparr[i] = stack.popNode();
if (tmparr[i] instanceof keywordType) {
nargs = i;
}
}
exprType[] args = new exprType[nargs];
for (int i = 0; i < nargs; i++) {
//what can happen is something like print sum(x for x in y), where we have already passed x in the args, and then get 'for x in y'
if(tmparr[i] instanceof ComprehensionCollection){
args = new exprType[]{
new ListComp(args[0], ((ComprehensionCollection)tmparr[i]).getGenerators())};
}else{
args[i] = (exprType) tmparr[i];
}
}
keywordType[] keywords = new keywordType[l - nargs];
for (int i = nargs; i < l; i++) {
if (!(tmparr[i] instanceof keywordType))
throw new ParseException(
"non-keyword argument following keyword", tmparr[i]);
keywords[i - nargs] = (keywordType) tmparr[i];
}
exprType func = (exprType) stack.popNode();
Call c = new Call(func, args, keywords, starargs, kwargs);
addSpecialsAndClearOriginal(n, c);
return c;
case JJTFUNCDEF:
//get the decorators
//and clear them for the next call (they always must be before a function def)
suite = (Suite) stack.popNode();
body = suite.body;
argumentsType arguments = makeArguments(stack.nodeArity() - 2);
NameTok nameTok = makeName(NameTok.FunctionName);
Decorators decs = (Decorators) stack.popNode() ;
decoratorsType[] decsexp = decs.exp;
FunctionDef funcDef = new FunctionDef(nameTok, arguments, body, decsexp);
if(decs.exp.length == 0){
addSpecialsBefore(decs, funcDef);
}
addSpecialsAndClearOriginal(suite, funcDef);
return funcDef;
case JJTDEFAULTARG:
value = (arity == 1) ? null : ((exprType) stack.popNode());
return new DefaultArg(((exprType) stack.popNode()), value);
case JJTEXTRAARGLIST:
return new ExtraArg(makeName(NameTok.VarArg), JJTEXTRAARGLIST);
case JJTEXTRAKEYWORDLIST:
return new ExtraArg(makeName(NameTok.KwArg), JJTEXTRAKEYWORDLIST);
case JJTCLASSDEF:
suite = (Suite) stack.popNode();
body = suite.body;
exprType[] bases = makeExprs(stack.nodeArity() - 1);
nameTok = makeName(NameTok.ClassName);
ClassDef classDef = new ClassDef(nameTok, bases, body);
addSpecialsAndClearOriginal(suite, classDef);
return classDef;
case JJTBEGIN_RETURN_STMT:
return new Return(null);
case JJTRETURN_STMT:
value = arity == 2 ? ((exprType) stack.popNode()) : null;
Return ret = (Return) stack.popNode();
ret.value = value;
return ret;
case JJTYIELD_STMT:
return stack.popNode();
case JJTYIELD_EXPR:
exprType yieldExpr = null;
if(arity > 0){
//we may have an empty yield, so, we have to check it before
yieldExpr = (exprType) stack.popNode();
}
return new Yield(yieldExpr);
case JJTRAISE_STMT:
exprType tback = arity >= 3 ? ((exprType) stack.popNode()) : null;
exprType inst = arity >= 2 ? ((exprType) stack.popNode()) : null;
exprType type = arity >= 1 ? ((exprType) stack.popNode()) : null;
return new Raise(type, inst, tback);
case JJTGLOBAL_STMT:
Global global = new Global(makeIdentifiers(NameTok.GlobalName));
return global;
case JJTEXEC_STMT:
exprType globals = arity >= 3 ? ((exprType) stack.popNode()) : null;
exprType locals = arity >= 2 ? ((exprType) stack.popNode()) : null;
value = (exprType) stack.popNode();
return new Exec(value, locals, globals);
case JJTASSERT_STMT:
exprType msg = arity == 2 ? ((exprType) stack.popNode()) : null;
test = (exprType) stack.popNode();
return new Assert(test, msg);
case JJTBEGIN_TRY_STMT:
//we do that just to get the specials
return new TryExcept(null, null, null);
case JJTTRYELSE_STMT:
orelseSuite = popSuiteAndSuiteType();
return orelseSuite;
case JJTTRYFINALLY_OUTER_STMT:
orelseSuite = popSuiteAndSuiteType();
return new TryFinally(null, orelseSuite); //it does not have a body at this time... it will be filled with the inner try..except
case JJTTRY_STMT:
TryFinally outer = null;
if(stack.peekNode() instanceof TryFinally){
outer = (TryFinally) stack.popNode();
arity--;
}
orelseSuite = null;
if(stack.peekNode() instanceof suiteType){
orelseSuite = (suiteType) stack.popNode();
arity--;
}
l = arity ;
excepthandlerType[] handlers = new excepthandlerType[l];
for (int i = l - 1; i >= 0; i--) {
handlers[i] = (excepthandlerType) stack.popNode();
}
suite = (Suite)stack.popNode();
TryExcept tryExc = (TryExcept) stack.popNode();
tryExc.body = suite.body;
tryExc.handlers = handlers;
tryExc.orelse = orelseSuite;
addSpecials(suite, tryExc);
if (outer == null){
return tryExc;
}else{
if(outer.body != null){
throw new RuntimeException("Error. Expecting null body to be filled on try..except..finally");
}
outer.body = new stmtType[]{tryExc};
return outer;
}
case JJTBEGIN_TRY_ELSE_STMT:
//we do that just to get the specials
return new suiteType(null);
case JJTBEGIN_EXCEPT_CLAUSE:
return new excepthandlerType(null,null,null);
case JJTEXCEPT_CLAUSE:
suite = (Suite) stack.popNode();
body = suite.body;
exprType excname = arity == 4 ? ((exprType) stack.popNode()) : null;
if (excname != null){
ctx.setStore(excname);
}
type = arity >= 3 ? ((exprType) stack.popNode()) : null;
excepthandlerType handler = (excepthandlerType) stack.popNode();
handler.type = type;
handler.name = excname;
handler.body = body;
addSpecials(suite, handler);
return handler;
case JJTBEGIN_FINALLY_STMT:
//we do that just to get the specials
return new suiteType(null);
case JJTTRYFINALLY_STMT:
suiteType finalBody = popSuiteAndSuiteType();
body = popSuite();
//We have a try..except in the stack, but we will change it for a try..finally
//This is because we recognize a try..except in the 'try:' token, but actually end up with a try..finally
TryExcept tryExcept = (TryExcept) stack.popNode();
TryFinally tryFinally = new TryFinally(body, finalBody);
addSpecialsAndClearOriginal(tryExcept, tryFinally);
return tryFinally;
case JJTWITH_STMT:
suite = (Suite) stack.popNode();
arity--;
exprType asOrExpr = (exprType) stack.popNode();
arity--;
exprType expr=null;
if(arity > 0){
expr = (exprType) stack.popNode();
arity--;
}else{
expr = asOrExpr;
asOrExpr = null;
}
suiteType s = new suiteType(suite.body);
addSpecialsAndClearOriginal(suite, s);
return new With(expr, asOrExpr, s);
case JJTWITH_VAR:
expr = (exprType) stack.popNode(); //expr
if (expr != null){
ctx.setStore(expr);
}
return expr;
case JJTOR_BOOLEAN:
return new BoolOp(BoolOp.Or, makeExprs());
case JJTAND_BOOLEAN:
return new BoolOp(BoolOp.And, makeExprs());
case JJTCOMPARISION:
l = arity / 2;
exprType[] comparators = new exprType[l];
int[] ops = new int[l];
for (int i = l-1; i >= 0; i--) {
comparators[i] = (exprType) stack.popNode();
SimpleNode op = stack.popNode();
switch (op.getId()) {
case JJTLESS_CMP: ops[i] = Compare.Lt; break;
case JJTGREATER_CMP: ops[i] = Compare.Gt; break;
case JJTEQUAL_CMP: ops[i] = Compare.Eq; break;
case JJTGREATER_EQUAL_CMP: ops[i] = Compare.GtE; break;
case JJTLESS_EQUAL_CMP: ops[i] = Compare.LtE; break;
case JJTNOTEQUAL_CMP: ops[i] = Compare.NotEq; break;
case JJTIN_CMP: ops[i] = Compare.In; break;
case JJTNOT_IN_CMP: ops[i] = Compare.NotIn; break;
case JJTIS_NOT_CMP: ops[i] = Compare.IsNot; break;
case JJTIS_CMP: ops[i] = Compare.Is; break;
default:
throw new RuntimeException("Unknown cmp op:" + op.getId());
}
}
return new Compare(((exprType) stack.popNode()), ops, comparators);
case JJTLESS_CMP:
case JJTGREATER_CMP:
case JJTEQUAL_CMP:
case JJTGREATER_EQUAL_CMP:
case JJTLESS_EQUAL_CMP:
case JJTNOTEQUAL_CMP:
case JJTIN_CMP:
case JJTNOT_IN_CMP:
case JJTIS_NOT_CMP:
case JJTIS_CMP:
return n;
case JJTOR_2OP:
return makeBinOp(BinOp.BitOr);
case JJTXOR_2OP:
return makeBinOp(BinOp.BitXor);
case JJTAND_2OP:
return makeBinOp(BinOp.BitAnd);
case JJTLSHIFT_2OP:
return makeBinOp(BinOp.LShift);
case JJTRSHIFT_2OP:
return makeBinOp(BinOp.RShift);
case JJTADD_2OP:
return makeBinOp(BinOp.Add);
case JJTSUB_2OP:
return makeBinOp(BinOp.Sub);
case JJTMUL_2OP:
return makeBinOp(BinOp.Mult);
case JJTDIV_2OP:
return makeBinOp(BinOp.Div);
case JJTMOD_2OP:
return makeBinOp(BinOp.Mod);
case JJTPOW_2OP:
return makeBinOp(BinOp.Pow);
case JJTFLOORDIV_2OP:
return makeBinOp(BinOp.FloorDiv);
case JJTPOS_1OP:
return new UnaryOp(UnaryOp.UAdd, ((exprType) stack.popNode()));
case JJTNEG_1OP:
return new UnaryOp(UnaryOp.USub, ((exprType) stack.popNode()));
case JJTINVERT_1OP:
return new UnaryOp(UnaryOp.Invert, ((exprType) stack.popNode()));
case JJTNOT_1OP:
return new UnaryOp(UnaryOp.Not, ((exprType) stack.popNode()));
case JJTEXTRAKEYWORDVALUELIST:
return new ExtraArgValue(((exprType) stack.popNode()), JJTEXTRAKEYWORDVALUELIST);
case JJTEXTRAARGVALUELIST:
return new ExtraArgValue(((exprType) stack.popNode()), JJTEXTRAARGVALUELIST);
case JJTKEYWORD:
value = (exprType) stack.popNode();
nameTok = makeName(NameTok.KeywordName);
return new keywordType(nameTok, value);
case JJTTUPLE:
if (stack.nodeArity() > 0) {
SimpleNode peeked = stack.peekNode();
if(peeked instanceof ComprehensionCollection){
ComprehensionCollection col = (ComprehensionCollection) stack.popNode();
return new ListComp(((exprType) stack.popNode()), col.getGenerators());
}
}
try {
exprType[] exp = makeExprs();
Tuple t = new Tuple(exp, Tuple.Load);
addSpecialsAndClearOriginal(n, t);
return t;
} catch (ClassCastException e) {
if(e.getMessage().equals(ExtraArgValue.class.getName())){
throw new ParseException("Token: '*' is not expected inside tuples.", lastPop);
}
e.printStackTrace();
throw new ParseException("Syntax error while detecting tuple.", lastPop);
}
case JJTLIST:
if (stack.nodeArity() > 0 && stack.peekNode() instanceof ComprehensionCollection) {
ComprehensionCollection col = (ComprehensionCollection) stack.popNode();
return new ListComp(((exprType) stack.popNode()), col.getGenerators());
}
return new List(makeExprs(), List.Load);
case JJTDICTIONARY:
l = arity / 2;
exprType[] keys = new exprType[l];
exprType[] vals = new exprType[l];
for (int i = l - 1; i >= 0; i--) {
vals[i] = (exprType) stack.popNode();
keys[i] = (exprType) stack.popNode();
}
return new Dict(keys, vals);
case JJTSTR_1OP:
return new Repr(((exprType) stack.popNode()));
case JJTSTRJOIN:
Str str2 = (Str) stack.popNode();
Object o = stack.popNode();
if(o instanceof Str){
Str str1 = (Str) o;
return new StrJoin(new exprType[]{str1, str2});
}else{
StrJoin strJ = (StrJoin) o;
exprType[] newStrs = new exprType[strJ.strs.length +1];
System.arraycopy(strJ.strs, 0, newStrs, 0, strJ.strs.length);
newStrs[strJ.strs.length] = str2;
strJ.strs = newStrs;
return strJ;
}
case JJTTEST:
if(arity == 2){
IfExp node = (IfExp) stack.popNode();
node.body = (exprType) stack.popNode();
return node;
}else{
return stack.popNode();
}
case JJTIF_EXP:
exprType ifExprOrelse=(exprType) stack.popNode();
exprType ifExprTest=(exprType) stack.popNode();
return new IfExp(ifExprTest,null,ifExprOrelse);
case JJTOLD_LAMBDEF:
case JJTLAMBDEF:
test = (exprType) stack.popNode();
arguments = makeArguments(arity - 1);
Lambda lambda = new Lambda(arguments, test);
if(arguments == null || arguments.args == null || arguments.args.length == 0){
lambda.getSpecialsBefore().add("lambda");
}else{
lambda.getSpecialsBefore().add("lambda ");
}
return lambda;
case JJTELLIPSES:
return new Ellipsis();
case JJTSLICE:
SimpleNode[] arr = new SimpleNode[arity];
for (int i = arity-1; i >= 0; i--) {
arr[i] = stack.popNode();
}
exprType[] values = new exprType[3];
int k = 0;
java.util.List<Object> specialsBefore = new ArrayList<Object>();
java.util.List<Object> specialsAfter = new ArrayList<Object>();
for (int j = 0; j < arity; j++) {
if (arr[j].getId() == JJTCOLON){
if(arr[j].specialsBefore != null){
specialsBefore.addAll(arr[j].specialsBefore);
arr[j].specialsBefore.clear(); //this nodes may be reused among parses, so, we have to erase the specials
}
if(arr[j].specialsAfter != null){
specialsAfter.addAll(arr[j].specialsAfter);
arr[j].specialsAfter.clear();
}
k++;
}else{
values[k] = (exprType) arr[j];
if(specialsBefore.size() > 0){
values[k].getSpecialsBefore().addAll(specialsBefore);
specialsBefore.clear();
}
if(specialsAfter.size() > 0){
values[k].getSpecialsBefore().addAll(specialsAfter);
specialsAfter.clear();
}
}
}
SimpleNode sliceRet;
if (k == 0) {
sliceRet = new Index(values[0]);
} else {
sliceRet = new Slice(values[0], values[1], values[2]);
}
//this may happen if we have no values
sliceRet.getSpecialsBefore().addAll(specialsBefore);
sliceRet.getSpecialsAfter().addAll(specialsAfter);
specialsBefore.clear();
specialsAfter.clear();
return sliceRet;
case JJTSUBSCRIPTLIST:
sliceType[] dims = new sliceType[arity];
for (int i = arity - 1; i >= 0; i--) {
SimpleNode sliceNode = stack.popNode();
if(sliceNode instanceof sliceType){
dims[i] = (sliceType) sliceNode;
}else if(sliceNode instanceof IdentityNode){
//this should be ignored...
//this happens when parsing something like a[1,], whereas a[1,2] would not have this.
}else{
throw new RuntimeException("Expected a sliceType or an IdentityNode. Received :"+sliceNode.getClass());
}
}
return new ExtSlice(dims);
case JJTAUG_PLUS:
return makeAugAssign(AugAssign.Add);
case JJTAUG_MINUS:
return makeAugAssign(AugAssign.Sub);
case JJTAUG_MULTIPLY:
return makeAugAssign(AugAssign.Mult);
case JJTAUG_DIVIDE:
return makeAugAssign(AugAssign.Div);
case JJTAUG_MODULO:
return makeAugAssign(AugAssign.Mod);
case JJTAUG_AND:
return makeAugAssign(AugAssign.BitAnd);
case JJTAUG_OR:
return makeAugAssign(AugAssign.BitOr);
case JJTAUG_XOR:
return makeAugAssign(AugAssign.BitXor);
case JJTAUG_LSHIFT:
return makeAugAssign(AugAssign.LShift);
case JJTAUG_RSHIFT:
return makeAugAssign(AugAssign.RShift);
case JJTAUG_POWER:
return makeAugAssign(AugAssign.Pow);
case JJTAUG_FLOORDIVIDE:
return makeAugAssign(AugAssign.FloorDiv);
case JJTLIST_FOR:
ComprehensionCollection col = null;
if(stack.peekNode() instanceof ComprehensionCollection){
col = (ComprehensionCollection) stack.popNode();
arity--;
}else{
col = new ComprehensionCollection();
}
ArrayList<exprType> ifs = new ArrayList<exprType>();
for (int i = arity-3; i >= 0; i--) {
SimpleNode ifsNode = stack.popNode();
ifs.add((exprType) ifsNode);
}
iter = (exprType) stack.popNode();
target = (exprType) stack.popNode();
ctx.setStore(target);
col.added.add(new Comprehension(target, iter, ifs.toArray(new exprType[0])));
return col;
case JJTIMPORTFROM:
ArrayList<aliasType> aliastL = new ArrayList<aliasType>();
while(arity > 0 && stack.peekNode() instanceof aliasType){
aliastL.add(0, (aliasType) stack.popNode());
arity--;
}
NameTok nT;
if(arity > 0){
nT = makeName(NameTok.ImportModule);
}else{
nT = new NameTok("", NameTok.ImportModule);
}
return new ImportFrom((NameTokType)nT, aliastL.toArray(new aliasType[0]), 0);
case JJTIMPORT:
return new Import(makeAliases(arity));
case JJTDOTTED_NAME:
name = new Name(null, Name.Load);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arity; i++) {
if (i > 0){
sb.insert(0, '.');
}
Name name0 = (Name) stack.popNode();
sb.insert(0, name0.id);
addSpecials(name0, name);
//we have to set that, because if we later add things to the previous Name, we will now want it to be added to
//the new name (comments will only appear later and may be added to the previous name -- so, we replace the previous
//name specials list).
name0.specialsBefore = name.getSpecialsBefore();
name0.specialsAfter = name.getSpecialsAfter();
}
name.id = sb.toString();
return name;
case JJTDOTTED_AS_NAME:
NameTok asname = null;
if (arity > 1){
asname = makeName(NameTok.ImportName);
}
return new aliasType(makeName(NameTok.ImportName), asname);
case JJTIMPORT_AS_NAME:
asname = null;
if (arity > 1){
asname = makeName(NameTok.ImportName);
}
return new aliasType(makeName(NameTok.ImportName), asname);
case JJTCOMMA:
case JJTCOLON:
return n;
default:
System.out.println("Error at TreeBuilder: default not treated:"+n.getId());
return null;
}
}
|
public SimpleNode closeNode(SimpleNode n, int arity) throws Exception {
exprType value;
exprType[] exprs;
int l;
switch (n.getId()) {
case -1:
System.out.println("Illegal node");
case JJTSINGLE_INPUT:
return new Interactive(makeStmts(arity));
case JJTFILE_INPUT:
return new Module(makeStmts(arity));
case JJTEVAL_INPUT:
return new Expression(((exprType) stack.popNode()));
case JJTNAME:
Name name = new Name(n.getImage().toString(), Name.Load);
addSpecialsAndClearOriginal(n, name);
return name;
case JJTNUM:
//throw new RuntimeException("how to handle this? -- fabio")
return new Num(n.getImage());
case JJTUNICODE:
case JJTSTRING:
Object[] image = (Object[]) n.getImage();
return new Str((String)image[0], (Integer)image[3], (Boolean)image[1], (Boolean)image[2]);
case JJTSUITE:
stmtType[] stmts = new stmtType[arity];
for (int i = arity-1; i >= 0; i--) {
SimpleNode yield_or_stmt = stack.popNode();
if(yield_or_stmt instanceof Yield){
stmts[i] = new Expr((Yield)yield_or_stmt);
}else{
stmts[i] = (stmtType) yield_or_stmt;
}
}
return new Suite(stmts);
case JJTEXPR_STMT:
value = (exprType) stack.popNode();
if (arity > 1) {
exprs = makeExprs(arity-1);
ctx.setStore(exprs);
return new Assign(exprs, value);
} else {
return new Expr(value);
}
case JJTINDEX_OP:
sliceType slice = (sliceType) stack.popNode();
value = (exprType) stack.popNode();
return new Subscript(value, slice, Subscript.Load);
case JJTDOT_OP:
NameTok attr = makeName(NameTok.Attrib);
value = (exprType) stack.popNode();
return new Attribute(value, attr, Attribute.Load);
case JJTBEGIN_DEL_STMT:
return new Delete(null);
case JJTDEL_STMT:
exprs = makeExprs(arity-1);
ctx.setDelete(exprs);
Delete d = (Delete) stack.popNode();
d.targets = exprs;
return d;
case JJTPRINT_STMT:
boolean nl = true;
if (stack.nodeArity() == 0){
Print p = new Print(null, null, true);
p.getSpecialsBefore().add(0, "print ");
return p;
}
if (stack.peekNode().getId() == JJTCOMMA) {
stack.popNode();
nl = false;
}
Print p = new Print(null, makeExprs(), nl);
p.getSpecialsBefore().add(0, "print ");
return p;
case JJTPRINTEXT_STMT:
nl = true;
if (stack.peekNode().getId() == JJTCOMMA) {
stack.popNode();
nl = false;
}
exprs = makeExprs(stack.nodeArity()-1);
p = new Print(((exprType) stack.popNode()), exprs, nl);
p.getSpecialsBefore().add(0, ">> ");
p.getSpecialsBefore().add(0, "print ");
return p;
case JJTBEGIN_FOR_STMT:
return new For(null,null,null,null);
case JJTFOR_STMT:
suiteType orelseSuite = null;
if (stack.nodeArity() == 6){
orelseSuite = popSuiteAndSuiteType();
}
stmtType[] body = popSuite();
exprType iter = (exprType) stack.popNode();
exprType target = (exprType) stack.popNode();
ctx.setStore(target);
For forStmt = (For) stack.popNode();
forStmt.target = target;
forStmt.iter = iter;
forStmt.body = body;
forStmt.orelse = orelseSuite;
return forStmt;
case JJTBEGIN_FOR_ELSE_STMT:
return new suiteType(null);
case JJTBEGIN_ELSE_STMT:
return new suiteType(null);
case JJTBEGIN_WHILE_STMT:
return new While(null, null, null);
case JJTWHILE_STMT:
orelseSuite = null;
if (stack.nodeArity() == 5){
orelseSuite = popSuiteAndSuiteType();
}
body = popSuite();
exprType test = (exprType) stack.popNode();
While w = (While) stack.popNode();
w.test = test;
w.body = body;
w.orelse = orelseSuite;
return w;
case JJTBEGIN_IF_STMT:
return new If(null, null, null);
case JJTBEGIN_ELIF_STMT:
return new If(null, null, null);
case JJTIF_STMT:
stmtType[] orelse = null;
//arity--;//because of the beg if stmt
if (arity % 3 == 1){
orelse = getBodyAndSpecials();
}
//make the suite
Suite suite = (Suite)stack.popNode();
body = suite.body;
test = (exprType) stack.popNode();
//make the if
If last = (If) stack.popNode();
last.test = test;
last.body = body;
last.orelse = orelse;
addSpecialsAndClearOriginal(suite, last);
for (int i = 0; i < (arity / 3)-1; i++) {
//arity--;//because of the beg if stmt
suite = (Suite)stack.popNode();
body = suite.body;
test = (exprType) stack.popNode();
stmtType[] newOrElse = new stmtType[] { last };
last = (If) stack.popNode();
last.test = test;
last.body = body;
last.orelse = newOrElse;
addSpecialsAndClearOriginal(suite, last);
}
return last;
case JJTPASS_STMT:
return new Pass();
case JJTBREAK_STMT:
return new Break();
case JJTCONTINUE_STMT:
return new Continue();
case JJTBEGIN_DECORATOR:
return new decoratorsType(null,null,null,null, null);
case JJTDECORATORS:
ArrayList<SimpleNode> list2 = new ArrayList<SimpleNode>();
ArrayList<SimpleNode> listArgs = new ArrayList<SimpleNode>();
while(stack.nodeArity() > 0){
SimpleNode node = stack.popNode();
while(!(node instanceof decoratorsType)){
if(node instanceof ComprehensionCollection){
listArgs.add(((ComprehensionCollection)node).getGenerators()[0]);
listArgs.add(stack.popNode()); //target
}else{
listArgs.add(node);
}
node = stack.popNode();
}
listArgs.add(node);//the decoratorsType
list2.add(0,makeDecorator(listArgs));
listArgs.clear();
}
return new Decorators((decoratorsType[]) list2.toArray(new decoratorsType[0]), JJTDECORATORS);
case JJTCALL_OP:
exprType starargs = null;
exprType kwargs = null;
l = arity - 1;
if (l > 0 && stack.peekNode().getId() == JJTEXTRAKEYWORDVALUELIST) {
ExtraArgValue nkwargs = (ExtraArgValue) stack.popNode();
kwargs = nkwargs.value;
this.addSpecialsAndClearOriginal(nkwargs, kwargs);
l--;
}
if (l > 0 && stack.peekNode().getId() == JJTEXTRAARGVALUELIST) {
ExtraArgValue nstarargs = (ExtraArgValue) stack.popNode();
starargs = nstarargs.value;
this.addSpecialsAndClearOriginal(nstarargs, starargs);
l--;
}
int nargs = l;
SimpleNode[] tmparr = new SimpleNode[l];
for (int i = l - 1; i >= 0; i--) {
tmparr[i] = stack.popNode();
if (tmparr[i] instanceof keywordType) {
nargs = i;
}
}
exprType[] args = new exprType[nargs];
for (int i = 0; i < nargs; i++) {
//what can happen is something like print sum(x for x in y), where we have already passed x in the args, and then get 'for x in y'
if(tmparr[i] instanceof ComprehensionCollection){
args = new exprType[]{
new ListComp(args[0], ((ComprehensionCollection)tmparr[i]).getGenerators())};
}else{
args[i] = (exprType) tmparr[i];
}
}
keywordType[] keywords = new keywordType[l - nargs];
for (int i = nargs; i < l; i++) {
if (!(tmparr[i] instanceof keywordType))
throw new ParseException(
"non-keyword argument following keyword", tmparr[i]);
keywords[i - nargs] = (keywordType) tmparr[i];
}
exprType func = (exprType) stack.popNode();
Call c = new Call(func, args, keywords, starargs, kwargs);
addSpecialsAndClearOriginal(n, c);
return c;
case JJTFUNCDEF:
//get the decorators
//and clear them for the next call (they always must be before a function def)
suite = (Suite) stack.popNode();
body = suite.body;
argumentsType arguments = makeArguments(stack.nodeArity() - 2);
NameTok nameTok = makeName(NameTok.FunctionName);
Decorators decs = (Decorators) stack.popNode() ;
decoratorsType[] decsexp = decs.exp;
FunctionDef funcDef = new FunctionDef(nameTok, arguments, body, decsexp);
if(decs.exp.length == 0){
addSpecialsBefore(decs, funcDef);
}
addSpecialsAndClearOriginal(suite, funcDef);
return funcDef;
case JJTDEFAULTARG:
value = (arity == 1) ? null : ((exprType) stack.popNode());
return new DefaultArg(((exprType) stack.popNode()), value);
case JJTEXTRAARGLIST:
return new ExtraArg(makeName(NameTok.VarArg), JJTEXTRAARGLIST);
case JJTEXTRAKEYWORDLIST:
return new ExtraArg(makeName(NameTok.KwArg), JJTEXTRAKEYWORDLIST);
case JJTCLASSDEF:
suite = (Suite) stack.popNode();
body = suite.body;
exprType[] bases = makeExprs(stack.nodeArity() - 1);
nameTok = makeName(NameTok.ClassName);
ClassDef classDef = new ClassDef(nameTok, bases, body);
addSpecialsAndClearOriginal(suite, classDef);
return classDef;
case JJTBEGIN_RETURN_STMT:
return new Return(null);
case JJTRETURN_STMT:
value = arity == 2 ? ((exprType) stack.popNode()) : null;
Return ret = (Return) stack.popNode();
ret.value = value;
return ret;
case JJTYIELD_STMT:
return stack.popNode();
case JJTYIELD_EXPR:
exprType yieldExpr = null;
if(arity > 0){
//we may have an empty yield, so, we have to check it before
yieldExpr = (exprType) stack.popNode();
}
return new Yield(yieldExpr);
case JJTRAISE_STMT:
exprType tback = arity >= 3 ? ((exprType) stack.popNode()) : null;
exprType inst = arity >= 2 ? ((exprType) stack.popNode()) : null;
exprType type = arity >= 1 ? ((exprType) stack.popNode()) : null;
return new Raise(type, inst, tback);
case JJTGLOBAL_STMT:
Global global = new Global(makeIdentifiers(NameTok.GlobalName));
return global;
case JJTEXEC_STMT:
exprType globals = arity >= 3 ? ((exprType) stack.popNode()) : null;
exprType locals = arity >= 2 ? ((exprType) stack.popNode()) : null;
value = (exprType) stack.popNode();
return new Exec(value, locals, globals);
case JJTASSERT_STMT:
exprType msg = arity == 2 ? ((exprType) stack.popNode()) : null;
test = (exprType) stack.popNode();
return new Assert(test, msg);
case JJTBEGIN_TRY_STMT:
//we do that just to get the specials
return new TryExcept(null, null, null);
case JJTTRYELSE_STMT:
orelseSuite = popSuiteAndSuiteType();
return orelseSuite;
case JJTTRYFINALLY_OUTER_STMT:
orelseSuite = popSuiteAndSuiteType();
return new TryFinally(null, orelseSuite); //it does not have a body at this time... it will be filled with the inner try..except
case JJTTRY_STMT:
TryFinally outer = null;
if(stack.peekNode() instanceof TryFinally){
outer = (TryFinally) stack.popNode();
arity--;
}
orelseSuite = null;
if(stack.peekNode() instanceof suiteType){
orelseSuite = (suiteType) stack.popNode();
arity--;
}
l = arity ;
excepthandlerType[] handlers = new excepthandlerType[l];
for (int i = l - 1; i >= 0; i--) {
handlers[i] = (excepthandlerType) stack.popNode();
}
suite = (Suite)stack.popNode();
TryExcept tryExc = (TryExcept) stack.popNode();
tryExc.body = suite.body;
tryExc.handlers = handlers;
tryExc.orelse = orelseSuite;
addSpecials(suite, tryExc);
if (outer == null){
return tryExc;
}else{
if(outer.body != null){
throw new RuntimeException("Error. Expecting null body to be filled on try..except..finally");
}
outer.body = new stmtType[]{tryExc};
return outer;
}
case JJTBEGIN_TRY_ELSE_STMT:
//we do that just to get the specials
return new suiteType(null);
case JJTBEGIN_EXCEPT_CLAUSE:
return new excepthandlerType(null,null,null);
case JJTEXCEPT_CLAUSE:
suite = (Suite) stack.popNode();
body = suite.body;
exprType excname = arity == 4 ? ((exprType) stack.popNode()) : null;
if (excname != null){
ctx.setStore(excname);
}
type = arity >= 3 ? ((exprType) stack.popNode()) : null;
excepthandlerType handler = (excepthandlerType) stack.popNode();
handler.type = type;
handler.name = excname;
handler.body = body;
addSpecials(suite, handler);
return handler;
case JJTBEGIN_FINALLY_STMT:
//we do that just to get the specials
return new suiteType(null);
case JJTTRYFINALLY_STMT:
suiteType finalBody = popSuiteAndSuiteType();
body = popSuite();
//We have a try..except in the stack, but we will change it for a try..finally
//This is because we recognize a try..except in the 'try:' token, but actually end up with a try..finally
TryExcept tryExcept = (TryExcept) stack.popNode();
TryFinally tryFinally = new TryFinally(body, finalBody);
tryFinally.beginLine = tryExcept.beginLine;
tryFinally.beginColumn = tryExcept.beginColumn;
addSpecialsAndClearOriginal(tryExcept, tryFinally);
return tryFinally;
case JJTWITH_STMT:
suite = (Suite) stack.popNode();
arity--;
exprType asOrExpr = (exprType) stack.popNode();
arity--;
exprType expr=null;
if(arity > 0){
expr = (exprType) stack.popNode();
arity--;
}else{
expr = asOrExpr;
asOrExpr = null;
}
suiteType s = new suiteType(suite.body);
addSpecialsAndClearOriginal(suite, s);
return new With(expr, asOrExpr, s);
case JJTWITH_VAR:
expr = (exprType) stack.popNode(); //expr
if (expr != null){
ctx.setStore(expr);
}
return expr;
case JJTOR_BOOLEAN:
return new BoolOp(BoolOp.Or, makeExprs());
case JJTAND_BOOLEAN:
return new BoolOp(BoolOp.And, makeExprs());
case JJTCOMPARISION:
l = arity / 2;
exprType[] comparators = new exprType[l];
int[] ops = new int[l];
for (int i = l-1; i >= 0; i--) {
comparators[i] = (exprType) stack.popNode();
SimpleNode op = stack.popNode();
switch (op.getId()) {
case JJTLESS_CMP: ops[i] = Compare.Lt; break;
case JJTGREATER_CMP: ops[i] = Compare.Gt; break;
case JJTEQUAL_CMP: ops[i] = Compare.Eq; break;
case JJTGREATER_EQUAL_CMP: ops[i] = Compare.GtE; break;
case JJTLESS_EQUAL_CMP: ops[i] = Compare.LtE; break;
case JJTNOTEQUAL_CMP: ops[i] = Compare.NotEq; break;
case JJTIN_CMP: ops[i] = Compare.In; break;
case JJTNOT_IN_CMP: ops[i] = Compare.NotIn; break;
case JJTIS_NOT_CMP: ops[i] = Compare.IsNot; break;
case JJTIS_CMP: ops[i] = Compare.Is; break;
default:
throw new RuntimeException("Unknown cmp op:" + op.getId());
}
}
return new Compare(((exprType) stack.popNode()), ops, comparators);
case JJTLESS_CMP:
case JJTGREATER_CMP:
case JJTEQUAL_CMP:
case JJTGREATER_EQUAL_CMP:
case JJTLESS_EQUAL_CMP:
case JJTNOTEQUAL_CMP:
case JJTIN_CMP:
case JJTNOT_IN_CMP:
case JJTIS_NOT_CMP:
case JJTIS_CMP:
return n;
case JJTOR_2OP:
return makeBinOp(BinOp.BitOr);
case JJTXOR_2OP:
return makeBinOp(BinOp.BitXor);
case JJTAND_2OP:
return makeBinOp(BinOp.BitAnd);
case JJTLSHIFT_2OP:
return makeBinOp(BinOp.LShift);
case JJTRSHIFT_2OP:
return makeBinOp(BinOp.RShift);
case JJTADD_2OP:
return makeBinOp(BinOp.Add);
case JJTSUB_2OP:
return makeBinOp(BinOp.Sub);
case JJTMUL_2OP:
return makeBinOp(BinOp.Mult);
case JJTDIV_2OP:
return makeBinOp(BinOp.Div);
case JJTMOD_2OP:
return makeBinOp(BinOp.Mod);
case JJTPOW_2OP:
return makeBinOp(BinOp.Pow);
case JJTFLOORDIV_2OP:
return makeBinOp(BinOp.FloorDiv);
case JJTPOS_1OP:
return new UnaryOp(UnaryOp.UAdd, ((exprType) stack.popNode()));
case JJTNEG_1OP:
return new UnaryOp(UnaryOp.USub, ((exprType) stack.popNode()));
case JJTINVERT_1OP:
return new UnaryOp(UnaryOp.Invert, ((exprType) stack.popNode()));
case JJTNOT_1OP:
return new UnaryOp(UnaryOp.Not, ((exprType) stack.popNode()));
case JJTEXTRAKEYWORDVALUELIST:
return new ExtraArgValue(((exprType) stack.popNode()), JJTEXTRAKEYWORDVALUELIST);
case JJTEXTRAARGVALUELIST:
return new ExtraArgValue(((exprType) stack.popNode()), JJTEXTRAARGVALUELIST);
case JJTKEYWORD:
value = (exprType) stack.popNode();
nameTok = makeName(NameTok.KeywordName);
return new keywordType(nameTok, value);
case JJTTUPLE:
if (stack.nodeArity() > 0) {
SimpleNode peeked = stack.peekNode();
if(peeked instanceof ComprehensionCollection){
ComprehensionCollection col = (ComprehensionCollection) stack.popNode();
return new ListComp(((exprType) stack.popNode()), col.getGenerators());
}
}
try {
exprType[] exp = makeExprs();
Tuple t = new Tuple(exp, Tuple.Load);
addSpecialsAndClearOriginal(n, t);
return t;
} catch (ClassCastException e) {
if(e.getMessage().equals(ExtraArgValue.class.getName())){
throw new ParseException("Token: '*' is not expected inside tuples.", lastPop);
}
e.printStackTrace();
throw new ParseException("Syntax error while detecting tuple.", lastPop);
}
case JJTLIST:
if (stack.nodeArity() > 0 && stack.peekNode() instanceof ComprehensionCollection) {
ComprehensionCollection col = (ComprehensionCollection) stack.popNode();
return new ListComp(((exprType) stack.popNode()), col.getGenerators());
}
return new List(makeExprs(), List.Load);
case JJTDICTIONARY:
l = arity / 2;
exprType[] keys = new exprType[l];
exprType[] vals = new exprType[l];
for (int i = l - 1; i >= 0; i--) {
vals[i] = (exprType) stack.popNode();
keys[i] = (exprType) stack.popNode();
}
return new Dict(keys, vals);
case JJTSTR_1OP:
return new Repr(((exprType) stack.popNode()));
case JJTSTRJOIN:
Str str2 = (Str) stack.popNode();
Object o = stack.popNode();
if(o instanceof Str){
Str str1 = (Str) o;
return new StrJoin(new exprType[]{str1, str2});
}else{
StrJoin strJ = (StrJoin) o;
exprType[] newStrs = new exprType[strJ.strs.length +1];
System.arraycopy(strJ.strs, 0, newStrs, 0, strJ.strs.length);
newStrs[strJ.strs.length] = str2;
strJ.strs = newStrs;
return strJ;
}
case JJTTEST:
if(arity == 2){
IfExp node = (IfExp) stack.popNode();
node.body = (exprType) stack.popNode();
return node;
}else{
return stack.popNode();
}
case JJTIF_EXP:
exprType ifExprOrelse=(exprType) stack.popNode();
exprType ifExprTest=(exprType) stack.popNode();
return new IfExp(ifExprTest,null,ifExprOrelse);
case JJTOLD_LAMBDEF:
case JJTLAMBDEF:
test = (exprType) stack.popNode();
arguments = makeArguments(arity - 1);
Lambda lambda = new Lambda(arguments, test);
if(arguments == null || arguments.args == null || arguments.args.length == 0){
lambda.getSpecialsBefore().add("lambda");
}else{
lambda.getSpecialsBefore().add("lambda ");
}
return lambda;
case JJTELLIPSES:
return new Ellipsis();
case JJTSLICE:
SimpleNode[] arr = new SimpleNode[arity];
for (int i = arity-1; i >= 0; i--) {
arr[i] = stack.popNode();
}
exprType[] values = new exprType[3];
int k = 0;
java.util.List<Object> specialsBefore = new ArrayList<Object>();
java.util.List<Object> specialsAfter = new ArrayList<Object>();
for (int j = 0; j < arity; j++) {
if (arr[j].getId() == JJTCOLON){
if(arr[j].specialsBefore != null){
specialsBefore.addAll(arr[j].specialsBefore);
arr[j].specialsBefore.clear(); //this nodes may be reused among parses, so, we have to erase the specials
}
if(arr[j].specialsAfter != null){
specialsAfter.addAll(arr[j].specialsAfter);
arr[j].specialsAfter.clear();
}
k++;
}else{
values[k] = (exprType) arr[j];
if(specialsBefore.size() > 0){
values[k].getSpecialsBefore().addAll(specialsBefore);
specialsBefore.clear();
}
if(specialsAfter.size() > 0){
values[k].getSpecialsBefore().addAll(specialsAfter);
specialsAfter.clear();
}
}
}
SimpleNode sliceRet;
if (k == 0) {
sliceRet = new Index(values[0]);
} else {
sliceRet = new Slice(values[0], values[1], values[2]);
}
//this may happen if we have no values
sliceRet.getSpecialsBefore().addAll(specialsBefore);
sliceRet.getSpecialsAfter().addAll(specialsAfter);
specialsBefore.clear();
specialsAfter.clear();
return sliceRet;
case JJTSUBSCRIPTLIST:
sliceType[] dims = new sliceType[arity];
for (int i = arity - 1; i >= 0; i--) {
SimpleNode sliceNode = stack.popNode();
if(sliceNode instanceof sliceType){
dims[i] = (sliceType) sliceNode;
}else if(sliceNode instanceof IdentityNode){
//this should be ignored...
//this happens when parsing something like a[1,], whereas a[1,2] would not have this.
}else{
throw new RuntimeException("Expected a sliceType or an IdentityNode. Received :"+sliceNode.getClass());
}
}
return new ExtSlice(dims);
case JJTAUG_PLUS:
return makeAugAssign(AugAssign.Add);
case JJTAUG_MINUS:
return makeAugAssign(AugAssign.Sub);
case JJTAUG_MULTIPLY:
return makeAugAssign(AugAssign.Mult);
case JJTAUG_DIVIDE:
return makeAugAssign(AugAssign.Div);
case JJTAUG_MODULO:
return makeAugAssign(AugAssign.Mod);
case JJTAUG_AND:
return makeAugAssign(AugAssign.BitAnd);
case JJTAUG_OR:
return makeAugAssign(AugAssign.BitOr);
case JJTAUG_XOR:
return makeAugAssign(AugAssign.BitXor);
case JJTAUG_LSHIFT:
return makeAugAssign(AugAssign.LShift);
case JJTAUG_RSHIFT:
return makeAugAssign(AugAssign.RShift);
case JJTAUG_POWER:
return makeAugAssign(AugAssign.Pow);
case JJTAUG_FLOORDIVIDE:
return makeAugAssign(AugAssign.FloorDiv);
case JJTLIST_FOR:
ComprehensionCollection col = null;
if(stack.peekNode() instanceof ComprehensionCollection){
col = (ComprehensionCollection) stack.popNode();
arity--;
}else{
col = new ComprehensionCollection();
}
ArrayList<exprType> ifs = new ArrayList<exprType>();
for (int i = arity-3; i >= 0; i--) {
SimpleNode ifsNode = stack.popNode();
ifs.add((exprType) ifsNode);
}
iter = (exprType) stack.popNode();
target = (exprType) stack.popNode();
ctx.setStore(target);
col.added.add(new Comprehension(target, iter, ifs.toArray(new exprType[0])));
return col;
case JJTIMPORTFROM:
ArrayList<aliasType> aliastL = new ArrayList<aliasType>();
while(arity > 0 && stack.peekNode() instanceof aliasType){
aliastL.add(0, (aliasType) stack.popNode());
arity--;
}
NameTok nT;
if(arity > 0){
nT = makeName(NameTok.ImportModule);
}else{
nT = new NameTok("", NameTok.ImportModule);
}
return new ImportFrom((NameTokType)nT, aliastL.toArray(new aliasType[0]), 0);
case JJTIMPORT:
return new Import(makeAliases(arity));
case JJTDOTTED_NAME:
name = new Name(null, Name.Load);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arity; i++) {
if (i > 0){
sb.insert(0, '.');
}
Name name0 = (Name) stack.popNode();
sb.insert(0, name0.id);
addSpecials(name0, name);
//we have to set that, because if we later add things to the previous Name, we will now want it to be added to
//the new name (comments will only appear later and may be added to the previous name -- so, we replace the previous
//name specials list).
name0.specialsBefore = name.getSpecialsBefore();
name0.specialsAfter = name.getSpecialsAfter();
}
name.id = sb.toString();
return name;
case JJTDOTTED_AS_NAME:
NameTok asname = null;
if (arity > 1){
asname = makeName(NameTok.ImportName);
}
return new aliasType(makeName(NameTok.ImportName), asname);
case JJTIMPORT_AS_NAME:
asname = null;
if (arity > 1){
asname = makeName(NameTok.ImportName);
}
return new aliasType(makeName(NameTok.ImportName), asname);
case JJTCOMMA:
case JJTCOLON:
return n;
default:
System.out.println("Error at TreeBuilder: default not treated:"+n.getId());
return null;
}
}
|
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 bd370053a..29cbe1af2 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,102 +1,98 @@
/**
* 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.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
- if (app != null) {
- app.setShowInHUD(false);
- }
+ hudComponents.remove((HUDComponent)e.getObject());
}
}
});
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.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
if (app != null) {
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)) {
hudComponents.remove((HUDComponent)e.getObject());
}
}
});
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/thesmith/eventhorizon/service/impl/LastfmEventServiceImpl.java b/src/main/java/thesmith/eventhorizon/service/impl/LastfmEventServiceImpl.java
index e01e18b..ae3fa36 100644
--- a/src/main/java/thesmith/eventhorizon/service/impl/LastfmEventServiceImpl.java
+++ b/src/main/java/thesmith/eventhorizon/service/impl/LastfmEventServiceImpl.java
@@ -1,67 +1,70 @@
package thesmith.eventhorizon.service.impl;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import thesmith.eventhorizon.model.Account;
import thesmith.eventhorizon.model.Event;
import thesmith.eventhorizon.service.EventService;
import com.google.appengine.repackaged.com.google.common.collect.Lists;
import com.google.appengine.repackaged.org.joda.time.format.DateTimeFormat;
import com.google.appengine.repackaged.org.joda.time.format.DateTimeFormatter;
@Service
public class LastfmEventServiceImpl implements EventService {
private static final String API_KEY = "b25b959554ed76058ac220b7b2e0a026";
private static final String DOMAIN_URL = "http://last.fm";
private static final String API_URL = "http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=%s&api_key=%s&format=json&page=%s&limit=10";
private static final DateTimeFormatter formater = DateTimeFormat.forPattern("dd MMM yyyy, HH:mm");
public List<Event> events(Account account, int page) {
if (!"lastfm".equals(account.getDomain()))
throw new RuntimeException("You can only get events for the lastfm domain");
try {
List<Event> events = Lists.newArrayList();
URL url = new URL(String.format(API_URL, account.getPersonId(), API_KEY, String.valueOf(page)));
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer json = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
json.append(line);
}
reader.close();
- JSONObject recentTracks = (new JSONObject(json.toString())).getJSONObject("recenttracks");
- if (recentTracks.has("track")) {
- JSONArray tracks = recentTracks.getJSONArray("track");
- for (int i = 0; i < tracks.length(); i++) {
- JSONObject track = tracks.getJSONObject(i);
- Event event = new Event();
- event.setTitle(track.getJSONObject("artist").getString("#text") + " - " + track.getString("name"));
- event.setTitleUrl(track.getString("url"));
- if (track.has("date")) {
- event.setCreated(formater.parseDateTime(track.getJSONObject("date").getString("#text")).toDate());
- } else {
- event.setCreated(new Date());
+ JSONObject doc = new JSONObject(json.toString());
+ if (doc.has("recenttracks")) {
+ JSONObject recentTracks = (new JSONObject(json.toString())).getJSONObject("recenttracks");
+ if (recentTracks.has("track")) {
+ JSONArray tracks = recentTracks.getJSONArray("track");
+ for (int i = 0; i < tracks.length(); i++) {
+ JSONObject track = tracks.getJSONObject(i);
+ Event event = new Event();
+ event.setTitle(track.getJSONObject("artist").getString("#text") + " - " + track.getString("name"));
+ event.setTitleUrl(track.getString("url"));
+ if (track.has("date")) {
+ event.setCreated(formater.parseDateTime(track.getJSONObject("date").getString("#text")).toDate());
+ } else {
+ event.setCreated(new Date());
+ }
+ event.setDomainUrl(DOMAIN_URL);
+ event.setUserUrl(DOMAIN_URL + "/user/" + account.getUserId());
+ events.add(event);
}
- event.setDomainUrl(DOMAIN_URL);
- event.setUserUrl(DOMAIN_URL + "/user/" + account.getUserId());
- events.add(event);
}
}
return events;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| false | true |
public List<Event> events(Account account, int page) {
if (!"lastfm".equals(account.getDomain()))
throw new RuntimeException("You can only get events for the lastfm domain");
try {
List<Event> events = Lists.newArrayList();
URL url = new URL(String.format(API_URL, account.getPersonId(), API_KEY, String.valueOf(page)));
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer json = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
json.append(line);
}
reader.close();
JSONObject recentTracks = (new JSONObject(json.toString())).getJSONObject("recenttracks");
if (recentTracks.has("track")) {
JSONArray tracks = recentTracks.getJSONArray("track");
for (int i = 0; i < tracks.length(); i++) {
JSONObject track = tracks.getJSONObject(i);
Event event = new Event();
event.setTitle(track.getJSONObject("artist").getString("#text") + " - " + track.getString("name"));
event.setTitleUrl(track.getString("url"));
if (track.has("date")) {
event.setCreated(formater.parseDateTime(track.getJSONObject("date").getString("#text")).toDate());
} else {
event.setCreated(new Date());
}
event.setDomainUrl(DOMAIN_URL);
event.setUserUrl(DOMAIN_URL + "/user/" + account.getUserId());
events.add(event);
}
}
return events;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
|
public List<Event> events(Account account, int page) {
if (!"lastfm".equals(account.getDomain()))
throw new RuntimeException("You can only get events for the lastfm domain");
try {
List<Event> events = Lists.newArrayList();
URL url = new URL(String.format(API_URL, account.getPersonId(), API_KEY, String.valueOf(page)));
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer json = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
json.append(line);
}
reader.close();
JSONObject doc = new JSONObject(json.toString());
if (doc.has("recenttracks")) {
JSONObject recentTracks = (new JSONObject(json.toString())).getJSONObject("recenttracks");
if (recentTracks.has("track")) {
JSONArray tracks = recentTracks.getJSONArray("track");
for (int i = 0; i < tracks.length(); i++) {
JSONObject track = tracks.getJSONObject(i);
Event event = new Event();
event.setTitle(track.getJSONObject("artist").getString("#text") + " - " + track.getString("name"));
event.setTitleUrl(track.getString("url"));
if (track.has("date")) {
event.setCreated(formater.parseDateTime(track.getJSONObject("date").getString("#text")).toDate());
} else {
event.setCreated(new Date());
}
event.setDomainUrl(DOMAIN_URL);
event.setUserUrl(DOMAIN_URL + "/user/" + account.getUserId());
events.add(event);
}
}
}
return events;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
|
diff --git a/src/ConsensusHealthChecker.java b/src/ConsensusHealthChecker.java
index dd88611..5badebd 100644
--- a/src/ConsensusHealthChecker.java
+++ b/src/ConsensusHealthChecker.java
@@ -1,762 +1,762 @@
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.commons.codec.binary.*;
/*
* TODO Possible extensions:
* - Include consensus signatures and tell by which Tor versions the
* consensus will be accepted (and by which not)
*/
public class ConsensusHealthChecker {
private String mostRecentValidAfterTime = null;
private byte[] mostRecentConsensus = null;
private SortedMap<String, byte[]> mostRecentVotes =
new TreeMap<String, byte[]>();
public void processConsensus(String validAfterTime, byte[] data) {
if (this.mostRecentValidAfterTime == null ||
this.mostRecentValidAfterTime.compareTo(validAfterTime) < 0) {
this.mostRecentValidAfterTime = validAfterTime;
this.mostRecentVotes.clear();
this.mostRecentConsensus = data;
}
}
public void processVote(String validAfterTime, String dirSource,
byte[] data) {
if (this.mostRecentValidAfterTime == null ||
this.mostRecentValidAfterTime.compareTo(validAfterTime) < 0) {
this.mostRecentValidAfterTime = validAfterTime;
this.mostRecentVotes.clear();
this.mostRecentConsensus = null;
}
if (this.mostRecentValidAfterTime.equals(validAfterTime)) {
this.mostRecentVotes.put(dirSource, data);
}
}
public void writeStatusWebsite() {
/* If we don't have any consensus, we cannot write useful consensus
* health information to the website. Do not overwrite existing page
* with a warning, because we might just not have learned about a new
* consensus in this execution. */
if (this.mostRecentConsensus == null) {
return;
}
/* Prepare parsing dates. */
SimpleDateFormat dateTimeFormat =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
StringBuilder knownFlagsResults = new StringBuilder();
StringBuilder numRelaysVotesResults = new StringBuilder();
StringBuilder consensusMethodsResults = new StringBuilder();
StringBuilder versionsResults = new StringBuilder();
StringBuilder paramsResults = new StringBuilder();
StringBuilder authorityKeysResults = new StringBuilder();
StringBuilder bandwidthScannersResults = new StringBuilder();
SortedSet<String> allKnownFlags = new TreeSet<String>();
SortedSet<String> allKnownVotes = new TreeSet<String>();
SortedMap<String, String> consensusAssignedFlags =
new TreeMap<String, String>();
SortedMap<String, SortedSet<String>> votesAssignedFlags =
new TreeMap<String, SortedSet<String>>();
SortedMap<String, String> votesKnownFlags =
new TreeMap<String, String>();
SortedMap<String, SortedMap<String, Integer>> flagsAgree =
new TreeMap<String, SortedMap<String, Integer>>();
SortedMap<String, SortedMap<String, Integer>> flagsLost =
new TreeMap<String, SortedMap<String, Integer>>();
SortedMap<String, SortedMap<String, Integer>> flagsMissing =
new TreeMap<String, SortedMap<String, Integer>>();
/* Read consensus and parse all information that we want to compare to
* votes. */
String consensusConsensusMethod = null, consensusKnownFlags = null,
consensusClientVersions = null, consensusServerVersions = null,
consensusParams = null, rLineTemp = null;
int consensusTotalRelays = 0, consensusRunningRelays = 0;
try {
BufferedReader br = new BufferedReader(new StringReader(new String(
this.mostRecentConsensus)));
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("consensus-method ")) {
consensusConsensusMethod = line;
} else if (line.startsWith("client-versions ")) {
consensusClientVersions = line;
} else if (line.startsWith("server-versions ")) {
consensusServerVersions = line;
} else if (line.startsWith("known-flags ")) {
consensusKnownFlags = line;
} else if (line.startsWith("params ")) {
consensusParams = line;
} else if (line.startsWith("r ")) {
rLineTemp = line;
} else if (line.startsWith("s ")) {
consensusTotalRelays++;
if (line.contains(" Running")) {
consensusRunningRelays++;
}
consensusAssignedFlags.put(Hex.encodeHexString(
Base64.decodeBase64(rLineTemp.split(" ")[2] + "=")).
toUpperCase() + " " + rLineTemp.split(" ")[1], line);
}
}
br.close();
} catch (IOException e) {
/* There should be no I/O taking place when reading a String. */
}
/* Read votes and parse all information to compare with the
* consensus. */
for (byte[] voteBytes : this.mostRecentVotes.values()) {
String voteConsensusMethods = null, voteKnownFlags = null,
voteClientVersions = null, voteServerVersions = null,
voteParams = null, dirSource = null, voteDirKeyExpires = null;
int voteTotalRelays = 0, voteRunningRelays = 0,
voteContainsBandwidthWeights = 0;
try {
BufferedReader br = new BufferedReader(new StringReader(
new String(voteBytes)));
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("consensus-methods ")) {
voteConsensusMethods = line;
} else if (line.startsWith("client-versions ")) {
voteClientVersions = line;
} else if (line.startsWith("server-versions ")) {
voteServerVersions = line;
} else if (line.startsWith("known-flags ")) {
voteKnownFlags = line;
} else if (line.startsWith("params ")) {
voteParams = line;
} else if (line.startsWith("dir-source ")) {
dirSource = line.split(" ")[1];
allKnownVotes.add(dirSource);
} else if (line.startsWith("dir-key-expires ")) {
voteDirKeyExpires = line;
} else if (line.startsWith("r ")) {
rLineTemp = line;
} else if (line.startsWith("s ")) {
voteTotalRelays++;
if (line.contains(" Running")) {
voteRunningRelays++;
}
String relayKey = Hex.encodeHexString(Base64.decodeBase64(
rLineTemp.split(" ")[2] + "=")).toUpperCase() + " "
+ rLineTemp.split(" ")[1];
SortedSet<String> sLines = null;
if (votesAssignedFlags.containsKey(relayKey)) {
sLines = votesAssignedFlags.get(relayKey);
} else {
sLines = new TreeSet<String>();
votesAssignedFlags.put(relayKey, sLines);
}
sLines.add(dirSource + " " + line);
} else if (line.startsWith("w ")) {
if (line.contains(" Measured")) {
voteContainsBandwidthWeights++;
}
}
}
br.close();
} catch (IOException e) {
/* There should be no I/O taking place when reading a String. */
}
/* Write known flags. */
knownFlagsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteKnownFlags + "</td>\n"
+ " </tr>\n");
votesKnownFlags.put(dirSource, voteKnownFlags);
for (String flag : voteKnownFlags.substring(
"known-flags ".length()).split(" ")) {
allKnownFlags.add(flag);
}
/* Write number of relays voted about. */
numRelaysVotesResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteTotalRelays + " total</td>\n"
+ " <td>" + voteRunningRelays + " Running</td>\n"
+ " </tr>\n");
/* Write supported consensus methods. */
if (!voteConsensusMethods.contains(consensusConsensusMethod.
split(" ")[1])) {
consensusMethodsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteConsensusMethods + "</font></td>\n"
+ " </tr>\n");
} else {
consensusMethodsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteConsensusMethods + "</td>\n"
+ " </tr>\n");
}
/* Write recommended versions. */
if (voteClientVersions == null) {
/* Not a versioning authority. */
} else if (!voteClientVersions.equals(consensusClientVersions)) {
versionsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteClientVersions + "</font></td>\n"
+ " </tr>\n");
} else {
versionsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteClientVersions + "</td>\n"
+ " </tr>\n");
}
if (voteServerVersions == null) {
/* Not a versioning authority. */
} else if (!voteServerVersions.equals(consensusServerVersions)) {
versionsResults.append(" <tr>\n"
+ " <td/>\n"
+ " <td><font color=\"red\">"
+ voteServerVersions + "</font></td>\n"
+ " </tr>\n");
} else {
versionsResults.append(" <tr>\n"
+ " <td/>\n"
+ " <td>" + voteServerVersions + "</td>\n"
+ " </tr>\n");
}
/* Write consensus parameters. */
if (voteParams == null) {
/* Authority doesn't set consensus parameters. */
} else if (!voteParams.equals(consensusParams)) {
paramsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteParams + "</font></td>\n"
+ " </tr>\n");
} else {
paramsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteParams + "</td>\n"
+ " </tr>\n");
}
/* Write authority key expiration date. */
if (voteDirKeyExpires != null) {
boolean expiresIn14Days = false;
try {
expiresIn14Days = (System.currentTimeMillis()
+ 14L * 24L * 60L * 60L * 1000L >
dateTimeFormat.parse(voteDirKeyExpires.substring(
"dir-key-expires ".length())).getTime());
} catch (ParseException e) {
/* Can't parse the timestamp? Whatever. */
}
if (expiresIn14Days) {
authorityKeysResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteDirKeyExpires + "</font></td>\n"
+ " </tr>\n");
} else {
authorityKeysResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteDirKeyExpires + "</td>\n"
+ " </tr>\n");
}
}
/* Write results for bandwidth scanner status. */
if (voteContainsBandwidthWeights > 0) {
bandwidthScannersResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteContainsBandwidthWeights
+ " Measured values in w lines<td/>\n"
+ " </tr>\n");
}
}
try {
/* Keep the past two consensus health statuses. */
File file0 = new File("website/consensus-health.html");
File file1 = new File("website/consensus-health-1.html");
File file2 = new File("website/consensus-health-2.html");
if (file2.exists()) {
file2.delete();
}
if (file1.exists()) {
file1.renameTo(file2);
}
if (file0.exists()) {
file0.renameTo(file1);
}
/* Start writing web page. */
BufferedWriter bw = new BufferedWriter(
new FileWriter("website/consensus-health.html"));
bw.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+ "Transitional//EN\">\n"
+ "<html>\n"
+ " <head>\n"
+ " <title>Tor Metrics Portal: Consensus health</title>\n"
+ " <meta http-equiv=Content-Type content=\"text/html; "
+ "charset=iso-8859-1\">\n"
+ " <link href=\"http://www.torproject.org/stylesheet-"
+ "ltr.css\" type=text/css rel=stylesheet>\n"
+ " <link href=\"http://www.torproject.org/favicon.ico\""
+ " type=image/x-icon rel=\"shortcut icon\">\n"
+ " </head>\n"
+ " <body>\n"
+ " <div class=\"center\">\n"
+ " <table class=\"banner\" border=\"0\" "
+ "cellpadding=\"0\" cellspacing=\"0\" summary=\"\">\n"
+ " <tr>\n"
+ " <td class=\"banner-left\"><a href=\"https://"
+ "www.torproject.org/\"><img src=\"http://www.torproject"
+ ".org/images/top-left.png\" alt=\"Click to go to home "
+ "page\" width=\"193\" height=\"79\"></a></td>\n"
+ " <td class=\"banner-middle\">\n"
+ " <a href=\"/\">Home</a>\n"
+ " <a href=\"graphs.html\">Graphs</a>\n"
+ " <a href=\"papers.html\">Papers</a>\n"
+ " <a href=\"data.html\">Data</a>\n"
+ " <a href=\"tools.html\">Tools</a>\n"
+ " <br/>\n"
+ " <font size=\"2\">\n"
+ " <a href=\"ernie-howto.html\">ERNIE Howto</a>\n"
+ " <a href=\"log.html\">Last log</a>\n"
- + " <a href=\"consensus-health.html\">Consensus health</a>\n"
+ + " <a class=\"current\">Consensus health</a>\n"
+ " </font>\n"
+ " </td>\n"
+ " <td class=\"banner-right\"></td>\n"
+ " </tr>\n"
+ " </table>\n"
+ " <div class=\"main-column\">\n"
+ " <h2>Tor Metrics Portal: Consensus Health</h2>\n"
+ " <br/>\n"
+ " <p>This page shows statistics about the current "
+ "consensus and votes to facilitate debugging of the "
+ "directory consensus process.</p>\n");
/* Write valid-after time. */
bw.write(" <br/>\n"
+ " <h3>Valid-after time</h3>\n"
+ " <br/>\n"
+ " <p>Consensus was published ");
boolean consensusIsStale = false;
try {
consensusIsStale = System.currentTimeMillis()
- 3L * 60L * 60L * 1000L >
dateTimeFormat.parse(this.mostRecentValidAfterTime).getTime();
} catch (ParseException e) {
/* Can't parse the timestamp? Whatever. */
}
if (consensusIsStale) {
bw.write("<font color=\"red\">" + this.mostRecentValidAfterTime
+ "</font>");
} else {
bw.write(this.mostRecentValidAfterTime);
}
bw.write(". <i>Note that it takes "
+ "15 to 30 minutes for the metrics portal to learn about "
+ "new consensus and votes and process them.</i></p>\n");
/* Write known flags. */
bw.write(" <br/>\n"
+ " <h3>Known flags</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (knownFlagsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(knownFlagsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusKnownFlags + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write number of relays voted about. */
bw.write(" <br/>\n"
+ " <h3>Number of relays voted about</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"320\">\n"
+ " <col width=\"320\">\n"
+ " </colgroup>\n");
if (numRelaysVotesResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/><td/></tr>\n");
} else {
bw.write(numRelaysVotesResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusTotalRelays + " total</font></td>\n"
+ " <td><font color=\"blue\">"
+ consensusRunningRelays + " Running</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write consensus methods. */
bw.write(" <br/>\n"
+ " <h3>Consensus methods</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (consensusMethodsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(consensusMethodsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusConsensusMethod + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write recommended versions. */
bw.write(" <br/>\n"
+ " <h3>Recommended versions</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (versionsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(versionsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusClientVersions + "</font></td>\n"
+ " </tr>\n");
bw.write(" <td/>\n"
+ " <td><font color=\"blue\">"
+ consensusServerVersions + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write consensus parameters. */
bw.write(" <br/>\n"
+ " <h3>Consensus parameters</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (paramsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(paramsResults.toString());
}
bw.write(" <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusParams + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write authority keys. */
bw.write(" <br/>\n"
+ " <h3>Authority keys</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (authorityKeysResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(authorityKeysResults.toString());
}
bw.write(" </table>\n"
+ " <br/>\n"
+ " <p><i>Note that expiration dates of legacy keys are "
+ "not included in votes and therefore not listed here!</i>"
+ "</p>\n");
/* Write bandwidth scanner status. */
bw.write(" <br/>\n"
+ " <h3>Bandwidth scanner status</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (bandwidthScannersResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(bandwidthScannersResults.toString());
}
bw.write(" </table>\n");
/* Write (huge) table with all flags. */
bw.write(" <br/>\n"
+ " <h3>Relay flags</h3>\n"
+ " <br/>\n"
+ " <p>The semantics of flags written in the table is "
+ "as follows:</p>\n"
+ " <ul>\n"
+ " <li><b>In vote and consensus:</b> Flag in vote "
+ "matches flag in consensus, or relay is not listed in "
+ "consensus (because it doesn't have the Running "
+ "flag)</li>\n"
+ " <li><b><font color=\"red\">Only in "
+ "vote:</font></b> Flag in vote, but missing in the "
+ "consensus, because there was no majority for the flag or "
+ "the flag was invalidated (e.g., Named gets invalidated by "
+ "Unnamed)</li>\n"
+ " <li><b><font color=\"gray\"><s>Only in "
+ "consensus:</s></font></b> Flag in consensus, but missing "
+ "in a vote of a directory authority voting on this "
+ "flag</li>\n"
+ " <li><b><font color=\"blue\">In "
+ "consensus:</font></b> Flag in consensus</li>\n"
+ " </ul>\n"
+ " <br/>\n"
+ " <p>See also the summary below the table.</p>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"120\">\n"
+ " <col width=\"80\">\n");
for (int i = 0; i < allKnownVotes.size(); i++) {
bw.write(" <col width=\""
+ (640 / allKnownVotes.size()) + "\">\n");
}
bw.write(" </colgroup>\n");
int linesWritten = 0;
for (Map.Entry<String, SortedSet<String>> e :
votesAssignedFlags.entrySet()) {
if (linesWritten++ % 10 == 0) {
bw.write(" <tr><td/><td/>\n");
for (String dir : allKnownVotes) {
String shortDirName = dir.length() > 6 ?
dir.substring(0, 5) + "." : dir;
bw.write("<td><br/><b>" + shortDirName + "</b></td>");
}
bw.write("<td><br/><b>consensus</b></td></tr>\n");
}
String relayKey = e.getKey();
SortedSet<String> votes = e.getValue();
String fingerprint = relayKey.split(" ")[0].substring(0, 8);
String nickname = relayKey.split(" ")[1];
bw.write(" <tr>\n"
+ " <td>" + fingerprint + "</td>\n"
+ " <td>" + nickname + "</td>\n");
SortedSet<String> relevantFlags = new TreeSet<String>();
for (String vote : votes) {
String[] parts = vote.split(" ");
for (int j = 2; j < parts.length; j++) {
relevantFlags.add(parts[j]);
}
}
String consensusFlags = null;
if (consensusAssignedFlags.containsKey(relayKey)) {
consensusFlags = consensusAssignedFlags.get(relayKey);
String[] parts = consensusFlags.split(" ");
for (int j = 1; j < parts.length; j++) {
relevantFlags.add(parts[j]);
}
}
for (String dir : allKnownVotes) {
String flags = null;
for (String vote : votes) {
if (vote.startsWith(dir)) {
flags = vote;
break;
}
}
if (flags != null) {
votes.remove(flags);
bw.write(" <td>");
int flagsWritten = 0;
for (String flag : relevantFlags) {
bw.write(flagsWritten++ > 0 ? "<br/>" : "");
SortedMap<String, SortedMap<String, Integer>> sums = null;
if (flags.contains(" " + flag)) {
if (consensusFlags == null ||
consensusFlags.contains(" " + flag)) {
bw.write(flag);
sums = flagsAgree;
} else {
bw.write("<font color=\"red\">" + flag + "</font>");
sums = flagsLost;
}
} else if (consensusFlags != null &&
votesKnownFlags.get(dir).contains(" " + flag) &&
consensusFlags.contains(" " + flag)) {
bw.write("<font color=\"gray\"><s>" + flag
+ "</s></font>");
sums = flagsMissing;
}
if (sums != null) {
SortedMap<String, Integer> sum = null;
if (sums.containsKey(dir)) {
sum = sums.get(dir);
} else {
sum = new TreeMap<String, Integer>();
sums.put(dir, sum);
}
sum.put(flag, sum.containsKey(flag) ?
sum.get(flag) + 1 : 1);
}
}
bw.write("</td>\n");
} else {
bw.write(" <td/>\n");
}
}
if (consensusFlags != null) {
bw.write(" <td>");
int flagsWritten = 0;
for (String flag : relevantFlags) {
bw.write(flagsWritten++ > 0 ? "<br/>" : "");
if (consensusFlags.contains(" " + flag)) {
bw.write("<font color=\"blue\">" + flag + "</font>");
}
}
bw.write("</td>\n");
} else {
bw.write(" <td/>\n");
}
bw.write(" </tr>\n");
}
bw.write(" </table>\n");
/* Write summary of overlap between votes and consensus. */
bw.write(" <br/>\n"
+ " <h3>Overlap between votes and consensus</h3>\n"
+ " <br/>\n"
+ " <p>The semantics of columns is similar to the "
+ "table above:</p>\n"
+ " <ul>\n"
+ " <li><b>In vote and consensus:</b> Flag in vote "
+ "matches flag in consensus, or relay is not listed in "
+ "consensus (because it doesn't have the Running "
+ "flag)</li>\n"
+ " <li><b><font color=\"red\">Only in "
+ "vote:</font></b> Flag in vote, but missing in the "
+ "consensus, because there was no majority for the flag or "
+ "the flag was invalidated (e.g., Named gets invalidated by "
+ "Unnamed)</li>\n"
+ " <li><b><font color=\"gray\"><s>Only in "
+ "consensus:</s></font></b> Flag in consensus, but missing "
+ "in a vote of a directory authority voting on this "
+ "flag</li>\n"
+ " </ul>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"210\">\n"
+ " <col width=\"210\">\n"
+ " <col width=\"210\">\n"
+ " </colgroup>\n");
bw.write(" <tr><td/><td><b>Only in vote</b></td>"
+ "<td><b>In vote and consensus</b></td>"
+ "<td><b>Only in consensus</b></td>\n");
for (String dir : allKnownVotes) {
boolean firstFlagWritten = false;
String[] flags = votesKnownFlags.get(dir).substring(
"known-flags ".length()).split(" ");
for (String flag : flags) {
bw.write(" <tr>\n");
if (firstFlagWritten) {
bw.write(" <td/>\n");
} else {
bw.write(" <td>" + dir + "</td>\n");
firstFlagWritten = true;
}
if (flagsLost.containsKey(dir) &&
flagsLost.get(dir).containsKey(flag)) {
bw.write(" <td><font color=\"red\"> "
+ flagsLost.get(dir).get(flag) + " " + flag
+ "</font></td>\n");
} else {
bw.write(" <td/>\n");
}
if (flagsAgree.containsKey(dir) &&
flagsAgree.get(dir).containsKey(flag)) {
bw.write(" <td>" + flagsAgree.get(dir).get(flag)
+ " " + flag + "</td>\n");
} else {
bw.write(" <td/>\n");
}
if (flagsMissing.containsKey(dir) &&
flagsMissing.get(dir).containsKey(flag)) {
bw.write(" <td><font color=\"gray\"><s>"
+ flagsMissing.get(dir).get(flag) + " " + flag
+ "</s></font></td>\n");
} else {
bw.write(" <td/>\n");
}
bw.write(" </tr>\n");
}
}
bw.write(" </table>\n");
/* Finish writing. */
bw.write(" </div>\n"
+ " </div>\n"
+ " <div class=\"bottom\" id=\"bottom\">\n"
+ " <p>\"Tor\" and the \"Onion Logo\" are <a "
+ "href=\"https://www.torproject.org/trademark-faq.html"
+ ".en\">"
+ "registered trademarks</a> of The Tor Project, "
+ "Inc.</p>\n"
+ " </div>\n"
+ " </body>\n"
+ "</html>");
bw.close();
} catch (IOException e) {
}
}
}
| true | true |
public void writeStatusWebsite() {
/* If we don't have any consensus, we cannot write useful consensus
* health information to the website. Do not overwrite existing page
* with a warning, because we might just not have learned about a new
* consensus in this execution. */
if (this.mostRecentConsensus == null) {
return;
}
/* Prepare parsing dates. */
SimpleDateFormat dateTimeFormat =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
StringBuilder knownFlagsResults = new StringBuilder();
StringBuilder numRelaysVotesResults = new StringBuilder();
StringBuilder consensusMethodsResults = new StringBuilder();
StringBuilder versionsResults = new StringBuilder();
StringBuilder paramsResults = new StringBuilder();
StringBuilder authorityKeysResults = new StringBuilder();
StringBuilder bandwidthScannersResults = new StringBuilder();
SortedSet<String> allKnownFlags = new TreeSet<String>();
SortedSet<String> allKnownVotes = new TreeSet<String>();
SortedMap<String, String> consensusAssignedFlags =
new TreeMap<String, String>();
SortedMap<String, SortedSet<String>> votesAssignedFlags =
new TreeMap<String, SortedSet<String>>();
SortedMap<String, String> votesKnownFlags =
new TreeMap<String, String>();
SortedMap<String, SortedMap<String, Integer>> flagsAgree =
new TreeMap<String, SortedMap<String, Integer>>();
SortedMap<String, SortedMap<String, Integer>> flagsLost =
new TreeMap<String, SortedMap<String, Integer>>();
SortedMap<String, SortedMap<String, Integer>> flagsMissing =
new TreeMap<String, SortedMap<String, Integer>>();
/* Read consensus and parse all information that we want to compare to
* votes. */
String consensusConsensusMethod = null, consensusKnownFlags = null,
consensusClientVersions = null, consensusServerVersions = null,
consensusParams = null, rLineTemp = null;
int consensusTotalRelays = 0, consensusRunningRelays = 0;
try {
BufferedReader br = new BufferedReader(new StringReader(new String(
this.mostRecentConsensus)));
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("consensus-method ")) {
consensusConsensusMethod = line;
} else if (line.startsWith("client-versions ")) {
consensusClientVersions = line;
} else if (line.startsWith("server-versions ")) {
consensusServerVersions = line;
} else if (line.startsWith("known-flags ")) {
consensusKnownFlags = line;
} else if (line.startsWith("params ")) {
consensusParams = line;
} else if (line.startsWith("r ")) {
rLineTemp = line;
} else if (line.startsWith("s ")) {
consensusTotalRelays++;
if (line.contains(" Running")) {
consensusRunningRelays++;
}
consensusAssignedFlags.put(Hex.encodeHexString(
Base64.decodeBase64(rLineTemp.split(" ")[2] + "=")).
toUpperCase() + " " + rLineTemp.split(" ")[1], line);
}
}
br.close();
} catch (IOException e) {
/* There should be no I/O taking place when reading a String. */
}
/* Read votes and parse all information to compare with the
* consensus. */
for (byte[] voteBytes : this.mostRecentVotes.values()) {
String voteConsensusMethods = null, voteKnownFlags = null,
voteClientVersions = null, voteServerVersions = null,
voteParams = null, dirSource = null, voteDirKeyExpires = null;
int voteTotalRelays = 0, voteRunningRelays = 0,
voteContainsBandwidthWeights = 0;
try {
BufferedReader br = new BufferedReader(new StringReader(
new String(voteBytes)));
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("consensus-methods ")) {
voteConsensusMethods = line;
} else if (line.startsWith("client-versions ")) {
voteClientVersions = line;
} else if (line.startsWith("server-versions ")) {
voteServerVersions = line;
} else if (line.startsWith("known-flags ")) {
voteKnownFlags = line;
} else if (line.startsWith("params ")) {
voteParams = line;
} else if (line.startsWith("dir-source ")) {
dirSource = line.split(" ")[1];
allKnownVotes.add(dirSource);
} else if (line.startsWith("dir-key-expires ")) {
voteDirKeyExpires = line;
} else if (line.startsWith("r ")) {
rLineTemp = line;
} else if (line.startsWith("s ")) {
voteTotalRelays++;
if (line.contains(" Running")) {
voteRunningRelays++;
}
String relayKey = Hex.encodeHexString(Base64.decodeBase64(
rLineTemp.split(" ")[2] + "=")).toUpperCase() + " "
+ rLineTemp.split(" ")[1];
SortedSet<String> sLines = null;
if (votesAssignedFlags.containsKey(relayKey)) {
sLines = votesAssignedFlags.get(relayKey);
} else {
sLines = new TreeSet<String>();
votesAssignedFlags.put(relayKey, sLines);
}
sLines.add(dirSource + " " + line);
} else if (line.startsWith("w ")) {
if (line.contains(" Measured")) {
voteContainsBandwidthWeights++;
}
}
}
br.close();
} catch (IOException e) {
/* There should be no I/O taking place when reading a String. */
}
/* Write known flags. */
knownFlagsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteKnownFlags + "</td>\n"
+ " </tr>\n");
votesKnownFlags.put(dirSource, voteKnownFlags);
for (String flag : voteKnownFlags.substring(
"known-flags ".length()).split(" ")) {
allKnownFlags.add(flag);
}
/* Write number of relays voted about. */
numRelaysVotesResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteTotalRelays + " total</td>\n"
+ " <td>" + voteRunningRelays + " Running</td>\n"
+ " </tr>\n");
/* Write supported consensus methods. */
if (!voteConsensusMethods.contains(consensusConsensusMethod.
split(" ")[1])) {
consensusMethodsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteConsensusMethods + "</font></td>\n"
+ " </tr>\n");
} else {
consensusMethodsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteConsensusMethods + "</td>\n"
+ " </tr>\n");
}
/* Write recommended versions. */
if (voteClientVersions == null) {
/* Not a versioning authority. */
} else if (!voteClientVersions.equals(consensusClientVersions)) {
versionsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteClientVersions + "</font></td>\n"
+ " </tr>\n");
} else {
versionsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteClientVersions + "</td>\n"
+ " </tr>\n");
}
if (voteServerVersions == null) {
/* Not a versioning authority. */
} else if (!voteServerVersions.equals(consensusServerVersions)) {
versionsResults.append(" <tr>\n"
+ " <td/>\n"
+ " <td><font color=\"red\">"
+ voteServerVersions + "</font></td>\n"
+ " </tr>\n");
} else {
versionsResults.append(" <tr>\n"
+ " <td/>\n"
+ " <td>" + voteServerVersions + "</td>\n"
+ " </tr>\n");
}
/* Write consensus parameters. */
if (voteParams == null) {
/* Authority doesn't set consensus parameters. */
} else if (!voteParams.equals(consensusParams)) {
paramsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteParams + "</font></td>\n"
+ " </tr>\n");
} else {
paramsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteParams + "</td>\n"
+ " </tr>\n");
}
/* Write authority key expiration date. */
if (voteDirKeyExpires != null) {
boolean expiresIn14Days = false;
try {
expiresIn14Days = (System.currentTimeMillis()
+ 14L * 24L * 60L * 60L * 1000L >
dateTimeFormat.parse(voteDirKeyExpires.substring(
"dir-key-expires ".length())).getTime());
} catch (ParseException e) {
/* Can't parse the timestamp? Whatever. */
}
if (expiresIn14Days) {
authorityKeysResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteDirKeyExpires + "</font></td>\n"
+ " </tr>\n");
} else {
authorityKeysResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteDirKeyExpires + "</td>\n"
+ " </tr>\n");
}
}
/* Write results for bandwidth scanner status. */
if (voteContainsBandwidthWeights > 0) {
bandwidthScannersResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteContainsBandwidthWeights
+ " Measured values in w lines<td/>\n"
+ " </tr>\n");
}
}
try {
/* Keep the past two consensus health statuses. */
File file0 = new File("website/consensus-health.html");
File file1 = new File("website/consensus-health-1.html");
File file2 = new File("website/consensus-health-2.html");
if (file2.exists()) {
file2.delete();
}
if (file1.exists()) {
file1.renameTo(file2);
}
if (file0.exists()) {
file0.renameTo(file1);
}
/* Start writing web page. */
BufferedWriter bw = new BufferedWriter(
new FileWriter("website/consensus-health.html"));
bw.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+ "Transitional//EN\">\n"
+ "<html>\n"
+ " <head>\n"
+ " <title>Tor Metrics Portal: Consensus health</title>\n"
+ " <meta http-equiv=Content-Type content=\"text/html; "
+ "charset=iso-8859-1\">\n"
+ " <link href=\"http://www.torproject.org/stylesheet-"
+ "ltr.css\" type=text/css rel=stylesheet>\n"
+ " <link href=\"http://www.torproject.org/favicon.ico\""
+ " type=image/x-icon rel=\"shortcut icon\">\n"
+ " </head>\n"
+ " <body>\n"
+ " <div class=\"center\">\n"
+ " <table class=\"banner\" border=\"0\" "
+ "cellpadding=\"0\" cellspacing=\"0\" summary=\"\">\n"
+ " <tr>\n"
+ " <td class=\"banner-left\"><a href=\"https://"
+ "www.torproject.org/\"><img src=\"http://www.torproject"
+ ".org/images/top-left.png\" alt=\"Click to go to home "
+ "page\" width=\"193\" height=\"79\"></a></td>\n"
+ " <td class=\"banner-middle\">\n"
+ " <a href=\"/\">Home</a>\n"
+ " <a href=\"graphs.html\">Graphs</a>\n"
+ " <a href=\"papers.html\">Papers</a>\n"
+ " <a href=\"data.html\">Data</a>\n"
+ " <a href=\"tools.html\">Tools</a>\n"
+ " <br/>\n"
+ " <font size=\"2\">\n"
+ " <a href=\"ernie-howto.html\">ERNIE Howto</a>\n"
+ " <a href=\"log.html\">Last log</a>\n"
+ " <a href=\"consensus-health.html\">Consensus health</a>\n"
+ " </font>\n"
+ " </td>\n"
+ " <td class=\"banner-right\"></td>\n"
+ " </tr>\n"
+ " </table>\n"
+ " <div class=\"main-column\">\n"
+ " <h2>Tor Metrics Portal: Consensus Health</h2>\n"
+ " <br/>\n"
+ " <p>This page shows statistics about the current "
+ "consensus and votes to facilitate debugging of the "
+ "directory consensus process.</p>\n");
/* Write valid-after time. */
bw.write(" <br/>\n"
+ " <h3>Valid-after time</h3>\n"
+ " <br/>\n"
+ " <p>Consensus was published ");
boolean consensusIsStale = false;
try {
consensusIsStale = System.currentTimeMillis()
- 3L * 60L * 60L * 1000L >
dateTimeFormat.parse(this.mostRecentValidAfterTime).getTime();
} catch (ParseException e) {
/* Can't parse the timestamp? Whatever. */
}
if (consensusIsStale) {
bw.write("<font color=\"red\">" + this.mostRecentValidAfterTime
+ "</font>");
} else {
bw.write(this.mostRecentValidAfterTime);
}
bw.write(". <i>Note that it takes "
+ "15 to 30 minutes for the metrics portal to learn about "
+ "new consensus and votes and process them.</i></p>\n");
/* Write known flags. */
bw.write(" <br/>\n"
+ " <h3>Known flags</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (knownFlagsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(knownFlagsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusKnownFlags + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write number of relays voted about. */
bw.write(" <br/>\n"
+ " <h3>Number of relays voted about</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"320\">\n"
+ " <col width=\"320\">\n"
+ " </colgroup>\n");
if (numRelaysVotesResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/><td/></tr>\n");
} else {
bw.write(numRelaysVotesResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusTotalRelays + " total</font></td>\n"
+ " <td><font color=\"blue\">"
+ consensusRunningRelays + " Running</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write consensus methods. */
bw.write(" <br/>\n"
+ " <h3>Consensus methods</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (consensusMethodsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(consensusMethodsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusConsensusMethod + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write recommended versions. */
bw.write(" <br/>\n"
+ " <h3>Recommended versions</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (versionsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(versionsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusClientVersions + "</font></td>\n"
+ " </tr>\n");
bw.write(" <td/>\n"
+ " <td><font color=\"blue\">"
+ consensusServerVersions + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write consensus parameters. */
bw.write(" <br/>\n"
+ " <h3>Consensus parameters</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (paramsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(paramsResults.toString());
}
bw.write(" <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusParams + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write authority keys. */
bw.write(" <br/>\n"
+ " <h3>Authority keys</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (authorityKeysResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(authorityKeysResults.toString());
}
bw.write(" </table>\n"
+ " <br/>\n"
+ " <p><i>Note that expiration dates of legacy keys are "
+ "not included in votes and therefore not listed here!</i>"
+ "</p>\n");
/* Write bandwidth scanner status. */
bw.write(" <br/>\n"
+ " <h3>Bandwidth scanner status</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (bandwidthScannersResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(bandwidthScannersResults.toString());
}
bw.write(" </table>\n");
/* Write (huge) table with all flags. */
bw.write(" <br/>\n"
+ " <h3>Relay flags</h3>\n"
+ " <br/>\n"
+ " <p>The semantics of flags written in the table is "
+ "as follows:</p>\n"
+ " <ul>\n"
+ " <li><b>In vote and consensus:</b> Flag in vote "
+ "matches flag in consensus, or relay is not listed in "
+ "consensus (because it doesn't have the Running "
+ "flag)</li>\n"
+ " <li><b><font color=\"red\">Only in "
+ "vote:</font></b> Flag in vote, but missing in the "
+ "consensus, because there was no majority for the flag or "
+ "the flag was invalidated (e.g., Named gets invalidated by "
+ "Unnamed)</li>\n"
+ " <li><b><font color=\"gray\"><s>Only in "
+ "consensus:</s></font></b> Flag in consensus, but missing "
+ "in a vote of a directory authority voting on this "
+ "flag</li>\n"
+ " <li><b><font color=\"blue\">In "
+ "consensus:</font></b> Flag in consensus</li>\n"
+ " </ul>\n"
+ " <br/>\n"
+ " <p>See also the summary below the table.</p>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"120\">\n"
+ " <col width=\"80\">\n");
for (int i = 0; i < allKnownVotes.size(); i++) {
bw.write(" <col width=\""
+ (640 / allKnownVotes.size()) + "\">\n");
}
bw.write(" </colgroup>\n");
int linesWritten = 0;
for (Map.Entry<String, SortedSet<String>> e :
votesAssignedFlags.entrySet()) {
if (linesWritten++ % 10 == 0) {
bw.write(" <tr><td/><td/>\n");
for (String dir : allKnownVotes) {
String shortDirName = dir.length() > 6 ?
dir.substring(0, 5) + "." : dir;
bw.write("<td><br/><b>" + shortDirName + "</b></td>");
}
bw.write("<td><br/><b>consensus</b></td></tr>\n");
}
String relayKey = e.getKey();
SortedSet<String> votes = e.getValue();
String fingerprint = relayKey.split(" ")[0].substring(0, 8);
String nickname = relayKey.split(" ")[1];
bw.write(" <tr>\n"
+ " <td>" + fingerprint + "</td>\n"
+ " <td>" + nickname + "</td>\n");
SortedSet<String> relevantFlags = new TreeSet<String>();
for (String vote : votes) {
String[] parts = vote.split(" ");
for (int j = 2; j < parts.length; j++) {
relevantFlags.add(parts[j]);
}
}
String consensusFlags = null;
if (consensusAssignedFlags.containsKey(relayKey)) {
consensusFlags = consensusAssignedFlags.get(relayKey);
String[] parts = consensusFlags.split(" ");
for (int j = 1; j < parts.length; j++) {
relevantFlags.add(parts[j]);
}
}
for (String dir : allKnownVotes) {
String flags = null;
for (String vote : votes) {
if (vote.startsWith(dir)) {
flags = vote;
break;
}
}
if (flags != null) {
votes.remove(flags);
bw.write(" <td>");
int flagsWritten = 0;
for (String flag : relevantFlags) {
bw.write(flagsWritten++ > 0 ? "<br/>" : "");
SortedMap<String, SortedMap<String, Integer>> sums = null;
if (flags.contains(" " + flag)) {
if (consensusFlags == null ||
consensusFlags.contains(" " + flag)) {
bw.write(flag);
sums = flagsAgree;
} else {
bw.write("<font color=\"red\">" + flag + "</font>");
sums = flagsLost;
}
} else if (consensusFlags != null &&
votesKnownFlags.get(dir).contains(" " + flag) &&
consensusFlags.contains(" " + flag)) {
bw.write("<font color=\"gray\"><s>" + flag
+ "</s></font>");
sums = flagsMissing;
}
if (sums != null) {
SortedMap<String, Integer> sum = null;
if (sums.containsKey(dir)) {
sum = sums.get(dir);
} else {
sum = new TreeMap<String, Integer>();
sums.put(dir, sum);
}
sum.put(flag, sum.containsKey(flag) ?
sum.get(flag) + 1 : 1);
}
}
bw.write("</td>\n");
} else {
bw.write(" <td/>\n");
}
}
if (consensusFlags != null) {
bw.write(" <td>");
int flagsWritten = 0;
for (String flag : relevantFlags) {
bw.write(flagsWritten++ > 0 ? "<br/>" : "");
if (consensusFlags.contains(" " + flag)) {
bw.write("<font color=\"blue\">" + flag + "</font>");
}
}
bw.write("</td>\n");
} else {
bw.write(" <td/>\n");
}
bw.write(" </tr>\n");
}
bw.write(" </table>\n");
/* Write summary of overlap between votes and consensus. */
bw.write(" <br/>\n"
+ " <h3>Overlap between votes and consensus</h3>\n"
+ " <br/>\n"
+ " <p>The semantics of columns is similar to the "
+ "table above:</p>\n"
+ " <ul>\n"
+ " <li><b>In vote and consensus:</b> Flag in vote "
+ "matches flag in consensus, or relay is not listed in "
+ "consensus (because it doesn't have the Running "
+ "flag)</li>\n"
+ " <li><b><font color=\"red\">Only in "
+ "vote:</font></b> Flag in vote, but missing in the "
+ "consensus, because there was no majority for the flag or "
+ "the flag was invalidated (e.g., Named gets invalidated by "
+ "Unnamed)</li>\n"
+ " <li><b><font color=\"gray\"><s>Only in "
+ "consensus:</s></font></b> Flag in consensus, but missing "
+ "in a vote of a directory authority voting on this "
+ "flag</li>\n"
+ " </ul>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"210\">\n"
+ " <col width=\"210\">\n"
+ " <col width=\"210\">\n"
+ " </colgroup>\n");
bw.write(" <tr><td/><td><b>Only in vote</b></td>"
+ "<td><b>In vote and consensus</b></td>"
+ "<td><b>Only in consensus</b></td>\n");
for (String dir : allKnownVotes) {
boolean firstFlagWritten = false;
String[] flags = votesKnownFlags.get(dir).substring(
"known-flags ".length()).split(" ");
for (String flag : flags) {
bw.write(" <tr>\n");
if (firstFlagWritten) {
bw.write(" <td/>\n");
} else {
bw.write(" <td>" + dir + "</td>\n");
firstFlagWritten = true;
}
if (flagsLost.containsKey(dir) &&
flagsLost.get(dir).containsKey(flag)) {
bw.write(" <td><font color=\"red\"> "
+ flagsLost.get(dir).get(flag) + " " + flag
+ "</font></td>\n");
} else {
bw.write(" <td/>\n");
}
if (flagsAgree.containsKey(dir) &&
flagsAgree.get(dir).containsKey(flag)) {
bw.write(" <td>" + flagsAgree.get(dir).get(flag)
+ " " + flag + "</td>\n");
} else {
bw.write(" <td/>\n");
}
if (flagsMissing.containsKey(dir) &&
flagsMissing.get(dir).containsKey(flag)) {
bw.write(" <td><font color=\"gray\"><s>"
+ flagsMissing.get(dir).get(flag) + " " + flag
+ "</s></font></td>\n");
} else {
bw.write(" <td/>\n");
}
bw.write(" </tr>\n");
}
}
bw.write(" </table>\n");
/* Finish writing. */
bw.write(" </div>\n"
+ " </div>\n"
+ " <div class=\"bottom\" id=\"bottom\">\n"
+ " <p>\"Tor\" and the \"Onion Logo\" are <a "
+ "href=\"https://www.torproject.org/trademark-faq.html"
+ ".en\">"
+ "registered trademarks</a> of The Tor Project, "
+ "Inc.</p>\n"
+ " </div>\n"
+ " </body>\n"
+ "</html>");
bw.close();
} catch (IOException e) {
}
}
|
public void writeStatusWebsite() {
/* If we don't have any consensus, we cannot write useful consensus
* health information to the website. Do not overwrite existing page
* with a warning, because we might just not have learned about a new
* consensus in this execution. */
if (this.mostRecentConsensus == null) {
return;
}
/* Prepare parsing dates. */
SimpleDateFormat dateTimeFormat =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
StringBuilder knownFlagsResults = new StringBuilder();
StringBuilder numRelaysVotesResults = new StringBuilder();
StringBuilder consensusMethodsResults = new StringBuilder();
StringBuilder versionsResults = new StringBuilder();
StringBuilder paramsResults = new StringBuilder();
StringBuilder authorityKeysResults = new StringBuilder();
StringBuilder bandwidthScannersResults = new StringBuilder();
SortedSet<String> allKnownFlags = new TreeSet<String>();
SortedSet<String> allKnownVotes = new TreeSet<String>();
SortedMap<String, String> consensusAssignedFlags =
new TreeMap<String, String>();
SortedMap<String, SortedSet<String>> votesAssignedFlags =
new TreeMap<String, SortedSet<String>>();
SortedMap<String, String> votesKnownFlags =
new TreeMap<String, String>();
SortedMap<String, SortedMap<String, Integer>> flagsAgree =
new TreeMap<String, SortedMap<String, Integer>>();
SortedMap<String, SortedMap<String, Integer>> flagsLost =
new TreeMap<String, SortedMap<String, Integer>>();
SortedMap<String, SortedMap<String, Integer>> flagsMissing =
new TreeMap<String, SortedMap<String, Integer>>();
/* Read consensus and parse all information that we want to compare to
* votes. */
String consensusConsensusMethod = null, consensusKnownFlags = null,
consensusClientVersions = null, consensusServerVersions = null,
consensusParams = null, rLineTemp = null;
int consensusTotalRelays = 0, consensusRunningRelays = 0;
try {
BufferedReader br = new BufferedReader(new StringReader(new String(
this.mostRecentConsensus)));
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("consensus-method ")) {
consensusConsensusMethod = line;
} else if (line.startsWith("client-versions ")) {
consensusClientVersions = line;
} else if (line.startsWith("server-versions ")) {
consensusServerVersions = line;
} else if (line.startsWith("known-flags ")) {
consensusKnownFlags = line;
} else if (line.startsWith("params ")) {
consensusParams = line;
} else if (line.startsWith("r ")) {
rLineTemp = line;
} else if (line.startsWith("s ")) {
consensusTotalRelays++;
if (line.contains(" Running")) {
consensusRunningRelays++;
}
consensusAssignedFlags.put(Hex.encodeHexString(
Base64.decodeBase64(rLineTemp.split(" ")[2] + "=")).
toUpperCase() + " " + rLineTemp.split(" ")[1], line);
}
}
br.close();
} catch (IOException e) {
/* There should be no I/O taking place when reading a String. */
}
/* Read votes and parse all information to compare with the
* consensus. */
for (byte[] voteBytes : this.mostRecentVotes.values()) {
String voteConsensusMethods = null, voteKnownFlags = null,
voteClientVersions = null, voteServerVersions = null,
voteParams = null, dirSource = null, voteDirKeyExpires = null;
int voteTotalRelays = 0, voteRunningRelays = 0,
voteContainsBandwidthWeights = 0;
try {
BufferedReader br = new BufferedReader(new StringReader(
new String(voteBytes)));
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("consensus-methods ")) {
voteConsensusMethods = line;
} else if (line.startsWith("client-versions ")) {
voteClientVersions = line;
} else if (line.startsWith("server-versions ")) {
voteServerVersions = line;
} else if (line.startsWith("known-flags ")) {
voteKnownFlags = line;
} else if (line.startsWith("params ")) {
voteParams = line;
} else if (line.startsWith("dir-source ")) {
dirSource = line.split(" ")[1];
allKnownVotes.add(dirSource);
} else if (line.startsWith("dir-key-expires ")) {
voteDirKeyExpires = line;
} else if (line.startsWith("r ")) {
rLineTemp = line;
} else if (line.startsWith("s ")) {
voteTotalRelays++;
if (line.contains(" Running")) {
voteRunningRelays++;
}
String relayKey = Hex.encodeHexString(Base64.decodeBase64(
rLineTemp.split(" ")[2] + "=")).toUpperCase() + " "
+ rLineTemp.split(" ")[1];
SortedSet<String> sLines = null;
if (votesAssignedFlags.containsKey(relayKey)) {
sLines = votesAssignedFlags.get(relayKey);
} else {
sLines = new TreeSet<String>();
votesAssignedFlags.put(relayKey, sLines);
}
sLines.add(dirSource + " " + line);
} else if (line.startsWith("w ")) {
if (line.contains(" Measured")) {
voteContainsBandwidthWeights++;
}
}
}
br.close();
} catch (IOException e) {
/* There should be no I/O taking place when reading a String. */
}
/* Write known flags. */
knownFlagsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteKnownFlags + "</td>\n"
+ " </tr>\n");
votesKnownFlags.put(dirSource, voteKnownFlags);
for (String flag : voteKnownFlags.substring(
"known-flags ".length()).split(" ")) {
allKnownFlags.add(flag);
}
/* Write number of relays voted about. */
numRelaysVotesResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteTotalRelays + " total</td>\n"
+ " <td>" + voteRunningRelays + " Running</td>\n"
+ " </tr>\n");
/* Write supported consensus methods. */
if (!voteConsensusMethods.contains(consensusConsensusMethod.
split(" ")[1])) {
consensusMethodsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteConsensusMethods + "</font></td>\n"
+ " </tr>\n");
} else {
consensusMethodsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteConsensusMethods + "</td>\n"
+ " </tr>\n");
}
/* Write recommended versions. */
if (voteClientVersions == null) {
/* Not a versioning authority. */
} else if (!voteClientVersions.equals(consensusClientVersions)) {
versionsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteClientVersions + "</font></td>\n"
+ " </tr>\n");
} else {
versionsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteClientVersions + "</td>\n"
+ " </tr>\n");
}
if (voteServerVersions == null) {
/* Not a versioning authority. */
} else if (!voteServerVersions.equals(consensusServerVersions)) {
versionsResults.append(" <tr>\n"
+ " <td/>\n"
+ " <td><font color=\"red\">"
+ voteServerVersions + "</font></td>\n"
+ " </tr>\n");
} else {
versionsResults.append(" <tr>\n"
+ " <td/>\n"
+ " <td>" + voteServerVersions + "</td>\n"
+ " </tr>\n");
}
/* Write consensus parameters. */
if (voteParams == null) {
/* Authority doesn't set consensus parameters. */
} else if (!voteParams.equals(consensusParams)) {
paramsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteParams + "</font></td>\n"
+ " </tr>\n");
} else {
paramsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteParams + "</td>\n"
+ " </tr>\n");
}
/* Write authority key expiration date. */
if (voteDirKeyExpires != null) {
boolean expiresIn14Days = false;
try {
expiresIn14Days = (System.currentTimeMillis()
+ 14L * 24L * 60L * 60L * 1000L >
dateTimeFormat.parse(voteDirKeyExpires.substring(
"dir-key-expires ".length())).getTime());
} catch (ParseException e) {
/* Can't parse the timestamp? Whatever. */
}
if (expiresIn14Days) {
authorityKeysResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteDirKeyExpires + "</font></td>\n"
+ " </tr>\n");
} else {
authorityKeysResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteDirKeyExpires + "</td>\n"
+ " </tr>\n");
}
}
/* Write results for bandwidth scanner status. */
if (voteContainsBandwidthWeights > 0) {
bandwidthScannersResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteContainsBandwidthWeights
+ " Measured values in w lines<td/>\n"
+ " </tr>\n");
}
}
try {
/* Keep the past two consensus health statuses. */
File file0 = new File("website/consensus-health.html");
File file1 = new File("website/consensus-health-1.html");
File file2 = new File("website/consensus-health-2.html");
if (file2.exists()) {
file2.delete();
}
if (file1.exists()) {
file1.renameTo(file2);
}
if (file0.exists()) {
file0.renameTo(file1);
}
/* Start writing web page. */
BufferedWriter bw = new BufferedWriter(
new FileWriter("website/consensus-health.html"));
bw.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+ "Transitional//EN\">\n"
+ "<html>\n"
+ " <head>\n"
+ " <title>Tor Metrics Portal: Consensus health</title>\n"
+ " <meta http-equiv=Content-Type content=\"text/html; "
+ "charset=iso-8859-1\">\n"
+ " <link href=\"http://www.torproject.org/stylesheet-"
+ "ltr.css\" type=text/css rel=stylesheet>\n"
+ " <link href=\"http://www.torproject.org/favicon.ico\""
+ " type=image/x-icon rel=\"shortcut icon\">\n"
+ " </head>\n"
+ " <body>\n"
+ " <div class=\"center\">\n"
+ " <table class=\"banner\" border=\"0\" "
+ "cellpadding=\"0\" cellspacing=\"0\" summary=\"\">\n"
+ " <tr>\n"
+ " <td class=\"banner-left\"><a href=\"https://"
+ "www.torproject.org/\"><img src=\"http://www.torproject"
+ ".org/images/top-left.png\" alt=\"Click to go to home "
+ "page\" width=\"193\" height=\"79\"></a></td>\n"
+ " <td class=\"banner-middle\">\n"
+ " <a href=\"/\">Home</a>\n"
+ " <a href=\"graphs.html\">Graphs</a>\n"
+ " <a href=\"papers.html\">Papers</a>\n"
+ " <a href=\"data.html\">Data</a>\n"
+ " <a href=\"tools.html\">Tools</a>\n"
+ " <br/>\n"
+ " <font size=\"2\">\n"
+ " <a href=\"ernie-howto.html\">ERNIE Howto</a>\n"
+ " <a href=\"log.html\">Last log</a>\n"
+ " <a class=\"current\">Consensus health</a>\n"
+ " </font>\n"
+ " </td>\n"
+ " <td class=\"banner-right\"></td>\n"
+ " </tr>\n"
+ " </table>\n"
+ " <div class=\"main-column\">\n"
+ " <h2>Tor Metrics Portal: Consensus Health</h2>\n"
+ " <br/>\n"
+ " <p>This page shows statistics about the current "
+ "consensus and votes to facilitate debugging of the "
+ "directory consensus process.</p>\n");
/* Write valid-after time. */
bw.write(" <br/>\n"
+ " <h3>Valid-after time</h3>\n"
+ " <br/>\n"
+ " <p>Consensus was published ");
boolean consensusIsStale = false;
try {
consensusIsStale = System.currentTimeMillis()
- 3L * 60L * 60L * 1000L >
dateTimeFormat.parse(this.mostRecentValidAfterTime).getTime();
} catch (ParseException e) {
/* Can't parse the timestamp? Whatever. */
}
if (consensusIsStale) {
bw.write("<font color=\"red\">" + this.mostRecentValidAfterTime
+ "</font>");
} else {
bw.write(this.mostRecentValidAfterTime);
}
bw.write(". <i>Note that it takes "
+ "15 to 30 minutes for the metrics portal to learn about "
+ "new consensus and votes and process them.</i></p>\n");
/* Write known flags. */
bw.write(" <br/>\n"
+ " <h3>Known flags</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (knownFlagsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(knownFlagsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusKnownFlags + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write number of relays voted about. */
bw.write(" <br/>\n"
+ " <h3>Number of relays voted about</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"320\">\n"
+ " <col width=\"320\">\n"
+ " </colgroup>\n");
if (numRelaysVotesResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/><td/></tr>\n");
} else {
bw.write(numRelaysVotesResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusTotalRelays + " total</font></td>\n"
+ " <td><font color=\"blue\">"
+ consensusRunningRelays + " Running</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write consensus methods. */
bw.write(" <br/>\n"
+ " <h3>Consensus methods</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (consensusMethodsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(consensusMethodsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusConsensusMethod + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write recommended versions. */
bw.write(" <br/>\n"
+ " <h3>Recommended versions</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (versionsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(versionsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusClientVersions + "</font></td>\n"
+ " </tr>\n");
bw.write(" <td/>\n"
+ " <td><font color=\"blue\">"
+ consensusServerVersions + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write consensus parameters. */
bw.write(" <br/>\n"
+ " <h3>Consensus parameters</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (paramsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(paramsResults.toString());
}
bw.write(" <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusParams + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write authority keys. */
bw.write(" <br/>\n"
+ " <h3>Authority keys</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (authorityKeysResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(authorityKeysResults.toString());
}
bw.write(" </table>\n"
+ " <br/>\n"
+ " <p><i>Note that expiration dates of legacy keys are "
+ "not included in votes and therefore not listed here!</i>"
+ "</p>\n");
/* Write bandwidth scanner status. */
bw.write(" <br/>\n"
+ " <h3>Bandwidth scanner status</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (bandwidthScannersResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(bandwidthScannersResults.toString());
}
bw.write(" </table>\n");
/* Write (huge) table with all flags. */
bw.write(" <br/>\n"
+ " <h3>Relay flags</h3>\n"
+ " <br/>\n"
+ " <p>The semantics of flags written in the table is "
+ "as follows:</p>\n"
+ " <ul>\n"
+ " <li><b>In vote and consensus:</b> Flag in vote "
+ "matches flag in consensus, or relay is not listed in "
+ "consensus (because it doesn't have the Running "
+ "flag)</li>\n"
+ " <li><b><font color=\"red\">Only in "
+ "vote:</font></b> Flag in vote, but missing in the "
+ "consensus, because there was no majority for the flag or "
+ "the flag was invalidated (e.g., Named gets invalidated by "
+ "Unnamed)</li>\n"
+ " <li><b><font color=\"gray\"><s>Only in "
+ "consensus:</s></font></b> Flag in consensus, but missing "
+ "in a vote of a directory authority voting on this "
+ "flag</li>\n"
+ " <li><b><font color=\"blue\">In "
+ "consensus:</font></b> Flag in consensus</li>\n"
+ " </ul>\n"
+ " <br/>\n"
+ " <p>See also the summary below the table.</p>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"120\">\n"
+ " <col width=\"80\">\n");
for (int i = 0; i < allKnownVotes.size(); i++) {
bw.write(" <col width=\""
+ (640 / allKnownVotes.size()) + "\">\n");
}
bw.write(" </colgroup>\n");
int linesWritten = 0;
for (Map.Entry<String, SortedSet<String>> e :
votesAssignedFlags.entrySet()) {
if (linesWritten++ % 10 == 0) {
bw.write(" <tr><td/><td/>\n");
for (String dir : allKnownVotes) {
String shortDirName = dir.length() > 6 ?
dir.substring(0, 5) + "." : dir;
bw.write("<td><br/><b>" + shortDirName + "</b></td>");
}
bw.write("<td><br/><b>consensus</b></td></tr>\n");
}
String relayKey = e.getKey();
SortedSet<String> votes = e.getValue();
String fingerprint = relayKey.split(" ")[0].substring(0, 8);
String nickname = relayKey.split(" ")[1];
bw.write(" <tr>\n"
+ " <td>" + fingerprint + "</td>\n"
+ " <td>" + nickname + "</td>\n");
SortedSet<String> relevantFlags = new TreeSet<String>();
for (String vote : votes) {
String[] parts = vote.split(" ");
for (int j = 2; j < parts.length; j++) {
relevantFlags.add(parts[j]);
}
}
String consensusFlags = null;
if (consensusAssignedFlags.containsKey(relayKey)) {
consensusFlags = consensusAssignedFlags.get(relayKey);
String[] parts = consensusFlags.split(" ");
for (int j = 1; j < parts.length; j++) {
relevantFlags.add(parts[j]);
}
}
for (String dir : allKnownVotes) {
String flags = null;
for (String vote : votes) {
if (vote.startsWith(dir)) {
flags = vote;
break;
}
}
if (flags != null) {
votes.remove(flags);
bw.write(" <td>");
int flagsWritten = 0;
for (String flag : relevantFlags) {
bw.write(flagsWritten++ > 0 ? "<br/>" : "");
SortedMap<String, SortedMap<String, Integer>> sums = null;
if (flags.contains(" " + flag)) {
if (consensusFlags == null ||
consensusFlags.contains(" " + flag)) {
bw.write(flag);
sums = flagsAgree;
} else {
bw.write("<font color=\"red\">" + flag + "</font>");
sums = flagsLost;
}
} else if (consensusFlags != null &&
votesKnownFlags.get(dir).contains(" " + flag) &&
consensusFlags.contains(" " + flag)) {
bw.write("<font color=\"gray\"><s>" + flag
+ "</s></font>");
sums = flagsMissing;
}
if (sums != null) {
SortedMap<String, Integer> sum = null;
if (sums.containsKey(dir)) {
sum = sums.get(dir);
} else {
sum = new TreeMap<String, Integer>();
sums.put(dir, sum);
}
sum.put(flag, sum.containsKey(flag) ?
sum.get(flag) + 1 : 1);
}
}
bw.write("</td>\n");
} else {
bw.write(" <td/>\n");
}
}
if (consensusFlags != null) {
bw.write(" <td>");
int flagsWritten = 0;
for (String flag : relevantFlags) {
bw.write(flagsWritten++ > 0 ? "<br/>" : "");
if (consensusFlags.contains(" " + flag)) {
bw.write("<font color=\"blue\">" + flag + "</font>");
}
}
bw.write("</td>\n");
} else {
bw.write(" <td/>\n");
}
bw.write(" </tr>\n");
}
bw.write(" </table>\n");
/* Write summary of overlap between votes and consensus. */
bw.write(" <br/>\n"
+ " <h3>Overlap between votes and consensus</h3>\n"
+ " <br/>\n"
+ " <p>The semantics of columns is similar to the "
+ "table above:</p>\n"
+ " <ul>\n"
+ " <li><b>In vote and consensus:</b> Flag in vote "
+ "matches flag in consensus, or relay is not listed in "
+ "consensus (because it doesn't have the Running "
+ "flag)</li>\n"
+ " <li><b><font color=\"red\">Only in "
+ "vote:</font></b> Flag in vote, but missing in the "
+ "consensus, because there was no majority for the flag or "
+ "the flag was invalidated (e.g., Named gets invalidated by "
+ "Unnamed)</li>\n"
+ " <li><b><font color=\"gray\"><s>Only in "
+ "consensus:</s></font></b> Flag in consensus, but missing "
+ "in a vote of a directory authority voting on this "
+ "flag</li>\n"
+ " </ul>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"210\">\n"
+ " <col width=\"210\">\n"
+ " <col width=\"210\">\n"
+ " </colgroup>\n");
bw.write(" <tr><td/><td><b>Only in vote</b></td>"
+ "<td><b>In vote and consensus</b></td>"
+ "<td><b>Only in consensus</b></td>\n");
for (String dir : allKnownVotes) {
boolean firstFlagWritten = false;
String[] flags = votesKnownFlags.get(dir).substring(
"known-flags ".length()).split(" ");
for (String flag : flags) {
bw.write(" <tr>\n");
if (firstFlagWritten) {
bw.write(" <td/>\n");
} else {
bw.write(" <td>" + dir + "</td>\n");
firstFlagWritten = true;
}
if (flagsLost.containsKey(dir) &&
flagsLost.get(dir).containsKey(flag)) {
bw.write(" <td><font color=\"red\"> "
+ flagsLost.get(dir).get(flag) + " " + flag
+ "</font></td>\n");
} else {
bw.write(" <td/>\n");
}
if (flagsAgree.containsKey(dir) &&
flagsAgree.get(dir).containsKey(flag)) {
bw.write(" <td>" + flagsAgree.get(dir).get(flag)
+ " " + flag + "</td>\n");
} else {
bw.write(" <td/>\n");
}
if (flagsMissing.containsKey(dir) &&
flagsMissing.get(dir).containsKey(flag)) {
bw.write(" <td><font color=\"gray\"><s>"
+ flagsMissing.get(dir).get(flag) + " " + flag
+ "</s></font></td>\n");
} else {
bw.write(" <td/>\n");
}
bw.write(" </tr>\n");
}
}
bw.write(" </table>\n");
/* Finish writing. */
bw.write(" </div>\n"
+ " </div>\n"
+ " <div class=\"bottom\" id=\"bottom\">\n"
+ " <p>\"Tor\" and the \"Onion Logo\" are <a "
+ "href=\"https://www.torproject.org/trademark-faq.html"
+ ".en\">"
+ "registered trademarks</a> of The Tor Project, "
+ "Inc.</p>\n"
+ " </div>\n"
+ " </body>\n"
+ "</html>");
bw.close();
} catch (IOException e) {
}
}
|
diff --git a/iControlU/src/me/firebreath15/icontrolu/iControlU.java b/iControlU/src/me/firebreath15/icontrolu/iControlU.java
index d2b29ef..4cf8871 100644
--- a/iControlU/src/me/firebreath15/icontrolu/iControlU.java
+++ b/iControlU/src/me/firebreath15/icontrolu/iControlU.java
@@ -1,152 +1,152 @@
/*
iControlU - By FireBreath15
This plugin allows server operators to control other players. Issue one command and anything the operator does, the
controlled player does. Chat, walking, and more features to come. When an OP chats, and they are controlling someone,
their message isn't sent. Instead the controled player says the message. Also, controlled players cannot move freely.
The OP controls that too. Each step is mimicked exactly by the controlled player. When the OP is finished, another
command stops the process and the controlled player can chat and move freely again.
Idea by me ^_^ after watching Doctor Who, I got inspired :p
controllers.<name>.person = the name of the player being controlled
controllers.<name>.controlling = exists if the player is controlling someone.
<player name> = exists if the player is being controlled.
<player name>.who = the name of the OP who controls this player
*/
package me.firebreath15.icontrolu;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitTask;
public class iControlU extends JavaPlugin{
INVAPI api;
public void onEnable(){
this.getConfig().set("controllers", null); //no ones controlled upon startup!
this.getConfig().set("controlled", null); //no ones controlled upon startup!
this.saveConfig();
this.getServer().getPluginManager().registerEvents(new onMove(this), this);
this.getServer().getPluginManager().registerEvents(new onChat(this), this);
this.getServer().getPluginManager().registerEvents(new onLogout(this), this);
this.getServer().getPluginManager().registerEvents(new onHurt(this), this);
this.getServer().getPluginManager().registerEvents(new onInteract(this), this);
api=new INVAPI();
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String args[]){
if(cmd.getName().equalsIgnoreCase("icu")){
if(sender instanceof Player){
if(args.length == 0 || args.length > 2){
//show help menu. they got their arguments wrong!
- sender.sendMessage(ChatColor.YELLOW+"==========[ iControlU Help v1.5.6]==========");
+ sender.sendMessage(ChatColor.YELLOW+"==========[ iControlU Help v1.5.7]==========");
sender.sendMessage(ChatColor.BLUE+"/icu control <player>"+ChatColor.GREEN+" Enter Control Mode with <player>.");
sender.sendMessage(ChatColor.BLUE+"/icu stop"+ChatColor.GREEN+" Exit Control Mode.");
sender.sendMessage(ChatColor.YELLOW+" ========== ");
sender.sendMessage(ChatColor.DARK_PURPLE+"Created by FireBreath15");
- sender.sendMessage(ChatColor.YELLOW+"==========[ iControlU Help v1.5.6]==========");
+ sender.sendMessage(ChatColor.YELLOW+"==========[ iControlU Help v1.5.7]==========");
}
if(args.length == 2){
if(args[0].equalsIgnoreCase("control")){
if(sender.hasPermission("icu.control")){
String name = sender.getName();
if(!(this.getConfig().contains("controllers."+name))){
if(this.getServer().getPlayer(args[1]) != null){
Player victim = this.getServer().getPlayer(args[1]);
if(!(victim.hasPermission("icu.exempt"))){
//here
Player s = (Player)sender;
victim.hidePlayer(s);
s.teleport(victim);
s.hidePlayer(victim);
Player[] ps = this.getServer().getOnlinePlayers();
int pon = ps.length;
for(int i=0; i<pon; i++){
ps[i].hidePlayer(s);
}
this.getConfig().set("controlled."+victim.getName(), sender.getName());
this.getConfig().set("controllers."+sender.getName()+".person", victim.getName());
this.getConfig().set("controllers."+name+".controlling", true);
this.saveConfig();
api.storePlayerInventory(s.getName());
api.storePlayerArmor(s.getName());
s.getInventory().setContents(victim.getInventory().getContents());
s.getInventory().setArmorContents(victim.getInventory().getArmorContents());
@SuppressWarnings("unused")
BukkitTask sync = new InvSync(this).runTaskLater(this, 20);
s.sendMessage(ChatColor.GOLD+"[iControlU] "+ChatColor.BLUE+"Control Mode activated.");
s.sendMessage(ChatColor.GOLD+"[iControlU] "+ChatColor.BLUE+"You begun controlling "+ChatColor.GREEN+victim.getName());
s.sendMessage(ChatColor.GOLD+"[iControlU] "+ChatColor.BLUE+"You now control "+victim.getName()+"'s chats and movements.");
}else{
- sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+"You can't control that player!");
+ sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+" You can't control that player!");
}
}else{
- sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+"Player not found!");
+ sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+" Player not found!");
}
}else{
- sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+"You're already controlling someone!");
+ sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+" You're already controlling someone!");
}
}else{
- sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+"You don't have permission");
+ sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+" You don't have permission");
}
}
}
if(args.length == 1){
if(args[0].equalsIgnoreCase("stop")){
if(sender.hasPermission("icu.stop")){
String name = sender.getName();
if(this.getConfig().contains("controllers."+name+".controlling")){
String player = this.getConfig().getString("controllers."+name+".person");
Player victim = this.getServer().getPlayer(player);
Player s = (Player)sender;
this.getConfig().set("controlled."+victim.getName(),null);
this.getConfig().set("controllers."+name, null);
this.saveConfig();
victim.showPlayer(s);
PotionEffect effect = new PotionEffect(PotionEffectType.INVISIBILITY, 200, 1);
s.addPotionEffect(effect);
s.showPlayer(victim);
Player[] ps = this.getServer().getOnlinePlayers();
int pon = ps.length;
for(int i=0; i<pon; i++){
ps[i].showPlayer(s);
// Now we cycle through every player online and show the sender to them. The controlling is over
// so we need to see the troll.
}
api.restorePlayerInventory(s.getName());
api.restorePlayerArmor(s.getName());
- sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+"You are no longer controlling someone");
+ sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+" You are no longer controlling someone");
}else{
- sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+"You aren't controlling anyone!");
+ sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+" You aren't controlling anyone!");
}
}else{
- sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+"You don't have permission!");
+ sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+" You don't have permission!");
}
}
}
}else{
- sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+"iControlU commands can only be sent from a player!");
+ sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+" iControlU commands can only be sent from a player!");
}
return true;
}
return false;
}
}
| false | true |
public boolean onCommand(CommandSender sender, Command cmd, String label, String args[]){
if(cmd.getName().equalsIgnoreCase("icu")){
if(sender instanceof Player){
if(args.length == 0 || args.length > 2){
//show help menu. they got their arguments wrong!
sender.sendMessage(ChatColor.YELLOW+"==========[ iControlU Help v1.5.6]==========");
sender.sendMessage(ChatColor.BLUE+"/icu control <player>"+ChatColor.GREEN+" Enter Control Mode with <player>.");
sender.sendMessage(ChatColor.BLUE+"/icu stop"+ChatColor.GREEN+" Exit Control Mode.");
sender.sendMessage(ChatColor.YELLOW+" ========== ");
sender.sendMessage(ChatColor.DARK_PURPLE+"Created by FireBreath15");
sender.sendMessage(ChatColor.YELLOW+"==========[ iControlU Help v1.5.6]==========");
}
if(args.length == 2){
if(args[0].equalsIgnoreCase("control")){
if(sender.hasPermission("icu.control")){
String name = sender.getName();
if(!(this.getConfig().contains("controllers."+name))){
if(this.getServer().getPlayer(args[1]) != null){
Player victim = this.getServer().getPlayer(args[1]);
if(!(victim.hasPermission("icu.exempt"))){
//here
Player s = (Player)sender;
victim.hidePlayer(s);
s.teleport(victim);
s.hidePlayer(victim);
Player[] ps = this.getServer().getOnlinePlayers();
int pon = ps.length;
for(int i=0; i<pon; i++){
ps[i].hidePlayer(s);
}
this.getConfig().set("controlled."+victim.getName(), sender.getName());
this.getConfig().set("controllers."+sender.getName()+".person", victim.getName());
this.getConfig().set("controllers."+name+".controlling", true);
this.saveConfig();
api.storePlayerInventory(s.getName());
api.storePlayerArmor(s.getName());
s.getInventory().setContents(victim.getInventory().getContents());
s.getInventory().setArmorContents(victim.getInventory().getArmorContents());
@SuppressWarnings("unused")
BukkitTask sync = new InvSync(this).runTaskLater(this, 20);
s.sendMessage(ChatColor.GOLD+"[iControlU] "+ChatColor.BLUE+"Control Mode activated.");
s.sendMessage(ChatColor.GOLD+"[iControlU] "+ChatColor.BLUE+"You begun controlling "+ChatColor.GREEN+victim.getName());
s.sendMessage(ChatColor.GOLD+"[iControlU] "+ChatColor.BLUE+"You now control "+victim.getName()+"'s chats and movements.");
}else{
sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+"You can't control that player!");
}
}else{
sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+"Player not found!");
}
}else{
sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+"You're already controlling someone!");
}
}else{
sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+"You don't have permission");
}
}
}
if(args.length == 1){
if(args[0].equalsIgnoreCase("stop")){
if(sender.hasPermission("icu.stop")){
String name = sender.getName();
if(this.getConfig().contains("controllers."+name+".controlling")){
String player = this.getConfig().getString("controllers."+name+".person");
Player victim = this.getServer().getPlayer(player);
Player s = (Player)sender;
this.getConfig().set("controlled."+victim.getName(),null);
this.getConfig().set("controllers."+name, null);
this.saveConfig();
victim.showPlayer(s);
PotionEffect effect = new PotionEffect(PotionEffectType.INVISIBILITY, 200, 1);
s.addPotionEffect(effect);
s.showPlayer(victim);
Player[] ps = this.getServer().getOnlinePlayers();
int pon = ps.length;
for(int i=0; i<pon; i++){
ps[i].showPlayer(s);
// Now we cycle through every player online and show the sender to them. The controlling is over
// so we need to see the troll.
}
api.restorePlayerInventory(s.getName());
api.restorePlayerArmor(s.getName());
sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+"You are no longer controlling someone");
}else{
sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+"You aren't controlling anyone!");
}
}else{
sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+"You don't have permission!");
}
}
}
}else{
sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+"iControlU commands can only be sent from a player!");
}
return true;
}
return false;
}
|
public boolean onCommand(CommandSender sender, Command cmd, String label, String args[]){
if(cmd.getName().equalsIgnoreCase("icu")){
if(sender instanceof Player){
if(args.length == 0 || args.length > 2){
//show help menu. they got their arguments wrong!
sender.sendMessage(ChatColor.YELLOW+"==========[ iControlU Help v1.5.7]==========");
sender.sendMessage(ChatColor.BLUE+"/icu control <player>"+ChatColor.GREEN+" Enter Control Mode with <player>.");
sender.sendMessage(ChatColor.BLUE+"/icu stop"+ChatColor.GREEN+" Exit Control Mode.");
sender.sendMessage(ChatColor.YELLOW+" ========== ");
sender.sendMessage(ChatColor.DARK_PURPLE+"Created by FireBreath15");
sender.sendMessage(ChatColor.YELLOW+"==========[ iControlU Help v1.5.7]==========");
}
if(args.length == 2){
if(args[0].equalsIgnoreCase("control")){
if(sender.hasPermission("icu.control")){
String name = sender.getName();
if(!(this.getConfig().contains("controllers."+name))){
if(this.getServer().getPlayer(args[1]) != null){
Player victim = this.getServer().getPlayer(args[1]);
if(!(victim.hasPermission("icu.exempt"))){
//here
Player s = (Player)sender;
victim.hidePlayer(s);
s.teleport(victim);
s.hidePlayer(victim);
Player[] ps = this.getServer().getOnlinePlayers();
int pon = ps.length;
for(int i=0; i<pon; i++){
ps[i].hidePlayer(s);
}
this.getConfig().set("controlled."+victim.getName(), sender.getName());
this.getConfig().set("controllers."+sender.getName()+".person", victim.getName());
this.getConfig().set("controllers."+name+".controlling", true);
this.saveConfig();
api.storePlayerInventory(s.getName());
api.storePlayerArmor(s.getName());
s.getInventory().setContents(victim.getInventory().getContents());
s.getInventory().setArmorContents(victim.getInventory().getArmorContents());
@SuppressWarnings("unused")
BukkitTask sync = new InvSync(this).runTaskLater(this, 20);
s.sendMessage(ChatColor.GOLD+"[iControlU] "+ChatColor.BLUE+"Control Mode activated.");
s.sendMessage(ChatColor.GOLD+"[iControlU] "+ChatColor.BLUE+"You begun controlling "+ChatColor.GREEN+victim.getName());
s.sendMessage(ChatColor.GOLD+"[iControlU] "+ChatColor.BLUE+"You now control "+victim.getName()+"'s chats and movements.");
}else{
sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+" You can't control that player!");
}
}else{
sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+" Player not found!");
}
}else{
sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+" You're already controlling someone!");
}
}else{
sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+" You don't have permission");
}
}
}
if(args.length == 1){
if(args[0].equalsIgnoreCase("stop")){
if(sender.hasPermission("icu.stop")){
String name = sender.getName();
if(this.getConfig().contains("controllers."+name+".controlling")){
String player = this.getConfig().getString("controllers."+name+".person");
Player victim = this.getServer().getPlayer(player);
Player s = (Player)sender;
this.getConfig().set("controlled."+victim.getName(),null);
this.getConfig().set("controllers."+name, null);
this.saveConfig();
victim.showPlayer(s);
PotionEffect effect = new PotionEffect(PotionEffectType.INVISIBILITY, 200, 1);
s.addPotionEffect(effect);
s.showPlayer(victim);
Player[] ps = this.getServer().getOnlinePlayers();
int pon = ps.length;
for(int i=0; i<pon; i++){
ps[i].showPlayer(s);
// Now we cycle through every player online and show the sender to them. The controlling is over
// so we need to see the troll.
}
api.restorePlayerInventory(s.getName());
api.restorePlayerArmor(s.getName());
sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+" You are no longer controlling someone");
}else{
sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+" You aren't controlling anyone!");
}
}else{
sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+" You don't have permission!");
}
}
}
}else{
sender.sendMessage(ChatColor.GOLD+"[iControlU]"+ChatColor.RED+" iControlU commands can only be sent from a player!");
}
return true;
}
return false;
}
|
diff --git a/src/main/java/org/jahia/modules/external/osgi/ExternalProviderActivator.java b/src/main/java/org/jahia/modules/external/osgi/ExternalProviderActivator.java
index 650cb6b..08cdc58 100644
--- a/src/main/java/org/jahia/modules/external/osgi/ExternalProviderActivator.java
+++ b/src/main/java/org/jahia/modules/external/osgi/ExternalProviderActivator.java
@@ -1,217 +1,216 @@
/**
*
* This file is part of Jahia: An integrated WCM, DMS and Portal Solution
* Copyright (C) 2002-2009 Jahia Limited. All rights reserved.
*
* 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.
*
* As a special exception to the terms and conditions of version 2.0 of
* the GPL (or any later version), you may redistribute this Program in connection
* with Free/Libre and Open Source Software ("FLOSS") applications as described
* in Jahia's FLOSS exception. You should have recieved a copy of the text
* describing the FLOSS exception, and it is also available here:
* http://www.jahia.com/license"
*
* Commercial and Supported Versions of the program
* Alternatively, commercial and supported versions of the program may be used
* in accordance with the terms contained in a separate written agreement
* between you and Jahia Limited. If you are unsure which license is appropriate
* for your use, please contact the sales department at [email protected].
*/
package org.jahia.modules.external.osgi;
import org.apache.commons.beanutils.BeanUtils;
import org.eclipse.gemini.blueprint.context.BundleContextAware;
import org.jahia.data.templates.JahiaTemplatesPackage;
import org.jahia.exceptions.JahiaInitializationException;
import org.jahia.osgi.BundleUtils;
import org.jahia.services.JahiaAfterInitializationService;
import org.jahia.services.SpringContextSingleton;
import org.jahia.services.content.JCRStoreProvider;
import org.jahia.services.content.JCRStoreService;
import org.osgi.framework.*;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Created by IntelliJ IDEA.
*
* @author : rincevent
* @since : JAHIA 6.1
* Created : 04/03/13
*/
public class ExternalProviderActivator implements BundleActivator,JahiaAfterInitializationService, BundleContextAware {
private static org.slf4j.Logger logger = LoggerFactory.getLogger(ExternalProviderActivator.class);
private BundleContext context;
/**
* Called when this bundle is started so the Framework can perform the
* bundle-specific activities necessary to start this bundle. This method
* can be used to register services or to allocate any resources that this
* bundle needs.
* <p/>
* <p/>
* This method must complete and return to its caller in a timely manner.
*
* @param context The execution context of the bundle being started.
* @throws Exception If this method throws an exception, this
* bundle is marked as stopped and the Framework will remove this
* bundle's listeners, unregister all services registered by this
* bundle, and release all services used by this bundle.
*/
@Override
public void start(BundleContext context) throws Exception {
this.context = context;
context.addBundleListener(new BundleListener() {
@Override
public void bundleChanged(BundleEvent event) {
if (event.getType() == BundleEvent.STARTED) {
mountBundle(event.getBundle());
} else if (event.getType() == BundleEvent.STOPPED) {
unmountBundle(event.getBundle());
}
}
});
Bundle[] bundles = context.getBundles();
for (Bundle bundle : bundles) {
if (bundle.getState() == Bundle.ACTIVE) {
mountBundle(bundle);
}
}
}
private void mountBundle(Bundle bundle) {
final JahiaTemplatesPackage pkg = BundleUtils.isJahiaModuleBundle(bundle) ? BundleUtils.getModule(
bundle) : null;
if (null != pkg && pkg.getSourcesFolder() != null) {
mountSourcesProvider(pkg);
}
}
private void unmountBundle(Bundle bundle) {
final JahiaTemplatesPackage pkg = BundleUtils.isJahiaModuleBundle(bundle) ? BundleUtils.getModule(
bundle) : null;
if (null != pkg && pkg.getSourcesFolder() != null) {
unmountSourcesProvider(pkg);
}
}
/**
* Called when this bundle is stopped so the Framework can perform the
* bundle-specific activities necessary to stop the bundle. In general, this
* method should undo the work that the <code>BundleActivator.start</code>
* method started. There should be no active threads that were started by
* this bundle when this bundle returns. A stopped bundle must not call any
* Framework objects.
* <p/>
* <p/>
* This method must complete and return to its caller in a timely manner.
*
* @param context The execution context of the bundle being stopped.
* @throws Exception If this method throws an exception, the
* bundle is still marked as stopped, and the Framework will remove
* the bundle's listeners, unregister all services registered by the
* bundle, and release all services used by the bundle.
*/
@Override
public void stop(BundleContext context) throws Exception {
Bundle[] bundles = context.getBundles();
for (Bundle bundle : bundles) {
if (bundle.getState() == Bundle.ACTIVE) {
unmountBundle(bundle);
}
}
}
public void mountSourcesProvider(JahiaTemplatesPackage templatePackage) {
JCRStoreService jcrStoreService = (JCRStoreService) SpringContextSingleton.getBean("JCRStoreService");
JCRStoreProvider provider = jcrStoreService.getSessionFactory().getProviders().get(
"module-" + templatePackage.getRootFolder() + "-" + templatePackage.getVersion().toString());
if (provider == null) {
try {
Object dataSource = SpringContextSingleton.getBeanInModulesContext("ModulesDataSourcePrototype");
logger.info("Mounting source for bundle "+templatePackage.getName());
Map<String, Object> properties = new LinkedHashMap<String, Object>();
File oldStructure = new File(templatePackage.getSourcesFolder(), "src/main/webapp");
if (oldStructure.exists()) {
properties.put("root", templatePackage.getSourcesFolder().toURI().toString() + "src/main/webapp");
} else {
properties.put("root",
templatePackage.getSourcesFolder().toURI().toString() + "src/main/resources");
}
properties.put("module", templatePackage);
BeanUtils.populate(dataSource, properties);
JCRStoreProvider ex = (JCRStoreProvider) SpringContextSingleton.getBeanInModulesContext(
"ExternalStoreProviderPrototype");
properties.clear();
properties.put("key",
"module-" + templatePackage.getRootFolder() + "-" + templatePackage.getVersion().toString());
properties.put("mountPoint", "/modules/" + templatePackage.getRootFolderWithVersion() + "/sources");
properties.put("dataSource", dataSource);
BeanUtils.populate(ex, properties);
ex.start();
- start(context);
} catch (IllegalAccessException e) {
logger.error(e.getMessage(), e);
} catch (InvocationTargetException e) {
logger.error(e.getMessage(), e);
} catch (JahiaInitializationException e) {
logger.error(e.getMessage(), e);
} catch (NoSuchBeanDefinitionException e) {
logger.debug(e.getMessage(), e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}
public void unmountSourcesProvider(JahiaTemplatesPackage templatePackage) {
JCRStoreService jcrStoreService = (JCRStoreService) SpringContextSingleton.getBean("JCRStoreService");
JCRStoreProvider provider = jcrStoreService.getSessionFactory().getProviders().get(
"module-" + templatePackage.getRootFolder() + "-" + templatePackage.getVersion().toString());
if (provider != null) {
logger.info("Unmounting source for bundle "+templatePackage.getName());
provider.stop();
}
}
@Override
public void initAfterAllServicesAreStarted() throws JahiaInitializationException {
try {
start(context);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
@Override
public void setBundleContext(BundleContext bundleContext) {
this.context = bundleContext;
try {
start(bundleContext);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}
| true | true |
public void mountSourcesProvider(JahiaTemplatesPackage templatePackage) {
JCRStoreService jcrStoreService = (JCRStoreService) SpringContextSingleton.getBean("JCRStoreService");
JCRStoreProvider provider = jcrStoreService.getSessionFactory().getProviders().get(
"module-" + templatePackage.getRootFolder() + "-" + templatePackage.getVersion().toString());
if (provider == null) {
try {
Object dataSource = SpringContextSingleton.getBeanInModulesContext("ModulesDataSourcePrototype");
logger.info("Mounting source for bundle "+templatePackage.getName());
Map<String, Object> properties = new LinkedHashMap<String, Object>();
File oldStructure = new File(templatePackage.getSourcesFolder(), "src/main/webapp");
if (oldStructure.exists()) {
properties.put("root", templatePackage.getSourcesFolder().toURI().toString() + "src/main/webapp");
} else {
properties.put("root",
templatePackage.getSourcesFolder().toURI().toString() + "src/main/resources");
}
properties.put("module", templatePackage);
BeanUtils.populate(dataSource, properties);
JCRStoreProvider ex = (JCRStoreProvider) SpringContextSingleton.getBeanInModulesContext(
"ExternalStoreProviderPrototype");
properties.clear();
properties.put("key",
"module-" + templatePackage.getRootFolder() + "-" + templatePackage.getVersion().toString());
properties.put("mountPoint", "/modules/" + templatePackage.getRootFolderWithVersion() + "/sources");
properties.put("dataSource", dataSource);
BeanUtils.populate(ex, properties);
ex.start();
start(context);
} catch (IllegalAccessException e) {
logger.error(e.getMessage(), e);
} catch (InvocationTargetException e) {
logger.error(e.getMessage(), e);
} catch (JahiaInitializationException e) {
logger.error(e.getMessage(), e);
} catch (NoSuchBeanDefinitionException e) {
logger.debug(e.getMessage(), e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}
|
public void mountSourcesProvider(JahiaTemplatesPackage templatePackage) {
JCRStoreService jcrStoreService = (JCRStoreService) SpringContextSingleton.getBean("JCRStoreService");
JCRStoreProvider provider = jcrStoreService.getSessionFactory().getProviders().get(
"module-" + templatePackage.getRootFolder() + "-" + templatePackage.getVersion().toString());
if (provider == null) {
try {
Object dataSource = SpringContextSingleton.getBeanInModulesContext("ModulesDataSourcePrototype");
logger.info("Mounting source for bundle "+templatePackage.getName());
Map<String, Object> properties = new LinkedHashMap<String, Object>();
File oldStructure = new File(templatePackage.getSourcesFolder(), "src/main/webapp");
if (oldStructure.exists()) {
properties.put("root", templatePackage.getSourcesFolder().toURI().toString() + "src/main/webapp");
} else {
properties.put("root",
templatePackage.getSourcesFolder().toURI().toString() + "src/main/resources");
}
properties.put("module", templatePackage);
BeanUtils.populate(dataSource, properties);
JCRStoreProvider ex = (JCRStoreProvider) SpringContextSingleton.getBeanInModulesContext(
"ExternalStoreProviderPrototype");
properties.clear();
properties.put("key",
"module-" + templatePackage.getRootFolder() + "-" + templatePackage.getVersion().toString());
properties.put("mountPoint", "/modules/" + templatePackage.getRootFolderWithVersion() + "/sources");
properties.put("dataSource", dataSource);
BeanUtils.populate(ex, properties);
ex.start();
} catch (IllegalAccessException e) {
logger.error(e.getMessage(), e);
} catch (InvocationTargetException e) {
logger.error(e.getMessage(), e);
} catch (JahiaInitializationException e) {
logger.error(e.getMessage(), e);
} catch (NoSuchBeanDefinitionException e) {
logger.debug(e.getMessage(), e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}
|
diff --git a/jreunion/src/com/googlecode/reunion/jreunion/server/S_SessionManager.java b/jreunion/src/com/googlecode/reunion/jreunion/server/S_SessionManager.java
index 60e47bd..439291b 100644
--- a/jreunion/src/com/googlecode/reunion/jreunion/server/S_SessionManager.java
+++ b/jreunion/src/com/googlecode/reunion/jreunion/server/S_SessionManager.java
@@ -1,185 +1,187 @@
package com.googlecode.reunion.jreunion.server;
import java.util.Iterator;
import java.util.Vector;
import com.googlecode.reunion.jreunion.game.G_Mob;
import com.googlecode.reunion.jreunion.game.G_Npc;
import com.googlecode.reunion.jreunion.game.G_Player;
/**
* @author Aidamina
* @license http://reunion.googlecode.com/svn/trunk/license.txt
*/
public class S_SessionManager {
private float sessionRadius = -1;
private java.util.List<S_Session> sessionList = new Vector<S_Session>();
private com.googlecode.reunion.jreunion.server.S_World world;
private S_Timer statusUpdateTime = new S_Timer();
public S_SessionManager(com.googlecode.reunion.jreunion.server.S_World world) {
this.world = world;
}
public void addSession(S_Session session) {
sessionList.add(session);
}
public int getNumberOfSessions() {
return sessionList.size();
}
public S_Session getSession(int index) {
return sessionList.get(index);
}
public Iterator<S_Session> getSessionListIterator() {
return sessionList.iterator();
}
public S_Session newSession(G_Player player) {
S_Session s = new S_Session(player);
addSession(s);
return s;
}
public void removeSession(S_Session session) {
sessionList.remove(session);
}
public void workSessions() {
/*
* Iterator iter = sessionList.iterator(); while (iter.hasNext()) {
* Session session = (Session) iter.next();
* session.WorkSession(getSessionRadius()); }
*/
Iterator<G_Player> player1Iter = S_Server.getInstance()
.getWorldModule().getPlayerManager().getPlayerListIterator();
while (player1Iter.hasNext()) {
G_Player player1 = player1Iter.next();
if (statusUpdateTime.getTimeElapsedSeconds() >= 10) {
S_Client client = S_Server.getInstance().getNetworkModule()
.getClient(player1);
if (client == null) {
continue;
}
statusUpdateTime.Stop();
statusUpdateTime.Reset();
//TODO: Move regen somewhere sane!
player1.updateStatus(0,
player1.getCurrHp() + (int) (player1.getMaxHp() * 0.1),
player1.getMaxHp());
player1.updateStatus(1,
player1.getCurrMana()
+ (int) (player1.getMaxMana() * 0.08),
player1.getMaxMana());
player1.updateStatus(2,
player1.getCurrStm()
+ (int) (player1.getMaxStm() * 0.08),
player1.getMaxStm());
player1.updateStatus(3,
player1.getCurrElect()
+ (int) (player1.getMaxElect() * 0.08),
player1.getMaxElect());
}
if (!statusUpdateTime.isRunning()) {
statusUpdateTime.Start();
}
Iterator<G_Player> player2Iter = world.getPlayerManager()
.getPlayerListIterator();
while (player2Iter.hasNext()) {
G_Player player2 = player2Iter.next();
if (player1 == player2) {
continue;
}
if (player1.getPosition().getMap() != player2.getPosition().getMap()) {
continue;
}
double xcomp = Math.pow(player1.getPosition().getX() - player2.getPosition().getX(),
2);
double ycomp = Math.pow(player1.getPosition().getY() - player2.getPosition().getY(),
2);
double zcomp = Math.pow(player1.getPosition().getZ() - player2.getPosition().getZ(),
2);
double distance = Math.sqrt((xcomp * xcomp) + (ycomp * ycomp) + (zcomp * zcomp));
if (distance <= player1.getSessionRadius()) {
player1.getSession().enter(player2);
}
if (distance > player1.getSessionRadius()) {
player1.getSession().exit(player2);
}
}
Iterator<G_Mob> mobIter = world.getMobManager()
.getMobListIterator();
while (mobIter.hasNext()) {
G_Mob mob = mobIter.next();
if (mob == null) {
continue;
}
if (mob.getPosition().getMap() != player1.getPosition().getMap()) {
continue;
}
int distance = mob.getDistance(player1);
if (distance > player1.getSessionRadius()) {
player1.getSession().exit(mob);
} else {
player1.getSession().enter(mob);
+ /*
if (distance <= 150 && mob.getAttackType() != -1) {
if (player1.getPosition().getMap()
.getMobArea()
.get((player1.getPosition().getX() / 10 - 300),
(player1.getPosition().getY() / 10)) == true) {
mob.moveToPlayer(player1, distance);
}
}
+ *///TODO: Crashes server because of the broken session implementation
}
}
Iterator<G_Npc> npcIter = world.getNpcManager()
.getNpcListIterator();
while (npcIter.hasNext()) {
G_Npc npc = npcIter.next();
if (npc == null) {
continue;
}
if (npc.getPosition().getMap() != player1.getPosition().getMap()) {
continue;
}
int distance = npc.getDistance(player1);
if (distance > player1.getSessionRadius()) {
player1.getSession().exit(npc);
} else {
player1.getSession().enter(npc);
}
}
}
}
}
| false | true |
public void workSessions() {
/*
* Iterator iter = sessionList.iterator(); while (iter.hasNext()) {
* Session session = (Session) iter.next();
* session.WorkSession(getSessionRadius()); }
*/
Iterator<G_Player> player1Iter = S_Server.getInstance()
.getWorldModule().getPlayerManager().getPlayerListIterator();
while (player1Iter.hasNext()) {
G_Player player1 = player1Iter.next();
if (statusUpdateTime.getTimeElapsedSeconds() >= 10) {
S_Client client = S_Server.getInstance().getNetworkModule()
.getClient(player1);
if (client == null) {
continue;
}
statusUpdateTime.Stop();
statusUpdateTime.Reset();
//TODO: Move regen somewhere sane!
player1.updateStatus(0,
player1.getCurrHp() + (int) (player1.getMaxHp() * 0.1),
player1.getMaxHp());
player1.updateStatus(1,
player1.getCurrMana()
+ (int) (player1.getMaxMana() * 0.08),
player1.getMaxMana());
player1.updateStatus(2,
player1.getCurrStm()
+ (int) (player1.getMaxStm() * 0.08),
player1.getMaxStm());
player1.updateStatus(3,
player1.getCurrElect()
+ (int) (player1.getMaxElect() * 0.08),
player1.getMaxElect());
}
if (!statusUpdateTime.isRunning()) {
statusUpdateTime.Start();
}
Iterator<G_Player> player2Iter = world.getPlayerManager()
.getPlayerListIterator();
while (player2Iter.hasNext()) {
G_Player player2 = player2Iter.next();
if (player1 == player2) {
continue;
}
if (player1.getPosition().getMap() != player2.getPosition().getMap()) {
continue;
}
double xcomp = Math.pow(player1.getPosition().getX() - player2.getPosition().getX(),
2);
double ycomp = Math.pow(player1.getPosition().getY() - player2.getPosition().getY(),
2);
double zcomp = Math.pow(player1.getPosition().getZ() - player2.getPosition().getZ(),
2);
double distance = Math.sqrt((xcomp * xcomp) + (ycomp * ycomp) + (zcomp * zcomp));
if (distance <= player1.getSessionRadius()) {
player1.getSession().enter(player2);
}
if (distance > player1.getSessionRadius()) {
player1.getSession().exit(player2);
}
}
Iterator<G_Mob> mobIter = world.getMobManager()
.getMobListIterator();
while (mobIter.hasNext()) {
G_Mob mob = mobIter.next();
if (mob == null) {
continue;
}
if (mob.getPosition().getMap() != player1.getPosition().getMap()) {
continue;
}
int distance = mob.getDistance(player1);
if (distance > player1.getSessionRadius()) {
player1.getSession().exit(mob);
} else {
player1.getSession().enter(mob);
if (distance <= 150 && mob.getAttackType() != -1) {
if (player1.getPosition().getMap()
.getMobArea()
.get((player1.getPosition().getX() / 10 - 300),
(player1.getPosition().getY() / 10)) == true) {
mob.moveToPlayer(player1, distance);
}
}
}
}
Iterator<G_Npc> npcIter = world.getNpcManager()
.getNpcListIterator();
while (npcIter.hasNext()) {
G_Npc npc = npcIter.next();
if (npc == null) {
continue;
}
if (npc.getPosition().getMap() != player1.getPosition().getMap()) {
continue;
}
int distance = npc.getDistance(player1);
if (distance > player1.getSessionRadius()) {
player1.getSession().exit(npc);
} else {
player1.getSession().enter(npc);
}
}
}
}
|
public void workSessions() {
/*
* Iterator iter = sessionList.iterator(); while (iter.hasNext()) {
* Session session = (Session) iter.next();
* session.WorkSession(getSessionRadius()); }
*/
Iterator<G_Player> player1Iter = S_Server.getInstance()
.getWorldModule().getPlayerManager().getPlayerListIterator();
while (player1Iter.hasNext()) {
G_Player player1 = player1Iter.next();
if (statusUpdateTime.getTimeElapsedSeconds() >= 10) {
S_Client client = S_Server.getInstance().getNetworkModule()
.getClient(player1);
if (client == null) {
continue;
}
statusUpdateTime.Stop();
statusUpdateTime.Reset();
//TODO: Move regen somewhere sane!
player1.updateStatus(0,
player1.getCurrHp() + (int) (player1.getMaxHp() * 0.1),
player1.getMaxHp());
player1.updateStatus(1,
player1.getCurrMana()
+ (int) (player1.getMaxMana() * 0.08),
player1.getMaxMana());
player1.updateStatus(2,
player1.getCurrStm()
+ (int) (player1.getMaxStm() * 0.08),
player1.getMaxStm());
player1.updateStatus(3,
player1.getCurrElect()
+ (int) (player1.getMaxElect() * 0.08),
player1.getMaxElect());
}
if (!statusUpdateTime.isRunning()) {
statusUpdateTime.Start();
}
Iterator<G_Player> player2Iter = world.getPlayerManager()
.getPlayerListIterator();
while (player2Iter.hasNext()) {
G_Player player2 = player2Iter.next();
if (player1 == player2) {
continue;
}
if (player1.getPosition().getMap() != player2.getPosition().getMap()) {
continue;
}
double xcomp = Math.pow(player1.getPosition().getX() - player2.getPosition().getX(),
2);
double ycomp = Math.pow(player1.getPosition().getY() - player2.getPosition().getY(),
2);
double zcomp = Math.pow(player1.getPosition().getZ() - player2.getPosition().getZ(),
2);
double distance = Math.sqrt((xcomp * xcomp) + (ycomp * ycomp) + (zcomp * zcomp));
if (distance <= player1.getSessionRadius()) {
player1.getSession().enter(player2);
}
if (distance > player1.getSessionRadius()) {
player1.getSession().exit(player2);
}
}
Iterator<G_Mob> mobIter = world.getMobManager()
.getMobListIterator();
while (mobIter.hasNext()) {
G_Mob mob = mobIter.next();
if (mob == null) {
continue;
}
if (mob.getPosition().getMap() != player1.getPosition().getMap()) {
continue;
}
int distance = mob.getDistance(player1);
if (distance > player1.getSessionRadius()) {
player1.getSession().exit(mob);
} else {
player1.getSession().enter(mob);
/*
if (distance <= 150 && mob.getAttackType() != -1) {
if (player1.getPosition().getMap()
.getMobArea()
.get((player1.getPosition().getX() / 10 - 300),
(player1.getPosition().getY() / 10)) == true) {
mob.moveToPlayer(player1, distance);
}
}
*///TODO: Crashes server because of the broken session implementation
}
}
Iterator<G_Npc> npcIter = world.getNpcManager()
.getNpcListIterator();
while (npcIter.hasNext()) {
G_Npc npc = npcIter.next();
if (npc == null) {
continue;
}
if (npc.getPosition().getMap() != player1.getPosition().getMap()) {
continue;
}
int distance = npc.getDistance(player1);
if (distance > player1.getSessionRadius()) {
player1.getSession().exit(npc);
} else {
player1.getSession().enter(npc);
}
}
}
}
|
diff --git a/src/main/java/iinteractive/bullfinch/Boss.java b/src/main/java/iinteractive/bullfinch/Boss.java
index f9e6b7b..93fa519 100644
--- a/src/main/java/iinteractive/bullfinch/Boss.java
+++ b/src/main/java/iinteractive/bullfinch/Boss.java
@@ -1,361 +1,362 @@
package iinteractive.bullfinch;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.command.KestrelCommandFactory;
import net.rubyeye.xmemcached.utils.AddrUtil;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Main class that drives workers from a Kestrel queue.
*
* @author gphat
*
*/
public class Boss {
static Logger logger = LoggerFactory.getLogger(Boss.class);
private HashMap<String,HashMap<Minion,Thread>> minionGroups;
private long configRefreshSeconds = 300;
private PerformanceCollector collector;
private boolean collecting = false;
private Thread emitterThread;
private PerformanceEmitter emitter;
private ArrayList<URL> configURLs;
private ArrayList<Long> configTimestamps;
public static void main(String[] args) {
if(args.length < 1) {
System.err.println("Must provide a config file");
return;
}
try {
Boss boss = new Boss(args[0]);
// Start all the threads now that we've verified that all were
// properly readied.
boss.start();
while(true) {
Thread.sleep(boss.getConfigRefreshSeconds() * 1000);
if (boss.isConfigStale()) {
logger.info("Restarting due to config file changes");
boss.stop();
boss = new Boss(args[0]);
boss.start();
}
}
} catch(Exception e) {
logger.error("Failed to load worker", e);
}
}
/**
* Create a new Boss object.
*
* @param config Configuration file URL
*/
public Boss(String configFile) throws Exception {
configURLs = new ArrayList<URL> ();
configTimestamps = new ArrayList<Long> ();
JSONObject config = readConfigFile(configFile);
if(config == null) {
logger.error("Failed to load config file.");
return;
}
Long configRefreshSecondsLng = (Long) config.get("config_refresh_seconds");
if(configRefreshSecondsLng == null) {
logger.info("No config_refresh_seconds specified, defaulting to 300");
configRefreshSecondsLng = new Long(300);
}
this.configRefreshSeconds = configRefreshSecondsLng.intValue();
logger.debug("Config will refresh in " + this.configRefreshSeconds + " seconds");
HashMap<String,Object> perfConfig = (HashMap<String,Object>) config.get("performance");
if(perfConfig != null) {
this.collecting = (Boolean) perfConfig.get("collect");
}
InetAddress addr = InetAddress.getLocalHost();
this.collector = new PerformanceCollector(addr.getHostName(), this.collecting);
// if(this.collecting) {
// // Prepare the emitter thread
// if(this.collecting) {
// Client kestrel = new Client((String) perfConfig.get("kestrel_host"), ((Long) perfConfig.get("kestrel_port")).intValue());
// kestrel.connect();
// this.emitter = new PerformanceEmitter(this.collector, kestrel, (String) perfConfig.get("queue"));
// if(perfConfig.containsKey("timeout")) {
// this.emitter.setTimeout(((Long) perfConfig.get("timeout")).intValue());
// }
// if(perfConfig.containsKey("retry_time")) {
// this.emitter.setRetryTime(((Long) perfConfig.get("retry_time")).intValue());
// }
// if(perfConfig.containsKey("retry_attempts")) {
// this.emitter.setRetryAttempts(((Long) perfConfig.get("retry_attempts")).intValue());
// }
// this.emitterThread = new Thread(this.emitter);
// }
// }
JSONArray workerList = (JSONArray) config.get("workers");
if(workerList == null) {
throw new ConfigurationException("Need a list of workers in the config file.");
}
@SuppressWarnings("unchecked")
Iterator<HashMap<String,Object>> workers = workerList.iterator();
// Get an empty hashmap to store threads
this.minionGroups = new HashMap<String,HashMap<Minion,Thread>>();
// The config has at least one worker in it, so we'll treat iterate
// over the workers and spin off each one in turn.
while(workers.hasNext()) {
HashMap<String,Object> workerConfig = (HashMap<String,Object>) workers.next();
prepareWorker(workerConfig);
}
}
/**
* Prepare a worker.
*
* @param workConfig The workers config.
* @throws Exception
*/
private void prepareWorker(HashMap<String,Object> workConfig) throws Exception {
String ref = (String) workConfig.get("$ref");
if (ref != null) {
workConfig = readConfigFile(ref);
}
String name = (String) workConfig.get("name");
if(name == null) {
throw new ConfigurationException("Each worker must have a name!");
}
String workHost = (String) workConfig.get("kestrel_host");
if(workHost == null) {
throw new ConfigurationException("Each worker must have a kestrel_host!");
}
Long workPortLng = (Long) workConfig.get("kestrel_port");
if(workPortLng == null) {
throw new ConfigurationException("Each worker must have a kestrel_port!");
}
int workPort = workPortLng.intValue();
String workerClass = (String) workConfig.get("worker_class");
if(workerClass == null) {
throw new ConfigurationException("Each worker must have a worker_class!");
}
String queue = (String) workConfig.get("subscribe_to");
if(queue == null) {
throw new ConfigurationException("Each worker must have a subscribe_to!");
}
Long workerCountLng = (Long) workConfig.get("worker_count");
// Default to a single worker
int workerCount = 1;
if(workerCountLng != null) {
// But allow it to be overridden.
workerCount = workerCountLng.intValue();
}
Long timeoutLng = (Long) workConfig.get("timeout");
if(timeoutLng == null) {
throw new ConfigurationException("Each worker must have a timeout!");
}
int timeout = timeoutLng.intValue();
// Get the config options to pass to the worker
@SuppressWarnings("unchecked")
HashMap<String,Object> workerConfig = (HashMap<String,Object>) workConfig.get("options");
if(workerConfig == null) {
throw new ConfigurationException("Each worker must have a worker_config!");
}
HashMap<Minion,Thread> workers = new HashMap<Minion,Thread>();
logger.debug("Created threadgroup for " + name);
for(int i = 0; i < workerCount; i++) {
// Create an instance of a worker.
Worker worker = (Worker) Class.forName(workerClass).newInstance();
worker.configure(workerConfig);
// Give it it's very own kestrel connection.
MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(workHost + ":" + workPort));
builder.setCommandFactory(new KestrelCommandFactory());
MemcachedClient client = builder.build();
client.setPrimitiveAsString(true);
client.setEnableHeartBeat(false);
+ client.setOpTimeout(timeout);
// Add the worker to the list so we can run it later.
Minion minion = new Minion(this.collector, client, queue, worker, timeout);
workers.put(minion, new Thread(minion));
}
this.minionGroups.put(name, workers);
logger.debug("Added worker threads to minion map.");
}
/**
* Get the number of seconds between config refresh checks.
*
* @return The number of seconds between config refreshes.
*/
private long getConfigRefreshSeconds() {
return this.configRefreshSeconds;
}
/**
* Start the worker threads.
*/
public void start() {
Iterator<String> workerNames = this.minionGroups.keySet().iterator();
// Iterate over each worker "group"...
while(workerNames.hasNext()) {
String name = workerNames.next();
Iterator<Thread> workers = this.minionGroups.get(name).values().iterator();
while(workers.hasNext()) {
Thread worker = workers.next();
worker.start();
}
}
if(this.collecting) {
this.emitterThread.start();
}
}
/**
* Stop the worker threads
*/
public void stop() {
Iterator<String> workerNames = this.minionGroups.keySet().iterator();
// Iterate over each worker "group"...
while(workerNames.hasNext()) {
String name = workerNames.next();
// Issue a cancel to each minion so they can stop
logger.debug("Cancelling minions");
Iterator<Minion> minions = this.minionGroups.get(name).keySet().iterator();
while(minions.hasNext()) {
// And start each thread in the group
Minion worker = minions.next();
worker.cancel();
}
if(this.collecting) {
this.emitter.cancel();
}
// Now wait around for each thread to finish in turn.
logger.debug("Joining threads");
Iterator<Thread> threads = this.minionGroups.get(name).values().iterator();
while(threads.hasNext()) {
Thread thread = threads.next();
try { thread.join(); } catch(Exception e) { logger.error("Interrupted joining thread."); }
}
if(this.collecting) {
try { this.emitterThread.join(); } catch(Exception e) { logger.error("Interrupted joining emitter thread."); }
}
}
}
/**
* Read the config file.
*
* @param path The location to find the file.
* @return A JSONObject of the config file.
* @throws Exception
* @throws FileNotFoundException
* @throws IOException
*/
private JSONObject readConfigFile(String configFile)
throws ConfigurationException, FileNotFoundException, IOException {
URL url = new URL(configFile);
logger.debug("Attempting to read " + url.toString());
JSONObject config;
try {
JSONParser parser = new JSONParser();
URLConnection conn = url.openConnection();
logger.debug("Last modified: " + conn.getLastModified());
config = (JSONObject) parser.parse(
new InputStreamReader(url.openStream())
);
configURLs.ensureCapacity(configURLs.size() + 1);
configTimestamps.ensureCapacity(configTimestamps.size() + 1);
configURLs.add(url);
configTimestamps.add(new Long (conn.getLastModified()));
}
catch ( Exception e ) {
logger.error("Failed to parse config file", e);
throw new ConfigurationException("Failed to parse config file=(" + url.toString() + ")");
}
return config;
}
/**
* Check all config file timestamps.
*
* @return A boolean value indicating whether or not the configuration is stale
*/
private boolean isConfigStale() {
boolean stale = false;
try {
for (int i = 0; i < configURLs.size() && !stale; i++)
if (configURLs.get(i).openConnection().getLastModified() > configTimestamps.get(i).longValue())
stale = true;
} catch (Exception e) {
logger.warn("Error getting config file, ignoring.", e);
stale = false;
}
return stale;
}
}
| true | true |
private void prepareWorker(HashMap<String,Object> workConfig) throws Exception {
String ref = (String) workConfig.get("$ref");
if (ref != null) {
workConfig = readConfigFile(ref);
}
String name = (String) workConfig.get("name");
if(name == null) {
throw new ConfigurationException("Each worker must have a name!");
}
String workHost = (String) workConfig.get("kestrel_host");
if(workHost == null) {
throw new ConfigurationException("Each worker must have a kestrel_host!");
}
Long workPortLng = (Long) workConfig.get("kestrel_port");
if(workPortLng == null) {
throw new ConfigurationException("Each worker must have a kestrel_port!");
}
int workPort = workPortLng.intValue();
String workerClass = (String) workConfig.get("worker_class");
if(workerClass == null) {
throw new ConfigurationException("Each worker must have a worker_class!");
}
String queue = (String) workConfig.get("subscribe_to");
if(queue == null) {
throw new ConfigurationException("Each worker must have a subscribe_to!");
}
Long workerCountLng = (Long) workConfig.get("worker_count");
// Default to a single worker
int workerCount = 1;
if(workerCountLng != null) {
// But allow it to be overridden.
workerCount = workerCountLng.intValue();
}
Long timeoutLng = (Long) workConfig.get("timeout");
if(timeoutLng == null) {
throw new ConfigurationException("Each worker must have a timeout!");
}
int timeout = timeoutLng.intValue();
// Get the config options to pass to the worker
@SuppressWarnings("unchecked")
HashMap<String,Object> workerConfig = (HashMap<String,Object>) workConfig.get("options");
if(workerConfig == null) {
throw new ConfigurationException("Each worker must have a worker_config!");
}
HashMap<Minion,Thread> workers = new HashMap<Minion,Thread>();
logger.debug("Created threadgroup for " + name);
for(int i = 0; i < workerCount; i++) {
// Create an instance of a worker.
Worker worker = (Worker) Class.forName(workerClass).newInstance();
worker.configure(workerConfig);
// Give it it's very own kestrel connection.
MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(workHost + ":" + workPort));
builder.setCommandFactory(new KestrelCommandFactory());
MemcachedClient client = builder.build();
client.setPrimitiveAsString(true);
client.setEnableHeartBeat(false);
// Add the worker to the list so we can run it later.
Minion minion = new Minion(this.collector, client, queue, worker, timeout);
workers.put(minion, new Thread(minion));
}
this.minionGroups.put(name, workers);
logger.debug("Added worker threads to minion map.");
}
|
private void prepareWorker(HashMap<String,Object> workConfig) throws Exception {
String ref = (String) workConfig.get("$ref");
if (ref != null) {
workConfig = readConfigFile(ref);
}
String name = (String) workConfig.get("name");
if(name == null) {
throw new ConfigurationException("Each worker must have a name!");
}
String workHost = (String) workConfig.get("kestrel_host");
if(workHost == null) {
throw new ConfigurationException("Each worker must have a kestrel_host!");
}
Long workPortLng = (Long) workConfig.get("kestrel_port");
if(workPortLng == null) {
throw new ConfigurationException("Each worker must have a kestrel_port!");
}
int workPort = workPortLng.intValue();
String workerClass = (String) workConfig.get("worker_class");
if(workerClass == null) {
throw new ConfigurationException("Each worker must have a worker_class!");
}
String queue = (String) workConfig.get("subscribe_to");
if(queue == null) {
throw new ConfigurationException("Each worker must have a subscribe_to!");
}
Long workerCountLng = (Long) workConfig.get("worker_count");
// Default to a single worker
int workerCount = 1;
if(workerCountLng != null) {
// But allow it to be overridden.
workerCount = workerCountLng.intValue();
}
Long timeoutLng = (Long) workConfig.get("timeout");
if(timeoutLng == null) {
throw new ConfigurationException("Each worker must have a timeout!");
}
int timeout = timeoutLng.intValue();
// Get the config options to pass to the worker
@SuppressWarnings("unchecked")
HashMap<String,Object> workerConfig = (HashMap<String,Object>) workConfig.get("options");
if(workerConfig == null) {
throw new ConfigurationException("Each worker must have a worker_config!");
}
HashMap<Minion,Thread> workers = new HashMap<Minion,Thread>();
logger.debug("Created threadgroup for " + name);
for(int i = 0; i < workerCount; i++) {
// Create an instance of a worker.
Worker worker = (Worker) Class.forName(workerClass).newInstance();
worker.configure(workerConfig);
// Give it it's very own kestrel connection.
MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(workHost + ":" + workPort));
builder.setCommandFactory(new KestrelCommandFactory());
MemcachedClient client = builder.build();
client.setPrimitiveAsString(true);
client.setEnableHeartBeat(false);
client.setOpTimeout(timeout);
// Add the worker to the list so we can run it later.
Minion minion = new Minion(this.collector, client, queue, worker, timeout);
workers.put(minion, new Thread(minion));
}
this.minionGroups.put(name, workers);
logger.debug("Added worker threads to minion map.");
}
|
diff --git a/src/java/org/jivesoftware/openfire/muc/spi/IQMUCRegisterHandler.java b/src/java/org/jivesoftware/openfire/muc/spi/IQMUCRegisterHandler.java
index d9f2c7bb..abbf9597 100644
--- a/src/java/org/jivesoftware/openfire/muc/spi/IQMUCRegisterHandler.java
+++ b/src/java/org/jivesoftware/openfire/muc/spi/IQMUCRegisterHandler.java
@@ -1,209 +1,213 @@
/**
* $RCSfile$
* $Revision: 1623 $
* $Date: 2005-07-12 18:40:57 -0300 (Tue, 12 Jul 2005) $
*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.openfire.muc.spi;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.QName;
import org.jivesoftware.openfire.forms.DataForm;
import org.jivesoftware.openfire.forms.FormField;
import org.jivesoftware.openfire.forms.spi.XDataFormImpl;
import org.jivesoftware.openfire.forms.spi.XFormFieldImpl;
import org.jivesoftware.openfire.muc.ConflictException;
import org.jivesoftware.openfire.muc.ForbiddenException;
import org.jivesoftware.openfire.muc.MUCRoom;
import org.jivesoftware.openfire.muc.MultiUserChatServer;
import org.jivesoftware.util.ElementUtil;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.xmpp.packet.IQ;
import org.xmpp.packet.PacketError;
import org.xmpp.packet.Presence;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* This class is responsible for handling packets with namespace jabber:iq:register that were
* sent to the MUC service. MultiUserChatServer will receive all the IQ packets and if the
* namespace of the IQ is jabber:iq:register then this class will handle the packet.
*
* @author Gaston Dombiak
*/
class IQMUCRegisterHandler {
private static Element probeResult;
private MultiUserChatServer mucServer;
public IQMUCRegisterHandler(MultiUserChatServer mucServer) {
this.mucServer = mucServer;
initialize();
}
public void initialize() {
if (probeResult == null) {
// Create the registration form of the room which contains information
// such as: first name, last name and nickname.
XDataFormImpl registrationForm = new XDataFormImpl(DataForm.TYPE_FORM);
registrationForm.setTitle(LocaleUtils.getLocalizedString("muc.form.reg.title"));
registrationForm.addInstruction(LocaleUtils
.getLocalizedString("muc.form.reg.instruction"));
XFormFieldImpl field = new XFormFieldImpl("FORM_TYPE");
field.setType(FormField.TYPE_HIDDEN);
field.addValue("http://jabber.org/protocol/muc#register");
registrationForm.addField(field);
field = new XFormFieldImpl("muc#register_first");
field.setType(FormField.TYPE_TEXT_SINGLE);
field.setLabel(LocaleUtils.getLocalizedString("muc.form.reg.first-name"));
field.setRequired(true);
registrationForm.addField(field);
field = new XFormFieldImpl("muc#register_last");
field.setType(FormField.TYPE_TEXT_SINGLE);
field.setLabel(LocaleUtils.getLocalizedString("muc.form.reg.last-name"));
field.setRequired(true);
registrationForm.addField(field);
field = new XFormFieldImpl("muc#register_roomnick");
field.setType(FormField.TYPE_TEXT_SINGLE);
field.setLabel(LocaleUtils.getLocalizedString("muc.form.reg.nickname"));
field.setRequired(true);
registrationForm.addField(field);
field = new XFormFieldImpl("muc#register_url");
field.setType(FormField.TYPE_TEXT_SINGLE);
field.setLabel(LocaleUtils.getLocalizedString("muc.form.reg.url"));
registrationForm.addField(field);
field = new XFormFieldImpl("muc#register_email");
field.setType(FormField.TYPE_TEXT_SINGLE);
field.setLabel(LocaleUtils.getLocalizedString("muc.form.reg.email"));
registrationForm.addField(field);
field = new XFormFieldImpl("muc#register_faqentry");
field.setType(FormField.TYPE_TEXT_MULTI);
field.setLabel(LocaleUtils.getLocalizedString("muc.form.reg.faqentry"));
registrationForm.addField(field);
// Create the probeResult and add the registration form
probeResult = DocumentHelper.createElement(QName.get("query", "jabber:iq:register"));
probeResult.add(registrationForm.asXMLElement());
}
}
public IQ handleIQ(IQ packet) {
IQ reply = null;
// Get the target room
- MUCRoom room = mucServer.getChatRoom(packet.getTo().getNode());
+ MUCRoom room = null;
+ String name = packet.getTo().getNode();
+ if (name != null) {
+ room = mucServer.getChatRoom(name);
+ }
if (room == null) {
// The room doesn't exist so answer a NOT_FOUND error
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.item_not_found);
return reply;
}
else if (!room.isRegistrationEnabled()) {
// The room does not accept users to register
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.not_allowed);
return reply;
}
if (IQ.Type.get == packet.getType()) {
reply = IQ.createResultIQ(packet);
String nickname = room.getReservedNickname(packet.getFrom().toBareJID());
Element currentRegistration = probeResult.createCopy();
if (nickname != null) {
// The user is already registered with the room so answer a completed form
ElementUtil.setProperty(currentRegistration, "query.registered", null);
Element form = currentRegistration.element(QName.get("x", "jabber:x:data"));
Iterator fields = form.elementIterator("field");
Element field;
while (fields.hasNext()) {
field = (Element) fields.next();
if ("muc#register_roomnick".equals(field.attributeValue("var"))) {
field.addElement("value").addText(nickname);
}
}
reply.setChildElement(currentRegistration);
}
else {
// The user is not registered with the room so answer an empty form
reply.setChildElement(currentRegistration);
}
}
else if (IQ.Type.set == packet.getType()) {
try {
// Keep a registry of the updated presences
List<Presence> presences = new ArrayList<Presence>();
reply = IQ.createResultIQ(packet);
Element iq = packet.getChildElement();
if (ElementUtil.includesProperty(iq, "query.remove")) {
// The user is deleting his registration
presences.addAll(room.addNone(packet.getFrom().toBareJID(), room.getRole()));
}
else {
// The user is trying to register with a room
Element formElement = iq.element("x");
// Check if a form was used to provide the registration info
if (formElement != null) {
// Get the sent form
XDataFormImpl registrationForm = new XDataFormImpl();
registrationForm.parse(formElement);
// Get the desired nickname sent in the form
Iterator<String> values = registrationForm.getField("muc#register_roomnick")
.getValues();
String nickname = (values.hasNext() ? values.next() : null);
// TODO The rest of the fields of the form are ignored. If we have a
// requirement in the future where we need those fields we'll have to change
// MUCRoom.addMember in order to receive a RegistrationInfo (new class)
// Add the new member to the members list
presences.addAll(room.addMember(packet.getFrom().toBareJID(),
nickname,
room.getRole()));
}
else {
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.bad_request);
}
}
// Send the updated presences to the room occupants
for (Presence presence : presences) {
room.send(presence);
}
}
catch (ForbiddenException e) {
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.forbidden);
}
catch (ConflictException e) {
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.conflict);
}
catch (Exception e) {
Log.error(e);
}
}
return reply;
}
}
| true | true |
public IQ handleIQ(IQ packet) {
IQ reply = null;
// Get the target room
MUCRoom room = mucServer.getChatRoom(packet.getTo().getNode());
if (room == null) {
// The room doesn't exist so answer a NOT_FOUND error
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.item_not_found);
return reply;
}
else if (!room.isRegistrationEnabled()) {
// The room does not accept users to register
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.not_allowed);
return reply;
}
if (IQ.Type.get == packet.getType()) {
reply = IQ.createResultIQ(packet);
String nickname = room.getReservedNickname(packet.getFrom().toBareJID());
Element currentRegistration = probeResult.createCopy();
if (nickname != null) {
// The user is already registered with the room so answer a completed form
ElementUtil.setProperty(currentRegistration, "query.registered", null);
Element form = currentRegistration.element(QName.get("x", "jabber:x:data"));
Iterator fields = form.elementIterator("field");
Element field;
while (fields.hasNext()) {
field = (Element) fields.next();
if ("muc#register_roomnick".equals(field.attributeValue("var"))) {
field.addElement("value").addText(nickname);
}
}
reply.setChildElement(currentRegistration);
}
else {
// The user is not registered with the room so answer an empty form
reply.setChildElement(currentRegistration);
}
}
else if (IQ.Type.set == packet.getType()) {
try {
// Keep a registry of the updated presences
List<Presence> presences = new ArrayList<Presence>();
reply = IQ.createResultIQ(packet);
Element iq = packet.getChildElement();
if (ElementUtil.includesProperty(iq, "query.remove")) {
// The user is deleting his registration
presences.addAll(room.addNone(packet.getFrom().toBareJID(), room.getRole()));
}
else {
// The user is trying to register with a room
Element formElement = iq.element("x");
// Check if a form was used to provide the registration info
if (formElement != null) {
// Get the sent form
XDataFormImpl registrationForm = new XDataFormImpl();
registrationForm.parse(formElement);
// Get the desired nickname sent in the form
Iterator<String> values = registrationForm.getField("muc#register_roomnick")
.getValues();
String nickname = (values.hasNext() ? values.next() : null);
// TODO The rest of the fields of the form are ignored. If we have a
// requirement in the future where we need those fields we'll have to change
// MUCRoom.addMember in order to receive a RegistrationInfo (new class)
// Add the new member to the members list
presences.addAll(room.addMember(packet.getFrom().toBareJID(),
nickname,
room.getRole()));
}
else {
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.bad_request);
}
}
// Send the updated presences to the room occupants
for (Presence presence : presences) {
room.send(presence);
}
}
catch (ForbiddenException e) {
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.forbidden);
}
catch (ConflictException e) {
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.conflict);
}
catch (Exception e) {
Log.error(e);
}
}
return reply;
}
|
public IQ handleIQ(IQ packet) {
IQ reply = null;
// Get the target room
MUCRoom room = null;
String name = packet.getTo().getNode();
if (name != null) {
room = mucServer.getChatRoom(name);
}
if (room == null) {
// The room doesn't exist so answer a NOT_FOUND error
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.item_not_found);
return reply;
}
else if (!room.isRegistrationEnabled()) {
// The room does not accept users to register
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.not_allowed);
return reply;
}
if (IQ.Type.get == packet.getType()) {
reply = IQ.createResultIQ(packet);
String nickname = room.getReservedNickname(packet.getFrom().toBareJID());
Element currentRegistration = probeResult.createCopy();
if (nickname != null) {
// The user is already registered with the room so answer a completed form
ElementUtil.setProperty(currentRegistration, "query.registered", null);
Element form = currentRegistration.element(QName.get("x", "jabber:x:data"));
Iterator fields = form.elementIterator("field");
Element field;
while (fields.hasNext()) {
field = (Element) fields.next();
if ("muc#register_roomnick".equals(field.attributeValue("var"))) {
field.addElement("value").addText(nickname);
}
}
reply.setChildElement(currentRegistration);
}
else {
// The user is not registered with the room so answer an empty form
reply.setChildElement(currentRegistration);
}
}
else if (IQ.Type.set == packet.getType()) {
try {
// Keep a registry of the updated presences
List<Presence> presences = new ArrayList<Presence>();
reply = IQ.createResultIQ(packet);
Element iq = packet.getChildElement();
if (ElementUtil.includesProperty(iq, "query.remove")) {
// The user is deleting his registration
presences.addAll(room.addNone(packet.getFrom().toBareJID(), room.getRole()));
}
else {
// The user is trying to register with a room
Element formElement = iq.element("x");
// Check if a form was used to provide the registration info
if (formElement != null) {
// Get the sent form
XDataFormImpl registrationForm = new XDataFormImpl();
registrationForm.parse(formElement);
// Get the desired nickname sent in the form
Iterator<String> values = registrationForm.getField("muc#register_roomnick")
.getValues();
String nickname = (values.hasNext() ? values.next() : null);
// TODO The rest of the fields of the form are ignored. If we have a
// requirement in the future where we need those fields we'll have to change
// MUCRoom.addMember in order to receive a RegistrationInfo (new class)
// Add the new member to the members list
presences.addAll(room.addMember(packet.getFrom().toBareJID(),
nickname,
room.getRole()));
}
else {
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.bad_request);
}
}
// Send the updated presences to the room occupants
for (Presence presence : presences) {
room.send(presence);
}
}
catch (ForbiddenException e) {
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.forbidden);
}
catch (ConflictException e) {
reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.conflict);
}
catch (Exception e) {
Log.error(e);
}
}
return reply;
}
|
diff --git a/trunk/src/main/java/ex4/MainNode.java b/trunk/src/main/java/ex4/MainNode.java
index 249db57..278ae0c 100644
--- a/trunk/src/main/java/ex4/MainNode.java
+++ b/trunk/src/main/java/ex4/MainNode.java
@@ -1,745 +1,746 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ex4;
import ex3.PRM;
import ex3.PRMUtil;
import ex3.Vertex;
import geometry_msgs.Point;
import geometry_msgs.Pose;
import geometry_msgs.PoseStamped;
import geometry_msgs.PoseWithCovarianceStamped;
import geometry_msgs.Twist;
import java.awt.Dimension;
import java.awt.geom.Path2D;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import launcher.RunParams;
import nav_msgs.OccupancyGrid;
import nav_msgs.Odometry;
import org.ros.message.MessageFactory;
import org.ros.message.MessageListener;
import org.ros.namespace.GraphName;
import org.ros.node.AbstractNodeMain;
import org.ros.node.ConnectedNode;
import org.ros.node.NodeConfiguration;
import org.ros.node.topic.Publisher;
import org.ros.node.topic.Subscriber;
import pf.AbstractLocaliser;
import std_msgs.Float32MultiArray;
import std_msgs.Int32;
import visualization_msgs.Marker;
import visualization_msgs.MarkerArray;
/**
*
* @author HammyG
*/
public class MainNode extends AbstractNodeMain {
private enum Phase {
INITIALISATION,
FINDROOM,
SCANNINGROOM,
FACECHECKINROOM,
EXPLORING,
FACECHECK,
ROTATETOPERSON,
PRMTOPERSON,
PRMTOROOM,
INMEETINGROOM,
COMPLETED
}
public static Double INITIAL_EXPLORATION_GRID_STEP = RunParams.getDouble("INITIAL_EXPLORATION_GRID_STEP");
public static Double MINIMUM_EXPLORATION_GRID_STEP = RunParams.getDouble("MINIMUM_EXPLORATION_GRID_STEP");
public static Double GRID_SIZE_REDUCTION_STEP = RunParams.getDouble("GRID_SIZE_REDUCTION_STEP");
public static Integer FACE_CONFIRM_DETECTIONS = RunParams.getInt("FACE_CONFIRM_DETECTIONS");
public static Double MAX_RECTANGLE_CENTRE_DISPARITY = RunParams.getDouble("MAX_RECTANGLE_CENTRE_DISPARITY");
public static Double MAX_RECTANGLE_DEPTH_DISPARITY = RunParams.getDouble("MAX_RECTANGLE_DEPTH_DISPARITY");
public static Double FACE_CENTRED_THRESHOLD = RunParams.getDouble("FACE_CENTRED_THRESHOLD");
public static Double INITIAL_EXPLORATION_CELL_SIZE = RunParams.getDouble("INITIAL_EXPLORATION_CELL_SIZE");
public static Double MINIMUM_EXPLORATION_CELL_SIZE = RunParams.getDouble("MINIMUM_EXPLORATION_CELL_SIZE");
public static Double CELL_SIZE_REDUCTION_STEP = RunParams.getDouble("CELL_SIZE_REDUCTION_STEP");
public static Integer EXPLORATION_TARGET_PER_CELL = RunParams.getInt("EXPLORATION_TARGET_PER_CELL");
public static String EXPLORATION_SAMPLING = RunParams.get("EXPLORATION_SAMPLING");
private float[] lastCameraData;
private Pose lastEstimatedPose;
public double currentGridStep = INITIAL_EXPLORATION_GRID_STEP;
public double currentCellSize = INITIAL_EXPLORATION_CELL_SIZE;
private Phase currentPhase = Phase.INITIALISATION;
private int pplCount = 0;
private int targetPplCount = 3;
public ArrayList<Vertex> explorationVertices;
public int faceCheckCount;
RectangleWithDepth lastFaceRectangle;
public static MessageFactory messageFactory;
public static Dimension CAMERA_DIMENSIONS = new Dimension(640, 480);
protected Driver driver;
public PRMUtil prmUtil;
public OccupancyGrid map;
private Polygon2D[] meetingRooms;
private PoseStamped[] centreOfMeetingRooms;
private int meetingRoomIndex = -1;
private double turnRemaining = 0;
Publisher<Twist> twist_pub;
Publisher<PoseStamped> goal;
Subscriber<Odometry> odom;
Subscriber<std_msgs.Int32> prmInfo;
Subscriber<std_msgs.Float32MultiArray> cameraRectSubscriber;
Subscriber<PoseWithCovarianceStamped> estimatedPose;
Subscriber<OccupancyGrid> mapSub;
Publisher<std_msgs.Bool> navActivePub;
Publisher<MarkerArray> explorationMarkerPub;
int a = 1; // DEBUGGING. PLEASE DELETE
@Override
public void onStart(ConnectedNode connectedNode) {
//set up the message factory
messageFactory = NodeConfiguration.newPrivate().getTopicMessageFactory();
StaticMethods.messageFactory = messageFactory;
//set publisher for moving the robot
twist_pub = connectedNode.newPublisher("cmd_vel", Twist._TYPE);
// Publisher for the goal which prm shall use
goal = connectedNode.newPublisher("goal", PoseStamped._TYPE);
// Publisher to activate or deactivate navigator.
navActivePub = connectedNode.newPublisher("nav_active", std_msgs.Bool._TYPE);
explorationMarkerPub = connectedNode.newPublisher("exp_vert", MarkerArray._TYPE);
explorationMarkerPub.setLatchMode(true);
//instantiate the driver with the twist publisher
driver = new Driver(twist_pub);
// This section is initialising the position of the rooms and the rectangles of the room
// We are also hard coding the centre of the rooms
meetingRooms = new Polygon2D[2];
meetingRooms[0] = new Polygon2D(new double[]{16.115, 20.435, 18.427, 13.835}, new double[]{15.175, 10.499, 8.38, 12.992}, 4);
meetingRooms[1] = new Polygon2D(new double[]{11.993, 15.885, 13.793, 9.703}, new double[]{19.136, 15.258, 12.987, 17.096}, 4);
PoseStamped centreMeetingRoomOne = messageFactory.newFromType(PoseStamped._TYPE);
PoseStamped centreMeetingRoomTwo = messageFactory.newFromType(PoseStamped._TYPE);
centreMeetingRoomOne.getPose().getPosition().setX(17.1);
centreMeetingRoomOne.getPose().getPosition().setY(11.75);
centreMeetingRoomTwo.getPose().getPosition().setX(12.4);
centreMeetingRoomTwo.getPose().getPosition().setY(16.6);
centreOfMeetingRooms = new PoseStamped[2];
centreOfMeetingRooms[0] = centreMeetingRoomOne;
centreOfMeetingRooms[1] = centreMeetingRoomTwo;
odom = connectedNode.newSubscriber("odom", Odometry._TYPE);
odom.addMessageListener(new MessageListener<Odometry>() {
@Override
public void onNewMessage(Odometry t) {
driver.onNewOdomMessage(t);
if (currentPhase == Phase.SCANNINGROOM) {
if (driver.isTargetReached()) {
Printer.println("Driver rotation target reached", "REDB");
Printer.println("Room is free. Exploring for humans!");
initialiseExploration();
}
}
// if (lastEstimatedPose == null){
// return;
// }
// double currentHeading = getHeadingFromLastPos();
// Printer.println("Current heading is " + currentHeading, "REDF");
// if (a == 1 || driver.isTargetReached()) {
// a = 2;
// Printer.println("Initialisation rotation test...", "REDF");
// int angle = -360;
// currentHeading = getHeadingFromLastPos();
// driver.turn(currentHeading, Math.toRadians(angle));
// }
// if (currentPhase == Phase.SCANNINGROOM) {
// if (turnRemaining >= 0) {
// Printer.println("Got initial pose... Initialising exploratio", "CYANF");
//
// }
// }
}
});
prmInfo = connectedNode.newSubscriber("goalInfo", std_msgs.Int32._TYPE);
prmInfo.addMessageListener(new MessageListener<Int32>() {
@Override
public void onNewMessage(Int32 t) {
if (t.getData() == PRM.GOAL_REACHED) {
if (currentPhase == Phase.FINDROOM) {
//start scanning the room (360);
scanRoomForFace();
} else if (currentPhase == Phase.EXPLORING) {
if (explorationVertices.size() > 0) {
goToNextExplorationVertex();
} else {
// Exploration path done. Let's go again, but increase
// the granularity
if (EXPLORATION_SAMPLING.equals("cell")) {
if (currentCellSize > MINIMUM_EXPLORATION_CELL_SIZE){
currentCellSize -= CELL_SIZE_REDUCTION_STEP;
}
} else if (EXPLORATION_SAMPLING.equals("grid")) {
if (currentGridStep > MINIMUM_EXPLORATION_GRID_STEP){
currentGridStep -= GRID_SIZE_REDUCTION_STEP;
}
}
initialiseExploration();
}
} else if (currentPhase == Phase.PRMTOPERSON) {
//Ask person if they want to go to meeting room, if yes prm to room else if no turn and continue exploring
Printer.println("Person accepted invite, PRMing to meeting room", "CYANF");
prmToMeetingRoom();
} else if (currentPhase == Phase.PRMTOROOM) {
// we are at the room now, drop person off and tell them they are at meeting room and then begin exploring again
Printer.println("Currently in a room, returning to exploration", "CYANF");
pplCount++;
// Before leaving meeting room check if the task is complete, if so then print statement else continue
if (isTaskComplete()) {
Printer.println("I have completed the whole task", "GREENB");
currentPhase = Phase.COMPLETED;
} else {
+ goToNextExplorationVertex();
returnToExploration();
}
}
} else if (t.getData() == PRM.NO_PATH) {
// If we can't find a route to the exploration node, give up
// and go to the next one.
if (currentPhase == Phase.EXPLORING) {
Printer.println("PRM could not find path. Popping next vertex.", "REDF");
goToNextExplorationVertex();
}
} else if (t.getData() == PRM.PATH_FOUND) {
System.out.println("Path found.");
}
}
});
mapSub = connectedNode.newSubscriber("inflatedMap", OccupancyGrid._TYPE);
mapSub.addMessageListener(new MessageListener<OccupancyGrid>() {
@Override
public void onNewMessage(OccupancyGrid t) {
if (currentPhase == Phase.INITIALISATION) {
Printer.println("Got map in MainNode", "CYANF");
map = t;
prmUtil = new PRMUtil(new Random(), messageFactory, map);
}
}
});
//set up subscriber for the rectangles from the opencv node. Messages
// are published even if there are no faces detected, but they will be
// empty (length 0)
cameraRectSubscriber = connectedNode.newSubscriber("face_rects", std_msgs.Float32MultiArray._TYPE);
cameraRectSubscriber.addMessageListener(new MessageListener<Float32MultiArray>() {
@Override
public void onNewMessage(Float32MultiArray t) {
onNewCameraRectanglePoints(t.getData());
if (t.getData().length != 0) {
if (currentPhase == Phase.SCANNINGROOM) {
Printer.println("Scanning room found face. Pausing and investigating face", "REDF");
driver.pauseTurning();
currentPhase = Phase.FACECHECKINROOM;
}
if (currentPhase == Phase.EXPLORING) {
std_msgs.Bool deactivate = navActivePub.newMessage();
deactivate.setData(false);
navActivePub.publish(deactivate);
currentPhase = Phase.FACECHECK;
}
Printer.println("Face seen. Stopping and investigating face", "CYANF");
}
if (currentPhase == Phase.FACECHECK || currentPhase == Phase.FACECHECKINROOM) { // if we are checking faces
// if we have not received enough messages to confirm a face
if (faceCheckCount < FACE_CONFIRM_DETECTIONS) {
if (t.getData().length == 0) {
// If we receive a zero length array while we are
// attempting to confirm a face, we abandon the check.
if (currentPhase == Phase.FACECHECK) {
Printer.println("Lost face (no faces). Returning to exploration", "CYANF");
returnToExploration();
} else if (currentPhase == Phase.FACECHECKINROOM) {
Printer.println("Lost face (no faces). Continuing to scan room", "CYANF");
returnToScanningRoom();
}
}
RectangleWithDepth newFaceRect = findPerson(lastFaceRectangle);
// Check whether the rectangle received is close to the
// one we received in the previous message.
if (newFaceRect != null && (lastFaceRectangle == null || rectangleOverlapValid(lastFaceRectangle, newFaceRect))) {
faceCheckCount++;
lastFaceRectangle = newFaceRect;
Printer.println("Face matches last seen. FaceCheckCount=" + faceCheckCount, "CYANF");
} else {
// If the rectangles are too dissimilar, we return to
// the exploration phase
Printer.println("Lost face (dissimilar). Returning to exploration", "CYANF");
if (currentPhase == Phase.FACECHECKINROOM) {
returnToScanningRoom();
} else if (currentPhase == Phase.FACECHECK) {
returnToExploration();
}
return;
}
}
// If we have made enough detections to confirm a face,
// set phase to rotate to person
if (faceCheckCount == FACE_CONFIRM_DETECTIONS) {
faceCheckCount = 0;
if (currentPhase == Phase.FACECHECKINROOM) {
if (meetingRoomIndex < meetingRooms.length) {
findEmptyRoom();
Printer.println("Face confirmed, therefore meeting room is not empty. Finding new meeting room.", "CYANF");
} else {
Printer.println("Face confirmed, therefore meeting room is not empty. No more rooms remaining.", "REDB");
}
} else if (currentPhase == Phase.FACECHECK) {
currentPhase = Phase.ROTATETOPERSON;
rotateTowardsPerson(findPerson(lastFaceRectangle));
Printer.println("Face confirmed. Rotating to person", "CYANF");
}
}
}
if (currentPhase == Phase.ROTATETOPERSON) {
if (t.getData().length == 0) {
Printer.println("Person lost while rotating - returning to exploration.", "CYANF");
driver.stopTurning();
returnToExploration();
return;
}
// If we've not yet reached the target angle, then return.
// note that the rotation is done in small increments, so
// the initial target is not necessarily the full rotation to
// the heading which faces the person.
if (!driver.isTargetReached()) {
return;
}
if (isFaceCentred(lastFaceRectangle)) {
Printer.println("Face in centre. PRMing to person", "CYANF");
currentPhase = Phase.PRMTOPERSON;
setPRMGoal(getObjectLocation(lastEstimatedPose, lastFaceRectangle.depth));
} else {
RectangleWithDepth rect = findPerson(lastFaceRectangle);
if (rect != null){
Printer.println("Face rectangle received was null. Returning to exploration.", "CYANF");
} else {
Printer.println("Face not in centre. Rotating towards person again", "CYANF");
rotateTowardsPerson(rect);
}
}
}
}
});
//set the subscriber for the estimated pose
estimatedPose = connectedNode.newSubscriber("amcl_pose", PoseWithCovarianceStamped._TYPE);
estimatedPose.addMessageListener(new MessageListener<PoseWithCovarianceStamped>() {
@Override
public void onNewMessage(PoseWithCovarianceStamped message) {
lastEstimatedPose = StaticMethods.copyPose(message.getPose().getPose());
if (currentPhase == Phase.INITIALISATION && map != null) {
//driver.onNewEstimatedPose(lastEstimatedPose);
findEmptyRoom();
//initialiseExploration();
}
}
});
Printer.println("MainNode initialised", "CYANF");
}
public double getHeadingFromLastPos() {
return AbstractLocaliser.getHeading(lastEstimatedPose.getOrientation());
}
public void findEmptyRoom() {
Printer.println("Kicking off find-room phase","CYANF");
currentPhase = Phase.FINDROOM;
meetingRoomIndex++;
if (PRMUtil.getEuclideanDistance(centreOfMeetingRooms[0].getPose().getPosition(), lastEstimatedPose.getPosition()) >
PRMUtil.getEuclideanDistance(centreOfMeetingRooms[1].getPose().getPosition(), lastEstimatedPose.getPosition())){
Printer.println("Room 1 was closer than room 0. Going to room 1.", "CYANF");
PoseStamped tmp = centreOfMeetingRooms[0];
centreOfMeetingRooms[0] = centreOfMeetingRooms[1];
centreOfMeetingRooms[1] = tmp;
}
if (meetingRoomIndex >= centreOfMeetingRooms.length) {
// No more free rooms! Panic
Printer.println("NO FREE ROOMS! Exiting :(", "REDB");
System.exit(0);
}
setPRMGoal(centreOfMeetingRooms[meetingRoomIndex]);
}
public void scanRoomForFace() {
Printer.println("Scanning room for face","CYANF");
currentPhase = Phase.SCANNINGROOM;
turnRemaining = Math.PI * 2;
driver.turn(getHeadingFromLastPos(), turnRemaining);
}
public void returnToScanningRoom() {
//driver.turn(turnRemaining, false, false);
//driver.turn(getHeadingFromLastPos(), turnRemaining);
currentPhase = Phase.SCANNINGROOM;
driver.resumeTurning();
lastFaceRectangle = null;
faceCheckCount = 0;
}
/*
* Returns the node state to exploration phase from the facecheck phase
*/
public void returnToExploration() {
std_msgs.Bool activate = navActivePub.newMessage();
activate.setData(true);
navActivePub.publish(activate);
currentPhase = Phase.EXPLORING;
lastFaceRectangle = null;
faceCheckCount = 0;
}
/*
* Called when we have received a map in order to initialise the structures
* needed to perform exploration of the map.
*/
public void initialiseExploration() {
ArrayList<Vertex> vertices = null;
if (EXPLORATION_SAMPLING.equals("grid")) {
vertices = prmUtil.gridSample(map,
currentGridStep, currentGridStep);
} else if (EXPLORATION_SAMPLING.equals("cell")) {
vertices = prmUtil.cellSample(map,
currentCellSize, EXPLORATION_TARGET_PER_CELL);
}
explorationVertices = getExplorationPath(lastEstimatedPose, vertices);
removeVerticesInMeetingRooms(explorationVertices);
currentPhase = Phase.EXPLORING;
MarkerArray markers = explorationMarkerPub.newMessage();
Marker m = prmUtil.makePathMarker(explorationVertices, "expvert", null, 23);
ArrayList<Marker> mlist = new ArrayList<Marker>();
mlist.add(m);
markers.setMarkers(mlist);
explorationMarkerPub.publish(markers);
goToNextExplorationVertex();
Printer.println("Exploratio initialised and markers published", "CYANF");
}
public ArrayList<Vertex> getExplorationPath(Pose startPose, ArrayList<Vertex> vertices) {
ArrayList<Vertex> explorePath = new ArrayList<Vertex>(vertices.size());
Point curPoint = startPose.getPosition();
while (vertices.size() > 0) {
int minIndex = -1;
double minDist = Double.MAX_VALUE;
for (int i = 0; i < vertices.size(); i++) {
double thisDist = PRMUtil.getEuclideanDistance(curPoint, vertices.get(i).getLocation());
if (thisDist < minDist) {
minIndex = i;
minDist = thisDist;
}
}
Vertex curVertex = vertices.remove(minIndex);
curPoint = curVertex.getLocation();
explorePath.add(curVertex);
}
return explorePath;
}
/*
* Send a goal message to the PRM containing the next position that the
* explorer should go to.
*/
public void goToNextExplorationVertex() {
Printer.println("Going to next exploration vertex.", "REDF");
Vertex nextVertex = this.explorationVertices.remove(0);
PoseStamped goalPose = messageFactory.newFromType(PoseStamped._TYPE);
goalPose.getPose().setPosition(nextVertex.getLocation());
setPRMGoal(goalPose);
}
/**
* Removes exploration vertices which exist within the meeting room as meeting room does not need to be explored
* counter used to tell us how many have been removed
*/
public void removeVerticesInMeetingRooms(ArrayList<Vertex> vertices) {
int removedCounter = 0;
for (int i = vertices.size() - 1; i >= 0; i--) {
// if vertex is within meeting room, then remove the vertex so it is not explored
Vertex nextVertex = vertices.get(i);
for (int j = 0; j < meetingRooms.length; j++) {
if (meetingRooms[j].contains(nextVertex.getLocation().getX(), nextVertex.getLocation().getY())) {
vertices.remove(i);
removedCounter++;
// A vertex can only be in a single meeting room (assuming
// non-overlapping rooms), so don't bother checking other ones
break;
}
}
}
Printer.println("removed " + removedCounter + " vertices found inside meeting rooms", "CYANF");
}
/**
* Change current phase to prm to meeting room
* set the PRM goal to be the location of the empty meeting room
*/
private void prmToMeetingRoom() {
currentPhase = Phase.PRMTOROOM;
setPRMGoal(centreOfMeetingRooms[meetingRoomIndex]);
}
/*
public void start() {
meetingRoomLocation = messageFactory.newFromType(PoseStamped._TYPE);
while (meetingRoomLocation == null) {
//find room
}
while (currentPhase != Phase.COMPLETED) {
currentPhase = Phase.EXPLORING;
RectangleWithDepth areaOfPerson = findPerson(null);
double areaCenterX = areaOfPerson.getCenterX();
double fromCenterX = areaCenterX - (CAMERA_DIMENSIONS.width / 2);
double turnAngle = Math.toRadians(10);
while (Math.abs(fromCenterX) > 10) {
if (fromCenterX > 0) {
//rectangle on the right
driver.turn(-turnAngle, true, true);
} else {
//rectangle on left
driver.turn(turnAngle, true, true);
}
areaOfPerson = findPerson(null);
}
currentPhase = Phase.PRMTOPERSON;
Pose estimatedPoseCopy = StaticMethods.copyPose(lastEstimatedPose);
PoseStamped personLocation = getObjectLocation(estimatedPoseCopy, areaOfPerson.depth);
setPRMGoal(personLocation);
if (personLost()) {
continue;
}
if (personAcceptsInvite()) {
currentPhase = Phase.PRMTOROOM;
setPRMGoal(meetingRoomLocation);
pplCount++;
currentPhase = Phase.INMEETINGROOM;
if (isTaskComplete()) {
currentPhase = Phase.COMPLETED;
} else {
//currently within meeting room
//get out of meeting room
}
} else {
//person did not accept invite
//turn away from the person
}
}
}
*/
private boolean isTaskComplete() {
//extend to add 15min time limit and/or other limits
return pplCount == targetPplCount;
}
/*
* Find the rectangle in the array closest to the one that we received
* previously. Otherwise, we select the closest rectangle to track.
*/
private RectangleWithDepth findPerson(RectangleWithDepth previousRect) {
float[] cameraDataCopy = Arrays.copyOf(lastCameraData, lastCameraData.length);
RectangleWithDepth[] rectangles = convert(cameraDataCopy);
if (previousRect == null) {
return getClosestRectangle(rectangles);
} else {
// find the rectangle that is the closest match to the one that we
// received as a parameter
return getMostSimilarRectangle(rectangles, previousRect);
}
}
/*
* Checks the disparity between two rectangles is below the value specified
* in the parameter file.
*/
public boolean rectangleOverlapValid(RectangleWithDepth lastRect, RectangleWithDepth curRect) {
Point lastCentre = getRectCentre(lastRect);
Point curCentre = getRectCentre(curRect);
double xDisparity = Math.abs(curCentre.getX() - lastCentre.getX());
double yDisparity = Math.abs(curCentre.getY() - lastCentre.getY());
boolean xValid = xDisparity <= (MAX_RECTANGLE_CENTRE_DISPARITY * curRect.width);
boolean yValid = yDisparity <= (MAX_RECTANGLE_CENTRE_DISPARITY * curRect.height);
return xValid && yValid;
}
public Point getRectCentre(RectangleWithDepth rect) {
Point centre = messageFactory.newFromType(Point._TYPE);
double lastX = rect.x + rect.width / 2;
double lastY = rect.y + rect.height / 2;
centre.setX(lastX);
centre.setY(lastY);
return centre;
}
/*
* Checks whether the centre point of curRect is within the rectangle lastRect.
*/
public boolean checkPointCentreInRectangle(RectangleWithDepth lastRect, RectangleWithDepth curRect) {
Point centre = getRectCentre(curRect);
boolean xInRect = centre.getX() > lastRect.x && centre.getX() < lastRect.x + lastRect.width;
boolean yInRect = centre.getY() > lastRect.y && centre.getY() < lastRect.y + lastRect.height;
return xInRect && yInRect;
}
/*
* Checks whether the rectangle defining the face detection is withing some
* distance of the centre of the image.
*/
public boolean isFaceCentred(RectangleWithDepth personDetection) {
Point centre = getRectCentre(personDetection);
return Math.abs(centre.getX() - (CAMERA_DIMENSIONS.width / 2)) < FACE_CENTRED_THRESHOLD * CAMERA_DIMENSIONS.width;
}
public void rotateTowardsPerson(RectangleWithDepth lastRectangle) {
double areaCentreX = lastRectangle.getCenterX();
double distFromCentreX = areaCentreX - (CAMERA_DIMENSIONS.width / 2);
Printer.println("DistFromCentreX: " + distFromCentreX, "CYANF");
double turnAngle = Math.toRadians(10);
if (distFromCentreX > 0) {
//rectangle on the right
//driver.turn(-turnAngle, true, false);
driver.turn(getHeadingFromLastPos(), -turnAngle);
} else {
//rectangle on left
//driver.turn(turnAngle, true, false);
driver.turn(getHeadingFromLastPos(), turnAngle);
}
}
private RectangleWithDepth[] convert(float[] data) {
int numberOfRectangles = (int) (data.length / 5.0);
RectangleWithDepth[] result = new RectangleWithDepth[numberOfRectangles];
for (int i = 0; i < numberOfRectangles; i++) {
int index = i * 5;
result[i] = new RectangleWithDepth(
data[index],
data[index + 1],
data[index + 2],
data[index + 3],
data[index + 4]);
}
return result;
}
/*
* Find the rectangle in the array that has the smallest depth.
*/
private RectangleWithDepth getClosestRectangle(RectangleWithDepth[] rectangles) {
RectangleWithDepth closestRect = null;
for (RectangleWithDepth rect : rectangles) {
if (closestRect == null || rect.getDepth() < closestRect.getDepth()) {
closestRect = rect;
}
}
return closestRect;
}
/*
* Finds the rectangle in the array that is most similar to the rectangle
* given.
*/
private RectangleWithDepth getMostSimilarRectangle(RectangleWithDepth[] rectangles,
RectangleWithDepth testRect) {
RectangleWithDepth mostSimilar = null;
double similarDist = Double.MAX_VALUE;
for (RectangleWithDepth rect : rectangles) {
Point thisCentre = getRectCentre(rect);
Point testCentre = getRectCentre(testRect);
double msgDepth = rect.depth;
double testDepth = testRect.depth;
double thisDist = PRMUtil.getEuclideanDistance(testCentre, thisCentre);
if (thisDist < similarDist && Math.abs(msgDepth - testDepth) <= MAX_RECTANGLE_DEPTH_DISPARITY) {
mostSimilar = rect;
similarDist = thisDist;
}
}
return mostSimilar;
}
/*
* Calculates the position of a detected visual feature which is directly
* in front of the robot.
*/
private PoseStamped getObjectLocation(Pose estimatedPoseCopy, double depth) {
PoseStamped personLocation = messageFactory.newFromType(PoseStamped._TYPE);
double heading = StaticMethods.getHeading(estimatedPoseCopy.getOrientation());
personLocation.getPose().getPosition().setX(
estimatedPoseCopy.getPosition().getX()
+ (depth * Math.cos(heading)));
personLocation.getPose().getPosition().setY(
estimatedPoseCopy.getPosition().getY()
+ (depth * Math.sin(heading)));
return personLocation;
}
private boolean personLost() {
return false;
}
private boolean personAcceptsInvite() {
return false;
}
private void setPRMGoal(PoseStamped targetLocation) {
goal.publish(targetLocation);
}
/*
public void updateMeetingRoomLocation(Point location) {
meetingRoomLocation.getPose().setPosition(location);
}
*/
public void onNewCameraRectanglePoints(float[] data) {
lastCameraData = data;
}
public void onNewEstimatedPose(Pose estimatedPose) {
lastEstimatedPose = estimatedPose;
}
@Override
public GraphName getDefaultNodeName() {
return GraphName.of("Arbitrator");
}
}
| true | true |
public void onStart(ConnectedNode connectedNode) {
//set up the message factory
messageFactory = NodeConfiguration.newPrivate().getTopicMessageFactory();
StaticMethods.messageFactory = messageFactory;
//set publisher for moving the robot
twist_pub = connectedNode.newPublisher("cmd_vel", Twist._TYPE);
// Publisher for the goal which prm shall use
goal = connectedNode.newPublisher("goal", PoseStamped._TYPE);
// Publisher to activate or deactivate navigator.
navActivePub = connectedNode.newPublisher("nav_active", std_msgs.Bool._TYPE);
explorationMarkerPub = connectedNode.newPublisher("exp_vert", MarkerArray._TYPE);
explorationMarkerPub.setLatchMode(true);
//instantiate the driver with the twist publisher
driver = new Driver(twist_pub);
// This section is initialising the position of the rooms and the rectangles of the room
// We are also hard coding the centre of the rooms
meetingRooms = new Polygon2D[2];
meetingRooms[0] = new Polygon2D(new double[]{16.115, 20.435, 18.427, 13.835}, new double[]{15.175, 10.499, 8.38, 12.992}, 4);
meetingRooms[1] = new Polygon2D(new double[]{11.993, 15.885, 13.793, 9.703}, new double[]{19.136, 15.258, 12.987, 17.096}, 4);
PoseStamped centreMeetingRoomOne = messageFactory.newFromType(PoseStamped._TYPE);
PoseStamped centreMeetingRoomTwo = messageFactory.newFromType(PoseStamped._TYPE);
centreMeetingRoomOne.getPose().getPosition().setX(17.1);
centreMeetingRoomOne.getPose().getPosition().setY(11.75);
centreMeetingRoomTwo.getPose().getPosition().setX(12.4);
centreMeetingRoomTwo.getPose().getPosition().setY(16.6);
centreOfMeetingRooms = new PoseStamped[2];
centreOfMeetingRooms[0] = centreMeetingRoomOne;
centreOfMeetingRooms[1] = centreMeetingRoomTwo;
odom = connectedNode.newSubscriber("odom", Odometry._TYPE);
odom.addMessageListener(new MessageListener<Odometry>() {
@Override
public void onNewMessage(Odometry t) {
driver.onNewOdomMessage(t);
if (currentPhase == Phase.SCANNINGROOM) {
if (driver.isTargetReached()) {
Printer.println("Driver rotation target reached", "REDB");
Printer.println("Room is free. Exploring for humans!");
initialiseExploration();
}
}
// if (lastEstimatedPose == null){
// return;
// }
// double currentHeading = getHeadingFromLastPos();
// Printer.println("Current heading is " + currentHeading, "REDF");
// if (a == 1 || driver.isTargetReached()) {
// a = 2;
// Printer.println("Initialisation rotation test...", "REDF");
// int angle = -360;
// currentHeading = getHeadingFromLastPos();
// driver.turn(currentHeading, Math.toRadians(angle));
// }
// if (currentPhase == Phase.SCANNINGROOM) {
// if (turnRemaining >= 0) {
// Printer.println("Got initial pose... Initialising exploratio", "CYANF");
//
// }
// }
}
});
prmInfo = connectedNode.newSubscriber("goalInfo", std_msgs.Int32._TYPE);
prmInfo.addMessageListener(new MessageListener<Int32>() {
@Override
public void onNewMessage(Int32 t) {
if (t.getData() == PRM.GOAL_REACHED) {
if (currentPhase == Phase.FINDROOM) {
//start scanning the room (360);
scanRoomForFace();
} else if (currentPhase == Phase.EXPLORING) {
if (explorationVertices.size() > 0) {
goToNextExplorationVertex();
} else {
// Exploration path done. Let's go again, but increase
// the granularity
if (EXPLORATION_SAMPLING.equals("cell")) {
if (currentCellSize > MINIMUM_EXPLORATION_CELL_SIZE){
currentCellSize -= CELL_SIZE_REDUCTION_STEP;
}
} else if (EXPLORATION_SAMPLING.equals("grid")) {
if (currentGridStep > MINIMUM_EXPLORATION_GRID_STEP){
currentGridStep -= GRID_SIZE_REDUCTION_STEP;
}
}
initialiseExploration();
}
} else if (currentPhase == Phase.PRMTOPERSON) {
//Ask person if they want to go to meeting room, if yes prm to room else if no turn and continue exploring
Printer.println("Person accepted invite, PRMing to meeting room", "CYANF");
prmToMeetingRoom();
} else if (currentPhase == Phase.PRMTOROOM) {
// we are at the room now, drop person off and tell them they are at meeting room and then begin exploring again
Printer.println("Currently in a room, returning to exploration", "CYANF");
pplCount++;
// Before leaving meeting room check if the task is complete, if so then print statement else continue
if (isTaskComplete()) {
Printer.println("I have completed the whole task", "GREENB");
currentPhase = Phase.COMPLETED;
} else {
returnToExploration();
}
}
} else if (t.getData() == PRM.NO_PATH) {
// If we can't find a route to the exploration node, give up
// and go to the next one.
if (currentPhase == Phase.EXPLORING) {
Printer.println("PRM could not find path. Popping next vertex.", "REDF");
goToNextExplorationVertex();
}
} else if (t.getData() == PRM.PATH_FOUND) {
System.out.println("Path found.");
}
}
});
mapSub = connectedNode.newSubscriber("inflatedMap", OccupancyGrid._TYPE);
mapSub.addMessageListener(new MessageListener<OccupancyGrid>() {
@Override
public void onNewMessage(OccupancyGrid t) {
if (currentPhase == Phase.INITIALISATION) {
Printer.println("Got map in MainNode", "CYANF");
map = t;
prmUtil = new PRMUtil(new Random(), messageFactory, map);
}
}
});
//set up subscriber for the rectangles from the opencv node. Messages
// are published even if there are no faces detected, but they will be
// empty (length 0)
cameraRectSubscriber = connectedNode.newSubscriber("face_rects", std_msgs.Float32MultiArray._TYPE);
cameraRectSubscriber.addMessageListener(new MessageListener<Float32MultiArray>() {
@Override
public void onNewMessage(Float32MultiArray t) {
onNewCameraRectanglePoints(t.getData());
if (t.getData().length != 0) {
if (currentPhase == Phase.SCANNINGROOM) {
Printer.println("Scanning room found face. Pausing and investigating face", "REDF");
driver.pauseTurning();
currentPhase = Phase.FACECHECKINROOM;
}
if (currentPhase == Phase.EXPLORING) {
std_msgs.Bool deactivate = navActivePub.newMessage();
deactivate.setData(false);
navActivePub.publish(deactivate);
currentPhase = Phase.FACECHECK;
}
Printer.println("Face seen. Stopping and investigating face", "CYANF");
}
if (currentPhase == Phase.FACECHECK || currentPhase == Phase.FACECHECKINROOM) { // if we are checking faces
// if we have not received enough messages to confirm a face
if (faceCheckCount < FACE_CONFIRM_DETECTIONS) {
if (t.getData().length == 0) {
// If we receive a zero length array while we are
// attempting to confirm a face, we abandon the check.
if (currentPhase == Phase.FACECHECK) {
Printer.println("Lost face (no faces). Returning to exploration", "CYANF");
returnToExploration();
} else if (currentPhase == Phase.FACECHECKINROOM) {
Printer.println("Lost face (no faces). Continuing to scan room", "CYANF");
returnToScanningRoom();
}
}
RectangleWithDepth newFaceRect = findPerson(lastFaceRectangle);
// Check whether the rectangle received is close to the
// one we received in the previous message.
if (newFaceRect != null && (lastFaceRectangle == null || rectangleOverlapValid(lastFaceRectangle, newFaceRect))) {
faceCheckCount++;
lastFaceRectangle = newFaceRect;
Printer.println("Face matches last seen. FaceCheckCount=" + faceCheckCount, "CYANF");
} else {
// If the rectangles are too dissimilar, we return to
// the exploration phase
Printer.println("Lost face (dissimilar). Returning to exploration", "CYANF");
if (currentPhase == Phase.FACECHECKINROOM) {
returnToScanningRoom();
} else if (currentPhase == Phase.FACECHECK) {
returnToExploration();
}
return;
}
}
// If we have made enough detections to confirm a face,
// set phase to rotate to person
if (faceCheckCount == FACE_CONFIRM_DETECTIONS) {
faceCheckCount = 0;
if (currentPhase == Phase.FACECHECKINROOM) {
if (meetingRoomIndex < meetingRooms.length) {
findEmptyRoom();
Printer.println("Face confirmed, therefore meeting room is not empty. Finding new meeting room.", "CYANF");
} else {
Printer.println("Face confirmed, therefore meeting room is not empty. No more rooms remaining.", "REDB");
}
} else if (currentPhase == Phase.FACECHECK) {
currentPhase = Phase.ROTATETOPERSON;
rotateTowardsPerson(findPerson(lastFaceRectangle));
Printer.println("Face confirmed. Rotating to person", "CYANF");
}
}
}
if (currentPhase == Phase.ROTATETOPERSON) {
if (t.getData().length == 0) {
Printer.println("Person lost while rotating - returning to exploration.", "CYANF");
driver.stopTurning();
returnToExploration();
return;
}
// If we've not yet reached the target angle, then return.
// note that the rotation is done in small increments, so
// the initial target is not necessarily the full rotation to
// the heading which faces the person.
if (!driver.isTargetReached()) {
return;
}
if (isFaceCentred(lastFaceRectangle)) {
Printer.println("Face in centre. PRMing to person", "CYANF");
currentPhase = Phase.PRMTOPERSON;
setPRMGoal(getObjectLocation(lastEstimatedPose, lastFaceRectangle.depth));
} else {
RectangleWithDepth rect = findPerson(lastFaceRectangle);
if (rect != null){
Printer.println("Face rectangle received was null. Returning to exploration.", "CYANF");
} else {
Printer.println("Face not in centre. Rotating towards person again", "CYANF");
rotateTowardsPerson(rect);
}
}
}
}
});
//set the subscriber for the estimated pose
estimatedPose = connectedNode.newSubscriber("amcl_pose", PoseWithCovarianceStamped._TYPE);
estimatedPose.addMessageListener(new MessageListener<PoseWithCovarianceStamped>() {
@Override
public void onNewMessage(PoseWithCovarianceStamped message) {
lastEstimatedPose = StaticMethods.copyPose(message.getPose().getPose());
if (currentPhase == Phase.INITIALISATION && map != null) {
//driver.onNewEstimatedPose(lastEstimatedPose);
findEmptyRoom();
//initialiseExploration();
}
}
});
Printer.println("MainNode initialised", "CYANF");
}
|
public void onStart(ConnectedNode connectedNode) {
//set up the message factory
messageFactory = NodeConfiguration.newPrivate().getTopicMessageFactory();
StaticMethods.messageFactory = messageFactory;
//set publisher for moving the robot
twist_pub = connectedNode.newPublisher("cmd_vel", Twist._TYPE);
// Publisher for the goal which prm shall use
goal = connectedNode.newPublisher("goal", PoseStamped._TYPE);
// Publisher to activate or deactivate navigator.
navActivePub = connectedNode.newPublisher("nav_active", std_msgs.Bool._TYPE);
explorationMarkerPub = connectedNode.newPublisher("exp_vert", MarkerArray._TYPE);
explorationMarkerPub.setLatchMode(true);
//instantiate the driver with the twist publisher
driver = new Driver(twist_pub);
// This section is initialising the position of the rooms and the rectangles of the room
// We are also hard coding the centre of the rooms
meetingRooms = new Polygon2D[2];
meetingRooms[0] = new Polygon2D(new double[]{16.115, 20.435, 18.427, 13.835}, new double[]{15.175, 10.499, 8.38, 12.992}, 4);
meetingRooms[1] = new Polygon2D(new double[]{11.993, 15.885, 13.793, 9.703}, new double[]{19.136, 15.258, 12.987, 17.096}, 4);
PoseStamped centreMeetingRoomOne = messageFactory.newFromType(PoseStamped._TYPE);
PoseStamped centreMeetingRoomTwo = messageFactory.newFromType(PoseStamped._TYPE);
centreMeetingRoomOne.getPose().getPosition().setX(17.1);
centreMeetingRoomOne.getPose().getPosition().setY(11.75);
centreMeetingRoomTwo.getPose().getPosition().setX(12.4);
centreMeetingRoomTwo.getPose().getPosition().setY(16.6);
centreOfMeetingRooms = new PoseStamped[2];
centreOfMeetingRooms[0] = centreMeetingRoomOne;
centreOfMeetingRooms[1] = centreMeetingRoomTwo;
odom = connectedNode.newSubscriber("odom", Odometry._TYPE);
odom.addMessageListener(new MessageListener<Odometry>() {
@Override
public void onNewMessage(Odometry t) {
driver.onNewOdomMessage(t);
if (currentPhase == Phase.SCANNINGROOM) {
if (driver.isTargetReached()) {
Printer.println("Driver rotation target reached", "REDB");
Printer.println("Room is free. Exploring for humans!");
initialiseExploration();
}
}
// if (lastEstimatedPose == null){
// return;
// }
// double currentHeading = getHeadingFromLastPos();
// Printer.println("Current heading is " + currentHeading, "REDF");
// if (a == 1 || driver.isTargetReached()) {
// a = 2;
// Printer.println("Initialisation rotation test...", "REDF");
// int angle = -360;
// currentHeading = getHeadingFromLastPos();
// driver.turn(currentHeading, Math.toRadians(angle));
// }
// if (currentPhase == Phase.SCANNINGROOM) {
// if (turnRemaining >= 0) {
// Printer.println("Got initial pose... Initialising exploratio", "CYANF");
//
// }
// }
}
});
prmInfo = connectedNode.newSubscriber("goalInfo", std_msgs.Int32._TYPE);
prmInfo.addMessageListener(new MessageListener<Int32>() {
@Override
public void onNewMessage(Int32 t) {
if (t.getData() == PRM.GOAL_REACHED) {
if (currentPhase == Phase.FINDROOM) {
//start scanning the room (360);
scanRoomForFace();
} else if (currentPhase == Phase.EXPLORING) {
if (explorationVertices.size() > 0) {
goToNextExplorationVertex();
} else {
// Exploration path done. Let's go again, but increase
// the granularity
if (EXPLORATION_SAMPLING.equals("cell")) {
if (currentCellSize > MINIMUM_EXPLORATION_CELL_SIZE){
currentCellSize -= CELL_SIZE_REDUCTION_STEP;
}
} else if (EXPLORATION_SAMPLING.equals("grid")) {
if (currentGridStep > MINIMUM_EXPLORATION_GRID_STEP){
currentGridStep -= GRID_SIZE_REDUCTION_STEP;
}
}
initialiseExploration();
}
} else if (currentPhase == Phase.PRMTOPERSON) {
//Ask person if they want to go to meeting room, if yes prm to room else if no turn and continue exploring
Printer.println("Person accepted invite, PRMing to meeting room", "CYANF");
prmToMeetingRoom();
} else if (currentPhase == Phase.PRMTOROOM) {
// we are at the room now, drop person off and tell them they are at meeting room and then begin exploring again
Printer.println("Currently in a room, returning to exploration", "CYANF");
pplCount++;
// Before leaving meeting room check if the task is complete, if so then print statement else continue
if (isTaskComplete()) {
Printer.println("I have completed the whole task", "GREENB");
currentPhase = Phase.COMPLETED;
} else {
goToNextExplorationVertex();
returnToExploration();
}
}
} else if (t.getData() == PRM.NO_PATH) {
// If we can't find a route to the exploration node, give up
// and go to the next one.
if (currentPhase == Phase.EXPLORING) {
Printer.println("PRM could not find path. Popping next vertex.", "REDF");
goToNextExplorationVertex();
}
} else if (t.getData() == PRM.PATH_FOUND) {
System.out.println("Path found.");
}
}
});
mapSub = connectedNode.newSubscriber("inflatedMap", OccupancyGrid._TYPE);
mapSub.addMessageListener(new MessageListener<OccupancyGrid>() {
@Override
public void onNewMessage(OccupancyGrid t) {
if (currentPhase == Phase.INITIALISATION) {
Printer.println("Got map in MainNode", "CYANF");
map = t;
prmUtil = new PRMUtil(new Random(), messageFactory, map);
}
}
});
//set up subscriber for the rectangles from the opencv node. Messages
// are published even if there are no faces detected, but they will be
// empty (length 0)
cameraRectSubscriber = connectedNode.newSubscriber("face_rects", std_msgs.Float32MultiArray._TYPE);
cameraRectSubscriber.addMessageListener(new MessageListener<Float32MultiArray>() {
@Override
public void onNewMessage(Float32MultiArray t) {
onNewCameraRectanglePoints(t.getData());
if (t.getData().length != 0) {
if (currentPhase == Phase.SCANNINGROOM) {
Printer.println("Scanning room found face. Pausing and investigating face", "REDF");
driver.pauseTurning();
currentPhase = Phase.FACECHECKINROOM;
}
if (currentPhase == Phase.EXPLORING) {
std_msgs.Bool deactivate = navActivePub.newMessage();
deactivate.setData(false);
navActivePub.publish(deactivate);
currentPhase = Phase.FACECHECK;
}
Printer.println("Face seen. Stopping and investigating face", "CYANF");
}
if (currentPhase == Phase.FACECHECK || currentPhase == Phase.FACECHECKINROOM) { // if we are checking faces
// if we have not received enough messages to confirm a face
if (faceCheckCount < FACE_CONFIRM_DETECTIONS) {
if (t.getData().length == 0) {
// If we receive a zero length array while we are
// attempting to confirm a face, we abandon the check.
if (currentPhase == Phase.FACECHECK) {
Printer.println("Lost face (no faces). Returning to exploration", "CYANF");
returnToExploration();
} else if (currentPhase == Phase.FACECHECKINROOM) {
Printer.println("Lost face (no faces). Continuing to scan room", "CYANF");
returnToScanningRoom();
}
}
RectangleWithDepth newFaceRect = findPerson(lastFaceRectangle);
// Check whether the rectangle received is close to the
// one we received in the previous message.
if (newFaceRect != null && (lastFaceRectangle == null || rectangleOverlapValid(lastFaceRectangle, newFaceRect))) {
faceCheckCount++;
lastFaceRectangle = newFaceRect;
Printer.println("Face matches last seen. FaceCheckCount=" + faceCheckCount, "CYANF");
} else {
// If the rectangles are too dissimilar, we return to
// the exploration phase
Printer.println("Lost face (dissimilar). Returning to exploration", "CYANF");
if (currentPhase == Phase.FACECHECKINROOM) {
returnToScanningRoom();
} else if (currentPhase == Phase.FACECHECK) {
returnToExploration();
}
return;
}
}
// If we have made enough detections to confirm a face,
// set phase to rotate to person
if (faceCheckCount == FACE_CONFIRM_DETECTIONS) {
faceCheckCount = 0;
if (currentPhase == Phase.FACECHECKINROOM) {
if (meetingRoomIndex < meetingRooms.length) {
findEmptyRoom();
Printer.println("Face confirmed, therefore meeting room is not empty. Finding new meeting room.", "CYANF");
} else {
Printer.println("Face confirmed, therefore meeting room is not empty. No more rooms remaining.", "REDB");
}
} else if (currentPhase == Phase.FACECHECK) {
currentPhase = Phase.ROTATETOPERSON;
rotateTowardsPerson(findPerson(lastFaceRectangle));
Printer.println("Face confirmed. Rotating to person", "CYANF");
}
}
}
if (currentPhase == Phase.ROTATETOPERSON) {
if (t.getData().length == 0) {
Printer.println("Person lost while rotating - returning to exploration.", "CYANF");
driver.stopTurning();
returnToExploration();
return;
}
// If we've not yet reached the target angle, then return.
// note that the rotation is done in small increments, so
// the initial target is not necessarily the full rotation to
// the heading which faces the person.
if (!driver.isTargetReached()) {
return;
}
if (isFaceCentred(lastFaceRectangle)) {
Printer.println("Face in centre. PRMing to person", "CYANF");
currentPhase = Phase.PRMTOPERSON;
setPRMGoal(getObjectLocation(lastEstimatedPose, lastFaceRectangle.depth));
} else {
RectangleWithDepth rect = findPerson(lastFaceRectangle);
if (rect != null){
Printer.println("Face rectangle received was null. Returning to exploration.", "CYANF");
} else {
Printer.println("Face not in centre. Rotating towards person again", "CYANF");
rotateTowardsPerson(rect);
}
}
}
}
});
//set the subscriber for the estimated pose
estimatedPose = connectedNode.newSubscriber("amcl_pose", PoseWithCovarianceStamped._TYPE);
estimatedPose.addMessageListener(new MessageListener<PoseWithCovarianceStamped>() {
@Override
public void onNewMessage(PoseWithCovarianceStamped message) {
lastEstimatedPose = StaticMethods.copyPose(message.getPose().getPose());
if (currentPhase == Phase.INITIALISATION && map != null) {
//driver.onNewEstimatedPose(lastEstimatedPose);
findEmptyRoom();
//initialiseExploration();
}
}
});
Printer.println("MainNode initialised", "CYANF");
}
|
diff --git a/src/main/java/org/powertac/factoredcustomer/DefaultUtilityOptimizer.java b/src/main/java/org/powertac/factoredcustomer/DefaultUtilityOptimizer.java
index 149e8e4..f0fabc0 100644
--- a/src/main/java/org/powertac/factoredcustomer/DefaultUtilityOptimizer.java
+++ b/src/main/java/org/powertac/factoredcustomer/DefaultUtilityOptimizer.java
@@ -1,570 +1,571 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.powertac.factoredcustomer;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
import org.apache.log4j.Logger;
import org.powertac.common.Tariff;
import org.powertac.common.TariffSubscription;
import org.powertac.common.TimeService;
import org.powertac.common.Timeslot;
import org.powertac.common.repo.RandomSeedRepo;
import org.powertac.common.repo.TariffSubscriptionRepo;
import org.powertac.common.repo.TimeslotRepo;
import org.powertac.common.interfaces.TariffMarket;
import org.powertac.common.enumerations.PowerType;
import org.powertac.common.spring.SpringApplicationContext;
import org.powertac.common.state.Domain;
import org.powertac.common.state.StateChange;
import org.powertac.factoredcustomer.interfaces.*;
import org.powertac.factoredcustomer.TariffSubscriberStructure.AllocationMethod;
/**
* Key class responsible for managing the tariff(s) for one customer across
* multiple capacity bundles if necessary.
*
* @author Prashant Reddy
*/
@Domain
class DefaultUtilityOptimizer implements UtilityOptimizer
{
protected Logger log = Logger.getLogger(DefaultUtilityOptimizer.class.getName());
protected final FactoredCustomerService factoredCustomerService;
protected final TariffMarket tariffMarketService;
protected final TariffSubscriptionRepo tariffSubscriptionRepo;
protected final TimeslotRepo timeslotRepo;
protected final RandomSeedRepo randomSeedRepo;
protected static final int NUM_HOURS_IN_DAY = 24;
protected static final long MEAN_TARIFF_DURATION = 5; // number of days
protected final CustomerStructure customerStructure;
protected final List<CapacityBundle> capacityBundles;
protected final List<Tariff> ignoredTariffs = new ArrayList<Tariff>();
protected Random inertiaSampler;
protected Random tariffSelector;
protected final List<Tariff> allTariffs = new ArrayList<Tariff>();
private int tariffEvaluationCounter = 0;
DefaultUtilityOptimizer(CustomerStructure structure, List<CapacityBundle> bundles)
{
customerStructure = structure;
capacityBundles = bundles;
factoredCustomerService = (FactoredCustomerService) SpringApplicationContext.getBean("factoredCustomerService");
tariffMarketService = (TariffMarket) SpringApplicationContext.getBean("tariffMarketService");
tariffSubscriptionRepo = (TariffSubscriptionRepo) SpringApplicationContext.getBean("tariffSubscriptionRepo");
timeslotRepo = (TimeslotRepo) SpringApplicationContext.getBean("timeslotRepo");
randomSeedRepo = (RandomSeedRepo) SpringApplicationContext.getBean("randomSeedRepo");
}
@Override
public void initialize()
{
inertiaSampler = new Random(randomSeedRepo.getRandomSeed("factoredcustomer.DefaultUtilityOptimizer",
customerStructure.structureId, "InertiaSampler").getValue());
tariffSelector = new Random(randomSeedRepo.getRandomSeed("factoredcustomer.DefaultUtilityOptimizer",
customerStructure.structureId, "TariffSelector").getValue());
subscribeDefault();
}
///////////////// TARIFF EVALUATION //////////////////////
@StateChange
protected void subscribe(Tariff tariff, CapacityBundle bundle, int customerCount, boolean verbose)
{
tariffMarketService.subscribeToTariff(tariff, bundle.getCustomerInfo(), customerCount);
if (verbose) log.info(bundle.getName() + ": Subscribed " + customerCount + " customers to tariff " + tariff.getId() + " successfully");
}
@StateChange
protected void unsubscribe(TariffSubscription subscription, CapacityBundle bundle, int customerCount, boolean verbose)
{
subscription.unsubscribe(customerCount);
if (verbose) log.info(bundle.getName() + ": Unsubscribed " + customerCount + " customers from tariff " + subscription.getTariff().getId() + " successfully");
}
/** @Override hook **/
protected void subscribeDefault()
{
for (CapacityBundle bundle: capacityBundles) {
PowerType powerType = bundle.getPowerType();
if (tariffMarketService.getDefaultTariff(powerType) != null) {
log.info(bundle.getName() + ": Subscribing " + bundle.getPopulation() + " customers to default " + powerType + " tariff");
subscribe(tariffMarketService.getDefaultTariff(powerType), bundle, bundle.getPopulation(), false);
} else {
log.info(bundle.getName() + ": No default tariff for power type " + powerType + "; trying generic type");
PowerType genericType = powerType.getGenericType();
if (tariffMarketService.getDefaultTariff(genericType) == null) {
log.error(bundle.getName() + ": No default tariff for generic power type " + genericType + " either!");
} else {
log.info(bundle.getName() + ": Subscribing " + bundle.getPopulation() + " customers to default " + genericType + " tariff");
subscribe(tariffMarketService.getDefaultTariff(genericType), bundle, bundle.getPopulation(), false);
}
}
}
}
@Override
public void handleNewTariffs (List<Tariff> newTariffs)
{
++tariffEvaluationCounter;
for (Tariff tariff: newTariffs) {
allTariffs.add(tariff);
}
for (CapacityBundle bundle: capacityBundles) {
evaluateTariffs(bundle, newTariffs);
}
}
private void evaluateTariffs(CapacityBundle bundle, List<Tariff> newTariffs)
{
if ((tariffEvaluationCounter % bundle.getSubscriberStructure().reconsiderationPeriod) == 0) {
reevaluateAllTariffs(bundle);
}
else if (! ignoredTariffs.isEmpty()) {
evaluateCurrentTariffs(bundle, newTariffs);
}
else if (! newTariffs.isEmpty()) {
boolean ignoringNewTariffs = true;
for (Tariff tariff: newTariffs) {
if (isTariffApplicable(tariff, bundle)) {
ignoringNewTariffs = false;
evaluateCurrentTariffs(bundle, newTariffs);
break;
}
}
if (ignoringNewTariffs) log.info(bundle.getName() + ": New tariffs are not applicable; skipping evaluation");
}
}
private void reevaluateAllTariffs(CapacityBundle bundle)
{
log.info(bundle.getName() + ": Reevaluating all tariffs for " + bundle.getPowerType() + " subscriptions");
List<Tariff> evalTariffs = new ArrayList<Tariff>();
for (Tariff tariff: allTariffs) {
if (! tariff.isRevoked() && ! tariff.isExpired() && isTariffApplicable(tariff, bundle)) {
evalTariffs.add(tariff);
}
}
assertNotEmpty(bundle, evalTariffs);
manageSubscriptions(bundle, evalTariffs);
}
private boolean isTariffApplicable(Tariff tariff, CapacityBundle bundle)
{
PowerType bundlePowerType = bundle.getCustomerInfo().getPowerType();
if (tariff.getPowerType() == bundlePowerType ||
tariff.getPowerType() == bundlePowerType.getGenericType()) {
return true;
}
return false;
}
private void evaluateCurrentTariffs(CapacityBundle bundle, List<Tariff> newTariffs)
{
if (bundle.getSubscriberStructure().inertiaDistribution != null) {
double inertia = bundle.getSubscriberStructure().inertiaDistribution.drawSample();
if (inertiaSampler.nextDouble() < inertia) {
log.info(bundle.getName() + ": Skipping " + bundle.getCustomerInfo().getPowerType() + " tariff reevaluation due to inertia");
for (Tariff newTariff: newTariffs) {
ignoredTariffs.add(newTariff);
}
return;
}
}
// Include previously ignored tariffs and currently subscribed tariffs in evaluation.
// Use map instead of list to eliminate duplicate tariffs.
Map<Long, Tariff> currTariffs = new HashMap<Long, Tariff>();
for (Tariff ignoredTariff: ignoredTariffs) {
currTariffs.put(ignoredTariff.getId(), ignoredTariff);
}
ignoredTariffs.clear();
List<TariffSubscription> subscriptions = tariffSubscriptionRepo.findSubscriptionsForCustomer(bundle.getCustomerInfo());
for (TariffSubscription subscription: subscriptions) {
currTariffs.put(subscription.getTariff().getId(), subscription.getTariff());
}
for (Tariff newTariff: newTariffs) {
currTariffs.put(newTariff.getId(), newTariff);
}
List<Tariff> evalTariffs = new ArrayList<Tariff>();
for (Tariff tariff: currTariffs.values()) {
if (isTariffApplicable(tariff, bundle)) {
evalTariffs.add(tariff);
}
}
assertNotEmpty(bundle, evalTariffs);
manageSubscriptions(bundle, evalTariffs);
}
private void assertNotEmpty(CapacityBundle bundle, List<Tariff> evalTariffs)
{
if (evalTariffs.isEmpty()) {
throw new Error(bundle.getName() + ": The evaluation tariffs list is unexpectedly empty!");
}
}
private void manageSubscriptions(CapacityBundle bundle, List<Tariff> evalTariffs)
{
Collections.shuffle(evalTariffs);
PowerType powerType = bundle.getCustomerInfo().getPowerType();
List<Long> tariffIds = new ArrayList<Long>(evalTariffs.size());
for (Tariff tariff: evalTariffs) tariffIds.add(tariff.getId());
logAllocationDetails(bundle.getName() + ": " + powerType + " tariffs for evaluation: " + tariffIds);
List<Double> estimatedPayments = estimatePayments(bundle, evalTariffs);
logAllocationDetails(bundle.getName() + ": Estimated payments for evaluated tariffs: " + estimatedPayments);
List<Integer> allocations = determineAllocations(bundle, evalTariffs, estimatedPayments);
logAllocationDetails(bundle.getName() + ": Allocations for evaluated tariffs: " + allocations);
int overAllocations = 0;
for (int i=0; i < evalTariffs.size(); ++i) {
Tariff evalTariff = evalTariffs.get(i);
int allocation = allocations.get(i);
TariffSubscription subscription = tariffSubscriptionRepo.findSubscriptionForTariffAndCustomer(evalTariff, bundle.getCustomerInfo()); // could be null
int currentCommitted = (subscription != null) ? subscription.getCustomersCommitted() : 0;
int numChange = allocation - currentCommitted;
log.debug(bundle.getName() + ": evalTariff = " + evalTariff.getId() + ", numChange = " + numChange +
", currentCommitted = " + currentCommitted + ", allocation = " + allocation);
if (numChange == 0) {
if (currentCommitted > 0) {
log.info(bundle.getName() + ": Maintaining " + currentCommitted + " " + powerType + " customers in tariff " + evalTariff.getId());
} else {
log.info(bundle.getName() + ": Not allocating any " + powerType + " customers to tariff " + evalTariff.getId());
}
} else if (numChange > 0) {
if (evalTariff.isExpired()) {
overAllocations += numChange;
if (currentCommitted > 0) {
log.info(bundle.getName() + ": Maintaining " + currentCommitted + " " + powerType + " customers in expired tariff " + evalTariff.getId());
}
log.info(bundle.getName() + ": Reallocating " + numChange + " " + powerType + " customers from expired tariff " + evalTariff.getId() + " to other tariffs");
} else {
log.info(bundle.getName() + ": Subscribing " + numChange + " " + powerType + " customers to tariff " + evalTariff.getId());
subscribe(evalTariff, bundle, numChange, false);
}
} else if (numChange < 0) {
log.info(bundle.getName() + ": Unsubscribing " + -numChange + " " + powerType + " customers from tariff " + evalTariff.getId());
unsubscribe(subscription, bundle, -numChange, false);
}
}
if (overAllocations > 0) {
int minIndex = 0;
double minEstimate = Double.POSITIVE_INFINITY;
for (int i=0; i < estimatedPayments.size(); ++i) {
if (estimatedPayments.get(i) < minEstimate && ! evalTariffs.get(i).isExpired()) {
minIndex = i;
minEstimate = estimatedPayments.get(i);
}
}
log.info(bundle.getName() + ": Subscribing " + overAllocations + " over-allocated customers to tariff " + evalTariffs.get(minIndex).getId());
subscribe(evalTariffs.get(minIndex), bundle, overAllocations, false);
}
}
private List<Double> estimatePayments(CapacityBundle bundle, List<Tariff> evalTariffs)
{
List<Double> estimatedPayments = new ArrayList<Double>(evalTariffs.size());
for (int i=0; i < evalTariffs.size(); ++i) {
Tariff tariff = evalTariffs.get(i);
if (tariff.isExpired()) {
if (bundle.getCustomerInfo().getPowerType().isConsumption()) {
estimatedPayments.add(Double.POSITIVE_INFINITY); // assume worst case
} else { // PRODUCTION or STORAGE
estimatedPayments.add(Double.NEGATIVE_INFINITY); // assume worst case
}
} else {
double fixedPayments = estimateFixedTariffPayments(tariff);
double variablePayment = forecastDailyUsageCharge(bundle, tariff);
double totalPayment = truncateTo2Decimals(fixedPayments + variablePayment);
estimatedPayments.add(totalPayment);
}
}
return estimatedPayments;
}
private double estimateFixedTariffPayments(Tariff tariff)
{
double lifecyclePayment = tariff.getEarlyWithdrawPayment() + tariff.getSignupPayment();
double minDuration;
if (tariff.getMinDuration() == 0) minDuration = MEAN_TARIFF_DURATION * TimeService.DAY;
else minDuration = tariff.getMinDuration();
return ((double) tariff.getPeriodicPayment() + (lifecyclePayment / minDuration));
}
private double forecastDailyUsageCharge(CapacityBundle bundle, Tariff tariff)
{
Timeslot hourlyTimeslot = timeslotRepo.currentTimeslot();
double totalUsage = 0.0;
double totalCharge = 0.0;
for (CapacityOriginator capacityOriginator: bundle.getCapacityOriginators()) {
CapacityProfile forecast = capacityOriginator.getCurrentForecast();
for (int i=0; i < CapacityProfile.NUM_TIMESLOTS; ++i) {
double usageSign = bundle.getPowerType().isConsumption() ? +1 : -1;
double hourlyUsage = usageSign * forecast.getCapacity(i);
totalCharge += tariff.getUsageCharge(hourlyTimeslot.getStartInstant(), hourlyUsage, totalUsage);
totalUsage += hourlyUsage;
}
}
return totalCharge;
}
private List<Integer> determineAllocations(CapacityBundle bundle, List<Tariff> evalTariffs,
List<Double> estimatedPayments)
{
if (evalTariffs.size() == 1) {
List<Integer> allocations = new ArrayList<Integer>();
allocations.add(bundle.getPopulation());
return allocations;
} else {
if (bundle.getSubscriberStructure().allocationMethod == AllocationMethod.TOTAL_ORDER) {
return determineTotalOrderAllocations(bundle, evalTariffs, estimatedPayments);
} else { // LOGIT_CHOICE
return determineLogitChoiceAllocations(bundle, evalTariffs, estimatedPayments);
}
}
}
private List<Integer> determineTotalOrderAllocations(CapacityBundle bundle, List<Tariff> evalTariffs,
List<Double> estimatedPayments)
{
int numTariffs = evalTariffs.size();
List<Double> allocationRule;
if (bundle.getSubscriberStructure().totalOrderRules.isEmpty()) {
allocationRule = new ArrayList<Double>(numTariffs);
allocationRule.add(1.0);
for (int i=1; i < numTariffs; ++i) {
allocationRule.add(0.0);
}
} else if (numTariffs <= bundle.getSubscriberStructure().totalOrderRules.size()) {
allocationRule = bundle.getSubscriberStructure().totalOrderRules.get(numTariffs - 1);
} else {
allocationRule = new ArrayList<Double>(numTariffs);
List<Double> largestRule = bundle.getSubscriberStructure().totalOrderRules.get(bundle.getSubscriberStructure().totalOrderRules.size() - 1);
for (int i=0; i < numTariffs; ++i) {
if (i < largestRule.size()) {
allocationRule.add(largestRule.get(i));
} else {
allocationRule.add(0.0);
}
}
}
// payments are positive for production, so sorting is still valid
List<Double> sortedPayments = new ArrayList<Double>(numTariffs);
for (double estimatedPayment: estimatedPayments) {
sortedPayments.add(estimatedPayment);
}
Collections.sort(sortedPayments, Collections.reverseOrder()); // we want descending order
List<Integer> allocations = new ArrayList<Integer>(numTariffs);
for (int i=0; i < numTariffs; ++i) {
if (allocationRule.get(i) > 0) {
double nextBest = sortedPayments.get(i);
for (int j=0; j < numTariffs; ++j) {
if (estimatedPayments.get(j) == nextBest) {
allocations.add((int) Math.round(bundle.getCustomerInfo().getPopulation() * allocationRule.get(i)));
}
}
}
else allocations.add(0);
}
return allocations;
}
private List<Integer> determineLogitChoiceAllocations(CapacityBundle bundle, List<Tariff> evalTariffs,
List<Double> estimatedPayments)
{
// logit choice model: p_i = e^(lambda * utility_i) / sum_i(e^(lambda * utility_i))
int numTariffs = evalTariffs.size();
double bestPayment = Collections.max(estimatedPayments);
double worstPayment = Collections.min(estimatedPayments);
List<Double> probabilities = new ArrayList<Double>(numTariffs);
if (bestPayment - worstPayment < 0.01) { // i.e., approximately zero
for (int i=0; i < numTariffs; ++i) {
probabilities.add(1.0 / numTariffs);
}
} else {
double sumPayments = 0.0;
for (int i=0; i < numTariffs; ++i) {
sumPayments += estimatedPayments.get(i);
}
double meanPayment = sumPayments / numTariffs;
double lambda = bundle.getSubscriberStructure().logitChoiceRationality; // [0.0 = irrational, 1.0 = perfectly rational]
List<Double> numerators = new ArrayList<Double>(numTariffs);
double denominator = 0.0;
for (int i=0; i < numTariffs; ++i) {
double basis = Math.max((bestPayment - meanPayment), (meanPayment - worstPayment));
double utility = ((estimatedPayments.get(i) - meanPayment) / basis) * 3.0; // [-3.0, +3.0]
double numerator = Math.exp(lambda * utility);
numerators.add(numerator);
denominator += numerator;
}
for (int i=0; i < numTariffs; ++i) {
probabilities.add(numerators.get(i) / denominator);
}
}
// Now determine allocations based on above probabilities
List<Integer> allocations = new ArrayList<Integer>(numTariffs);
int population = bundle.getPopulation();
if (bundle.getCustomerInfo().isMultiContracting())
{
int sumAllocations = 0;
for (int i=0; i < numTariffs; ++i) {
int allocation;
- if (i < (numTariffs - 1)) {
+ if (sumAllocations == population) {
+ allocation = 0;
+ } else if (i < (numTariffs - 1)) {
allocation = (int) Math.round(population * probabilities.get(i));
if ((sumAllocations + allocation) > population) {
allocation = population - sumAllocations;
}
sumAllocations += allocation;
- if (sumAllocations == population) break;
} else {
allocation = population - sumAllocations;
}
allocations.add(allocation);
}
} else {
double r = ((double) tariffSelector.nextInt(100) / 100.0); // [0.0, 1.0]
double cumProbability = 0.0;
for (int i=0; i < numTariffs; ++i) {
cumProbability += probabilities.get(i);
if (r <= cumProbability) {
allocations.add(population);
for (int j=i+1; j < numTariffs; ++j) {
allocations.add(0);
}
break;
} else {
allocations.add(0);
}
}
}
return allocations;
}
///////////////// TIMESLOT ACTIVITY //////////////////////
@Override
public void handleNewTimeslot(Timeslot timeslot)
{
checkRevokedSubscriptions();
usePower(timeslot);
}
private void checkRevokedSubscriptions()
{
for (CapacityBundle bundle: capacityBundles) {
List<TariffSubscription> revoked = tariffSubscriptionRepo.getRevokedSubscriptionList(bundle.getCustomerInfo());
for (TariffSubscription revokedSubscription : revoked) {
revokedSubscription.handleRevokedTariff();
}
}
}
private void usePower(Timeslot timeslot)
{
for (CapacityBundle bundle: capacityBundles) {
List<TariffSubscription> subscriptions = tariffSubscriptionRepo.findSubscriptionsForCustomer(bundle.getCustomerInfo());
double totalCapacity = 0.0;
double totalUsageCharge = 0.0;
for (TariffSubscription subscription: subscriptions) {
if (subscription.getCustomersCommitted() > 0) {
double usageSign = bundle.getPowerType().isConsumption() ? +1 : -1;
double currCapacity = usageSign * useCapacity(subscription, bundle);
if (factoredCustomerService.getUsageChargesLogging() == true) {
double charge = subscription.getTariff().getUsageCharge(currCapacity, subscription.getTotalUsage(), false);
totalUsageCharge += charge;
}
subscription.usePower(currCapacity);
totalCapacity += currCapacity;
}
}
log.info(bundle.getName() + ": Total " + bundle.getPowerType() + " capacity for timeslot " + timeslot.getSerialNumber() + " = " + totalCapacity);
logUsageCharges(bundle.getName() + ": Total " + bundle.getPowerType() + " usage charge for timeslot " + timeslot.getSerialNumber() + " = " + totalUsageCharge);
}
}
public double useCapacity(TariffSubscription subscription, CapacityBundle bundle)
{
double capacity = 0;
for (CapacityOriginator capacityOriginator: bundle.getCapacityOriginators()) {
capacity += capacityOriginator.useCapacity(subscription);
}
return capacity;
}
protected String getCustomerName()
{
return customerStructure.name;
}
protected double truncateTo2Decimals(double x)
{
double fract, whole;
if (x > 0) {
whole = Math.floor(x);
fract = Math.floor((x - whole) * 100) / 100;
} else {
whole = Math.ceil(x);
fract = Math.ceil((x - whole) * 100) / 100;
}
return whole + fract;
}
private void logAllocationDetails(String msg)
{
if (factoredCustomerService.getAllocationDetailsLogging() == true) {
log.info(msg);
}
}
private void logUsageCharges(String msg)
{
if (factoredCustomerService.getUsageChargesLogging() == true) {
log.info(msg);
}
}
@Override
public String toString()
{
return this.getClass().getCanonicalName() + ":" + getCustomerName();
}
} // end class
| false | true |
private List<Integer> determineLogitChoiceAllocations(CapacityBundle bundle, List<Tariff> evalTariffs,
List<Double> estimatedPayments)
{
// logit choice model: p_i = e^(lambda * utility_i) / sum_i(e^(lambda * utility_i))
int numTariffs = evalTariffs.size();
double bestPayment = Collections.max(estimatedPayments);
double worstPayment = Collections.min(estimatedPayments);
List<Double> probabilities = new ArrayList<Double>(numTariffs);
if (bestPayment - worstPayment < 0.01) { // i.e., approximately zero
for (int i=0; i < numTariffs; ++i) {
probabilities.add(1.0 / numTariffs);
}
} else {
double sumPayments = 0.0;
for (int i=0; i < numTariffs; ++i) {
sumPayments += estimatedPayments.get(i);
}
double meanPayment = sumPayments / numTariffs;
double lambda = bundle.getSubscriberStructure().logitChoiceRationality; // [0.0 = irrational, 1.0 = perfectly rational]
List<Double> numerators = new ArrayList<Double>(numTariffs);
double denominator = 0.0;
for (int i=0; i < numTariffs; ++i) {
double basis = Math.max((bestPayment - meanPayment), (meanPayment - worstPayment));
double utility = ((estimatedPayments.get(i) - meanPayment) / basis) * 3.0; // [-3.0, +3.0]
double numerator = Math.exp(lambda * utility);
numerators.add(numerator);
denominator += numerator;
}
for (int i=0; i < numTariffs; ++i) {
probabilities.add(numerators.get(i) / denominator);
}
}
// Now determine allocations based on above probabilities
List<Integer> allocations = new ArrayList<Integer>(numTariffs);
int population = bundle.getPopulation();
if (bundle.getCustomerInfo().isMultiContracting())
{
int sumAllocations = 0;
for (int i=0; i < numTariffs; ++i) {
int allocation;
if (i < (numTariffs - 1)) {
allocation = (int) Math.round(population * probabilities.get(i));
if ((sumAllocations + allocation) > population) {
allocation = population - sumAllocations;
}
sumAllocations += allocation;
if (sumAllocations == population) break;
} else {
allocation = population - sumAllocations;
}
allocations.add(allocation);
}
} else {
double r = ((double) tariffSelector.nextInt(100) / 100.0); // [0.0, 1.0]
double cumProbability = 0.0;
for (int i=0; i < numTariffs; ++i) {
cumProbability += probabilities.get(i);
if (r <= cumProbability) {
allocations.add(population);
for (int j=i+1; j < numTariffs; ++j) {
allocations.add(0);
}
break;
} else {
allocations.add(0);
}
}
}
return allocations;
}
|
private List<Integer> determineLogitChoiceAllocations(CapacityBundle bundle, List<Tariff> evalTariffs,
List<Double> estimatedPayments)
{
// logit choice model: p_i = e^(lambda * utility_i) / sum_i(e^(lambda * utility_i))
int numTariffs = evalTariffs.size();
double bestPayment = Collections.max(estimatedPayments);
double worstPayment = Collections.min(estimatedPayments);
List<Double> probabilities = new ArrayList<Double>(numTariffs);
if (bestPayment - worstPayment < 0.01) { // i.e., approximately zero
for (int i=0; i < numTariffs; ++i) {
probabilities.add(1.0 / numTariffs);
}
} else {
double sumPayments = 0.0;
for (int i=0; i < numTariffs; ++i) {
sumPayments += estimatedPayments.get(i);
}
double meanPayment = sumPayments / numTariffs;
double lambda = bundle.getSubscriberStructure().logitChoiceRationality; // [0.0 = irrational, 1.0 = perfectly rational]
List<Double> numerators = new ArrayList<Double>(numTariffs);
double denominator = 0.0;
for (int i=0; i < numTariffs; ++i) {
double basis = Math.max((bestPayment - meanPayment), (meanPayment - worstPayment));
double utility = ((estimatedPayments.get(i) - meanPayment) / basis) * 3.0; // [-3.0, +3.0]
double numerator = Math.exp(lambda * utility);
numerators.add(numerator);
denominator += numerator;
}
for (int i=0; i < numTariffs; ++i) {
probabilities.add(numerators.get(i) / denominator);
}
}
// Now determine allocations based on above probabilities
List<Integer> allocations = new ArrayList<Integer>(numTariffs);
int population = bundle.getPopulation();
if (bundle.getCustomerInfo().isMultiContracting())
{
int sumAllocations = 0;
for (int i=0; i < numTariffs; ++i) {
int allocation;
if (sumAllocations == population) {
allocation = 0;
} else if (i < (numTariffs - 1)) {
allocation = (int) Math.round(population * probabilities.get(i));
if ((sumAllocations + allocation) > population) {
allocation = population - sumAllocations;
}
sumAllocations += allocation;
} else {
allocation = population - sumAllocations;
}
allocations.add(allocation);
}
} else {
double r = ((double) tariffSelector.nextInt(100) / 100.0); // [0.0, 1.0]
double cumProbability = 0.0;
for (int i=0; i < numTariffs; ++i) {
cumProbability += probabilities.get(i);
if (r <= cumProbability) {
allocations.add(population);
for (int j=i+1; j < numTariffs; ++j) {
allocations.add(0);
}
break;
} else {
allocations.add(0);
}
}
}
return allocations;
}
|
diff --git a/impl/src/main/java/org/jboss/cdi/tck/tests/decorators/builtin/conversation/ConversationDecorator.java b/impl/src/main/java/org/jboss/cdi/tck/tests/decorators/builtin/conversation/ConversationDecorator.java
index 0f8084fa7..5e25b3ad3 100644
--- a/impl/src/main/java/org/jboss/cdi/tck/tests/decorators/builtin/conversation/ConversationDecorator.java
+++ b/impl/src/main/java/org/jboss/cdi/tck/tests/decorators/builtin/conversation/ConversationDecorator.java
@@ -1,45 +1,45 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.cdi.tck.tests.decorators.builtin.conversation;
import javax.decorator.Decorator;
import javax.decorator.Delegate;
import javax.enterprise.context.Conversation;
import javax.inject.Inject;
/**
* @author Martin Kouba
*
*/
@Decorator
public abstract class ConversationDecorator implements Conversation {
@Inject
@Delegate
Conversation conversation;
@Inject
ConversationObserver conversationObserver;
@Override
public void begin(String id) {
- conversation.begin();
+ conversation.begin(id);
conversationObserver.setDecoratedConversationId(conversation.getId());
}
}
| true | true |
public void begin(String id) {
conversation.begin();
conversationObserver.setDecoratedConversationId(conversation.getId());
}
|
public void begin(String id) {
conversation.begin(id);
conversationObserver.setDecoratedConversationId(conversation.getId());
}
|
diff --git a/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/ScalarisDataHandler.java b/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/ScalarisDataHandler.java
index 7b9566d5..a0ea0002 100644
--- a/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/ScalarisDataHandler.java
+++ b/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/ScalarisDataHandler.java
@@ -1,1306 +1,1308 @@
/**
* Copyright 2011 Zuse Institute Berlin
*
* 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 de.zib.scalaris.examples.wikipedia;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import com.ericsson.otp.erlang.OtpErlangString;
import de.zib.scalaris.Connection;
import de.zib.scalaris.ConnectionException;
import de.zib.scalaris.ErlangValue;
import de.zib.scalaris.NotFoundException;
import de.zib.scalaris.ScalarisVM;
import de.zib.scalaris.Transaction;
import de.zib.scalaris.TransactionSingleOp;
import de.zib.scalaris.UnknownException;
import de.zib.scalaris.examples.wikipedia.InvolvedKey.OP;
import de.zib.scalaris.examples.wikipedia.Options.STORE_CONTRIB_TYPE;
import de.zib.scalaris.examples.wikipedia.bliki.MyNamespace;
import de.zib.scalaris.examples.wikipedia.bliki.MyWikiModel;
import de.zib.scalaris.examples.wikipedia.data.Contribution;
import de.zib.scalaris.examples.wikipedia.data.Page;
import de.zib.scalaris.examples.wikipedia.data.Revision;
import de.zib.scalaris.examples.wikipedia.data.ShortRevision;
import de.zib.scalaris.examples.wikipedia.data.SiteInfo;
import de.zib.scalaris.operations.Operation;
import de.zib.scalaris.operations.ReadOp;
/**
* Retrieves and writes values from/to Scalaris.
*
* @author Nico Kruber, [email protected]
*/
public class ScalarisDataHandler {
/**
* Gets the key to store {@link SiteInfo} objects at.
*
* @return Scalaris key
*/
public final static String getSiteInfoKey() {
return "siteinfo";
}
/**
* Gets the key to store the list of pages in the given namespace at.
*
* @param namespace the namespace ID
*
* @return Scalaris key
*/
public final static String getPageListKey(int namespace) {
return "pages:" + namespace;
}
/**
* Gets the key to store the number of pages at.
*
* @param namespace the namespace ID
*
* @return Scalaris key
*/
public final static String getPageCountKey(int namespace) {
return getPageListKey(namespace) + ":count";
}
/**
* Gets the key to store the number of articles, i.e. pages in the main
* namespace, at.
*
* @return Scalaris key
*/
public final static String getArticleCountKey() {
return "articles:count";
}
/**
* Gets the key to store {@link Revision} objects at.
*
* @param title the title of the page
* @param id the id of the revision
* @param nsObject the namespace for page title normalisation
*
* @return Scalaris key
*/
public final static String getRevKey(String title, int id, final MyNamespace nsObject) {
return MyWikiModel.normalisePageTitle(title, nsObject) + ":rev:" + id;
}
/**
* Gets the key to store {@link Page} objects at.
*
* @param title the title of the page
* @param nsObject the namespace for page title normalisation
*
* @return Scalaris key
*/
public final static String getPageKey(String title, final MyNamespace nsObject) {
return MyWikiModel.normalisePageTitle(title, nsObject) + ":page";
}
/**
* Gets the key to store the list of revisions of a page at.
*
* @param title the title of the page
* @param nsObject the namespace for page title normalisation
*
* @return Scalaris key
*/
public final static String getRevListKey(String title, final MyNamespace nsObject) {
return MyWikiModel.normalisePageTitle(title, nsObject) + ":revs";
}
/**
* Gets the key to store the list of pages belonging to a category at.
*
* @param title the category title (including <tt>Category:</tt>)
* @param nsObject the namespace for page title normalisation
*
* @return Scalaris key
*/
public final static String getCatPageListKey(String title, final MyNamespace nsObject) {
return MyWikiModel.normalisePageTitle(title, nsObject) + ":cpages";
}
/**
* Gets the key to store the number of pages belonging to a category at.
*
* @param title the category title (including <tt>Category:</tt>)
* @param nsObject the namespace for page title normalisation
*
* @return Scalaris key
*/
public final static String getCatPageCountKey(String title, final MyNamespace nsObject) {
return MyWikiModel.normalisePageTitle(title, nsObject) + ":cpages:count";
}
/**
* Gets the key to store the list of pages using a template at.
*
* @param title the template title (including <tt>Template:</tt>)
* @param nsObject the namespace for page title normalisation
*
* @return Scalaris key
*/
public final static String getTplPageListKey(String title, final MyNamespace nsObject) {
return MyWikiModel.normalisePageTitle(title, nsObject) + ":tpages";
}
/**
* Gets the key to store the list of pages linking to the given title.
*
* @param title the page's title
* @param nsObject the namespace for page title normalisation
*
* @return Scalaris key
*/
public final static String getBackLinksPageListKey(String title, final MyNamespace nsObject) {
return MyWikiModel.normalisePageTitle(title, nsObject) + ":blpages";
}
/**
* Gets the key to store the number of page edits.
*
* @return Scalaris key
*/
public final static String getStatsPageEditsKey() {
return "stats:pageedits";
}
/**
* Gets the key to store the list of contributions of a user.
*
* @param contributor the user name or IP address of the user who created
* the revision
*
* @return Scalaris key
*/
public final static String getContributionListKey(String contributor) {
return contributor + ":user:contrib";
}
/**
* Retrieves the Scalaris version string.
*
* @param connection
* the connection to the DB
*
* @return a result object with the version string on success
*/
public static ValueResult<String> getDbVersion(Connection connection) {
final long timeAtStart = System.currentTimeMillis();
final String statName = "Scalaris version";
List<InvolvedKey> involvedKeys = new ArrayList<InvolvedKey>();
if (connection == null) {
return new ValueResult<String>(false, involvedKeys,
"no connection to Scalaris", true, statName,
System.currentTimeMillis() - timeAtStart);
}
String node = connection.getRemote().toString();
try {
ScalarisVM scalarisVm = new ScalarisVM(node);
String version = scalarisVm.getVersion();
return new ValueResult<String>(involvedKeys, version, statName,
System.currentTimeMillis() - timeAtStart);
} catch (ConnectionException e) {
return new ValueResult<String>(false, involvedKeys,
"no connection to Scalaris node \"" + node + "\"", true,
statName, System.currentTimeMillis() - timeAtStart);
} catch (UnknownException e) {
return new ValueResult<String>(false, involvedKeys,
"unknown exception reading Scalaris version from node \""
+ node + "\"", true, statName,
System.currentTimeMillis() - timeAtStart);
}
}
/**
* Retrieves a page's history from Scalaris.
*
* @param connection
* the connection to Scalaris
* @param title
* the title of the page
* @param nsObject
* the namespace for page title normalisation
*
* @return a result object with the page history on success
*/
public static PageHistoryResult getPageHistory(Connection connection,
String title, final MyNamespace nsObject) {
final long timeAtStart = System.currentTimeMillis();
final String statName = "history of " + title;
List<InvolvedKey> involvedKeys = new ArrayList<InvolvedKey>();
if (connection == null) {
return new PageHistoryResult(false, involvedKeys, "no connection to Scalaris",
true, statName, System.currentTimeMillis() - timeAtStart);
}
TransactionSingleOp scalaris_single = new TransactionSingleOp(connection);
TransactionSingleOp.RequestList requests = new TransactionSingleOp.RequestList();
requests.addOp(new ReadOp(getPageKey(title, nsObject)));
requests.addOp(new ReadOp(getRevListKey(title, nsObject)));
TransactionSingleOp.ResultList results;
try {
ScalarisDataHandler.addInvolvedKeys(involvedKeys, requests.getRequests());
results = scalaris_single.req_list(requests);
} catch (Exception e) {
return new PageHistoryResult(false, involvedKeys,
"unknown exception reading \""
+ getPageKey(title, nsObject) + "\" or \""
+ getRevListKey(title, nsObject)
+ "\" from Scalaris: " + e.getMessage(),
e instanceof ConnectionException, statName,
System.currentTimeMillis() - timeAtStart);
}
Page page;
try {
page = results.processReadAt(0).jsonValue(Page.class);
} catch (NotFoundException e) {
PageHistoryResult result = new PageHistoryResult(
false, involvedKeys,
"page not found at \"" + getPageKey(title, nsObject) + "\"",
false, statName, System.currentTimeMillis() - timeAtStart);
result.not_existing = true;
return result;
} catch (Exception e) {
return new PageHistoryResult(false, involvedKeys,
"unknown exception reading \""
+ getPageKey(title, nsObject)
+ "\" from Scalaris: " + e.getMessage(),
e instanceof ConnectionException, statName,
System.currentTimeMillis() - timeAtStart);
}
List<ShortRevision> revisions;
try {
revisions = results.processReadAt(1).jsonListValue(ShortRevision.class);
} catch (NotFoundException e) {
PageHistoryResult result = new PageHistoryResult(false,
involvedKeys, "revision list \""
+ getRevListKey(title, nsObject)
+ "\" does not exist", false, statName,
System.currentTimeMillis() - timeAtStart);
result.not_existing = true;
return result;
} catch (Exception e) {
return new PageHistoryResult(false, involvedKeys,
"unknown exception reading \""
+ getRevListKey(title, nsObject)
+ "\" from Scalaris: " + e.getMessage(),
e instanceof ConnectionException, statName,
System.currentTimeMillis() - timeAtStart);
}
return new PageHistoryResult(involvedKeys, page, revisions, statName,
System.currentTimeMillis() - timeAtStart);
}
/**
* Retrieves the current, i.e. most up-to-date, version of a page from
* Scalaris.
*
* @param connection
* the connection to Scalaris
* @param title
* the title of the page
* @param nsObject
* the namespace for page title normalisation
*
* @return a result object with the page and revision on success
*/
public static RevisionResult getRevision(Connection connection,
String title, final MyNamespace nsObject) {
return getRevision(connection, title, -1, nsObject);
}
/**
* Retrieves the given version of a page from Scalaris.
*
* @param connection
* the connection to Scalaris
* @param title
* the title of the page
* @param id
* the id of the version
* @param nsObject
* the namespace for page title normalisation
*
* @return a result object with the page and revision on success
*/
public static RevisionResult getRevision(Connection connection,
String title, int id, final MyNamespace nsObject) {
final long timeAtStart = System.currentTimeMillis();
Page page = null;
Revision revision = null;
List<InvolvedKey> involvedKeys = new ArrayList<InvolvedKey>();
if (connection == null) {
return new RevisionResult(false, involvedKeys,
"no connection to Scalaris", true, page, revision, false,
false, title, System.currentTimeMillis() - timeAtStart);
}
TransactionSingleOp scalaris_single;
String scalaris_key;
scalaris_single = new TransactionSingleOp(connection);
scalaris_key = getPageKey(title, nsObject);
try {
involvedKeys.add(new InvolvedKey(OP.READ, scalaris_key));
page = scalaris_single.read(scalaris_key).jsonValue(Page.class);
} catch (NotFoundException e) {
return new RevisionResult(false, involvedKeys,
"page not found at \"" + scalaris_key + "\"", false, page,
revision, true, false, title,
System.currentTimeMillis() - timeAtStart);
} catch (Exception e) {
return new RevisionResult(false, involvedKeys,
"unknown exception reading \"" + scalaris_key
+ "\" from Scalaris: " + e.getMessage(),
e instanceof ConnectionException, page, revision, false,
false, title, System.currentTimeMillis() - timeAtStart);
}
// load requested version if it is not the current one cached in the Page object
if (id != page.getCurRev().getId() && id >= 0) {
scalaris_key = getRevKey(title, id, nsObject);
try {
involvedKeys.add(new InvolvedKey(OP.READ, scalaris_key));
revision = scalaris_single.read(scalaris_key).jsonValue(Revision.class);
} catch (NotFoundException e) {
return new RevisionResult(false, involvedKeys,
"revision not found at \"" + scalaris_key + "\"",
false, page, revision, false, true, title,
System.currentTimeMillis() - timeAtStart);
} catch (Exception e) {
return new RevisionResult(false, involvedKeys,
"unknown exception reading \"" + scalaris_key
+ "\" from Scalaris: " + e.getMessage(),
e instanceof ConnectionException, page, revision,
false, false, title,
System.currentTimeMillis() - timeAtStart);
}
} else {
revision = page.getCurRev();
}
return new RevisionResult(involvedKeys, page, revision, title,
System.currentTimeMillis() - timeAtStart);
}
/**
* Retrieves a list of all available pages from Scalaris.
*
* @param connection
* the connection to Scalaris
*
* @return a result object with the page list on success
*/
public static ValueResult<List<String>> getPageList(Connection connection) {
ArrayList<String> scalaris_keys = new ArrayList<String>(
MyNamespace.MAX_NAMESPACE_ID - MyNamespace.MIN_NAMESPACE_ID + 1);
for (int i = MyNamespace.MIN_NAMESPACE_ID; i < MyNamespace.MAX_NAMESPACE_ID; ++i) {
scalaris_keys.add(getPageListKey(i));
}
return getPageList2(connection, ScalarisOpType.PAGE_LIST,
scalaris_keys, false, "page list");
}
/**
* Retrieves a list of available pages in the given namespace from Scalaris.
*
* @param namespace
* the namespace ID
* @param connection
* the connection to Scalaris
*
* @return a result object with the page list on success
*/
public static ValueResult<List<String>> getPageList(int namespace, Connection connection) {
return getPageList2(connection, ScalarisOpType.PAGE_LIST,
Arrays.asList(getPageListKey(namespace)), false, "page list:" + namespace);
}
/**
* Retrieves a list of pages in the given category from Scalaris.
*
* @param connection
* the connection to Scalaris
* @param title
* the title of the category
* @param nsObject
* the namespace for page title normalisation
*
* @return a result object with the page list on success
*/
public static ValueResult<List<String>> getPagesInCategory(Connection connection,
String title, final MyNamespace nsObject) {
return getPageList2(connection, ScalarisOpType.CATEGORY_PAGE_LIST,
Arrays.asList(getCatPageListKey(title, nsObject)), false,
"pages in " + title);
}
/**
* Retrieves a list of pages using the given template from Scalaris.
*
* @param connection
* the connection to Scalaris
* @param title
* the title of the template
* @param nsObject
* the namespace for page title normalisation
*
* @return a result object with the page list on success
*/
public static ValueResult<List<String>> getPagesInTemplate(Connection connection,
String title, final MyNamespace nsObject) {
return getPageList2(connection, ScalarisOpType.TEMPLATE_PAGE_LIST,
Arrays.asList(getTplPageListKey(title, nsObject)), true,
"pages in " + title);
}
/**
* Retrieves a list of pages linking to the given page from Scalaris.
*
* @param connection
* the connection to Scalaris
* @param title
* the title of the page
* @param nsObject
* the namespace for page title normalisation
*
* @return a result object with the page list on success
*/
public static ValueResult<List<String>> getPagesLinkingTo(Connection connection,
String title, final MyNamespace nsObject) {
final String statName = "links to " + title;
if (Options.getInstance().WIKI_USE_BACKLINKS) {
return getPageList2(connection, ScalarisOpType.BACKLINK_PAGE_LIST,
Arrays.asList(getBackLinksPageListKey(title, nsObject)),
false, statName);
} else {
return new ValueResult<List<String>>(new ArrayList<InvolvedKey>(0),
new ArrayList<String>(0));
}
}
/**
* Retrieves a list of pages linking to the given page from Scalaris.
*
* @param connection
* the connection to Scalaris
* @param contributor
* the user name or IP address of the user who created the
* revision
*
* @return a result object with the page list on success
*/
public static ValueResult<List<Contribution>> getContributions(
Connection connection, String contributor) {
final String statName = "contributions of " + contributor;
if (Options.getInstance().WIKI_STORE_CONTRIBUTIONS != STORE_CONTRIB_TYPE.NONE) {
ValueResult<List<Contribution>> result = getPageList3(connection,
ScalarisOpType.CONTRIBUTION,
Arrays.asList(getContributionListKey(contributor)), false,
statName, new ErlangConverter<List<Contribution>>() {
@Override
public List<Contribution> convert(ErlangValue v)
throws ClassCastException {
return v.jsonListValue(Contribution.class);
}
});
if (result.success && result.value == null) {
result.value = new ArrayList<Contribution>(0);
}
return result;
} else {
return new ValueResult<List<Contribution>>(
new ArrayList<InvolvedKey>(0), new ArrayList<Contribution>(0));
}
}
/**
* Retrieves a list of pages from Scalaris.
*
* @param connection
* the connection to Scalaris
* @param opType
* operation type indicating what is being read
* @param scalaris_keys
* the keys under which the page list is stored in Scalaris
* @param failNotFound
* whether the operation should fail if the key is not found or
* not
* @param statName
* name for the time measurement statistics
*
* @return a result object with the page list on success
*/
private static ValueResult<List<String>> getPageList2(
Connection connection, ScalarisOpType opType,
Collection<String> scalaris_keys, boolean failNotFound,
String statName) {
ValueResult<List<String>> result = getPageList3(connection, opType,
scalaris_keys, failNotFound, statName,
new ErlangConverter<List<String>>() {
@Override
public List<String> convert(ErlangValue v)
throws ClassCastException {
return v.stringListValue();
}
});
if (result.success && result.value == null) {
result.value = new ArrayList<String>(0);
}
return result;
}
/**
* Retrieves a list of pages from Scalaris.
* @param <T>
*
* @param connection
* the connection to Scalaris
* @param opType
* operation type indicating what is being read
* @param scalaris_keys
* the keys under which the page list is stored in Scalaris
* @param failNotFound
* whether the operation should fail if the key is not found or
* not (the value contains null if not failed!)
* @param statName
* name for the time measurement statistics
*
* @return a result object with the page list on success
*/
private static <T> ValueResult<List<T>> getPageList3(Connection connection,
ScalarisOpType opType, Collection<String> scalaris_keys,
boolean failNotFound, String statName, ErlangConverter<List<T>> conv) {
final long timeAtStart = System.currentTimeMillis();
List<InvolvedKey> involvedKeys = new ArrayList<InvolvedKey>();
if (connection == null) {
return new ValueResult<List<T>>(false, involvedKeys,
"no connection to Scalaris", true, statName,
System.currentTimeMillis() - timeAtStart);
}
final MyScalarisSingleOpExecutor executor = new MyScalarisSingleOpExecutor(
new TransactionSingleOp(connection), involvedKeys);
final ScalarisReadListOp1<T> readOp = new ScalarisReadListOp1<T>(scalaris_keys,
Options.getInstance().OPTIMISATIONS.get(opType), conv, failNotFound);
executor.addOp(readOp);
try {
executor.run();
} catch (Exception e) {
return new ValueResult<List<T>>(false, involvedKeys,
"unknown exception reading page list at \""
+ involvedKeys.toString() + "\" from Scalaris: "
+ e.getMessage(), e instanceof ConnectionException,
statName, System.currentTimeMillis() - timeAtStart);
}
return new ValueResult<List<T>>(involvedKeys, readOp.getValue(), statName,
System.currentTimeMillis() - timeAtStart);
}
/**
* Retrieves the number of all available pages from Scalaris.
*
* @param connection
* the connection to Scalaris
*
* @return a result object with the number of pages on success
*/
public static ValueResult<BigInteger> getPageCount(Connection connection) {
ArrayList<String> scalaris_keys = new ArrayList<String>(
MyNamespace.MAX_NAMESPACE_ID - MyNamespace.MIN_NAMESPACE_ID + 1);
for (int i = MyNamespace.MIN_NAMESPACE_ID; i < MyNamespace.MAX_NAMESPACE_ID; ++i) {
scalaris_keys.add(getPageCountKey(i));
}
return getInteger2(connection, scalaris_keys, false, "page count");
}
/**
* Retrieves the number of available pages in the given namespace from
* Scalaris.
*
* @param namespace
* the namespace ID
* @param connection
* the connection to Scalaris
*
* @return a result object with the number of pages on success
*/
public static ValueResult<BigInteger> getPageCount(int namespace, Connection connection) {
return getInteger2(connection, getPageCountKey(namespace), false, "page count:" + namespace);
}
/**
* Retrieves the number of available articles, i.e. pages in the main
* namespace, from Scalaris.
*
* @param connection
* the connection to Scalaris
*
* @return a result object with the number of articles on success
*/
public static ValueResult<BigInteger> getArticleCount(Connection connection) {
return getInteger2(connection, getArticleCountKey(), false, "article count");
}
/**
* Retrieves the number of pages in the given category from Scalaris.
*
* @param connection
* the connection to Scalaris
* @param title
* the title of the category
* @param nsObject
* the namespace for page title normalisation
*
* @return a result object with the number of pages on success
*/
public static ValueResult<BigInteger> getPagesInCategoryCount(
Connection connection, String title, final MyNamespace nsObject) {
return getInteger2(connection, getCatPageCountKey(title, nsObject),
false, "page count in " + title);
}
/**
* Retrieves the number of available articles, i.e. pages in the main
* namespace, from Scalaris.
*
* @param connection
* the connection to Scalaris
*
* @return a result object with the number of articles on success
*/
public static ValueResult<BigInteger> getStatsPageEdits(Connection connection) {
return getInteger2(connection, getStatsPageEditsKey(), false, "page edits");
}
/**
* Retrieves an integral number from Scalaris.
*
* @param connection
* the connection to Scalaris
* @param scalaris_key
* the key under which the number is stored in Scalaris
* @param failNotFound
* whether the operation should fail if the key is not found or
* not
* @param statName
* name for the time measurement statistics
*
* @return a result object with the number on success
*/
private static ValueResult<BigInteger> getInteger2(Connection connection,
String scalaris_key, boolean failNotFound, String statName) {
return getInteger2(connection, Arrays.asList(scalaris_key), failNotFound, statName);
}
/**
* Retrieves an integral number from Scalaris.
*
* @param connection
* the connection to Scalaris
* @param scalaris_keys
* the keys under which the number is stored in Scalaris
* @param failNotFound
* whether the operation should fail if the key is not found or
* not
* @param statName
* name for the time measurement statistics
*
* @return a result object with the number on success
*/
private static ValueResult<BigInteger> getInteger2(Connection connection,
Collection<String> scalaris_keys, boolean failNotFound, String statName) {
final long timeAtStart = System.currentTimeMillis();
List<InvolvedKey> involvedKeys = new ArrayList<InvolvedKey>();
if (connection == null) {
return new ValueResult<BigInteger>(false, involvedKeys,
"no connection to Scalaris", true, statName,
System.currentTimeMillis() - timeAtStart);
}
TransactionSingleOp scalaris_single = new TransactionSingleOp(connection);
TransactionSingleOp.ResultList results;
try {
TransactionSingleOp.RequestList requests = new TransactionSingleOp.RequestList();
for (String scalaris_key : scalaris_keys) {
involvedKeys.add(new InvolvedKey(OP.READ, scalaris_key));
requests.addOp(new ReadOp(scalaris_key));
}
results = scalaris_single.req_list(requests);
} catch (Exception e) {
return new ValueResult<BigInteger>(false, involvedKeys,
"unknown exception reading (integral) number(s) at \""
+ scalaris_keys.toString() + "\" from Scalaris: "
+ e.getMessage(), e instanceof ConnectionException,
statName, System.currentTimeMillis() - timeAtStart);
}
BigInteger number = BigInteger.ZERO;
int curOp = 0;
for (String scalaris_key : scalaris_keys) {
try {
number = number.add(results.processReadAt(curOp++).bigIntValue());
} catch (NotFoundException e) {
if (failNotFound) {
return new ValueResult<BigInteger>(false, involvedKeys,
"unknown exception reading (integral) number at \""
+ scalaris_key + "\" from Scalaris: "
+ e.getMessage(), false, statName,
System.currentTimeMillis() - timeAtStart);
}
} catch (Exception e) {
return new ValueResult<BigInteger>(false, involvedKeys,
"unknown exception reading (integral) number at \""
+ scalaris_key + "\" from Scalaris: "
+ e.getMessage(), e instanceof ConnectionException,
statName, System.currentTimeMillis() - timeAtStart);
}
}
return new ValueResult<BigInteger>(involvedKeys, number, statName,
System.currentTimeMillis() - timeAtStart);
}
/**
* Retrieves a random page title from Scalaris.
*
* @param connection
* the connection to Scalaris
* @param random
* the random number generator to use
*
* @return a result object with the page list on success
*/
public static ValueResult<String> getRandomArticle(Connection connection, Random random) {
ValueResult<List<ErlangValue>> result = getPageList3(connection,
ScalarisOpType.PAGE_LIST, Arrays.asList(getPageListKey(0)),
true, "random article",
new ErlangConverter<List<ErlangValue>>() {
@Override
public List<ErlangValue> convert(ErlangValue v)
throws ClassCastException {
return v.listValue();
}
});
if (result.success) {
String randomTitle = result.value.get(
random.nextInt(result.value.size())).stringValue();
return new ValueResult<String>(result.involvedKeys, randomTitle);
} else {
return new ValueResult<String>(false, result.involvedKeys,
result.message, result.connect_failed);
}
}
/**
* Saves or edits a page with the given parameters
*
* @param connection
* the connection to use
* @param title0
* the (unnormalised) title of the page
* @param newRev
* the new revision to add
* @param prevRevId
* the version of the previously existing revision or <tt>-1</tt>
* if there was no previous revision
* @param restrictions
* new restrictions of the page or <tt>null</tt> if they should
* not be changed
* @param siteinfo
* information about the wikipedia (used for parsing categories
* and templates)
* @param username
* name of the user editing the page (for enforcing restrictions)
* @param nsObject
* the namespace for page title normalisation
*
* @return success status
*/
public static SavePageResult savePage(final Connection connection, final String title0,
final Revision newRev, final int prevRevId, final Map<String, String> restrictions,
final SiteInfo siteinfo, final String username, final MyNamespace nsObject) {
long timeAtStart = System.currentTimeMillis();
final String statName = "saving " + title0;
Page oldPage = null;
Page newPage = null;
List<ShortRevision> newShortRevs = null;
BigInteger pageEdits = null;
List<InvolvedKey> involvedKeys = new ArrayList<InvolvedKey>();
if (connection == null) {
return new SavePageResult(false, involvedKeys,
"no connection to Scalaris", true, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
String title;
Integer namespace;
do {
String[] parts = MyWikiModel.splitNsTitle(title0, nsObject);
namespace = nsObject.getNumberByName(parts[0]);
title = MyWikiModel.createFullPageName(namespace.toString(),
MyWikiModel.normaliseName(parts[1]));
} while (false);
Transaction scalaris_tx = new Transaction(connection);
// check that the current version is still up-to-date:
// read old version first, then write
String pageInfoKey = getPageKey(title0, nsObject);
Transaction.RequestList requests = new Transaction.RequestList();
requests.addOp(new ReadOp(pageInfoKey));
Transaction.ResultList results;
try {
ScalarisDataHandler.addInvolvedKeys(involvedKeys, requests.getRequests());
results = scalaris_tx.req_list(requests);
} catch (Exception e) {
return new SavePageResult(false, involvedKeys,
"unknown exception getting page info (" + pageInfoKey
+ ") from Scalaris: " + e.getMessage(),
e instanceof ConnectionException, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
int oldRevId;
try {
oldPage = results.processReadAt(0).jsonValue(Page.class);
newPage = new Page(oldPage.getTitle(), oldPage.getId(),
oldPage.isRedirect(), new LinkedHashMap<String, String>(
oldPage.getRestrictions()), newRev);
oldRevId = oldPage.getCurRev().getId();
} catch (NotFoundException e) {
// this is ok and means that the page did not exist yet
newPage = new Page(title0, 1, false,
new LinkedHashMap<String, String>(), newRev);
oldRevId = 0;
} catch (Exception e) {
return new SavePageResult(false, involvedKeys,
"unknown exception reading \"" + pageInfoKey
+ "\" from Scalaris: " + e.getMessage(),
e instanceof ConnectionException, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
newRev.setId(oldRevId + 1);
if (!newPage.checkEditAllowed(username)) {
return new SavePageResult(false, involvedKeys,
"operation not allowed: edit is restricted", false,
oldPage, newPage, newShortRevs, pageEdits,
statName, System.currentTimeMillis() - timeAtStart);
}
/*
* if prevRevId is greater than 0, it must match the old revision,
* if it is -1, then there should not be an old page
*/
if ((prevRevId > 0 && prevRevId != oldRevId) || (prevRevId == -1 && oldPage != null)) {
return new SavePageResult(false, involvedKeys, "curRev(" + oldRevId
+ ") != oldRev(" + prevRevId + ")", false, oldPage,
newPage, newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
// write:
// get previous categories, templates and backlinks:
final MyWikiModel wikiModel = new MyWikiModel("", "", new MyNamespace(siteinfo));
wikiModel.setPageName(title0);
Set<String> oldCats;
Set<String> oldTpls;
Set<String> oldLnks;
if (oldPage != null && oldPage.getCurRev() != null) {
// get a list of previous categories and templates:
wikiModel.setUp();
final long timeAtRenderStart = System.currentTimeMillis();
wikiModel.render(null, oldPage.getCurRev().unpackedText());
timeAtStart -= (System.currentTimeMillis() - timeAtRenderStart);
// note: no need to normalise the pages, we will do so during the write/read key generation
oldCats = wikiModel.getCategories().keySet();
oldTpls = wikiModel.getTemplates();
if (Options.getInstance().WIKI_USE_BACKLINKS) {
oldLnks = wikiModel.getLinks();
} else {
// use empty link lists to turn back-links off
oldLnks = new HashSet<String>();
}
wikiModel.tearDown();
} else {
oldCats = new HashSet<String>();
oldTpls = new HashSet<String>();
oldLnks = new HashSet<String>();
}
// get new categories and templates
wikiModel.setUp();
do {
final long timeAtRenderStart = System.currentTimeMillis();
wikiModel.render(null, newRev.unpackedText());
timeAtStart -= (System.currentTimeMillis() - timeAtRenderStart);
} while (false);
if (wikiModel.getRedirectLink() != null) {
newPage.setRedirect(true);
}
if (restrictions != null) {
newPage.setRestrictions(restrictions);
}
// note: do not tear down the wiki model - the following statements
// still need it and it will be removed at the end of the method anyway
// note: no need to normalise the pages, we will do so during the write/read key generation
final Set<String> newCats = wikiModel.getCategories().keySet();
Difference catDiff = new Difference(oldCats, newCats,
new Difference.GetPageListAndCountKey() {
@Override
public String getPageListKey(String name) {
return getCatPageListKey(
wikiModel.getCategoryNamespace() + ":" + name,
nsObject);
}
@Override
public String getPageCountKey(String name) {
return getCatPageCountKey(
wikiModel.getCategoryNamespace() + ":" + name,
nsObject);
}
}, ScalarisOpType.CATEGORY_PAGE_LIST);
final Set<String> newTpls = wikiModel.getTemplates();
Difference tplDiff = new Difference(oldTpls, newTpls,
new Difference.GetPageListKey() {
@Override
public String getPageListKey(String name) {
return getTplPageListKey(
wikiModel.getTemplateNamespace() + ":" + name,
nsObject);
}
}, ScalarisOpType.TEMPLATE_PAGE_LIST);
// use empty link lists to turn back-links off
final Set<String> newLnks = Options.getInstance().WIKI_USE_BACKLINKS ? wikiModel.getLinks() : new HashSet<String>();
Difference lnkDiff = new Difference(oldLnks, newLnks,
new Difference.GetPageListKey() {
@Override
public String getPageListKey(String name) {
return getBackLinksPageListKey(name, nsObject);
}
}, ScalarisOpType.BACKLINK_PAGE_LIST);
// now save the changes:
do {
final MyScalarisTxOpExecutor executor0 = new MyScalarisTxOpExecutor(
scalaris_tx, involvedKeys);
executor0.setCommitLast(true);
MyScalarisOpExecWrapper executor = new MyScalarisOpExecWrapper(
executor0);
int articleCountChange = 0;
final boolean wasArticle = (oldPage != null)
&& MyWikiModel.isArticle(namespace, oldLnks, oldCats);
final boolean isArticle = (namespace == 0)
&& MyWikiModel.isArticle(namespace, newLnks, newCats);
if (wasArticle == isArticle) {
articleCountChange = 0;
} else if (!wasArticle) {
articleCountChange = 1;
} else if (!isArticle) {
articleCountChange = -1;
}
// PAGE LISTS UPDATE, step 1: append to / remove from old lists
executor.addAppend(ScalarisOpType.SHORTREV_LIST, getRevListKey(title0, nsObject), new ShortRevision(newRev), null);
if (articleCountChange != 0) {
executor.addIncrement(ScalarisOpType.ARTICLE_COUNT, getArticleCountKey(), articleCountChange);
}
// write differences (categories, templates, backlinks)
catDiff.addScalarisOps(executor, title);
tplDiff.addScalarisOps(executor, title);
lnkDiff.addScalarisOps(executor, title);
// new page? -> add to page/article lists
if (oldPage == null) {
final String pageListKey = getPageListKey(namespace);
final String pageCountKey = getPageCountKey(namespace);
executor.addAppend(ScalarisOpType.PAGE_LIST, pageListKey, title, pageCountKey);
}
executor.addWrite(ScalarisOpType.PAGE, getPageKey(title0, nsObject), newPage);
- executor.addWrite(ScalarisOpType.REVISION, getRevKey(title0, oldPage.getCurRev().getId(), nsObject), oldPage.getCurRev());
+ if (oldPage != null) {
+ executor.addWrite(ScalarisOpType.REVISION, getRevKey(title0, oldPage.getCurRev().getId(), nsObject), oldPage.getCurRev());
+ }
// PAGE LISTS UPDATE, step 2: execute and evaluate operations
try {
executor.getExecutor().run();
} catch (Exception e) {
return new SavePageResult(false, involvedKeys,
"unknown exception writing page \"" + title0
+ "\" to Scalaris: " + e.getMessage(),
e instanceof ConnectionException, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
} while (false);
if (Options.getInstance().WIKI_STORE_CONTRIBUTIONS == STORE_CONTRIB_TYPE.OUTSIDE_TX) {
addContribution(scalaris_tx, oldPage, newPage, involvedKeys);
}
increasePageEditStat(scalaris_tx, involvedKeys);
return new SavePageResult(involvedKeys, oldPage, newPage, newShortRevs,
pageEdits, statName, System.currentTimeMillis() - timeAtStart);
}
/**
* Increases the number of overall page edits statistic.
*
* @param scalaris_tx
* the transaction object to use
* @param involvedKeys
* all keys that have been read or written during the operation
*/
private static void increasePageEditStat(
Transaction scalaris_tx, List<InvolvedKey> involvedKeys) {
// increase number of page edits (for statistics)
// as this is not that important, use a separate transaction and do not
// fail if updating the value fails
final MyScalarisTxOpExecutor executor0 = new MyScalarisTxOpExecutor(
scalaris_tx, involvedKeys);
executor0.setCommitLast(true);
MyScalarisOpExecWrapper executor = new MyScalarisOpExecWrapper(
executor0);
executor.addIncrement(ScalarisOpType.EDIT_STAT, getStatsPageEditsKey(), 1);
try {
executor.getExecutor().run();
} catch (Exception e) {
}
}
/**
* Adds a contribution to the list of contributions of the user.
*
* @param scalaris_tx
* the transaction object to use
* @param oldPage
* the old page object or <tt>null</tt> if there was no old page
* @param newPage
* the newly created page object
* @param involvedKeys
* all keys that have been read or written during the operation
*/
private static void addContribution(
Transaction scalaris_tx, Page oldPage, Page newPage, List<InvolvedKey> involvedKeys) {
// as this is not that important, use a separate transaction and do not
// fail if updating the value fails
final MyScalarisTxOpExecutor executor0 = new MyScalarisTxOpExecutor(
scalaris_tx, involvedKeys);
executor0.setCommitLast(true);
MyScalarisOpExecWrapper executor = new MyScalarisOpExecWrapper(
executor0);
String scalaris_key = getContributionListKey(newPage.getCurRev().getContributor().toString());
executor.addAppend(ScalarisOpType.CONTRIBUTION, scalaris_key,
Arrays.asList(new Contribution(oldPage, newPage)), null);
try {
executor.getExecutor().run();
} catch (Exception e) {
}
}
/**
* Handles differences of sets.
*
* @author Nico Kruber, [email protected]
*/
private static class Difference {
public Set<String> onlyOld;
public Set<String> onlyNew;
@SuppressWarnings("unchecked")
private Set<String>[] changes = new Set[2];
private GetPageListKey keyGen;
final private ScalarisOpType opType;
/**
* Creates a new object calculating differences of two sets.
*
* @param oldSet
* the old set
* @param newSet
* the new set
* @param keyGen
* object creating the Scalaris key for the page lists (based
* on a set entry)
* @param opType
* operation type indicating what is being updated
*/
public Difference(Set<String> oldSet, Set<String> newSet,
GetPageListKey keyGen, ScalarisOpType opType) {
this.onlyOld = new HashSet<String>(oldSet);
this.onlyNew = new HashSet<String>(newSet);
this.onlyOld.removeAll(newSet);
this.onlyNew.removeAll(oldSet);
this.changes[0] = this.onlyOld;
this.changes[1] = this.onlyNew;
this.keyGen = keyGen;
this.opType = opType;
}
static public interface GetPageListKey {
/**
* Gets the Scalaris key for a page list for the given article's
* name.
*
* @param name the name of an article
* @return the key for Scalaris
*/
public abstract String getPageListKey(String name);
}
static public interface GetPageListAndCountKey extends GetPageListKey {
/**
* Gets the Scalaris key for a page list counter for the given
* article's name.
*
* @param name the name of an article
* @return the key for Scalaris
*/
public abstract String getPageCountKey(String name);
}
/**
* Adds the appropriate list append operations to the given executor.
*
* @param executor executor performing the Scalaris operations
* @param title (normalised) page name to update
*/
public void addScalarisOps(MyScalarisOpExecWrapper executor,
String title) {
String scalaris_key;
GetPageListAndCountKey keyCountGen = null;
if (keyGen instanceof GetPageListAndCountKey) {
keyCountGen = (GetPageListAndCountKey) keyGen;
}
// remove from old page list
for (String name: onlyOld) {
scalaris_key = keyGen.getPageListKey(name);
// System.out.println(scalaris_key + " -= " + title);
String scalaris_countKey = keyCountGen == null ? null : keyCountGen.getPageCountKey(name);
executor.addRemove(opType, scalaris_key, title, scalaris_countKey);
}
// add to new page list
for (String name: onlyNew) {
scalaris_key = keyGen.getPageListKey(name);
// System.out.println(scalaris_key + " += " + title);
String scalaris_countKey = keyCountGen == null ? null : keyCountGen.getPageCountKey(name);
executor.addAppend(opType, scalaris_key, title, scalaris_countKey);
}
}
}
/**
* Updates a list of pages by removing and/or adding new page titles.
*
* @param scalaris_tx
* connection to Scalaris
* @param opType
* operation type indicating what is being updated
* @param pageList_key
* Scalaris key for the page list
* @param pageCount_key
* Scalaris key for the number of pages in the list (may be null
* if not used)
* @param entriesToAdd
* list of (normalised) page names to add to the list
* @param entriesToRemove
* list of (normalised) page names to remove from the list
* @param statName
* name for the time measurement statistics
*
* @return the result of the operation
*/
public static ValueResult<Integer> updatePageList(Transaction scalaris_tx,
ScalarisOpType opType, String pageList_key, String pageCount_key,
List<String> entriesToAdd, List<String> entriesToRemove,
final String statName) {
final long timeAtStart = System.currentTimeMillis();
List<InvolvedKey> involvedKeys = new ArrayList<InvolvedKey>();
try {
final MyScalarisTxOpExecutor executor0 = new MyScalarisTxOpExecutor(
scalaris_tx, involvedKeys);
executor0.setCommitLast(true);
MyScalarisOpExecWrapper executor = new MyScalarisOpExecWrapper(
executor0);
executor.addAppendRemove(opType, pageList_key, entriesToAdd,
entriesToRemove, pageCount_key);
executor.getExecutor().run();
return new ValueResult<Integer>(involvedKeys, null, statName,
System.currentTimeMillis() - timeAtStart);
} catch (Exception e) {
return new ValueResult<Integer>(false, involvedKeys,
"unknown exception updating \"" + pageList_key
+ "\" and \"" + pageCount_key + "\" in Scalaris: "
+ e.getMessage(), e instanceof ConnectionException,
statName, System.currentTimeMillis() - timeAtStart);
}
}
/**
* Adds all keys from the given operation list to the list of involved keys.
*
* @param involvedKeys
* list of involved keys
* @param ops
* new operations
*/
public static void addInvolvedKeys(List<InvolvedKey> involvedKeys, Collection<? extends Operation> ops) {
assert involvedKeys != null;
assert ops != null;
for (Operation op : ops) {
final OtpErlangString key = op.getKey();
if (key != null) {
if (op instanceof ReadOp) {
involvedKeys.add(new InvolvedKey(InvolvedKey.OP.READ, key.stringValue()));
} else {
involvedKeys.add(new InvolvedKey(InvolvedKey.OP.WRITE, key.stringValue()));
}
}
}
}
}
| true | true |
public static SavePageResult savePage(final Connection connection, final String title0,
final Revision newRev, final int prevRevId, final Map<String, String> restrictions,
final SiteInfo siteinfo, final String username, final MyNamespace nsObject) {
long timeAtStart = System.currentTimeMillis();
final String statName = "saving " + title0;
Page oldPage = null;
Page newPage = null;
List<ShortRevision> newShortRevs = null;
BigInteger pageEdits = null;
List<InvolvedKey> involvedKeys = new ArrayList<InvolvedKey>();
if (connection == null) {
return new SavePageResult(false, involvedKeys,
"no connection to Scalaris", true, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
String title;
Integer namespace;
do {
String[] parts = MyWikiModel.splitNsTitle(title0, nsObject);
namespace = nsObject.getNumberByName(parts[0]);
title = MyWikiModel.createFullPageName(namespace.toString(),
MyWikiModel.normaliseName(parts[1]));
} while (false);
Transaction scalaris_tx = new Transaction(connection);
// check that the current version is still up-to-date:
// read old version first, then write
String pageInfoKey = getPageKey(title0, nsObject);
Transaction.RequestList requests = new Transaction.RequestList();
requests.addOp(new ReadOp(pageInfoKey));
Transaction.ResultList results;
try {
ScalarisDataHandler.addInvolvedKeys(involvedKeys, requests.getRequests());
results = scalaris_tx.req_list(requests);
} catch (Exception e) {
return new SavePageResult(false, involvedKeys,
"unknown exception getting page info (" + pageInfoKey
+ ") from Scalaris: " + e.getMessage(),
e instanceof ConnectionException, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
int oldRevId;
try {
oldPage = results.processReadAt(0).jsonValue(Page.class);
newPage = new Page(oldPage.getTitle(), oldPage.getId(),
oldPage.isRedirect(), new LinkedHashMap<String, String>(
oldPage.getRestrictions()), newRev);
oldRevId = oldPage.getCurRev().getId();
} catch (NotFoundException e) {
// this is ok and means that the page did not exist yet
newPage = new Page(title0, 1, false,
new LinkedHashMap<String, String>(), newRev);
oldRevId = 0;
} catch (Exception e) {
return new SavePageResult(false, involvedKeys,
"unknown exception reading \"" + pageInfoKey
+ "\" from Scalaris: " + e.getMessage(),
e instanceof ConnectionException, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
newRev.setId(oldRevId + 1);
if (!newPage.checkEditAllowed(username)) {
return new SavePageResult(false, involvedKeys,
"operation not allowed: edit is restricted", false,
oldPage, newPage, newShortRevs, pageEdits,
statName, System.currentTimeMillis() - timeAtStart);
}
/*
* if prevRevId is greater than 0, it must match the old revision,
* if it is -1, then there should not be an old page
*/
if ((prevRevId > 0 && prevRevId != oldRevId) || (prevRevId == -1 && oldPage != null)) {
return new SavePageResult(false, involvedKeys, "curRev(" + oldRevId
+ ") != oldRev(" + prevRevId + ")", false, oldPage,
newPage, newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
// write:
// get previous categories, templates and backlinks:
final MyWikiModel wikiModel = new MyWikiModel("", "", new MyNamespace(siteinfo));
wikiModel.setPageName(title0);
Set<String> oldCats;
Set<String> oldTpls;
Set<String> oldLnks;
if (oldPage != null && oldPage.getCurRev() != null) {
// get a list of previous categories and templates:
wikiModel.setUp();
final long timeAtRenderStart = System.currentTimeMillis();
wikiModel.render(null, oldPage.getCurRev().unpackedText());
timeAtStart -= (System.currentTimeMillis() - timeAtRenderStart);
// note: no need to normalise the pages, we will do so during the write/read key generation
oldCats = wikiModel.getCategories().keySet();
oldTpls = wikiModel.getTemplates();
if (Options.getInstance().WIKI_USE_BACKLINKS) {
oldLnks = wikiModel.getLinks();
} else {
// use empty link lists to turn back-links off
oldLnks = new HashSet<String>();
}
wikiModel.tearDown();
} else {
oldCats = new HashSet<String>();
oldTpls = new HashSet<String>();
oldLnks = new HashSet<String>();
}
// get new categories and templates
wikiModel.setUp();
do {
final long timeAtRenderStart = System.currentTimeMillis();
wikiModel.render(null, newRev.unpackedText());
timeAtStart -= (System.currentTimeMillis() - timeAtRenderStart);
} while (false);
if (wikiModel.getRedirectLink() != null) {
newPage.setRedirect(true);
}
if (restrictions != null) {
newPage.setRestrictions(restrictions);
}
// note: do not tear down the wiki model - the following statements
// still need it and it will be removed at the end of the method anyway
// note: no need to normalise the pages, we will do so during the write/read key generation
final Set<String> newCats = wikiModel.getCategories().keySet();
Difference catDiff = new Difference(oldCats, newCats,
new Difference.GetPageListAndCountKey() {
@Override
public String getPageListKey(String name) {
return getCatPageListKey(
wikiModel.getCategoryNamespace() + ":" + name,
nsObject);
}
@Override
public String getPageCountKey(String name) {
return getCatPageCountKey(
wikiModel.getCategoryNamespace() + ":" + name,
nsObject);
}
}, ScalarisOpType.CATEGORY_PAGE_LIST);
final Set<String> newTpls = wikiModel.getTemplates();
Difference tplDiff = new Difference(oldTpls, newTpls,
new Difference.GetPageListKey() {
@Override
public String getPageListKey(String name) {
return getTplPageListKey(
wikiModel.getTemplateNamespace() + ":" + name,
nsObject);
}
}, ScalarisOpType.TEMPLATE_PAGE_LIST);
// use empty link lists to turn back-links off
final Set<String> newLnks = Options.getInstance().WIKI_USE_BACKLINKS ? wikiModel.getLinks() : new HashSet<String>();
Difference lnkDiff = new Difference(oldLnks, newLnks,
new Difference.GetPageListKey() {
@Override
public String getPageListKey(String name) {
return getBackLinksPageListKey(name, nsObject);
}
}, ScalarisOpType.BACKLINK_PAGE_LIST);
// now save the changes:
do {
final MyScalarisTxOpExecutor executor0 = new MyScalarisTxOpExecutor(
scalaris_tx, involvedKeys);
executor0.setCommitLast(true);
MyScalarisOpExecWrapper executor = new MyScalarisOpExecWrapper(
executor0);
int articleCountChange = 0;
final boolean wasArticle = (oldPage != null)
&& MyWikiModel.isArticle(namespace, oldLnks, oldCats);
final boolean isArticle = (namespace == 0)
&& MyWikiModel.isArticle(namespace, newLnks, newCats);
if (wasArticle == isArticle) {
articleCountChange = 0;
} else if (!wasArticle) {
articleCountChange = 1;
} else if (!isArticle) {
articleCountChange = -1;
}
// PAGE LISTS UPDATE, step 1: append to / remove from old lists
executor.addAppend(ScalarisOpType.SHORTREV_LIST, getRevListKey(title0, nsObject), new ShortRevision(newRev), null);
if (articleCountChange != 0) {
executor.addIncrement(ScalarisOpType.ARTICLE_COUNT, getArticleCountKey(), articleCountChange);
}
// write differences (categories, templates, backlinks)
catDiff.addScalarisOps(executor, title);
tplDiff.addScalarisOps(executor, title);
lnkDiff.addScalarisOps(executor, title);
// new page? -> add to page/article lists
if (oldPage == null) {
final String pageListKey = getPageListKey(namespace);
final String pageCountKey = getPageCountKey(namespace);
executor.addAppend(ScalarisOpType.PAGE_LIST, pageListKey, title, pageCountKey);
}
executor.addWrite(ScalarisOpType.PAGE, getPageKey(title0, nsObject), newPage);
executor.addWrite(ScalarisOpType.REVISION, getRevKey(title0, oldPage.getCurRev().getId(), nsObject), oldPage.getCurRev());
// PAGE LISTS UPDATE, step 2: execute and evaluate operations
try {
executor.getExecutor().run();
} catch (Exception e) {
return new SavePageResult(false, involvedKeys,
"unknown exception writing page \"" + title0
+ "\" to Scalaris: " + e.getMessage(),
e instanceof ConnectionException, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
} while (false);
if (Options.getInstance().WIKI_STORE_CONTRIBUTIONS == STORE_CONTRIB_TYPE.OUTSIDE_TX) {
addContribution(scalaris_tx, oldPage, newPage, involvedKeys);
}
increasePageEditStat(scalaris_tx, involvedKeys);
return new SavePageResult(involvedKeys, oldPage, newPage, newShortRevs,
pageEdits, statName, System.currentTimeMillis() - timeAtStart);
}
|
public static SavePageResult savePage(final Connection connection, final String title0,
final Revision newRev, final int prevRevId, final Map<String, String> restrictions,
final SiteInfo siteinfo, final String username, final MyNamespace nsObject) {
long timeAtStart = System.currentTimeMillis();
final String statName = "saving " + title0;
Page oldPage = null;
Page newPage = null;
List<ShortRevision> newShortRevs = null;
BigInteger pageEdits = null;
List<InvolvedKey> involvedKeys = new ArrayList<InvolvedKey>();
if (connection == null) {
return new SavePageResult(false, involvedKeys,
"no connection to Scalaris", true, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
String title;
Integer namespace;
do {
String[] parts = MyWikiModel.splitNsTitle(title0, nsObject);
namespace = nsObject.getNumberByName(parts[0]);
title = MyWikiModel.createFullPageName(namespace.toString(),
MyWikiModel.normaliseName(parts[1]));
} while (false);
Transaction scalaris_tx = new Transaction(connection);
// check that the current version is still up-to-date:
// read old version first, then write
String pageInfoKey = getPageKey(title0, nsObject);
Transaction.RequestList requests = new Transaction.RequestList();
requests.addOp(new ReadOp(pageInfoKey));
Transaction.ResultList results;
try {
ScalarisDataHandler.addInvolvedKeys(involvedKeys, requests.getRequests());
results = scalaris_tx.req_list(requests);
} catch (Exception e) {
return new SavePageResult(false, involvedKeys,
"unknown exception getting page info (" + pageInfoKey
+ ") from Scalaris: " + e.getMessage(),
e instanceof ConnectionException, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
int oldRevId;
try {
oldPage = results.processReadAt(0).jsonValue(Page.class);
newPage = new Page(oldPage.getTitle(), oldPage.getId(),
oldPage.isRedirect(), new LinkedHashMap<String, String>(
oldPage.getRestrictions()), newRev);
oldRevId = oldPage.getCurRev().getId();
} catch (NotFoundException e) {
// this is ok and means that the page did not exist yet
newPage = new Page(title0, 1, false,
new LinkedHashMap<String, String>(), newRev);
oldRevId = 0;
} catch (Exception e) {
return new SavePageResult(false, involvedKeys,
"unknown exception reading \"" + pageInfoKey
+ "\" from Scalaris: " + e.getMessage(),
e instanceof ConnectionException, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
newRev.setId(oldRevId + 1);
if (!newPage.checkEditAllowed(username)) {
return new SavePageResult(false, involvedKeys,
"operation not allowed: edit is restricted", false,
oldPage, newPage, newShortRevs, pageEdits,
statName, System.currentTimeMillis() - timeAtStart);
}
/*
* if prevRevId is greater than 0, it must match the old revision,
* if it is -1, then there should not be an old page
*/
if ((prevRevId > 0 && prevRevId != oldRevId) || (prevRevId == -1 && oldPage != null)) {
return new SavePageResult(false, involvedKeys, "curRev(" + oldRevId
+ ") != oldRev(" + prevRevId + ")", false, oldPage,
newPage, newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
// write:
// get previous categories, templates and backlinks:
final MyWikiModel wikiModel = new MyWikiModel("", "", new MyNamespace(siteinfo));
wikiModel.setPageName(title0);
Set<String> oldCats;
Set<String> oldTpls;
Set<String> oldLnks;
if (oldPage != null && oldPage.getCurRev() != null) {
// get a list of previous categories and templates:
wikiModel.setUp();
final long timeAtRenderStart = System.currentTimeMillis();
wikiModel.render(null, oldPage.getCurRev().unpackedText());
timeAtStart -= (System.currentTimeMillis() - timeAtRenderStart);
// note: no need to normalise the pages, we will do so during the write/read key generation
oldCats = wikiModel.getCategories().keySet();
oldTpls = wikiModel.getTemplates();
if (Options.getInstance().WIKI_USE_BACKLINKS) {
oldLnks = wikiModel.getLinks();
} else {
// use empty link lists to turn back-links off
oldLnks = new HashSet<String>();
}
wikiModel.tearDown();
} else {
oldCats = new HashSet<String>();
oldTpls = new HashSet<String>();
oldLnks = new HashSet<String>();
}
// get new categories and templates
wikiModel.setUp();
do {
final long timeAtRenderStart = System.currentTimeMillis();
wikiModel.render(null, newRev.unpackedText());
timeAtStart -= (System.currentTimeMillis() - timeAtRenderStart);
} while (false);
if (wikiModel.getRedirectLink() != null) {
newPage.setRedirect(true);
}
if (restrictions != null) {
newPage.setRestrictions(restrictions);
}
// note: do not tear down the wiki model - the following statements
// still need it and it will be removed at the end of the method anyway
// note: no need to normalise the pages, we will do so during the write/read key generation
final Set<String> newCats = wikiModel.getCategories().keySet();
Difference catDiff = new Difference(oldCats, newCats,
new Difference.GetPageListAndCountKey() {
@Override
public String getPageListKey(String name) {
return getCatPageListKey(
wikiModel.getCategoryNamespace() + ":" + name,
nsObject);
}
@Override
public String getPageCountKey(String name) {
return getCatPageCountKey(
wikiModel.getCategoryNamespace() + ":" + name,
nsObject);
}
}, ScalarisOpType.CATEGORY_PAGE_LIST);
final Set<String> newTpls = wikiModel.getTemplates();
Difference tplDiff = new Difference(oldTpls, newTpls,
new Difference.GetPageListKey() {
@Override
public String getPageListKey(String name) {
return getTplPageListKey(
wikiModel.getTemplateNamespace() + ":" + name,
nsObject);
}
}, ScalarisOpType.TEMPLATE_PAGE_LIST);
// use empty link lists to turn back-links off
final Set<String> newLnks = Options.getInstance().WIKI_USE_BACKLINKS ? wikiModel.getLinks() : new HashSet<String>();
Difference lnkDiff = new Difference(oldLnks, newLnks,
new Difference.GetPageListKey() {
@Override
public String getPageListKey(String name) {
return getBackLinksPageListKey(name, nsObject);
}
}, ScalarisOpType.BACKLINK_PAGE_LIST);
// now save the changes:
do {
final MyScalarisTxOpExecutor executor0 = new MyScalarisTxOpExecutor(
scalaris_tx, involvedKeys);
executor0.setCommitLast(true);
MyScalarisOpExecWrapper executor = new MyScalarisOpExecWrapper(
executor0);
int articleCountChange = 0;
final boolean wasArticle = (oldPage != null)
&& MyWikiModel.isArticle(namespace, oldLnks, oldCats);
final boolean isArticle = (namespace == 0)
&& MyWikiModel.isArticle(namespace, newLnks, newCats);
if (wasArticle == isArticle) {
articleCountChange = 0;
} else if (!wasArticle) {
articleCountChange = 1;
} else if (!isArticle) {
articleCountChange = -1;
}
// PAGE LISTS UPDATE, step 1: append to / remove from old lists
executor.addAppend(ScalarisOpType.SHORTREV_LIST, getRevListKey(title0, nsObject), new ShortRevision(newRev), null);
if (articleCountChange != 0) {
executor.addIncrement(ScalarisOpType.ARTICLE_COUNT, getArticleCountKey(), articleCountChange);
}
// write differences (categories, templates, backlinks)
catDiff.addScalarisOps(executor, title);
tplDiff.addScalarisOps(executor, title);
lnkDiff.addScalarisOps(executor, title);
// new page? -> add to page/article lists
if (oldPage == null) {
final String pageListKey = getPageListKey(namespace);
final String pageCountKey = getPageCountKey(namespace);
executor.addAppend(ScalarisOpType.PAGE_LIST, pageListKey, title, pageCountKey);
}
executor.addWrite(ScalarisOpType.PAGE, getPageKey(title0, nsObject), newPage);
if (oldPage != null) {
executor.addWrite(ScalarisOpType.REVISION, getRevKey(title0, oldPage.getCurRev().getId(), nsObject), oldPage.getCurRev());
}
// PAGE LISTS UPDATE, step 2: execute and evaluate operations
try {
executor.getExecutor().run();
} catch (Exception e) {
return new SavePageResult(false, involvedKeys,
"unknown exception writing page \"" + title0
+ "\" to Scalaris: " + e.getMessage(),
e instanceof ConnectionException, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
} while (false);
if (Options.getInstance().WIKI_STORE_CONTRIBUTIONS == STORE_CONTRIB_TYPE.OUTSIDE_TX) {
addContribution(scalaris_tx, oldPage, newPage, involvedKeys);
}
increasePageEditStat(scalaris_tx, involvedKeys);
return new SavePageResult(involvedKeys, oldPage, newPage, newShortRevs,
pageEdits, statName, System.currentTimeMillis() - timeAtStart);
}
|
diff --git a/src/test/java/urbanairship/UrbanAirshipClientTest.java b/src/test/java/urbanairship/UrbanAirshipClientTest.java
index ae85caa..db5b6f8 100644
--- a/src/test/java/urbanairship/UrbanAirshipClientTest.java
+++ b/src/test/java/urbanairship/UrbanAirshipClientTest.java
@@ -1,105 +1,106 @@
package urbanairship;
import java.util.Calendar;
import org.testng.Assert;
import org.testng.annotations.*;
import com.google.gson.Gson;
public class UrbanAirshipClientTest
{
private String username = "username";
private String password = "password";
@BeforeTest
public void setUp()
{
String usernameProperty = (String) System.getProperties().get("urbanairship.java.username");
if (usernameProperty != null)
{
username = usernameProperty;
}
String passwordProperty = (String) System.getProperties().get("urbanairship.java.password");
if (passwordProperty != null)
{
password = passwordProperty;
}
}
@Test(enabled=false)
public void client()
{
UrbanAirshipClient client = new UrbanAirshipClient(username, password);
Device dev = new Device();
dev.setiOSDeviceToken("todo");
client.register(dev);
}
@Test
public void jsonPush()
{
APS aps = new APS();
aps.setAlert("Hello world");
aps.setAutoBadge("+1");
Push p = new Push();
p.setAps(aps);
Gson gson = GsonFactory.create();
String json = gson.toJson(p);
Assert.assertNotNull(json);
System.out.println("Push: " + json);
}
@Test
public void jsonCalendar()
{
APS aps = new APS();
aps.setAlert("You've got mail!");
aps.setBadge(1);
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_YEAR, 1);
+ c.set(Calendar.MILLISECOND, 0);
Broadcast bcast = new Broadcast();
bcast.setScheduleFor(c);
Assert.assertNotNull(bcast.getScheduleFor());
bcast.setAps(aps);
Gson gson = GsonFactory.create();
String json = gson.toJson(bcast);
Assert.assertNotNull(json);
System.out.println("Broadcast: " + json);
Broadcast bcast2 = gson.fromJson(json, Broadcast.class);
Assert.assertNotNull(bcast2);
Assert.assertNotNull(bcast2.getScheduleFor());
Assert.assertEquals(bcast.getScheduleFor().getTimeInMillis(),
bcast2.getScheduleFor().getTimeInMillis());
}
}
| true | true |
public void jsonCalendar()
{
APS aps = new APS();
aps.setAlert("You've got mail!");
aps.setBadge(1);
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_YEAR, 1);
Broadcast bcast = new Broadcast();
bcast.setScheduleFor(c);
Assert.assertNotNull(bcast.getScheduleFor());
bcast.setAps(aps);
Gson gson = GsonFactory.create();
String json = gson.toJson(bcast);
Assert.assertNotNull(json);
System.out.println("Broadcast: " + json);
Broadcast bcast2 = gson.fromJson(json, Broadcast.class);
Assert.assertNotNull(bcast2);
Assert.assertNotNull(bcast2.getScheduleFor());
Assert.assertEquals(bcast.getScheduleFor().getTimeInMillis(),
bcast2.getScheduleFor().getTimeInMillis());
}
|
public void jsonCalendar()
{
APS aps = new APS();
aps.setAlert("You've got mail!");
aps.setBadge(1);
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_YEAR, 1);
c.set(Calendar.MILLISECOND, 0);
Broadcast bcast = new Broadcast();
bcast.setScheduleFor(c);
Assert.assertNotNull(bcast.getScheduleFor());
bcast.setAps(aps);
Gson gson = GsonFactory.create();
String json = gson.toJson(bcast);
Assert.assertNotNull(json);
System.out.println("Broadcast: " + json);
Broadcast bcast2 = gson.fromJson(json, Broadcast.class);
Assert.assertNotNull(bcast2);
Assert.assertNotNull(bcast2.getScheduleFor());
Assert.assertEquals(bcast.getScheduleFor().getTimeInMillis(),
bcast2.getScheduleFor().getTimeInMillis());
}
|
diff --git a/bundles/core/org.openhab.core/src/main/java/org/openhab/core/internal/items/ItemUpdater.java b/bundles/core/org.openhab.core/src/main/java/org/openhab/core/internal/items/ItemUpdater.java
index 16d833ce..67a096ae 100644
--- a/bundles/core/org.openhab.core/src/main/java/org/openhab/core/internal/items/ItemUpdater.java
+++ b/bundles/core/org.openhab.core/src/main/java/org/openhab/core/internal/items/ItemUpdater.java
@@ -1,120 +1,120 @@
/**
* openHAB, the open Home Automation Bus.
* Copyright (C) 2010-2013, openHAB.org <[email protected]>
*
* See the contributors.txt file in the distribution for a
* full listing of individual contributors.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with Eclipse (or a modified version of that library),
* containing parts covered by the terms of the Eclipse Public License
* (EPL), the licensors of this Program grant you additional permission
* to convey the resulting work.
*/
package org.openhab.core.internal.items;
import org.openhab.core.events.AbstractEventSubscriber;
import org.openhab.core.items.GenericItem;
import org.openhab.core.items.GroupItem;
import org.openhab.core.items.Item;
import org.openhab.core.items.ItemNotFoundException;
import org.openhab.core.items.ItemRegistry;
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The ItemUpdater listens on the event bus and passes any received status update
* to the item registry.
*
* @author Kai Kreuzer
* @since 0.1.0
*
*/
public class ItemUpdater extends AbstractEventSubscriber {
private static final Logger logger = LoggerFactory.getLogger(ItemUpdater.class);
protected ItemRegistry itemRegistry;
public void setItemRegistry(ItemRegistry itemRegistry) {
this.itemRegistry = itemRegistry;
}
public void unsetItemRegistry(ItemRegistry itemRegistry) {
this.itemRegistry = null;
}
/**
* {@inheritDoc}
*/
@Override
public void receiveUpdate(String itemName, State newStatus) {
if (itemRegistry != null) {
try {
GenericItem item = (GenericItem) itemRegistry.getItem(itemName);
boolean isAccepted = false;
if (item.getAcceptedDataTypes().contains(newStatus.getClass())) {
isAccepted = true;
} else {
// Look for class hierarchy
for (Class<? extends State> state : item.getAcceptedDataTypes()) {
try {
if (!state.isEnum() && state.newInstance().getClass().isAssignableFrom(newStatus.getClass())) {
isAccepted = true;
break;
}
} catch (InstantiationException e) {
- logger.warn("InstantiationException on ", e.getMessage()); // Should never happen
+ logger.warn("InstantiationException on {}", e.getMessage()); // Should never happen
} catch (IllegalAccessException e) {
- logger.warn("IllegalAccessException on ", e.getMessage()); // Should never happen
+ logger.warn("IllegalAccessException on {}", e.getMessage()); // Should never happen
}
}
}
if (isAccepted) {
item.setState(newStatus);
} else {
logger.debug("Received update of a not accepted type (" + newStatus.getClass().getSimpleName() + ") for item " + itemName);
}
} catch (ItemNotFoundException e) {
logger.debug("Received update for non-existing item: {}", e.getMessage());
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void receiveCommand(String itemName, Command command) {
// if the item is a group, we have to pass the command to it as it needs to pass the command to its members
if(itemRegistry!=null) {
try {
Item item = itemRegistry.getItem(itemName);
if (item instanceof GroupItem) {
GroupItem groupItem = (GroupItem) item;
groupItem.send(command);
}
} catch (ItemNotFoundException e) {
logger.debug("Received command for non-existing item: {}", e.getMessage());
}
}
}
}
| false | true |
public void receiveUpdate(String itemName, State newStatus) {
if (itemRegistry != null) {
try {
GenericItem item = (GenericItem) itemRegistry.getItem(itemName);
boolean isAccepted = false;
if (item.getAcceptedDataTypes().contains(newStatus.getClass())) {
isAccepted = true;
} else {
// Look for class hierarchy
for (Class<? extends State> state : item.getAcceptedDataTypes()) {
try {
if (!state.isEnum() && state.newInstance().getClass().isAssignableFrom(newStatus.getClass())) {
isAccepted = true;
break;
}
} catch (InstantiationException e) {
logger.warn("InstantiationException on ", e.getMessage()); // Should never happen
} catch (IllegalAccessException e) {
logger.warn("IllegalAccessException on ", e.getMessage()); // Should never happen
}
}
}
if (isAccepted) {
item.setState(newStatus);
} else {
logger.debug("Received update of a not accepted type (" + newStatus.getClass().getSimpleName() + ") for item " + itemName);
}
} catch (ItemNotFoundException e) {
logger.debug("Received update for non-existing item: {}", e.getMessage());
}
}
}
|
public void receiveUpdate(String itemName, State newStatus) {
if (itemRegistry != null) {
try {
GenericItem item = (GenericItem) itemRegistry.getItem(itemName);
boolean isAccepted = false;
if (item.getAcceptedDataTypes().contains(newStatus.getClass())) {
isAccepted = true;
} else {
// Look for class hierarchy
for (Class<? extends State> state : item.getAcceptedDataTypes()) {
try {
if (!state.isEnum() && state.newInstance().getClass().isAssignableFrom(newStatus.getClass())) {
isAccepted = true;
break;
}
} catch (InstantiationException e) {
logger.warn("InstantiationException on {}", e.getMessage()); // Should never happen
} catch (IllegalAccessException e) {
logger.warn("IllegalAccessException on {}", e.getMessage()); // Should never happen
}
}
}
if (isAccepted) {
item.setState(newStatus);
} else {
logger.debug("Received update of a not accepted type (" + newStatus.getClass().getSimpleName() + ") for item " + itemName);
}
} catch (ItemNotFoundException e) {
logger.debug("Received update for non-existing item: {}", e.getMessage());
}
}
}
|
diff --git a/src/com/kmcginn/airquotes/HelpActivity.java b/src/com/kmcginn/airquotes/HelpActivity.java
index 3f5dda8..04b93a8 100644
--- a/src/com/kmcginn/airquotes/HelpActivity.java
+++ b/src/com/kmcginn/airquotes/HelpActivity.java
@@ -1,178 +1,179 @@
package com.kmcginn.airquotes;
import java.util.Locale;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
public class HelpActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
+ actionBar.setDisplayHomeAsUpEnabled(true);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.help_pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.help, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
// TODO: If Settings has multiple levels, Up should navigate up
// that hierarchy.
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
//INIT FRAGMENT TYPE BASED ON POSITION
Fragment fragment = new Fragment();
switch(position) {
case 0:
fragment = MessageHelpFragment.newInstance();
break;
case 1:
fragment = MapHelpFragment.newInstance();
break;
case 2:
fragment = FriendsHelpFragment.newInstance();
break;
default:
fragment = new Fragment();
}
//Bundle args = new Bundle();
//args.putString("user", user);
//example of how to add arguments to fragments, if we need it
//args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
//fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
}
| true | true |
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.help_pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
|
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayHomeAsUpEnabled(true);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.help_pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
|
diff --git a/cst/eu.esdihumboldt.cst/src/main/java/eu/esdihumboldt/cst/transformer/configuration/ReflectionHelper.java b/cst/eu.esdihumboldt.cst/src/main/java/eu/esdihumboldt/cst/transformer/configuration/ReflectionHelper.java
index ab3ee1208..c542a8efe 100644
--- a/cst/eu.esdihumboldt.cst/src/main/java/eu/esdihumboldt/cst/transformer/configuration/ReflectionHelper.java
+++ b/cst/eu.esdihumboldt.cst/src/main/java/eu/esdihumboldt/cst/transformer/configuration/ReflectionHelper.java
@@ -1,716 +1,728 @@
/*
* HUMBOLDT: A Framework for Data Harmonisation and Service Integration.
* EU Integrated Project #030962 01.10.2006 - 30.09.2010
*
* For more information on the project, please refer to the this web site:
* http://www.esdi-humboldt.eu
*
* LICENSE: For information on the license under which this program is
* available, please refer to http:/www.esdi-humboldt.eu/license.html#core
* (c) the HUMBOLDT Consortium, 2007 to 2010.
*/
package eu.esdihumboldt.cst.transformer.configuration;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipException;
/**
* <p>Title: ReflectionHelper</p>
* <p>Description: Provides several utility methods which use Java Reflections
* to access hidden types, fields and methods.</p>
* <p>Copyright: Copyright (c) 2004-2008</p>
* <p>Company: Fraunhofer IGD</p>
* @author Michel Kraemer
* @version $Id: ReflectionHelper.java 6090 2009-12-11 09:50:36Z mkraemer $
*/
public class ReflectionHelper {
/**
* The package resolver used to retrieve URLs to packages
*/
private static PackageResolver _packageResolver =
new DefaultPackageResolver();
/**
* Sets the package resolver used to retrieve URLs to packages
* @see #getFilesFromPackage(String)
* @param res the package resolver
*/
public static synchronized void setPackageResolver(PackageResolver res) {
_packageResolver = res;
}
/**
* Returns a public setter method for a given property
* @param c the class which would contain the setter method
* @param property the property
* @param propertyType the property's type
* @return the public setter or null if there is no setter for this property
*/
public static Method findSetter(Class<?> c, String property,
Class<?> propertyType) {
char[] propertyNameArr = property.toCharArray();
propertyNameArr[0] = Character.toUpperCase(propertyNameArr[0]);
String setterName = "set" + new String(propertyNameArr);
Method result = null;
Method[] methods = c.getMethods();
for (Method m : methods) {
if (m.getName().equals(setterName) &&
m.getParameterTypes().length == 1 &&
(propertyType == null || m.getParameterTypes()[0].isAssignableFrom(propertyType))) {
result = m;
break;
}
}
return result;
}
/**
* Returns a setter method for a given property, no matter if the
* method is visible or hidden or if it is declared in the given class
* or in a superclass or implemented interface.
* @param c the class which would contain the setter method
* @param property the property
* @param propertyType the property's type
* @return the setter or null if there is no setter for this property
*/
public static Method findDeepSetter(Class<?> c, String property,
Class<?> propertyType) {
if (c == Object.class || c == null) {
return null;
}
char[] propertyNameArr = property.toCharArray();
propertyNameArr[0] = Character.toUpperCase(propertyNameArr[0]);
String setterName = "set" + new String(propertyNameArr);
Method result = null;
//search visible and hidden methods in this class
Method[] methods = c.getDeclaredMethods();
for (Method m : methods) {
if (m.getName().equals(setterName) &&
m.getParameterTypes().length == 1 &&
(propertyType == null || m.getParameterTypes()[0].isAssignableFrom(propertyType))) {
result = m;
break;
}
}
//search superclass and interfaces
if (result == null) {
result = findDeepSetter(c.getSuperclass(), property, propertyType);
if (result == null) {
Class<?>[] interfaces = c.getInterfaces();
for (Class<?> inter : interfaces) {
result = findDeepSetter(inter, property, propertyType);
if (result != null) {
break;
}
}
}
}
return result;
}
/**
* Returns a public getter method for a given property
* @param c the class which would contain the getter method
* @param property the property
* @param propertyType the property's type
* @return the public getter or null if there is no getter for this property
*/
public static Method findGetter(Class<?> c, String property,
Class<?> propertyType) {
char[] propertyNameArr = property.toCharArray();
propertyNameArr[0] = Character.toUpperCase(propertyNameArr[0]);
String getterName = "get" + new String(propertyNameArr);
Method result = null;
Method[] methods = c.getMethods();
for (Method m : methods) {
if (m.getName().equals(getterName) &&
m.getParameterTypes().length == 0 &&
(propertyType == null || propertyType.isAssignableFrom(m.getReturnType()))) {
result = m;
break;
}
}
return result;
}
/**
* Returns a getter method for a given property, no matter if the
* method is visible or hidden or if it is declared in the given class
* or in a superclass or implemented interface.
* @param c the class which would contain the getter method
* @param property the property
* @param propertyType the property's type (can be null if the type
* does not matter)
* @return the getter or null if there is no getter for this property
*/
public static Method findDeepGetter(Class<?> c, String property,
Class<?> propertyType) {
if (c == Object.class || c == null) {
return null;
}
char[] propertyNameArr = property.toCharArray();
propertyNameArr[0] = Character.toUpperCase(propertyNameArr[0]);
String getterName = "get" + new String(propertyNameArr);
Method result = null;
//search visible and hidden methods in this class
Method[] methods = c.getDeclaredMethods();
for (Method m : methods) {
if (m.getName().equals(getterName) &&
m.getParameterTypes().length == 0 &&
(propertyType == null || propertyType.isAssignableFrom(m.getReturnType()))) {
result = m;
break;
}
}
//search superclass and interfaces
if (result == null) {
result = findDeepGetter(c.getSuperclass(), property, propertyType);
if (result == null) {
Class<?>[] interfaces = c.getInterfaces();
for (Class<?> inter : interfaces) {
result = findDeepGetter(inter, property, propertyType);
if (result != null) {
break;
}
}
}
}
return result;
}
/**
* Returns a public field for a given property
* @param c the class which would contain the field
* @param property the property
* @param propertyType the property's type
* @return the field or null if there is no field for this property
*/
public static Field findField(Class<?> c, String property,
Class<?> propertyType) {
Field result = null;
Field[] fields = c.getFields();
for (Field f : fields) {
String fn = f.getName();
if (fn.charAt(0) == '_') {
//handle code style
fn = fn.substring(1);
}
if (fn.equals(property) &&
(propertyType == null || f.getType().isAssignableFrom(propertyType))) {
result = f;
break;
}
}
return result;
}
/**
* Returns a field for a given property, no matter if the
* field is visible or hidden or if it is declared in the given class
* or in a superclass.
* @param c the class which would contain the field
* @param property the property
* @param propertyType the property's type
* @return the field or null if there is no field for this property
*/
public static Field findDeepField(Class<?> c, String property,
Class<?> propertyType) {
if (c == Object.class || c == null) {
return null;
}
Field result = null;
//search visible and hidden fields in this class
Field[] fields = c.getDeclaredFields();
for (Field f : fields) {
String fn = f.getName();
if (fn.charAt(0) == '_') {
//handle code style
fn = fn.substring(1);
}
if (fn.equals(property) &&
(propertyType == null || f.getType().isAssignableFrom(propertyType))) {
result = f;
break;
}
}
//search superclass
if (result == null) {
result = findDeepField(c.getSuperclass(), property, propertyType);
}
return result;
}
/**
* Invokes a setter method on a given bean
* @param bean the object to invoke the getter on
* @param setter the setter method
* @param value the value to set
* @throws IllegalArgumentException if the argument's type is invalid
* @throws IllegalAccessException if the setter is not accessible
* @throws InvocationTargetException if the setter throws an exception
* @throws NoSuchMethodException if there is no setter for this property
*/
private static void invokeSetter(Object bean, Method setter, Object value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
boolean accessible = setter.isAccessible();
setter.setAccessible(true);
try {
setter.invoke(bean, value);
} finally {
setter.setAccessible(accessible);
}
}
/**
* Invokes a public setter for a property
* @param bean the object to invoke the public setter on
* @param propertyName the name of the property that shall be updated
* @param value the value passed to the setter
* @throws IllegalArgumentException if the argument's type is invalid
* @throws IllegalAccessException if the setter is not accessible
* @throws InvocationTargetException if the setter throws an exception
* @throws NoSuchMethodException if there is no setter for this property
*/
public static void setProperty(Object bean, String propertyName,
Object value) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
Method setter = findSetter(bean.getClass(), propertyName,
value.getClass());
if (setter == null) {
throw new NoSuchMethodException("There is " +
"no setter for property " + propertyName);
}
invokeSetter(bean, setter, value);
}
/**
* Invokes a setter for a property, no matter if the setter is visible
* or hidden or if it is declared in the given class or in a superclass
* or implemented interface.
* @param bean the object to invoke the public setter on
* @param propertyName the name of the property that shall be updated
* @param value the value passed to the setter
* @throws IllegalArgumentException if the argument's type is invalid
* @throws IllegalAccessException if the setter is not accessible
* @throws InvocationTargetException if the setter throws an exception
* @throws NoSuchMethodException if there is no setter for this property
*/
public static void setDeepProperty(Object bean, String propertyName,
Object value) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
Method setter = findDeepSetter(bean.getClass(), propertyName,
value.getClass());
if (setter == null) {
throw new NoSuchMethodException("There is " +
"no setter for property " + propertyName);
}
invokeSetter(bean, setter, value);
}
/**
* Invokes a getter method on a given bean
* @param <T> the result type
* @param bean the object to invoke the getter on
* @param getter the getter method
* @return the property's value
* @throws IllegalArgumentException if the argument's type is invalid
* @throws IllegalAccessException if the getter is not accessible
* @throws InvocationTargetException if the getter throws an exception
* @throws NoSuchMethodException if there is no getter for this property
*/
@SuppressWarnings("unchecked")
private static <T> T invokeGetter(Object bean, Method getter)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
boolean accessible = getter.isAccessible();
getter.setAccessible(true);
T result = null;
try {
result = (T)getter.invoke(bean);
} finally {
getter.setAccessible(accessible);
}
return result;
}
/**
* Invokes a public getter for a property
* @param <T> the result type
* @param bean the object to invoke the public getter on
* @param propertyName the name of the property to retrieve
* @return the property's value
* @throws IllegalArgumentException if the argument's type is invalid
* @throws IllegalAccessException if the getter is not accessible
* @throws InvocationTargetException if the getter throws an exception
* @throws NoSuchMethodException if there is no getter for this property
*/
public static <T> T getProperty(Object bean, String propertyName)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
Method getter = findGetter(bean.getClass(), propertyName, Object.class);
if (getter == null) {
throw new NoSuchMethodException("There is " +
"no getter for property " + propertyName);
}
return ReflectionHelper.<T>invokeGetter(bean, getter);
}
/**
* Invokes a getter for a property, no matter if the getter is visible
* or hidden or if it is declared in the given class or in a superclass
* or implemented interface.
* @param <T> the result type
* @param bean the object to invoke the getter on
* @param propertyName the name of the property to retrieve
* @return the property's value
* @throws IllegalArgumentException if the argument's type is invalid
* @throws IllegalAccessException if the setter is not accessible
* @throws InvocationTargetException if the setter throws an exception
* @throws NoSuchMethodException if there is no setter for this property
*/
public static <T> T getDeepProperty(Object bean, String propertyName)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
Method getter = findDeepGetter(bean.getClass(), propertyName, null);
if (getter == null) {
throw new NoSuchMethodException("There is " +
"no getter for property " + propertyName);
}
return ReflectionHelper.<T>invokeGetter(bean, getter);
}
/**
* @return the URL to the JAR file this class is in or null
* @throws MalformedURLException if the URL to the jar file
* could not be created
*/
public static URL getCurrentJarURL() throws MalformedURLException {
String name = ReflectionHelper.class.getCanonicalName();
name = name.replaceAll("\\.", "/");
name = name + ".class";
URL url = ReflectionHelper.class.getClassLoader().getResource(name);
String str = url.toString();
int to = str.indexOf("!/");
if (to == -1) {
url = ClassLoader.getSystemResource(name);
if(url != null){
str = url.toString();
to = str.indexOf("!/");
}else{
return null;
}
}
return new URL(str.substring(0, to + 2));
}
/**
* Returns an array of all files contained by a given package
* @param pkg the package (e.g. "de.igd.fhg.CityServer3D")
* @return an array of files
* @throws IOException if the package could not be found
*/
public static synchronized File[] getFilesFromPackage(String pkg)
throws IOException {
File[] files;
try {
URL u = _packageResolver.resolve(pkg);
if (u != null && !u.toString().startsWith("jar:")) {
//we got the package as an URL. Simply create a file
//from this URL
File dir;
try {
dir = new File(u.toURI());
} catch (URISyntaxException e) {
//if the URL contains spaces and they have not been
//replaced by %20 then we'll have to use the following line
dir = new File(u.getFile());
}
if (!dir.isDirectory()) {
//try another method
dir = new File(u.getFile());
}
files = null;
if (dir.isDirectory()) {
files = dir.listFiles();
}
} else {
JarFile jarFile;
//the package may be in a jar file
//get the current jar file and search it
- if (u != null && u.toURI().toString().startsWith("jar:file:")) {
- String p = u.toURI().toString().substring(4);
- p = p.substring(0, p.indexOf("!/"));
- File file = new File(URI.create(p));
- p = file.getAbsolutePath();
+ if (u != null && u.toString().startsWith("jar:file:")) {
+ // first try using URL and File
try {
- jarFile = new JarFile(p);
- } catch (ZipException e) {
- throw new IllegalArgumentException("No zip file: " + p, e);
- }
+ String p = u.toString().substring(4);
+ p = p.substring(0, p.indexOf("!/"));
+ File file = new File(URI.create(p));
+ p = file.getAbsolutePath();
+ try {
+ jarFile = new JarFile(p);
+ } catch (ZipException e) {
+ throw new IllegalArgumentException("No zip file: " + p, e);
+ }
+ } catch (Throwable e1) {
+ // second try directly using path
+ String p = u.toString().substring(9);
+ p = p.substring(0, p.indexOf("!/"));
+ try {
+ jarFile = new JarFile(p);
+ } catch (ZipException e2) {
+ throw new IllegalArgumentException("No zip file: " + p, e2);
+ }
+ }
} else {
u = getCurrentJarURL();
//open jar file
JarURLConnection juc = (JarURLConnection)u.openConnection();
jarFile = juc.getJarFile();
}
//enumerate entries and add those that match the package path
Enumeration<JarEntry> entries = jarFile.entries();
ArrayList<String> file_names = new ArrayList<String>();
String package_path = pkg.replaceAll("\\.", "/");
boolean slashed = false;
if (package_path.charAt(0) == '/') {
package_path = package_path.substring(1);
slashed = true;
}
while (entries.hasMoreElements()) {
JarEntry j = entries.nextElement();
if (j.getName().matches("^" + package_path + ".+\\..+")) {
if (slashed) {
file_names.add("/" + j.getName());
} else {
file_names.add(j.getName());
}
}
}
//convert list to array
files = new File[file_names.size()];
Iterator<String> i = file_names.iterator();
int n = 0;
while (i.hasNext()) {
files[n++] = new File(i.next());
}
}
} catch (Throwable e) {
throw new IOException("Could not find package: " + pkg, e);
}
if(files != null && files.length == 0)
return null; //let's not require paranoid callers
return files;
}
/**
* Gets a list of all classes in the given package and all
* subpackages recursively.
* @param pkg the package
* @return the list of classes
* @throws IOException if a subpackage or a class could not be loaded
*/
public static List<Class<?>> getClassesFromPackage(String pkg)
throws IOException {
return getClassesFromPackage(pkg, true);
}
/**
* Gets a list of all classes in the given package
* @param pkg the package
* @param recursive true if all subpackages shall be traversed too
* @return the list of classes
* @throws IOException if a subpackage or a class could not be loaded
*/
public static List<Class<?>> getClassesFromPackage(String pkg,
boolean recursive)
throws IOException {
List<Class<?>> result = new ArrayList<Class<?>>();
getClassesFromPackage(pkg, result, recursive);
return result;
}
/**
* Gets a list of all subpackages in the given package
* @param pkg the package
* @return the list of classes
* @throws IOException if a subpackage or a class could not be loaded
*/
public static List<String> getSubPackagesFromPackage(String pkg)
throws IOException {
return getSubPackagesFromPackage(pkg, true);
}
/**
* Gets a list of all subpackages in the given package
* @param pkg the package
* @param recursive true if all subpackages shall be traversed too
* @return the list of classes
* @throws IOException if a subpackage or a class could not be loaded
*/
public static List<String> getSubPackagesFromPackage(String pkg,
boolean recursive)
throws IOException {
List<String> result = new ArrayList<String>();
getSubPackagesFromPackage(pkg, result, recursive);
return result;
}
private static void getSubPackagesFromPackage(String pkg, List<String> l,
boolean recursive) throws IOException {
File[] files = getFilesFromPackage(pkg);
for (File f : files) {
String name = f.getName();
if (f.isDirectory() && !name.startsWith(".")) {
l.add(pkg + "." + name);
if (recursive) {
getSubPackagesFromPackage(pkg + "." + name, l, true);
}
}
}
}
private static void getClassesFromPackage(String pkg, List<Class<?>> l,
boolean recursive) throws IOException {
File[] files = getFilesFromPackage(pkg);
for (File f : files) {
String name = f.getName();
if (f.isDirectory() && recursive) {
if (!name.startsWith(".")) {
getClassesFromPackage(pkg + "." + name, l, true);
}
} else if (name.toLowerCase().endsWith(".class")) {
//the following lines make sure we also handle classes
//in subpackages. These subpackages may be returned by
//ApplicationContext.getFilesFromPackage() when we are
//in a jar file
String classPath = f.toURI().toString().replace('/',
'.').replace('\\', '.');
String className = classPath.substring(
classPath.lastIndexOf(pkg), classPath.lastIndexOf('.'));
Class<?> c;
try {
c = Class.forName(className);
} catch (ClassNotFoundException e) {
throw new IOException("Could not load class: " +
e.getMessage());
}
l.add(c);
}
}
}
/**
* <p>Find the most specialised class from group compatible with clazz.
* A direct superclass match is searched and returned if found.</p>
* <p>If not and checkAssignability is true,
* the most derived assignable class is being searched.</p>
* <p>See The Java Language Specification, sections 5.1.1 and 5.1.4 , for details.</p>
* @param clazz a class
* @param group a collection of classes to match against
* @param checkAssignability whether to use assignability when no direct match is found
* @return null or the most specialised match from group
*/
public static Class<?> findMostSpecificMatch(Class<?> clazz,
Collection<Class<?>> group, boolean checkAssignability) {
if (clazz == null || group == null)
throw new IllegalArgumentException("");
//scale up the type hierarchy until we have found a matching class
for (Class<?> c = clazz; c != Object.class; c = c.getSuperclass()) {
if(group.contains(c))
return c;
}
if (checkAssignability) {
//in lieu of a direct match, check assignability (likely clazz is an interface)
Class<?> result = null;
for(Class<?> c : group) {
if(clazz.isAssignableFrom(c)) {
//result null or less specialized -> overwrite
if(result == null || result.isAssignableFrom(c))
result = c;
}
}
return result;
} else {
return null;
}
}
/**
* Performs a shallow copy of all fields defined by the class of src
* and all superclasses.
* @param <T> the type of the source and destination object
* @param src the source object
* @param dst the destination object
* @throws IllegalArgumentException if a field is unaccessible
* @throws IllegalAccessException if a field is not accessible
*/
public static <T> void shallowEnforceDeepProperties(T src, T dst)
throws IllegalArgumentException, IllegalAccessException {
Class<?> cls = src.getClass();
shallowEnforceDeepProperties(cls, src, dst);
}
private static <T> void shallowEnforceDeepProperties(Class<?> cls,
T src, T dst)
throws IllegalArgumentException, IllegalAccessException {
if (cls == Object.class || cls == null) {
return;
}
Field[] fields = cls.getDeclaredFields();
for (Field f : fields) {
if (Modifier.isStatic(f.getModifiers()) ||
Modifier.isFinal(f.getModifiers())) {
continue;
}
boolean accessible = f.isAccessible();
f.setAccessible(true);
try {
Object val = f.get(src);
f.set(dst, val);
} finally {
f.setAccessible(accessible);
}
}
shallowEnforceDeepProperties(cls.getSuperclass(), src, dst);
}
}
| false | true |
public static synchronized File[] getFilesFromPackage(String pkg)
throws IOException {
File[] files;
try {
URL u = _packageResolver.resolve(pkg);
if (u != null && !u.toString().startsWith("jar:")) {
//we got the package as an URL. Simply create a file
//from this URL
File dir;
try {
dir = new File(u.toURI());
} catch (URISyntaxException e) {
//if the URL contains spaces and they have not been
//replaced by %20 then we'll have to use the following line
dir = new File(u.getFile());
}
if (!dir.isDirectory()) {
//try another method
dir = new File(u.getFile());
}
files = null;
if (dir.isDirectory()) {
files = dir.listFiles();
}
} else {
JarFile jarFile;
//the package may be in a jar file
//get the current jar file and search it
if (u != null && u.toURI().toString().startsWith("jar:file:")) {
String p = u.toURI().toString().substring(4);
p = p.substring(0, p.indexOf("!/"));
File file = new File(URI.create(p));
p = file.getAbsolutePath();
try {
jarFile = new JarFile(p);
} catch (ZipException e) {
throw new IllegalArgumentException("No zip file: " + p, e);
}
} else {
u = getCurrentJarURL();
//open jar file
JarURLConnection juc = (JarURLConnection)u.openConnection();
jarFile = juc.getJarFile();
}
//enumerate entries and add those that match the package path
Enumeration<JarEntry> entries = jarFile.entries();
ArrayList<String> file_names = new ArrayList<String>();
String package_path = pkg.replaceAll("\\.", "/");
boolean slashed = false;
if (package_path.charAt(0) == '/') {
package_path = package_path.substring(1);
slashed = true;
}
while (entries.hasMoreElements()) {
JarEntry j = entries.nextElement();
if (j.getName().matches("^" + package_path + ".+\\..+")) {
if (slashed) {
file_names.add("/" + j.getName());
} else {
file_names.add(j.getName());
}
}
}
//convert list to array
files = new File[file_names.size()];
Iterator<String> i = file_names.iterator();
int n = 0;
while (i.hasNext()) {
files[n++] = new File(i.next());
}
}
} catch (Throwable e) {
throw new IOException("Could not find package: " + pkg, e);
}
if(files != null && files.length == 0)
return null; //let's not require paranoid callers
return files;
}
|
public static synchronized File[] getFilesFromPackage(String pkg)
throws IOException {
File[] files;
try {
URL u = _packageResolver.resolve(pkg);
if (u != null && !u.toString().startsWith("jar:")) {
//we got the package as an URL. Simply create a file
//from this URL
File dir;
try {
dir = new File(u.toURI());
} catch (URISyntaxException e) {
//if the URL contains spaces and they have not been
//replaced by %20 then we'll have to use the following line
dir = new File(u.getFile());
}
if (!dir.isDirectory()) {
//try another method
dir = new File(u.getFile());
}
files = null;
if (dir.isDirectory()) {
files = dir.listFiles();
}
} else {
JarFile jarFile;
//the package may be in a jar file
//get the current jar file and search it
if (u != null && u.toString().startsWith("jar:file:")) {
// first try using URL and File
try {
String p = u.toString().substring(4);
p = p.substring(0, p.indexOf("!/"));
File file = new File(URI.create(p));
p = file.getAbsolutePath();
try {
jarFile = new JarFile(p);
} catch (ZipException e) {
throw new IllegalArgumentException("No zip file: " + p, e);
}
} catch (Throwable e1) {
// second try directly using path
String p = u.toString().substring(9);
p = p.substring(0, p.indexOf("!/"));
try {
jarFile = new JarFile(p);
} catch (ZipException e2) {
throw new IllegalArgumentException("No zip file: " + p, e2);
}
}
} else {
u = getCurrentJarURL();
//open jar file
JarURLConnection juc = (JarURLConnection)u.openConnection();
jarFile = juc.getJarFile();
}
//enumerate entries and add those that match the package path
Enumeration<JarEntry> entries = jarFile.entries();
ArrayList<String> file_names = new ArrayList<String>();
String package_path = pkg.replaceAll("\\.", "/");
boolean slashed = false;
if (package_path.charAt(0) == '/') {
package_path = package_path.substring(1);
slashed = true;
}
while (entries.hasMoreElements()) {
JarEntry j = entries.nextElement();
if (j.getName().matches("^" + package_path + ".+\\..+")) {
if (slashed) {
file_names.add("/" + j.getName());
} else {
file_names.add(j.getName());
}
}
}
//convert list to array
files = new File[file_names.size()];
Iterator<String> i = file_names.iterator();
int n = 0;
while (i.hasNext()) {
files[n++] = new File(i.next());
}
}
} catch (Throwable e) {
throw new IOException("Could not find package: " + pkg, e);
}
if(files != null && files.length == 0)
return null; //let's not require paranoid callers
return files;
}
|
diff --git a/src/org/e2k/CROWD36.java b/src/org/e2k/CROWD36.java
index 08bdbbf..7f5b53e 100644
--- a/src/org/e2k/CROWD36.java
+++ b/src/org/e2k/CROWD36.java
@@ -1,270 +1,274 @@
package org.e2k;
import javax.swing.JOptionPane;
public class CROWD36 extends MFSK {
private int baudRate=40;
private int state=0;
private double samplesPerSymbol;
private Rivet theApp;
public long sampleCount=0;
private long symbolCounter=0;
private long energyStartPoint;
private StringBuffer lineBuffer=new StringBuffer();
private CircularDataBuffer energyBuffer=new CircularDataBuffer();
private boolean figureShift=false;
private int lineCount=0;
private int correctionValue=0;
private int highFreq=-1;
private int lowFreq=5000;
private final int Tones[]={1410,1450,1490,1530,1570,1610,1650,1690,1730,1770,1810,1850,1890,1930,1970,2010,2050,2090,2130,2170,2210,2250,2290,2330,2370,2410,2450,2490,2530,2570,2610,2650,2690,2730};
// Update to test new PC setup
public CROWD36 (Rivet tapp,int baud) {
baudRate=baud;
theApp=tapp;
}
public void setBaudRate(int baudRate) {
this.baudRate = baudRate;
}
public int getBaudRate() {
return baudRate;
}
public void setState(int state) {
this.state = state;
}
public int getState() {
return state;
}
public String[] decode (CircularDataBuffer circBuf,WaveData waveData) {
String outLines[]=new String[2];
// Just starting
if (state==0) {
// Check the sample rate
if (waveData.getSampleRate()>11025) {
state=-1;
JOptionPane.showMessageDialog(null,"WAV files containing\nCROWD36 recordings must have\nbeen recorded at a sample rate\nof 11.025 KHz or less.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
// Check this is a mono recording
if (waveData.getChannels()!=1) {
state=-1;
JOptionPane.showMessageDialog(null,"Rivet can only process\nmono WAV files.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
samplesPerSymbol=samplesPerSymbol(baudRate,waveData.getSampleRate());
state=1;
+ figureShift=false;
+ highFreq=-1;
+ lowFreq=5000;
+ correctionValue=0;
// sampleCount must start negative to account for the buffer gradually filling
sampleCount=0-circBuf.retMax();
symbolCounter=0;
// Clear the energy buffer
energyBuffer.setBufferCounter(0);
// Clear the display side of things
lineCount=0;
lineBuffer.delete(0,lineBuffer.length());
theApp.setStatusLabel("Known Tone Hunt");
return null;
}
// Hunting for known tones
if (state==1) {
outLines[0]=syncToneHunt(circBuf,waveData);
if (outLines[0]!=null) {
state=2;
energyStartPoint=sampleCount;
energyBuffer.setBufferCounter(0);
theApp.setStatusLabel("Calculating Symbol Timing");
}
}
// Set the symbol timing
if (state==2) {
final int lookAHEAD=1;
// Obtain an average of the last few samples put through ABS
double no=samplesPerSymbol/20.0;
energyBuffer.addToCircBuffer(circBuf.getABSAverage(0,(int)no));
// Gather a symbols worth of energy values
if (energyBuffer.getBufferCounter()>(int)(samplesPerSymbol*lookAHEAD)) {
// Now find the lowest energy value
long perfectPoint=energyBuffer.returnLowestBin()+energyStartPoint+(int)samplesPerSymbol;
// Calculate what the value of the symbol counter should be
symbolCounter=(int)samplesPerSymbol-(perfectPoint-sampleCount);
state=3;
theApp.setStatusLabel("Symbol Timing Achieved");
if (theApp.isSoundCardInput()==true) outLines[0]=theApp.getTimeStamp()+" Symbol timing found";
else outLines[0]=theApp.getTimeStamp()+" Symbol timing found at position "+Long.toString(perfectPoint);
sampleCount++;
symbolCounter++;
return outLines;
}
}
// Decode traffic
if (state==3) {
// Only do this at the start of each symbol
if (symbolCounter>=samplesPerSymbol) {
symbolCounter=0;
int freq=crowd36Freq(circBuf,waveData,0);
outLines=displayMessage(freq,waveData.isFromFile());
}
}
sampleCount++;
symbolCounter++;
return outLines;
}
private int crowd36Freq (CircularDataBuffer circBuf,WaveData waveData,int pos) {
// 8 KHz sampling
if (waveData.getSampleRate()==8000.0) {
int freq=doCR36_8000FFT(circBuf,waveData,pos);
freq=freq+correctionValue;
return freq;
}
else if (waveData.getSampleRate()==11025.0) {
int freq=doCR36_11025FFT(circBuf,waveData,pos);
freq=freq+correctionValue;
return freq;
}
return -1;
}
private String[] displayMessage (int freq,boolean isFile) {
String outLines[]=new String[2];
int tone=getTone(freq);
String ch=getChar(tone);
if (theApp.isDebug()==false) {
if (ch.equals("ls")) return null;
else if (ch.equals("fs")) return null;
if (ch.equals("cr")) {
lineCount=50;
}
else {
lineBuffer.append(ch);
if (ch.length()>0) lineCount++;
}
if (lineCount==50) {
outLines[0]=lineBuffer.toString();
lineBuffer.delete(0,lineBuffer.length());
lineCount=0;
return outLines;
}
return null;
}
else {
outLines[0]=lineBuffer.toString();
lineBuffer.delete(0,lineBuffer.length());
lineCount=0;
outLines[0]=freq+" Hz at "+Long.toString(sampleCount+(int)samplesPerSymbol)+" tone "+Long.toString(tone)+" "+ch;
return outLines;
}
}
private String getChar(int tone) {
String out="";
final String C36A[]={"Q" , "X" , "W" , "V" , "E" , "K" , " " , "B" , "R" , "J" , "<*10>" , "G" , "T" ,"F" , "<fs>" , "M" , "Y" , "C" , "cr" , "Z" , "U" , "L" , "<*22>" , "D" , "I" , "H" , "<ls>" , "S" , "O" , "N" , "<*30>" , "A" , "P" , "<*33>"};
final String F36A[]={"1" , "\u0429" , "2" , "=" , "3" , "(" , " " , "?" , "4" , "\u042e" , "<*10>" , "8" , "5" ,"\u042d" , "<fs>" , "." , "6" , ":" , "cr" , "+" , "7" , ")" , "<*22>" , " " , "8" , "\u0449" , "<ls>" , "" , "9" , "," , "<*30>" , "-" , "0" , "<*33>"};
//if (tone==16) figureShift=true;
//else if (tone==28) figureShift=false;
//figureShift=true;
try {
if ((tone<0)||(tone>33)) tone=33;
if (figureShift==false) out=C36A[tone];
else out=F36A[tone];
if (out.equals("<ls>")) figureShift=false;
else if (out.equals("<fs>")) figureShift=true;
else if (out.equals("cr")) figureShift=false;
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,e.toString(),"Rivet", JOptionPane.INFORMATION_MESSAGE);
return "";
}
return out;
}
// Convert from a frequency to a tone number
private int getTone (int freq) {
int a,index=-1,lowVal=999,dif;
// Store the highest and lowest frequencies detected
if (freq>highFreq) highFreq=freq;
else if (freq<lowFreq) lowFreq=freq;
// Match the frequency to a tone number
for (a=0;a<Tones.length;a++) {
dif=Math.abs(Tones[a]-freq);
if (dif<lowVal) {
lowVal=dif;
index=a;
}
}
return index;
}
// Hunt for known CROWD 36 tones
private String syncToneHunt (CircularDataBuffer circBuf,WaveData waveData) {
int difference,sHigh=31;
// Get 4 symbols
int freq1=crowd36Freq(circBuf,waveData,0);
// Check this first tone isn't just noise
if (getPercentageOfTotal()<5.0) return null;
int freq2=crowd36Freq(circBuf,waveData,(int)samplesPerSymbol*1);
// Check we have a high low
if (freq2>freq1) return null;
// Check there is more than 100 Hz of difference
difference=freq1-freq2;
if (difference<100) return null;
int freq3=crowd36Freq(circBuf,waveData,(int)samplesPerSymbol*2);
// Don't waste time carrying on if freq1 isn't the same as freq3
if (freq1!=freq3) return null;
int freq4=crowd36Freq(circBuf,waveData,(int)samplesPerSymbol*3);
// Check 2 of the symbol frequencies are different
if ((freq1!=freq3)||(freq2!=freq4)) return null;
// Check that 2 of the symbol frequencies are the same
if ((freq1==freq2)||(freq3==freq4)) return null;
// Calculate the difference between the sync tones
difference=freq1-freq2;
if (difference==875) sHigh=23;
// was 31
correctionValue=Tones[sHigh]-freq1;
String line=theApp.getTimeStamp()+" CROWD36 Sync Tones Found (Correcting by "+Integer.toString(correctionValue)+" Hz) sync tone difference "+Integer.toString(difference)+" Hz";
return line;
}
public int getLineCount() {
return this.lineCount;
}
public String getLineBuffer () {
return this.lineBuffer.toString();
}
public String lowHighFreqs () {
String line;
line="Lowest frequency "+Integer.toString(lowFreq)+" Hz : Highest Frequency "+Integer.toString(highFreq)+" Hz";
return line;
}
}
| true | true |
public String[] decode (CircularDataBuffer circBuf,WaveData waveData) {
String outLines[]=new String[2];
// Just starting
if (state==0) {
// Check the sample rate
if (waveData.getSampleRate()>11025) {
state=-1;
JOptionPane.showMessageDialog(null,"WAV files containing\nCROWD36 recordings must have\nbeen recorded at a sample rate\nof 11.025 KHz or less.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
// Check this is a mono recording
if (waveData.getChannels()!=1) {
state=-1;
JOptionPane.showMessageDialog(null,"Rivet can only process\nmono WAV files.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
samplesPerSymbol=samplesPerSymbol(baudRate,waveData.getSampleRate());
state=1;
// sampleCount must start negative to account for the buffer gradually filling
sampleCount=0-circBuf.retMax();
symbolCounter=0;
// Clear the energy buffer
energyBuffer.setBufferCounter(0);
// Clear the display side of things
lineCount=0;
lineBuffer.delete(0,lineBuffer.length());
theApp.setStatusLabel("Known Tone Hunt");
return null;
}
// Hunting for known tones
if (state==1) {
outLines[0]=syncToneHunt(circBuf,waveData);
if (outLines[0]!=null) {
state=2;
energyStartPoint=sampleCount;
energyBuffer.setBufferCounter(0);
theApp.setStatusLabel("Calculating Symbol Timing");
}
}
// Set the symbol timing
if (state==2) {
final int lookAHEAD=1;
// Obtain an average of the last few samples put through ABS
double no=samplesPerSymbol/20.0;
energyBuffer.addToCircBuffer(circBuf.getABSAverage(0,(int)no));
// Gather a symbols worth of energy values
if (energyBuffer.getBufferCounter()>(int)(samplesPerSymbol*lookAHEAD)) {
// Now find the lowest energy value
long perfectPoint=energyBuffer.returnLowestBin()+energyStartPoint+(int)samplesPerSymbol;
// Calculate what the value of the symbol counter should be
symbolCounter=(int)samplesPerSymbol-(perfectPoint-sampleCount);
state=3;
theApp.setStatusLabel("Symbol Timing Achieved");
if (theApp.isSoundCardInput()==true) outLines[0]=theApp.getTimeStamp()+" Symbol timing found";
else outLines[0]=theApp.getTimeStamp()+" Symbol timing found at position "+Long.toString(perfectPoint);
sampleCount++;
symbolCounter++;
return outLines;
}
}
// Decode traffic
if (state==3) {
// Only do this at the start of each symbol
if (symbolCounter>=samplesPerSymbol) {
symbolCounter=0;
int freq=crowd36Freq(circBuf,waveData,0);
outLines=displayMessage(freq,waveData.isFromFile());
}
}
sampleCount++;
symbolCounter++;
return outLines;
}
|
public String[] decode (CircularDataBuffer circBuf,WaveData waveData) {
String outLines[]=new String[2];
// Just starting
if (state==0) {
// Check the sample rate
if (waveData.getSampleRate()>11025) {
state=-1;
JOptionPane.showMessageDialog(null,"WAV files containing\nCROWD36 recordings must have\nbeen recorded at a sample rate\nof 11.025 KHz or less.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
// Check this is a mono recording
if (waveData.getChannels()!=1) {
state=-1;
JOptionPane.showMessageDialog(null,"Rivet can only process\nmono WAV files.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return null;
}
samplesPerSymbol=samplesPerSymbol(baudRate,waveData.getSampleRate());
state=1;
figureShift=false;
highFreq=-1;
lowFreq=5000;
correctionValue=0;
// sampleCount must start negative to account for the buffer gradually filling
sampleCount=0-circBuf.retMax();
symbolCounter=0;
// Clear the energy buffer
energyBuffer.setBufferCounter(0);
// Clear the display side of things
lineCount=0;
lineBuffer.delete(0,lineBuffer.length());
theApp.setStatusLabel("Known Tone Hunt");
return null;
}
// Hunting for known tones
if (state==1) {
outLines[0]=syncToneHunt(circBuf,waveData);
if (outLines[0]!=null) {
state=2;
energyStartPoint=sampleCount;
energyBuffer.setBufferCounter(0);
theApp.setStatusLabel("Calculating Symbol Timing");
}
}
// Set the symbol timing
if (state==2) {
final int lookAHEAD=1;
// Obtain an average of the last few samples put through ABS
double no=samplesPerSymbol/20.0;
energyBuffer.addToCircBuffer(circBuf.getABSAverage(0,(int)no));
// Gather a symbols worth of energy values
if (energyBuffer.getBufferCounter()>(int)(samplesPerSymbol*lookAHEAD)) {
// Now find the lowest energy value
long perfectPoint=energyBuffer.returnLowestBin()+energyStartPoint+(int)samplesPerSymbol;
// Calculate what the value of the symbol counter should be
symbolCounter=(int)samplesPerSymbol-(perfectPoint-sampleCount);
state=3;
theApp.setStatusLabel("Symbol Timing Achieved");
if (theApp.isSoundCardInput()==true) outLines[0]=theApp.getTimeStamp()+" Symbol timing found";
else outLines[0]=theApp.getTimeStamp()+" Symbol timing found at position "+Long.toString(perfectPoint);
sampleCount++;
symbolCounter++;
return outLines;
}
}
// Decode traffic
if (state==3) {
// Only do this at the start of each symbol
if (symbolCounter>=samplesPerSymbol) {
symbolCounter=0;
int freq=crowd36Freq(circBuf,waveData,0);
outLines=displayMessage(freq,waveData.isFromFile());
}
}
sampleCount++;
symbolCounter++;
return outLines;
}
|
diff --git a/src/com/vloxlands/gen/MapGenerator.java b/src/com/vloxlands/gen/MapGenerator.java
index 7271de3..8bf4786 100644
--- a/src/com/vloxlands/gen/MapGenerator.java
+++ b/src/com/vloxlands/gen/MapGenerator.java
@@ -1,60 +1,60 @@
package com.vloxlands.gen;
import org.lwjgl.util.vector.Vector3f;
import com.vloxlands.game.world.Island;
import com.vloxlands.game.world.Map;
public class MapGenerator extends Thread
{
public Map map;
public float progress, progressBefore;
IslandGenerator gen;
int z, x, spread, size, index;
public MapGenerator(int x, int z, int spread, int size)
{
this.x = x;
this.z = z;
this.spread = spread;
this.size = size;
progress = 0;
progressBefore = 0;
setDaemon(true);
setName("MapGenerator-Thread");
}
@Override
public void run()
{
map = new Map();
while (!isDone())
{
if (gen == null)
{
progressBefore = progress;
gen = new IslandGenerator((int) (size * 0.75), (int) (size * 1.25));
gen.start();
index++;
}
System.out.print(""); // don't why this is needed
progress = gen.progress / (x * z) + progressBefore;
if (gen.finishedIsland != null)
{
Island i = gen.finishedIsland;
- i.setPos(new Vector3f(((index - 1) / x) * size * 2, 0, ((index - 1) % z) * size * 2));
+ i.setPos(new Vector3f(((index - 1) / z) * size * 2, 0, ((index - 1) % z) * size * 2));
map.addIsland(i);
gen = null;
}
}
}
public boolean isDone()
{
return map.islands.size() == (x * z);
}
}
| true | true |
public void run()
{
map = new Map();
while (!isDone())
{
if (gen == null)
{
progressBefore = progress;
gen = new IslandGenerator((int) (size * 0.75), (int) (size * 1.25));
gen.start();
index++;
}
System.out.print(""); // don't why this is needed
progress = gen.progress / (x * z) + progressBefore;
if (gen.finishedIsland != null)
{
Island i = gen.finishedIsland;
i.setPos(new Vector3f(((index - 1) / x) * size * 2, 0, ((index - 1) % z) * size * 2));
map.addIsland(i);
gen = null;
}
}
}
|
public void run()
{
map = new Map();
while (!isDone())
{
if (gen == null)
{
progressBefore = progress;
gen = new IslandGenerator((int) (size * 0.75), (int) (size * 1.25));
gen.start();
index++;
}
System.out.print(""); // don't why this is needed
progress = gen.progress / (x * z) + progressBefore;
if (gen.finishedIsland != null)
{
Island i = gen.finishedIsland;
i.setPos(new Vector3f(((index - 1) / z) * size * 2, 0, ((index - 1) % z) * size * 2));
map.addIsland(i);
gen = null;
}
}
}
|
diff --git a/plugins/org.eclipse.birt.report.engine.emitter.config.postscript/src/org/eclipse/birt/report/engine/emitter/config/postscript/PostscriptEmitterDescriptor.java b/plugins/org.eclipse.birt.report.engine.emitter.config.postscript/src/org/eclipse/birt/report/engine/emitter/config/postscript/PostscriptEmitterDescriptor.java
index 24f362a02..16de02f35 100644
--- a/plugins/org.eclipse.birt.report.engine.emitter.config.postscript/src/org/eclipse/birt/report/engine/emitter/config/postscript/PostscriptEmitterDescriptor.java
+++ b/plugins/org.eclipse.birt.report.engine.emitter.config.postscript/src/org/eclipse/birt/report/engine/emitter/config/postscript/PostscriptEmitterDescriptor.java
@@ -1,270 +1,271 @@
/*******************************************************************************
* Copyright (c) 2008 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.config.postscript;
import org.eclipse.birt.report.engine.api.IPDFRenderOption;
import org.eclipse.birt.report.engine.api.IRenderOption;
import org.eclipse.birt.report.engine.api.RenderOption;
import org.eclipse.birt.report.engine.emitter.config.AbstractConfigurableOptionObserver;
import org.eclipse.birt.report.engine.emitter.config.AbstractEmitterDescriptor;
import org.eclipse.birt.report.engine.emitter.config.ConfigurableOption;
import org.eclipse.birt.report.engine.emitter.config.IConfigurableOption;
import org.eclipse.birt.report.engine.emitter.config.IConfigurableOptionObserver;
import org.eclipse.birt.report.engine.emitter.config.IOptionValue;
import org.eclipse.birt.report.engine.emitter.config.OptionValue;
import org.eclipse.birt.report.engine.emitter.config.postscript.i18n.Messages;
import org.eclipse.birt.report.engine.emitter.postscript.PostscriptRenderOption;
/**
* This class is a descriptor of postscript emitter.
*/
public class PostscriptEmitterDescriptor extends AbstractEmitterDescriptor
{
private static final String FONT_SUBSTITUTION = "FontSubstitution";
private static final String BIDI_PROCESSING = "BIDIProcessing";
private static final String TEXT_WRAPPING = "TextWrapping";
private IConfigurableOption[] options;
public PostscriptEmitterDescriptor( )
{
initOptions( );
}
private void initOptions( )
{
// Initializes the option for BIDIProcessing.
ConfigurableOption bidiProcessing = new ConfigurableOption(
BIDI_PROCESSING );
bidiProcessing.setDisplayName( Messages
.getString( "OptionDisplayValue.BidiProcessing" ) ); //$NON-NLS-1$
bidiProcessing.setDataType( IConfigurableOption.DataType.BOOLEAN );
bidiProcessing.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
bidiProcessing.setDefaultValue( Boolean.TRUE );
bidiProcessing.setToolTip( null );
bidiProcessing.setDescription( Messages
.getString( "OptionDescription.BidiProcessing" ) ); //$NON-NLS-1$
// Initializes the option for TextWrapping.
ConfigurableOption textWrapping = new ConfigurableOption( TEXT_WRAPPING );
textWrapping.setDisplayName( Messages
.getString( "OptionDisplayValue.TextWrapping" ) ); //$NON-NLS-1$
textWrapping.setDataType( IConfigurableOption.DataType.BOOLEAN );
textWrapping.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
textWrapping.setDefaultValue( Boolean.TRUE );
textWrapping.setToolTip( null );
textWrapping.setDescription( Messages
.getString( "OptionDescription.TextWrapping" ) ); //$NON-NLS-1$
// Initializes the option for fontSubstitution.
ConfigurableOption fontSubstitution = new ConfigurableOption(
FONT_SUBSTITUTION );
fontSubstitution.setDisplayName( Messages
.getString( "OptionDisplayValue.FontSubstitution" ) );
fontSubstitution.setDataType( IConfigurableOption.DataType.BOOLEAN );
fontSubstitution
.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
fontSubstitution.setDefaultValue( Boolean.TRUE );
fontSubstitution.setToolTip( null );
fontSubstitution.setDescription( Messages
.getString( "OptionDescription.FontSubstitution" ) ); //$NON-NLS-1$
// Initializes the option for PageOverFlow.
ConfigurableOption pageOverFlow = new ConfigurableOption(
IPDFRenderOption.PAGE_OVERFLOW );
pageOverFlow.setDisplayName( Messages
.getString( "OptionDisplayValue.PageOverFlow" ) ); //$NON-NLS-1$
pageOverFlow.setDataType( IConfigurableOption.DataType.INTEGER );
pageOverFlow.setDisplayType( IConfigurableOption.DisplayType.COMBO );
pageOverFlow
.setChoices( new OptionValue[]{
new OptionValue(
IPDFRenderOption.CLIP_CONTENT,
Messages
.getString( "OptionDisplayValue.CLIP_CONTENT" ) ), //$NON-NLS-1$
new OptionValue(
IPDFRenderOption.FIT_TO_PAGE_SIZE,
Messages
.getString( "OptionDisplayValue.FIT_TO_PAGE_SIZE" ) ), //$NON-NLS-1$
new OptionValue(
IPDFRenderOption.OUTPUT_TO_MULTIPLE_PAGES,
Messages
.getString( "OptionDisplayValue.OUTPUT_TO_MULTIPLE_PAGES" ) ), //$NON-NLS-1$
new OptionValue(
IPDFRenderOption.ENLARGE_PAGE_SIZE,
Messages
.getString( "OptionDisplayValue.ENLARGE_PAGE_SIZE" ) ) //$NON-NLS-1$
} );
pageOverFlow.setDefaultValue( IPDFRenderOption.CLIP_CONTENT );
pageOverFlow.setToolTip( null );
pageOverFlow.setDescription( Messages
.getString( "OptionDescription.PageOverFlow" ) ); //$NON-NLS-1$
// Initializes the option for copies.
ConfigurableOption copies = new ConfigurableOption(
PostscriptRenderOption.OPTION_COPIES );
copies
.setDisplayName( Messages
.getString( "OptionDisplayValue.Copies" ) ); //$NON-NLS-1$
copies.setDataType( IConfigurableOption.DataType.INTEGER );
copies.setDisplayType( IConfigurableOption.DisplayType.TEXT );
copies.setDefaultValue( 1 );
copies.setToolTip( null );
copies
.setDescription( Messages
.getString( "OptionDescription.Copies" ) ); //$NON-NLS-1$
// Initializes the option for collate.
ConfigurableOption collate = new ConfigurableOption(
PostscriptRenderOption.OPTION_COLLATE );
collate.setDisplayName( Messages
.getString( "OptionDisplayValue.Collate" ) ); //$NON-NLS-1$
collate.setDataType( IConfigurableOption.DataType.BOOLEAN );
collate.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
collate.setDefaultValue( Boolean.FALSE );
collate.setToolTip( null );
collate.setDescription( Messages
.getString( "OptionDescription.Collate" ) ); //$NON-NLS-1$
// Initializes the option for duplex.
ConfigurableOption duplex = new ConfigurableOption(
PostscriptRenderOption.OPTION_DUPLEX );
duplex
.setDisplayName( Messages
.getString( "OptionDisplayValue.Duplex" ) ); //$NON-NLS-1$
duplex.setDataType( IConfigurableOption.DataType.STRING );
duplex.setDisplayType( IConfigurableOption.DisplayType.TEXT );
duplex.setDefaultValue( null );
duplex.setToolTip( null );
duplex
.setDescription( Messages
.getString( "OptionDescription.Duplex" ) ); //$NON-NLS-1$
// Initializes the option for paperSize.
ConfigurableOption paperSize = new ConfigurableOption(
PostscriptRenderOption.OPTION_PAPER_SIZE );
paperSize
.setDisplayName( Messages
.getString( "OptionDisplayValue.PaperSize" ) ); //$NON-NLS-1$
paperSize.setDataType( IConfigurableOption.DataType.STRING );
paperSize.setDisplayType( IConfigurableOption.DisplayType.TEXT );
paperSize.setDefaultValue( "A4" );
paperSize.setToolTip( null );
paperSize
.setDescription( Messages
.getString( "OptionDescription.PaperSize" ) ); //$NON-NLS-1$
// Initializes the option for paperTray.
ConfigurableOption paperTray = new ConfigurableOption(
PostscriptRenderOption.OPTION_PAPER_TRAY );
paperTray.setDisplayName( Messages
.getString( "OptionDisplayValue.PaperTray" ) ); //$NON-NLS-1$
paperTray.setDataType( IConfigurableOption.DataType.STRING );
paperTray.setDisplayType( IConfigurableOption.DisplayType.TEXT );
paperTray.setDefaultValue( null );
paperTray.setToolTip( null );
paperTray.setDescription( Messages
.getString( "OptionDescription.PaperTray" ) ); //$NON-NLS-1$
options = new IConfigurableOption[]{bidiProcessing, textWrapping,
- fontSubstitution, pageOverFlow,};
+ fontSubstitution, pageOverFlow, copies, collate, duplex,
+ paperSize, paperTray};
}
@Override
public IConfigurableOptionObserver createOptionObserver( )
{
return new PostscriptOptionObserver( );
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.report.engine.emitter.config.IEmitterDescriptor#
* getDescription()
*/
public String getDescription( )
{
return Messages.getString( "PostscriptEmitter.Description" ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.report.engine.emitter.config.IEmitterDescriptor#
* getDisplayName()
*/
public String getDisplayName( )
{
return Messages.getString( "PostscriptEmitter.DisplayName" ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.engine.emitter.config.IEmitterDescriptor#getID()
*/
public String getID( )
{
return "org.eclipse.birt.report.engine.emitter.postscript"; //$NON-NLS-1$
}
public String getRenderOptionName( String name )
{
assert name != null;
if ( TEXT_WRAPPING.equals( name ) )
{
return IPDFRenderOption.PDF_TEXT_WRAPPING;
}
if ( BIDI_PROCESSING.equals( name ) )
{
return IPDFRenderOption.PDF_BIDI_PROCESSING;
}
if ( FONT_SUBSTITUTION.equals( name ) )
{
return IPDFRenderOption.PDF_FONT_SUBSTITUTION;
}
return name;
}
class PostscriptOptionObserver extends AbstractConfigurableOptionObserver
{
@Override
public IConfigurableOption[] getOptions( )
{
return options;
}
@Override
public IRenderOption getPreferredRenderOption( )
{
RenderOption renderOption = new RenderOption( );
renderOption.setEmitterID( getID( ) );
renderOption.setOutputFormat( "postscript" ); //$NON-NLS-1$
for ( IOptionValue optionValue : values )
{
if ( optionValue != null )
{
renderOption.setOption( getRenderOptionName( optionValue
.getName( ) ), optionValue.getValue( ) );
}
}
return renderOption;
}
}
}
| true | true |
private void initOptions( )
{
// Initializes the option for BIDIProcessing.
ConfigurableOption bidiProcessing = new ConfigurableOption(
BIDI_PROCESSING );
bidiProcessing.setDisplayName( Messages
.getString( "OptionDisplayValue.BidiProcessing" ) ); //$NON-NLS-1$
bidiProcessing.setDataType( IConfigurableOption.DataType.BOOLEAN );
bidiProcessing.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
bidiProcessing.setDefaultValue( Boolean.TRUE );
bidiProcessing.setToolTip( null );
bidiProcessing.setDescription( Messages
.getString( "OptionDescription.BidiProcessing" ) ); //$NON-NLS-1$
// Initializes the option for TextWrapping.
ConfigurableOption textWrapping = new ConfigurableOption( TEXT_WRAPPING );
textWrapping.setDisplayName( Messages
.getString( "OptionDisplayValue.TextWrapping" ) ); //$NON-NLS-1$
textWrapping.setDataType( IConfigurableOption.DataType.BOOLEAN );
textWrapping.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
textWrapping.setDefaultValue( Boolean.TRUE );
textWrapping.setToolTip( null );
textWrapping.setDescription( Messages
.getString( "OptionDescription.TextWrapping" ) ); //$NON-NLS-1$
// Initializes the option for fontSubstitution.
ConfigurableOption fontSubstitution = new ConfigurableOption(
FONT_SUBSTITUTION );
fontSubstitution.setDisplayName( Messages
.getString( "OptionDisplayValue.FontSubstitution" ) );
fontSubstitution.setDataType( IConfigurableOption.DataType.BOOLEAN );
fontSubstitution
.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
fontSubstitution.setDefaultValue( Boolean.TRUE );
fontSubstitution.setToolTip( null );
fontSubstitution.setDescription( Messages
.getString( "OptionDescription.FontSubstitution" ) ); //$NON-NLS-1$
// Initializes the option for PageOverFlow.
ConfigurableOption pageOverFlow = new ConfigurableOption(
IPDFRenderOption.PAGE_OVERFLOW );
pageOverFlow.setDisplayName( Messages
.getString( "OptionDisplayValue.PageOverFlow" ) ); //$NON-NLS-1$
pageOverFlow.setDataType( IConfigurableOption.DataType.INTEGER );
pageOverFlow.setDisplayType( IConfigurableOption.DisplayType.COMBO );
pageOverFlow
.setChoices( new OptionValue[]{
new OptionValue(
IPDFRenderOption.CLIP_CONTENT,
Messages
.getString( "OptionDisplayValue.CLIP_CONTENT" ) ), //$NON-NLS-1$
new OptionValue(
IPDFRenderOption.FIT_TO_PAGE_SIZE,
Messages
.getString( "OptionDisplayValue.FIT_TO_PAGE_SIZE" ) ), //$NON-NLS-1$
new OptionValue(
IPDFRenderOption.OUTPUT_TO_MULTIPLE_PAGES,
Messages
.getString( "OptionDisplayValue.OUTPUT_TO_MULTIPLE_PAGES" ) ), //$NON-NLS-1$
new OptionValue(
IPDFRenderOption.ENLARGE_PAGE_SIZE,
Messages
.getString( "OptionDisplayValue.ENLARGE_PAGE_SIZE" ) ) //$NON-NLS-1$
} );
pageOverFlow.setDefaultValue( IPDFRenderOption.CLIP_CONTENT );
pageOverFlow.setToolTip( null );
pageOverFlow.setDescription( Messages
.getString( "OptionDescription.PageOverFlow" ) ); //$NON-NLS-1$
// Initializes the option for copies.
ConfigurableOption copies = new ConfigurableOption(
PostscriptRenderOption.OPTION_COPIES );
copies
.setDisplayName( Messages
.getString( "OptionDisplayValue.Copies" ) ); //$NON-NLS-1$
copies.setDataType( IConfigurableOption.DataType.INTEGER );
copies.setDisplayType( IConfigurableOption.DisplayType.TEXT );
copies.setDefaultValue( 1 );
copies.setToolTip( null );
copies
.setDescription( Messages
.getString( "OptionDescription.Copies" ) ); //$NON-NLS-1$
// Initializes the option for collate.
ConfigurableOption collate = new ConfigurableOption(
PostscriptRenderOption.OPTION_COLLATE );
collate.setDisplayName( Messages
.getString( "OptionDisplayValue.Collate" ) ); //$NON-NLS-1$
collate.setDataType( IConfigurableOption.DataType.BOOLEAN );
collate.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
collate.setDefaultValue( Boolean.FALSE );
collate.setToolTip( null );
collate.setDescription( Messages
.getString( "OptionDescription.Collate" ) ); //$NON-NLS-1$
// Initializes the option for duplex.
ConfigurableOption duplex = new ConfigurableOption(
PostscriptRenderOption.OPTION_DUPLEX );
duplex
.setDisplayName( Messages
.getString( "OptionDisplayValue.Duplex" ) ); //$NON-NLS-1$
duplex.setDataType( IConfigurableOption.DataType.STRING );
duplex.setDisplayType( IConfigurableOption.DisplayType.TEXT );
duplex.setDefaultValue( null );
duplex.setToolTip( null );
duplex
.setDescription( Messages
.getString( "OptionDescription.Duplex" ) ); //$NON-NLS-1$
// Initializes the option for paperSize.
ConfigurableOption paperSize = new ConfigurableOption(
PostscriptRenderOption.OPTION_PAPER_SIZE );
paperSize
.setDisplayName( Messages
.getString( "OptionDisplayValue.PaperSize" ) ); //$NON-NLS-1$
paperSize.setDataType( IConfigurableOption.DataType.STRING );
paperSize.setDisplayType( IConfigurableOption.DisplayType.TEXT );
paperSize.setDefaultValue( "A4" );
paperSize.setToolTip( null );
paperSize
.setDescription( Messages
.getString( "OptionDescription.PaperSize" ) ); //$NON-NLS-1$
// Initializes the option for paperTray.
ConfigurableOption paperTray = new ConfigurableOption(
PostscriptRenderOption.OPTION_PAPER_TRAY );
paperTray.setDisplayName( Messages
.getString( "OptionDisplayValue.PaperTray" ) ); //$NON-NLS-1$
paperTray.setDataType( IConfigurableOption.DataType.STRING );
paperTray.setDisplayType( IConfigurableOption.DisplayType.TEXT );
paperTray.setDefaultValue( null );
paperTray.setToolTip( null );
paperTray.setDescription( Messages
.getString( "OptionDescription.PaperTray" ) ); //$NON-NLS-1$
options = new IConfigurableOption[]{bidiProcessing, textWrapping,
fontSubstitution, pageOverFlow,};
}
|
private void initOptions( )
{
// Initializes the option for BIDIProcessing.
ConfigurableOption bidiProcessing = new ConfigurableOption(
BIDI_PROCESSING );
bidiProcessing.setDisplayName( Messages
.getString( "OptionDisplayValue.BidiProcessing" ) ); //$NON-NLS-1$
bidiProcessing.setDataType( IConfigurableOption.DataType.BOOLEAN );
bidiProcessing.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
bidiProcessing.setDefaultValue( Boolean.TRUE );
bidiProcessing.setToolTip( null );
bidiProcessing.setDescription( Messages
.getString( "OptionDescription.BidiProcessing" ) ); //$NON-NLS-1$
// Initializes the option for TextWrapping.
ConfigurableOption textWrapping = new ConfigurableOption( TEXT_WRAPPING );
textWrapping.setDisplayName( Messages
.getString( "OptionDisplayValue.TextWrapping" ) ); //$NON-NLS-1$
textWrapping.setDataType( IConfigurableOption.DataType.BOOLEAN );
textWrapping.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
textWrapping.setDefaultValue( Boolean.TRUE );
textWrapping.setToolTip( null );
textWrapping.setDescription( Messages
.getString( "OptionDescription.TextWrapping" ) ); //$NON-NLS-1$
// Initializes the option for fontSubstitution.
ConfigurableOption fontSubstitution = new ConfigurableOption(
FONT_SUBSTITUTION );
fontSubstitution.setDisplayName( Messages
.getString( "OptionDisplayValue.FontSubstitution" ) );
fontSubstitution.setDataType( IConfigurableOption.DataType.BOOLEAN );
fontSubstitution
.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
fontSubstitution.setDefaultValue( Boolean.TRUE );
fontSubstitution.setToolTip( null );
fontSubstitution.setDescription( Messages
.getString( "OptionDescription.FontSubstitution" ) ); //$NON-NLS-1$
// Initializes the option for PageOverFlow.
ConfigurableOption pageOverFlow = new ConfigurableOption(
IPDFRenderOption.PAGE_OVERFLOW );
pageOverFlow.setDisplayName( Messages
.getString( "OptionDisplayValue.PageOverFlow" ) ); //$NON-NLS-1$
pageOverFlow.setDataType( IConfigurableOption.DataType.INTEGER );
pageOverFlow.setDisplayType( IConfigurableOption.DisplayType.COMBO );
pageOverFlow
.setChoices( new OptionValue[]{
new OptionValue(
IPDFRenderOption.CLIP_CONTENT,
Messages
.getString( "OptionDisplayValue.CLIP_CONTENT" ) ), //$NON-NLS-1$
new OptionValue(
IPDFRenderOption.FIT_TO_PAGE_SIZE,
Messages
.getString( "OptionDisplayValue.FIT_TO_PAGE_SIZE" ) ), //$NON-NLS-1$
new OptionValue(
IPDFRenderOption.OUTPUT_TO_MULTIPLE_PAGES,
Messages
.getString( "OptionDisplayValue.OUTPUT_TO_MULTIPLE_PAGES" ) ), //$NON-NLS-1$
new OptionValue(
IPDFRenderOption.ENLARGE_PAGE_SIZE,
Messages
.getString( "OptionDisplayValue.ENLARGE_PAGE_SIZE" ) ) //$NON-NLS-1$
} );
pageOverFlow.setDefaultValue( IPDFRenderOption.CLIP_CONTENT );
pageOverFlow.setToolTip( null );
pageOverFlow.setDescription( Messages
.getString( "OptionDescription.PageOverFlow" ) ); //$NON-NLS-1$
// Initializes the option for copies.
ConfigurableOption copies = new ConfigurableOption(
PostscriptRenderOption.OPTION_COPIES );
copies
.setDisplayName( Messages
.getString( "OptionDisplayValue.Copies" ) ); //$NON-NLS-1$
copies.setDataType( IConfigurableOption.DataType.INTEGER );
copies.setDisplayType( IConfigurableOption.DisplayType.TEXT );
copies.setDefaultValue( 1 );
copies.setToolTip( null );
copies
.setDescription( Messages
.getString( "OptionDescription.Copies" ) ); //$NON-NLS-1$
// Initializes the option for collate.
ConfigurableOption collate = new ConfigurableOption(
PostscriptRenderOption.OPTION_COLLATE );
collate.setDisplayName( Messages
.getString( "OptionDisplayValue.Collate" ) ); //$NON-NLS-1$
collate.setDataType( IConfigurableOption.DataType.BOOLEAN );
collate.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
collate.setDefaultValue( Boolean.FALSE );
collate.setToolTip( null );
collate.setDescription( Messages
.getString( "OptionDescription.Collate" ) ); //$NON-NLS-1$
// Initializes the option for duplex.
ConfigurableOption duplex = new ConfigurableOption(
PostscriptRenderOption.OPTION_DUPLEX );
duplex
.setDisplayName( Messages
.getString( "OptionDisplayValue.Duplex" ) ); //$NON-NLS-1$
duplex.setDataType( IConfigurableOption.DataType.STRING );
duplex.setDisplayType( IConfigurableOption.DisplayType.TEXT );
duplex.setDefaultValue( null );
duplex.setToolTip( null );
duplex
.setDescription( Messages
.getString( "OptionDescription.Duplex" ) ); //$NON-NLS-1$
// Initializes the option for paperSize.
ConfigurableOption paperSize = new ConfigurableOption(
PostscriptRenderOption.OPTION_PAPER_SIZE );
paperSize
.setDisplayName( Messages
.getString( "OptionDisplayValue.PaperSize" ) ); //$NON-NLS-1$
paperSize.setDataType( IConfigurableOption.DataType.STRING );
paperSize.setDisplayType( IConfigurableOption.DisplayType.TEXT );
paperSize.setDefaultValue( "A4" );
paperSize.setToolTip( null );
paperSize
.setDescription( Messages
.getString( "OptionDescription.PaperSize" ) ); //$NON-NLS-1$
// Initializes the option for paperTray.
ConfigurableOption paperTray = new ConfigurableOption(
PostscriptRenderOption.OPTION_PAPER_TRAY );
paperTray.setDisplayName( Messages
.getString( "OptionDisplayValue.PaperTray" ) ); //$NON-NLS-1$
paperTray.setDataType( IConfigurableOption.DataType.STRING );
paperTray.setDisplayType( IConfigurableOption.DisplayType.TEXT );
paperTray.setDefaultValue( null );
paperTray.setToolTip( null );
paperTray.setDescription( Messages
.getString( "OptionDescription.PaperTray" ) ); //$NON-NLS-1$
options = new IConfigurableOption[]{bidiProcessing, textWrapping,
fontSubstitution, pageOverFlow, copies, collate, duplex,
paperSize, paperTray};
}
|
diff --git a/src/main/java/org/spoutcraft/launcher/rest/Versions.java b/src/main/java/org/spoutcraft/launcher/rest/Versions.java
index 63c9bf3..f8af52b 100644
--- a/src/main/java/org/spoutcraft/launcher/rest/Versions.java
+++ b/src/main/java/org/spoutcraft/launcher/rest/Versions.java
@@ -1,97 +1,97 @@
/*
* This file is part of Spoutcraft.
*
* Copyright (c) 2011-2012, Spout LLC <http://www.spout.org/>
* Spoutcraft is licensed under the Spout License Version 1.
*
* Spoutcraft is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the Spout License Version 1.
*
* Spoutcraft is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License,
* the MIT license and the Spout License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spoutcraft.launcher.rest;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.io.IOUtils;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.ObjectMapper;
public final class Versions {
private static List<String> versions = null;
public static synchronized List<String> getMinecraftVersions() {
if (versions == null) {
InputStream stream = null;
try {
URLConnection conn = (new URL(RestAPI.VERSIONS_URL)).openConnection();
stream = conn.getInputStream();
ObjectMapper mapper = new ObjectMapper();
Channel c = mapper.readValue(stream, Channel.class);
Set<String> versions = new HashSet<String>();
for (Version version : c.releaseChannel.stable) {
versions.add(version.version);
}
for (Version version : c.releaseChannel.beta) {
versions.add(version.version);
}
for (Version version : c.releaseChannel.dev) {
versions.add(version.version);
}
Versions.versions = new ArrayList<String>(versions);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(stream);
}
- //TODO: Fix
- versions.add(0, "1.4.5");
+ //TODO: Fix by implementing get.spout.org API for MC
+ //versions.add(0, "1.4.5");
}
return versions;
}
public static synchronized String getLatestMinecraftVersion() {
return getMinecraftVersions().get(0);
}
private static class Channel {
@JsonProperty("release_channel")
private ChannelType releaseChannel;
}
private static class ChannelType {
@JsonProperty("dev")
private Version[] dev;
@JsonProperty("beta")
private Version[] beta;
@JsonProperty("stable")
private Version[] stable;
}
private static class Version {
@JsonProperty("version")
private String version;
}
}
| true | true |
public static synchronized List<String> getMinecraftVersions() {
if (versions == null) {
InputStream stream = null;
try {
URLConnection conn = (new URL(RestAPI.VERSIONS_URL)).openConnection();
stream = conn.getInputStream();
ObjectMapper mapper = new ObjectMapper();
Channel c = mapper.readValue(stream, Channel.class);
Set<String> versions = new HashSet<String>();
for (Version version : c.releaseChannel.stable) {
versions.add(version.version);
}
for (Version version : c.releaseChannel.beta) {
versions.add(version.version);
}
for (Version version : c.releaseChannel.dev) {
versions.add(version.version);
}
Versions.versions = new ArrayList<String>(versions);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(stream);
}
//TODO: Fix
versions.add(0, "1.4.5");
}
return versions;
}
|
public static synchronized List<String> getMinecraftVersions() {
if (versions == null) {
InputStream stream = null;
try {
URLConnection conn = (new URL(RestAPI.VERSIONS_URL)).openConnection();
stream = conn.getInputStream();
ObjectMapper mapper = new ObjectMapper();
Channel c = mapper.readValue(stream, Channel.class);
Set<String> versions = new HashSet<String>();
for (Version version : c.releaseChannel.stable) {
versions.add(version.version);
}
for (Version version : c.releaseChannel.beta) {
versions.add(version.version);
}
for (Version version : c.releaseChannel.dev) {
versions.add(version.version);
}
Versions.versions = new ArrayList<String>(versions);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(stream);
}
//TODO: Fix by implementing get.spout.org API for MC
//versions.add(0, "1.4.5");
}
return versions;
}
|
diff --git a/src/com/NightOutApps/chiconightout/CNOMapView.java b/src/com/NightOutApps/chiconightout/CNOMapView.java
index 90d8321..5c6bf8f 100644
--- a/src/com/NightOutApps/chiconightout/CNOMapView.java
+++ b/src/com/NightOutApps/chiconightout/CNOMapView.java
@@ -1,186 +1,186 @@
package com.NightOutApps.chiconightout;
import java.io.IOException;
import java.util.Calendar;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
public class CNOMapView extends MapActivity implements OnClickListener{
private MapView map;
private MapController control;
Calendar calendar = Calendar.getInstance();
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
public static final String DRINKNAME = "DrinkName";
public static final String DRINKDESCRIPT = "DrinkDescription";
private Cursor c = null;
public static final String DATABASE_TABLE = "Drink";
private String[] colsfrom = {"_id", DRINKNAME, DRINKDESCRIPT};
String barStr = "Bar_id = 2";
GeoPoint centerP = new GeoPoint(39728478, -121842176);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
View barListButton = findViewById(R.id.barlistbutton);
barListButton.setOnClickListener(this);
initMapView();
initMyLocation();
initDatabase();
GeoPoint bansheePoint = new GeoPoint(39730006,-121841087); //39729912,-121841041
GeoPoint beachPoint = new GeoPoint(39730693,-121839199); //39730685,-121839423
GeoPoint bellasPoint = new GeoPoint(39729984,-121841755);
GeoPoint crazyPoint = new GeoPoint(39729596,-121839414); //39729621,-121839522
GeoPoint downPoint = new GeoPoint(39729491,-121839170);
GeoPoint duffysPoint = new GeoPoint(39729171,-121838808);
GeoPoint joesPoint = new GeoPoint(39723920,-121844260);
GeoPoint lasallesPoint = new GeoPoint(39729414,-121840720);
GeoPoint lostPoint = new GeoPoint(39729412,-121839089);
GeoPoint bearPoint = new GeoPoint(39729000,-121842430); //39729192, 121842705
GeoPoint maltesePoint = new GeoPoint(39721210,-121827139);
GeoPoint panamasPoint = new GeoPoint(39730627,-121839792); //39730517,-121839671
GeoPoint rileysPoint = new GeoPoint(39724563,-121843874);
GeoPoint gradPoint = new GeoPoint(39724585,-121838365);
GeoPoint townPoint = new GeoPoint(39729303,-121838974);
GeoPoint ubarPoint = new GeoPoint(39730858,-121839387); //39730685, -121839423
- Drawable bansheeIcon = this.getResources().getDrawable(R.drawable.banshee_icontest);
- Drawable beachIcon = this.getResources().getDrawable(R.drawable.beach_icontest);
- Drawable bellasIcon = this.getResources().getDrawable(R.drawable.bellas_icontest);
- Drawable crazyIcon = this.getResources().getDrawable(R.drawable.crazy_horse_icontest);
- Drawable downIcon = this.getResources().getDrawable(R.drawable.down_lo_icontest);
- Drawable duffysIcon = this.getResources().getDrawable(R.drawable.duffys_icontest);
- Drawable joesIcon = this.getResources().getDrawable(R.drawable.joes_icontest);
- Drawable lasallesIcon = this.getResources().getDrawable(R.drawable.lasalles_icontest);
- Drawable lostIcon = this.getResources().getDrawable(R.drawable.lost_on_main_icontest);
- Drawable bearIcon = this.getResources().getDrawable(R.drawable.madison_bear_icontest);
- Drawable malteseIcon = this.getResources().getDrawable(R.drawable.maltese_icontest);
- Drawable panamasIcon = this.getResources().getDrawable(R.drawable.panamas_icontest);
- Drawable rileysIcon = this.getResources().getDrawable(R.drawable.rileys_icontest);
- Drawable gradIcon = this.getResources().getDrawable(R.drawable.the_grad_icontest);
- Drawable townIcon = this.getResources().getDrawable(R.drawable.town_lounge_icontest);
- Drawable ubarIcon = this.getResources().getDrawable(R.drawable.u_bar_icontest);
+ Drawable bansheeIcon = this.getResources().getDrawable(R.drawable.banshee_icon_trans);
+ Drawable beachIcon = this.getResources().getDrawable(R.drawable.beach_icon_trans);
+ Drawable bellasIcon = this.getResources().getDrawable(R.drawable.bellas_icon_trans);
+ Drawable crazyIcon = this.getResources().getDrawable(R.drawable.crazy_horse_icon_trans);
+ Drawable downIcon = this.getResources().getDrawable(R.drawable.down_lo_icon_trans);
+ Drawable duffysIcon = this.getResources().getDrawable(R.drawable.duffys_icon_trans);
+ Drawable joesIcon = this.getResources().getDrawable(R.drawable.joes_icon_trans);
+ Drawable lasallesIcon = this.getResources().getDrawable(R.drawable.lasalles_icon_trans);
+ Drawable lostIcon = this.getResources().getDrawable(R.drawable.lost_on_main_icon_trans);
+ Drawable bearIcon = this.getResources().getDrawable(R.drawable.madison_bear_icon_trans);
+ Drawable malteseIcon = this.getResources().getDrawable(R.drawable.maltese_icon_trans);
+ Drawable panamasIcon = this.getResources().getDrawable(R.drawable.panamas_icon_trans);
+ Drawable rileysIcon = this.getResources().getDrawable(R.drawable.rileys_icon_trans);
+ Drawable gradIcon = this.getResources().getDrawable(R.drawable.the_grad_icon_trans);
+ Drawable townIcon = this.getResources().getDrawable(R.drawable.town_lounge_icon_trans);
+ Drawable ubarIcon = this.getResources().getDrawable(R.drawable.u_bar_icon_trans);
Drawable cnoIco = this.getResources().getDrawable(R.drawable.ic_launcher);
Rect bansheeR = new Rect(-bansheeIcon.getIntrinsicWidth()/2, -bansheeIcon.getIntrinsicHeight(), bansheeIcon.getIntrinsicWidth()/2, 0);
Rect beachR = new Rect(0, -beachIcon.getIntrinsicHeight(), beachIcon.getIntrinsicWidth(), 0);
Rect bellasR = new Rect(-bellasIcon.getIntrinsicWidth()/2, -bellasIcon.getIntrinsicHeight(), bellasIcon.getIntrinsicWidth()/2, 0);
Rect crazyR = new Rect(-crazyIcon.getIntrinsicWidth()/2, -crazyIcon.getIntrinsicHeight(), crazyIcon.getIntrinsicWidth()/2, 0);
Rect downR = new Rect(-downIcon.getIntrinsicWidth(), -downIcon.getIntrinsicHeight(), 0, 0);
Rect duffysR = new Rect(0, -duffysIcon.getIntrinsicHeight(), duffysIcon.getIntrinsicWidth(), 0);
Rect joesR = new Rect(-joesIcon.getIntrinsicWidth()/2, -joesIcon.getIntrinsicHeight(), joesIcon.getIntrinsicWidth()/2, 0);
Rect lasallesR = new Rect(-lasallesIcon.getIntrinsicWidth()/2, -lasallesIcon.getIntrinsicHeight(), lasallesIcon.getIntrinsicWidth()/2, 0);
Rect lostR = new Rect(0, -lostIcon.getIntrinsicHeight(), lostIcon.getIntrinsicWidth(), 0);
Rect bearR = new Rect(-bearIcon.getIntrinsicWidth()/2, -bearIcon.getIntrinsicHeight(), bearIcon.getIntrinsicWidth()/2, 0);
Rect malteseR = new Rect(-malteseIcon.getIntrinsicWidth()/2, -malteseIcon.getIntrinsicHeight(), malteseIcon.getIntrinsicWidth()/2, 0);
Rect panamasR = new Rect(-panamasIcon.getIntrinsicWidth()/2, -panamasIcon.getIntrinsicHeight(), panamasIcon.getIntrinsicWidth()/2, 0);
Rect rileysR = new Rect(-rileysIcon.getIntrinsicWidth()/2, -rileysIcon.getIntrinsicHeight(), rileysIcon.getIntrinsicWidth()/2, 0);
Rect gradR = new Rect(-gradIcon.getIntrinsicWidth()/2, -gradIcon.getIntrinsicHeight(), gradIcon.getIntrinsicWidth()/2, 0);
Rect townR = new Rect(-townIcon.getIntrinsicWidth(), -townIcon.getIntrinsicHeight(), 0, 0);
Rect ubarR = new Rect(-ubarIcon.getIntrinsicWidth()/2, -ubarIcon.getIntrinsicHeight(), ubarIcon.getIntrinsicWidth()/2, 0);
BarItem overlaybanshee = new BarItem(bansheePoint, "Banshee", "I'm at Banshee!", bansheeIcon, bansheeR);
BarItem overlaybeach = new BarItem(beachPoint, "Beach", "I'm in Mexico City!", beachIcon, beachR);
BarItem overlaybellas = new BarItem(bellasPoint, "Bellas", "I'm in Mexico City!", bellasIcon, bellasR);
BarItem overlaycrazy = new BarItem(crazyPoint, "Crazy Horse", "I'm in Mexico City!", crazyIcon, crazyR);
BarItem overlaydown = new BarItem(downPoint, "Down Lo", "I'm in Mexico City!", downIcon, downR);
BarItem overlayduffys = new BarItem(duffysPoint, "Duffys", "I'm in Mexico City!", duffysIcon, duffysR);
BarItem overlayjoes = new BarItem(joesPoint, "Joes", "I'm in Mexico City!", joesIcon, joesR);
BarItem overlaylasalles = new BarItem(lasallesPoint, "Lasalles", "I'm in Mexico City!", lasallesIcon, lasallesR);
BarItem overlaylost = new BarItem(lostPoint, "Lost On Main", "I'm in Mexico City!", lostIcon, lostR);
BarItem overlaybear = new BarItem(bearPoint, "Madison Bear Garden", "I'm in Mexico City!", bearIcon, bearR);
BarItem overlaymaltese = new BarItem(maltesePoint, "Maltese", "I'm in Mexico City!", malteseIcon, malteseR);
BarItem overlaypanamas = new BarItem(panamasPoint, "Panamas", "I'm in Mexico City!", panamasIcon, panamasR);
BarItem overlayrileys = new BarItem(rileysPoint, "Rileys", "I'm in Mexico City!", rileysIcon, rileysR);
BarItem overlaygrad = new BarItem(gradPoint, "The Grad", "I'm in Mexico City!", gradIcon, gradR);
BarItem overlaytown = new BarItem(townPoint, "Town Lounge", "I'm in Mexico City!", townIcon, townR);
BarItem overlayubar = new BarItem(ubarPoint, "University Bar", "I'm in Mexico City!", ubarIcon, ubarR);
BarOverlay barsOverlay = new BarOverlay(cnoIco, this);
barsOverlay.addOverlay(overlaybanshee);
barsOverlay.addOverlay(overlaybeach);
barsOverlay.addOverlay(overlaybellas);
barsOverlay.addOverlay(overlaycrazy);
barsOverlay.addOverlay(overlaydown);
barsOverlay.addOverlay(overlayduffys);
barsOverlay.addOverlay(overlayjoes);
barsOverlay.addOverlay(overlaylasalles);
barsOverlay.addOverlay(overlaylost);
barsOverlay.addOverlay(overlaybear);
barsOverlay.addOverlay(overlaymaltese);
barsOverlay.addOverlay(overlaypanamas);
barsOverlay.addOverlay(overlayrileys);
barsOverlay.addOverlay(overlaygrad);
barsOverlay.addOverlay(overlaytown);
barsOverlay.addOverlay(overlayubar);
map.getOverlays().add(barsOverlay);
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
private void initMapView() {
map = (MapView) findViewById(R.id.map);
control = map.getController();
map.setBuiltInZoomControls(true);
map.setSatellite(false);
map.invalidate();
}
private void initMyLocation() {
final MyLocationOverlay overlay = new MyLocationOverlay(this, map);
overlay.enableMyLocation();
overlay.runOnFirstFix(new Runnable() {
public void run() {
control.setZoom(17);
control.animateTo(centerP);
}
});
map.getOverlays().add(overlay);
}
private void initDatabase() {
MyDBHelper myDbHelper = new MyDBHelper(CNOMapView.this);
try {
myDbHelper.createDataBase();
Toast.makeText(CNOMapView.this, "Success in creation", Toast.LENGTH_SHORT).show();
}
catch (IOException ioe) {
throw new Error("Unable to create database");
}
}
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.barlistbutton:
Intent i = new Intent(this, BarListView.class);
startActivity(i);
break;
}
}
}
| true | true |
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
View barListButton = findViewById(R.id.barlistbutton);
barListButton.setOnClickListener(this);
initMapView();
initMyLocation();
initDatabase();
GeoPoint bansheePoint = new GeoPoint(39730006,-121841087); //39729912,-121841041
GeoPoint beachPoint = new GeoPoint(39730693,-121839199); //39730685,-121839423
GeoPoint bellasPoint = new GeoPoint(39729984,-121841755);
GeoPoint crazyPoint = new GeoPoint(39729596,-121839414); //39729621,-121839522
GeoPoint downPoint = new GeoPoint(39729491,-121839170);
GeoPoint duffysPoint = new GeoPoint(39729171,-121838808);
GeoPoint joesPoint = new GeoPoint(39723920,-121844260);
GeoPoint lasallesPoint = new GeoPoint(39729414,-121840720);
GeoPoint lostPoint = new GeoPoint(39729412,-121839089);
GeoPoint bearPoint = new GeoPoint(39729000,-121842430); //39729192, 121842705
GeoPoint maltesePoint = new GeoPoint(39721210,-121827139);
GeoPoint panamasPoint = new GeoPoint(39730627,-121839792); //39730517,-121839671
GeoPoint rileysPoint = new GeoPoint(39724563,-121843874);
GeoPoint gradPoint = new GeoPoint(39724585,-121838365);
GeoPoint townPoint = new GeoPoint(39729303,-121838974);
GeoPoint ubarPoint = new GeoPoint(39730858,-121839387); //39730685, -121839423
Drawable bansheeIcon = this.getResources().getDrawable(R.drawable.banshee_icontest);
Drawable beachIcon = this.getResources().getDrawable(R.drawable.beach_icontest);
Drawable bellasIcon = this.getResources().getDrawable(R.drawable.bellas_icontest);
Drawable crazyIcon = this.getResources().getDrawable(R.drawable.crazy_horse_icontest);
Drawable downIcon = this.getResources().getDrawable(R.drawable.down_lo_icontest);
Drawable duffysIcon = this.getResources().getDrawable(R.drawable.duffys_icontest);
Drawable joesIcon = this.getResources().getDrawable(R.drawable.joes_icontest);
Drawable lasallesIcon = this.getResources().getDrawable(R.drawable.lasalles_icontest);
Drawable lostIcon = this.getResources().getDrawable(R.drawable.lost_on_main_icontest);
Drawable bearIcon = this.getResources().getDrawable(R.drawable.madison_bear_icontest);
Drawable malteseIcon = this.getResources().getDrawable(R.drawable.maltese_icontest);
Drawable panamasIcon = this.getResources().getDrawable(R.drawable.panamas_icontest);
Drawable rileysIcon = this.getResources().getDrawable(R.drawable.rileys_icontest);
Drawable gradIcon = this.getResources().getDrawable(R.drawable.the_grad_icontest);
Drawable townIcon = this.getResources().getDrawable(R.drawable.town_lounge_icontest);
Drawable ubarIcon = this.getResources().getDrawable(R.drawable.u_bar_icontest);
Drawable cnoIco = this.getResources().getDrawable(R.drawable.ic_launcher);
Rect bansheeR = new Rect(-bansheeIcon.getIntrinsicWidth()/2, -bansheeIcon.getIntrinsicHeight(), bansheeIcon.getIntrinsicWidth()/2, 0);
Rect beachR = new Rect(0, -beachIcon.getIntrinsicHeight(), beachIcon.getIntrinsicWidth(), 0);
Rect bellasR = new Rect(-bellasIcon.getIntrinsicWidth()/2, -bellasIcon.getIntrinsicHeight(), bellasIcon.getIntrinsicWidth()/2, 0);
Rect crazyR = new Rect(-crazyIcon.getIntrinsicWidth()/2, -crazyIcon.getIntrinsicHeight(), crazyIcon.getIntrinsicWidth()/2, 0);
Rect downR = new Rect(-downIcon.getIntrinsicWidth(), -downIcon.getIntrinsicHeight(), 0, 0);
Rect duffysR = new Rect(0, -duffysIcon.getIntrinsicHeight(), duffysIcon.getIntrinsicWidth(), 0);
Rect joesR = new Rect(-joesIcon.getIntrinsicWidth()/2, -joesIcon.getIntrinsicHeight(), joesIcon.getIntrinsicWidth()/2, 0);
Rect lasallesR = new Rect(-lasallesIcon.getIntrinsicWidth()/2, -lasallesIcon.getIntrinsicHeight(), lasallesIcon.getIntrinsicWidth()/2, 0);
Rect lostR = new Rect(0, -lostIcon.getIntrinsicHeight(), lostIcon.getIntrinsicWidth(), 0);
Rect bearR = new Rect(-bearIcon.getIntrinsicWidth()/2, -bearIcon.getIntrinsicHeight(), bearIcon.getIntrinsicWidth()/2, 0);
Rect malteseR = new Rect(-malteseIcon.getIntrinsicWidth()/2, -malteseIcon.getIntrinsicHeight(), malteseIcon.getIntrinsicWidth()/2, 0);
Rect panamasR = new Rect(-panamasIcon.getIntrinsicWidth()/2, -panamasIcon.getIntrinsicHeight(), panamasIcon.getIntrinsicWidth()/2, 0);
Rect rileysR = new Rect(-rileysIcon.getIntrinsicWidth()/2, -rileysIcon.getIntrinsicHeight(), rileysIcon.getIntrinsicWidth()/2, 0);
Rect gradR = new Rect(-gradIcon.getIntrinsicWidth()/2, -gradIcon.getIntrinsicHeight(), gradIcon.getIntrinsicWidth()/2, 0);
Rect townR = new Rect(-townIcon.getIntrinsicWidth(), -townIcon.getIntrinsicHeight(), 0, 0);
Rect ubarR = new Rect(-ubarIcon.getIntrinsicWidth()/2, -ubarIcon.getIntrinsicHeight(), ubarIcon.getIntrinsicWidth()/2, 0);
BarItem overlaybanshee = new BarItem(bansheePoint, "Banshee", "I'm at Banshee!", bansheeIcon, bansheeR);
BarItem overlaybeach = new BarItem(beachPoint, "Beach", "I'm in Mexico City!", beachIcon, beachR);
BarItem overlaybellas = new BarItem(bellasPoint, "Bellas", "I'm in Mexico City!", bellasIcon, bellasR);
BarItem overlaycrazy = new BarItem(crazyPoint, "Crazy Horse", "I'm in Mexico City!", crazyIcon, crazyR);
BarItem overlaydown = new BarItem(downPoint, "Down Lo", "I'm in Mexico City!", downIcon, downR);
BarItem overlayduffys = new BarItem(duffysPoint, "Duffys", "I'm in Mexico City!", duffysIcon, duffysR);
BarItem overlayjoes = new BarItem(joesPoint, "Joes", "I'm in Mexico City!", joesIcon, joesR);
BarItem overlaylasalles = new BarItem(lasallesPoint, "Lasalles", "I'm in Mexico City!", lasallesIcon, lasallesR);
BarItem overlaylost = new BarItem(lostPoint, "Lost On Main", "I'm in Mexico City!", lostIcon, lostR);
BarItem overlaybear = new BarItem(bearPoint, "Madison Bear Garden", "I'm in Mexico City!", bearIcon, bearR);
BarItem overlaymaltese = new BarItem(maltesePoint, "Maltese", "I'm in Mexico City!", malteseIcon, malteseR);
BarItem overlaypanamas = new BarItem(panamasPoint, "Panamas", "I'm in Mexico City!", panamasIcon, panamasR);
BarItem overlayrileys = new BarItem(rileysPoint, "Rileys", "I'm in Mexico City!", rileysIcon, rileysR);
BarItem overlaygrad = new BarItem(gradPoint, "The Grad", "I'm in Mexico City!", gradIcon, gradR);
BarItem overlaytown = new BarItem(townPoint, "Town Lounge", "I'm in Mexico City!", townIcon, townR);
BarItem overlayubar = new BarItem(ubarPoint, "University Bar", "I'm in Mexico City!", ubarIcon, ubarR);
BarOverlay barsOverlay = new BarOverlay(cnoIco, this);
barsOverlay.addOverlay(overlaybanshee);
barsOverlay.addOverlay(overlaybeach);
barsOverlay.addOverlay(overlaybellas);
barsOverlay.addOverlay(overlaycrazy);
barsOverlay.addOverlay(overlaydown);
barsOverlay.addOverlay(overlayduffys);
barsOverlay.addOverlay(overlayjoes);
barsOverlay.addOverlay(overlaylasalles);
barsOverlay.addOverlay(overlaylost);
barsOverlay.addOverlay(overlaybear);
barsOverlay.addOverlay(overlaymaltese);
barsOverlay.addOverlay(overlaypanamas);
barsOverlay.addOverlay(overlayrileys);
barsOverlay.addOverlay(overlaygrad);
barsOverlay.addOverlay(overlaytown);
barsOverlay.addOverlay(overlayubar);
map.getOverlays().add(barsOverlay);
}
|
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
View barListButton = findViewById(R.id.barlistbutton);
barListButton.setOnClickListener(this);
initMapView();
initMyLocation();
initDatabase();
GeoPoint bansheePoint = new GeoPoint(39730006,-121841087); //39729912,-121841041
GeoPoint beachPoint = new GeoPoint(39730693,-121839199); //39730685,-121839423
GeoPoint bellasPoint = new GeoPoint(39729984,-121841755);
GeoPoint crazyPoint = new GeoPoint(39729596,-121839414); //39729621,-121839522
GeoPoint downPoint = new GeoPoint(39729491,-121839170);
GeoPoint duffysPoint = new GeoPoint(39729171,-121838808);
GeoPoint joesPoint = new GeoPoint(39723920,-121844260);
GeoPoint lasallesPoint = new GeoPoint(39729414,-121840720);
GeoPoint lostPoint = new GeoPoint(39729412,-121839089);
GeoPoint bearPoint = new GeoPoint(39729000,-121842430); //39729192, 121842705
GeoPoint maltesePoint = new GeoPoint(39721210,-121827139);
GeoPoint panamasPoint = new GeoPoint(39730627,-121839792); //39730517,-121839671
GeoPoint rileysPoint = new GeoPoint(39724563,-121843874);
GeoPoint gradPoint = new GeoPoint(39724585,-121838365);
GeoPoint townPoint = new GeoPoint(39729303,-121838974);
GeoPoint ubarPoint = new GeoPoint(39730858,-121839387); //39730685, -121839423
Drawable bansheeIcon = this.getResources().getDrawable(R.drawable.banshee_icon_trans);
Drawable beachIcon = this.getResources().getDrawable(R.drawable.beach_icon_trans);
Drawable bellasIcon = this.getResources().getDrawable(R.drawable.bellas_icon_trans);
Drawable crazyIcon = this.getResources().getDrawable(R.drawable.crazy_horse_icon_trans);
Drawable downIcon = this.getResources().getDrawable(R.drawable.down_lo_icon_trans);
Drawable duffysIcon = this.getResources().getDrawable(R.drawable.duffys_icon_trans);
Drawable joesIcon = this.getResources().getDrawable(R.drawable.joes_icon_trans);
Drawable lasallesIcon = this.getResources().getDrawable(R.drawable.lasalles_icon_trans);
Drawable lostIcon = this.getResources().getDrawable(R.drawable.lost_on_main_icon_trans);
Drawable bearIcon = this.getResources().getDrawable(R.drawable.madison_bear_icon_trans);
Drawable malteseIcon = this.getResources().getDrawable(R.drawable.maltese_icon_trans);
Drawable panamasIcon = this.getResources().getDrawable(R.drawable.panamas_icon_trans);
Drawable rileysIcon = this.getResources().getDrawable(R.drawable.rileys_icon_trans);
Drawable gradIcon = this.getResources().getDrawable(R.drawable.the_grad_icon_trans);
Drawable townIcon = this.getResources().getDrawable(R.drawable.town_lounge_icon_trans);
Drawable ubarIcon = this.getResources().getDrawable(R.drawable.u_bar_icon_trans);
Drawable cnoIco = this.getResources().getDrawable(R.drawable.ic_launcher);
Rect bansheeR = new Rect(-bansheeIcon.getIntrinsicWidth()/2, -bansheeIcon.getIntrinsicHeight(), bansheeIcon.getIntrinsicWidth()/2, 0);
Rect beachR = new Rect(0, -beachIcon.getIntrinsicHeight(), beachIcon.getIntrinsicWidth(), 0);
Rect bellasR = new Rect(-bellasIcon.getIntrinsicWidth()/2, -bellasIcon.getIntrinsicHeight(), bellasIcon.getIntrinsicWidth()/2, 0);
Rect crazyR = new Rect(-crazyIcon.getIntrinsicWidth()/2, -crazyIcon.getIntrinsicHeight(), crazyIcon.getIntrinsicWidth()/2, 0);
Rect downR = new Rect(-downIcon.getIntrinsicWidth(), -downIcon.getIntrinsicHeight(), 0, 0);
Rect duffysR = new Rect(0, -duffysIcon.getIntrinsicHeight(), duffysIcon.getIntrinsicWidth(), 0);
Rect joesR = new Rect(-joesIcon.getIntrinsicWidth()/2, -joesIcon.getIntrinsicHeight(), joesIcon.getIntrinsicWidth()/2, 0);
Rect lasallesR = new Rect(-lasallesIcon.getIntrinsicWidth()/2, -lasallesIcon.getIntrinsicHeight(), lasallesIcon.getIntrinsicWidth()/2, 0);
Rect lostR = new Rect(0, -lostIcon.getIntrinsicHeight(), lostIcon.getIntrinsicWidth(), 0);
Rect bearR = new Rect(-bearIcon.getIntrinsicWidth()/2, -bearIcon.getIntrinsicHeight(), bearIcon.getIntrinsicWidth()/2, 0);
Rect malteseR = new Rect(-malteseIcon.getIntrinsicWidth()/2, -malteseIcon.getIntrinsicHeight(), malteseIcon.getIntrinsicWidth()/2, 0);
Rect panamasR = new Rect(-panamasIcon.getIntrinsicWidth()/2, -panamasIcon.getIntrinsicHeight(), panamasIcon.getIntrinsicWidth()/2, 0);
Rect rileysR = new Rect(-rileysIcon.getIntrinsicWidth()/2, -rileysIcon.getIntrinsicHeight(), rileysIcon.getIntrinsicWidth()/2, 0);
Rect gradR = new Rect(-gradIcon.getIntrinsicWidth()/2, -gradIcon.getIntrinsicHeight(), gradIcon.getIntrinsicWidth()/2, 0);
Rect townR = new Rect(-townIcon.getIntrinsicWidth(), -townIcon.getIntrinsicHeight(), 0, 0);
Rect ubarR = new Rect(-ubarIcon.getIntrinsicWidth()/2, -ubarIcon.getIntrinsicHeight(), ubarIcon.getIntrinsicWidth()/2, 0);
BarItem overlaybanshee = new BarItem(bansheePoint, "Banshee", "I'm at Banshee!", bansheeIcon, bansheeR);
BarItem overlaybeach = new BarItem(beachPoint, "Beach", "I'm in Mexico City!", beachIcon, beachR);
BarItem overlaybellas = new BarItem(bellasPoint, "Bellas", "I'm in Mexico City!", bellasIcon, bellasR);
BarItem overlaycrazy = new BarItem(crazyPoint, "Crazy Horse", "I'm in Mexico City!", crazyIcon, crazyR);
BarItem overlaydown = new BarItem(downPoint, "Down Lo", "I'm in Mexico City!", downIcon, downR);
BarItem overlayduffys = new BarItem(duffysPoint, "Duffys", "I'm in Mexico City!", duffysIcon, duffysR);
BarItem overlayjoes = new BarItem(joesPoint, "Joes", "I'm in Mexico City!", joesIcon, joesR);
BarItem overlaylasalles = new BarItem(lasallesPoint, "Lasalles", "I'm in Mexico City!", lasallesIcon, lasallesR);
BarItem overlaylost = new BarItem(lostPoint, "Lost On Main", "I'm in Mexico City!", lostIcon, lostR);
BarItem overlaybear = new BarItem(bearPoint, "Madison Bear Garden", "I'm in Mexico City!", bearIcon, bearR);
BarItem overlaymaltese = new BarItem(maltesePoint, "Maltese", "I'm in Mexico City!", malteseIcon, malteseR);
BarItem overlaypanamas = new BarItem(panamasPoint, "Panamas", "I'm in Mexico City!", panamasIcon, panamasR);
BarItem overlayrileys = new BarItem(rileysPoint, "Rileys", "I'm in Mexico City!", rileysIcon, rileysR);
BarItem overlaygrad = new BarItem(gradPoint, "The Grad", "I'm in Mexico City!", gradIcon, gradR);
BarItem overlaytown = new BarItem(townPoint, "Town Lounge", "I'm in Mexico City!", townIcon, townR);
BarItem overlayubar = new BarItem(ubarPoint, "University Bar", "I'm in Mexico City!", ubarIcon, ubarR);
BarOverlay barsOverlay = new BarOverlay(cnoIco, this);
barsOverlay.addOverlay(overlaybanshee);
barsOverlay.addOverlay(overlaybeach);
barsOverlay.addOverlay(overlaybellas);
barsOverlay.addOverlay(overlaycrazy);
barsOverlay.addOverlay(overlaydown);
barsOverlay.addOverlay(overlayduffys);
barsOverlay.addOverlay(overlayjoes);
barsOverlay.addOverlay(overlaylasalles);
barsOverlay.addOverlay(overlaylost);
barsOverlay.addOverlay(overlaybear);
barsOverlay.addOverlay(overlaymaltese);
barsOverlay.addOverlay(overlaypanamas);
barsOverlay.addOverlay(overlayrileys);
barsOverlay.addOverlay(overlaygrad);
barsOverlay.addOverlay(overlaytown);
barsOverlay.addOverlay(overlayubar);
map.getOverlays().add(barsOverlay);
}
|
diff --git a/org.eclipse.egit.ui.test/src/org/eclipse/egit/ui/view/repositories/GitRepositoriesViewFetchAndPushTest.java b/org.eclipse.egit.ui.test/src/org/eclipse/egit/ui/view/repositories/GitRepositoriesViewFetchAndPushTest.java
index 5eac99a7..6f4c7e4a 100644
--- a/org.eclipse.egit.ui.test/src/org/eclipse/egit/ui/view/repositories/GitRepositoriesViewFetchAndPushTest.java
+++ b/org.eclipse.egit.ui.test/src/org/eclipse/egit/ui/view/repositories/GitRepositoriesViewFetchAndPushTest.java
@@ -1,248 +1,249 @@
/*******************************************************************************
* Copyright (c) 2010 SAP 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:
* Mathias Kinzler (SAP AG) - initial implementation
*******************************************************************************/
package org.eclipse.egit.ui.view.repositories;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import org.eclipse.egit.core.op.CloneOperation;
import org.eclipse.egit.ui.Activator;
import org.eclipse.egit.ui.UIText;
import org.eclipse.egit.ui.internal.push.PushConfiguredRemoteAction;
import org.eclipse.egit.ui.test.ContextMenuHelper;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepository;
import org.eclipse.jgit.transport.URIish;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swtbot.swt.finder.junit.SWTBotJunit4ClassRunner;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTable;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* SWTBot Tests for the Git Repositories View (mainly fetch and push)
*/
@RunWith(SWTBotJunit4ClassRunner.class)
public class GitRepositoriesViewFetchAndPushTest extends
GitRepositoriesViewTestBase {
private static File repositoryFile;
private static File remoteRepositoryFile;
private static File clonedRepositoryFile;
private static File clonedRepositoryFile2;
@BeforeClass
public static void beforeClass() throws Exception {
repositoryFile = createProjectAndCommitToRepository();
remoteRepositoryFile = createRemoteRepository(repositoryFile);
waitInUI();
// now let's clone the remote repository
URIish uri = new URIish("file:///" + remoteRepositoryFile.getPath());
File workdir = new File(testDirectory, "ClonedRepo");
CloneOperation op = new CloneOperation(uri, true, null, workdir,
"refs/heads/master", "origin");
op.run(null);
clonedRepositoryFile = new File(workdir, Constants.DOT_GIT);
// now let's clone the remote repository
uri = new URIish(remoteRepositoryFile.getPath());
workdir = new File(testDirectory, "ClonedRepo2");
op = new CloneOperation(uri, true, null, workdir, "refs/heads/master",
"origin");
op.run(null);
clonedRepositoryFile2 = new File(workdir, Constants.DOT_GIT);
}
@Before
public void before() throws Exception {
clearView();
deleteAllProjects();
}
@Test
public void testPushToOrigin() throws Exception {
Activator.getDefault().getRepositoryUtil().addConfiguredRepository(
clonedRepositoryFile);
shareProjects(clonedRepositoryFile);
SWTBotTree tree = getOrOpenView().bot().tree();
tree.select(0);
Repository repository = lookupRepository(clonedRepositoryFile);
// add the configuration for push
repository.getConfig().setString("remote", "origin", "push",
"refs/heads/*:refs/remotes/origin/*");
+ repository.getConfig().save();
myRepoViewUtil.getRemotesItem(tree, clonedRepositoryFile).expand().getNode(
"origin").expand().getNode(1).select();
ContextMenuHelper.clickContextMenu(tree, myUtil
.getPluginLocalizedValue("SimplePushCommand"));
String destinationString = clonedRepositoryFile.getParentFile()
.getName()
+ " - " + "origin";
String dialogTitle = NLS.bind(UIText.ResultDialog_title,
destinationString);
// first time: expect new branch
SWTBotShell confirmed = bot.shell(dialogTitle);
SWTBotTable table = confirmed.bot().table();
int rowCount = table.rowCount();
boolean newBranch = false;
for (int i = 0; i < rowCount; i++) {
newBranch = table.getTableItem(i).getText(3).equals(
UIText.PushResultTable_statusOkNewBranch);
if (newBranch)
break;
}
confirmed.close();
assertTrue("New branch expected", newBranch);
// second time: expect up to date
myRepoViewUtil.getRemotesItem(tree, clonedRepositoryFile).expand().getNode(
"origin").expand().getNode(1).select();
ContextMenuHelper.clickContextMenu(tree, myUtil
.getPluginLocalizedValue("SimplePushCommand"));
confirmed = bot.shell(dialogTitle);
table = confirmed.bot().table();
rowCount = table.rowCount();
boolean uptodate = false;
for (int i = 0; i < rowCount; i++) {
uptodate = table.getTableItem(i).getText(3).equals(
UIText.PushResultTable_statusUpToDate);
if (uptodate)
break;
}
confirmed.close();
assertTrue("Up to date expected", uptodate);
// touch and run again: expect new branch
String objectIdBefore = repository.getRef("refs/heads/master")
.getLeaf().getObjectId().name();
objectIdBefore = objectIdBefore.substring(0, 7);
touchAndSubmit(null);
myRepoViewUtil.getRemotesItem(tree, clonedRepositoryFile).expand().getNode(
"origin").expand().getNode(1).select();
ContextMenuHelper.clickContextMenu(tree, myUtil
.getPluginLocalizedValue("SimplePushCommand"));
confirmed = bot.shell(dialogTitle);
table = confirmed.bot().table();
rowCount = table.rowCount();
newBranch = false;
for (int i = 0; i < rowCount; i++) {
newBranch = table.getTableItem(i).getText(3).startsWith(
objectIdBefore);
if (newBranch)
break;
}
confirmed.close();
assertTrue("New branch expected", newBranch);
}
@Test
public void testFetchFromOrigin() throws Exception {
Activator.getDefault().getRepositoryUtil().addConfiguredRepository(
clonedRepositoryFile);
Activator.getDefault().getRepositoryUtil().addConfiguredRepository(
clonedRepositoryFile2);
FileRepository repository = lookupRepository(clonedRepositoryFile2);
// add the configuration for push from cloned2
repository.getConfig().setString("remote", "origin", "push",
"refs/heads/*:refs/heads/*");
repository.getConfig().save();
SWTBotTree tree = getOrOpenView().bot().tree();
String destinationString = clonedRepositoryFile.getParentFile()
.getName()
+ " - " + "origin";
String dialogTitle = NLS.bind(UIText.FetchResultDialog_title,
destinationString);
myRepoViewUtil.getRemotesItem(tree, clonedRepositoryFile).expand().getNode(
"origin").expand().getNode(0).select();
ContextMenuHelper.clickContextMenu(tree, myUtil
.getPluginLocalizedValue("SimpleFetchCommand"));
SWTBotShell confirm = bot.shell(dialogTitle);
assertEquals("Wrong result table row count", 0, confirm.bot().table()
.rowCount());
confirm.close();
deleteAllProjects();
shareProjects(clonedRepositoryFile2);
String objid = repository.getRef("refs/heads/master").getTarget()
.getObjectId().name();
objid = objid.substring(0, 7);
touchAndSubmit(null);
// push from other repository
PushConfiguredRemoteAction action = new PushConfiguredRemoteAction(
repository, "origin");
action.run(bot.activeShell().widget, false);
destinationString = clonedRepositoryFile2.getParentFile().getName()
+ " - " + "origin";
String pushdialogTitle = NLS.bind(UIText.ResultDialog_title,
destinationString);
bot.shell(pushdialogTitle).close();
deleteAllProjects();
refreshAndWait();
myRepoViewUtil.getRemotesItem(tree, clonedRepositoryFile).expand().getNode(
"origin").expand().getNode(0).select();
ContextMenuHelper.clickContextMenu(tree, myUtil
.getPluginLocalizedValue("SimpleFetchCommand"));
confirm = bot.shell(dialogTitle);
SWTBotTable table = confirm.bot().table();
boolean found = false;
for (int i = 0; i < table.rowCount(); i++) {
found = table.getTableItem(i).getText(2).startsWith(objid);
if (found)
break;
}
assertTrue(found);
confirm.close();
myRepoViewUtil.getRemotesItem(tree, clonedRepositoryFile).expand().getNode(
"origin").expand().getNode(0).select();
ContextMenuHelper.clickContextMenu(tree, myUtil
.getPluginLocalizedValue("SimpleFetchCommand"));
confirm = bot.shell(dialogTitle);
assertEquals("Wrong result table row count", 0, confirm.bot().table()
.rowCount());
}
}
| true | true |
public void testPushToOrigin() throws Exception {
Activator.getDefault().getRepositoryUtil().addConfiguredRepository(
clonedRepositoryFile);
shareProjects(clonedRepositoryFile);
SWTBotTree tree = getOrOpenView().bot().tree();
tree.select(0);
Repository repository = lookupRepository(clonedRepositoryFile);
// add the configuration for push
repository.getConfig().setString("remote", "origin", "push",
"refs/heads/*:refs/remotes/origin/*");
myRepoViewUtil.getRemotesItem(tree, clonedRepositoryFile).expand().getNode(
"origin").expand().getNode(1).select();
ContextMenuHelper.clickContextMenu(tree, myUtil
.getPluginLocalizedValue("SimplePushCommand"));
String destinationString = clonedRepositoryFile.getParentFile()
.getName()
+ " - " + "origin";
String dialogTitle = NLS.bind(UIText.ResultDialog_title,
destinationString);
// first time: expect new branch
SWTBotShell confirmed = bot.shell(dialogTitle);
SWTBotTable table = confirmed.bot().table();
int rowCount = table.rowCount();
boolean newBranch = false;
for (int i = 0; i < rowCount; i++) {
newBranch = table.getTableItem(i).getText(3).equals(
UIText.PushResultTable_statusOkNewBranch);
if (newBranch)
break;
}
confirmed.close();
assertTrue("New branch expected", newBranch);
// second time: expect up to date
myRepoViewUtil.getRemotesItem(tree, clonedRepositoryFile).expand().getNode(
"origin").expand().getNode(1).select();
ContextMenuHelper.clickContextMenu(tree, myUtil
.getPluginLocalizedValue("SimplePushCommand"));
confirmed = bot.shell(dialogTitle);
table = confirmed.bot().table();
rowCount = table.rowCount();
boolean uptodate = false;
for (int i = 0; i < rowCount; i++) {
uptodate = table.getTableItem(i).getText(3).equals(
UIText.PushResultTable_statusUpToDate);
if (uptodate)
break;
}
confirmed.close();
assertTrue("Up to date expected", uptodate);
// touch and run again: expect new branch
String objectIdBefore = repository.getRef("refs/heads/master")
.getLeaf().getObjectId().name();
objectIdBefore = objectIdBefore.substring(0, 7);
touchAndSubmit(null);
myRepoViewUtil.getRemotesItem(tree, clonedRepositoryFile).expand().getNode(
"origin").expand().getNode(1).select();
ContextMenuHelper.clickContextMenu(tree, myUtil
.getPluginLocalizedValue("SimplePushCommand"));
confirmed = bot.shell(dialogTitle);
table = confirmed.bot().table();
rowCount = table.rowCount();
newBranch = false;
for (int i = 0; i < rowCount; i++) {
newBranch = table.getTableItem(i).getText(3).startsWith(
objectIdBefore);
if (newBranch)
break;
}
confirmed.close();
assertTrue("New branch expected", newBranch);
}
|
public void testPushToOrigin() throws Exception {
Activator.getDefault().getRepositoryUtil().addConfiguredRepository(
clonedRepositoryFile);
shareProjects(clonedRepositoryFile);
SWTBotTree tree = getOrOpenView().bot().tree();
tree.select(0);
Repository repository = lookupRepository(clonedRepositoryFile);
// add the configuration for push
repository.getConfig().setString("remote", "origin", "push",
"refs/heads/*:refs/remotes/origin/*");
repository.getConfig().save();
myRepoViewUtil.getRemotesItem(tree, clonedRepositoryFile).expand().getNode(
"origin").expand().getNode(1).select();
ContextMenuHelper.clickContextMenu(tree, myUtil
.getPluginLocalizedValue("SimplePushCommand"));
String destinationString = clonedRepositoryFile.getParentFile()
.getName()
+ " - " + "origin";
String dialogTitle = NLS.bind(UIText.ResultDialog_title,
destinationString);
// first time: expect new branch
SWTBotShell confirmed = bot.shell(dialogTitle);
SWTBotTable table = confirmed.bot().table();
int rowCount = table.rowCount();
boolean newBranch = false;
for (int i = 0; i < rowCount; i++) {
newBranch = table.getTableItem(i).getText(3).equals(
UIText.PushResultTable_statusOkNewBranch);
if (newBranch)
break;
}
confirmed.close();
assertTrue("New branch expected", newBranch);
// second time: expect up to date
myRepoViewUtil.getRemotesItem(tree, clonedRepositoryFile).expand().getNode(
"origin").expand().getNode(1).select();
ContextMenuHelper.clickContextMenu(tree, myUtil
.getPluginLocalizedValue("SimplePushCommand"));
confirmed = bot.shell(dialogTitle);
table = confirmed.bot().table();
rowCount = table.rowCount();
boolean uptodate = false;
for (int i = 0; i < rowCount; i++) {
uptodate = table.getTableItem(i).getText(3).equals(
UIText.PushResultTable_statusUpToDate);
if (uptodate)
break;
}
confirmed.close();
assertTrue("Up to date expected", uptodate);
// touch and run again: expect new branch
String objectIdBefore = repository.getRef("refs/heads/master")
.getLeaf().getObjectId().name();
objectIdBefore = objectIdBefore.substring(0, 7);
touchAndSubmit(null);
myRepoViewUtil.getRemotesItem(tree, clonedRepositoryFile).expand().getNode(
"origin").expand().getNode(1).select();
ContextMenuHelper.clickContextMenu(tree, myUtil
.getPluginLocalizedValue("SimplePushCommand"));
confirmed = bot.shell(dialogTitle);
table = confirmed.bot().table();
rowCount = table.rowCount();
newBranch = false;
for (int i = 0; i < rowCount; i++) {
newBranch = table.getTableItem(i).getText(3).startsWith(
objectIdBefore);
if (newBranch)
break;
}
confirmed.close();
assertTrue("New branch expected", newBranch);
}
|
diff --git a/Countdown/src/Countdown/OperatorNode.java b/Countdown/src/Countdown/OperatorNode.java
index 63d2d69..85629e6 100644
--- a/Countdown/src/Countdown/OperatorNode.java
+++ b/Countdown/src/Countdown/OperatorNode.java
@@ -1,137 +1,139 @@
package Countdown;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Andrew Cassidy
*/
public class OperatorNode extends SyntaxTreeNode {
public OperatorType Type;
public SyntaxTreeNode Left;
public SyntaxTreeNode Right;
private boolean isValid = false;
@Override
public boolean IsValid() {
return isValid;
}
public int Evaluate() {
int left = Left.Evaluate();
int right = Right.Evaluate();
isValid = Left.IsValid() && Right.IsValid();
if (!isValid)
return 0;
if (Type == OperatorType.Divide) {
isValid &= right != 0;
if (!isValid)
return 0;
isValid &= left % right == 0;
if (!isValid)
return 0;
}
switch (Type) {
case Plus:
return Left.Evaluate() + Right.Evaluate();
case Minus:
return Left.Evaluate() - Right.Evaluate();
case Times:
return Left.Evaluate() * Right.Evaluate();
case Divide:
return Left.Evaluate() / Right.Evaluate();
default:
return Left.Evaluate() + Right.Evaluate();
}
}
private String OperatorString() {
return Type.toString();
}
@Override
public String toString() {
return toString(false);
}
// public boolean needsBrackets(OperatorNode parentNode, OperatorNode subNode) {
// return (parentNode.Type.getValue() <= subNode.Type.getValue())
// && (subNode.Type == parentNode.Type)
// && (parentNode.Type == OperatorType.Plus || parentNode.Type == OperatorType.Times);
// }
public String toString(boolean bracket) {
SyntaxTreeNode node = simplify();
if (node instanceof OperatorNode) {
OperatorNode opNode = (OperatorNode) node;
StringBuffer returnString = new StringBuffer();
returnString.append(opNode.Left.toString());
returnString.append(opNode.Type.toString());
returnString.append(opNode.Right.toString());
// parent higher?
boolean needsBrackets = bracket;
if (opNode.Parent != null)
{
needsBrackets |= opNode.Parent.Type.getPrecedence() < opNode.Type.getPrecedence();
// are we on rhs of a non-cumutative operator?
- needsBrackets |= (!opNode.Parent.Type.isComutative() && opNode.Parent.Right == opNode);
+ needsBrackets |= (!opNode.Parent.Type.isComutative()
+ && opNode.Parent.Right == opNode &&
+ opNode.Parent.Type.getPrecedence() == opNode.Type.getPrecedence());
}
if (needsBrackets)
{
returnString.append(")");
returnString.insert(0, "(");
}
return returnString.toString();
} else
return node.toString();
}
public boolean SubTreeSearch(SyntaxTreeNode node) {
if (Left == node || Right == node)
return true;
else
return Left.SubTreeSearch(node) || Right.SubTreeSearch(node);
}
public SyntaxTreeNode DeepCopy() {
OperatorNode copy = new OperatorNode();
copy.Left = this.Left.DeepCopy();
copy.Right = this.Right.DeepCopy();
copy.Left.Parent = copy;
copy.Right.Parent = copy;
copy.Type = this.Type;
return copy;
}
public SyntaxTreeNode simplify() {
if (Type == OperatorType.Times && Right instanceof NumberNode
&& ((NumberNode) Right).Value() == 1) {
return Left;
} else if (Type == OperatorType.Times && Left instanceof NumberNode
&& ((NumberNode) Left).Value() == 1) {
return Right;
} else if ((Type == OperatorType.Divide)
&& (Right instanceof NumberNode)
&& (((NumberNode) Right).Value() == 1)) {
return Left;
}
return this;
}
}
| true | true |
public String toString(boolean bracket) {
SyntaxTreeNode node = simplify();
if (node instanceof OperatorNode) {
OperatorNode opNode = (OperatorNode) node;
StringBuffer returnString = new StringBuffer();
returnString.append(opNode.Left.toString());
returnString.append(opNode.Type.toString());
returnString.append(opNode.Right.toString());
// parent higher?
boolean needsBrackets = bracket;
if (opNode.Parent != null)
{
needsBrackets |= opNode.Parent.Type.getPrecedence() < opNode.Type.getPrecedence();
// are we on rhs of a non-cumutative operator?
needsBrackets |= (!opNode.Parent.Type.isComutative() && opNode.Parent.Right == opNode);
}
if (needsBrackets)
{
returnString.append(")");
returnString.insert(0, "(");
}
return returnString.toString();
} else
return node.toString();
}
|
public String toString(boolean bracket) {
SyntaxTreeNode node = simplify();
if (node instanceof OperatorNode) {
OperatorNode opNode = (OperatorNode) node;
StringBuffer returnString = new StringBuffer();
returnString.append(opNode.Left.toString());
returnString.append(opNode.Type.toString());
returnString.append(opNode.Right.toString());
// parent higher?
boolean needsBrackets = bracket;
if (opNode.Parent != null)
{
needsBrackets |= opNode.Parent.Type.getPrecedence() < opNode.Type.getPrecedence();
// are we on rhs of a non-cumutative operator?
needsBrackets |= (!opNode.Parent.Type.isComutative()
&& opNode.Parent.Right == opNode &&
opNode.Parent.Type.getPrecedence() == opNode.Type.getPrecedence());
}
if (needsBrackets)
{
returnString.append(")");
returnString.insert(0, "(");
}
return returnString.toString();
} else
return node.toString();
}
|
diff --git a/lib/packetpig/src/main/java/com/packetloop/packetpig/loaders/pcap/packet/DnsPacketAllRecordReader.java b/lib/packetpig/src/main/java/com/packetloop/packetpig/loaders/pcap/packet/DnsPacketAllRecordReader.java
index 43aed1a..2942727 100644
--- a/lib/packetpig/src/main/java/com/packetloop/packetpig/loaders/pcap/packet/DnsPacketAllRecordReader.java
+++ b/lib/packetpig/src/main/java/com/packetloop/packetpig/loaders/pcap/packet/DnsPacketAllRecordReader.java
@@ -1,177 +1,177 @@
package com.packetloop.packetpig.loaders.pcap.packet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.krakenapps.pcap.decoder.ethernet.EthernetType;
import org.krakenapps.pcap.decoder.ip.InternetProtocol;
import org.krakenapps.pcap.decoder.ip.IpDecoder;
import org.krakenapps.pcap.decoder.ip.Ipv4Packet;
import org.krakenapps.pcap.decoder.udp.UdpDecoder;
import org.krakenapps.pcap.decoder.udp.UdpPacket;
import org.krakenapps.pcap.decoder.udp.UdpPortProtocolMapper;
import org.krakenapps.pcap.decoder.udp.UdpProcessor;
import org.krakenapps.pcap.packet.PcapPacket;
import org.krakenapps.pcap.util.Buffer;
import org.xbill.DNS.ARecord;
import org.xbill.DNS.Flags;
import org.xbill.DNS.Message;
import org.xbill.DNS.Record;
import org.xbill.DNS.Section;
import com.packetloop.packetpig.loaders.pcap.PcapRecordReader;
public class DnsPacketAllRecordReader extends PcapRecordReader {
private ArrayList<Tuple> tupleQueue;
volatile String srcIP;
volatile String dstIP;
volatile int srcPort;
volatile int dstPort;
volatile boolean valid = false;
volatile Message dns;
@Override
public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException {
super.initialize(split, context);
tupleQueue = new ArrayList<Tuple>();
IpDecoder ipDecoder = new IpDecoder();
UdpProcessor udpProcessor = new UdpProcessor() {
@Override
public void process(UdpPacket p) {
try {
Buffer buf = p.getData();
byte[] data = new byte[buf.readableBytes()];
buf.gets(data);
dns = new Message(data);
valid = true;
dstPort = p.getDestinationPort();
srcPort = p.getSourcePort();
} catch (IOException e) {
e.printStackTrace();
clear();
}
}
};
UdpDecoder udpDecoder = new UdpDecoder(new UdpPortProtocolMapper()) {
@Override
public void process(Ipv4Packet packet) {
super.process(packet);
srcIP = packet.getSourceAddress().getHostAddress();
dstIP = packet.getDestinationAddress().getHostAddress();
}
};
udpDecoder.registerUdpProcessor(udpProcessor);
eth.register(EthernetType.IPV4, ipDecoder);
ipDecoder.register(InternetProtocol.UDP, udpDecoder);
}
private void clear()
{
valid = false;
srcIP = null;
dstIP = null;
srcPort = -1;
dstPort = -1;
dns = null;
}
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
if (tupleQueue.size() > 0) {
tuple = tupleQueue.remove(0);
return true;
}
try {
// keep going until the decoder says it found a good one.
PcapPacket packet = null;
do
{
packet = is.getPacket();
eth.decode(packet);
}
while(!valid);
long tv_sec = packet.getPacketHeader().getTsSec();
long tv_usec = packet.getPacketHeader().getTsUsec();
long ts = tv_sec * 1000 + tv_usec / 1000;
key = new Date(ts).getTime() / 1000;
int id = dns.getHeader().getID();
String mode = dns.getHeader().getFlag(Flags.QR)?"response":"question";
for(Record rec : dns.getSectionArray(Section.QUESTION))
{
int i = 0;
Tuple t = TupleFactory.getInstance().newTuple(9);
t.set(i++, id); // transaction id
t.set(i++, mode); // mode ('query' or 'response')
t.set(i++, rec.getName().toString()); // qname
t.set(i++, null); // answer.ip OR null (for ques)
t.set(i++, 0); // qttl
t.set(i++, srcIP);
t.set(i++, dstIP);
t.set(i++, rec.getDClass());
- t.set(i++, rec.getTTL());
+ t.set(i++, rec.getType());
tupleQueue.add(t);
}
for(Record rec : dns.getSectionArray(Section.ANSWER))
{
int i = 0;
Tuple t = TupleFactory.getInstance().newTuple(9);
t.set(i++, id); // transaction id
t.set(i++, mode); // mode ('query' or 'response')
t.set(i++, rec.getName().toString()); // qname
if (rec instanceof ARecord) {
t.set(i++, ((ARecord)rec).getAddress().getHostAddress()); // answer.ip OR null
}else {
t.set(i++, null);
}
t.set(i++, rec.getTTL()); // qttl
t.set(i++, srcIP);
t.set(i++, dstIP);
t.set(i++, rec.getDClass());
- t.set(i++, rec.getTTL());
+ t.set(i++, rec.getType());
tupleQueue.add(t);
}
clear();
if (tupleQueue.size() > 0) {
tuple = tupleQueue.remove(0);
return true;
}
else
{
clear();
is.close();
return false;
}
} catch (IOException ignored) {
ignored.printStackTrace();
clear();
is.close();
return false;
}
}
@Override
public void close() throws IOException {
super.close();
is.close();
}
}
| false | true |
public boolean nextKeyValue() throws IOException, InterruptedException {
if (tupleQueue.size() > 0) {
tuple = tupleQueue.remove(0);
return true;
}
try {
// keep going until the decoder says it found a good one.
PcapPacket packet = null;
do
{
packet = is.getPacket();
eth.decode(packet);
}
while(!valid);
long tv_sec = packet.getPacketHeader().getTsSec();
long tv_usec = packet.getPacketHeader().getTsUsec();
long ts = tv_sec * 1000 + tv_usec / 1000;
key = new Date(ts).getTime() / 1000;
int id = dns.getHeader().getID();
String mode = dns.getHeader().getFlag(Flags.QR)?"response":"question";
for(Record rec : dns.getSectionArray(Section.QUESTION))
{
int i = 0;
Tuple t = TupleFactory.getInstance().newTuple(9);
t.set(i++, id); // transaction id
t.set(i++, mode); // mode ('query' or 'response')
t.set(i++, rec.getName().toString()); // qname
t.set(i++, null); // answer.ip OR null (for ques)
t.set(i++, 0); // qttl
t.set(i++, srcIP);
t.set(i++, dstIP);
t.set(i++, rec.getDClass());
t.set(i++, rec.getTTL());
tupleQueue.add(t);
}
for(Record rec : dns.getSectionArray(Section.ANSWER))
{
int i = 0;
Tuple t = TupleFactory.getInstance().newTuple(9);
t.set(i++, id); // transaction id
t.set(i++, mode); // mode ('query' or 'response')
t.set(i++, rec.getName().toString()); // qname
if (rec instanceof ARecord) {
t.set(i++, ((ARecord)rec).getAddress().getHostAddress()); // answer.ip OR null
}else {
t.set(i++, null);
}
t.set(i++, rec.getTTL()); // qttl
t.set(i++, srcIP);
t.set(i++, dstIP);
t.set(i++, rec.getDClass());
t.set(i++, rec.getTTL());
tupleQueue.add(t);
}
clear();
if (tupleQueue.size() > 0) {
tuple = tupleQueue.remove(0);
return true;
}
else
{
clear();
is.close();
return false;
}
} catch (IOException ignored) {
ignored.printStackTrace();
clear();
is.close();
return false;
}
}
|
public boolean nextKeyValue() throws IOException, InterruptedException {
if (tupleQueue.size() > 0) {
tuple = tupleQueue.remove(0);
return true;
}
try {
// keep going until the decoder says it found a good one.
PcapPacket packet = null;
do
{
packet = is.getPacket();
eth.decode(packet);
}
while(!valid);
long tv_sec = packet.getPacketHeader().getTsSec();
long tv_usec = packet.getPacketHeader().getTsUsec();
long ts = tv_sec * 1000 + tv_usec / 1000;
key = new Date(ts).getTime() / 1000;
int id = dns.getHeader().getID();
String mode = dns.getHeader().getFlag(Flags.QR)?"response":"question";
for(Record rec : dns.getSectionArray(Section.QUESTION))
{
int i = 0;
Tuple t = TupleFactory.getInstance().newTuple(9);
t.set(i++, id); // transaction id
t.set(i++, mode); // mode ('query' or 'response')
t.set(i++, rec.getName().toString()); // qname
t.set(i++, null); // answer.ip OR null (for ques)
t.set(i++, 0); // qttl
t.set(i++, srcIP);
t.set(i++, dstIP);
t.set(i++, rec.getDClass());
t.set(i++, rec.getType());
tupleQueue.add(t);
}
for(Record rec : dns.getSectionArray(Section.ANSWER))
{
int i = 0;
Tuple t = TupleFactory.getInstance().newTuple(9);
t.set(i++, id); // transaction id
t.set(i++, mode); // mode ('query' or 'response')
t.set(i++, rec.getName().toString()); // qname
if (rec instanceof ARecord) {
t.set(i++, ((ARecord)rec).getAddress().getHostAddress()); // answer.ip OR null
}else {
t.set(i++, null);
}
t.set(i++, rec.getTTL()); // qttl
t.set(i++, srcIP);
t.set(i++, dstIP);
t.set(i++, rec.getDClass());
t.set(i++, rec.getType());
tupleQueue.add(t);
}
clear();
if (tupleQueue.size() > 0) {
tuple = tupleQueue.remove(0);
return true;
}
else
{
clear();
is.close();
return false;
}
} catch (IOException ignored) {
ignored.printStackTrace();
clear();
is.close();
return false;
}
}
|
diff --git a/replication-http/src/main/java/org/openstreetmap/osmosis/replicationhttp/v0_6/ReplicationDataClientFactory.java b/replication-http/src/main/java/org/openstreetmap/osmosis/replicationhttp/v0_6/ReplicationDataClientFactory.java
index 9a029e8f..cc4bba02 100644
--- a/replication-http/src/main/java/org/openstreetmap/osmosis/replicationhttp/v0_6/ReplicationDataClientFactory.java
+++ b/replication-http/src/main/java/org/openstreetmap/osmosis/replicationhttp/v0_6/ReplicationDataClientFactory.java
@@ -1,57 +1,57 @@
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.replicationhttp.v0_6;
import java.net.InetSocketAddress;
import org.openstreetmap.osmosis.core.pipeline.common.TaskConfiguration;
import org.openstreetmap.osmosis.core.pipeline.common.TaskManager;
import org.openstreetmap.osmosis.core.pipeline.common.TaskManagerFactory;
import org.openstreetmap.osmosis.core.pipeline.v0_6.RunnableChangeSourceManager;
/**
* The task manager factory for a HTTP replication data client.
*
* @author Brett Henderson
*/
public class ReplicationDataClientFactory extends TaskManagerFactory {
private static final String ARG_HOST = "host";
private static final String ARG_PORT = "port";
private static final String ARG_PATH_PREFIX = "pathPrefix";
private static final String DEFAULT_HOST = "localhost";
private static final int DEFAULT_PORT = 0;
private static final String DEFAULT_PATH_PREFIX = "";
/**
* {@inheritDoc}
*/
@Override
protected TaskManager createTaskManagerImpl(TaskConfiguration taskConfig) {
String host;
int port;
StringBuilder basePath;
// Get the task arguments.
host = getStringArgument(taskConfig, ARG_HOST, DEFAULT_HOST);
port = getIntegerArgument(taskConfig, ARG_PORT, DEFAULT_PORT);
basePath = new StringBuilder(getStringArgument(taskConfig, ARG_PATH_PREFIX, DEFAULT_PATH_PREFIX));
// Ensure that the base path if it exists has a leading slash but no trailing slash.
- while (basePath.charAt(0) == '/') {
+ while (basePath.length() > 0 && basePath.charAt(0) == '/') {
basePath.delete(0, 1);
}
- while (basePath.charAt(basePath.length() - 1) == '/') {
+ while (basePath.length() > 0 && basePath.charAt(basePath.length() - 1) == '/') {
basePath.delete(basePath.length() - 1, basePath.length());
}
if (basePath.length() > 0) {
basePath.insert(0, '/');
}
return new RunnableChangeSourceManager(
taskConfig.getId(),
new ReplicationDataClient(new InetSocketAddress(host, port), basePath.toString()),
taskConfig.getPipeArgs()
);
}
}
| false | true |
protected TaskManager createTaskManagerImpl(TaskConfiguration taskConfig) {
String host;
int port;
StringBuilder basePath;
// Get the task arguments.
host = getStringArgument(taskConfig, ARG_HOST, DEFAULT_HOST);
port = getIntegerArgument(taskConfig, ARG_PORT, DEFAULT_PORT);
basePath = new StringBuilder(getStringArgument(taskConfig, ARG_PATH_PREFIX, DEFAULT_PATH_PREFIX));
// Ensure that the base path if it exists has a leading slash but no trailing slash.
while (basePath.charAt(0) == '/') {
basePath.delete(0, 1);
}
while (basePath.charAt(basePath.length() - 1) == '/') {
basePath.delete(basePath.length() - 1, basePath.length());
}
if (basePath.length() > 0) {
basePath.insert(0, '/');
}
return new RunnableChangeSourceManager(
taskConfig.getId(),
new ReplicationDataClient(new InetSocketAddress(host, port), basePath.toString()),
taskConfig.getPipeArgs()
);
}
|
protected TaskManager createTaskManagerImpl(TaskConfiguration taskConfig) {
String host;
int port;
StringBuilder basePath;
// Get the task arguments.
host = getStringArgument(taskConfig, ARG_HOST, DEFAULT_HOST);
port = getIntegerArgument(taskConfig, ARG_PORT, DEFAULT_PORT);
basePath = new StringBuilder(getStringArgument(taskConfig, ARG_PATH_PREFIX, DEFAULT_PATH_PREFIX));
// Ensure that the base path if it exists has a leading slash but no trailing slash.
while (basePath.length() > 0 && basePath.charAt(0) == '/') {
basePath.delete(0, 1);
}
while (basePath.length() > 0 && basePath.charAt(basePath.length() - 1) == '/') {
basePath.delete(basePath.length() - 1, basePath.length());
}
if (basePath.length() > 0) {
basePath.insert(0, '/');
}
return new RunnableChangeSourceManager(
taskConfig.getId(),
new ReplicationDataClient(new InetSocketAddress(host, port), basePath.toString()),
taskConfig.getPipeArgs()
);
}
|
diff --git a/java/server/src/org/openqa/selenium/remote/server/DefaultDriverSessions.java b/java/server/src/org/openqa/selenium/remote/server/DefaultDriverSessions.java
index a8cdf3e49..4c0d6f346 100644
--- a/java/server/src/org/openqa/selenium/remote/server/DefaultDriverSessions.java
+++ b/java/server/src/org/openqa/selenium/remote/server/DefaultDriverSessions.java
@@ -1,112 +1,114 @@
/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium.remote.server;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.SessionId;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
public class DefaultDriverSessions implements DriverSessions {
private final DriverFactory factory;
// TODO(simon): Replace with an actual factory. Or UUIDs.
private static final AtomicLong sessionKeyFactory = new AtomicLong(System.currentTimeMillis());
private final Map<SessionId, Session> sessionIdToDriver =
new ConcurrentHashMap<SessionId, Session>();
private static Map<Capabilities, String> defaultDrivers = new HashMap<Capabilities, String>() {{
put(DesiredCapabilities.chrome(), "org.openqa.selenium.chrome.ChromeDriver");
put(DesiredCapabilities.firefox(), "org.openqa.selenium.firefox.FirefoxDriver");
put(DesiredCapabilities.htmlUnit(), "org.openqa.selenium.htmlunit.HtmlUnitDriver");
put(DesiredCapabilities.internetExplorer(), "org.openqa.selenium.ie.InternetExplorerDriver");
put(DesiredCapabilities.opera(), "com.opera.core.systems.OperaDriver");
}};
public DefaultDriverSessions() {
this(Platform.getCurrent(), new DefaultDriverFactory());
}
protected DefaultDriverSessions(Platform runningOn, DriverFactory factory) {
this.factory = factory;
registerDefaults(runningOn);
}
private void registerDefaults(Platform current) {
if (current.equals(Platform.ANDROID)) {
+ // AndroidDriver is here for backward-compatibility reasons, it should be removed at some point
registerDriver(DesiredCapabilities.android(), "org.openqa.selenium.android.AndroidDriver");
+ registerDriver(DesiredCapabilities.android(), "org.openqa.selenium.android.AndroidApkDriver");
return;
}
for (Map.Entry<Capabilities, String> entry : defaultDrivers.entrySet()) {
Capabilities caps = entry.getKey();
if (caps.getPlatform() != null && caps.getPlatform().is(current)) {
registerDriver(caps, entry.getValue());
} else if (caps.getPlatform() == null) {
registerDriver(caps, entry.getValue());
}
}
}
private void registerDriver(Capabilities caps, String className) {
try {
registerDriver(caps, Class.forName(className).asSubclass(WebDriver.class));
} catch (ClassNotFoundException e) {
// OK. Fall through. We just won't be able to create these
} catch (NoClassDefFoundError e) {
// OK. Missing a dependency, which is obviously a Bad Thing
// TODO(simon): Log this!
}
}
public SessionId newSession(Capabilities desiredCapabilities) throws Exception {
SessionId sessionId = new SessionId(String.valueOf(sessionKeyFactory.getAndIncrement()));
Session session = DefaultSession.createSession(factory, sessionId, desiredCapabilities);
sessionIdToDriver.put(sessionId, session);
return sessionId;
}
public Session get(SessionId sessionId) {
return sessionIdToDriver.get(sessionId);
}
public void deleteSession(SessionId sessionId) {
final Session removedSession = sessionIdToDriver.remove(sessionId);
if (removedSession != null) {
removedSession.close();
}
}
public void registerDriver(Capabilities capabilities, Class<? extends WebDriver> implementation) {
factory.registerDriver(capabilities, implementation);
}
public Set<SessionId> getSessions() {
return Collections.unmodifiableSet(sessionIdToDriver.keySet());
}
}
| false | true |
private void registerDefaults(Platform current) {
if (current.equals(Platform.ANDROID)) {
registerDriver(DesiredCapabilities.android(), "org.openqa.selenium.android.AndroidDriver");
return;
}
for (Map.Entry<Capabilities, String> entry : defaultDrivers.entrySet()) {
Capabilities caps = entry.getKey();
if (caps.getPlatform() != null && caps.getPlatform().is(current)) {
registerDriver(caps, entry.getValue());
} else if (caps.getPlatform() == null) {
registerDriver(caps, entry.getValue());
}
}
}
|
private void registerDefaults(Platform current) {
if (current.equals(Platform.ANDROID)) {
// AndroidDriver is here for backward-compatibility reasons, it should be removed at some point
registerDriver(DesiredCapabilities.android(), "org.openqa.selenium.android.AndroidDriver");
registerDriver(DesiredCapabilities.android(), "org.openqa.selenium.android.AndroidApkDriver");
return;
}
for (Map.Entry<Capabilities, String> entry : defaultDrivers.entrySet()) {
Capabilities caps = entry.getKey();
if (caps.getPlatform() != null && caps.getPlatform().is(current)) {
registerDriver(caps, entry.getValue());
} else if (caps.getPlatform() == null) {
registerDriver(caps, entry.getValue());
}
}
}
|
diff --git a/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/FencingExecutor.java b/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/FencingExecutor.java
index 30c5867fb..9158aba22 100644
--- a/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/FencingExecutor.java
+++ b/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/FencingExecutor.java
@@ -1,157 +1,157 @@
package org.ovirt.engine.core.bll;
import org.ovirt.engine.core.common.businessentities.FenceActionType;
import org.ovirt.engine.core.common.businessentities.FenceStatusReturnValue;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VdsSpmStatus;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.errors.VdcBLLException;
import org.ovirt.engine.core.common.vdscommands.FenceVdsVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.SpmStopVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.utils.linq.LinqUtils;
import org.ovirt.engine.core.utils.linq.Predicate;
import org.ovirt.engine.core.utils.log.Log;
import org.ovirt.engine.core.utils.log.LogFactory;
import org.ovirt.engine.core.utils.pm.VdsFencingOptions;
public class FencingExecutor {
private final VDS _vds;
private FenceActionType _action = FenceActionType.forValue(0);
private Guid _vdsToRunId;
private String _vdsToRunName;
public FencingExecutor(VDS vds, FenceActionType actionType) {
_vds = vds;
_action = actionType;
}
public boolean FindVdsToFence() {
final Guid NO_VDS = Guid.Empty;
int count = 0;
// make sure that loop is executed at least once , no matter what is the
// value in config
int retries = Math.max(Config.<Integer> GetValue(ConfigValues.FindFenceProxyRetries), 1);
int delayInMs = 1000 * Config.<Integer> GetValue(ConfigValues.FindFenceProxyDelayBetweenRetriesInSec);
_vdsToRunId = NO_VDS;
VDS vdsToRun = null;
// check if this is a new host, no need to retry , only status is
// available on new host.
if (_vds.getId().equals(NO_VDS)) {
vdsToRun = LinqUtils.firstOrNull(DbFacade.getInstance().getVdsDAO().getAll(), new Predicate<VDS>() {
@Override
public boolean eval(VDS vds) {
return vds.getstatus() == VDSStatus.Up
&& vds.getstorage_pool_id().equals(_vds.getstorage_pool_id());
}
});
if (vdsToRun != null) {
_vdsToRunId = vdsToRun.getId();
_vdsToRunName = vdsToRun.getvds_name();
}
} else {
// If can not find a proxy host retry and delay between retries
// as configured.
while (count < retries) {
vdsToRun = LinqUtils.firstOrNull(DbFacade.getInstance().getVdsDAO().getAll(), new Predicate<VDS>() {
@Override
public boolean eval(VDS vds) {
return !vds.getId().equals(_vds.getId())
&& vds.getstorage_pool_id().equals(_vds.getstorage_pool_id())
&& vds.getstatus() == VDSStatus.Up;
}
});
if (vdsToRun != null) {
_vdsToRunId = vdsToRun.getId();
_vdsToRunName = vdsToRun.getvds_name();
break;
}
// do not retry getting proxy for Status operation.
if (_action == FenceActionType.Status)
break;
log.infoFormat("Atempt {0} to find fencing proxy host failed...", ++count);
try {
Thread.sleep(delayInMs);
} catch (Exception e) {
log.error(e.getMessage());
break;
}
}
}
- if (_vdsToRunId == NO_VDS) {
+ if (NO_VDS.equals(_vdsToRunId)) {
log.errorFormat("Failed to run Power Management command on Host {0}, no running proxy Host was found.",
_vds.getvds_name());
}
- return (_vdsToRunId != NO_VDS);
+ return !NO_VDS.equals(_vdsToRunId);
}
public VDSReturnValue Fence() {
VDSReturnValue retValue = null;
try {
// skip following code in case of testing a new host status
if (_vds.getId() != null && !_vds.getId().equals(Guid.Empty)) {
// get the host spm status again from the database in order to test it's current state.
_vds.setspm_status((DbFacade.getInstance().getVdsDAO().get(_vds.getId()).getspm_status()));
// try to stop SPM if action is Restart or Stop and the vds is SPM
if ((_action == FenceActionType.Restart || _action == FenceActionType.Stop)
&& (_vds.getspm_status() != VdsSpmStatus.None)) {
Backend.getInstance()
.getResourceManager()
.RunVdsCommand(VDSCommandType.SpmStop,
new SpmStopVDSCommandParameters(_vds.getId(), _vds.getstorage_pool_id()));
}
}
retValue = runFencingAction(_action);
} catch (VdcBLLException e) {
retValue = new VDSReturnValue();
retValue.setReturnValue(new FenceStatusReturnValue("unknown", e.getMessage()));
retValue.setExceptionString(e.getMessage());
retValue.setSucceeded(false);
}
return retValue;
}
/**
* Check if the proxy can be used to fence the host successfully.
* @return Whether the proxy host can be used to fence the host successfully.
*/
public boolean checkProxyHostConnectionToHost() {
return runFencingAction(FenceActionType.Status).getSucceeded();
}
/**
* Run the specified fencing action.
* @param actionType The action to run.
* @return The result of running the fencing command.
*/
private VDSReturnValue runFencingAction(FenceActionType actionType) {
String managementPort = "";
if (_vds.getpm_port() != null && _vds.getpm_port() != 0) {
managementPort = _vds.getpm_port().toString();
}
// get real agent and default parameters
String agent = VdsFencingOptions.getRealAgent(_vds.getpm_type());
String managementOptions = VdsFencingOptions.getDefaultAgentOptions(_vds.getpm_type(),_vds.getpm_options());
log.infoFormat("Executing <{0}> Power Management command, Proxy Host:{1}, "
+ "Agent:{2}, Target Host:{3}, Management IP:{4}, User:{5}, Options:{6}", actionType, _vdsToRunName,
agent, _vds.getvds_name(), _vds.getManagmentIp(), _vds.getpm_user(), managementOptions);
return Backend
.getInstance()
.getResourceManager()
.RunVdsCommand(
VDSCommandType.FenceVds,
new FenceVdsVDSCommandParameters(_vdsToRunId, _vds.getId(), _vds.getManagmentIp(),
managementPort, agent, _vds.getpm_user(), _vds.getpm_password(),
managementOptions, actionType));
}
private static Log log = LogFactory.getLog(FencingExecutor.class);
}
| false | true |
public boolean FindVdsToFence() {
final Guid NO_VDS = Guid.Empty;
int count = 0;
// make sure that loop is executed at least once , no matter what is the
// value in config
int retries = Math.max(Config.<Integer> GetValue(ConfigValues.FindFenceProxyRetries), 1);
int delayInMs = 1000 * Config.<Integer> GetValue(ConfigValues.FindFenceProxyDelayBetweenRetriesInSec);
_vdsToRunId = NO_VDS;
VDS vdsToRun = null;
// check if this is a new host, no need to retry , only status is
// available on new host.
if (_vds.getId().equals(NO_VDS)) {
vdsToRun = LinqUtils.firstOrNull(DbFacade.getInstance().getVdsDAO().getAll(), new Predicate<VDS>() {
@Override
public boolean eval(VDS vds) {
return vds.getstatus() == VDSStatus.Up
&& vds.getstorage_pool_id().equals(_vds.getstorage_pool_id());
}
});
if (vdsToRun != null) {
_vdsToRunId = vdsToRun.getId();
_vdsToRunName = vdsToRun.getvds_name();
}
} else {
// If can not find a proxy host retry and delay between retries
// as configured.
while (count < retries) {
vdsToRun = LinqUtils.firstOrNull(DbFacade.getInstance().getVdsDAO().getAll(), new Predicate<VDS>() {
@Override
public boolean eval(VDS vds) {
return !vds.getId().equals(_vds.getId())
&& vds.getstorage_pool_id().equals(_vds.getstorage_pool_id())
&& vds.getstatus() == VDSStatus.Up;
}
});
if (vdsToRun != null) {
_vdsToRunId = vdsToRun.getId();
_vdsToRunName = vdsToRun.getvds_name();
break;
}
// do not retry getting proxy for Status operation.
if (_action == FenceActionType.Status)
break;
log.infoFormat("Atempt {0} to find fencing proxy host failed...", ++count);
try {
Thread.sleep(delayInMs);
} catch (Exception e) {
log.error(e.getMessage());
break;
}
}
}
if (_vdsToRunId == NO_VDS) {
log.errorFormat("Failed to run Power Management command on Host {0}, no running proxy Host was found.",
_vds.getvds_name());
}
return (_vdsToRunId != NO_VDS);
}
|
public boolean FindVdsToFence() {
final Guid NO_VDS = Guid.Empty;
int count = 0;
// make sure that loop is executed at least once , no matter what is the
// value in config
int retries = Math.max(Config.<Integer> GetValue(ConfigValues.FindFenceProxyRetries), 1);
int delayInMs = 1000 * Config.<Integer> GetValue(ConfigValues.FindFenceProxyDelayBetweenRetriesInSec);
_vdsToRunId = NO_VDS;
VDS vdsToRun = null;
// check if this is a new host, no need to retry , only status is
// available on new host.
if (_vds.getId().equals(NO_VDS)) {
vdsToRun = LinqUtils.firstOrNull(DbFacade.getInstance().getVdsDAO().getAll(), new Predicate<VDS>() {
@Override
public boolean eval(VDS vds) {
return vds.getstatus() == VDSStatus.Up
&& vds.getstorage_pool_id().equals(_vds.getstorage_pool_id());
}
});
if (vdsToRun != null) {
_vdsToRunId = vdsToRun.getId();
_vdsToRunName = vdsToRun.getvds_name();
}
} else {
// If can not find a proxy host retry and delay between retries
// as configured.
while (count < retries) {
vdsToRun = LinqUtils.firstOrNull(DbFacade.getInstance().getVdsDAO().getAll(), new Predicate<VDS>() {
@Override
public boolean eval(VDS vds) {
return !vds.getId().equals(_vds.getId())
&& vds.getstorage_pool_id().equals(_vds.getstorage_pool_id())
&& vds.getstatus() == VDSStatus.Up;
}
});
if (vdsToRun != null) {
_vdsToRunId = vdsToRun.getId();
_vdsToRunName = vdsToRun.getvds_name();
break;
}
// do not retry getting proxy for Status operation.
if (_action == FenceActionType.Status)
break;
log.infoFormat("Atempt {0} to find fencing proxy host failed...", ++count);
try {
Thread.sleep(delayInMs);
} catch (Exception e) {
log.error(e.getMessage());
break;
}
}
}
if (NO_VDS.equals(_vdsToRunId)) {
log.errorFormat("Failed to run Power Management command on Host {0}, no running proxy Host was found.",
_vds.getvds_name());
}
return !NO_VDS.equals(_vdsToRunId);
}
|
diff --git a/net.sf.jmoney/src/net/sf/jmoney/model2/CapitalAccountExtension.java b/net.sf.jmoney/src/net/sf/jmoney/model2/CapitalAccountExtension.java
index 2fbd465a..973c0f02 100644
--- a/net.sf.jmoney/src/net/sf/jmoney/model2/CapitalAccountExtension.java
+++ b/net.sf.jmoney/src/net/sf/jmoney/model2/CapitalAccountExtension.java
@@ -1,87 +1,87 @@
/*
*
* JMoney - A Personal Finance Manager
* Copyright (c) 2006 Nigel Westbury <[email protected]>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
package net.sf.jmoney.model2;
/**
* This is a helper class that makes it a little easier for a plug-in to extend
* the CapitalAccount object.
* <P>
* To add fields and methods to a CapitalAccount object, one may derive a class
* from CapitalAccountExtension. This mechanism allows multiple extensions to a
* CapitalAccount object to be added and maintained at runtime.
* <P>
* All extensions to CapitalAccount objects implement the same methods that are
* in the CapitalAccount object. This is for convenience so the consumer can get
* a single object that supports both the original CapitalAccount methods and
* the extension methods. All CapitalAccount methods are passed on to the
* CapitalAccount object.
*
* @author Nigel Westbury
*/
public abstract class CapitalAccountExtension extends AccountExtension {
- public CapitalAccountExtension(CapitalAccount extendedObject) {
+ public CapitalAccountExtension(ExtendableObject extendedObject) {
super(extendedObject);
}
public String getAbbreviation() {
return getBaseObject().getAbbreviation();
}
/**
* @return the comment of this account.
*/
public String getComment() {
return getBaseObject().getComment();
}
@Override
public ObjectCollection<CapitalAccount> getSubAccountCollection() {
return getBaseObject().getSubAccountCollection();
}
public void setAbbreviation(String abbreviation) {
getBaseObject().setAbbreviation(abbreviation);
}
public void setComment(String comment) {
getBaseObject().setComment(comment);
}
public <A extends CapitalAccount> A createSubAccount(ExtendablePropertySet<A> propertySet) {
return getBaseObject().createSubAccount(propertySet);
}
boolean deleteSubAccount(CapitalAccount subAccount) {
return getBaseObject().deleteSubAccount(subAccount);
}
// This does some casting - perhaps this is not needed
// if generics are used????
@Override
public CapitalAccount getBaseObject() {
return (CapitalAccount)baseObject;
}
}
| true | true |
public CapitalAccountExtension(CapitalAccount extendedObject) {
super(extendedObject);
}
|
public CapitalAccountExtension(ExtendableObject extendedObject) {
super(extendedObject);
}
|
diff --git a/org.eclipse.stem.ui.diseasemodels.multipopulation/src/org/eclipse/stem/diseasemodels/multipopulation/presentation/MultiPopulationDiseaseModelPropertyEditor.java b/org.eclipse.stem.ui.diseasemodels.multipopulation/src/org/eclipse/stem/diseasemodels/multipopulation/presentation/MultiPopulationDiseaseModelPropertyEditor.java
index 3eccebeb..aa1f9cbd 100644
--- a/org.eclipse.stem.ui.diseasemodels.multipopulation/src/org/eclipse/stem/diseasemodels/multipopulation/presentation/MultiPopulationDiseaseModelPropertyEditor.java
+++ b/org.eclipse.stem.ui.diseasemodels.multipopulation/src/org/eclipse/stem/diseasemodels/multipopulation/presentation/MultiPopulationDiseaseModelPropertyEditor.java
@@ -1,363 +1,373 @@
package org.eclipse.stem.diseasemodels.multipopulation.presentation;
/*******************************************************************************
* Copyright (c) 2007, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import java.util.List;
import java.util.Map;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.stem.core.common.CommonPackage;
import org.eclipse.stem.core.common.DoubleValue;
import org.eclipse.stem.core.common.DoubleValueList;
import org.eclipse.stem.core.common.DoubleValueMatrix;
import org.eclipse.stem.core.common.StringValueList;
import org.eclipse.stem.diseasemodels.multipopulation.MultiPopulationSEIRDiseaseModel;
import org.eclipse.stem.diseasemodels.multipopulation.MultiPopulationSIDiseaseModel;
import org.eclipse.stem.diseasemodels.multipopulation.MultiPopulationSIRDiseaseModel;
import org.eclipse.stem.diseasemodels.multipopulation.MultipopulationPackage;
import org.eclipse.stem.diseasemodels.standard.DiseaseModel;
import org.eclipse.stem.diseasemodels.standard.StandardPackage;
import org.eclipse.stem.ui.adapters.diseasemodelpropertyeditor.DiseaseModelPropertyEditor;
import org.eclipse.stem.ui.adapters.propertystrings.PropertyStringProvider;
import org.eclipse.stem.ui.adapters.propertystrings.PropertyStringProviderAdapter;
import org.eclipse.stem.ui.adapters.propertystrings.PropertyStringProviderAdapterFactory;
import org.eclipse.stem.ui.widgets.MatrixEditorWidget.MatrixEditorValidator;
import org.eclipse.stem.ui.wizards.DiseaseWizardMessages;
import org.eclipse.stem.ui.wizards.StandardDiseaseModelPropertyEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
/**
*
*/
public class MultiPopulationDiseaseModelPropertyEditor extends
StandardDiseaseModelPropertyEditor {
/**
* @param parent
* @param style
* @param diseaseModel
* @param projectValidator
*/
public MultiPopulationDiseaseModelPropertyEditor(Composite parent,
int style, DiseaseModel diseaseModel,
ModifyListener projectValidator) {
super(parent, style, diseaseModel, projectValidator);
} // MultiDiseaseModelPropertyEditor
/**
* @see org.eclipse.stem.ui.wizards.StandardDiseaseModelPropertyEditor#populate(org.eclipse.stem.diseasemodels.standard.DiseaseModel)
*/
@Override
public void populate(DiseaseModel diseaseModel) {
super.populate(diseaseModel);
for (final Map.Entry<EStructuralFeature, Text> entry : map.entrySet()) {
double dVal = 0.0;
switch (entry.getKey().getFeatureID()) {
case MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__PHYSICALLY_ADJACENT_INFECTIOUS_PROPORTION:
dVal = (new Double(entry.getValue().getText())).doubleValue();
((MultiPopulationSIDiseaseModel) diseaseModel).setPhysicallyAdjacentInfectiousProportion(dVal);
break;
case MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__ROAD_NETWORK_INFECTIOUS_PROPORTION:
dVal = (new Double(entry.getValue().getText())).doubleValue();
((MultiPopulationSIDiseaseModel) diseaseModel).setRoadNetworkInfectiousProportion(dVal);
break;
default:
break;
} // switch
} // for each Map.entry
for(final Map.Entry<EStructuralFeature, String[]>entry:matrixMap.entrySet()) {
switch(entry.getKey().getFeatureID()) {
case MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__INFECTIOUS_MORTALITY_RATE:
double [] dvals = getDoubleArray(entry.getValue());
DoubleValueList newList = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValueList();
((MultiPopulationSIDiseaseModel) diseaseModel).setInfectiousMortalityRate(newList);
for(double d:dvals) {
DoubleValue dval = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValue();
dval.setValue(d);
((MultiPopulationSIDiseaseModel) diseaseModel).getInfectiousMortalityRate().getValues().add(dval);
}
break;
case MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__RECOVERY_RATE:
dvals = getDoubleArray(entry.getValue());
newList = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValueList();
((MultiPopulationSIDiseaseModel) diseaseModel).setRecoveryRate(newList);
for(double d:dvals) {
DoubleValue dval = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValue();
dval.setValue(d);
((MultiPopulationSIDiseaseModel) diseaseModel).getRecoveryRate().getValues().add(dval);
}
break;
case MultipopulationPackage.MULTI_POPULATION_SIR_DISEASE_MODEL__IMMUNITY_LOSS_RATE:
dvals = getDoubleArray(entry.getValue());
newList = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValueList();
((MultiPopulationSIRDiseaseModel) diseaseModel).setImmunityLossRate(newList);
for(double d:dvals) {
DoubleValue dval = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValue();
dval.setValue(d);
((MultiPopulationSIRDiseaseModel) diseaseModel).getImmunityLossRate().getValues().add(dval);
}
break;
case MultipopulationPackage.MULTI_POPULATION_SEIR_DISEASE_MODEL__INCUBATION_RATE:
dvals = getDoubleArray(entry.getValue());
newList = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValueList();
((MultiPopulationSEIRDiseaseModel) diseaseModel).setIncubationRate(newList);
for(double d:dvals) {
DoubleValue dval = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValue();
dval.setValue(d);
((MultiPopulationSEIRDiseaseModel) diseaseModel).getIncubationRate().getValues().add(dval);
}
break;
case MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__TRANSMISSION_RATE:
dvals = getDoubleArray(entry.getValue());
DoubleValueMatrix newMatrix = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValueMatrix();
((MultiPopulationSIDiseaseModel) diseaseModel).setTransmissionRate(newMatrix);
// ugh
int groups = (int)Math.sqrt((double)dvals.length);
for(int r=0;r<groups;++r) {
DoubleValueList nl = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValueList();
((MultiPopulationSIDiseaseModel) diseaseModel).getTransmissionRate().getValueLists().add(nl);
for(int c=0;c<groups;++c) {
DoubleValue dval = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValue();
dval.setValue(dvals[r*groups+c]);
nl.getValues().add(dval);
}
}
break;
case MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__POPULATION_GROUPS:
String [] svals = entry.getValue();
StringValueList newSList = CommonPackage.eINSTANCE.getCommonFactory().createStringValueList();
((MultiPopulationSIDiseaseModel) diseaseModel).setPopulationGroups(newSList);
for(String s:svals) {
org.eclipse.stem.core.common.StringValue sval = CommonPackage.eINSTANCE.getCommonFactory().createStringValue();
sval.setValue(s);
((MultiPopulationSIDiseaseModel) diseaseModel).getPopulationGroups().getValues().add(sval);
}
break;
}
}
// Let's fill in the identifiers for the various rates to make it easier to edit later in the property editor
if(((MultiPopulationSIDiseaseModel) diseaseModel).getPopulationGroups() != null) {
String []groups = new String[((MultiPopulationSIDiseaseModel) diseaseModel).getPopulationGroups().getValues().size()];
int i=0;
for(org.eclipse.stem.core.common.StringValue sv:((MultiPopulationSIDiseaseModel) diseaseModel).getPopulationGroups().getValues())
groups[i++] = sv.getValue();
i=0;
- for(DoubleValue dv:((MultiPopulationSIDiseaseModel) diseaseModel).getInfectiousMortalityRate().getValues())
- dv.setIdentifier(groups[i++]);
+ DoubleValueList dvl = ((MultiPopulationSIDiseaseModel) diseaseModel).getInfectiousMortalityRate();
+ if(dvl != null)
+ for(DoubleValue dv:dvl.getValues())
+ dv.setIdentifier(groups[i++]);
i=0;
- for(DoubleValue dv:((MultiPopulationSIDiseaseModel) diseaseModel).getRecoveryRate().getValues())
- dv.setIdentifier(groups[i++]);
+ dvl = ((MultiPopulationSIDiseaseModel) diseaseModel).getRecoveryRate();
+ if(dvl != null)
+ for(DoubleValue dv:dvl.getValues())
+ dv.setIdentifier(groups[i++]);
i=0;
- for(DoubleValueList dvl:((MultiPopulationSIDiseaseModel) diseaseModel).getTransmissionRate().getValueLists()) {
- dvl.setIdentifier(groups[i++]);
+ DoubleValueMatrix dvm = ((MultiPopulationSIDiseaseModel) diseaseModel).getTransmissionRate();
+ if(dvm != null)
+ for(DoubleValueList dvl2:dvm.getValueLists()) {
+ dvl2.setIdentifier(groups[i++]);
int j=0;
- for(DoubleValue dv:dvl.getValues())
+ for(DoubleValue dv:dvl2.getValues())
dv.setIdentifier(groups[j++]);
}
if(diseaseModel instanceof MultiPopulationSIRDiseaseModel) {
i=0;
- for(DoubleValue dv:((MultiPopulationSIRDiseaseModel) diseaseModel).getImmunityLossRate().getValues())
- dv.setIdentifier(groups[i++]);
+ dvl = ((MultiPopulationSIRDiseaseModel) diseaseModel).getImmunityLossRate();
+ if(dvl != null)
+ for(DoubleValue dv:dvl.getValues())
+ dv.setIdentifier(groups[i++]);
}
if(diseaseModel instanceof MultiPopulationSEIRDiseaseModel) {
i=0;
- for(DoubleValue dv:((MultiPopulationSEIRDiseaseModel) diseaseModel).getIncubationRate().getValues())
- dv.setIdentifier(groups[i++]);
+ dvl = ((MultiPopulationSEIRDiseaseModel) diseaseModel).getIncubationRate();
+ if(dvl != null)
+ for(DoubleValue dv:dvl.getValues())
+ dv.setIdentifier(groups[i++]);
}
} // has groups
}
private double [] getDoubleArray(String []svals) {
double [] res = new double[svals.length];
for(int i=0;i<res.length;++i) res[i] = Double.parseDouble(svals[i]);
return res;
}
/**
* @see org.eclipse.stem.ui.wizards.StandardDiseaseModelPropertyEditor#validate()
*/
@Override
public boolean validate() {
boolean retValue = super.validate();
// Infectious Mortality Rate
if (retValue) {
// Yes
final Text text = map
.get(MultipopulationPackage.Literals.MULTI_POPULATION_SI_DISEASE_MODEL__RECOVERY_RATE);
if (text != null) {
// Yes
retValue = !text.getText().equals(""); //$NON-NLS-1$
// nothing?
if (!retValue) {
// Yes
errorMessage = DiseaseWizardMessages
.getString("RECOVERY_RATE_INVALID"); //$NON-NLS-1$
} // if
else {
// No
// Is it a valid value?
retValue = isValidValue(text.getText(), 0.0);
if (!retValue) {
// No
errorMessage = MultipopulationDiseaseWizardMessages
.getString("RECOVERY_RATE_INVALID"); //$NON-NLS-1$
} // if
}
} // if
}
if (retValue) {
// Yes
Text text = map
.get(MultipopulationPackage.Literals.MULTI_POPULATION_SI_DISEASE_MODEL__PHYSICALLY_ADJACENT_INFECTIOUS_PROPORTION);
if (text != null) {
// Yes
retValue = !text.getText().equals(""); //$NON-NLS-1$
// nothing?
if (!retValue) {
// Yes
errorMessage = DiseaseWizardMessages
.getString("PHYS_ADJ_INVALID"); //$NON-NLS-1$
} // if
else {
// No
// Is it a valid value?
retValue = isValidValue(text.getText(), 0.0);
if (!retValue) {
// No
errorMessage = MultipopulationDiseaseWizardMessages
.getString("PHYS_ADJ_INVALID"); //$NON-NLS-1$
} // if
}
} // if
}
if (retValue) {
// Yes
Text text = map
.get(MultipopulationPackage.Literals.MULTI_POPULATION_SI_DISEASE_MODEL__ROAD_NETWORK_INFECTIOUS_PROPORTION);
if (text != null) {
// Yes
retValue = !text.getText().equals(""); //$NON-NLS-1$
// nothing?
if (!retValue) {
// Yes
errorMessage = DiseaseWizardMessages
.getString("ROAD_NET_INVALID"); //$NON-NLS-1$
} // if
else {
// No
// Is it a valid value?
retValue = isValidValue(text.getText(), 0.0);
if (!retValue) {
// No
errorMessage = MultipopulationDiseaseWizardMessages
.getString("ROAD_NET_INVALID"); //$NON-NLS-1$
} // if
}
} // if
}
return retValue;
}
/**
* These are overriden by subclass
*/
@Override
public short getColCount(EStructuralFeature feature) {
String [] groups = matrixMap.get(MultipopulationPackage.eINSTANCE.getMultiPopulationSIDiseaseModel_PopulationGroups());
if(groups == null)return 0;
else return (short)groups.length;
}
@Override
public boolean getFixedSize(EStructuralFeature feature) {
if(feature.getFeatureID() == MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__POPULATION_GROUPS)
return false;
return true;
}
@Override
public String[] getRowNames(EStructuralFeature feature) {
String [] groups = matrixMap.get(MultipopulationPackage.eINSTANCE.getMultiPopulationSIDiseaseModel_PopulationGroups());
return groups;
}
@Override
public String[] getColNames(EStructuralFeature feature) {
String [] groups = matrixMap.get(MultipopulationPackage.eINSTANCE.getMultiPopulationSIDiseaseModel_PopulationGroups());
return groups;
}
@Override
public short getRowCount(EStructuralFeature feature) {
String [] groups = matrixMap.get(MultipopulationPackage.eINSTANCE.getMultiPopulationSIDiseaseModel_PopulationGroups());
if(groups == null)return 0;
else return (short)groups.length;
}
/**
* getValidator. Validators
* subclass for more advanced validation (>0 etc.)
* @param feature
* @return
*/
@Override
public MatrixEditorValidator getValidator(EStructuralFeature feature) {
EClassifier type = feature.getEType();
MatrixEditorValidator validator=null;
if(feature.getFeatureID() == MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__TRANSMISSION_RATE ||
feature.getFeatureID() == MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__INFECTIOUS_MORTALITY_RATE ||
feature.getFeatureID() == MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__RECOVERY_RATE)
validator = new MatrixEditorValidator() {
public boolean validateValue(String val) {
if(val == null || val.trim().equals("")) return false;
try {
Double.parseDouble(val.trim());
} catch(NumberFormatException nfe) {
return false;
}
return isValidValue(val, 0.0);
}
};
if(validator == null) validator = super.getValidator(feature);
return validator;
}
} // MultiPopulationDiseaseModelPropertyEditor
| false | true |
public void populate(DiseaseModel diseaseModel) {
super.populate(diseaseModel);
for (final Map.Entry<EStructuralFeature, Text> entry : map.entrySet()) {
double dVal = 0.0;
switch (entry.getKey().getFeatureID()) {
case MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__PHYSICALLY_ADJACENT_INFECTIOUS_PROPORTION:
dVal = (new Double(entry.getValue().getText())).doubleValue();
((MultiPopulationSIDiseaseModel) diseaseModel).setPhysicallyAdjacentInfectiousProportion(dVal);
break;
case MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__ROAD_NETWORK_INFECTIOUS_PROPORTION:
dVal = (new Double(entry.getValue().getText())).doubleValue();
((MultiPopulationSIDiseaseModel) diseaseModel).setRoadNetworkInfectiousProportion(dVal);
break;
default:
break;
} // switch
} // for each Map.entry
for(final Map.Entry<EStructuralFeature, String[]>entry:matrixMap.entrySet()) {
switch(entry.getKey().getFeatureID()) {
case MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__INFECTIOUS_MORTALITY_RATE:
double [] dvals = getDoubleArray(entry.getValue());
DoubleValueList newList = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValueList();
((MultiPopulationSIDiseaseModel) diseaseModel).setInfectiousMortalityRate(newList);
for(double d:dvals) {
DoubleValue dval = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValue();
dval.setValue(d);
((MultiPopulationSIDiseaseModel) diseaseModel).getInfectiousMortalityRate().getValues().add(dval);
}
break;
case MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__RECOVERY_RATE:
dvals = getDoubleArray(entry.getValue());
newList = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValueList();
((MultiPopulationSIDiseaseModel) diseaseModel).setRecoveryRate(newList);
for(double d:dvals) {
DoubleValue dval = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValue();
dval.setValue(d);
((MultiPopulationSIDiseaseModel) diseaseModel).getRecoveryRate().getValues().add(dval);
}
break;
case MultipopulationPackage.MULTI_POPULATION_SIR_DISEASE_MODEL__IMMUNITY_LOSS_RATE:
dvals = getDoubleArray(entry.getValue());
newList = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValueList();
((MultiPopulationSIRDiseaseModel) diseaseModel).setImmunityLossRate(newList);
for(double d:dvals) {
DoubleValue dval = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValue();
dval.setValue(d);
((MultiPopulationSIRDiseaseModel) diseaseModel).getImmunityLossRate().getValues().add(dval);
}
break;
case MultipopulationPackage.MULTI_POPULATION_SEIR_DISEASE_MODEL__INCUBATION_RATE:
dvals = getDoubleArray(entry.getValue());
newList = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValueList();
((MultiPopulationSEIRDiseaseModel) diseaseModel).setIncubationRate(newList);
for(double d:dvals) {
DoubleValue dval = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValue();
dval.setValue(d);
((MultiPopulationSEIRDiseaseModel) diseaseModel).getIncubationRate().getValues().add(dval);
}
break;
case MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__TRANSMISSION_RATE:
dvals = getDoubleArray(entry.getValue());
DoubleValueMatrix newMatrix = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValueMatrix();
((MultiPopulationSIDiseaseModel) diseaseModel).setTransmissionRate(newMatrix);
// ugh
int groups = (int)Math.sqrt((double)dvals.length);
for(int r=0;r<groups;++r) {
DoubleValueList nl = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValueList();
((MultiPopulationSIDiseaseModel) diseaseModel).getTransmissionRate().getValueLists().add(nl);
for(int c=0;c<groups;++c) {
DoubleValue dval = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValue();
dval.setValue(dvals[r*groups+c]);
nl.getValues().add(dval);
}
}
break;
case MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__POPULATION_GROUPS:
String [] svals = entry.getValue();
StringValueList newSList = CommonPackage.eINSTANCE.getCommonFactory().createStringValueList();
((MultiPopulationSIDiseaseModel) diseaseModel).setPopulationGroups(newSList);
for(String s:svals) {
org.eclipse.stem.core.common.StringValue sval = CommonPackage.eINSTANCE.getCommonFactory().createStringValue();
sval.setValue(s);
((MultiPopulationSIDiseaseModel) diseaseModel).getPopulationGroups().getValues().add(sval);
}
break;
}
}
// Let's fill in the identifiers for the various rates to make it easier to edit later in the property editor
if(((MultiPopulationSIDiseaseModel) diseaseModel).getPopulationGroups() != null) {
String []groups = new String[((MultiPopulationSIDiseaseModel) diseaseModel).getPopulationGroups().getValues().size()];
int i=0;
for(org.eclipse.stem.core.common.StringValue sv:((MultiPopulationSIDiseaseModel) diseaseModel).getPopulationGroups().getValues())
groups[i++] = sv.getValue();
i=0;
for(DoubleValue dv:((MultiPopulationSIDiseaseModel) diseaseModel).getInfectiousMortalityRate().getValues())
dv.setIdentifier(groups[i++]);
i=0;
for(DoubleValue dv:((MultiPopulationSIDiseaseModel) diseaseModel).getRecoveryRate().getValues())
dv.setIdentifier(groups[i++]);
i=0;
for(DoubleValueList dvl:((MultiPopulationSIDiseaseModel) diseaseModel).getTransmissionRate().getValueLists()) {
dvl.setIdentifier(groups[i++]);
int j=0;
for(DoubleValue dv:dvl.getValues())
dv.setIdentifier(groups[j++]);
}
if(diseaseModel instanceof MultiPopulationSIRDiseaseModel) {
i=0;
for(DoubleValue dv:((MultiPopulationSIRDiseaseModel) diseaseModel).getImmunityLossRate().getValues())
dv.setIdentifier(groups[i++]);
}
if(diseaseModel instanceof MultiPopulationSEIRDiseaseModel) {
i=0;
for(DoubleValue dv:((MultiPopulationSEIRDiseaseModel) diseaseModel).getIncubationRate().getValues())
dv.setIdentifier(groups[i++]);
}
} // has groups
}
|
public void populate(DiseaseModel diseaseModel) {
super.populate(diseaseModel);
for (final Map.Entry<EStructuralFeature, Text> entry : map.entrySet()) {
double dVal = 0.0;
switch (entry.getKey().getFeatureID()) {
case MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__PHYSICALLY_ADJACENT_INFECTIOUS_PROPORTION:
dVal = (new Double(entry.getValue().getText())).doubleValue();
((MultiPopulationSIDiseaseModel) diseaseModel).setPhysicallyAdjacentInfectiousProportion(dVal);
break;
case MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__ROAD_NETWORK_INFECTIOUS_PROPORTION:
dVal = (new Double(entry.getValue().getText())).doubleValue();
((MultiPopulationSIDiseaseModel) diseaseModel).setRoadNetworkInfectiousProportion(dVal);
break;
default:
break;
} // switch
} // for each Map.entry
for(final Map.Entry<EStructuralFeature, String[]>entry:matrixMap.entrySet()) {
switch(entry.getKey().getFeatureID()) {
case MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__INFECTIOUS_MORTALITY_RATE:
double [] dvals = getDoubleArray(entry.getValue());
DoubleValueList newList = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValueList();
((MultiPopulationSIDiseaseModel) diseaseModel).setInfectiousMortalityRate(newList);
for(double d:dvals) {
DoubleValue dval = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValue();
dval.setValue(d);
((MultiPopulationSIDiseaseModel) diseaseModel).getInfectiousMortalityRate().getValues().add(dval);
}
break;
case MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__RECOVERY_RATE:
dvals = getDoubleArray(entry.getValue());
newList = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValueList();
((MultiPopulationSIDiseaseModel) diseaseModel).setRecoveryRate(newList);
for(double d:dvals) {
DoubleValue dval = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValue();
dval.setValue(d);
((MultiPopulationSIDiseaseModel) diseaseModel).getRecoveryRate().getValues().add(dval);
}
break;
case MultipopulationPackage.MULTI_POPULATION_SIR_DISEASE_MODEL__IMMUNITY_LOSS_RATE:
dvals = getDoubleArray(entry.getValue());
newList = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValueList();
((MultiPopulationSIRDiseaseModel) diseaseModel).setImmunityLossRate(newList);
for(double d:dvals) {
DoubleValue dval = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValue();
dval.setValue(d);
((MultiPopulationSIRDiseaseModel) diseaseModel).getImmunityLossRate().getValues().add(dval);
}
break;
case MultipopulationPackage.MULTI_POPULATION_SEIR_DISEASE_MODEL__INCUBATION_RATE:
dvals = getDoubleArray(entry.getValue());
newList = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValueList();
((MultiPopulationSEIRDiseaseModel) diseaseModel).setIncubationRate(newList);
for(double d:dvals) {
DoubleValue dval = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValue();
dval.setValue(d);
((MultiPopulationSEIRDiseaseModel) diseaseModel).getIncubationRate().getValues().add(dval);
}
break;
case MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__TRANSMISSION_RATE:
dvals = getDoubleArray(entry.getValue());
DoubleValueMatrix newMatrix = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValueMatrix();
((MultiPopulationSIDiseaseModel) diseaseModel).setTransmissionRate(newMatrix);
// ugh
int groups = (int)Math.sqrt((double)dvals.length);
for(int r=0;r<groups;++r) {
DoubleValueList nl = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValueList();
((MultiPopulationSIDiseaseModel) diseaseModel).getTransmissionRate().getValueLists().add(nl);
for(int c=0;c<groups;++c) {
DoubleValue dval = CommonPackage.eINSTANCE.getCommonFactory().createDoubleValue();
dval.setValue(dvals[r*groups+c]);
nl.getValues().add(dval);
}
}
break;
case MultipopulationPackage.MULTI_POPULATION_SI_DISEASE_MODEL__POPULATION_GROUPS:
String [] svals = entry.getValue();
StringValueList newSList = CommonPackage.eINSTANCE.getCommonFactory().createStringValueList();
((MultiPopulationSIDiseaseModel) diseaseModel).setPopulationGroups(newSList);
for(String s:svals) {
org.eclipse.stem.core.common.StringValue sval = CommonPackage.eINSTANCE.getCommonFactory().createStringValue();
sval.setValue(s);
((MultiPopulationSIDiseaseModel) diseaseModel).getPopulationGroups().getValues().add(sval);
}
break;
}
}
// Let's fill in the identifiers for the various rates to make it easier to edit later in the property editor
if(((MultiPopulationSIDiseaseModel) diseaseModel).getPopulationGroups() != null) {
String []groups = new String[((MultiPopulationSIDiseaseModel) diseaseModel).getPopulationGroups().getValues().size()];
int i=0;
for(org.eclipse.stem.core.common.StringValue sv:((MultiPopulationSIDiseaseModel) diseaseModel).getPopulationGroups().getValues())
groups[i++] = sv.getValue();
i=0;
DoubleValueList dvl = ((MultiPopulationSIDiseaseModel) diseaseModel).getInfectiousMortalityRate();
if(dvl != null)
for(DoubleValue dv:dvl.getValues())
dv.setIdentifier(groups[i++]);
i=0;
dvl = ((MultiPopulationSIDiseaseModel) diseaseModel).getRecoveryRate();
if(dvl != null)
for(DoubleValue dv:dvl.getValues())
dv.setIdentifier(groups[i++]);
i=0;
DoubleValueMatrix dvm = ((MultiPopulationSIDiseaseModel) diseaseModel).getTransmissionRate();
if(dvm != null)
for(DoubleValueList dvl2:dvm.getValueLists()) {
dvl2.setIdentifier(groups[i++]);
int j=0;
for(DoubleValue dv:dvl2.getValues())
dv.setIdentifier(groups[j++]);
}
if(diseaseModel instanceof MultiPopulationSIRDiseaseModel) {
i=0;
dvl = ((MultiPopulationSIRDiseaseModel) diseaseModel).getImmunityLossRate();
if(dvl != null)
for(DoubleValue dv:dvl.getValues())
dv.setIdentifier(groups[i++]);
}
if(diseaseModel instanceof MultiPopulationSEIRDiseaseModel) {
i=0;
dvl = ((MultiPopulationSEIRDiseaseModel) diseaseModel).getIncubationRate();
if(dvl != null)
for(DoubleValue dv:dvl.getValues())
dv.setIdentifier(groups[i++]);
}
} // has groups
}
|
diff --git a/src/com/codisimus/plugins/chestlock/listeners/BlockEventListener.java b/src/com/codisimus/plugins/chestlock/listeners/BlockEventListener.java
index bc8fd6b..c77ba7e 100644
--- a/src/com/codisimus/plugins/chestlock/listeners/BlockEventListener.java
+++ b/src/com/codisimus/plugins/chestlock/listeners/BlockEventListener.java
@@ -1,80 +1,79 @@
package com.codisimus.plugins.chestlock.listeners;
import com.codisimus.plugins.chestlock.ChestLock;
import com.codisimus.plugins.chestlock.LockedDoor;
import com.codisimus.plugins.chestlock.Safe;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockListener;
import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.material.Door;
/**
* Listens for griefing events
*
* @author Codisimus
*/
public class BlockEventListener extends BlockListener {
/**
* Blocks Players from opening locked doors with redstone
*
* @param event The BlockRedstoneEvent that occurred
*/
@Override
public void onBlockRedstoneChange(BlockRedstoneEvent event) {
//Return if the Block is not a LockedDoor
LockedDoor lockedDoor = ChestLock.findDoor(event.getBlock());
if (lockedDoor == null)
return;
//Return if the key is unlockable
if (lockedDoor.key == 0)
return;
//Allow Redstone to close a Door but not open it
if (!((Door)lockedDoor.block.getState().getData()).isOpen())
event.setNewCurrent(event.getOldCurrent());
}
/**
* Prevents Players from breaking owned Blocks
*
* @param event The BlockBreakEvent that occurred
*/
@Override
public void onBlockBreak (BlockBreakEvent event) {
Block block = event.getBlock();
Player player = event.getPlayer();
//Check if the Block is a LockedDoor
LockedDoor door = ChestLock.findDoor(block);
if (door != null) {
//Cancel the event if the Player is not the Owner of the LockedDoor and does not have the admin node
if (!player.getName().equals(door.owner) && !ChestLock.hasPermission(player, "admin")) {
event.setCancelled(true);
return;
}
//Delete the LockedDoor from the saved data
ChestLock.doors.remove(door);
return;
}
//Return if the Block is not a Safe
Safe safe = ChestLock.findSafe(block);
if (safe == null)
return;
//Cancel the event if the Player is not the Owner of the Safe
- if (safe.isOwner(player)) {
+ if (!safe.isOwner(player)) {
event.setCancelled(true);
return;
}
//Delete the Safe from the saved data
ChestLock.removeSafe(safe);
- return;
}
}
| false | true |
public void onBlockBreak (BlockBreakEvent event) {
Block block = event.getBlock();
Player player = event.getPlayer();
//Check if the Block is a LockedDoor
LockedDoor door = ChestLock.findDoor(block);
if (door != null) {
//Cancel the event if the Player is not the Owner of the LockedDoor and does not have the admin node
if (!player.getName().equals(door.owner) && !ChestLock.hasPermission(player, "admin")) {
event.setCancelled(true);
return;
}
//Delete the LockedDoor from the saved data
ChestLock.doors.remove(door);
return;
}
//Return if the Block is not a Safe
Safe safe = ChestLock.findSafe(block);
if (safe == null)
return;
//Cancel the event if the Player is not the Owner of the Safe
if (safe.isOwner(player)) {
event.setCancelled(true);
return;
}
//Delete the Safe from the saved data
ChestLock.removeSafe(safe);
return;
}
|
public void onBlockBreak (BlockBreakEvent event) {
Block block = event.getBlock();
Player player = event.getPlayer();
//Check if the Block is a LockedDoor
LockedDoor door = ChestLock.findDoor(block);
if (door != null) {
//Cancel the event if the Player is not the Owner of the LockedDoor and does not have the admin node
if (!player.getName().equals(door.owner) && !ChestLock.hasPermission(player, "admin")) {
event.setCancelled(true);
return;
}
//Delete the LockedDoor from the saved data
ChestLock.doors.remove(door);
return;
}
//Return if the Block is not a Safe
Safe safe = ChestLock.findSafe(block);
if (safe == null)
return;
//Cancel the event if the Player is not the Owner of the Safe
if (!safe.isOwner(player)) {
event.setCancelled(true);
return;
}
//Delete the Safe from the saved data
ChestLock.removeSafe(safe);
}
|
diff --git a/test/assignment2/Test3.java b/test/assignment2/Test3.java
index 29fce97..7b6badd 100644
--- a/test/assignment2/Test3.java
+++ b/test/assignment2/Test3.java
@@ -1,103 +1,103 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package assignment2;
import badm.BridgeHelper;
import badm.Budget;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.*;
import org.workplicity.task.NetTask;
import org.workplicity.util.Helper;
import org.workplicity.worklet.WorkletContext;
/**
*
* @author idontknow5691
*/
public class Test3 {
private static WorkletContext context = WorkletContext.getInstance();
private static Budget budget;
private static Integer id;
public Test3() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void login(){
try {
// Set the store name since the default may be be not ours
NetTask.setStoreName("badm");
NetTask.setUrlBase("http://localhost:8080/netprevayle/task");
// Attempt the login
if(!Helper.login("admin", "gazelle", context))
fail("login failed");
} catch (Exception e) {
fail("failed with exception: " + e);
}
}
@Test
public void createBudget(){
try{
budget = (Budget) BridgeHelper.getBudgetFactory().create();
budget.setDescription("My Budget");
}catch(Exception e){
fail("cannot create budget" + e);
}
}
@Test
public void syncBudget(){
try{
budget.setDescription("I'M A BUDGET!!!!!!!!");
budget.commit();
}catch(Exception e){
fail("cannot sync budget" + e);
}
}
@Test
public void queryBudget(){
try{
budget.setDescription("I'M A BUDGET!!!!!!!!");
budget.setTotal(1337);
- id = budget.getId();
budget.commit();
+ id = budget.getId();
}catch(Exception e){
fail("cannot sync budget" + e);
}
try{
Budget queriedBudget = Budget.find(id);
assertEquals(queriedBudget.getDescription(), "I'M A BUDGET!!!!!!!!");
System.out.println(queriedBudget.getDescription());
}catch(Exception e){
fail("Could not fetch the budget"+e);
}
}
}
| false | true |
public void queryBudget(){
try{
budget.setDescription("I'M A BUDGET!!!!!!!!");
budget.setTotal(1337);
id = budget.getId();
budget.commit();
}catch(Exception e){
fail("cannot sync budget" + e);
}
try{
Budget queriedBudget = Budget.find(id);
assertEquals(queriedBudget.getDescription(), "I'M A BUDGET!!!!!!!!");
System.out.println(queriedBudget.getDescription());
}catch(Exception e){
fail("Could not fetch the budget"+e);
}
}
|
public void queryBudget(){
try{
budget.setDescription("I'M A BUDGET!!!!!!!!");
budget.setTotal(1337);
budget.commit();
id = budget.getId();
}catch(Exception e){
fail("cannot sync budget" + e);
}
try{
Budget queriedBudget = Budget.find(id);
assertEquals(queriedBudget.getDescription(), "I'M A BUDGET!!!!!!!!");
System.out.println(queriedBudget.getDescription());
}catch(Exception e){
fail("Could not fetch the budget"+e);
}
}
|
diff --git a/src/com/android/calendar/LaunchActivity.java b/src/com/android/calendar/LaunchActivity.java
index a83730ca..be8b287d 100644
--- a/src/com/android/calendar/LaunchActivity.java
+++ b/src/com/android/calendar/LaunchActivity.java
@@ -1,109 +1,110 @@
/*
* Copyright (C) 2007 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.calendar;
import com.google.android.googlelogin.GoogleLoginServiceConstants;
import android.accounts.AccountManager;
import android.accounts.AuthenticatorException;
import android.accounts.Future2;
import android.accounts.Future2Callback;
import android.accounts.OperationCanceledException;
import android.accounts.Account;
import android.accounts.Constants;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Gmail;
import java.io.IOException;
public class LaunchActivity extends Activity {
static final String KEY_DETAIL_VIEW = "DETAIL_VIEW";
private Bundle mExtras;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
mExtras = getIntent().getExtras();
// Our UI is not something intended for the user to see. We just
// stick around until we can figure out what to do next based on
// the current state of the system.
- setVisible(false);
+ // TODO: Removed until framework is fixed in b/2008662
+ // setVisible(false);
// Only try looking for an account if this is the first launch.
if (icicle == null) {
// This will request a Gmail account and if none are present, it will
// invoke SetupWizard to login or create one. The result is returned
// via the Future2Callback.
Bundle bundle = new Bundle();
bundle.putCharSequence("optional_message", getText(R.string.calendar_plug));
AccountManager.get(this).getAuthTokenByFeatures(
GoogleLoginServiceConstants.ACCOUNT_TYPE, Gmail.GMAIL_AUTH_SERVICE,
new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE}, this,
bundle, null /* loginOptions */, new Future2Callback() {
public void run(Future2 future) {
try {
Bundle result = future.getResult();
onAccountsLoaded(new Account(
result.getString(GoogleLoginServiceConstants.AUTH_ACCOUNT_KEY),
result.getString(Constants.ACCOUNT_TYPE_KEY)));
} catch (OperationCanceledException e) {
finish();
} catch (IOException e) {
finish();
} catch (AuthenticatorException e) {
finish();
}
}
}, null /* handler */);
}
}
private void onAccountsLoaded(Account account) {
// Get the data for from this intent, if any
Intent myIntent = getIntent();
Uri myData = myIntent.getData();
// Set up the intent for the start activity
Intent intent = new Intent();
if (myData != null) {
intent.setData(myData);
}
String defaultViewKey = CalendarPreferenceActivity.KEY_START_VIEW;
if (mExtras != null) {
intent.putExtras(mExtras);
if (mExtras.getBoolean(KEY_DETAIL_VIEW, false)) {
defaultViewKey = CalendarPreferenceActivity.KEY_DETAILED_VIEW;
}
}
intent.putExtras(myIntent);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String startActivity = prefs.getString(defaultViewKey,
CalendarPreferenceActivity.DEFAULT_START_VIEW);
intent.setClassName(this, startActivity);
startActivity(intent);
finish();
}
}
| true | true |
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
mExtras = getIntent().getExtras();
// Our UI is not something intended for the user to see. We just
// stick around until we can figure out what to do next based on
// the current state of the system.
setVisible(false);
// Only try looking for an account if this is the first launch.
if (icicle == null) {
// This will request a Gmail account and if none are present, it will
// invoke SetupWizard to login or create one. The result is returned
// via the Future2Callback.
Bundle bundle = new Bundle();
bundle.putCharSequence("optional_message", getText(R.string.calendar_plug));
AccountManager.get(this).getAuthTokenByFeatures(
GoogleLoginServiceConstants.ACCOUNT_TYPE, Gmail.GMAIL_AUTH_SERVICE,
new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE}, this,
bundle, null /* loginOptions */, new Future2Callback() {
public void run(Future2 future) {
try {
Bundle result = future.getResult();
onAccountsLoaded(new Account(
result.getString(GoogleLoginServiceConstants.AUTH_ACCOUNT_KEY),
result.getString(Constants.ACCOUNT_TYPE_KEY)));
} catch (OperationCanceledException e) {
finish();
} catch (IOException e) {
finish();
} catch (AuthenticatorException e) {
finish();
}
}
}, null /* handler */);
}
}
|
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
mExtras = getIntent().getExtras();
// Our UI is not something intended for the user to see. We just
// stick around until we can figure out what to do next based on
// the current state of the system.
// TODO: Removed until framework is fixed in b/2008662
// setVisible(false);
// Only try looking for an account if this is the first launch.
if (icicle == null) {
// This will request a Gmail account and if none are present, it will
// invoke SetupWizard to login or create one. The result is returned
// via the Future2Callback.
Bundle bundle = new Bundle();
bundle.putCharSequence("optional_message", getText(R.string.calendar_plug));
AccountManager.get(this).getAuthTokenByFeatures(
GoogleLoginServiceConstants.ACCOUNT_TYPE, Gmail.GMAIL_AUTH_SERVICE,
new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE}, this,
bundle, null /* loginOptions */, new Future2Callback() {
public void run(Future2 future) {
try {
Bundle result = future.getResult();
onAccountsLoaded(new Account(
result.getString(GoogleLoginServiceConstants.AUTH_ACCOUNT_KEY),
result.getString(Constants.ACCOUNT_TYPE_KEY)));
} catch (OperationCanceledException e) {
finish();
} catch (IOException e) {
finish();
} catch (AuthenticatorException e) {
finish();
}
}
}, null /* handler */);
}
}
|
diff --git a/bundles/org.eclipse.equinox.metatype/src/org/eclipse/equinox/metatype/MetaTypeProviderImpl.java b/bundles/org.eclipse.equinox.metatype/src/org/eclipse/equinox/metatype/MetaTypeProviderImpl.java
index 45a43435..fd3ebdeb 100644
--- a/bundles/org.eclipse.equinox.metatype/src/org/eclipse/equinox/metatype/MetaTypeProviderImpl.java
+++ b/bundles/org.eclipse.equinox.metatype/src/org/eclipse/equinox/metatype/MetaTypeProviderImpl.java
@@ -1,237 +1,237 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.metatype;
import java.io.IOException;
import java.util.*;
import javax.xml.parsers.SAXParserFactory;
import org.eclipse.osgi.util.NLS;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.service.metatype.*;
/**
* Implementation of MetaTypeProvider
*/
public class MetaTypeProviderImpl implements MetaTypeProvider {
public static final String METADATA_NOT_FOUND = "METADATA_NOT_FOUND"; //$NON-NLS-1$
public static final String OCD_ID_NOT_FOUND = "OCD_ID_NOT_FOUND"; //$NON-NLS-1$
public static final String ASK_INVALID_LOCALE = "ASK_INVALID_LOCALE"; //$NON-NLS-1$
public static final String META_FILE_EXT = ".XML"; //$NON-NLS-1$
public static final String RESOURCE_FILE_CONN = "_"; //$NON-NLS-1$
public static final String RESOURCE_FILE_EXT = ".properties"; //$NON-NLS-1$
public static final char DIRECTORY_SEP = '/';
Bundle _bundle;
Hashtable _allPidOCDs = new Hashtable(7);
Hashtable _allFPidOCDs = new Hashtable(7);
String[] _locales;
boolean _isThereMeta = false;
/**
* Constructor of class MetaTypeProviderImpl.
*/
MetaTypeProviderImpl(Bundle bundle, SAXParserFactory parserFactory) throws IOException {
this._bundle = bundle;
// read all bundle's metadata files and build internal data structures
_isThereMeta = readMetaFiles(bundle, parserFactory);
if (!_isThereMeta) {
Logging.log(Logging.WARN, NLS.bind(MetaTypeMsg.METADATA_NOT_FOUND, new Long(bundle.getBundleId()), bundle.getSymbolicName()));
}
}
/**
* This method should do the following:
* <p> - Obtain a SAX parser from the XML Parser Service:
* <p>
*
* <pre> </pre>
*
* The parser may be SAX 1 (eXML) or SAX 2 (XML4J). It should attempt to use
* a SAX2 parser by instantiating an XMLReader and extending DefaultHandler
* BUT if that fails it should fall back to instantiating a SAX1 Parser and
* extending HandlerBase.
* <p> - Pass the parser the URL for the bundle's METADATA.XML file
* <p> - Handle the callbacks from the parser and build the appropriate
* MetaType objects - ObjectClassDefinitions & AttributeDefinitions
*
* @param bundle The bundle object for which the metadata should be read
* @param parserFactory The bundle object for which the metadata should be
* read
* @return void
* @throws IOException If there are errors accessing the metadata.xml file
*/
private boolean readMetaFiles(Bundle bundle, SAXParserFactory parserFactory) throws IOException {
boolean isThereMetaHere = false;
Enumeration allFileKeys = FragmentUtils.findEntryPaths(bundle, MetaTypeService.METATYPE_DOCUMENTS_LOCATION);
if (allFileKeys == null)
return isThereMetaHere;
while (allFileKeys.hasMoreElements()) {
boolean _isMetaDataFile;
String fileName = (String) allFileKeys.nextElement();
Vector allOCDsInFile = null;
java.net.URL[] urls = FragmentUtils.findEntries(bundle, fileName);
if (urls != null) {
for (int i = 0; i < urls.length; i++) {
try {
// Assume all XML files are what we want by default.
_isMetaDataFile = true;
DataParser parser = new DataParser(bundle, urls[i], parserFactory);
allOCDsInFile = parser.doParse();
if (allOCDsInFile == null) {
_isMetaDataFile = false;
}
} catch (Exception e) {
// Ok, looks like it is not what we want.
_isMetaDataFile = false;
}
if ((_isMetaDataFile) && (allOCDsInFile != null)) {
// We got some OCDs now.
for (int j = 0; j < allOCDsInFile.size(); j++) {
ObjectClassDefinitionImpl ocd = (ObjectClassDefinitionImpl) allOCDsInFile.elementAt(j);
if (ocd.getType() == ObjectClassDefinitionImpl.PID) {
isThereMetaHere = true;
- _allPidOCDs.put(ocd.getID(), ocd);
+ _allPidOCDs.put(ocd.getPID(), ocd);
} else {
isThereMetaHere = true;
- _allFPidOCDs.put(ocd.getID(), ocd);
+ _allFPidOCDs.put(ocd.getPID(), ocd);
}
} // End of for
}
}
} // End of if(urls!=null)
} // End of while
return isThereMetaHere;
}
/*
* (non-Javadoc)
*
* @see org.osgi.service.metatype.MetaTypeProvider#getObjectClassDefinition(java.lang.String,
* java.lang.String)
*/
public ObjectClassDefinition getObjectClassDefinition(String pid, String locale) {
if (isInvalidLocale(locale)) {
throw new IllegalArgumentException(NLS.bind(MetaTypeMsg.ASK_INVALID_LOCALE, pid, locale));
}
ObjectClassDefinitionImpl ocd;
if (_allPidOCDs.containsKey(pid)) {
ocd = (ObjectClassDefinitionImpl) ((ObjectClassDefinitionImpl) _allPidOCDs.get(pid)).clone();
ocd.setResourceBundle(locale, _bundle);
return ocd;
} else if (_allFPidOCDs.containsKey(pid)) {
ocd = (ObjectClassDefinitionImpl) ((ObjectClassDefinitionImpl) _allFPidOCDs.get(pid)).clone();
ocd.setResourceBundle(locale, _bundle);
return ocd;
} else {
throw new IllegalArgumentException(NLS.bind(MetaTypeMsg.OCD_ID_NOT_FOUND, pid));
}
}
/**
* Internal Method - Check if the locale is invalid.
*/
public boolean isInvalidLocale(String locale) {
// Just a simple and quick check here.
if (locale == null || locale.length() == 0)
return false;
int idx_first = locale.indexOf(ObjectClassDefinitionImpl.LOCALE_SEP);
int idx_second = locale.lastIndexOf(ObjectClassDefinitionImpl.LOCALE_SEP);
if (idx_first == -1 && locale.length() == 2)
// It is format of only language.
return false;
if ((idx_first == 2) && (idx_second == 5 || idx_second == 2))
// It is format of language + "_" + country [ + "_" + variation ].
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see org.osgi.service.metatype.MetaTypeProvider#getLocales()
*/
public synchronized String[] getLocales() {
if (_locales != null)
return checkForDefault(_locales);
Vector localizationFiles = new Vector(7);
// get all the localization resources for PIDS
Enumeration ocds = _allPidOCDs.elements();
while (ocds.hasMoreElements()) {
ObjectClassDefinitionImpl ocd = (ObjectClassDefinitionImpl) ocds.nextElement();
if (ocd._localization != null && !localizationFiles.contains(ocd._localization))
localizationFiles.add(ocd._localization);
}
// get all the localization resources for FPIDS
ocds = _allFPidOCDs.elements();
while (ocds.hasMoreElements()) {
ObjectClassDefinitionImpl ocd = (ObjectClassDefinitionImpl) ocds.nextElement();
if (ocd._localization != null && !localizationFiles.contains(ocd._localization))
localizationFiles.add(ocd._localization);
}
if (localizationFiles.size() == 0)
localizationFiles.add(Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME);
Vector locales = new Vector(7);
Enumeration eLocalizationFiles = localizationFiles.elements();
while (eLocalizationFiles.hasMoreElements()) {
String localizationFile = (String) eLocalizationFiles.nextElement();
int iSlash = localizationFile.lastIndexOf(DIRECTORY_SEP);
String baseDir;
String baseFileName;
if (iSlash < 0) {
baseDir = ""; //$NON-NLS-1$
} else {
baseDir = localizationFile.substring(0, iSlash);
}
baseFileName = localizationFile + RESOURCE_FILE_CONN;
Enumeration resources = FragmentUtils.findEntryPaths(this._bundle, baseDir);
if (resources != null) {
while (resources.hasMoreElements()) {
String resource = (String) resources.nextElement();
if (resource.startsWith(baseFileName) && resource.toLowerCase().endsWith(RESOURCE_FILE_EXT))
locales.add(resource.substring(baseFileName.length(), resource.length() - RESOURCE_FILE_EXT.length()));
}
}
}
_locales = (String[]) locales.toArray(new String[locales.size()]);
return checkForDefault(_locales);
}
/**
* Internal Method - checkForDefault
*/
private String[] checkForDefault(String[] locales) {
if (locales == null || locales.length == 0 || (locales.length == 1 && Locale.getDefault().toString().equals(locales[0])))
return null;
return locales;
}
}
| false | true |
private boolean readMetaFiles(Bundle bundle, SAXParserFactory parserFactory) throws IOException {
boolean isThereMetaHere = false;
Enumeration allFileKeys = FragmentUtils.findEntryPaths(bundle, MetaTypeService.METATYPE_DOCUMENTS_LOCATION);
if (allFileKeys == null)
return isThereMetaHere;
while (allFileKeys.hasMoreElements()) {
boolean _isMetaDataFile;
String fileName = (String) allFileKeys.nextElement();
Vector allOCDsInFile = null;
java.net.URL[] urls = FragmentUtils.findEntries(bundle, fileName);
if (urls != null) {
for (int i = 0; i < urls.length; i++) {
try {
// Assume all XML files are what we want by default.
_isMetaDataFile = true;
DataParser parser = new DataParser(bundle, urls[i], parserFactory);
allOCDsInFile = parser.doParse();
if (allOCDsInFile == null) {
_isMetaDataFile = false;
}
} catch (Exception e) {
// Ok, looks like it is not what we want.
_isMetaDataFile = false;
}
if ((_isMetaDataFile) && (allOCDsInFile != null)) {
// We got some OCDs now.
for (int j = 0; j < allOCDsInFile.size(); j++) {
ObjectClassDefinitionImpl ocd = (ObjectClassDefinitionImpl) allOCDsInFile.elementAt(j);
if (ocd.getType() == ObjectClassDefinitionImpl.PID) {
isThereMetaHere = true;
_allPidOCDs.put(ocd.getID(), ocd);
} else {
isThereMetaHere = true;
_allFPidOCDs.put(ocd.getID(), ocd);
}
} // End of for
}
}
} // End of if(urls!=null)
} // End of while
return isThereMetaHere;
}
|
private boolean readMetaFiles(Bundle bundle, SAXParserFactory parserFactory) throws IOException {
boolean isThereMetaHere = false;
Enumeration allFileKeys = FragmentUtils.findEntryPaths(bundle, MetaTypeService.METATYPE_DOCUMENTS_LOCATION);
if (allFileKeys == null)
return isThereMetaHere;
while (allFileKeys.hasMoreElements()) {
boolean _isMetaDataFile;
String fileName = (String) allFileKeys.nextElement();
Vector allOCDsInFile = null;
java.net.URL[] urls = FragmentUtils.findEntries(bundle, fileName);
if (urls != null) {
for (int i = 0; i < urls.length; i++) {
try {
// Assume all XML files are what we want by default.
_isMetaDataFile = true;
DataParser parser = new DataParser(bundle, urls[i], parserFactory);
allOCDsInFile = parser.doParse();
if (allOCDsInFile == null) {
_isMetaDataFile = false;
}
} catch (Exception e) {
// Ok, looks like it is not what we want.
_isMetaDataFile = false;
}
if ((_isMetaDataFile) && (allOCDsInFile != null)) {
// We got some OCDs now.
for (int j = 0; j < allOCDsInFile.size(); j++) {
ObjectClassDefinitionImpl ocd = (ObjectClassDefinitionImpl) allOCDsInFile.elementAt(j);
if (ocd.getType() == ObjectClassDefinitionImpl.PID) {
isThereMetaHere = true;
_allPidOCDs.put(ocd.getPID(), ocd);
} else {
isThereMetaHere = true;
_allFPidOCDs.put(ocd.getPID(), ocd);
}
} // End of for
}
}
} // End of if(urls!=null)
} // End of while
return isThereMetaHere;
}
|
diff --git a/src/uk/org/ponder/rsf/flow/ARIProcessor.java b/src/uk/org/ponder/rsf/flow/ARIProcessor.java
index 1b77425..f9e64f3 100644
--- a/src/uk/org/ponder/rsf/flow/ARIProcessor.java
+++ b/src/uk/org/ponder/rsf/flow/ARIProcessor.java
@@ -1,56 +1,56 @@
/*
* Created on 5 Feb 2007
*/
package uk.org.ponder.rsf.flow;
import java.util.ArrayList;
import java.util.List;
import uk.org.ponder.rsf.view.MappingViewResolver;
import uk.org.ponder.rsf.viewstate.ViewParameters;
/** Coordinates discovery of other ActionResultInterceptors from round the
* context. A particular function is to locate "local ARIs" that are registered
* as ViewComponentProducers just for the current view.
* @author Antranig Basman ([email protected])
*
*/
public class ARIProcessor implements ActionResultInterceptor {
private List interceptors;
private MappingViewResolver mappingViewResolver;
public void setInterceptors(List interceptors) {
this.interceptors = interceptors;
}
public void setMappingViewResolver(MappingViewResolver mappingViewResolver) {
this.mappingViewResolver = mappingViewResolver;
}
public void interceptActionResult(ARIResult ariresult, ViewParameters incoming,
Object result) {
if (interceptors == null) {
interceptors = new ArrayList();
}
ArrayList requestinterceptors = new ArrayList(interceptors);
accreteViewARIs(requestinterceptors, incoming);
for (int i = 0; i < requestinterceptors.size(); ++ i) {
- ActionResultInterceptor ari = (ActionResultInterceptor) interceptors.get(i);
+ ActionResultInterceptor ari = (ActionResultInterceptor) requestinterceptors.get(i);
ari.interceptActionResult(ariresult, incoming, result);
}
}
private void accreteViewARIs(List interceptors, ViewParameters incoming) {
List producers = mappingViewResolver.getProducers(incoming.viewID);
for (int i = 0; i < producers.size(); ++ i) {
Object producer = producers.get(i);
if (producer instanceof ActionResultInterceptor) {
interceptors.add(mappingViewResolver.mapProducer(producer));
}
}
}
}
| true | true |
public void interceptActionResult(ARIResult ariresult, ViewParameters incoming,
Object result) {
if (interceptors == null) {
interceptors = new ArrayList();
}
ArrayList requestinterceptors = new ArrayList(interceptors);
accreteViewARIs(requestinterceptors, incoming);
for (int i = 0; i < requestinterceptors.size(); ++ i) {
ActionResultInterceptor ari = (ActionResultInterceptor) interceptors.get(i);
ari.interceptActionResult(ariresult, incoming, result);
}
}
|
public void interceptActionResult(ARIResult ariresult, ViewParameters incoming,
Object result) {
if (interceptors == null) {
interceptors = new ArrayList();
}
ArrayList requestinterceptors = new ArrayList(interceptors);
accreteViewARIs(requestinterceptors, incoming);
for (int i = 0; i < requestinterceptors.size(); ++ i) {
ActionResultInterceptor ari = (ActionResultInterceptor) requestinterceptors.get(i);
ari.interceptActionResult(ariresult, incoming, result);
}
}
|
diff --git a/dataobject/src/main/java/org/chromattic/dataobject/DataObjectService.java b/dataobject/src/main/java/org/chromattic/dataobject/DataObjectService.java
index bb502e1e..e133ba35 100644
--- a/dataobject/src/main/java/org/chromattic/dataobject/DataObjectService.java
+++ b/dataobject/src/main/java/org/chromattic/dataobject/DataObjectService.java
@@ -1,196 +1,197 @@
/*
* Copyright (C) 2010 eXo Platform SAS.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.chromattic.dataobject;
import org.chromattic.metamodel.typegen.CNDNodeTypeSerializer;
import org.chromattic.metamodel.typegen.NodeType;
import org.chromattic.metamodel.typegen.NodeTypeSerializer;
import org.chromattic.metamodel.typegen.SchemaBuilder;
import org.chromattic.metamodel.typegen.XMLNodeTypeSerializer;
import org.exoplatform.services.jcr.ext.resource.UnifiedNodeReference;
import org.exoplatform.services.jcr.ext.script.groovy.JcrGroovyCompiler;
import org.exoplatform.services.jcr.ext.script.groovy.JcrGroovyResourceLoader;
import org.reflext.api.ClassTypeInfo;
import org.reflext.api.TypeResolver;
import org.reflext.core.TypeResolverImpl;
import org.reflext.jlr.JavaLangReflectReflectionModel;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* The data object service.
*
* @author <a href="mailto:[email protected]">Julien Viet</a>
* @version $Revision$
*/
public class DataObjectService {
public DataObjectService() {
}
public void start() {
}
public void stop() {
}
/**
* Generates the node types for the specified data object paths. This operation returns the schema source
* in the specified format.
*
* @param format the schema output format
* @param source the compilation source
* @param doPaths the data object paths
* @return the data object paths
* @throws DataObjectException anything that would prevent data object compilation
* @throws NullPointerException if any argument is null
* @throws IllegalArgumentException if any data object path is null
*/
public String generateSchema(
NodeTypeFormat format,
CompilationSource source,
String... doPaths) throws DataObjectException, NullPointerException, IllegalArgumentException {
Map<String, NodeType> doNodeTypes = generateSchema(source, doPaths);
//
NodeTypeSerializer serializer;
switch (format) {
case EXO:
serializer = new XMLNodeTypeSerializer();
break;
case CND:
serializer = new CNDNodeTypeSerializer();
break;
default:
throw new AssertionError();
}
//
for (NodeType nodeType : doNodeTypes.values()) {
serializer.addNodeType(nodeType);
}
//
try {
StringWriter writer = new StringWriter();
serializer.writeTo(writer);
return writer.toString();
}
catch (Exception e) {
throw new DataObjectException("Unexpected io exception", e);
}
}
/**
* Generates the node types for the specified data object paths. This operations returns a map
* with the data object path as keys and the related node type as values.
*
* @param source the compilation source
* @param doPaths the data object paths
* @return the data object paths
* @throws DataObjectException anything that would prevent data object compilation
* @throws NullPointerException if any argument is null
* @throws IllegalArgumentException if any data object path is null
*/
public Map<String, NodeType> generateSchema(
CompilationSource source,
String... doPaths) throws DataObjectException, NullPointerException, IllegalArgumentException {
// Generate classes
Map<String, Class<?>> classes = generateClasses(source, doPaths);
// Generate class types
TypeResolver<Type> domain = TypeResolverImpl.create(JavaLangReflectReflectionModel.getInstance());
Map<ClassTypeInfo, String> doClassTypes = new HashMap<ClassTypeInfo, String>();
for (Map.Entry<String, Class<?>> entry : classes.entrySet()) {
doClassTypes.put((ClassTypeInfo)domain.resolve(entry.getValue()), entry.getKey());
}
// Generate bean mappings
Map<String, NodeType> doNodeTypes = new HashMap<String, NodeType>();
for (Map.Entry<ClassTypeInfo, NodeType> entry : new SchemaBuilder().build(doClassTypes.keySet()).entrySet()) {
ClassTypeInfo doClassType = entry.getKey();
NodeType doNodeType = entry.getValue();
String doPath = doClassTypes.get(doClassType);
doNodeTypes.put(doPath, doNodeType);
}
//
return doNodeTypes;
}
/**
* Compiles the specified classes and returns a map with a data object path as key and
* the corresponding compiled data object class.
*
* @param source the compilation source
* @param doPaths the data object paths
* @return the compiled data object classes
* @throws DataObjectException anything that would prevent data object compilation
* @throws NullPointerException if any argument is null
* @throws IllegalArgumentException if any data object path is null
*/
public Map<String, Class<?>> generateClasses(
CompilationSource source,
String... doPaths) throws DataObjectException, NullPointerException, IllegalArgumentException {
if (source == null) {
throw new NullPointerException("No null source accepted");
}
for (String doPath : doPaths) {
if (doPath == null) {
throw new IllegalArgumentException("Data object paths must not contain a null value");
}
}
// Build the classloader url
try {
- URL url = new URL("jcr://" + source.getRepositoryRef() + "/" + source.getWorkspaceRef() + "#" + source.getPath());
+ // see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4648098
+ URL url = new UnifiedNodeReference(source.getRepositoryRef(), source.getWorkspaceRef(), source.getPath()).getURL();
//
JcrGroovyCompiler compiler = new JcrGroovyCompiler();
compiler.getGroovyClassLoader().setResourceLoader(new JcrGroovyResourceLoader(new URL[]{url}));
//
UnifiedNodeReference[] doRefs = new UnifiedNodeReference[doPaths.length];
for (int i = 0;i < doPaths.length;i++) {
doRefs[i] = new UnifiedNodeReference(source.getRepositoryRef(), source.getWorkspaceRef(), doPaths[i]);
}
// Compile to classes
Class[] classes = compiler.compile(doRefs);
Map<String, Class<?>> doClasses = new HashMap<String, Class<?>>();
for (int i = 0;i< doPaths.length;i++) {
doClasses.put(doPaths[i], classes[i]);
}
//
return doClasses;
}
catch (IOException e) {
throw new DataObjectException("Could not generate data object classes", e);
}
}
}
| true | true |
public Map<String, Class<?>> generateClasses(
CompilationSource source,
String... doPaths) throws DataObjectException, NullPointerException, IllegalArgumentException {
if (source == null) {
throw new NullPointerException("No null source accepted");
}
for (String doPath : doPaths) {
if (doPath == null) {
throw new IllegalArgumentException("Data object paths must not contain a null value");
}
}
// Build the classloader url
try {
URL url = new URL("jcr://" + source.getRepositoryRef() + "/" + source.getWorkspaceRef() + "#" + source.getPath());
//
JcrGroovyCompiler compiler = new JcrGroovyCompiler();
compiler.getGroovyClassLoader().setResourceLoader(new JcrGroovyResourceLoader(new URL[]{url}));
//
UnifiedNodeReference[] doRefs = new UnifiedNodeReference[doPaths.length];
for (int i = 0;i < doPaths.length;i++) {
doRefs[i] = new UnifiedNodeReference(source.getRepositoryRef(), source.getWorkspaceRef(), doPaths[i]);
}
// Compile to classes
Class[] classes = compiler.compile(doRefs);
Map<String, Class<?>> doClasses = new HashMap<String, Class<?>>();
for (int i = 0;i< doPaths.length;i++) {
doClasses.put(doPaths[i], classes[i]);
}
//
return doClasses;
}
catch (IOException e) {
throw new DataObjectException("Could not generate data object classes", e);
}
}
|
public Map<String, Class<?>> generateClasses(
CompilationSource source,
String... doPaths) throws DataObjectException, NullPointerException, IllegalArgumentException {
if (source == null) {
throw new NullPointerException("No null source accepted");
}
for (String doPath : doPaths) {
if (doPath == null) {
throw new IllegalArgumentException("Data object paths must not contain a null value");
}
}
// Build the classloader url
try {
// see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4648098
URL url = new UnifiedNodeReference(source.getRepositoryRef(), source.getWorkspaceRef(), source.getPath()).getURL();
//
JcrGroovyCompiler compiler = new JcrGroovyCompiler();
compiler.getGroovyClassLoader().setResourceLoader(new JcrGroovyResourceLoader(new URL[]{url}));
//
UnifiedNodeReference[] doRefs = new UnifiedNodeReference[doPaths.length];
for (int i = 0;i < doPaths.length;i++) {
doRefs[i] = new UnifiedNodeReference(source.getRepositoryRef(), source.getWorkspaceRef(), doPaths[i]);
}
// Compile to classes
Class[] classes = compiler.compile(doRefs);
Map<String, Class<?>> doClasses = new HashMap<String, Class<?>>();
for (int i = 0;i< doPaths.length;i++) {
doClasses.put(doPaths[i], classes[i]);
}
//
return doClasses;
}
catch (IOException e) {
throw new DataObjectException("Could not generate data object classes", e);
}
}
|
diff --git a/src/main/java/org/basex/query/func/FNQName.java b/src/main/java/org/basex/query/func/FNQName.java
index 41bc22cba..6c071f8a7 100644
--- a/src/main/java/org/basex/query/func/FNQName.java
+++ b/src/main/java/org/basex/query/func/FNQName.java
@@ -1,190 +1,190 @@
package org.basex.query.func;
import static org.basex.query.QueryText.*;
import static org.basex.query.util.Err.*;
import static org.basex.util.Token.*;
import org.basex.query.*;
import org.basex.query.expr.*;
import org.basex.query.iter.*;
import org.basex.query.util.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.query.value.type.*;
import org.basex.util.*;
/**
* QName functions.
*
* @author BaseX Team 2005-12, BSD License
* @author Christian Gruen
*/
public final class FNQName extends StandardFunc {
/**
* Constructor.
* @param ii input info
* @param f function definition
* @param e arguments
*/
public FNQName(final InputInfo ii, final Function f, final Expr... e) {
super(ii, f, e);
}
@Override
public Iter iter(final QueryContext ctx) throws QueryException {
switch(sig) {
case IN_SCOPE_PREFIXES: return inscope(ctx);
default: return super.iter(ctx);
}
}
@Override
public Item item(final QueryContext ctx, final InputInfo ii) throws QueryException {
// functions have 1 or 2 arguments...
final Item it = expr[0].item(ctx, info);
final Item it2 = expr.length == 2 ? expr[1].item(ctx, info) : null;
switch(sig) {
case RESOLVE_QNAME: return resolveQName(ctx, it, it2);
case QNAME: return qName(it, it2);
case LOCAL_NAME_FROM_QNAME: return lnFromQName(ctx, it);
case PREFIX_FROM_QNAME: return prefixFromQName(ctx, it);
case NAMESPACE_URI_FOR_PREFIX: return nsUriForPrefix(it, it2);
case RESOLVE_URI: return resolveUri(ctx, it, it2);
default: return super.item(ctx, ii);
}
}
/**
* Returns the in-scope prefixes of the specified node.
* @param ctx query context
* @return prefix sequence
* @throws QueryException query exception
*/
private Iter inscope(final QueryContext ctx) throws QueryException {
final ANode node = (ANode) checkType(expr[0].item(ctx, info),
NodeType.ELM);
final Atts ns = node.nsScope().add(XML, XMLURI);
final int as = ns.size();
final ValueBuilder vb = new ValueBuilder(as);
for(int a = 0; a < as; ++a) {
final byte[] key = ns.name(a);
if(key.length + ns.string(a).length != 0) vb.add(Str.get(key));
}
return vb;
}
/**
* Resolves a QName.
* @param it qname
* @param it2 item
* @return prefix sequence
* @throws QueryException query exception
*/
private Item qName(final Item it, final Item it2) throws QueryException {
final byte[] uri = checkEStr(it);
final byte[] name = checkEStr(it2);
final byte[] str = !contains(name, ':') && eq(uri, XMLURI) ?
concat(XMLC, name) : name;
if(!XMLToken.isQName(str)) Err.value(info, AtomType.QNM, Str.get(name));
final QNm nm = new QNm(str, uri);
if(nm.hasPrefix() && uri.length == 0)
Err.value(info, AtomType.URI, Str.get(nm.uri()));
return nm;
}
/**
* Returns the local name of a QName.
* @param ctx query context
* @param it qname
* @return prefix sequence
* @throws QueryException query exception
*/
private Item lnFromQName(final QueryContext ctx, final Item it) throws QueryException {
if(it == null) return null;
final QNm nm = (QNm) checkType(it, AtomType.QNM);
return AtomType.NCN.cast(Str.get(nm.local()), ctx, info);
}
/**
* Returns the local name of a QName.
* @param ctx query context
* @param it qname
* @return prefix sequence
* @throws QueryException query exception
*/
private Item prefixFromQName(final QueryContext ctx, final Item it)
throws QueryException {
if(it == null) return null;
final QNm nm = (QNm) checkType(it, AtomType.QNM);
return nm.hasPrefix() ? AtomType.NCN.cast(Str.get(nm.prefix()), ctx, info) : null;
}
/**
* Returns a new QName.
* @param ctx query context
* @param it qname
* @param it2 item
* @return prefix sequence
* @throws QueryException query exception
*/
private Item resolveQName(final QueryContext ctx, final Item it,
final Item it2) throws QueryException {
final ANode base = (ANode) checkType(it2, NodeType.ELM);
if(it == null) return null;
final byte[] name = checkEStr(it);
if(!XMLToken.isQName(name)) Err.value(info, AtomType.QNM, it);
final QNm nm = new QNm(name);
final byte[] pref = nm.prefix();
final byte[] uri = base.uri(pref, ctx);
if(uri == null) NSDECL.thrw(info, pref);
nm.uri(uri);
return nm;
}
/**
* Returns the namespace URI for a prefix.
* @param it qname
* @param it2 item
* @return prefix sequence
* @throws QueryException query exception
*/
private Item nsUriForPrefix(final Item it, final Item it2) throws QueryException {
final byte[] pref = checkEStr(it);
final ANode an = (ANode) checkType(it2, NodeType.ELM);
if(eq(pref, XML)) return Uri.uri(XMLURI, false);
final Atts at = an.nsScope();
final byte[] s = at.string(pref);
return s == null || s.length == 0 ? null : Uri.uri(s, false);
}
/**
* Resolves a URI.
* @param ctx query context
* @param it item
* @param it2 second item
* @return prefix sequence
* @throws QueryException query exception
*/
private Item resolveUri(final QueryContext ctx, final Item it, final Item it2)
throws QueryException {
if(it == null) return null;
// check relative uri
final Uri rel = Uri.uri(checkEStr(it));
if(!rel.isValid()) URIINVRES.thrw(info, rel);
if(rel.isAbsolute()) return rel;
// check base uri
final Uri base = it2 == null ? ctx.sc.baseURI() : Uri.uri(checkEStr(it2));
if(!base.isAbsolute()) URIABS.thrw(info, base);
- if(!base.isValid() || contains(base.string(), '#') ||
- !contains(base.string(), token("//"))) URIINVRES.thrw(info, base);
+ if(!base.isValid() || contains(base.string(), '#') || !contains(base.string(), '/'))
+ URIINVRES.thrw(info, base);
return base.resolve(rel);
}
}
| true | true |
private Item resolveUri(final QueryContext ctx, final Item it, final Item it2)
throws QueryException {
if(it == null) return null;
// check relative uri
final Uri rel = Uri.uri(checkEStr(it));
if(!rel.isValid()) URIINVRES.thrw(info, rel);
if(rel.isAbsolute()) return rel;
// check base uri
final Uri base = it2 == null ? ctx.sc.baseURI() : Uri.uri(checkEStr(it2));
if(!base.isAbsolute()) URIABS.thrw(info, base);
if(!base.isValid() || contains(base.string(), '#') ||
!contains(base.string(), token("//"))) URIINVRES.thrw(info, base);
return base.resolve(rel);
}
|
private Item resolveUri(final QueryContext ctx, final Item it, final Item it2)
throws QueryException {
if(it == null) return null;
// check relative uri
final Uri rel = Uri.uri(checkEStr(it));
if(!rel.isValid()) URIINVRES.thrw(info, rel);
if(rel.isAbsolute()) return rel;
// check base uri
final Uri base = it2 == null ? ctx.sc.baseURI() : Uri.uri(checkEStr(it2));
if(!base.isAbsolute()) URIABS.thrw(info, base);
if(!base.isValid() || contains(base.string(), '#') || !contains(base.string(), '/'))
URIINVRES.thrw(info, base);
return base.resolve(rel);
}
|
diff --git a/52n-sos-importer-core/src/main/java/org/n52/sos/importer/model/xml/Step1ModelHandler.java b/52n-sos-importer-core/src/main/java/org/n52/sos/importer/model/xml/Step1ModelHandler.java
index 78e482f5..5af289c1 100644
--- a/52n-sos-importer-core/src/main/java/org/n52/sos/importer/model/xml/Step1ModelHandler.java
+++ b/52n-sos-importer-core/src/main/java/org/n52/sos/importer/model/xml/Step1ModelHandler.java
@@ -1,98 +1,95 @@
/**
* Copyright (C) 2012
* by 52North Initiative for Geospatial Open Source Software GmbH
*
* Contact: Andreas Wytzisk
* 52 North Initiative for Geospatial Open Source Software GmbH
* Martin-Luther-King-Weg 24
* 48155 Muenster, Germany
* [email protected]
*
* This program is free software; you can redistribute and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
*
* This program is distributed WITHOUT ANY WARRANTY; even without 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 (see gnu-gpl v2.txt). If not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA or
* visit the Free Software Foundation web page, http://www.fsf.org.
*/
package org.n52.sos.importer.model.xml;
import org.apache.log4j.Logger;
import org.n52.sos.importer.model.Step1Model;
import org.n52.sos.importer.view.Step1Panel;
import org.x52North.sensorweb.sos.importer.x02.CredentialsDocument.Credentials;
import org.x52North.sensorweb.sos.importer.x02.DataFileDocument.DataFile;
import org.x52North.sensorweb.sos.importer.x02.LocalFileDocument.LocalFile;
import org.x52North.sensorweb.sos.importer.x02.RemoteFileDocument.RemoteFile;
import org.x52North.sensorweb.sos.importer.x02.SosImportConfigurationDocument.SosImportConfiguration;
/**
* Get updates from Step1Model<br />
* Provided information:
* <ul>
* <li>DataFile.LocalFile.Path</li>
* </ul>
* @author <a href="mailto:[email protected]">Eike Hinderk Jürrens</a>
*/
public class Step1ModelHandler implements ModelHandler<Step1Model> {
private static final Logger logger = Logger.getLogger(Step1ModelHandler.class);
@Override
public void handleModel(Step1Model stepModel, SosImportConfiguration sosImportConf) {
if (logger.isTraceEnabled()) {
logger.trace("handleModel()");
}
DataFile dF = sosImportConf.getDataFile();
if (dF == null) {
dF = sosImportConf.addNewDataFile();
}
if (stepModel.getFeedingType() == Step1Panel.CSV_FILE) {
if (dF.getRemoteFile() != null) {
// TODO remove old
dF.setRemoteFile(null);
}
LocalFile lF = (dF.getLocalFile() == null) ? dF.addNewLocalFile() : dF.getLocalFile();
String path = stepModel.getCSVFilePath();
if (path != null && !path.equals("")) {
lF.setPath(path);
} else {
String msg = "empty path to CSV file in Step1Model: " + path;
logger.error(msg);
throw new NullPointerException(msg);
}
} else {
if (dF.getLocalFile() != null) {
// TODO remove old
dF.setLocalFile(null);
}
RemoteFile rF = (dF.getRemoteFile() == null)? dF.addNewRemoteFile() : dF.getRemoteFile();
String url = stepModel.getUrl();
- if (stepModel.getDirectory() != null) {
- if (url.charAt(url.length() - 1) != '/'
- && stepModel.getDirectory().charAt(0) != '/') {
- url += '/';
- }
- url += stepModel.getDirectory();
- if (url.charAt(url.length() - 1) != '/'
- && stepModel.getFilenameSchema().charAt(0) != '/') {
- url += '/';
- }
- url += stepModel.getFilenameSchema();
+ if (stepModel.getDirectory() != null && url.charAt(url.length() - 1) != '/'
+ && stepModel.getDirectory().charAt(0) != '/') {
+ url += '/';
}
- rF.setURL(stepModel.getUrl());
+ url += stepModel.getDirectory();
+ if (url.charAt(url.length() - 1) != '/' && stepModel.getFilenameSchema().charAt(0) != '/') {
+ url += '/';
+ }
+ url += stepModel.getFilenameSchema();
+ rF.setURL(url);
Credentials cDoc = (rF.getCredentials() == null)? rF.addNewCredentials() : rF.getCredentials();
cDoc.setUserName(stepModel.getUser());
cDoc.setPassword(stepModel.getPassword());
}
dF.setRefenceIsARegularExpression(stepModel.isRegex());
}
}
| false | true |
public void handleModel(Step1Model stepModel, SosImportConfiguration sosImportConf) {
if (logger.isTraceEnabled()) {
logger.trace("handleModel()");
}
DataFile dF = sosImportConf.getDataFile();
if (dF == null) {
dF = sosImportConf.addNewDataFile();
}
if (stepModel.getFeedingType() == Step1Panel.CSV_FILE) {
if (dF.getRemoteFile() != null) {
// TODO remove old
dF.setRemoteFile(null);
}
LocalFile lF = (dF.getLocalFile() == null) ? dF.addNewLocalFile() : dF.getLocalFile();
String path = stepModel.getCSVFilePath();
if (path != null && !path.equals("")) {
lF.setPath(path);
} else {
String msg = "empty path to CSV file in Step1Model: " + path;
logger.error(msg);
throw new NullPointerException(msg);
}
} else {
if (dF.getLocalFile() != null) {
// TODO remove old
dF.setLocalFile(null);
}
RemoteFile rF = (dF.getRemoteFile() == null)? dF.addNewRemoteFile() : dF.getRemoteFile();
String url = stepModel.getUrl();
if (stepModel.getDirectory() != null) {
if (url.charAt(url.length() - 1) != '/'
&& stepModel.getDirectory().charAt(0) != '/') {
url += '/';
}
url += stepModel.getDirectory();
if (url.charAt(url.length() - 1) != '/'
&& stepModel.getFilenameSchema().charAt(0) != '/') {
url += '/';
}
url += stepModel.getFilenameSchema();
}
rF.setURL(stepModel.getUrl());
Credentials cDoc = (rF.getCredentials() == null)? rF.addNewCredentials() : rF.getCredentials();
cDoc.setUserName(stepModel.getUser());
cDoc.setPassword(stepModel.getPassword());
}
dF.setRefenceIsARegularExpression(stepModel.isRegex());
}
|
public void handleModel(Step1Model stepModel, SosImportConfiguration sosImportConf) {
if (logger.isTraceEnabled()) {
logger.trace("handleModel()");
}
DataFile dF = sosImportConf.getDataFile();
if (dF == null) {
dF = sosImportConf.addNewDataFile();
}
if (stepModel.getFeedingType() == Step1Panel.CSV_FILE) {
if (dF.getRemoteFile() != null) {
// TODO remove old
dF.setRemoteFile(null);
}
LocalFile lF = (dF.getLocalFile() == null) ? dF.addNewLocalFile() : dF.getLocalFile();
String path = stepModel.getCSVFilePath();
if (path != null && !path.equals("")) {
lF.setPath(path);
} else {
String msg = "empty path to CSV file in Step1Model: " + path;
logger.error(msg);
throw new NullPointerException(msg);
}
} else {
if (dF.getLocalFile() != null) {
// TODO remove old
dF.setLocalFile(null);
}
RemoteFile rF = (dF.getRemoteFile() == null)? dF.addNewRemoteFile() : dF.getRemoteFile();
String url = stepModel.getUrl();
if (stepModel.getDirectory() != null && url.charAt(url.length() - 1) != '/'
&& stepModel.getDirectory().charAt(0) != '/') {
url += '/';
}
url += stepModel.getDirectory();
if (url.charAt(url.length() - 1) != '/' && stepModel.getFilenameSchema().charAt(0) != '/') {
url += '/';
}
url += stepModel.getFilenameSchema();
rF.setURL(url);
Credentials cDoc = (rF.getCredentials() == null)? rF.addNewCredentials() : rF.getCredentials();
cDoc.setUserName(stepModel.getUser());
cDoc.setPassword(stepModel.getPassword());
}
dF.setRefenceIsARegularExpression(stepModel.isRegex());
}
|
diff --git a/src/cz/muni/fi/spc/SchedVis/model/entities/Machine.java b/src/cz/muni/fi/spc/SchedVis/model/entities/Machine.java
index c0fe32a..af59ad2 100644
--- a/src/cz/muni/fi/spc/SchedVis/model/entities/Machine.java
+++ b/src/cz/muni/fi/spc/SchedVis/model/entities/Machine.java
@@ -1,390 +1,390 @@
/*
* This file is part of SchedVis.
*
* SchedVis 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.
*
* SchedVis 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
* SchedVis. If not, see <http://www.gnu.org/licenses/>.
*/
/**
*
*/
package cz.muni.fi.spc.SchedVis.model.entities;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.hibernate.Criteria;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Index;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import cz.muni.fi.spc.SchedVis.model.BaseEntity;
import cz.muni.fi.spc.SchedVis.model.EventType;
import cz.muni.fi.spc.SchedVis.model.JobHint;
import cz.muni.fi.spc.SchedVis.util.Database;
/**
* JPA Entity that represents a machine.
*
* @author Lukáš Petrovický <[email protected]>
*
*/
@Entity
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public final class Machine extends BaseEntity implements Comparable<Machine> {
private static Integer internalIdCounter = 0;
private static PreparedStatement s;
private static final Map<Integer, Machine> byId = Collections
.synchronizedMap(new HashMap<Integer, Machine>());
private static final Map<String, Machine> byName = Collections
.synchronizedMap(new HashMap<String, Machine>());
/**
* Retrieve all the machines in a given group.
*
* @param groupId
* ID of the group whose machines will be retrieved. If null,
* machines in no group are retrieved.
* @return The machines.
*/
@SuppressWarnings("unchecked")
public static Set<Machine> getAll(final Integer groupId) {
final Criteria crit = BaseEntity.getCriteria(Machine.class);
if (groupId != null) {
crit.add(Restrictions.eq("group", MachineGroup.getWithId(groupId))); //$NON-NLS-1$
} else {
crit.add(Restrictions.isNull("group")); //$NON-NLS-1$
}
crit.addOrder(Order.asc("name")); //$NON-NLS-1$
return new TreeSet<Machine>(crit.list());
}
/**
* Retrieve all machines, regardless whether they are or are not in some
* group.
*
* @return The machines.
*/
@SuppressWarnings("unchecked")
public static Set<Machine> getAllGroupless() {
final Criteria crit = BaseEntity.getCriteria(Machine.class);
crit.addOrder(Order.asc("name")); //$NON-NLS-1$
return new TreeSet<Machine>(crit.list());
}
/**
* Get the latest schedule that concerns given machine at a given time. This
* method ties directly to SQLite, even skipping Hibernate - it is essential
* that this method is as fast as possible.
*
* @param which
* The machine in which we are interested.
* @param evt
* The latest schedule is looked for in the interval of event 1 to
* this number.
* @return Jobs in the schedule.
*/
public synchronized static List<Job> getLatestSchedule(final Machine which,
final Event evt) {
try {
if (Machine.s == null) {
- final String query = "SELECT id, assignedCPUs, deadline, job, jobHint, expectedStart, expectedEnd, bringsSchedule FROM Job WHERE machine_id = ? AND parent = (SELECT max(parent) FROM Job WHERE machine_id = ? AND parent <= ?)"; //$NON-NLS-1$
+ final String query = "SELECT id, assignedCPUs, deadline, number, jobHintId, expectedStart, expectedEnd, bringsSchedule FROM Job WHERE machine_id = ? AND parent = (SELECT max(parent) FROM Job WHERE machine_id = ? AND parent <= ?)"; //$NON-NLS-1$
Machine.s = BaseEntity.getConnection(Database.getEntityManager())
.prepareStatement(query);
}
Machine.s.setInt(1, which.getId());
Machine.s.setInt(2, which.getId());
Machine.s.setInt(3, evt.getId());
final ResultSet rs = Machine.s.executeQuery();
final List<Job> schedules = new ArrayList<Job>();
while (rs.next()) {
final Job schedule = new Job();
schedule.setId(rs.getInt(1));
schedule.setAssignedCPUs(rs.getString(2));
schedule.setDeadline(rs.getInt(3));
schedule.setNumber(rs.getInt(4));
schedule.setHint(JobHint.getWithId(rs.getInt(5)));
schedule.setExpectedStart(rs.getInt(6));
schedule.setExpectedEnd(rs.getInt(7));
if (rs.getInt(8) == 1) {
schedule.setBringsSchedule(true);
} else {
schedule.setBringsSchedule(false);
}
schedules.add(schedule);
}
rs.close();
Machine.s.clearParameters();
return schedules;
} catch (final SQLException e) {
e.printStackTrace();
return new ArrayList<Job>();
}
}
private static Machine getWithName(final String name) {
final Criteria crit = BaseEntity.getCriteria(Machine.class);
crit.add(Restrictions.eq("name", name)); //$NON-NLS-1$
crit.setMaxResults(1);
return (Machine) crit.uniqueResult();
}
/**
* Retrieve machine with a given name.
*
* @param name
* The name in question.
* @param cache
* Whether or not to use the local entity cache.
* @return The machine.
*/
public static Machine getWithName(final String name, final boolean cache) {
if (!cache) {
return Machine.getWithName(name);
}
if (!Machine.byName.containsKey(name)) {
final Machine m = Machine.getWithName(name);
if (m == null) {
return null;
}
Machine.byName.put(name, m);
}
final Machine m = Machine.byName.get(name);
if (!Machine.byId.containsKey(m.getId())) {
Machine.byId.put(m.getId(), m);
}
return m;
}
/**
* Determine whether a machine is active (not off-line) at a given point in
* time.
*
* @param m
* Machine in question.
* @param evt
* The given point of time.
* @return False when the last machine event up to and including the given
* time is machine failure. True otherwise, especially when there are
* no such events.
*/
public static boolean isActive(final Machine m, final Event evt) {
final Integer[] machineEvents = new Integer[] {
EventType.MACHINE_FAIL.getId(),
EventType.MACHINE_FAIL_MOVE_BAD.getId(),
EventType.MACHINE_FAIL_MOVE_GOOD.getId(),
EventType.MACHINE_RESTART.getId() };
final Criteria crit = BaseEntity.getCriteria(Event.class);
crit.add(Restrictions.in("eventTypeId", machineEvents)); //$NON-NLS-1$
crit.add(Restrictions.lt("id", evt.getId()));
crit.setProjection(Projections.max("id"));
final Integer evtId = (Integer) crit.uniqueResult();
if (evtId == null) {
return true;
}
final Event e = Event.getWithId(evtId);
if (e == null) {
return true;
}
final EventType et = e.getType();
if ((et == EventType.MACHINE_FAIL)
|| (et == EventType.MACHINE_FAIL_MOVE_BAD)
|| (et == EventType.MACHINE_FAIL_MOVE_GOOD)) {
return false;
}
return true;
}
private int internalId;
private String os;
private int id;
private int cpus;
private int hdd;
private String name;
private String platform;
private int ram;
private int speed;
private MachineGroup group;
public Machine() {
synchronized (Machine.internalIdCounter) {
this.setInternalId(Machine.internalIdCounter++);
}
}
@Override
public int compareTo(final Machine o) {
return Integer.valueOf(this.getId()).compareTo(Integer.valueOf(o.getId()));
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Machine)) {
return false;
}
final Machine other = (Machine) obj;
if (this.internalId != other.internalId) {
return false;
}
return true;
}
public int getCPUs() {
return this.cpus;
}
@ManyToOne
@JoinColumn(name = "group_fk")
public MachineGroup getGroup() {
return this.group;
}
public int getHDD() {
return this.hdd;
}
@Id
@GeneratedValue
public int getId() {
return this.id;
}
public int getInternalId() {
return this.internalId;
}
@Index(name = "mnIndex")
public String getName() {
return this.name;
}
public String getOS() {
return this.os;
}
public String getPlatform() {
return this.platform;
}
public int getRAM() {
return this.ram;
}
public int getSpeed() {
return this.speed;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + this.internalId;
return result;
}
public void setCPUs(final int cpus) {
this.cpus = cpus;
}
public void setGroup(final MachineGroup group) {
this.group = group;
}
public void setHDD(final int hdd) {
this.hdd = hdd;
}
protected void setId(final int id) {
this.id = id;
}
private void setInternalId(final int id) {
this.internalId = id;
}
public void setName(final String name) {
this.name = name;
}
public void setOS(final String os) {
this.os = os;
}
public void setPlatform(final String platform) {
this.platform = platform;
}
public void setRAM(final int ram) {
this.ram = ram;
}
public void setSpeed(final int speed) {
this.speed = speed;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Machine [cpus=" + this.cpus + ", "
+ (this.group != null ? "group=" + this.group + ", " : "") + "hdd="
+ this.hdd + ", id=" + this.id + ", "
+ (this.name != null ? "name=" + this.name + ", " : "")
+ (this.os != null ? "os=" + this.os + ", " : "")
+ (this.platform != null ? "platform=" + this.platform + ", " : "")
+ "ram=" + this.ram + ", speed=" + this.speed + "]";
}
}
| true | true |
public synchronized static List<Job> getLatestSchedule(final Machine which,
final Event evt) {
try {
if (Machine.s == null) {
final String query = "SELECT id, assignedCPUs, deadline, job, jobHint, expectedStart, expectedEnd, bringsSchedule FROM Job WHERE machine_id = ? AND parent = (SELECT max(parent) FROM Job WHERE machine_id = ? AND parent <= ?)"; //$NON-NLS-1$
Machine.s = BaseEntity.getConnection(Database.getEntityManager())
.prepareStatement(query);
}
Machine.s.setInt(1, which.getId());
Machine.s.setInt(2, which.getId());
Machine.s.setInt(3, evt.getId());
final ResultSet rs = Machine.s.executeQuery();
final List<Job> schedules = new ArrayList<Job>();
while (rs.next()) {
final Job schedule = new Job();
schedule.setId(rs.getInt(1));
schedule.setAssignedCPUs(rs.getString(2));
schedule.setDeadline(rs.getInt(3));
schedule.setNumber(rs.getInt(4));
schedule.setHint(JobHint.getWithId(rs.getInt(5)));
schedule.setExpectedStart(rs.getInt(6));
schedule.setExpectedEnd(rs.getInt(7));
if (rs.getInt(8) == 1) {
schedule.setBringsSchedule(true);
} else {
schedule.setBringsSchedule(false);
}
schedules.add(schedule);
}
rs.close();
Machine.s.clearParameters();
return schedules;
} catch (final SQLException e) {
e.printStackTrace();
return new ArrayList<Job>();
}
}
|
public synchronized static List<Job> getLatestSchedule(final Machine which,
final Event evt) {
try {
if (Machine.s == null) {
final String query = "SELECT id, assignedCPUs, deadline, number, jobHintId, expectedStart, expectedEnd, bringsSchedule FROM Job WHERE machine_id = ? AND parent = (SELECT max(parent) FROM Job WHERE machine_id = ? AND parent <= ?)"; //$NON-NLS-1$
Machine.s = BaseEntity.getConnection(Database.getEntityManager())
.prepareStatement(query);
}
Machine.s.setInt(1, which.getId());
Machine.s.setInt(2, which.getId());
Machine.s.setInt(3, evt.getId());
final ResultSet rs = Machine.s.executeQuery();
final List<Job> schedules = new ArrayList<Job>();
while (rs.next()) {
final Job schedule = new Job();
schedule.setId(rs.getInt(1));
schedule.setAssignedCPUs(rs.getString(2));
schedule.setDeadline(rs.getInt(3));
schedule.setNumber(rs.getInt(4));
schedule.setHint(JobHint.getWithId(rs.getInt(5)));
schedule.setExpectedStart(rs.getInt(6));
schedule.setExpectedEnd(rs.getInt(7));
if (rs.getInt(8) == 1) {
schedule.setBringsSchedule(true);
} else {
schedule.setBringsSchedule(false);
}
schedules.add(schedule);
}
rs.close();
Machine.s.clearParameters();
return schedules;
} catch (final SQLException e) {
e.printStackTrace();
return new ArrayList<Job>();
}
}
|
diff --git a/grails/src/java/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java b/grails/src/java/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java
index c8dbbc322..e44b9954a 100644
--- a/grails/src/java/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java
+++ b/grails/src/java/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java
@@ -1,405 +1,405 @@
/*
* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.web.metaclass;
import grails.util.GrailsWebUtil;
import grails.util.JSonBuilder;
import grails.util.OpenRicoBuilder;
import groovy.lang.*;
import groovy.text.Template;
import groovy.xml.StreamingMarkupBuilder;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang.StringUtils;
import org.codehaus.groovy.grails.commons.ConfigurationHolder;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.metaclass.AbstractDynamicMethodInvocation;
import org.codehaus.groovy.grails.plugins.GrailsPlugin;
import org.codehaus.groovy.grails.plugins.GrailsPluginManager;
import org.codehaus.groovy.grails.web.pages.GSPResponseWriter;
import org.codehaus.groovy.grails.web.pages.GroovyPageUtils;
import org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest;
import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Allows rendering of text, views, and templates to the response
*
* @author Graeme Rocher
* @since 0.2
* <p/>
* Created: Oct 27, 2005
*/
public class RenderDynamicMethod extends AbstractDynamicMethodInvocation {
public static final String METHOD_SIGNATURE = "render";
public static final Pattern METHOD_PATTERN = Pattern.compile('^' + METHOD_SIGNATURE + '$');
public static final String ARGUMENT_TEXT = "text";
public static final String ARGUMENT_STATUS = "status";
public static final String ARGUMENT_CONTENT_TYPE = "contentType";
public static final String ARGUMENT_ENCODING = "encoding";
public static final String ARGUMENT_VIEW = "view";
public static final String ARGUMENT_MODEL = "model";
public static final String ARGUMENT_TEMPLATE = "template";
public static final String ARGUMENT_CONTEXTPATH = "contextPath";
public static final String ARGUMENT_BEAN = "bean";
public static final String ARGUMENT_COLLECTION = "collection";
public static final String ARGUMENT_BUILDER = "builder";
public static final String ARGUMENT_VAR = "var";
private static final String DEFAULT_ARGUMENT = "it";
private static final String BUILDER_TYPE_RICO = "rico";
private static final String BUILDER_TYPE_JSON = "json";
private static final int BUFFER_SIZE = 8192;
private static final String TEXT_HTML = "text/html";
private String gspEncoding;
private static final String DEFAULT_ENCODING = "utf-8";
private Object ARGUMENT_PLUGIN = "plugin";
public RenderDynamicMethod() {
super(METHOD_PATTERN);
Map config = ConfigurationHolder.getFlatConfig();
Object gspEnc = config.get("grails.views.gsp.encoding");
if ((gspEnc != null) && (gspEnc.toString().trim().length() > 0)) {
this.gspEncoding = gspEnc.toString();
} else {
gspEncoding = DEFAULT_ENCODING;
}
}
public Object invoke(Object target, String methodName, Object[] arguments) {
if (arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE, target.getClass(), arguments);
GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes();
GrailsApplication application = webRequest.getAttributes().getGrailsApplication();
HttpServletRequest request = webRequest.getCurrentRequest();
HttpServletResponse response = webRequest.getCurrentResponse();
boolean renderView = true;
GroovyObject controller = (GroovyObject) target;
if ((arguments[0] instanceof String) || (arguments[0] instanceof GString)) {
setContentType(response, TEXT_HTML, DEFAULT_ENCODING,true);
String text = arguments[0].toString();
renderView = renderText(text, response);
} else if (arguments[0] instanceof Closure) {
- setContentType(response, TEXT_HTML, DEFAULT_ENCODING, true);
+ setContentType(response, TEXT_HTML, gspEncoding, true);
Closure closure = (Closure) arguments[arguments.length - 1];
renderView = renderMarkup(closure, response);
} else if (arguments[0] instanceof Map) {
Map argMap = (Map) arguments[0];
Writer out;
if (argMap.containsKey(ARGUMENT_CONTENT_TYPE) && argMap.containsKey(ARGUMENT_ENCODING)) {
String contentType = argMap.get(ARGUMENT_CONTENT_TYPE).toString();
String encoding = argMap.get(ARGUMENT_ENCODING).toString();
setContentType(response, contentType, encoding);
out = GSPResponseWriter.getInstance(response, BUFFER_SIZE);
} else if (argMap.containsKey(ARGUMENT_CONTENT_TYPE)) {
setContentType(response, argMap.get(ARGUMENT_CONTENT_TYPE).toString(), DEFAULT_ENCODING);
out = GSPResponseWriter.getInstance(response, BUFFER_SIZE);
} else {
setContentType(response, TEXT_HTML, DEFAULT_ENCODING, true);
out = GSPResponseWriter.getInstance(response, BUFFER_SIZE);
}
if(argMap.containsKey(ARGUMENT_STATUS)) {
Object statusObj = argMap.get(ARGUMENT_STATUS);
if(statusObj!=null) {
try {
response.setStatus(Integer.parseInt(statusObj.toString()));
}
catch (NumberFormatException e) {
throw new ControllerExecutionException("Argument [status] of method [render] must be a valid integer.");
}
}
}
webRequest.setOut(out);
if (arguments[arguments.length - 1] instanceof Closure) {
Closure callable = (Closure) arguments[arguments.length - 1];
if (BUILDER_TYPE_RICO.equals(argMap.get(ARGUMENT_BUILDER))) {
renderView = renderRico(callable, response);
} else if (BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER)) || isJSONResponse(response)) {
renderView = renderJSON(callable, response);
} else {
renderView = renderMarkup(callable, response);
}
} else if (arguments[arguments.length - 1] instanceof String) {
String text = (String) arguments[arguments.length - 1];
renderView = renderText(text, out);
} else if (argMap.containsKey(ARGUMENT_TEXT)) {
String text = argMap.get(ARGUMENT_TEXT).toString();
renderView = renderText(text, out);
} else if (argMap.containsKey(ARGUMENT_VIEW)) {
renderView(argMap, target, controller);
} else if (argMap.containsKey(ARGUMENT_TEMPLATE)) {
renderView = renderTemplate(target, controller, webRequest, argMap, out);
} else {
Object object = arguments[0];
renderView = renderObject(object, out);
}
try {
if (!renderView) {
out.flush();
}
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments [" + argMap + "]: " + e.getMessage(), e);
}
} else {
throw new MissingMethodException(METHOD_SIGNATURE, target.getClass(), arguments);
}
webRequest.setRenderView(renderView);
return null;
}
private boolean renderTemplate(Object target, GroovyObject controller, GrailsWebRequest webRequest, Map argMap, Writer out) {
boolean renderView;
String templateName = argMap.get(ARGUMENT_TEMPLATE).toString();
String contextPath = getContextPath(webRequest, argMap);
String var = (String) argMap.get(ARGUMENT_VAR);
// get the template uri
String templateUri = GroovyPageUtils.getTemplateURI(controller, templateName);
// retrieve gsp engine
GroovyPagesTemplateEngine engine = (GroovyPagesTemplateEngine) webRequest.getApplicationContext().getBean(GroovyPagesTemplateEngine.BEAN_ID);
try {
Resource r = engine.getResourceForUri(contextPath + templateUri);
if (!r.exists()) {
r = engine.getResourceForUri(contextPath + "/grails-app/views/" + templateUri);
}
Template t = engine.createTemplate(r); //templateUri);
if (t == null) {
throw new ControllerExecutionException("Unable to load template for uri [" + templateUri + "]. Template not found.");
}
Map binding = new HashMap();
if (argMap.containsKey(ARGUMENT_BEAN)) {
Object bean = argMap.get(ARGUMENT_BEAN);
if (argMap.containsKey(ARGUMENT_MODEL)) {
Object modelObject = argMap.get(ARGUMENT_MODEL);
if (modelObject instanceof Map)
binding.putAll((Map) modelObject);
}
renderTemplateForBean(t, binding, bean, var, out);
} else if (argMap.containsKey(ARGUMENT_COLLECTION)) {
Object colObject = argMap.get(ARGUMENT_COLLECTION);
if (argMap.containsKey(ARGUMENT_MODEL)) {
Object modelObject = argMap.get(ARGUMENT_MODEL);
if (modelObject instanceof Map)
binding.putAll((Map) modelObject);
}
renderTemplateForCollection(t, binding, colObject, var, out);
} else if (argMap.containsKey(ARGUMENT_MODEL)) {
Object modelObject = argMap.get(ARGUMENT_MODEL);
renderTemplateForModel(t, modelObject, target, out);
} else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
renderView = false;
}
catch (GroovyRuntimeException gre) {
throw new ControllerExecutionException("Error rendering template [" + templateName + "]: " + gre.getMessage(), gre);
}
catch (IOException ioex) {
throw new ControllerExecutionException("I/O error executing render method for arguments [" + argMap + "]: " + ioex.getMessage(), ioex);
}
return renderView;
}
private String getContextPath(GrailsWebRequest webRequest, Map argMap) {
Object cp = argMap.get(ARGUMENT_CONTEXTPATH);
String contextPath = (cp != null ? cp.toString() : "");
Object pluginName = argMap.get(ARGUMENT_PLUGIN);
if(pluginName!=null) {
ApplicationContext applicationContext = webRequest.getApplicationContext();
GrailsPluginManager pluginManager = (GrailsPluginManager) applicationContext.getBean(GrailsPluginManager.BEAN_NAME);
GrailsPlugin plugin = pluginManager.getGrailsPlugin(pluginName.toString());
if(plugin!=null && !plugin.isBasePlugin()) contextPath = plugin.getPluginPath();
}
return contextPath;
}
private void setContentType(HttpServletResponse response, String contentType, String encoding) {
setContentType(response, contentType, encoding, false);
}
private void setContentType(HttpServletResponse response, String contentType, String encoding, boolean contentTypeIsDefault) {
if(response.getContentType()==null || !contentTypeIsDefault)
response.setContentType(GrailsWebUtil.getContentType(contentType,encoding));
}
private boolean renderObject(Object object, Writer out) {
boolean renderView;
try {
out.write(DefaultGroovyMethods.inspect(object));
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error obtaining response writer: " + e.getMessage(), e);
}
return renderView;
}
private void renderTemplateForModel(Template template, Object modelObject, Object target, Writer out) throws IOException {
if (modelObject instanceof Map) {
Writable w = template.make((Map) modelObject);
w.writeTo(out);
} else {
Writable w = template.make(new BeanMap(target));
w.writeTo(out);
}
}
private void renderTemplateForCollection(Template template, Map binding, Object colObject, String var, Writer out) throws IOException {
if (colObject instanceof Collection) {
Collection c = (Collection) colObject;
for (Iterator i = c.iterator(); i.hasNext();) {
Object o = i.next();
if (StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, o);
else
binding.put(var, o);
Writable w = template.make(binding);
w.writeTo(out);
}
} else {
if (StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, colObject);
else
binding.put(var, colObject);
Writable w = template.make(binding);
w.writeTo(out);
}
}
private void renderTemplateForBean(Template template, Map binding, Object bean, String varName, Writer out) throws IOException {
if (StringUtils.isBlank(varName)) {
binding.put(DEFAULT_ARGUMENT, bean);
} else
binding.put(varName, bean);
Writable w = template.make(binding);
w.writeTo(out);
}
private void renderView(Map argMap, Object target, GroovyObject controller) {
String viewName = argMap.get(ARGUMENT_VIEW).toString();
Object modelObject = argMap.get(ARGUMENT_MODEL);
String viewUri = GroovyPageUtils.getNoSuffixViewURI((GroovyObject) target, viewName);
Map model;
if (modelObject instanceof Map) {
model = (Map) modelObject;
} else if (target instanceof GroovyObject) {
model = new BeanMap(target);
} else {
model = new HashMap();
}
controller.setProperty(ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY, new ModelAndView(viewUri, model));
}
private boolean renderJSON(Closure callable, HttpServletResponse response) {
boolean renderView;
JSonBuilder jsonBuilder;
try {
jsonBuilder = new JSonBuilder(response);
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments [" + callable + "]: " + e.getMessage(), e);
}
jsonBuilder.invokeMethod("json", new Object[]{callable});
return renderView;
}
private boolean renderRico(Closure callable, HttpServletResponse response) {
boolean renderView;
OpenRicoBuilder orb;
try {
orb = new OpenRicoBuilder(response);
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments [" + callable + "]: " + e.getMessage(), e);
}
orb.invokeMethod("ajax", new Object[]{callable});
return renderView;
}
private boolean renderMarkup(Closure closure, HttpServletResponse response) {
boolean renderView;
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable) b.bind(closure);
try {
markup.writeTo(response.getWriter());
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments [" + closure + "]: " + e.getMessage(), e);
}
renderView = false;
return renderView;
}
private boolean renderText(String text, HttpServletResponse response) {
try {
PrintWriter writer = response.getWriter();
return renderText(text, writer);
} catch (IOException e) {
throw new ControllerExecutionException(e.getMessage(), e);
}
}
private boolean renderText(String text, Writer writer) {
try {
writer.write(text);
return false;
} catch (IOException e) {
throw new ControllerExecutionException(e.getMessage(), e);
}
}
private boolean isJSONResponse(HttpServletResponse response) {
String contentType = response.getContentType();
return contentType != null && (contentType.indexOf("application/json") > -1 || contentType.indexOf("text/json") > -1);
}
}
| true | true |
public Object invoke(Object target, String methodName, Object[] arguments) {
if (arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE, target.getClass(), arguments);
GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes();
GrailsApplication application = webRequest.getAttributes().getGrailsApplication();
HttpServletRequest request = webRequest.getCurrentRequest();
HttpServletResponse response = webRequest.getCurrentResponse();
boolean renderView = true;
GroovyObject controller = (GroovyObject) target;
if ((arguments[0] instanceof String) || (arguments[0] instanceof GString)) {
setContentType(response, TEXT_HTML, DEFAULT_ENCODING,true);
String text = arguments[0].toString();
renderView = renderText(text, response);
} else if (arguments[0] instanceof Closure) {
setContentType(response, TEXT_HTML, DEFAULT_ENCODING, true);
Closure closure = (Closure) arguments[arguments.length - 1];
renderView = renderMarkup(closure, response);
} else if (arguments[0] instanceof Map) {
Map argMap = (Map) arguments[0];
Writer out;
if (argMap.containsKey(ARGUMENT_CONTENT_TYPE) && argMap.containsKey(ARGUMENT_ENCODING)) {
String contentType = argMap.get(ARGUMENT_CONTENT_TYPE).toString();
String encoding = argMap.get(ARGUMENT_ENCODING).toString();
setContentType(response, contentType, encoding);
out = GSPResponseWriter.getInstance(response, BUFFER_SIZE);
} else if (argMap.containsKey(ARGUMENT_CONTENT_TYPE)) {
setContentType(response, argMap.get(ARGUMENT_CONTENT_TYPE).toString(), DEFAULT_ENCODING);
out = GSPResponseWriter.getInstance(response, BUFFER_SIZE);
} else {
setContentType(response, TEXT_HTML, DEFAULT_ENCODING, true);
out = GSPResponseWriter.getInstance(response, BUFFER_SIZE);
}
if(argMap.containsKey(ARGUMENT_STATUS)) {
Object statusObj = argMap.get(ARGUMENT_STATUS);
if(statusObj!=null) {
try {
response.setStatus(Integer.parseInt(statusObj.toString()));
}
catch (NumberFormatException e) {
throw new ControllerExecutionException("Argument [status] of method [render] must be a valid integer.");
}
}
}
webRequest.setOut(out);
if (arguments[arguments.length - 1] instanceof Closure) {
Closure callable = (Closure) arguments[arguments.length - 1];
if (BUILDER_TYPE_RICO.equals(argMap.get(ARGUMENT_BUILDER))) {
renderView = renderRico(callable, response);
} else if (BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER)) || isJSONResponse(response)) {
renderView = renderJSON(callable, response);
} else {
renderView = renderMarkup(callable, response);
}
} else if (arguments[arguments.length - 1] instanceof String) {
String text = (String) arguments[arguments.length - 1];
renderView = renderText(text, out);
} else if (argMap.containsKey(ARGUMENT_TEXT)) {
String text = argMap.get(ARGUMENT_TEXT).toString();
renderView = renderText(text, out);
} else if (argMap.containsKey(ARGUMENT_VIEW)) {
renderView(argMap, target, controller);
} else if (argMap.containsKey(ARGUMENT_TEMPLATE)) {
renderView = renderTemplate(target, controller, webRequest, argMap, out);
} else {
Object object = arguments[0];
renderView = renderObject(object, out);
}
try {
if (!renderView) {
out.flush();
}
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments [" + argMap + "]: " + e.getMessage(), e);
}
} else {
throw new MissingMethodException(METHOD_SIGNATURE, target.getClass(), arguments);
}
webRequest.setRenderView(renderView);
return null;
}
|
public Object invoke(Object target, String methodName, Object[] arguments) {
if (arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE, target.getClass(), arguments);
GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes();
GrailsApplication application = webRequest.getAttributes().getGrailsApplication();
HttpServletRequest request = webRequest.getCurrentRequest();
HttpServletResponse response = webRequest.getCurrentResponse();
boolean renderView = true;
GroovyObject controller = (GroovyObject) target;
if ((arguments[0] instanceof String) || (arguments[0] instanceof GString)) {
setContentType(response, TEXT_HTML, DEFAULT_ENCODING,true);
String text = arguments[0].toString();
renderView = renderText(text, response);
} else if (arguments[0] instanceof Closure) {
setContentType(response, TEXT_HTML, gspEncoding, true);
Closure closure = (Closure) arguments[arguments.length - 1];
renderView = renderMarkup(closure, response);
} else if (arguments[0] instanceof Map) {
Map argMap = (Map) arguments[0];
Writer out;
if (argMap.containsKey(ARGUMENT_CONTENT_TYPE) && argMap.containsKey(ARGUMENT_ENCODING)) {
String contentType = argMap.get(ARGUMENT_CONTENT_TYPE).toString();
String encoding = argMap.get(ARGUMENT_ENCODING).toString();
setContentType(response, contentType, encoding);
out = GSPResponseWriter.getInstance(response, BUFFER_SIZE);
} else if (argMap.containsKey(ARGUMENT_CONTENT_TYPE)) {
setContentType(response, argMap.get(ARGUMENT_CONTENT_TYPE).toString(), DEFAULT_ENCODING);
out = GSPResponseWriter.getInstance(response, BUFFER_SIZE);
} else {
setContentType(response, TEXT_HTML, DEFAULT_ENCODING, true);
out = GSPResponseWriter.getInstance(response, BUFFER_SIZE);
}
if(argMap.containsKey(ARGUMENT_STATUS)) {
Object statusObj = argMap.get(ARGUMENT_STATUS);
if(statusObj!=null) {
try {
response.setStatus(Integer.parseInt(statusObj.toString()));
}
catch (NumberFormatException e) {
throw new ControllerExecutionException("Argument [status] of method [render] must be a valid integer.");
}
}
}
webRequest.setOut(out);
if (arguments[arguments.length - 1] instanceof Closure) {
Closure callable = (Closure) arguments[arguments.length - 1];
if (BUILDER_TYPE_RICO.equals(argMap.get(ARGUMENT_BUILDER))) {
renderView = renderRico(callable, response);
} else if (BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER)) || isJSONResponse(response)) {
renderView = renderJSON(callable, response);
} else {
renderView = renderMarkup(callable, response);
}
} else if (arguments[arguments.length - 1] instanceof String) {
String text = (String) arguments[arguments.length - 1];
renderView = renderText(text, out);
} else if (argMap.containsKey(ARGUMENT_TEXT)) {
String text = argMap.get(ARGUMENT_TEXT).toString();
renderView = renderText(text, out);
} else if (argMap.containsKey(ARGUMENT_VIEW)) {
renderView(argMap, target, controller);
} else if (argMap.containsKey(ARGUMENT_TEMPLATE)) {
renderView = renderTemplate(target, controller, webRequest, argMap, out);
} else {
Object object = arguments[0];
renderView = renderObject(object, out);
}
try {
if (!renderView) {
out.flush();
}
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments [" + argMap + "]: " + e.getMessage(), e);
}
} else {
throw new MissingMethodException(METHOD_SIGNATURE, target.getClass(), arguments);
}
webRequest.setRenderView(renderView);
return null;
}
|
diff --git a/src/com/zavteam/plugins/RunnableMessager.java b/src/com/zavteam/plugins/RunnableMessager.java
index b292c75..2e8286e 100644
--- a/src/com/zavteam/plugins/RunnableMessager.java
+++ b/src/com/zavteam/plugins/RunnableMessager.java
@@ -1,88 +1,88 @@
package com.zavteam.plugins;
import java.util.Random;
import org.bukkit.ChatColor;
import org.bukkit.util.ChatPaginator;
public class RunnableMessager implements Runnable {
public ZavAutoMessager plugin;
public RunnableMessager(ZavAutoMessager plugin) {
this.plugin = plugin;
}
private int previousMessage;
private static ChatColor[] COLOR_LIST = {ChatColor.AQUA, ChatColor.BLACK, ChatColor.BLUE, ChatColor.DARK_AQUA, ChatColor.DARK_BLUE, ChatColor.DARK_GRAY,
ChatColor.DARK_GREEN, ChatColor.DARK_PURPLE, ChatColor.DARK_RED, ChatColor.GOLD, ChatColor.GRAY, ChatColor.GREEN, ChatColor.LIGHT_PURPLE,
ChatColor.RED, ChatColor.YELLOW};
@Override
public void run() {
boolean messageRandom = (Boolean) plugin.mainConfig.get("messageinrandomorder", false);
if ((Boolean) plugin.mainConfig.get("enabled", true)) {
String[] cutMessageList = new String[10];
if (plugin.messages.size() == 1) {
plugin.messageIt = 0;
} else {
if (messageRandom) {
plugin.messageIt = getRandomMessage();
}
}
ChatMessage cm = null;
try {
cm = plugin.messages.get(plugin.messageIt);
} catch (Exception e) {
e.printStackTrace();
ZavAutoMessager.log.severe("Cannot load messages. There is most likely an error with your config. Please check");
ZavAutoMessager.log.severe("Shutting down plugin.");
plugin.disableZavAutoMessager();
}
if (cm.isCommand()) {
cm.processAsCommand();
if (plugin.messageIt == plugin.messages.size() - 1) {
plugin.messageIt = 0;
} else {
plugin.messageIt = plugin.messageIt + 1;
}
return;
}
cutMessageList[0] = ((String) plugin.mainConfig.get("chatformat", "[&6AutoMessager&f]: %msg")).replace("%msg", cm.getMessage());
cutMessageList[0] = cutMessageList[0].replace("&random", getRandomChatColor());
cutMessageList[0] = ChatColor.translateAlternateColorCodes('&', cutMessageList[0]);
if ((Boolean) plugin.mainConfig.get("wordwrap", true)) {
cutMessageList = cutMessageList[0].split("%n");
} else {
- cutMessageList = ChatPaginator.wordWrap(cutMessageList[0], 59);
+ cutMessageList = ChatPaginator.paginate(cutMessageList[0], 1).getLines();
}
plugin.MessagesHandler.handleChatMessage(cutMessageList, cm);
if (plugin.messageIt == plugin.messages.size() - 1) {
plugin.messageIt = 0;
} else {
plugin.messageIt = plugin.messageIt + 1;
}
}
}
private String getRandomChatColor() {
Random random = new Random();
return COLOR_LIST[random.nextInt(COLOR_LIST.length)].toString();
}
private int getRandomMessage() {
Random random = new Random();
if ((Boolean) plugin.mainConfig.get("dontrepeatrandommessages", true)) {
int i = random.nextInt(plugin.messages.size());
if (!(i == previousMessage)) {
previousMessage = i;
return i;
}
return getRandomMessage();
}
return random.nextInt(plugin.messages.size());
}
}
| true | true |
public void run() {
boolean messageRandom = (Boolean) plugin.mainConfig.get("messageinrandomorder", false);
if ((Boolean) plugin.mainConfig.get("enabled", true)) {
String[] cutMessageList = new String[10];
if (plugin.messages.size() == 1) {
plugin.messageIt = 0;
} else {
if (messageRandom) {
plugin.messageIt = getRandomMessage();
}
}
ChatMessage cm = null;
try {
cm = plugin.messages.get(plugin.messageIt);
} catch (Exception e) {
e.printStackTrace();
ZavAutoMessager.log.severe("Cannot load messages. There is most likely an error with your config. Please check");
ZavAutoMessager.log.severe("Shutting down plugin.");
plugin.disableZavAutoMessager();
}
if (cm.isCommand()) {
cm.processAsCommand();
if (plugin.messageIt == plugin.messages.size() - 1) {
plugin.messageIt = 0;
} else {
plugin.messageIt = plugin.messageIt + 1;
}
return;
}
cutMessageList[0] = ((String) plugin.mainConfig.get("chatformat", "[&6AutoMessager&f]: %msg")).replace("%msg", cm.getMessage());
cutMessageList[0] = cutMessageList[0].replace("&random", getRandomChatColor());
cutMessageList[0] = ChatColor.translateAlternateColorCodes('&', cutMessageList[0]);
if ((Boolean) plugin.mainConfig.get("wordwrap", true)) {
cutMessageList = cutMessageList[0].split("%n");
} else {
cutMessageList = ChatPaginator.wordWrap(cutMessageList[0], 59);
}
plugin.MessagesHandler.handleChatMessage(cutMessageList, cm);
if (plugin.messageIt == plugin.messages.size() - 1) {
plugin.messageIt = 0;
} else {
plugin.messageIt = plugin.messageIt + 1;
}
}
}
|
public void run() {
boolean messageRandom = (Boolean) plugin.mainConfig.get("messageinrandomorder", false);
if ((Boolean) plugin.mainConfig.get("enabled", true)) {
String[] cutMessageList = new String[10];
if (plugin.messages.size() == 1) {
plugin.messageIt = 0;
} else {
if (messageRandom) {
plugin.messageIt = getRandomMessage();
}
}
ChatMessage cm = null;
try {
cm = plugin.messages.get(plugin.messageIt);
} catch (Exception e) {
e.printStackTrace();
ZavAutoMessager.log.severe("Cannot load messages. There is most likely an error with your config. Please check");
ZavAutoMessager.log.severe("Shutting down plugin.");
plugin.disableZavAutoMessager();
}
if (cm.isCommand()) {
cm.processAsCommand();
if (plugin.messageIt == plugin.messages.size() - 1) {
plugin.messageIt = 0;
} else {
plugin.messageIt = plugin.messageIt + 1;
}
return;
}
cutMessageList[0] = ((String) plugin.mainConfig.get("chatformat", "[&6AutoMessager&f]: %msg")).replace("%msg", cm.getMessage());
cutMessageList[0] = cutMessageList[0].replace("&random", getRandomChatColor());
cutMessageList[0] = ChatColor.translateAlternateColorCodes('&', cutMessageList[0]);
if ((Boolean) plugin.mainConfig.get("wordwrap", true)) {
cutMessageList = cutMessageList[0].split("%n");
} else {
cutMessageList = ChatPaginator.paginate(cutMessageList[0], 1).getLines();
}
plugin.MessagesHandler.handleChatMessage(cutMessageList, cm);
if (plugin.messageIt == plugin.messages.size() - 1) {
plugin.messageIt = 0;
} else {
plugin.messageIt = plugin.messageIt + 1;
}
}
}
|
diff --git a/src/java/org/joshy/html/css/TobeRuleBank.java b/src/java/org/joshy/html/css/TobeRuleBank.java
index f881e8cb..7fe8d31f 100644
--- a/src/java/org/joshy/html/css/TobeRuleBank.java
+++ b/src/java/org/joshy/html/css/TobeRuleBank.java
@@ -1,175 +1,180 @@
/*
* TobeRuleBank.java
*
* Created on den 30 juli 2004, 23:15
*/
package org.joshy.html.css;
import org.w3c.css.sac.*;
import net.homelinux.tobe.css.Ruleset;
import net.homelinux.tobe.css.AttributeResolver;
import net.homelinux.tobe.css.StyleMap;
/**
* Tries to make sense of SAC, which is not easy. This might be very wrong because SAC totally SUCKS.
*
* @author Torbj�rn Gannholm
*/
public class TobeRuleBank implements RuleBank {
java.util.List ruleList = new java.util.LinkedList();
StyleMap styleMap;
/** Creates a new instance of TobeRuleBank */
public TobeRuleBank() {
}
public void addRule(JStyle rule) {
Ruleset rs = new Ruleset();
ruleList.add(rs);
rs.addPropertyDeclaration(rule);
for(int i = 0; i < rule.selector_list.getLength(); i++) {
Selector selector = rule.selector_list.item(i);
Selector nextSelector = null;
Condition cond = null;
net.homelinux.tobe.css.Selector s = null;
if(selector.getSelectorType() == Selector.SAC_DIRECT_ADJACENT_SELECTOR) {
nextSelector = selector;
selector = ((SiblingSelector) nextSelector).getSelector();
}
if(selector.getSelectorType() == Selector.SAC_CHILD_SELECTOR) {
nextSelector = selector;
selector = ((DescendantSelector) nextSelector).getAncestorSelector();
}
if(selector.getSelectorType() == Selector.SAC_DESCENDANT_SELECTOR) {
nextSelector = selector;
selector = ((DescendantSelector) nextSelector).getAncestorSelector();
}
if(selector.getSelectorType() == Selector.SAC_CONDITIONAL_SELECTOR) {
cond = ((ConditionalSelector) selector).getCondition();
selector = ((ConditionalSelector) selector).getSimpleSelector();
}
if(selector.getSelectorType() == Selector.SAC_ELEMENT_NODE_SELECTOR) {
s = rs.createSelector(net.homelinux.tobe.css.Selector.DESCENDANT_AXIS, ((ElementSelector) selector).getLocalName());
}
if(cond != null) addConditions(s, cond);
if(nextSelector != null) addChainedSelector(s,nextSelector);
}
}
/** note: not yet implemented evaluating cascade and specificity, we just find a value and that's it */
public org.w3c.dom.css.CSSStyleDeclaration findRule(org.w3c.dom.Element elem, String property, boolean inherit) {
if(styleMap == null) styleMap = StyleMap.createMap(elem.getOwnerDocument(), ruleList, new StaticHtmlAttributeResolver());
java.util.List styleList = styleMap.getMappedProperties(elem);
for(java.util.Iterator i = styleList.iterator(); i.hasNext();) {
JStyle style = (JStyle) i.next();
org.w3c.dom.css.CSSStyleDeclaration dec = style.declaration;
// if the style has the property we want
if(dec != null && dec.getPropertyValue(property) != null &&
!dec.getPropertyValue(property).equals("")) {
return dec;
}
}
//no bite, maybe look at parent?
if(inherit) {
org.w3c.dom.Node parent = elem.getParentNode();
if(parent != null && parent.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE)
return findRule((org.w3c.dom.Element)parent, property, inherit);
}
//no luck?
return null;
}
private void addConditions(net.homelinux.tobe.css.Selector s, Condition cond) {
- AttributeCondition attr = (AttributeCondition) cond;
- CombinatorCondition comb = (CombinatorCondition) cond;
- LangCondition lang = (LangCondition) cond;
- PositionalCondition pos = (PositionalCondition) cond;
switch(cond.getConditionType()) {
case Condition.SAC_AND_CONDITION:
+ CombinatorCondition comb = (CombinatorCondition) cond;
addConditions(s, comb.getFirstCondition());
addConditions(s, comb.getSecondCondition());
break;
case Condition.SAC_ATTRIBUTE_CONDITION:
+ AttributeCondition attr = (AttributeCondition) cond;
if(attr.getSpecified()) {
s.addAttributeEqualsCondition(attr.getLocalName(), attr.getValue());
} else {
s.addAttributeExistsCondition(attr.getLocalName());
}
break;
case Condition.SAC_BEGIN_HYPHEN_ATTRIBUTE_CONDITION:
+ attr = (AttributeCondition) cond;
s.addAttributeMatchesFirstPartCondition(attr.getLocalName(), attr.getValue());
break;
case Condition.SAC_CLASS_CONDITION:
+ attr = (AttributeCondition) cond;
s.addClassCondition(attr.getValue());
break;
case Condition.SAC_ID_CONDITION:
+ attr = (AttributeCondition) cond;
s.addIDCondition(attr.getValue());
break;
case Condition.SAC_LANG_CONDITION:
+ LangCondition lang = (LangCondition) cond;
s.addLangCondition(lang.getLang());
break;
case Condition.SAC_ONE_OF_ATTRIBUTE_CONDITION:
+ attr = (AttributeCondition) cond;
s.addAttributeMatchesListCondition(attr.getLocalName(), attr.getValue());
break;
case Condition.SAC_POSITIONAL_CONDITION:
+ PositionalCondition pos = (PositionalCondition) cond;
s.addFirstChildCondition();
break;
case Condition.SAC_PSEUDO_CLASS_CONDITION:
+ attr = (AttributeCondition) cond;
if(attr.getValue().equals("link")) s.setPseudoClass(AttributeResolver.LINK_PSEUDOCLASS);
if(attr.getValue().equals("visited")) s.setPseudoClass(AttributeResolver.VISITED_PSEUDOCLASS);
if(attr.getValue().equals("hover")) s.setPseudoClass(AttributeResolver.HOVER_PSEUDOCLASS);
if(attr.getValue().equals("active")) s.setPseudoClass(AttributeResolver.ACTIVE_PSEUDOCLASS);
if(attr.getValue().equals("focus")) s.setPseudoClass(AttributeResolver.FOCUS_PSEUDOCLASS);
break;
default:
System.err.println("Bad condition");
}
}
private void addChainedSelector(net.homelinux.tobe.css.Selector s, Selector selector) {
int axis = 0;
switch(selector.getSelectorType()) {
case Selector.SAC_DIRECT_ADJACENT_SELECTOR:
axis = net.homelinux.tobe.css.Selector.IMMEDIATE_SIBLING_AXIS;
selector = ((SiblingSelector) selector).getSiblingSelector();
break;
case Selector.SAC_CHILD_SELECTOR:
axis = net.homelinux.tobe.css.Selector.CHILD_AXIS;
selector = ((DescendantSelector) selector).getSimpleSelector();
break;
case Selector.SAC_DESCENDANT_SELECTOR:
axis = net.homelinux.tobe.css.Selector.DESCENDANT_AXIS;
selector = ((DescendantSelector) selector).getAncestorSelector();
break;
default:
System.err.println("Bad selector");
}
Selector nextSelector = null;
Condition cond = null;
if(selector.getSelectorType() == selector.SAC_DIRECT_ADJACENT_SELECTOR) {
nextSelector = selector;
selector = ((SiblingSelector) nextSelector).getSelector();
}
if(selector.getSelectorType() == selector.SAC_CHILD_SELECTOR) {
nextSelector = selector;
selector = ((DescendantSelector) nextSelector).getAncestorSelector();
}
if(selector.getSelectorType() == selector.SAC_DESCENDANT_SELECTOR) {
nextSelector = selector;
selector = ((DescendantSelector) nextSelector).getAncestorSelector();
}
if(selector.getSelectorType() == selector.SAC_CONDITIONAL_SELECTOR) {
cond = ((ConditionalSelector) selector).getCondition();
selector = ((ConditionalSelector) selector).getSimpleSelector();
}
if(selector.getSelectorType() == selector.SAC_ELEMENT_NODE_SELECTOR) {
s = s.appendChainedSelector(axis, ((ElementSelector) selector).getLocalName());
}
if(cond != null) addConditions(s, cond);
if(nextSelector != null) addChainedSelector(s,nextSelector);
}
}
| false | true |
private void addConditions(net.homelinux.tobe.css.Selector s, Condition cond) {
AttributeCondition attr = (AttributeCondition) cond;
CombinatorCondition comb = (CombinatorCondition) cond;
LangCondition lang = (LangCondition) cond;
PositionalCondition pos = (PositionalCondition) cond;
switch(cond.getConditionType()) {
case Condition.SAC_AND_CONDITION:
addConditions(s, comb.getFirstCondition());
addConditions(s, comb.getSecondCondition());
break;
case Condition.SAC_ATTRIBUTE_CONDITION:
if(attr.getSpecified()) {
s.addAttributeEqualsCondition(attr.getLocalName(), attr.getValue());
} else {
s.addAttributeExistsCondition(attr.getLocalName());
}
break;
case Condition.SAC_BEGIN_HYPHEN_ATTRIBUTE_CONDITION:
s.addAttributeMatchesFirstPartCondition(attr.getLocalName(), attr.getValue());
break;
case Condition.SAC_CLASS_CONDITION:
s.addClassCondition(attr.getValue());
break;
case Condition.SAC_ID_CONDITION:
s.addIDCondition(attr.getValue());
break;
case Condition.SAC_LANG_CONDITION:
s.addLangCondition(lang.getLang());
break;
case Condition.SAC_ONE_OF_ATTRIBUTE_CONDITION:
s.addAttributeMatchesListCondition(attr.getLocalName(), attr.getValue());
break;
case Condition.SAC_POSITIONAL_CONDITION:
s.addFirstChildCondition();
break;
case Condition.SAC_PSEUDO_CLASS_CONDITION:
if(attr.getValue().equals("link")) s.setPseudoClass(AttributeResolver.LINK_PSEUDOCLASS);
if(attr.getValue().equals("visited")) s.setPseudoClass(AttributeResolver.VISITED_PSEUDOCLASS);
if(attr.getValue().equals("hover")) s.setPseudoClass(AttributeResolver.HOVER_PSEUDOCLASS);
if(attr.getValue().equals("active")) s.setPseudoClass(AttributeResolver.ACTIVE_PSEUDOCLASS);
if(attr.getValue().equals("focus")) s.setPseudoClass(AttributeResolver.FOCUS_PSEUDOCLASS);
break;
default:
System.err.println("Bad condition");
}
}
|
private void addConditions(net.homelinux.tobe.css.Selector s, Condition cond) {
switch(cond.getConditionType()) {
case Condition.SAC_AND_CONDITION:
CombinatorCondition comb = (CombinatorCondition) cond;
addConditions(s, comb.getFirstCondition());
addConditions(s, comb.getSecondCondition());
break;
case Condition.SAC_ATTRIBUTE_CONDITION:
AttributeCondition attr = (AttributeCondition) cond;
if(attr.getSpecified()) {
s.addAttributeEqualsCondition(attr.getLocalName(), attr.getValue());
} else {
s.addAttributeExistsCondition(attr.getLocalName());
}
break;
case Condition.SAC_BEGIN_HYPHEN_ATTRIBUTE_CONDITION:
attr = (AttributeCondition) cond;
s.addAttributeMatchesFirstPartCondition(attr.getLocalName(), attr.getValue());
break;
case Condition.SAC_CLASS_CONDITION:
attr = (AttributeCondition) cond;
s.addClassCondition(attr.getValue());
break;
case Condition.SAC_ID_CONDITION:
attr = (AttributeCondition) cond;
s.addIDCondition(attr.getValue());
break;
case Condition.SAC_LANG_CONDITION:
LangCondition lang = (LangCondition) cond;
s.addLangCondition(lang.getLang());
break;
case Condition.SAC_ONE_OF_ATTRIBUTE_CONDITION:
attr = (AttributeCondition) cond;
s.addAttributeMatchesListCondition(attr.getLocalName(), attr.getValue());
break;
case Condition.SAC_POSITIONAL_CONDITION:
PositionalCondition pos = (PositionalCondition) cond;
s.addFirstChildCondition();
break;
case Condition.SAC_PSEUDO_CLASS_CONDITION:
attr = (AttributeCondition) cond;
if(attr.getValue().equals("link")) s.setPseudoClass(AttributeResolver.LINK_PSEUDOCLASS);
if(attr.getValue().equals("visited")) s.setPseudoClass(AttributeResolver.VISITED_PSEUDOCLASS);
if(attr.getValue().equals("hover")) s.setPseudoClass(AttributeResolver.HOVER_PSEUDOCLASS);
if(attr.getValue().equals("active")) s.setPseudoClass(AttributeResolver.ACTIVE_PSEUDOCLASS);
if(attr.getValue().equals("focus")) s.setPseudoClass(AttributeResolver.FOCUS_PSEUDOCLASS);
break;
default:
System.err.println("Bad condition");
}
}
|
diff --git a/illaclient/src/illarion/client/world/interactive/InteractionManager.java b/illaclient/src/illarion/client/world/interactive/InteractionManager.java
index 13e04ef4..9288340b 100644
--- a/illaclient/src/illarion/client/world/interactive/InteractionManager.java
+++ b/illaclient/src/illarion/client/world/interactive/InteractionManager.java
@@ -1,153 +1,145 @@
/*
* This file is part of the Illarion Client.
*
* Copyright © 2011 - Illarion e.V.
*
* The Illarion Client is free software: you can redistribute i and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* The Illarion Client is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* the Illarion Client. If not, see <http://www.gnu.org/licenses/>.
*/
package illarion.client.world.interactive;
import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.builder.ControlBuilder;
import de.lessvoid.nifty.builder.ImageBuilder;
import de.lessvoid.nifty.controls.dragndrop.DraggableControl;
import de.lessvoid.nifty.controls.dragndrop.builder.DraggableBuilder;
import de.lessvoid.nifty.elements.Element;
import de.lessvoid.nifty.elements.render.ImageRenderer;
import de.lessvoid.nifty.input.NiftyMouseInputEvent;
import de.lessvoid.nifty.loaderv2.types.ImageType;
import de.lessvoid.nifty.render.NiftyImage;
import de.lessvoid.nifty.screen.Screen;
import de.lessvoid.nifty.tools.SizeValue;
import illarion.client.graphics.Item;
import illarion.client.gui.EntitySlickRenderImage;
import illarion.client.world.World;
/**
* Main purpose of this class is to interconnect the GUI environment and the map
* environment to exchange informations between both.
*
* @author Martin Karing <[email protected]>
*/
public final class InteractionManager {
private final NiftyMouseInputEvent mouseEvent;
private Draggable draggedObject;
private Element draggedGraphic;
private boolean isDragging;
private Nifty activeNifty;
private Screen activeScreen;
public InteractionManager() {
mouseEvent = new NiftyMouseInputEvent();
}
public void dropAt(final int x, final int y) {
if (draggedObject == null) {
return;
}
final InteractiveMapTile targetTile =
World.getMap().getInteractive()
.getInteractiveTileOnScreenLoc(x, y);
if (targetTile == null) {
return;
}
draggedObject.dragTo(targetTile);
draggedObject = null;
isDragging = false;
cleanDraggedElement();
}
public void startDragging(final Draggable draggable) {
draggedObject = draggable;
isDragging = true;
}
public void setActiveNiftyEnv(final Nifty nifty, final Screen screen) {
activeNifty = nifty;
activeScreen = screen;
}
/**
* @param oldx
* @param oldy
* @param newx
* @param newy
*/
public void notifyDragging(int oldx, int oldy, int newx, int newy) {
if (!isDragging) {
final InteractiveMapTile targetTile =
World.getMap().getInteractive()
.getInteractiveTileOnScreenLoc(oldx, oldy);
if (targetTile == null) {
return;
}
if (!targetTile.canDrag()) {
return;
}
startDragging(targetTile);
cleanDraggedElement();
if (activeScreen != null && activeNifty != null) {
final Item movedItem = targetTile.getTopImage();
final int width = movedItem.getWidth();
final int height = movedItem.getHeight();
draggedGraphic = activeScreen.findElementByName("mapDragObject");
- DraggableControl dragControl = draggedGraphic.getNiftyControl(DraggableControl.class);
draggedGraphic.resetLayout();
draggedGraphic.setConstraintWidth(new SizeValue(Integer.toString(width) + "px"));
draggedGraphic.setConstraintHeight(new SizeValue(Integer.toString(height) + "px"));
draggedGraphic.setConstraintX(new SizeValue(Integer.toString(oldx - width / 2) + "px"));
draggedGraphic.setConstraintY(new SizeValue(Integer.toString(oldy - height / 2) + "px"));
draggedGraphic.setVisible(true);
draggedGraphic.reactivate();
- Element imgElement = draggedGraphic.findElementByName("mapDragImage");
- if (imgElement == null) {
- ImageBuilder imgBuilder = new ImageBuilder("mapDragImage");
- imgBuilder.width(Integer.toString(width) + "px");
- imgBuilder.height(Integer.toString(height) + "px");
- imgBuilder.visible(true);
- imgElement = imgBuilder.build(activeNifty, activeScreen, draggedGraphic);
- }
+ final Element imgElement = draggedGraphic.findElementByName("mapDragImage");
imgElement.setWidth(width);
imgElement.setHeight(height);
final ImageRenderer imgRender = imgElement.getRenderer(ImageRenderer.class);
imgRender.setImage(new NiftyImage(activeNifty.getRenderEngine(), new EntitySlickRenderImage(movedItem)));
activeScreen.layoutLayers();
mouseEvent.initialize(oldx, oldy, 0, true, false, false);
mouseEvent.setButton0InitialDown(true);
activeScreen.mouseEvent(mouseEvent);
mouseEvent.initialize(newx, newy, 0, true, false, false);
activeScreen.mouseEvent(mouseEvent);
}
}
}
private void cleanDraggedElement() {
if (draggedGraphic != null) {
draggedGraphic.setVisible(false);
draggedGraphic = null;
}
}
}
| false | true |
public void notifyDragging(int oldx, int oldy, int newx, int newy) {
if (!isDragging) {
final InteractiveMapTile targetTile =
World.getMap().getInteractive()
.getInteractiveTileOnScreenLoc(oldx, oldy);
if (targetTile == null) {
return;
}
if (!targetTile.canDrag()) {
return;
}
startDragging(targetTile);
cleanDraggedElement();
if (activeScreen != null && activeNifty != null) {
final Item movedItem = targetTile.getTopImage();
final int width = movedItem.getWidth();
final int height = movedItem.getHeight();
draggedGraphic = activeScreen.findElementByName("mapDragObject");
DraggableControl dragControl = draggedGraphic.getNiftyControl(DraggableControl.class);
draggedGraphic.resetLayout();
draggedGraphic.setConstraintWidth(new SizeValue(Integer.toString(width) + "px"));
draggedGraphic.setConstraintHeight(new SizeValue(Integer.toString(height) + "px"));
draggedGraphic.setConstraintX(new SizeValue(Integer.toString(oldx - width / 2) + "px"));
draggedGraphic.setConstraintY(new SizeValue(Integer.toString(oldy - height / 2) + "px"));
draggedGraphic.setVisible(true);
draggedGraphic.reactivate();
Element imgElement = draggedGraphic.findElementByName("mapDragImage");
if (imgElement == null) {
ImageBuilder imgBuilder = new ImageBuilder("mapDragImage");
imgBuilder.width(Integer.toString(width) + "px");
imgBuilder.height(Integer.toString(height) + "px");
imgBuilder.visible(true);
imgElement = imgBuilder.build(activeNifty, activeScreen, draggedGraphic);
}
imgElement.setWidth(width);
imgElement.setHeight(height);
final ImageRenderer imgRender = imgElement.getRenderer(ImageRenderer.class);
imgRender.setImage(new NiftyImage(activeNifty.getRenderEngine(), new EntitySlickRenderImage(movedItem)));
activeScreen.layoutLayers();
mouseEvent.initialize(oldx, oldy, 0, true, false, false);
mouseEvent.setButton0InitialDown(true);
activeScreen.mouseEvent(mouseEvent);
mouseEvent.initialize(newx, newy, 0, true, false, false);
activeScreen.mouseEvent(mouseEvent);
}
}
}
|
public void notifyDragging(int oldx, int oldy, int newx, int newy) {
if (!isDragging) {
final InteractiveMapTile targetTile =
World.getMap().getInteractive()
.getInteractiveTileOnScreenLoc(oldx, oldy);
if (targetTile == null) {
return;
}
if (!targetTile.canDrag()) {
return;
}
startDragging(targetTile);
cleanDraggedElement();
if (activeScreen != null && activeNifty != null) {
final Item movedItem = targetTile.getTopImage();
final int width = movedItem.getWidth();
final int height = movedItem.getHeight();
draggedGraphic = activeScreen.findElementByName("mapDragObject");
draggedGraphic.resetLayout();
draggedGraphic.setConstraintWidth(new SizeValue(Integer.toString(width) + "px"));
draggedGraphic.setConstraintHeight(new SizeValue(Integer.toString(height) + "px"));
draggedGraphic.setConstraintX(new SizeValue(Integer.toString(oldx - width / 2) + "px"));
draggedGraphic.setConstraintY(new SizeValue(Integer.toString(oldy - height / 2) + "px"));
draggedGraphic.setVisible(true);
draggedGraphic.reactivate();
final Element imgElement = draggedGraphic.findElementByName("mapDragImage");
imgElement.setWidth(width);
imgElement.setHeight(height);
final ImageRenderer imgRender = imgElement.getRenderer(ImageRenderer.class);
imgRender.setImage(new NiftyImage(activeNifty.getRenderEngine(), new EntitySlickRenderImage(movedItem)));
activeScreen.layoutLayers();
mouseEvent.initialize(oldx, oldy, 0, true, false, false);
mouseEvent.setButton0InitialDown(true);
activeScreen.mouseEvent(mouseEvent);
mouseEvent.initialize(newx, newy, 0, true, false, false);
activeScreen.mouseEvent(mouseEvent);
}
}
}
|
diff --git a/client/src/es/deusto/weblab/client/WebLabClient.java b/client/src/es/deusto/weblab/client/WebLabClient.java
index 65900e729..e36c18b1a 100644
--- a/client/src/es/deusto/weblab/client/WebLabClient.java
+++ b/client/src/es/deusto/weblab/client/WebLabClient.java
@@ -1,325 +1,325 @@
/*
* Copyright (C) 2005-2009 University of Deusto
* All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution.
*
* This software consists of contributions made by many individuals,
* listed below:
*
* Author: Pablo Orduña <[email protected]>
*
*/
package es.deusto.weblab.client;
import java.util.List;
import java.util.Map;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.RunAsyncCallback;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.ScriptElement;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import es.deusto.weblab.client.admin.comm.IWlAdminCommunication;
import es.deusto.weblab.client.admin.comm.WlAdminCommunication;
import es.deusto.weblab.client.admin.controller.IWlAdminController;
import es.deusto.weblab.client.admin.controller.WlAdminController;
import es.deusto.weblab.client.admin.ui.WlAdminThemeFactory;
import es.deusto.weblab.client.admin.ui.WlAdminThemeFactory.IWlAdminThemeLoadedCallback;
import es.deusto.weblab.client.configuration.ConfigurationManager;
import es.deusto.weblab.client.configuration.IConfigurationLoadedCallback;
import es.deusto.weblab.client.dto.SessionID;
import es.deusto.weblab.client.lab.comm.IWlLabCommunication;
import es.deusto.weblab.client.lab.comm.WlLabCommunication;
import es.deusto.weblab.client.lab.controller.IWlLabController;
import es.deusto.weblab.client.lab.controller.PollingHandler;
import es.deusto.weblab.client.lab.controller.WlLabController;
import es.deusto.weblab.client.lab.experiments.ExperimentFactory;
import es.deusto.weblab.client.lab.ui.WlLabThemeBase;
import es.deusto.weblab.client.lab.ui.WlLabThemeFactory;
import es.deusto.weblab.client.lab.ui.WlLabThemeFactory.IWlLabThemeLoadedCallback;
import es.deusto.weblab.client.ui.widgets.WlWaitingLabel;
public class WebLabClient implements EntryPoint {
private static final String WEBLAB_SESSION_ID_COOKIE = "weblabsessionid";
public static final int MAX_FACEBOOK_WIDTH = 735;
private static final String MAIN_SLOT = "weblab_slot";
private static final String SCRIPT_CONFIG_FILE = GWT.getModuleBaseURL() + "configuration.js";
private static final String SESSION_ID_URL_PARAM = "session_id";
private static final String MOBILE_URL_PARAM = "mobile";
private static final String LOCALE_URL_PARAM = "locale";
private static final String FACEBOOK_URL_PARAM = "facebook";
private static final String ADMIN_URL_PARAM = "admin";
public static final String LOCALE_COOKIE = "weblabdeusto.locale";
private static final String THEME_PROPERTY = "theme";
private static final String DEFAULT_THEME = "deusto";
private static final String GOOGLE_ANALYTICS_TRACKING_CODE = "google.analytics.tracking.code";
private ConfigurationManager configurationManager;
private void putWidget(Widget widget){
while(RootPanel.get(WebLabClient.MAIN_SLOT).getWidgetCount() > 0)
RootPanel.get(WebLabClient.MAIN_SLOT).remove(0);
RootPanel.get(WebLabClient.MAIN_SLOT).add(widget);
}
private void showError(String message){
final Label errorMessage = new Label(message);
this.putWidget(errorMessage);
}
private boolean localeConfigured(){
return Window.Location.getParameter(WebLabClient.LOCALE_URL_PARAM) != null;
}
private boolean isFacebook(){
final String urlSaysIsFacebook = Window.Location.getParameter(WebLabClient.FACEBOOK_URL_PARAM);
return urlSaysIsFacebook != null && (urlSaysIsFacebook.toLowerCase().equals("yes") || urlSaysIsFacebook.toLowerCase().equals("true"));
}
private boolean isMobile(){
final String urlSaysIsMobile = Window.Location.getParameter(WebLabClient.MOBILE_URL_PARAM);
return urlSaysIsMobile != null && (urlSaysIsMobile.toLowerCase().equals("yes") || urlSaysIsMobile.toLowerCase().equals("true"));
}
private boolean wantsAdminApp(){
final String urlSaysWantsAdminApp = Window.Location.getParameter(WebLabClient.ADMIN_URL_PARAM);
return urlSaysWantsAdminApp != null && (urlSaysWantsAdminApp.toLowerCase().equals("yes") || urlSaysWantsAdminApp.toLowerCase().equals("true"));
}
private void selectLanguage(){
final String weblabLocaleCookie = Cookies.getCookie(WebLabClient.LOCALE_COOKIE);
if(weblabLocaleCookie != null && !this.localeConfigured()){
WebLabClient.refresh(weblabLocaleCookie);
}
}
public static void refresh(String locale){
String newUrl = Window.Location.getPath() + "?";
final Map<String, List<String>> parameters = Window.Location.getParameterMap();
for(final String parameter : parameters.keySet())
if(!parameter.equals(WebLabClient.LOCALE_URL_PARAM)){
String value = "";
for(final String v : parameters.get(parameter))
value = v;
newUrl += parameter + "=" + value + "&";
}
newUrl += WebLabClient.LOCALE_URL_PARAM + "=" + locale;
Window.Location.replace(newUrl);
}
public void loadLabApp() {
try{
ExperimentFactory.loadExperiments(WebLabClient.this.configurationManager);
}catch(final Exception e){
WebLabClient.this.showError("Error checking experiments: " + e.getMessage());
e.printStackTrace();
return;
}
final IWlLabCommunication communications = new WlLabCommunication(
WebLabClient.this.configurationManager
);
final PollingHandler pollingHandler = new PollingHandler(
WebLabClient.this.configurationManager
);
final boolean isUsingMobile = this.isMobile();
final IWlLabController controller = new WlLabController(
WebLabClient.this.configurationManager,
communications,
pollingHandler,
isUsingMobile,
isFacebook()
);
if(isFacebook())
RootPanel.get(WebLabClient.MAIN_SLOT).setWidth(MAX_FACEBOOK_WIDTH + "px");
pollingHandler.setController(controller);
final IWlLabThemeLoadedCallback themeLoadedCallback = new IWlLabThemeLoadedCallback() {
@Override
public void onThemeLoaded(WlLabThemeBase theme) {
controller.setUIManager(theme);
try{
final String providedCredentials = Window.Location.getParameter(WebLabClient.SESSION_ID_URL_PARAM);
if(providedCredentials == null)
theme.onInit();
else{
final String sessionId;
final int position = providedCredentials.indexOf(';');
if(position >= 0){
sessionId = providedCredentials.substring(0, position);
final String cookie = providedCredentials.substring(position + 1);
- Cookies.setCookie(WEBLAB_SESSION_ID_COOKIE, cookie);
+ Cookies.setCookie(WEBLAB_SESSION_ID_COOKIE, cookie, null, null, "/", false);
}else
sessionId = providedCredentials;
controller.startLoggedIn(new SessionID(sessionId));
}
}catch(final Exception e){
WebLabClient.this.showError("Error initializing theme: " + e.getMessage());
e.printStackTrace();
return;
}
WebLabClient.this.putWidget(theme.getWidget());
}
@Override
public void onFailure(Throwable e) {
WebLabClient.this.showError("Error creating theme: " + e.getMessage() + "; " + e);
return;
}
};
try {
WlLabThemeFactory.themeFactory(
WebLabClient.this.configurationManager,
controller,
WebLabClient.this.configurationManager.getProperty(
WebLabClient.THEME_PROPERTY,
WebLabClient.DEFAULT_THEME
),
isUsingMobile,
themeLoadedCallback
);
} catch (final Exception e){
this.showError("Error creating theme: " + e.getMessage() + "; " + e);
return;
}
}
public void loadAdminApp() {
final IWlAdminCommunication communications = new WlAdminCommunication(
WebLabClient.this.configurationManager
);
final IWlAdminController controller = new WlAdminController(
WebLabClient.this.configurationManager,
communications
);
final IWlAdminThemeLoadedCallback themeLoadedCallback = new IWlAdminThemeLoadedCallback() {
@Override
public void onThemeLoaded(es.deusto.weblab.client.admin.ui.WlAdminThemeBase theme) {
controller.setUIManager(theme);
try{
final String sessionId = Window.Location.getParameter(WebLabClient.SESSION_ID_URL_PARAM);
theme.onInit();
if(sessionId != null)
controller.startLoggedIn(new SessionID(sessionId));
}catch(final Exception e){
WebLabClient.this.showError("Error initializing theme: " + e.getMessage());
e.printStackTrace();
return;
}
WebLabClient.this.putWidget(theme.getWidget());
}
@Override
public void onFailure(Throwable e) {
WebLabClient.this.showError("Error creating theme: " + e.getMessage() + "; " + e);
return;
}
};
try {
WlAdminThemeFactory.themeFactory(
WebLabClient.this.configurationManager,
controller,
WebLabClient.this.configurationManager.getProperty(
WebLabClient.THEME_PROPERTY,
WebLabClient.DEFAULT_THEME
),
themeLoadedCallback
);
} catch (final Exception e){
this.showError("Error creating theme: " + e.getMessage() + "; " + e);
return;
}
}
@Override
public void onModuleLoad() {
final WlWaitingLabel loadingLabel = new WlWaitingLabel("Loading WebLab-Deusto");
loadingLabel.start();
this.putWidget(loadingLabel.getWidget());
this.selectLanguage();
final String configFile = WebLabClient.SCRIPT_CONFIG_FILE;
this.configurationManager = new ConfigurationManager(configFile, new IConfigurationLoadedCallback(){
@Override
public void onLoaded() {
final String trackingCode = WebLabClient.this.configurationManager.getProperty(GOOGLE_ANALYTICS_TRACKING_CODE, null);
if(trackingCode != null)
loadGoogleAnalytics(trackingCode);
if ( WebLabClient.this.wantsAdminApp() ) {
GWT.runAsync(new RunAsyncCallback() {
@Override
public void onSuccess() {
WebLabClient.this.loadAdminApp();
}
@Override
public void onFailure(Throwable reason) {}
});
} else {
GWT.runAsync(new RunAsyncCallback() {
@Override
public void onSuccess() {
WebLabClient.this.loadLabApp();
}
@Override
public void onFailure(Throwable reason) {}
});
}
}
@Override
public void onFailure(Throwable t) {
WebLabClient.this.showError("Error loading configuration file: " + t.getMessage());
}
});
this.configurationManager.start();
}
private void loadGoogleAnalytics(String trackingCode) {
final ScriptElement gaqScript = Document.get().createScriptElement(
"var _gaq = _gaq || [];" +
"_gaq.push(['_setAccount', '" + trackingCode + "']);" +
"_gaq.push(['_trackPageview']);"
);
final Element s = Document.get().getElementsByTagName("script").getItem(0);
s.getParentNode().insertBefore(gaqScript, s);
final ScriptElement ga = Document.get().createScriptElement();
ga.setSrc(("https:".equals(Window.Location.getProtocol()) ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js");
ga.setType("text/javascript");
ga.setAttribute("async", "true");
s.getParentNode().insertBefore(ga, s);
}
}
| true | true |
public void loadLabApp() {
try{
ExperimentFactory.loadExperiments(WebLabClient.this.configurationManager);
}catch(final Exception e){
WebLabClient.this.showError("Error checking experiments: " + e.getMessage());
e.printStackTrace();
return;
}
final IWlLabCommunication communications = new WlLabCommunication(
WebLabClient.this.configurationManager
);
final PollingHandler pollingHandler = new PollingHandler(
WebLabClient.this.configurationManager
);
final boolean isUsingMobile = this.isMobile();
final IWlLabController controller = new WlLabController(
WebLabClient.this.configurationManager,
communications,
pollingHandler,
isUsingMobile,
isFacebook()
);
if(isFacebook())
RootPanel.get(WebLabClient.MAIN_SLOT).setWidth(MAX_FACEBOOK_WIDTH + "px");
pollingHandler.setController(controller);
final IWlLabThemeLoadedCallback themeLoadedCallback = new IWlLabThemeLoadedCallback() {
@Override
public void onThemeLoaded(WlLabThemeBase theme) {
controller.setUIManager(theme);
try{
final String providedCredentials = Window.Location.getParameter(WebLabClient.SESSION_ID_URL_PARAM);
if(providedCredentials == null)
theme.onInit();
else{
final String sessionId;
final int position = providedCredentials.indexOf(';');
if(position >= 0){
sessionId = providedCredentials.substring(0, position);
final String cookie = providedCredentials.substring(position + 1);
Cookies.setCookie(WEBLAB_SESSION_ID_COOKIE, cookie);
}else
sessionId = providedCredentials;
controller.startLoggedIn(new SessionID(sessionId));
}
}catch(final Exception e){
WebLabClient.this.showError("Error initializing theme: " + e.getMessage());
e.printStackTrace();
return;
}
WebLabClient.this.putWidget(theme.getWidget());
}
@Override
public void onFailure(Throwable e) {
WebLabClient.this.showError("Error creating theme: " + e.getMessage() + "; " + e);
return;
}
};
try {
WlLabThemeFactory.themeFactory(
WebLabClient.this.configurationManager,
controller,
WebLabClient.this.configurationManager.getProperty(
WebLabClient.THEME_PROPERTY,
WebLabClient.DEFAULT_THEME
),
isUsingMobile,
themeLoadedCallback
);
} catch (final Exception e){
this.showError("Error creating theme: " + e.getMessage() + "; " + e);
return;
}
}
|
public void loadLabApp() {
try{
ExperimentFactory.loadExperiments(WebLabClient.this.configurationManager);
}catch(final Exception e){
WebLabClient.this.showError("Error checking experiments: " + e.getMessage());
e.printStackTrace();
return;
}
final IWlLabCommunication communications = new WlLabCommunication(
WebLabClient.this.configurationManager
);
final PollingHandler pollingHandler = new PollingHandler(
WebLabClient.this.configurationManager
);
final boolean isUsingMobile = this.isMobile();
final IWlLabController controller = new WlLabController(
WebLabClient.this.configurationManager,
communications,
pollingHandler,
isUsingMobile,
isFacebook()
);
if(isFacebook())
RootPanel.get(WebLabClient.MAIN_SLOT).setWidth(MAX_FACEBOOK_WIDTH + "px");
pollingHandler.setController(controller);
final IWlLabThemeLoadedCallback themeLoadedCallback = new IWlLabThemeLoadedCallback() {
@Override
public void onThemeLoaded(WlLabThemeBase theme) {
controller.setUIManager(theme);
try{
final String providedCredentials = Window.Location.getParameter(WebLabClient.SESSION_ID_URL_PARAM);
if(providedCredentials == null)
theme.onInit();
else{
final String sessionId;
final int position = providedCredentials.indexOf(';');
if(position >= 0){
sessionId = providedCredentials.substring(0, position);
final String cookie = providedCredentials.substring(position + 1);
Cookies.setCookie(WEBLAB_SESSION_ID_COOKIE, cookie, null, null, "/", false);
}else
sessionId = providedCredentials;
controller.startLoggedIn(new SessionID(sessionId));
}
}catch(final Exception e){
WebLabClient.this.showError("Error initializing theme: " + e.getMessage());
e.printStackTrace();
return;
}
WebLabClient.this.putWidget(theme.getWidget());
}
@Override
public void onFailure(Throwable e) {
WebLabClient.this.showError("Error creating theme: " + e.getMessage() + "; " + e);
return;
}
};
try {
WlLabThemeFactory.themeFactory(
WebLabClient.this.configurationManager,
controller,
WebLabClient.this.configurationManager.getProperty(
WebLabClient.THEME_PROPERTY,
WebLabClient.DEFAULT_THEME
),
isUsingMobile,
themeLoadedCallback
);
} catch (final Exception e){
this.showError("Error creating theme: " + e.getMessage() + "; " + e);
return;
}
}
|
diff --git a/thesis/src/main/java/pls/stats/NumberFolderComparator.java b/thesis/src/main/java/pls/stats/NumberFolderComparator.java
index 6c98717..72b4a3e 100644
--- a/thesis/src/main/java/pls/stats/NumberFolderComparator.java
+++ b/thesis/src/main/java/pls/stats/NumberFolderComparator.java
@@ -1,21 +1,21 @@
package pls.stats;
import java.util.Comparator;
import org.apache.hadoop.fs.FileStatus;
public class NumberFolderComparator implements Comparator<FileStatus> {
@Override
public int compare(FileStatus fs1, FileStatus fs2) {
return (int)Math.signum(getRunNumber(fs1) - getRunNumber(fs2));
}
private long getRunNumber(FileStatus fs) {
String name = fs.getPath().getName();
- if (name.matches("\\s+")) {
+ if (name.matches("\\d+")) {
return Long.parseLong(name);
} else {
return Long.MAX_VALUE;
}
}
}
| true | true |
private long getRunNumber(FileStatus fs) {
String name = fs.getPath().getName();
if (name.matches("\\s+")) {
return Long.parseLong(name);
} else {
return Long.MAX_VALUE;
}
}
|
private long getRunNumber(FileStatus fs) {
String name = fs.getPath().getName();
if (name.matches("\\d+")) {
return Long.parseLong(name);
} else {
return Long.MAX_VALUE;
}
}
|
diff --git a/bridge-impl/src/main/java/com/liferay/faces/bridge/context/map/RequestParameterMapMultiPartImpl.java b/bridge-impl/src/main/java/com/liferay/faces/bridge/context/map/RequestParameterMapMultiPartImpl.java
index 75266eb87..28c118610 100644
--- a/bridge-impl/src/main/java/com/liferay/faces/bridge/context/map/RequestParameterMapMultiPartImpl.java
+++ b/bridge-impl/src/main/java/com/liferay/faces/bridge/context/map/RequestParameterMapMultiPartImpl.java
@@ -1,654 +1,656 @@
/**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.faces.bridge.context.map;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.faces.render.ResponseStateManager;
import javax.portlet.ActionRequest;
import javax.portlet.ClientDataRequest;
import javax.portlet.PortalContext;
import javax.portlet.PortletMode;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletSession;
import javax.portlet.ResourceRequest;
import javax.portlet.WindowState;
import javax.servlet.http.Cookie;
import org.apache.commons.fileupload.FileItemHeaders;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.InvalidFileNameException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.portlet.PortletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FileUtils;
import com.liferay.faces.bridge.BridgeFactoryFinder;
import com.liferay.faces.bridge.config.BridgeConfigConstants;
import com.liferay.faces.bridge.container.PortletContainer;
import com.liferay.faces.bridge.context.BridgeContext;
import com.liferay.faces.bridge.model.UploadedFile;
import com.liferay.faces.bridge.model.UploadedFileFactory;
import com.liferay.faces.util.helper.BooleanHelper;
import com.liferay.faces.util.logging.Logger;
import com.liferay.faces.util.logging.LoggerFactory;
import com.liferay.faces.util.map.AbstractPropertyMapEntry;
import com.liferay.portal.kernel.util.StringPool;
/**
* @author Neil Griffin
*/
public class RequestParameterMapMultiPartImpl extends RequestParameterMap {
// Logger
private static final Logger logger = LoggerFactory.getLogger(RequestParameterMapMultiPartImpl.class);
// Private Constants
private static final String CONTEXT_PARAM_UPLOADED_FILES_DIR = "javax.faces.UPLOADED_FILES_DIR";
private static final String CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE = "javax.faces.UPLOADED_FILE_MAX_SIZE";
private static final String JAVA_IO_TMPDIR = "java.io.tmpdir";
private static final int DEFAULT_FILE_MAX_SIZE = 104857600; // 100MB
// Private Data Members
private Map<String, String> requestParameterMap;
private Map<String, List<UploadedFile>> requestParameterFileMap;
@SuppressWarnings("unchecked")
public RequestParameterMapMultiPartImpl(BridgeContext bridgeContext, ClientDataRequest clientDataRequest) {
try {
PortletSession portletSession = clientDataRequest.getPortletSession();
// Determine the uploaded files directory path according to the JSF 2.2 proposal:
// https://javaserverfaces-spec-public.dev.java.net/issues/show_bug.cgi?id=690
String uploadedFilesDir = bridgeContext.getInitParameter(CONTEXT_PARAM_UPLOADED_FILES_DIR);
if (uploadedFilesDir == null) {
uploadedFilesDir = System.getProperty(JAVA_IO_TMPDIR);
if (logger.isDebugEnabled()) {
logger.debug(
"The web.xml context-param name=[{0}] not found, using default system property=[{1}] value=[{2}]",
new Object[] { CONTEXT_PARAM_UPLOADED_FILES_DIR, JAVA_IO_TMPDIR, uploadedFilesDir });
}
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Using web.xml context-param name=[{0}] value=[{1}]",
new Object[] { CONTEXT_PARAM_UPLOADED_FILES_DIR, uploadedFilesDir });
}
}
// Using the portlet sessionId, determine a unique folder path and create the path if it does not exist.
String sessionId = portletSession.getId();
// FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be
// created properly.
sessionId = sessionId.replaceAll("[^A-Za-z0-9]", StringPool.BLANK);
File uploadedFilesPath = new File(uploadedFilesDir, sessionId);
if (!uploadedFilesPath.exists()) {
try {
uploadedFilesPath.mkdirs();
}
catch (SecurityException e) {
uploadedFilesDir = System.getProperty(JAVA_IO_TMPDIR);
logger.error(
"Security exception message=[{0}] when trying to create unique path=[{1}] so using default system property=[{2}] value=[{3}]",
new Object[] { e.getMessage(), uploadedFilesPath.toString(), JAVA_IO_TMPDIR, uploadedFilesDir });
uploadedFilesPath = new File(uploadedFilesDir, sessionId);
uploadedFilesPath.mkdirs();
}
}
// Initialize commons-fileupload with the file upload path.
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
diskFileItemFactory.setRepository(uploadedFilesPath);
// Initialize commons-fileupload so that uploaded temporary files are not automatically deleted.
diskFileItemFactory.setFileCleaningTracker(null);
// Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk
// instead of staying in memory.
diskFileItemFactory.setSizeThreshold(0);
// Determine the max file upload size threshold in bytes.
String uploadedFilesMaxSize = bridgeContext.getInitParameter(CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE);
int fileMaxSize = DEFAULT_FILE_MAX_SIZE;
if (uploadedFilesMaxSize == null) {
if (logger.isDebugEnabled()) {
logger.debug("The web.xml context-param name=[{0}] not found, using default=[{1}] bytes",
new Object[] { CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, DEFAULT_FILE_MAX_SIZE });
}
}
else {
try {
fileMaxSize = Integer.parseInt(uploadedFilesMaxSize);
if (logger.isDebugEnabled()) {
logger.debug("Using web.xml context-param name=[{0}] value=[{1}] bytes",
new Object[] { CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, fileMaxSize });
}
}
catch (NumberFormatException e) {
logger.error("Invalid value=[{0}] for web.xml context-param name=[{1}] using default=[{2}] bytes.",
new Object[] {
uploadedFilesMaxSize, CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, DEFAULT_FILE_MAX_SIZE
});
}
}
// Parse the request parameters and save all uploaded files in a map.
PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory);
portletFileUpload.setFileSizeMax(fileMaxSize);
requestParameterMap = new HashMap<String, String>();
requestParameterFileMap = new HashMap<String, List<UploadedFile>>();
// Get the namespace that might be found in request parameter names.
String namespace = bridgeContext.getPortletContainer().getResponseNamespace();
// FACES-271: Include name+value pairs found in the ActionRequest.
PortletContainer portletContainer = bridgeContext.getPortletContainer();
Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet();
for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) {
String parameterName = mapEntry.getKey();
int pos = parameterName.indexOf(namespace);
if (pos >= 0) {
parameterName = parameterName.substring(pos + namespace.length());
}
String[] parameterValues = mapEntry.getValue();
if (parameterValues.length > 0) {
String fixedRequestParameterValue = portletContainer.fixRequestParameterValue(parameterValues[0]);
requestParameterMap.put(parameterName, fixedRequestParameterValue);
logger.debug("Found in ActionRequest: {0}=[{1}]", parameterName, fixedRequestParameterValue);
}
}
UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) BridgeFactoryFinder.getFactory(
UploadedFileFactory.class);
// Begin parsing the request for file parts:
try {
FileItemIterator fileItemIterator = null;
if (clientDataRequest instanceof ResourceRequest) {
ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest;
fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest));
}
else {
ActionRequest actionRequest = (ActionRequest) clientDataRequest;
fileItemIterator = portletFileUpload.getItemIterator(actionRequest);
}
boolean optimizeNamespace = BooleanHelper.toBoolean(bridgeContext.getInitParameter(
BridgeConfigConstants.PARAM_OPTIMIZE_PORTLET_NAMESPACE1), true);
if (fileItemIterator != null) {
int totalFiles = 0;
// For each field found in the request:
while (fileItemIterator.hasNext()) {
try {
totalFiles++;
// Get the stream of field data from the request.
FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();
// Get field name from the field stream.
String fieldName = fieldStream.getFieldName();
// If namespace optimization is enabled and the namespace is present in the field name,
// then remove the portlet namespace from the field name.
if (optimizeNamespace) {
int pos = fieldName.indexOf(namespace);
if (pos >= 0) {
fieldName = fieldName.substring(pos + namespace.length());
}
}
// Get the content-type, and file-name from the field stream.
String contentType = fieldStream.getContentType();
boolean formField = fieldStream.isFormField();
String fileName = null;
try {
fileName = fieldStream.getName();
}
catch (InvalidFileNameException e) {
fileName = e.getName();
}
// Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
// current field is a simple form-field because the call below to diskFileItem.getString()
// will fail otherwise.
DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
contentType, formField, fileName);
Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);
// If the current field is a simple form-field, then save the form field value in the map.
if (diskFileItem.isFormField()) {
String characterEncoding = clientDataRequest.getCharacterEncoding();
String requestParameterValue = null;
if (characterEncoding == null) {
requestParameterValue = diskFileItem.getString();
}
else {
requestParameterValue = diskFileItem.getString(characterEncoding);
}
String fixedRequestParameterValue = portletContainer.fixRequestParameterValue(
requestParameterValue);
requestParameterMap.put(fieldName, fixedRequestParameterValue);
logger.debug("{0}=[{1}]", fieldName, fixedRequestParameterValue);
}
else {
File tempFile = diskFileItem.getStoreLocation();
// If the copy was successful, then
if (tempFile.exists()) {
// Copy the commons-fileupload temporary file to a file in the same temporary
// location, but with the filename provided by the user in the upload. This has two
// benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
// the file, the developer can have access to a semi-permanent file, because the
// commmons-fileupload DiskFileItem.finalize() method automatically deletes the
// temporary one.
String tempFileName = tempFile.getName();
String tempFileAbsolutePath = tempFile.getAbsolutePath();
String copiedFileName = stripIllegalCharacters(fileName);
String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
copiedFileName);
File copiedFile = new File(copiedFileAbsolutePath);
FileUtils.copyFile(tempFile, copiedFile);
// If present, build up a map of headers.
Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
FileItemHeaders fileItemHeaders = fieldStream.getHeaders();
if (fileItemHeaders != null) {
Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();
if (headerNameItr != null) {
while (headerNameItr.hasNext()) {
String headerName = headerNameItr.next();
Iterator<String> headerValuesItr = fileItemHeaders.getHeaders(
headerName);
List<String> headerValues = new ArrayList<String>();
if (headerValuesItr != null) {
while (headerValuesItr.hasNext()) {
String headerValue = headerValuesItr.next();
headerValues.add(headerValue);
}
}
headersMap.put(headerName, headerValues);
}
}
}
// Put a valid UploadedFile instance into the map that contains all of the
// uploaded file's attributes, along with a successful status.
Map<String, Object> attributeMap = new HashMap<String, Object>();
String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
String message = null;
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(
copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(),
diskFileItem.getContentType(), headersMap, id, message, fileName,
diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED);
requestParameterMap.put(fieldName, copiedFileAbsolutePath);
addUploadedFile(fieldName, uploadedFile);
logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
fileName);
}
else {
- Exception e = new IOException(
- "Failed to copy the stream of file data to a temporary file");
- UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
- addUploadedFile(fieldName, uploadedFile);
+ if ((fileName != null) && (fileName.trim().length() > 0)) {
+ Exception e = new IOException(
+ "Failed to copy the stream of uploaded file=[" + fileName + "] to a temporary file (possibly a zero-length uploaded file)");
+ UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
+ addUploadedFile(fieldName, uploadedFile);
+ }
}
}
}
catch (Exception e) {
logger.error(e);
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
String fieldName = Integer.toString(totalFiles);
addUploadedFile(fieldName, uploadedFile);
}
}
}
}
// If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in
// the map so that the developer can have some idea that something went wrong.
catch (Exception e) {
logger.error(e);
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
addUploadedFile("unknown", uploadedFile);
}
clientDataRequest.setAttribute(PARAM_UPLOADED_FILES, requestParameterFileMap);
// If not found in the request, Section 6.9 of the Bridge spec requires that the value of the
// ResponseStateManager.RENDER_KIT_ID_PARAM request parameter be set to the value of the
// "javax.portlet.faces.<portletName>.defaultRenderKitId" PortletContext attribute.
String renderKitIdParam = requestParameterMap.get(ResponseStateManager.RENDER_KIT_ID_PARAM);
if (renderKitIdParam == null) {
renderKitIdParam = bridgeContext.getDefaultRenderKitId();
if (renderKitIdParam != null) {
requestParameterMap.put(ResponseStateManager.RENDER_KIT_ID_PARAM, renderKitIdParam);
}
}
}
catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
protected void addUploadedFile(String fieldName, UploadedFile uploadedFile) {
List<UploadedFile> uploadedFiles = requestParameterFileMap.get(fieldName);
if (uploadedFiles == null) {
uploadedFiles = new ArrayList<UploadedFile>();
requestParameterFileMap.put(fieldName, uploadedFiles);
}
uploadedFiles.add(uploadedFile);
}
@Override
protected AbstractPropertyMapEntry<String> createPropertyMapEntry(String name) {
return new RequestParameterMapEntryMultiPart(name, requestParameterMap);
}
@Override
protected void removeProperty(String name) {
throw new UnsupportedOperationException();
}
protected String stripIllegalCharacters(String fileName) {
// FACES-64: Need to strip out invalid characters.
// http://technet.microsoft.com/en-us/library/cc956689.aspx
String strippedFileName = fileName;
if (fileName != null) {
strippedFileName = fileName.replaceAll("[\\\\/\\[\\]:|<>+;=.?\"]", "-");
}
return strippedFileName;
}
@Override
protected String getProperty(String name) {
return requestParameterMap.get(name);
}
@Override
protected void setProperty(String name, String value) {
throw new UnsupportedOperationException();
}
@Override
protected Enumeration<String> getPropertyNames() {
// Note#1: Section 6.9 of the Bridge spec requires that a parameter name be added to the return value of
// ExternalContext.getRequestParameterNames() for ResponseStateManager.RENDER_KIT_ID_PARAM. This will
// automatically be the case because this class builds up its own internal requestParameterMap in the
// constructor that will contain the ResponseStateManager.RENDER_KIT_ID_PARAM if required.
// Note#2: This can't be cached because the caller basically wants a new enumeration to iterate over each time.
return Collections.enumeration(requestParameterMap.keySet());
}
/**
* Since {@link PortletFileUpload#parseRequest(ActionRequest)} only works with {@link ActionRequest}, this adapter
* class is necessary to force commons-fileupload to work with ResourceRequest (Ajax file upload).
*
* @author Neil Griffin
*/
protected class ActionRequestAdapter implements ActionRequest {
private ResourceRequest resourceRequest;
public ActionRequestAdapter(ResourceRequest resourceRequest) {
this.resourceRequest = resourceRequest;
}
public void removeAttribute(String name) {
resourceRequest.removeAttribute(name);
}
public Object getAttribute(String name) {
return resourceRequest.getAttribute(name);
}
public void setAttribute(String name, Object value) {
resourceRequest.setAttribute(name, value);
}
public Enumeration<String> getAttributeNames() {
return resourceRequest.getAttributeNames();
}
public String getAuthType() {
return resourceRequest.getAuthType();
}
public String getCharacterEncoding() {
return resourceRequest.getCharacterEncoding();
}
public void setCharacterEncoding(String enc) throws UnsupportedEncodingException {
resourceRequest.setCharacterEncoding(enc);
}
public int getContentLength() {
return resourceRequest.getContentLength();
}
public String getContentType() {
return resourceRequest.getContentType();
}
public String getContextPath() {
return resourceRequest.getContextPath();
}
public Cookie[] getCookies() {
return resourceRequest.getCookies();
}
public boolean isPortletModeAllowed(PortletMode mode) {
return resourceRequest.isPortletModeAllowed(mode);
}
public boolean isRequestedSessionIdValid() {
return resourceRequest.isRequestedSessionIdValid();
}
public boolean isWindowStateAllowed(WindowState state) {
return resourceRequest.isWindowStateAllowed(state);
}
public boolean isSecure() {
return resourceRequest.isSecure();
}
public boolean isUserInRole(String role) {
return resourceRequest.isUserInRole(role);
}
public Locale getLocale() {
return resourceRequest.getLocale();
}
public Enumeration<Locale> getLocales() {
return resourceRequest.getLocales();
}
public String getMethod() {
return resourceRequest.getMethod();
}
public String getParameter(String name) {
return resourceRequest.getParameter(name);
}
public Map<String, String[]> getParameterMap() {
return resourceRequest.getParameterMap();
}
public Enumeration<String> getParameterNames() {
return resourceRequest.getParameterNames();
}
public String[] getParameterValues(String name) {
return resourceRequest.getParameterValues(name);
}
public PortalContext getPortalContext() {
return resourceRequest.getPortalContext();
}
public InputStream getPortletInputStream() throws IOException {
return resourceRequest.getPortletInputStream();
}
public PortletMode getPortletMode() {
return resourceRequest.getPortletMode();
}
public PortletSession getPortletSession() {
return resourceRequest.getPortletSession();
}
public PortletSession getPortletSession(boolean create) {
return resourceRequest.getPortletSession();
}
public PortletPreferences getPreferences() {
return resourceRequest.getPreferences();
}
public Map<String, String[]> getPrivateParameterMap() {
return resourceRequest.getPrivateParameterMap();
}
public Enumeration<String> getProperties(String name) {
return resourceRequest.getProperties(name);
}
public String getProperty(String name) {
return resourceRequest.getProperty(name);
}
public Enumeration<String> getPropertyNames() {
return resourceRequest.getPropertyNames();
}
public Map<String, String[]> getPublicParameterMap() {
return resourceRequest.getPublicParameterMap();
}
public BufferedReader getReader() throws UnsupportedEncodingException, IOException {
return resourceRequest.getReader();
}
public String getRemoteUser() {
return resourceRequest.getRemoteUser();
}
public String getRequestedSessionId() {
return resourceRequest.getRequestedSessionId();
}
public String getResponseContentType() {
return resourceRequest.getResponseContentType();
}
public Enumeration<String> getResponseContentTypes() {
return resourceRequest.getResponseContentTypes();
}
public String getScheme() {
return resourceRequest.getScheme();
}
public String getServerName() {
return resourceRequest.getServerName();
}
public int getServerPort() {
return resourceRequest.getServerPort();
}
public Principal getUserPrincipal() {
return resourceRequest.getUserPrincipal();
}
public String getWindowID() {
return resourceRequest.getWindowID();
}
public WindowState getWindowState() {
return resourceRequest.getWindowState();
}
}
}
| true | true |
public RequestParameterMapMultiPartImpl(BridgeContext bridgeContext, ClientDataRequest clientDataRequest) {
try {
PortletSession portletSession = clientDataRequest.getPortletSession();
// Determine the uploaded files directory path according to the JSF 2.2 proposal:
// https://javaserverfaces-spec-public.dev.java.net/issues/show_bug.cgi?id=690
String uploadedFilesDir = bridgeContext.getInitParameter(CONTEXT_PARAM_UPLOADED_FILES_DIR);
if (uploadedFilesDir == null) {
uploadedFilesDir = System.getProperty(JAVA_IO_TMPDIR);
if (logger.isDebugEnabled()) {
logger.debug(
"The web.xml context-param name=[{0}] not found, using default system property=[{1}] value=[{2}]",
new Object[] { CONTEXT_PARAM_UPLOADED_FILES_DIR, JAVA_IO_TMPDIR, uploadedFilesDir });
}
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Using web.xml context-param name=[{0}] value=[{1}]",
new Object[] { CONTEXT_PARAM_UPLOADED_FILES_DIR, uploadedFilesDir });
}
}
// Using the portlet sessionId, determine a unique folder path and create the path if it does not exist.
String sessionId = portletSession.getId();
// FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be
// created properly.
sessionId = sessionId.replaceAll("[^A-Za-z0-9]", StringPool.BLANK);
File uploadedFilesPath = new File(uploadedFilesDir, sessionId);
if (!uploadedFilesPath.exists()) {
try {
uploadedFilesPath.mkdirs();
}
catch (SecurityException e) {
uploadedFilesDir = System.getProperty(JAVA_IO_TMPDIR);
logger.error(
"Security exception message=[{0}] when trying to create unique path=[{1}] so using default system property=[{2}] value=[{3}]",
new Object[] { e.getMessage(), uploadedFilesPath.toString(), JAVA_IO_TMPDIR, uploadedFilesDir });
uploadedFilesPath = new File(uploadedFilesDir, sessionId);
uploadedFilesPath.mkdirs();
}
}
// Initialize commons-fileupload with the file upload path.
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
diskFileItemFactory.setRepository(uploadedFilesPath);
// Initialize commons-fileupload so that uploaded temporary files are not automatically deleted.
diskFileItemFactory.setFileCleaningTracker(null);
// Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk
// instead of staying in memory.
diskFileItemFactory.setSizeThreshold(0);
// Determine the max file upload size threshold in bytes.
String uploadedFilesMaxSize = bridgeContext.getInitParameter(CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE);
int fileMaxSize = DEFAULT_FILE_MAX_SIZE;
if (uploadedFilesMaxSize == null) {
if (logger.isDebugEnabled()) {
logger.debug("The web.xml context-param name=[{0}] not found, using default=[{1}] bytes",
new Object[] { CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, DEFAULT_FILE_MAX_SIZE });
}
}
else {
try {
fileMaxSize = Integer.parseInt(uploadedFilesMaxSize);
if (logger.isDebugEnabled()) {
logger.debug("Using web.xml context-param name=[{0}] value=[{1}] bytes",
new Object[] { CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, fileMaxSize });
}
}
catch (NumberFormatException e) {
logger.error("Invalid value=[{0}] for web.xml context-param name=[{1}] using default=[{2}] bytes.",
new Object[] {
uploadedFilesMaxSize, CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, DEFAULT_FILE_MAX_SIZE
});
}
}
// Parse the request parameters and save all uploaded files in a map.
PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory);
portletFileUpload.setFileSizeMax(fileMaxSize);
requestParameterMap = new HashMap<String, String>();
requestParameterFileMap = new HashMap<String, List<UploadedFile>>();
// Get the namespace that might be found in request parameter names.
String namespace = bridgeContext.getPortletContainer().getResponseNamespace();
// FACES-271: Include name+value pairs found in the ActionRequest.
PortletContainer portletContainer = bridgeContext.getPortletContainer();
Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet();
for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) {
String parameterName = mapEntry.getKey();
int pos = parameterName.indexOf(namespace);
if (pos >= 0) {
parameterName = parameterName.substring(pos + namespace.length());
}
String[] parameterValues = mapEntry.getValue();
if (parameterValues.length > 0) {
String fixedRequestParameterValue = portletContainer.fixRequestParameterValue(parameterValues[0]);
requestParameterMap.put(parameterName, fixedRequestParameterValue);
logger.debug("Found in ActionRequest: {0}=[{1}]", parameterName, fixedRequestParameterValue);
}
}
UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) BridgeFactoryFinder.getFactory(
UploadedFileFactory.class);
// Begin parsing the request for file parts:
try {
FileItemIterator fileItemIterator = null;
if (clientDataRequest instanceof ResourceRequest) {
ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest;
fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest));
}
else {
ActionRequest actionRequest = (ActionRequest) clientDataRequest;
fileItemIterator = portletFileUpload.getItemIterator(actionRequest);
}
boolean optimizeNamespace = BooleanHelper.toBoolean(bridgeContext.getInitParameter(
BridgeConfigConstants.PARAM_OPTIMIZE_PORTLET_NAMESPACE1), true);
if (fileItemIterator != null) {
int totalFiles = 0;
// For each field found in the request:
while (fileItemIterator.hasNext()) {
try {
totalFiles++;
// Get the stream of field data from the request.
FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();
// Get field name from the field stream.
String fieldName = fieldStream.getFieldName();
// If namespace optimization is enabled and the namespace is present in the field name,
// then remove the portlet namespace from the field name.
if (optimizeNamespace) {
int pos = fieldName.indexOf(namespace);
if (pos >= 0) {
fieldName = fieldName.substring(pos + namespace.length());
}
}
// Get the content-type, and file-name from the field stream.
String contentType = fieldStream.getContentType();
boolean formField = fieldStream.isFormField();
String fileName = null;
try {
fileName = fieldStream.getName();
}
catch (InvalidFileNameException e) {
fileName = e.getName();
}
// Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
// current field is a simple form-field because the call below to diskFileItem.getString()
// will fail otherwise.
DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
contentType, formField, fileName);
Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);
// If the current field is a simple form-field, then save the form field value in the map.
if (diskFileItem.isFormField()) {
String characterEncoding = clientDataRequest.getCharacterEncoding();
String requestParameterValue = null;
if (characterEncoding == null) {
requestParameterValue = diskFileItem.getString();
}
else {
requestParameterValue = diskFileItem.getString(characterEncoding);
}
String fixedRequestParameterValue = portletContainer.fixRequestParameterValue(
requestParameterValue);
requestParameterMap.put(fieldName, fixedRequestParameterValue);
logger.debug("{0}=[{1}]", fieldName, fixedRequestParameterValue);
}
else {
File tempFile = diskFileItem.getStoreLocation();
// If the copy was successful, then
if (tempFile.exists()) {
// Copy the commons-fileupload temporary file to a file in the same temporary
// location, but with the filename provided by the user in the upload. This has two
// benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
// the file, the developer can have access to a semi-permanent file, because the
// commmons-fileupload DiskFileItem.finalize() method automatically deletes the
// temporary one.
String tempFileName = tempFile.getName();
String tempFileAbsolutePath = tempFile.getAbsolutePath();
String copiedFileName = stripIllegalCharacters(fileName);
String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
copiedFileName);
File copiedFile = new File(copiedFileAbsolutePath);
FileUtils.copyFile(tempFile, copiedFile);
// If present, build up a map of headers.
Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
FileItemHeaders fileItemHeaders = fieldStream.getHeaders();
if (fileItemHeaders != null) {
Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();
if (headerNameItr != null) {
while (headerNameItr.hasNext()) {
String headerName = headerNameItr.next();
Iterator<String> headerValuesItr = fileItemHeaders.getHeaders(
headerName);
List<String> headerValues = new ArrayList<String>();
if (headerValuesItr != null) {
while (headerValuesItr.hasNext()) {
String headerValue = headerValuesItr.next();
headerValues.add(headerValue);
}
}
headersMap.put(headerName, headerValues);
}
}
}
// Put a valid UploadedFile instance into the map that contains all of the
// uploaded file's attributes, along with a successful status.
Map<String, Object> attributeMap = new HashMap<String, Object>();
String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
String message = null;
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(
copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(),
diskFileItem.getContentType(), headersMap, id, message, fileName,
diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED);
requestParameterMap.put(fieldName, copiedFileAbsolutePath);
addUploadedFile(fieldName, uploadedFile);
logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
fileName);
}
else {
Exception e = new IOException(
"Failed to copy the stream of file data to a temporary file");
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
addUploadedFile(fieldName, uploadedFile);
}
}
}
catch (Exception e) {
logger.error(e);
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
String fieldName = Integer.toString(totalFiles);
addUploadedFile(fieldName, uploadedFile);
}
}
}
}
// If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in
// the map so that the developer can have some idea that something went wrong.
catch (Exception e) {
logger.error(e);
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
addUploadedFile("unknown", uploadedFile);
}
clientDataRequest.setAttribute(PARAM_UPLOADED_FILES, requestParameterFileMap);
// If not found in the request, Section 6.9 of the Bridge spec requires that the value of the
// ResponseStateManager.RENDER_KIT_ID_PARAM request parameter be set to the value of the
// "javax.portlet.faces.<portletName>.defaultRenderKitId" PortletContext attribute.
String renderKitIdParam = requestParameterMap.get(ResponseStateManager.RENDER_KIT_ID_PARAM);
if (renderKitIdParam == null) {
renderKitIdParam = bridgeContext.getDefaultRenderKitId();
if (renderKitIdParam != null) {
requestParameterMap.put(ResponseStateManager.RENDER_KIT_ID_PARAM, renderKitIdParam);
}
}
}
catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
|
public RequestParameterMapMultiPartImpl(BridgeContext bridgeContext, ClientDataRequest clientDataRequest) {
try {
PortletSession portletSession = clientDataRequest.getPortletSession();
// Determine the uploaded files directory path according to the JSF 2.2 proposal:
// https://javaserverfaces-spec-public.dev.java.net/issues/show_bug.cgi?id=690
String uploadedFilesDir = bridgeContext.getInitParameter(CONTEXT_PARAM_UPLOADED_FILES_DIR);
if (uploadedFilesDir == null) {
uploadedFilesDir = System.getProperty(JAVA_IO_TMPDIR);
if (logger.isDebugEnabled()) {
logger.debug(
"The web.xml context-param name=[{0}] not found, using default system property=[{1}] value=[{2}]",
new Object[] { CONTEXT_PARAM_UPLOADED_FILES_DIR, JAVA_IO_TMPDIR, uploadedFilesDir });
}
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Using web.xml context-param name=[{0}] value=[{1}]",
new Object[] { CONTEXT_PARAM_UPLOADED_FILES_DIR, uploadedFilesDir });
}
}
// Using the portlet sessionId, determine a unique folder path and create the path if it does not exist.
String sessionId = portletSession.getId();
// FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be
// created properly.
sessionId = sessionId.replaceAll("[^A-Za-z0-9]", StringPool.BLANK);
File uploadedFilesPath = new File(uploadedFilesDir, sessionId);
if (!uploadedFilesPath.exists()) {
try {
uploadedFilesPath.mkdirs();
}
catch (SecurityException e) {
uploadedFilesDir = System.getProperty(JAVA_IO_TMPDIR);
logger.error(
"Security exception message=[{0}] when trying to create unique path=[{1}] so using default system property=[{2}] value=[{3}]",
new Object[] { e.getMessage(), uploadedFilesPath.toString(), JAVA_IO_TMPDIR, uploadedFilesDir });
uploadedFilesPath = new File(uploadedFilesDir, sessionId);
uploadedFilesPath.mkdirs();
}
}
// Initialize commons-fileupload with the file upload path.
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
diskFileItemFactory.setRepository(uploadedFilesPath);
// Initialize commons-fileupload so that uploaded temporary files are not automatically deleted.
diskFileItemFactory.setFileCleaningTracker(null);
// Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk
// instead of staying in memory.
diskFileItemFactory.setSizeThreshold(0);
// Determine the max file upload size threshold in bytes.
String uploadedFilesMaxSize = bridgeContext.getInitParameter(CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE);
int fileMaxSize = DEFAULT_FILE_MAX_SIZE;
if (uploadedFilesMaxSize == null) {
if (logger.isDebugEnabled()) {
logger.debug("The web.xml context-param name=[{0}] not found, using default=[{1}] bytes",
new Object[] { CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, DEFAULT_FILE_MAX_SIZE });
}
}
else {
try {
fileMaxSize = Integer.parseInt(uploadedFilesMaxSize);
if (logger.isDebugEnabled()) {
logger.debug("Using web.xml context-param name=[{0}] value=[{1}] bytes",
new Object[] { CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, fileMaxSize });
}
}
catch (NumberFormatException e) {
logger.error("Invalid value=[{0}] for web.xml context-param name=[{1}] using default=[{2}] bytes.",
new Object[] {
uploadedFilesMaxSize, CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, DEFAULT_FILE_MAX_SIZE
});
}
}
// Parse the request parameters and save all uploaded files in a map.
PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory);
portletFileUpload.setFileSizeMax(fileMaxSize);
requestParameterMap = new HashMap<String, String>();
requestParameterFileMap = new HashMap<String, List<UploadedFile>>();
// Get the namespace that might be found in request parameter names.
String namespace = bridgeContext.getPortletContainer().getResponseNamespace();
// FACES-271: Include name+value pairs found in the ActionRequest.
PortletContainer portletContainer = bridgeContext.getPortletContainer();
Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet();
for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) {
String parameterName = mapEntry.getKey();
int pos = parameterName.indexOf(namespace);
if (pos >= 0) {
parameterName = parameterName.substring(pos + namespace.length());
}
String[] parameterValues = mapEntry.getValue();
if (parameterValues.length > 0) {
String fixedRequestParameterValue = portletContainer.fixRequestParameterValue(parameterValues[0]);
requestParameterMap.put(parameterName, fixedRequestParameterValue);
logger.debug("Found in ActionRequest: {0}=[{1}]", parameterName, fixedRequestParameterValue);
}
}
UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) BridgeFactoryFinder.getFactory(
UploadedFileFactory.class);
// Begin parsing the request for file parts:
try {
FileItemIterator fileItemIterator = null;
if (clientDataRequest instanceof ResourceRequest) {
ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest;
fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest));
}
else {
ActionRequest actionRequest = (ActionRequest) clientDataRequest;
fileItemIterator = portletFileUpload.getItemIterator(actionRequest);
}
boolean optimizeNamespace = BooleanHelper.toBoolean(bridgeContext.getInitParameter(
BridgeConfigConstants.PARAM_OPTIMIZE_PORTLET_NAMESPACE1), true);
if (fileItemIterator != null) {
int totalFiles = 0;
// For each field found in the request:
while (fileItemIterator.hasNext()) {
try {
totalFiles++;
// Get the stream of field data from the request.
FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();
// Get field name from the field stream.
String fieldName = fieldStream.getFieldName();
// If namespace optimization is enabled and the namespace is present in the field name,
// then remove the portlet namespace from the field name.
if (optimizeNamespace) {
int pos = fieldName.indexOf(namespace);
if (pos >= 0) {
fieldName = fieldName.substring(pos + namespace.length());
}
}
// Get the content-type, and file-name from the field stream.
String contentType = fieldStream.getContentType();
boolean formField = fieldStream.isFormField();
String fileName = null;
try {
fileName = fieldStream.getName();
}
catch (InvalidFileNameException e) {
fileName = e.getName();
}
// Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
// current field is a simple form-field because the call below to diskFileItem.getString()
// will fail otherwise.
DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
contentType, formField, fileName);
Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);
// If the current field is a simple form-field, then save the form field value in the map.
if (diskFileItem.isFormField()) {
String characterEncoding = clientDataRequest.getCharacterEncoding();
String requestParameterValue = null;
if (characterEncoding == null) {
requestParameterValue = diskFileItem.getString();
}
else {
requestParameterValue = diskFileItem.getString(characterEncoding);
}
String fixedRequestParameterValue = portletContainer.fixRequestParameterValue(
requestParameterValue);
requestParameterMap.put(fieldName, fixedRequestParameterValue);
logger.debug("{0}=[{1}]", fieldName, fixedRequestParameterValue);
}
else {
File tempFile = diskFileItem.getStoreLocation();
// If the copy was successful, then
if (tempFile.exists()) {
// Copy the commons-fileupload temporary file to a file in the same temporary
// location, but with the filename provided by the user in the upload. This has two
// benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
// the file, the developer can have access to a semi-permanent file, because the
// commmons-fileupload DiskFileItem.finalize() method automatically deletes the
// temporary one.
String tempFileName = tempFile.getName();
String tempFileAbsolutePath = tempFile.getAbsolutePath();
String copiedFileName = stripIllegalCharacters(fileName);
String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
copiedFileName);
File copiedFile = new File(copiedFileAbsolutePath);
FileUtils.copyFile(tempFile, copiedFile);
// If present, build up a map of headers.
Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
FileItemHeaders fileItemHeaders = fieldStream.getHeaders();
if (fileItemHeaders != null) {
Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();
if (headerNameItr != null) {
while (headerNameItr.hasNext()) {
String headerName = headerNameItr.next();
Iterator<String> headerValuesItr = fileItemHeaders.getHeaders(
headerName);
List<String> headerValues = new ArrayList<String>();
if (headerValuesItr != null) {
while (headerValuesItr.hasNext()) {
String headerValue = headerValuesItr.next();
headerValues.add(headerValue);
}
}
headersMap.put(headerName, headerValues);
}
}
}
// Put a valid UploadedFile instance into the map that contains all of the
// uploaded file's attributes, along with a successful status.
Map<String, Object> attributeMap = new HashMap<String, Object>();
String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
String message = null;
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(
copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(),
diskFileItem.getContentType(), headersMap, id, message, fileName,
diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED);
requestParameterMap.put(fieldName, copiedFileAbsolutePath);
addUploadedFile(fieldName, uploadedFile);
logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
fileName);
}
else {
if ((fileName != null) && (fileName.trim().length() > 0)) {
Exception e = new IOException(
"Failed to copy the stream of uploaded file=[" + fileName + "] to a temporary file (possibly a zero-length uploaded file)");
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
addUploadedFile(fieldName, uploadedFile);
}
}
}
}
catch (Exception e) {
logger.error(e);
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
String fieldName = Integer.toString(totalFiles);
addUploadedFile(fieldName, uploadedFile);
}
}
}
}
// If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in
// the map so that the developer can have some idea that something went wrong.
catch (Exception e) {
logger.error(e);
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
addUploadedFile("unknown", uploadedFile);
}
clientDataRequest.setAttribute(PARAM_UPLOADED_FILES, requestParameterFileMap);
// If not found in the request, Section 6.9 of the Bridge spec requires that the value of the
// ResponseStateManager.RENDER_KIT_ID_PARAM request parameter be set to the value of the
// "javax.portlet.faces.<portletName>.defaultRenderKitId" PortletContext attribute.
String renderKitIdParam = requestParameterMap.get(ResponseStateManager.RENDER_KIT_ID_PARAM);
if (renderKitIdParam == null) {
renderKitIdParam = bridgeContext.getDefaultRenderKitId();
if (renderKitIdParam != null) {
requestParameterMap.put(ResponseStateManager.RENDER_KIT_ID_PARAM, renderKitIdParam);
}
}
}
catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
|
diff --git a/code/Lua.java b/code/Lua.java
index 7bf58b1..ab22541 100644
--- a/code/Lua.java
+++ b/code/Lua.java
@@ -1,3548 +1,3548 @@
/* $Header$
* (c) Copyright 2006, Intuwave Ltd. All Rights Reserved.
*
* Although Intuwave has tested this program and reviewed the documentation,
* Intuwave makes no warranty or representation, either expressed or implied,
* with respect to this software, its quality, performance, merchantability,
* or fitness for a particular purpose. As a result, this software is licensed
* "AS-IS", and you are assuming the entire risk as to its quality and
* performance.
*
* You are granted license to use this code as a basis for your own
* application(s) under the terms of the separate license between you and
* Intuwave.
*/
import java.io.InputStream;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Stack;
import java.util.Vector;
// hopefully these only needed during testing:
import java.io.ByteArrayOutputStream;
/**
* <p>
* Encapsulates a Lua execution environment. A lot of Jili's public API
* manifests as public methods in this class. A key part of the API is
* the ability to call Lua functions from Java (ultimately, all Lua code
* is executed in this manner).
* </p>
*
* <p>
* The Stack
* </p>
*
* <p>
* All arguments to Lua functions and all results returned by Lua
* functions are placed onto a stack. The stack can be indexed by an
* integer in the same way as the PUC-Rio implementation. A positive
* index is an absolute index and ranges from 1 (the bottom-most
* element) through to <var>n</var> (the top-most element),
* where <var>n</var> is the number of elements on the stack. Negative
* indexes are relative indexes, -1 is the top-most element, -2 is the
* element underneath that, and so on. 0 is not used.
* </p>
*
* <p>
* Note that in Jili the stack is used only for passing arguments and
* returning results, unlike PUC-Rio.
* </p>
*
* <p>
* The protocol for calling a function is described in the {@link Lua#call}
* method. In brief: push the function onto the stack, then push the
* arguments to the call.
* </p>
*
* <p>
* The methods {@link Lua#push}, {@link Lua#pop}, {@link Lua#value},
* {@link Lua#getTop}, {@link Lua#setTop} are used to manipulate the stack.
* </p>
*/
public final class Lua
{
/** Version string. */
public static final String VERSION = "Lua 5.1 (Jili 0.X.Y)";
/** Table of globals (global variables). Actually shared across all
* coroutines. */
private LuaTable global = new LuaTable();
/** VM data stack. */
private Vector stack = new Vector();
private int base; // = 0;
int nCcalls; // = 0;
/** Instruction to resume execution at. Index into code array. */
private int savedpc; // = 0;
/**
* Vector of CallInfo records. Actually it's a Stack which is a
* subclass of Vector, but it mostly the Vector methods that are used.
*/
private Stack civ = new Stack();
/** CallInfo record for currently active function. */
private CallInfo ci = new CallInfo();
{
civ.addElement(ci);
}
/** Open Upvalues. All UpVal objects that reference the VM stack.
* openupval is a java.util.Vector of UpVal stored in order of stack
* slot index: higher stack indexes are stored at higher Vector
* positions.
*/
private Vector openupval = new Vector();
/** Number of list items to accumulate before a SETLIST instruction. */
static final int LFIELDS_PER_FLUSH = 50;
/** Limit for table tag-method chains (to avoid loops) */
private static final int MAXTAGLOOP = 100;
/**
* Maximum number of local variables per function. As per
* LUAI_MAXVARS from "luaconf.h". Default access so that {@link
* FuncState} can see it.
*/
static final int MAXVARS = 200;
static final int MAXSTACK = 250;
static final int MAXUPVALUES = 60;
/** Used to communicate error status (ERRRUN, etc) from point where
* error is raised to the code that catches it.
*/
private int errorStatus;
/**
* The current error handler (set by {@link Lua#pcall}). A Lua
* function to call.
*/
private Object errfunc;
/** Nonce object used by pcall and friends (to detect when an
* exception is a Lua error). */
private static final String LUA_ERROR = "";
/** Metatable for primitive types. Shared between all coroutines. */
private LuaTable[] metatable = new LuaTable[NUM_TAGS];
//////////////////////////////////////////////////////////////////////
// Public API
/**
* Equivalent of LUA_MULTRET.
*/
// Required, by vmPoscall, to be negative.
public static final int MULTRET = -1;
/**
* The Lua <code>nil</code> value.
*/
public static final Object NIL = null;
// Lua type tags, from lua.h
/** Lua type tag, representing no stack value. */
public static final int TNONE = -1;
/** Lua type tag, representing <code>nil</code>. */
public static final int TNIL = 0;
/** Lua type tag, representing boolean. */
public static final int TBOOLEAN = 1;
// TLIGHTUSERDATA not available. :todo: make available?
/** Lua type tag, representing numbers. */
public static final int TNUMBER = 3;
/** Lua type tag, representing strings. */
public static final int TSTRING = 4;
/** Lua type tag, representing tables. */
public static final int TTABLE = 5;
/** Lua type tag, representing functions. */
public static final int TFUNCTION = 6;
/** Lua type tag, representing userdata. */
public static final int TUSERDATA = 7;
/** Lua type tag, representing threads.
public static final int TTHREAD = 8;
/** Number of type tags. Should correspond to last entry in the list
* of tags.
*/
private static final int NUM_TAGS = 8;
/** Names for above type tags, starting from {@link Lua#TNIL}.
* Equivalent to luaT_typenames.
*/
private static final String[] TYPENAME =
{
"nil", "boolean", "userdata", "number",
"string", "table", "function", "userdata", "thread"
};
/**
* Minimum stack size that Lua Java functions gets. May turn out to
* be silly / redundant.
*/
public static final int MINSTACK = 20;
/** Status code, returned from pcall and friends, that indicates the
* coroutine has yielded.
*/
public static final int YIELD = 1;
/** Status code, returned from pcall and friends, that indicates
* a runtime error.
*/
public static final int ERRRUN = 2;
/** Status code, returned from pcall and friends, that indicates
* a syntax error.
*/
public static final int ERRSYNTAX = 3;
/** Status code, returned from pcall and friends, that indicates
* a memory allocation error.
*/
public static final int ERRMEM = 4;
/** Status code, returned from pcall and friends, that indicates
* an error whilst running the error handler function.
*/
public static final int ERRERR = 5;
/** Status code, returned from loadFile and friends, that indicates
* an IO error.
*/
public static final int ERRFILE = 6;
// Enums for gc().
/** Action, passed to {@link Lua#gc}, that requests the GC to stop. */
public static final int GCSTOP = 0;
/** Action, passed to {@link Lua#gc}, that requests the GC to restart. */
public static final int GCRESTART = 1;
/** Action, passed to {@link Lua#gc}, that requests a full collection. */
public static final int GCCOLLECT = 2;
/** Action, passed to {@link Lua#gc}, that returns amount of memory
* (in Kibibytes) in use (by the entire Java runtime).
*/
public static final int GCCOUNT = 3;
/** Action, passed to {@link Lua#gc}, that returns the remainder of
* dividing the amount of memory in use by 1024.
*/
public static final int GCCOUNTB = 4;
/** Action, passed to {@link Lua#gc}, that requests an incremental
* garbage collection be performed.
*/
public static final int GCSTEP = 5;
/** Action, passed to {@link Lua#gc}, that sets a new value for the
* <var>pause</var> of the collector.
*/
public static final int GCSETPAUSE = 6;
/** Action, passed to {@link Lua#gc}, that sets a new values for the
* <var>step multiplier</var> of the collector.
*/
public static final int GCSETSTEPMUL = 7;
/**
* Calls a Lua value. Normally this is called on functions, but the
* semantics of Lua permit calls on any value as long as its metatable
* permits it.
*
* In order to call a function, the function must be
* pushed onto the stack, then its arguments must be
* {@link Lua#push pushed} onto the stack; the first argument is pushed
* directly after the function,
* then the following arguments are pushed in order (direct
* order). The parameter <var>n</var> specifies the number of
* arguments (which may be 0).
*
* When the function returns the function value on the stack and all
* the arguments are removed from the stack and replaced with the
* results of the function, adjusted to the number specified by
* <var>r</var>. So the first result from the function call will be
* at the same index where the function was immediately prior to
* calling this method.
*
* @param n The number of arguments in this function call.
* @param r The number of results required.
*/
public void call(int n, int r)
{
if (n < 0 || n + base > stack.size())
{
throw new IllegalArgumentException();
}
int func = stack.size() - (n + 1);
this.vmCall(func, r);
}
/**
* Concatenate values (usually strings) on the stack.
* <var>n</var> values from the top of the stack are concatenated, as
* strings, and replaced with the resulting string.
* @param n the number of values to concatenate.
*/
public void concat(int n)
{
apiChecknelems(n);
if (n >= 2)
{
vmConcat(n, (stack.size() - base) - 1);
pop(n-1);
}
else if (n == 0) // push empty string
{
push("");
} // else n == 1; nothing to do
}
/**
* Generates a Lua error using the error message.
* @param message the error message.
* @return never.
*/
public int error(Object message)
{
return gErrormsg(message);
}
/**
* Control garbage collector. Note that in Jili most of the options
* to this function make no sense and they will not do anything.
* @param what specifies what GC action to take.
* @param data data that may be used by the action.
* @return varies.
*/
public int gc(int what, int data)
{
Runtime rt;
switch (what)
{
case GCSTOP:
return 0;
case GCRESTART:
case GCCOLLECT:
case GCSTEP:
System.gc();
return 0;
case GCCOUNT:
rt = Runtime.getRuntime();
return (int)((rt.totalMemory() - rt.freeMemory()) / 1024);
case GCCOUNTB:
rt = Runtime.getRuntime();
return (int)((rt.totalMemory() - rt.freeMemory()) % 1024);
case GCSETPAUSE:
case GCSETSTEPMUL:
return 0;
}
return 0;
}
/**
* Get a field from a table (or other object).
* @param t The object whose field to retrieve.
* @param field The name of the field.
* @return the Lua value
*/
public Object getField(Object t, String field)
{
return vmGettable(t, field);
}
/**
* Get a global variable.
* @param name The name of the global variable.
* @return The value of the global variable.
*/
public Object getGlobal(String name)
{
return vmGettable(global, name);
}
/**
* Gets the global environment. The global environment, where global
* variables live, is returned as a <code>LuaTable</code>. Note that
* modifying this table has exactly the same effect as creating or
* changing global variables from within Lua.
* @return The global environment as a table.
*/
public LuaTable getGlobals()
{
return global;
}
/** Get metatable.
* @param o the Lua value whose metatable to retrieve.
* @return The metatable, or null if there is no metatable.
*/
public LuaTable getMetatable(Object o)
{
LuaTable mt;
if (o instanceof LuaTable)
{
LuaTable t = (LuaTable)o;
mt = t.getMetatable();
}
else if (o instanceof LuaUserdata)
{
LuaUserdata u = (LuaUserdata)o;
mt = u.getMetatable();
}
else
{
mt = metatable[type(o)];
}
return mt;
}
/**
* Gets the number of elements in the stack. If the stack is not
* empty then this is the index of the top-most element.
* @return number of stack elements.
*/
public int getTop()
{
return stack.size() - base;
}
/**
* Insert Lua value into stack immediately at specified index. Values
* in stack at that index and higher get pushed up.
* @param o the Lua value to insert into the stack.
* @param idx the stack index at which to insert.
*/
public void insert(Object o, int idx)
{
idx = absIndex(idx);
stack.insertElementAt(o, idx);
}
/**
* Tests that an object is a Lua boolean.
* @param o the Object to test.
* @return true if and only if the object is a Lua boolean.
*/
public static boolean isBoolean(Object o)
{
return o instanceof Boolean;
}
/**
* Tests that an object is a Lua function implementated in Java (a Lua
* Java Function).
* @param o the Object to test.
* @return true if and only if the object is a Lua Java Function.
*/
public static boolean isJavaFunction(Object o)
{
return o instanceof LuaJavaCallback;
}
/**
* Tests that an object is a Lua function (implemented in Lua or
* Java).
* @param o the Object to test.
* @return true if and only if the object is a function.
*/
public static boolean isFunction(Object o)
{
return o instanceof LuaFunction ||
o instanceof LuaJavaCallback;
}
/**
* Tests that an object is Lua <code>nil</code>.
* @param o the Object to test.
* @return true if and only if the object is Lua <code>nil</code>.
*/
public static boolean isNil(Object o)
{
return null == o;
}
/**
* Tests that an object is a Lua number or a string convertible to a
* number.
* @param o the Object to test.
* @return true if and only if the object is a number or a convertible string.
*/
public static boolean isNumber(Object o)
{
return tonumber(o, NUMOP);
}
/**
* Tests that an object is a Lua string or a number (which is always
* convertible to a string).
* @param o the Object to test.
* @return true if and only if object is a string or number.
*/
public static boolean isString(Object o)
{
return o instanceof String;
}
/**
* Tests that an object is a Lua table.
* @param o the Object to test.
* @return <code>true</code> if and only if the object is a Lua table.
*/
public static boolean isTable(Object o)
{
return o instanceof LuaTable;
}
/**
* Tests that an object is a Lua thread.
* @param o the Object to test.
* @return <code>true</code> if and only if the object is a Lua thread.
*/
public static boolean isThread(Object o)
{
// :todo: implement me.
return false;
}
/**
* Tests that an object is a Lua userdata.
* @param o the Object to test.
* @return true if and only if the object is a Lua userdata.
*/
public static boolean isUserdata(Object o)
{
return o instanceof LuaUserdata;
}
/**
* <p>
* Tests that an object is a Lua value. Returns <code>true</code> for
* an argument that is a Jili representation of a Lua value,
* <code>false</code> for Java references that are not Lua values.
* For example <code>isValue(new LuaTable())</code> is
* <code>true</code>, but <code>isValue(new Object[] { })</code> is
* <code>false</code> because Java arrays are not a representation of
* any Lua value.
* </p>
* <p>
* PUC-Rio Lua provides no
* counterpart for this method because in their implementation it is
* impossible to get non Lua values on the stack, whereas in Jili it
* is common to mix Lua values with ordinary, non Lua, Java objects.
* </p>
* @param o the Object to test.
* @return true if and if it represents a Lua value.
*/
public static boolean isValue(Object o)
{
return o == null ||
o instanceof Boolean ||
o instanceof String ||
o instanceof Double ||
o instanceof LuaFunction ||
o instanceof LuaJavaCallback ||
o instanceof LuaTable ||
o instanceof LuaUserdata;
}
/**
* <p>
* Loads a Lua chunk in binary or source form.
* Comparable to C's lua_load. If the chunk is determined to be
* binary then it is loaded directly. Otherwise the chunk is assumed
* to be a Lua source chunk and compilation is required first; the
* <code>InputStream</code> is used to create a <code>Reader</code>
* (using the
* {@link java.io.InputStreamReader#InputStreamReader(InputStream)}
* constructor) and the Lua source is compiled.
* </p>
* <p>
* If successful, The compiled chunk, a Lua function, is pushed onto
* the stack and a zero status code is returned. Otherwise a non-zero
* status code is returned to indicate an error and the error message
* is pushed onto the stack.
* </p>
* @param in The binary chunk as an InputStream, for example from
* {@link Class#getResourceAsStream}.
* @param chunkname The name of the chunk.
* @return A status code.
*/
public int load(InputStream in, String chunkname)
{
push(new LuaInternal(in, chunkname));
return pcall(0, 1, null);
}
/**
* Loads a Lua chunk in source form.
* Comparable to C's lua_load. Since this takes a {@link
* java.io.Reader} parameter,
* this method is restricted to loading Lua chunks in source form.
* In every other respect this method is just like {@link
* Lua#load(InputStream, String)}.
* @param in The source chunk as a Reader, for example from
* <code>java.io.InputStreamReader(Class.getResourceAsStream())</code>.
* @param chunkname The name of the chunk.
* @return A status code.
* @see java.io.InputStreamReader
*/
public int load(Reader in, String chunkname)
{
push(new LuaInternal(in, chunkname));
return pcall(0, 1, null);
}
/**
* Slowly get the next key from a table. Unlike most other functions
* in the API this one uses the stack. The top-of-stack is popped and
* used to find the next key in the table at the position specified by
* index. If there is a next key then the key and its value are
* pushed onto the stack and <code>true</code> is returned.
* Otherwise (the end of the table has been reached)
* <code>false</code> is returned.
* @param idx stack index of table.
* @return true if and only if there are more keys in the table.
* @deprecated Use :todo: iterator protocol instead.
*/
public boolean next(int idx)
{
Object o = value(idx);
// :todo: api check
LuaTable t = (LuaTable)o;
Object key = value(-1);
pop(1);
Enumeration e = t.keys();
if (key == NIL)
{
if (e.hasMoreElements())
{
key = e.nextElement();
push(key);
push(t.get(key));
return true;
}
return false;
}
while (e.hasMoreElements())
{
Object k = e.nextElement();
if (k == key)
{
if (e.hasMoreElements())
{
key = e.nextElement();
push(key);
push(t.get(key));
return true;
}
return false;
}
}
// protocol error which we could potentially diagnose.
return false;
}
/**
* Protected {@link Lua#call}.
* @param nargs number of arguments.
* @param nresults number of result required.
* @param ef error function to call in case of error.
* @return status code
*/
public int pcall(int nargs, int nresults, Object ef)
{
apiChecknelems(nargs+1);
int restoreStack = stack.size() - (nargs + 1);
// Most of this code comes from luaD_pcall
int restoreCi = civ.size();
int oldnCcalls = nCcalls;
Object old_errfunc = errfunc;
errfunc = ef;
// :todo: save and restore allowhooks
try
{
errorStatus = 0;
call(nargs, nresults);
}
catch (RuntimeException e)
{
if (e.getMessage() == LUA_ERROR)
{
fClose(restoreStack); // close eventual pending closures
// copy error object (usually a string) down
stack.setElementAt(stack.lastElement(), restoreStack);
stack.setSize(restoreStack+1);
nCcalls = oldnCcalls;
civ.setSize(restoreCi);
ci = (CallInfo)civ.lastElement();
base = ci.base();
savedpc = ci.savedpc();
}
else
{
throw e;
}
}
errfunc = old_errfunc;
return errorStatus;
}
/**
* Removes (and discards) the top-most <var>n</var> elements from the stack.
* @param n the number of elements to remove.
*/
public void pop(int n)
{
if (n < 0)
{
throw new IllegalArgumentException();
}
stack.setSize(stack.size() - n);
}
/**
* Pushes a value onto the stack in preparation for calling a
* function (or returning from one). See {@link Lua#call} for
* the protocol to be used for calling functions. See {@link
* Lua#pushNumber} for pushing numbers, and {@link Lua#pushValue} for
* pushing a value that is already on the stack.
* @param o the Lua value to push.
*/
public void push(Object o)
{
stack.addElement(o);
}
/**
* Push boolean onto the stack.
* @param b the boolean to push.
*/
public void pushBoolean(boolean b)
{
push(valueOfBoolean(b));
}
/**
* Push literal string onto the stack.
* @param s the string to push.
*/
public void pushLiteral(String s)
{
push(s);
}
/** Push nil onto the stack. */
public void pushNil()
{
push(NIL);
}
/**
* Pushes a number onto the stack. See also {@link Lua#push}.
* @param d the number to push.
*/
public void pushNumber(double d)
{
push(new Double(d));
}
/**
* Copies a stack element onto the top of the stack.
* Equivalent to <code>L.push(L.value(idx))</code>.
* @param idx stack index of value to push.
*/
public void pushValue(int idx)
{
push(value(idx));
}
/**
* Implements equality without metamethods.
* @param o1 the first Lua value to compare.
* @param o2 the other Lua value.
* @return true if and only if they compare equal.
*/
public static boolean rawEqual(Object o1, Object o2)
{
return oRawequal(o1, o2);
}
/**
* Gets an element from a table, without using metamethods.
* @param t The table to access.
* @param k The index (key) into the table.
* @return The value at the specified index.
*/
public static Object rawGet(Object t, Object k)
{
LuaTable table = (LuaTable)t;
return table.get(k);
}
/**
* Gets an element from an array, without using metamethods.
* @param t the array (table).
* @param i the index of the element to retrieve.
* @return the value at the specified index.
*/
public static Object rawGetI(Object t, int i)
{
LuaTable table = (LuaTable)t;
return table.getnum(i);
}
/**
* Sets an element in a table, without using metamethods.
* @param t The table to modify.
* @param k The index into the table.
* @param v The new value to be stored at index <var>k</var>.
*/
public static void rawSet(Object t, Object k, Object v)
{
if (k == NIL)
{
throw new NullPointerException();
}
LuaTable table = (LuaTable)t;
table.put(k, v);
}
/**
* Set the environment for a function, thread, or userdata.
* @param o Object whose environment will be set.
* @param table Environment table to use.
* @return true if the object had its environment set, false otherwise.
*/
public boolean setFenv(Object o, Object table)
{
// :todo: consider implementing common env interface for
// LuaFunction, LuaJavaCallback, LuaUserdata, Lua. One cast to an
// interface and an interface method call may be shorter
// than this mess.
LuaTable t = (LuaTable)table;
if (o instanceof LuaFunction)
{
LuaFunction f = (LuaFunction)o;
f.setEnv(t);
return true;
}
if (o instanceof LuaJavaCallback)
{
LuaJavaCallback f = (LuaJavaCallback)o;
// :todo: implement this case.
return false;
}
if (o instanceof LuaUserdata)
{
LuaUserdata u = (LuaUserdata)o;
u.setEnv(t);
return true;
}
if (false)
{
// :todo: implement TTHREAD case;
return false;
}
return false;
}
/**
* Set a field in a Lua value.
* @param t Lua value of which to set a field.
* @param name Name of field to set.
* @param v new Lua value for field.
*/
public void setField(Object t, String name, Object v)
{
vmSettable(t, name, v);
}
/**
* Sets the metatable for a Lua value.
* @param o Lua value of which to set metatable.
* @param mt The new metatable.
*/
public void setMetatable(Object o, Object mt)
{
if (isNil(mt))
{
mt = null;
}
else
{
apiCheck(mt instanceof LuaTable);
}
LuaTable mtt = (LuaTable)mt;
if (o instanceof LuaTable)
{
LuaTable t = (LuaTable)o;
t.setMetatable(mtt);
}
else if (o instanceof LuaUserdata)
{
LuaUserdata u = (LuaUserdata)o;
u.setMetatable(mtt);
}
else
{
metatable[type(o)] = mtt;
}
}
/**
* Set a global variable.
* @param name name of the global variable to set.
* @param value desired new value for the variable.
*/
public void setGlobal(String name, Object value)
{
vmSettable(global, name, value);
}
/**
* Set the stack top.
* @param n the desired size of the stack (in elements).
*/
public void setTop(int n)
{
if (n < 0)
{
throw new IllegalArgumentException();
}
stack.setSize(base+n);
}
/**
* Convert to boolean.
* @param o Lua value to convert.
* @return the resulting primitive boolean.
*/
public boolean toBoolean(Object o)
{
return !(o == NIL || Boolean.FALSE.equals(o));
}
/**
* Convert to integer and return it. Returns 0 if cannot be
* converted.
* @param o Lua value to convert.
* @return the resulting int.
*/
public int toInteger(Object o)
{
if (tonumber(o, NUMOP))
{
return (int)NUMOP[0];
}
return 0;
}
/**
* Convert to number and return it. Returns 0 if cannot be
* converted.
* @param o Lua value to convert.
* @return The resulting number.
*/
public double toNumber(Object o)
{
if (tonumber(o, NUMOP))
{
return NUMOP[0];
}
return 0;
}
/**
* Convert to string and return it. If value cannot be converted then
* null is returned. Note that unlike <code>lua_tostring</code> this
* does not modify the Lua value.
* @param o Lua value to convert.
* @return The resulting string.
*/
public String toString(Object o)
{
return vmTostring(o);
}
/**
* Type of the Lua value at the specified stack index.
* @param idx stack index to type.
* @return the type, or {@link Lua#TNONE} if there is no value at <var>idx</var>
*/
public int type(int idx)
{
idx = absIndex(idx);
if (idx < 0)
{
return TNONE;
}
Object o = stack.elementAt(idx);
return type(o);
}
/**
* Type of a Lua value.
* @param o the Lua value whose type to return.
* @return the Lua type from an enumeration.
*/
public int type(Object o)
{
if (o == NIL)
{
return TNIL;
}
else if (o instanceof Double)
{
return TNUMBER;
}
else if (o instanceof Boolean)
{
return TBOOLEAN;
}
else if (o instanceof String)
{
return TSTRING;
}
else if (o instanceof LuaTable)
{
return TTABLE;
}
else if (o instanceof LuaFunction || o instanceof LuaJavaCallback)
{
return TFUNCTION;
}
else if (o instanceof LuaUserdata)
{
return TUSERDATA;
}
// :todo: thread
return TNONE;
}
/**
* Name of type.
* @param type a Lua type from, for example, {@link Lua#type}.
* @return the type's name.
*/
public String typeName(int type)
{
if (TNONE == type)
{
return "no value";
}
return TYPENAME[type];
}
/**
* Gets a value from the stack.
* If <var>idx</var> is positive and exceeds
* the size of the stack, {@link Lua#NIL} is returned.
* @param idx the stack index of the value to retrieve.
* @return the Lua value from the stack.
*/
public Object value(int idx)
{
idx = absIndex(idx);
if (idx < 0)
{
return NIL;
}
return stack.elementAt(idx);
}
/**
* Converts primitive boolean into a Lua value.
* @param b the boolean to convert.
* @return the resulting Lua value.
*/
public static Object valueOfBoolean(boolean b)
{
// If CLDC 1.1 had
// <code>java.lang.Boolean.valueOf(boolean);</code> then I probably
// wouldn't have written this. This does have a small advantage:
// code that uses this method does not need to assume that Lua booleans in
// Jili are represented using Java.lang.Boolean.
if (b)
{
return Boolean.TRUE;
}
else
{
return Boolean.FALSE;
}
}
/**
* Converts primitive number into a Lua value.
* @param d the number to convert.
* @return the resulting Lua value.
*/
public static Object valueOfNumber(double d)
{
// :todo: consider interning "common" numbers, like 0, 1, -1, etc.
return new Double(d);
}
// Miscellaneous private functions.
/** Convert from Java API stack index to absolute index.
* @return an index into <code>this.stack</code> or -1 if out of range.
*/
int absIndex(int idx)
{
int s = stack.size();
if (idx == 0)
{
return -1;
}
if (idx > 0)
{
if (idx + base > s)
{
return -1;
}
return base + idx - 1;
}
// idx < 0
if (s + idx < base)
{
return -1;
}
return s + idx;
}
//////////////////////////////////////////////////////////////////////
// Auxiliary API
// :todo: consider placing in separate class (or macroised) so that we
// can change its definition (to remove the check for example).
private void apiCheck(boolean cond)
{
if (!cond)
{
throw new IllegalArgumentException();
}
}
private void apiChecknelems(int n)
{
apiCheck(n <= stack.size() - base);
}
/**
* Checks a general condition and raises error if false.
* @param cond the (evaluated) condition to check.
* @param numarg argument index.
* @param extramsg extra error message to append.
*/
public void argCheck(boolean cond, int numarg, String extramsg)
{
if (cond)
{
return;
}
argError(numarg, extramsg);
}
/**
* Raise a general error for an argument.
* @param narg argument index.
* @param extramsg extra message string to append.
* @return never (used idiomatically in <code>return argError(...)</code>)
*/
public int argError(int narg, String extramsg)
{
// :todo: use debug API as per PUC-Rio
if (true)
{
return error("bad argument " + narg + " (" + extramsg + ")");
}
return 0;
}
/**
* Calls a metamethod. Pushes 1 result onto stack if method called.
* @param obj stack index of object whose metamethod to call
* @param event metamethod (event) name.
* @return true if and only if metamethod was found and called.
*/
public boolean callMeta(int obj, String event)
{
Object o = value(obj);
Object ev = getMetafield(o, event);
if (ev == null)
{
return false;
}
push(ev);
push(o);
call(1, 1);
return true;
}
/**
* Checks that an argument is present (can be anything).
* Raises error if not.
* @param narg argument index.
*/
public void checkAny(int narg)
{
if (type(narg) == TNONE)
{
argError(narg, "value expected");
}
}
/**
* Checks is a number and returns it as an integer. Raises error if
* not a number.
* @param narg argument index.
* @return the argument as an int.
*/
public int checkInt(int narg)
{
Object o = value(narg);
int d = toInteger(o);
if (d == 0 && !isNumber(o))
{
tagError(narg, TNUMBER);
}
return d;
}
/**
* Checks that an optional string argument is an element from a set of
* strings. Raises error if not.
* @param narg argument index.
* @param def default string to use if argument not present.
* @param lst the set of strings to match against.
* @return an index into <var>lst</var> specifying the matching string.
*/
public int checkOption(int narg, String def, String[] lst)
{
String name;
if (def == null)
{
name = checkString(narg);
}
else
{
name = optString(narg, def);
}
for (int i=0; i<lst.length; ++i)
{
if (lst[i].equals(name))
{
return i;
}
}
return argError(narg, "invalid option '" + name + "'");
}
/**
* Checks argument is a string and returns it. Raises error if not a
* string.
* @param narg argument index.
* @return the argument as a string.
*/
public String checkString(int narg)
{
String s = toString(value(narg));
if (s == null)
{
tagError(narg, TSTRING);
}
return s;
}
/**
* Checks the type of an argument, raises error if not matching.
* @param narg argument index.
* @param t typecode (from {@link Lua#type} for example).
*/
public void checkType(int narg, int t)
{
if (type(narg) != t)
{
tagError(narg, t);
}
}
/**
* Loads and runs the given string.
* @param s the string to run.
* @return a status code, as per {@link Lua#load}.
*/
public int doString(String s)
{
int status = load(Lua.stringReader(s), s);
if (status == 0)
{
status = pcall(0, MULTRET, null);
}
return status;
}
private int errfile(String what, String fname, Exception e)
{
push("cannot " + what + " " + fname + ": " + e.toString());
return ERRFILE;
}
/**
* Get a field (event) from an Lua value's metatable. Returns null
* if there is no field nor metatable.
* @param o Lua value to get metafield for.
* @param event name of metafield (event).
* @return the field from the metatable, or null.
*/
public Object getMetafield(Object o, String event)
{
LuaTable mt = getMetatable(o);
if (mt == null)
{
return null;
}
return mt.get(event);
}
private boolean isnoneornil(int narg)
{
return type(narg) <= TNIL;
}
/**
* Loads a Lua chunk from a file. The <var>filename</var> argument is
* used in a call to {@link Class#getResourceAsStream} where
* <code>this</code> is the {@link Lua} instance, thus relative
* pathnames will be relative to the location of the
* <code>Lua.class</code> file. Pushes compiled chunk, or error
* message, onto stack.
* @param filename location of file.
* @return status code, as per {@link Lua#load}.
*/
public int loadFile(String filename)
{
if (filename == null)
{
throw new NullPointerException();
}
InputStream in = getClass().getResourceAsStream(filename);
if (in == null)
{
return errfile("open", filename, new IOException());
}
int status = 0;
try
{
in.mark(1);
int c = in.read();
if (c == '#') // Unix exec. file?
{
// :todo: handle this case
}
in.reset();
status = load(in, "@" + filename);
}
catch (IOException e)
{
return errfile("read", filename, e);
}
return status;
}
/**
* Loads a Lua chunk from a string. Pushes compiled chunk, or error
* message, onto stack.
* @param s the string to load.
* @param chunkname the name of the chunk.
* @return status code, as per {@link Lua#load}.
*/
public int loadString(String s, String chunkname)
{
return load(stringReader(s), chunkname);
}
/**
* Get optional integer argument. Raises error if non-number
* supplied.
* @param narg argument index.
* @param def default value for integer.
* @return an int.
*/
public int optInt(int narg, int def)
{
if (isnoneornil(narg))
{
return def;
}
return checkInt(narg);
}
/**
* Get optional string argument. Raises error if non-string supplied.
* @param narg argument index.
* @param def default value for string.
* @return a string.
*/
public String optString(int narg, String def)
{
if (isnoneornil(narg))
{
return def;
}
return checkString(narg);
}
private void tagError(int narg, int tag)
{
typerror(narg, typeName(tag));
}
/**
* Name of type of value at <var>idx</var>.
* @param idx stack index.
* @return the name of the value's type.
*/
public String typeNameOfIndex(int idx)
{
return TYPENAME[type(idx)];
}
/**
* Declare type error in argument.
* @param narg Index of argument.
* @param tname Name of type expected.
*/
public void typerror(int narg, String tname)
{
argError(narg, tname + " expected, got " + typeNameOfIndex(narg));
}
/**
* Return string identifying current position of the control at level
* <var>level</var>.
* @param level specifies the call-stack level.
* @return a description for that level.
*/
public String where(int level)
{
Debug ar = getStack(level); // check function at level
if (ar != null)
{
getInfo("Sl", ar); // get info about it
if (ar.currentline() > 0) // is there info?
{
return ar.short_src() + ":" + ar.currentline() + ": ";
}
}
return ""; // else, no information available...
}
/**
* Provide {@link java.io.Reader} interface over a <code>String</code>.
* Equivalent of {@link java.io.StringReader#StringReader} from J2SE.
* The ability to convert a <code>String</code> to a
* <code>Reader</code> is required internally,
* to provide the Lua function <code>loadstring</code>; exposed
* externally as a convenience.
* @param s the string from which to read.
* @return a {@link java.io.Reader} that reads successive chars from <var>s</var>.
*/
public static Reader stringReader(String s)
{
return new StringReader(s);
}
//////////////////////////////////////////////////////////////////////
// Debug
// Methods equivalent to debug API. In PUC-Rio most of these are in
// ldebug.c
private boolean getInfo(String what, Debug ar)
{
Object f = null;
CallInfo callinfo = null;
// :todo: complete me
if (ar.i_ci() > 0) // no tail call?
{
callinfo = (CallInfo)civ.elementAt(ar.i_ci());
f = stack.elementAt(callinfo.function());
// assert isFunction(f);
}
return auxgetinfo(what, ar, f, callinfo);
}
/**
* Locates function activation at specified call level and returns a
* {@link Debug}
* record for it, or <code>null</code> if level is too high.
* May become public.
* @param level the call level.
* @return a {@link Debug} instance describing the activation record.
*/
private Debug getStack(int level)
{
int ici; // Index of CallInfo
for (ici=civ.size()-1; level > 0 && ici > 0; --ici)
{
CallInfo ci = (CallInfo)civ.elementAt(ici);
--level;
if (isLua(ci)) // Lua function?
{
level -= ci.tailcalls(); // skip lost tail calls
}
}
if (level == 0 && ici > 0) // level found?
{
return new Debug(ici);
}
else if (level < 0) // level is of a lost tail call?
{
return new Debug(0);
}
return null;
}
/**
* @return true is okay, false otherwise (for example, error).
*/
private boolean auxgetinfo(String what, Debug ar, Object f, CallInfo ci)
{
boolean status = true;
if (f == null)
{
// :todo: implement me
return status;
}
for (int i=0; i<what.length(); ++i)
{
switch (what.charAt(i))
{
case 'S':
funcinfo(ar, f);
break;
case 'l':
ar.setCurrentline((ci != null) ? currentline(ci) : -1);
break;
// :todo: more cases.
default:
status = false;
}
}
return status;
}
private int currentline(CallInfo ci)
{
int pc = currentpc(ci);
if (pc < 0)
{
return -1; // only active Lua functions have current-line info
}
else
{
Object faso = stack.elementAt(ci.function());
LuaFunction f = (LuaFunction)faso;
return f.proto().getline(pc);
}
}
private int currentpc(CallInfo ci)
{
if (!isLua(ci)) // function is not a Lua function?
{
return -1;
}
if (ci == this.ci)
{
ci.setSavedpc(savedpc);
}
return pcRel(ci.savedpc());
}
private void funcinfo(Debug ar, Object cl)
{
if (cl instanceof LuaJavaCallback)
{
ar.setSource("=[Java]");
ar.setLinedefined(-1);
ar.setLastlinedefined(-1);
ar.setWhat("Java");
}
else
{
Proto p = ((LuaFunction)cl).proto();
ar.setSource(p.source());
ar.setLinedefined(p.linedefined());
ar.setLastlinedefined(p.lastlinedefined());
ar.setWhat(ar.linedefined() == 0 ? "main" : "Lua");
}
}
/** Equivalent to macro isLua _and_ f_isLua from lstate.h. */
private boolean isLua(CallInfo callinfo)
{
Object f = stack.elementAt(callinfo.function());
return f instanceof LuaFunction;
}
private static int pcRel(int pc)
{
return pc - 1;
}
//////////////////////////////////////////////////////////////////////
// Do
// Methods equivalent to the file ldo.c. Prefixed with d.
// Some of these are in vm* instead.
void dThrow(int status)
{
errorStatus = status;
throw new RuntimeException(LUA_ERROR);
}
//////////////////////////////////////////////////////////////////////
// Func
// Methods equivalent to the file lfunc.c. Prefixed with f.
/** Equivalent of luaF_close. All open upvalues referencing stack
* slots level or higher are closed.
* @param level Absolute stack index.
*/
void fClose(int level)
{
int i = openupval.size();
while (--i >= 0)
{
UpVal uv = (UpVal)openupval.elementAt(i);
if (uv.offset() < level)
{
break;
}
uv.close();
}
openupval.setSize(i+1);
return;
}
UpVal fFindupval(int idx)
{
/*
* We search from the end of the Vector towards the beginning,
* looking for an UpVal for the required stack-slot.
*/
int i = openupval.size();
while (--i >= 0)
{
UpVal uv = (UpVal)openupval.elementAt(i);
if (uv.offset() == idx)
{
return uv;
}
if (uv.offset() < idx)
{
break;
}
}
// i points to be position _after_ which we want to insert a new
// UpVal (it's -1 when we want to insert at the beginning).
UpVal uv = new UpVal(stack, idx);
openupval.insertElementAt(uv, i+1);
return uv;
}
//////////////////////////////////////////////////////////////////////
// Debug
// Methods equivalent to the file ldebug.c. Prefixed with g.
/** p1 and p2 are absolute stack indexes. Corrupts NUMOP[0]. */
private void gAritherror(int p1, int p2)
{
if (!tonumber(value(p1), NUMOP))
{
p2 = p1; // first operand is wrong
}
gTypeerror(value(p2), "perform arithmetic on");
}
/** p1 and p2 are absolute stack indexes. */
private void gConcaterror(int p1, int p2)
{
if (stack.elementAt(p1) instanceof String)
{
p1 = p2;
}
// assert !(p1 instanceof String);
gTypeerror(stack.elementAt(p1), "concatenate");
}
boolean gCheckcode(Proto p)
{
// :todo: implement me.
return true ;
}
private int gErrormsg(Object message)
{
push(message);
if (errfunc != null) // is there an error handling function
{
if (!isFunction(errfunc))
{
dThrow(ERRERR);
}
insert(errfunc, getTop()); // push function (under error arg)
vmCall(stack.size()-2, 1); // call it
}
dThrow(ERRRUN);
// NOTREACHED
return 0;
}
boolean gOrdererror(Object p1, Object p2)
{
String t1 = typeName(type(p1));
String t2 = typeName(type(p2));
if (t1.charAt(2) == t2.charAt(2))
{
gRunerror("attempt to compare two " + t1 + "values");
}
else
{
gRunerror("attempt to compare " + t1 + " with " + t2);
}
// NOTREACHED
return false;
}
void gRunerror(String s)
{
gErrormsg(s);
}
private void gTypeerror(Object o, String op)
{
// :todo: PUC-Rio searches the stack to see if the value (which may
// be a reference to stack cell) is a local variable. Jili can't do
// that so easily. Consider changing interface.
String t = typeName(type(o));
gRunerror("attempt to " + op + " a " + t + " value");
}
//////////////////////////////////////////////////////////////////////
// Object
// Methods equivalent to the file lobject.c. Prefixed with o.
private static final int IDSIZE = 60;
/**
* @return a string no longer than IDSIZE.
*/
static String oChunkid(String source)
{
int len = IDSIZE;
if (source.startsWith("="))
{
if(source.length() < IDSIZE+1)
{
return source.substring(1);
}
else
{
return source.substring(1, 1+len);
}
}
// else "source" or "...source"
if (source.startsWith("@"))
{
len -= " '...' ".length();
int l = source.length();
if (l > len)
{
return "..." + // get last part of file name
source.substring(source.length()-len, source.length());
}
return source;
}
// else [string "string"]
int l = source.indexOf('\n');
if (l == -1)
{
l = source.length();
}
len -= " [string \"...\"] ".length();
if (l > len)
{
l = len;
}
StringBuffer buf = new StringBuffer();
buf.append("[string \"");
buf.append(source.substring(0, l));
if (source.length() > l) // must truncate
{
buf.append("...");
}
buf.append("\"]");
return buf.toString();
}
/** Equivalent to luaO_rawequalObj. */
private static boolean oRawequal(Object a, Object b)
{
// see also vmEqual
if (NIL == a)
{
return NIL == b;
}
// Now a is not null, so a.equals() is a valid call.
// Numbers (Doubles), Booleans, Strings all get compared by value,
// as they should; tables, functions, get compared by identity as
// they should.
return a.equals(b);
}
/** Equivalent to luaO_str2d. */
private static boolean oStr2d(String s, double[] out)
{
// :todo: using try/catch may be too slow. In which case we'll have
// to recognise the valid formats first.
try
{
out[0] = Double.parseDouble(s);
return true;
}
catch (NumberFormatException e0_)
{
try
{
// Attempt hexadecimal conversion.
// :todo: using String.trim is not strictly accurate, because it
// trims other ASCII control characters as well as whitespace.
s = s.trim().toUpperCase();
if (s.startsWith("0X"))
{
s = s.substring(2);
}
else if (s.startsWith("-0X"))
{
s = "-" + s.substring(3);
}
out[0] = Integer.parseInt(s, 16);
return true;
}
catch (NumberFormatException e1_)
{
return false;
}
}
}
////////////////////////////////////////////////////////////////////////
// VM
// Most of the methods in this section are equivalent to the files
// lvm.c and ldo.c from PUC-Rio. They're mostly prefixed with vm as
// well.
private static final int PCRLUA = 0;
private static final int PCRJ = 1;
private static final int PCRYIELD = 2;
// Instruction decomposition.
// There follows a series of methods that extract the various fields
// from a VM instruction. See lopcodes.h from PUC-Rio.
// :todo: Consider replacing with m4 macros (or similar).
// A brief overview of the instruction format:
// Logically an instruction has an opcode (6 bits), op, and up to
// three fields using one of three formats:
// A B C (8 bits, 9 bits, 9 bits)
// A Bx (8 bits, 18 bits)
// A sBx (8 bits, 18 bits signed - excess K)
// Some instructions do not use all the fields (EG OP_UNM only uses A
// and B).
// When packed into a word (an int in Jili) the following layouts are
// used:
// 31 (MSB) 23 22 14 13 6 5 0 (LSB)
// +--------------+--------------+------------+--------+
// | B | C | A | OPCODE |
// +--------------+--------------+------------+--------+
//
// +--------------+--------------+------------+--------+
// | Bx | A | OPCODE |
// +--------------+--------------+------------+--------+
//
// +--------------+--------------+------------+--------+
// | sBx | A | OPCODE |
// +--------------+--------------+------------+--------+
static final int NO_REG = 0xff; // SIZE_A == 8, (1 << 8)-1
// Hardwired values for speed.
/** Equivalent of macro GET_OPCODE */
static int OPCODE(int instruction)
{
// POS_OP == 0 (shift amount)
// SIZE_OP == 6 (opcode width)
return instruction & 0x3f;
}
/** Equivalent of macro GET_OPCODE */
static int SET_OPCODE(int i, int op)
{
// POS_OP == 0 (shift amount)
// SIZE_OP == 6 (opcode width)
return (i & ~0x3F) | (op & 0x3F);
}
/** Equivalent of macro GETARG_A */
static int ARGA(int instruction)
{
// POS_A == POS_OP + SIZE_OP == 6 (shift amount)
// SIZE_A == 8 (operand width)
return (instruction >>> 6) & 0xff;
}
static int SETARG_A(int i, int u)
{
return (i & ~(0xff << 6)) | ((u & 0xff) << 6);
}
/** Equivalent of macro GETARG_B */
static int ARGB(int instruction)
{
// POS_B == POS_OP + SIZE_OP + SIZE_A + SIZE_C == 23 (shift amount)
// SIZE_B == 9 (operand width)
/* No mask required as field occupies the most significant bits of a
* 32-bit int. */
return (instruction >>> 23);
}
static int SETARG_B(int i, int b)
{
return (i & ~(0x1ff << 23)) | ((b & 0x1ff) << 23);
}
/** Equivalent of macro GETARG_C */
static int ARGC(int instruction)
{
// POS_C == POS_OP + SIZE_OP + SIZE_A == 14 (shift amount)
// SIZE_C == 9 (operand width)
return (instruction >>> 14) & 0x1ff;
}
static int SETARG_C(int i, int c)
{
return (i & ~(0x1ff << 14)) | ((c & 0x1ff) << 14);
}
/** Equivalent of macro GETARG_Bx */
static int ARGBx(int instruction)
{
// POS_Bx = POS_C == 14
// SIZE_Bx == SIZE_C + SIZE_B == 18
/* No mask required as field occupies the most significant bits of a
* 32 bit int. */
return (instruction >>> 14);
}
static int SETARG_Bx(int i, int bx)
{
return (i & 0x3fff) | (bx << 14) ;
}
/** Equivalent of macro GETARG_sBx */
static int ARGsBx(int instruction)
{
// As ARGBx but with (2**17-1) subtracted.
return (instruction >>> 14) - MAXARG_sBx;
}
static int SETARG_sBx(int i, int bx)
{
return (i & 0x3fff) | ((bx+MAXARG_sBx) << 14) ; // CHECK THIS IS RIGHT
}
static boolean ISK(int field)
{
// The "is constant" bit position depends on the size of the B and C
// fields (required to be the same width).
// SIZE_B == 9
return field >= 0x100;
}
/**
* Near equivalent of macros RKB and RKC. Note: non-static as it
* requires stack and base instance members. Stands for "Register or
* Konstant" by the way, it gets value from either the register file
* (stack) or the constant array (k).
*/
private Object RK(Object[] k, int field)
{
if (ISK(field))
{
return k[field & 0xff];
}
return stack.elementAt(base + field);
}
// CREATE functions are required by FuncState, so default access.
static int CREATE_ABC(int o, int a, int b, int c)
{
// POS_OP == 0
// POS_A == 6
// POS_B == 23
// POS_C == 14
return o | (a << 6) | (b << 23) | (c << 14);
}
static int CREATE_ABx(int o, int a, int bc)
{
// POS_OP == 0
// POS_A == 6
// POS_Bx == POS_C == 14
return o | (a << 6) | (bc << 14);
}
// opcode enumeration.
// Generated by a script:
// awk -f opcode.awk < lopcodes.h
// and then pasted into here.
// Made default access so that code generation, in FuncState, can see
// the enumeration as well.
static final int OP_MOVE = 0;
static final int OP_LOADK = 1;
static final int OP_LOADBOOL = 2;
static final int OP_LOADNIL = 3;
static final int OP_GETUPVAL = 4;
static final int OP_GETGLOBAL = 5;
static final int OP_GETTABLE = 6;
static final int OP_SETGLOBAL = 7;
static final int OP_SETUPVAL = 8;
static final int OP_SETTABLE = 9;
static final int OP_NEWTABLE = 10;
static final int OP_SELF = 11;
static final int OP_ADD = 12;
static final int OP_SUB = 13;
static final int OP_MUL = 14;
static final int OP_DIV = 15;
static final int OP_MOD = 16;
static final int OP_POW = 17;
static final int OP_UNM = 18;
static final int OP_NOT = 19;
static final int OP_LEN = 20;
static final int OP_CONCAT = 21;
static final int OP_JMP = 22;
static final int OP_EQ = 23;
static final int OP_LT = 24;
static final int OP_LE = 25;
static final int OP_TEST = 26;
static final int OP_TESTSET = 27;
static final int OP_CALL = 28;
static final int OP_TAILCALL = 29;
static final int OP_RETURN = 30;
static final int OP_FORLOOP = 31;
static final int OP_FORPREP = 32;
static final int OP_TFORLOOP = 33;
static final int OP_SETLIST = 34;
static final int OP_CLOSE = 35;
static final int OP_CLOSURE = 36;
static final int OP_VARARG = 37;
// end of instruction decomposition
static final int SIZE_C = 9;
static final int SIZE_B = 9;
static final int SIZE_Bx = SIZE_C + SIZE_B;
static final int SIZE_A = 8;
static final int SIZE_OP = 6;
static final int POS_OP = 0;
static final int POS_A = POS_OP + SIZE_OP;
static final int POS_C = POS_A + SIZE_A;
static final int POS_B = POS_C + SIZE_C;
static final int POS_Bx = POS_C;
static final int MAXARG_Bx = (1<<SIZE_Bx)-1;
static final int MAXARG_sBx = MAXARG_Bx>>1; // `sBx' is signed
static final int MAXARG_A = (1<<SIZE_A)-1;
static final int MAXARG_B = (1<<SIZE_B)-1;
static final int MAXARG_C = (1<<SIZE_C)-1;
/* this bit 1 means constant (0 means register) */
static final int BITRK = 1 << (SIZE_B - 1) ;
static final int MAXINDEXRK = BITRK - 1 ;
/**
* Equivalent of luaD_call.
* @param func absolute stack index of function to call.
* @param r number of required results.
*/
private void vmCall(int func, int r)
{
++nCcalls;
if (vmPrecall(func, r) == PCRLUA)
{
vmExecute(1);
}
--nCcalls;
}
/** Equivalent of luaV_concat. */
private void vmConcat(int total, int last)
{
do
{
int top = base + last + 1;
int n = 2; // number of elements handled in this pass (at least 2)
if (!tostring(top-2)|| !tostring(top-1))
{
if (!call_binTM(top-2, top-1, top-2, "__concat"))
{
gConcaterror(top-2, top-1);
}
}
else if (((String)stack.elementAt(top-1)).length() > 0)
{
int tl = ((String)stack.elementAt(top-1)).length();
for (n = 1; n < total && tostring(top-n-1); ++n)
{
tl += ((String)stack.elementAt(top-n-1)).length();
if (tl < 0)
{
gRunerror("string length overflow");
}
}
StringBuffer buffer = new StringBuffer(tl);
for (int i=n; i>0; i--) // concat all strings
{
buffer.append(stack.elementAt(top-i));
}
stack.setElementAt(buffer.toString(), top-n);
}
total -= n-1; // got n strings to create 1 new
last -= n-1;
} while (total > 1); // repeat until only 1 result left
}
/**
* Primitive for testing Lua equality of two values. Equivalent of
* PUC-Rio's equalobj macro. Note that using null to model nil
* complicates this test, maybe we should use a nonce object.
* In the loosest sense, this is the equivalent of
* <code>luaV_equalval</code>.
*/
private boolean vmEqual(Object a, Object b)
{
// :todo: consider if (a == b) return true;
if (NIL == a)
{
return NIL == b;
}
// Now a is not null, so a.equals() is a valid call.
if (a.equals(b))
{
return true;
}
if (NIL == b)
{
return false;
}
// Now b is not null, so b.getClass() is a valid call.
if (a.getClass() != b.getClass())
{
return false;
}
// Same class, but different objects.
if (a instanceof LuaJavaCallback ||
a instanceof LuaTable)
{
// Resort to metamethods.
Object tm = get_compTM(getMetatable(a), getMetatable(b), "__eq");
if (null == tm) // no TM?
{
return false;
}
Object res = callTMres(tm, a, b); // call TM
return !isFalse(res);
}
return false;
}
/**
* Array of numeric operands. Used when converting strings to numbers
* by an arithmetic opcode (ADD, SUB, MUL, DIV, MOD, POW, UNM).
*/
private static final double[] NUMOP = new double[2];
/** The core VM execution engine. */
private void vmExecute(int nexeccalls)
{
// This labelled while loop is used to simulate the effect of C's
// goto. The end of the while loop is never reached. The beginning
// of the while loop is branched to using a "continue reentry;"
// statement (when a Lua function is called or returns).
reentry:
while (true)
{
// assert stack.elementAt[ci.function()] instanceof LuaFunction;
LuaFunction function = (LuaFunction)stack.elementAt(ci.function());
Proto proto = function.proto();
int[] code = proto.code();
Object[] k = proto.constant();
int pc = savedpc;
while (true) // main loop of interpreter
{
// Where the PUC-Rio code used the Protect macro, this has been
// replaced with "savedpc = pc" and a "// Protect" comment.
// Where the PUC-Rio code used the dojump macro, this has been
// replaced with the equivalent increment of the pc and a
// "//dojump" comment.
int i = code[pc++]; // VM instruction.
// :todo: count and line hook
int a = ARGA(i); // its A field.
Object rb;
Object rc;
switch (OPCODE(i))
{
case OP_MOVE:
stack.setElementAt(stack.elementAt(base+ARGB(i)), base+a);
continue;
case OP_LOADK:
stack.setElementAt(k[ARGBx(i)], base+a);
continue;
case OP_LOADBOOL:
stack.setElementAt(valueOfBoolean(ARGB(i) != 0), base+a);
if (ARGC(i) != 0)
{
++pc;
}
continue;
case OP_LOADNIL:
{
int b = base + ARGB(i);
do
{
stack.setElementAt(NIL, b--);
} while (b >= base + a);
continue;
}
case OP_GETUPVAL:
{
int b = ARGB(i);
stack.setElementAt(function.upVal(b).getValue(), base+a);
continue;
}
case OP_GETGLOBAL:
rb = k[ARGBx(i)];
// assert rb instance of String;
savedpc = pc; // Protect
stack.setElementAt(vmGettable(function.getEnv(), rb), base+a);
continue;
case OP_GETTABLE:
{
savedpc = pc; // Protect
Object t = stack.elementAt(base+ARGB(i));
stack.setElementAt(vmGettable(t, RK(k, ARGC(i))), base+a);
continue;
}
case OP_SETUPVAL:
{
UpVal uv = function.upVal(ARGB(i));
uv.setValue(stack.elementAt(base+a));
continue;
}
case OP_SETGLOBAL:
savedpc = pc; // Protect
vmSettable(function.getEnv(), k[ARGBx(i)],
stack.elementAt(base+a));
continue;
case OP_SETTABLE:
{
savedpc = pc; // Protect
Object t = stack.elementAt(base+a);
vmSettable(t, RK(k, ARGB(i)), RK(k, ARGC(i)));
continue;
}
case OP_NEWTABLE:
{
// :todo: use the b and c hints, currently ignored.
int b = ARGB(i);
int c = ARGC(i);
stack.setElementAt(new LuaTable(), base+a);
continue;
}
case OP_SELF:
{
int b = ARGB(i);
rb = stack.elementAt(base+b);
stack.setElementAt(rb, base+a+1);
savedpc = pc; // Protect
stack.setElementAt(vmGettable(rb, RK(k, ARGC(i))), base+a);
continue;
}
case OP_ADD:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double sum = ((Double)rb).doubleValue() +
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(sum), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double sum = NUMOP[0] + NUMOP[1];
stack.setElementAt(valueOfNumber(sum), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__add"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_SUB:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double difference = ((Double)rb).doubleValue() -
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(difference), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double difference = NUMOP[0] - NUMOP[1];
stack.setElementAt(valueOfNumber(difference), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__sub"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_MUL:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double product = ((Double)rb).doubleValue() *
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(product), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double product = NUMOP[0] * NUMOP[1];
stack.setElementAt(valueOfNumber(product), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__mul"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_DIV:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double quotient = ((Double)rb).doubleValue() /
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(quotient), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double quotient = NUMOP[0] / NUMOP[1];
stack.setElementAt(valueOfNumber(quotient), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__div"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_MOD:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double db = ((Double)rb).doubleValue();
double dc = ((Double)rc).doubleValue();
double modulus = modulus(db, dc);
stack.setElementAt(valueOfNumber(modulus), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double modulus = modulus(NUMOP[0], NUMOP[1]);
stack.setElementAt(valueOfNumber(modulus), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__mod"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_POW:
// There's no Math.pow. :todo: consider implementing.
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double result = iNumpow(((Double)rb).doubleValue(),
((Double)rc).doubleValue());
stack.setElementAt(valueOfNumber(result), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double result = iNumpow(NUMOP[0], NUMOP[1]);
stack.setElementAt(valueOfNumber(result), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__pow"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_UNM:
{
rb = stack.elementAt(base+ARGB(i));
if (rb instanceof Double)
{
double db = ((Double)rb).doubleValue();
stack.setElementAt(valueOfNumber(-db), base+a);
}
else if (tonumber(rb, NUMOP))
{
stack.setElementAt(valueOfNumber(-NUMOP[0]), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGB(i), base+a,
"__unm"))
{
gAritherror(base+ARGB(i), base+ARGB(i));
}
continue;
}
case OP_NOT:
{
Object ra = stack.elementAt(base+ARGB(i));
stack.setElementAt(valueOfBoolean(isFalse(ra)), base+a);
continue;
}
case OP_LEN:
rb = stack.elementAt(base+ARGB(i));
if (rb instanceof LuaTable)
{
LuaTable t = (LuaTable)rb;
stack.setElementAt(new Double(t.getn()), base+a);
continue;
}
else if (rb instanceof String)
{
String s = (String)rb;
stack.setElementAt(new Double(s.length()), base+a);
continue;
}
savedpc = pc; // Protect
if (!call_binTM(base+ARGB(i), base+ARGB(i), base+a, "__len"))
{
gTypeerror(rb, "get length of");
}
continue;
case OP_CONCAT:
{
int b = ARGB(i);
int c = ARGC(i);
savedpc = pc; // Protect
// :todo: It's possible that the compiler assumes that all
// stack locations _above_ b end up with junk in them. In
// which case we can improve the speed of vmConcat (by not
// converting each stack slot, but simply using
// StringBuffer.append on whatever is there).
vmConcat(c - b + 1, c);
stack.setElementAt(stack.elementAt(base+b), base+a);
continue;
}
case OP_JMP:
// dojump
pc += ARGsBx(i);
continue;
case OP_EQ:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (vmEqual(rb, rc) == (a != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_LT:
savedpc = pc; // Protect
if (vmLessthan(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_LE:
savedpc = pc; // Protect
if (vmLessequal(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_TEST:
if (isFalse(stack.elementAt(base+a)) != (ARGC(i) != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_TESTSET:
rb = stack.elementAt(base+ARGB(i));
if (isFalse(rb) != (ARGC(i) != 0))
{
stack.setElementAt(rb, base+a);
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_CALL:
{
int b = ARGB(i);
int nresults = ARGC(i) - 1;
if (b != 0)
{
stack.setSize(base+a+b);
}
savedpc = pc;
switch (vmPrecall(base+a, nresults))
{
case PCRLUA:
nexeccalls++;
continue reentry;
case PCRJ:
// Was Java function called by precall, adjust result
if (nresults >= 0)
{
stack.setSize(ci.top());
}
continue;
default:
return; // yield
}
}
case OP_TAILCALL:
{
int b = ARGB(i);
if (b != 0)
{
stack.setSize(base+a+b);
}
savedpc = pc;
// assert ARGC(i) - 1 == MULTRET
switch (vmPrecall(base+a, MULTRET))
{
case PCRLUA:
{
// tail call: put new frame in place of previous one.
CallInfo ci = (CallInfo)civ.elementAt(civ.size()-2);
int func = ci.function();
int pfunc = this.ci.function();
- fClose(base);
+ fClose(ci.base());
base = func + (this.ci.base() - pfunc);
int aux; // loop index is used after loop ends
for (aux=0; pfunc+aux < stack.size(); ++aux)
{
// move frame down
stack.setElementAt(stack.elementAt(pfunc+aux), func+aux);
}
stack.setSize(func+aux); // correct top
// assert stack.size() == base + ((LuaFunction)stack.elementAt(func)).proto().maxstacksize();
ci.tailcall(base, stack.size());
dec_ci(); // remove new frame.
continue reentry;
}
case PCRJ: // It was a Java function
{
continue;
}
default:
{
return; // yield
}
}
}
case OP_RETURN:
{
fClose(base);
int b = ARGB(i);
if (b != 0)
{
int top = a + b - 1;
stack.setSize(base + top);
}
savedpc = pc;
// 'adjust' replaces aliased 'b' in PUC-Rio code.
boolean adjust = vmPoscall(base+a);
if (--nexeccalls == 0)
{
return;
}
if (adjust)
{
stack.setSize(ci.top());
}
continue reentry;
}
case OP_FORLOOP:
{
double step =
((Double)stack.elementAt(base+a+2)).doubleValue();
double idx =
((Double)stack.elementAt(base+a)).doubleValue() + step;
double limit =
((Double)stack.elementAt(base+a+1)).doubleValue();
if ((0 < step && idx <= limit) ||
(step <= 0 && limit <= idx))
{
// dojump
pc += ARGsBx(i);
Object d = valueOfNumber(idx);
stack.setElementAt(d, base+a); // internal index
stack.setElementAt(d, base+a+3); // external index
}
continue;
}
case OP_FORPREP:
{
int init = base+a;
int plimit = base+a+1;
int pstep = base+a+2;
savedpc = pc; // next steps may throw errors
if (!tonumber(init))
{
gRunerror("'for' initial value must be a number");
}
else if (!tonumber(plimit))
{
gRunerror("'for' limit must be a number");
}
else if (!tonumber(pstep))
{
gRunerror("'for' step must be a number");
}
double step =
((Double)stack.elementAt(pstep)).doubleValue();
double idx =
((Double)stack.elementAt(init)).doubleValue() - step;
stack.setElementAt(new Double(idx), init);
// dojump
pc += ARGsBx(i);
continue;
}
case OP_TFORLOOP:
{
int cb = base+a+3; // call base
stack.setElementAt(stack.elementAt(base+a+2), cb+2);
stack.setElementAt(stack.elementAt(base+a+1), cb+1);
stack.setElementAt(stack.elementAt(base+a), cb);
stack.setSize(cb+3);
savedpc = pc; // Protect
vmCall(cb, ARGC(i));
stack.setSize(ci.top());
if (NIL != stack.elementAt(cb)) // continue loop
{
stack.setElementAt(stack.elementAt(cb), cb-1);
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
}
case OP_SETLIST:
{
int n = ARGB(i);
int c = ARGC(i);
int last;
LuaTable t;
if (0 == n)
{
n = (stack.size() - a) - 1;
// :todo: check this against PUC-Rio
// stack.setSize ??
}
if (0 == c)
{
c = code[pc++];
}
t = (LuaTable)stack.elementAt(base+a);
last = ((c-1)*LFIELDS_PER_FLUSH) + n;
// :todo: consider expanding space in table
for (; n > 0; n--)
{
Object val = stack.elementAt(base+a+n);
t.putnum(last--, val);
}
continue;
}
case OP_CLOSE:
fClose(base+a);
continue;
case OP_CLOSURE:
{
Proto p = function.proto().proto()[ARGBx(i)];
int nup = p.nups();
UpVal[] up = new UpVal[nup];
for (int j=0; j<nup; j++, pc++)
{
int in = code[pc];
if (OPCODE(in) == OP_GETUPVAL)
{
up[j] = function.upVal(ARGB(in));
}
else
{
// assert OPCODE(in) == OP_MOVE;
up[j] = fFindupval(base + ARGB(in));
}
}
LuaFunction nf = new LuaFunction(p, up, function.getEnv());
stack.setElementAt(nf, base+a);
continue;
}
case OP_VARARG:
{
int b = ARGB(i)-1;
int n = (base - ci.function()) -
function.proto().numparams() - 1;
if (b == MULTRET)
{
// :todo: Protect
// :todo: check stack
b = n;
stack.setSize(base+a+n);
}
for (int j=0; j<b; ++j)
{
if (j < n)
{
Object src = stack.elementAt(base - n + j);
stack.setElementAt(src, base+a+j);
}
else
{
stack.setElementAt(NIL, base+a+j);
}
}
continue;
}
} /* switch */
} /* while */
} /* reentry: while */
}
double iNumpow(double a, double b)
{
// :todo: this needs proper checking for boundary cases
boolean invert = b < 0.0 ;
if (invert) b = -b ;
if (a == 0.0)
return invert ? Double.NaN : a ;
double result = 1.0 ;
int ipow = (int) b ;
b -= ipow ;
double t = a ;
while (ipow > 0)
{
if ((ipow & 1) != 0)
result *= t ;
ipow >>= 1 ;
t = t*t ;
}
if (b != 0.0) // integer only case, save doing unnecessary work
{
if (a < 0.0) // doesn't work if a negative (complex result!)
return Double.NaN ;
t = Math.sqrt(a) ;
double half = 0.5 ;
while (b > 0.0)
{
if (b >= half)
{
result = result * t ;
b -= half ;
}
b = b+b ;
t = Math.sqrt(t) ;
if (t == 1.0)
break ;
}
}
return invert ? 1.0 / result : result ;
}
/** helper function for iNumpow()
private double sqrt(double d)
{
if (d == 0.0)
return d;
boolean recip = d < 1.0 ;
if (recip)
d = 1.0 / d ;
int adjust = 0 ;
double four = 4.0 ;
while (d >= four)
{
d /= four ;
adjust += 1 ;
}
double p = 1.0 ;
double result = 0.0 ;
double half = 0.5 ;
for (int i = 0 ; i < 53 ; i++)
{
double test = result + p ;
if (test*test <= d)
result = test;
p = p * half ;
}
while (adjust > 0)
{
result *= 2.0 ;
adjust -= 1 ;
}
return recip ? 1.0 / result : result ;
}
*/
/** Equivalent of luaV_gettable. */
private Object vmGettable(Object t, Object key)
{
Object tm;
for (int loop = 0; loop < MAXTAGLOOP; ++loop)
{
if (t instanceof LuaTable) // 't' is a table?
{
LuaTable h = (LuaTable)t;
Object res = h.get(key);
if (!isNil(res) || ((tm = tagmethod(h, "__index")) == null))
{
return res;
} // else will try the tag method
}
else if ((tm = tagmethod(t, "__index")) == null)
{
gTypeerror(t, "index");
}
if (isFunction(tm))
{
return callTMres(tm, t, key);
}
t = tm; // else repeat with 'tm'
}
gRunerror("loop in gettable");
// NOTREACHED
return null;
}
/** Equivalent of luaV_lessthan. */
private boolean vmLessthan(Object l, Object r)
{
// :todo: currently goes wrong when comparing nil. Fix it.
if (l.getClass() != r.getClass())
{
// :todo: Make Lua error
throw new IllegalArgumentException();
}
else if (l instanceof Double)
{
return ((Double)l).doubleValue() < ((Double)r).doubleValue();
}
else if (l instanceof String)
{
// :todo: PUC-Rio use strcoll, maybe we should use something
// equivalent.
return ((String)l).compareTo((String)r) < 0;
}
int res = call_orderTM(l, r, "__lt");
if (res >= 0) {
return res != 0;
}
return gOrdererror(l, r);
}
/** Equivalent of luaV_lessequal. */
private boolean vmLessequal(Object l, Object r)
{
// :todo: currently goes wrong when comparing nil. Fix it.
if (l.getClass() != r.getClass())
{
// :todo: Make Lua error
throw new IllegalArgumentException();
}
else if (l instanceof Double)
{
return ((Double)l).doubleValue() <= ((Double)r).doubleValue();
}
else if (l instanceof String)
{
return ((String)l).compareTo((String)r) <= 0;
}
int res = call_orderTM(l, r, "__le"); // first try 'le'
if (res >= 0)
{
return res != 0;
}
res = call_orderTM(r, l, "__lt"); // else try 'lt'
if (res >= 0)
{
return res == 0;
}
return gOrdererror(l, r);
}
/**
* Equivalent of luaD_poscall.
* @param firstResult stack index (absolute) of the first result
*/
private boolean vmPoscall(int firstResult)
{
// :todo: call hook
CallInfo lci; // local copy, for faster access
lci = dec_ci();
// Now (as a result of the dec_ci call), lci is the CallInfo record
// for the current function (the function executing an OP_RETURN
// instruction), and this.ci is the CallInfo record for the function
// we are returning to.
int res = lci.res();
int wanted = lci.nresults(); // Caution: wanted could be == MULTRET
base = this.ci.base();
savedpc = this.ci.savedpc();
// Move results (and pad with nils to required number if necessary)
int i = wanted;
int top = stack.size();
// The movement is always downwards, so copying from the top-most
// result first is always correct.
while (i != 0 && firstResult < top)
{
stack.setElementAt(stack.elementAt(firstResult++), res++);
i--;
}
if (i > 0)
{
stack.setSize(res+i);
}
// :todo: consider using two stack.setSize calls to nil out
// remaining required results.
// This trick only works if Lua.NIL == null, whereas the current
// code works regardless of what Lua.NIL is.
while (i-- > 0)
{
stack.setElementAt(NIL, res++);
}
stack.setSize(res);
return wanted != MULTRET;
}
/**
* Equivalent of LuaD_precall. This method expects that the arguments
* to the function are placed above the function on the stack.
* @param func absolute stack index of the function to call.
* @param r number of results expected.
*/
private int vmPrecall(int func, int r)
{
Object faso; // Function AS Object
faso = stack.elementAt(func);
if (!isFunction(faso))
{
faso = tryfuncTM(func);
}
this.ci.setSavedpc(savedpc);
if (faso instanceof LuaFunction)
{
LuaFunction f = (LuaFunction)faso;
Proto p = f.proto();
// :todo: ensure enough stack
if (!p.is_vararg())
{
base = func + 1;
if (stack.size() > base + p.numparams())
{
// trim stack to the argument list
stack.setSize(base + p.numparams());
}
}
else
{
int nargs = (stack.size() - func) - 1;
base = adjust_varargs(p, nargs);
}
int top = base + p.maxstacksize();
inc_ci(func, base, top, r);
savedpc = 0;
// expand stack to the function's max stack size.
stack.setSize(top);
// :todo: implement call hook.
return PCRLUA;
}
else if (faso instanceof LuaJavaCallback)
{
LuaJavaCallback fj = (LuaJavaCallback)faso;
// :todo: checkstack (not sure it's necessary)
base = func + 1;
inc_ci(func, base, stack.size()+MINSTACK, r);
// :todo: call hook
int n = fj.luaFunction(this);
if (n < 0) // yielding?
{
return PCRYIELD;
}
else
{
vmPoscall(stack.size() - n);
return PCRJ;
}
}
throw new IllegalArgumentException();
}
/** Equivalent of luaV_settable. */
private void vmSettable(Object t, Object key, Object val)
{
for (int loop = 0; loop < MAXTAGLOOP; ++loop)
{
Object tm;
if (t instanceof LuaTable) // 't' is a table
{
LuaTable h = (LuaTable)t;
Object o = h.get(key);
if (o != NIL || // result is no nil?
(tm = tagmethod(h, "__newindex")) == null) // or no TM?
{
h.put(key, val);
return;
}
// else will try the tag method
}
else if ((tm = tagmethod(t, "__newindex")) == null)
{
gTypeerror(t, "index");
}
if (isFunction(tm))
{
callTM(tm, t, key, val);
return;
}
t = tm; // else repeat with 'tm'
}
gRunerror("loop in settable");
}
private String vmTostring(Object o)
{
if (o instanceof String)
{
return (String)o;
}
if (!(o instanceof Double))
{
return null;
}
// Convert number to string. PUC-Rio abstracts this operation into
// a macro, lua_number2str. The macro is only invoked from their
// equivalent of this code.
Double d = (Double)o;
String repr = d.toString();
// Note: A naive conversion results in 3..4 == "3.04.0" which isn't
// good. We special case the integers.
if (repr.endsWith(".0"))
{
repr = repr.substring(0, repr.length()-2);
}
return repr;
}
/** Equivalent of adjust_varargs in "ldo.c". */
private int adjust_varargs(Proto p, int actual)
{
int nfixargs = p.numparams();
for (; actual < nfixargs; ++actual)
{
stack.addElement(NIL);
}
// PUC-Rio's LUA_COMPAT_VARARG is not supported here.
// Move fixed parameters to final position
int fixed = stack.size() - actual; // first fixed argument
int base = stack.size(); // final position of first argument
for (int i=0; i<nfixargs; ++i)
{
stack.addElement(stack.elementAt(fixed+i));
stack.setElementAt(NIL, fixed+i);
}
return base;
}
/**
* @param p1 left hand operand. Absolate stack index.
* @param p2 right hand operand. Absolute stack index.
* @param res absolute stack index of result.
* @return false if no tagmethod, true otherwise
*/
private boolean call_binTM(int p1, int p2, int res, String event)
{
Object tm = tagmethod(value(p1), event); // try first operand
if (isNil(tm))
{
tm = tagmethod(value(p2), event); // try second operand
}
if (!isFunction(tm))
{
return false;
}
stack.setElementAt(callTMres(tm, value(p1), value(p2)), res);
return true;
}
/**
* @return -1 if no tagmethod, 0 false, 1 true
*/
private int call_orderTM(Object p1, Object p2, String event)
{
Object tm1 = tagmethod(p1, event);
if (tm1 == NIL) // not metamethod
{
return -1;
}
Object tm2 = tagmethod(p2, event);
if (!oRawequal(tm1, tm2)) // different metamethods?
{
return -1;
}
return isFalse(callTMres(tm1, p1, p2)) ? 0 : 1;
}
private void callTM(Object f, Object p1, Object p2, Object p3)
{
push(f);
push(p1);
push(p2);
push(p3);
vmCall(stack.size()-4, 0);
}
private Object callTMres(Object f, Object p1, Object p2)
{
push(f);
push(p1);
push(p2);
vmCall(stack.size()-3, 1);
Object res = stack.lastElement();
pop(1);
return res;
}
private Object get_compTM(LuaTable mt1, LuaTable mt2, String event)
{
if (mt1 == null)
{
return null;
}
Object tm1 = mt1.get(event);
if (isNil(tm1))
{
return null; // no metamethod
}
if (mt1 == mt2)
{
return tm1; // same metatables => same metamethods
}
if (mt2 == null)
{
return null;
}
Object tm2 = mt2.get(event);
if (isNil(tm2))
{
return null; // no metamethod
}
if (oRawequal(tm1, tm2)) // same metamethods?
{
return tm1;
}
return null;
}
/**
* Gets tagmethod for object.
*/
private Object tagmethod(Object o, String event)
{
LuaTable mt;
mt = getMetatable(o);
if (mt == null)
{
return null;
}
return mt.get(event);
}
/**
* Computes the result of Lua's modules operator (%). Note that this
* modulus operator does not match Java's %.
*/
private static double modulus(double x, double y)
{
return x - Math.floor(x/y)*y;
}
/**
* Convert to number. Returns true if the argument o was converted to
* a number. Converted number is placed in <var>out[0]</var>. Returns
* false if the argument <var>o</var> could not be converted to a number.
* Overloaded.
*/
private static boolean tonumber(Object o, double[] out)
{
if (o instanceof Double)
{
out[0] = ((Double)o).doubleValue();
return true;
}
if (!(o instanceof String))
{
return false;
}
if (oStr2d((String)o, out))
{
return true;
}
return false;
}
/**
* Converts a stack slot to number. Returns true if the element at
* the specified stack slot was converted to a number. False
* otherwise. Note that this actually modifies the element stored at
* <var>idx</var> in the stack (in faithful emulation of the PUC-Rio
* code). Corrupts <code>NUMOP[0]</code>. Overloaded.
* @param idx absolute stack slot.
*/
private boolean tonumber(int idx)
{
if (tonumber(stack.elementAt(idx), NUMOP))
{
stack.setElementAt(new Double(NUMOP[0]), idx);
return true;
}
return false;
}
/**
* Convert a pair of operands for an arithmetic opcode. Stores
* converted results in <code>out[0]</code> and <code>out[1]</code>.
* @return true if and only if both values converted to number.
*/
private static boolean toNumberPair(Object x, Object y, double[] out)
{
if (tonumber(y, out))
{
out[1] = out[0];
if (tonumber(x, out))
{
return true;
}
}
return false;
}
/**
* Convert to string. Returns true if element was number or string
* (the number will have been converted to a string), false otherwise.
* Note this actually modifies the element stored at <var>idx</var> in
* the stack (in faithful emulation of the PUC-Rio code).
*/
private boolean tostring(int idx)
{
Object o = stack.elementAt(idx);
String s = vmTostring(o);
if (s == null)
{
return false;
}
stack.setElementAt(s, idx);
return true;
}
/**
* @param func absolute stack index of the function object.
*/
private Object tryfuncTM(int func)
{
Object tm = tagmethod(stack.elementAt(func), "__call");
if (!isFunction(tm))
{
gTypeerror(stack.elementAt(func), "call");
}
insert(tm, func);
return tm;
}
/** Lua's is False predicate. */
private boolean isFalse(Object o)
{
return o == NIL || Boolean.FALSE.equals(o);
}
/** Make new CallInfo record. */
private CallInfo inc_ci(int func, int base, int top, int nresults)
{
ci = new CallInfo(func, base, top, nresults);
civ.addElement(ci);
return ci;
}
/** Pop topmost CallInfo record and return it. */
private CallInfo dec_ci()
{
CallInfo ci = (CallInfo)civ.pop();
this.ci = (CallInfo)civ.lastElement();
return ci;
}
/** corresponds to ldump's luaU_dump method, but with data gone and writer
replaced by OutputStream */
int uDump(Proto f, OutputStream writer, boolean strip) throws IOException
{
DumpState D = new DumpState(this, new DataOutputStream(writer), strip) ;
D.DumpHeader();
D.DumpFunction(f, null);
D.writer.flush();
return D.status;
}
}
final class DumpState
{
// Lua L; // not needed?
DataOutputStream writer;
boolean strip;
int status;
boolean littleEndian = true ;
// :TODO: Lua interface is for a writer interface, not a stream
DumpState(Lua L, DataOutputStream writer, boolean strip)
{
// this.L = L;
this.writer = writer ;
this.strip = strip ;
}
DumpState(Lua L, DataOutputStream writer, boolean strip, boolean littleEndian)
{
this (L, writer, strip);
this.littleEndian = littleEndian ;
}
//////////////// dumper ////////////////////
static final byte [] header = new byte []
{ 0x1B, 0x4C, 0x75, 0x61,
0x51, 0x00, 0x00, 0x04, // big endian currently
0x04, 0x04, 0x08, 0x00
} ;
void DumpHeader() throws IOException
{
writer.write(header, 0, 6) ;
writer.writeByte(littleEndian ? 0x01 : 0x00) ;
writer.write(header, 7, 5) ;
}
private void DumpInt(int i) throws IOException
{
if (littleEndian)
{
writer.writeByte(i) ;
writer.writeByte(i >>> 8) ;
writer.writeByte(i >>> 16) ;
writer.writeByte(i >>> 24) ;
}
else
writer.writeInt(i) ;// big-endian version
}
private void DumpNumber(double d) throws IOException
{
if (littleEndian)
{
ByteArrayOutputStream sos = new ByteArrayOutputStream() ;
DataOutputStream dos = new DataOutputStream(sos) ;
dos.writeDouble(d) ;
dos.flush() ;
byte [] bytes = sos.toByteArray() ;
for (int i = 7 ; i >= 0 ; i--)
writer.writeByte(bytes[i]) ;
}
else
writer.writeDouble(d) ;
}
void DumpFunction(Proto f, String p) throws IOException
{
DumpString((f.source == p || strip) ? null : f.source);
DumpInt(f.linedefined);
DumpInt(f.lastlinedefined);
writer.writeByte(f.nups);
writer.writeByte(f.numparams);
writer.writeBoolean(f.is_vararg);
writer.writeByte(f.maxstacksize);
DumpCode(f);
DumpConstants(f);
DumpDebug(f);
}
private void DumpCode(Proto f) throws IOException
{
int n = f.sizecode ;
int [] code = f.code ;
DumpInt(n);
for (int i = 0 ; i < n ; i++)
DumpInt(code[i]) ;
}
private void DumpConstants(Proto f) throws IOException
{
int n = f.sizek;
Object [] k = f.k ;
DumpInt(n) ;
for (int i = 0 ; i < n ; i++)
{
Object o = k[i] ;
if (o == null)
{
writer.writeByte(Lua.TNIL) ;
}
else if (o instanceof Boolean)
{
writer.writeByte(Lua.TBOOLEAN) ;
writer.writeBoolean(((Boolean)o).booleanValue()) ;
}
else if (o instanceof Double)
{
writer.writeByte(Lua.TNUMBER) ;
DumpNumber(((Double)o).doubleValue()) ;
}
else if (o instanceof String)
{
writer.writeByte(Lua.TSTRING) ;
DumpString((String)o) ;
}
else
{
//lua_assert(false); /* cannot happen */
}
}
n = f.sizep ;
DumpInt(n) ;
for (int i = 0 ; i < n ; i++)
{
Proto subfunc = f.p[i] ;
DumpFunction(subfunc, f.source) ;
}
}
private void DumpString(String s) throws IOException
{
if (s == null)
{
DumpInt(0);
}
else
{
try
{
byte [] contents = s.getBytes("UTF-8") ;
int size = contents.length ;
DumpInt(size+1) ;
writer.write(contents, 0, size) ;
writer.writeByte(0) ;
}
catch (UnsupportedEncodingException uee)
{
// :todo: handle this case appropriately
}
}
}
private void DumpDebug(Proto f) throws IOException
{
if (strip)
{
DumpInt(0) ;
DumpInt(0) ;
DumpInt(0) ;
return ;
}
int n = f.sizelineinfo;
DumpInt(n);
for (int i=0; i<n; i++)
DumpInt(f.lineinfo[i]) ;
n = f.sizelocvars;
DumpInt(n);
for (int i=0; i<n; i++)
{
LocVar locvar = f.locvars[i] ;
DumpString(locvar.varname);
DumpInt(locvar.startpc);
DumpInt(locvar.endpc);
}
n = f.sizeupvalues;
DumpInt(n);
for (int i=0; i<n; i++)
DumpString(f.upvalues[i]);
}
}
| true | true |
private void vmExecute(int nexeccalls)
{
// This labelled while loop is used to simulate the effect of C's
// goto. The end of the while loop is never reached. The beginning
// of the while loop is branched to using a "continue reentry;"
// statement (when a Lua function is called or returns).
reentry:
while (true)
{
// assert stack.elementAt[ci.function()] instanceof LuaFunction;
LuaFunction function = (LuaFunction)stack.elementAt(ci.function());
Proto proto = function.proto();
int[] code = proto.code();
Object[] k = proto.constant();
int pc = savedpc;
while (true) // main loop of interpreter
{
// Where the PUC-Rio code used the Protect macro, this has been
// replaced with "savedpc = pc" and a "// Protect" comment.
// Where the PUC-Rio code used the dojump macro, this has been
// replaced with the equivalent increment of the pc and a
// "//dojump" comment.
int i = code[pc++]; // VM instruction.
// :todo: count and line hook
int a = ARGA(i); // its A field.
Object rb;
Object rc;
switch (OPCODE(i))
{
case OP_MOVE:
stack.setElementAt(stack.elementAt(base+ARGB(i)), base+a);
continue;
case OP_LOADK:
stack.setElementAt(k[ARGBx(i)], base+a);
continue;
case OP_LOADBOOL:
stack.setElementAt(valueOfBoolean(ARGB(i) != 0), base+a);
if (ARGC(i) != 0)
{
++pc;
}
continue;
case OP_LOADNIL:
{
int b = base + ARGB(i);
do
{
stack.setElementAt(NIL, b--);
} while (b >= base + a);
continue;
}
case OP_GETUPVAL:
{
int b = ARGB(i);
stack.setElementAt(function.upVal(b).getValue(), base+a);
continue;
}
case OP_GETGLOBAL:
rb = k[ARGBx(i)];
// assert rb instance of String;
savedpc = pc; // Protect
stack.setElementAt(vmGettable(function.getEnv(), rb), base+a);
continue;
case OP_GETTABLE:
{
savedpc = pc; // Protect
Object t = stack.elementAt(base+ARGB(i));
stack.setElementAt(vmGettable(t, RK(k, ARGC(i))), base+a);
continue;
}
case OP_SETUPVAL:
{
UpVal uv = function.upVal(ARGB(i));
uv.setValue(stack.elementAt(base+a));
continue;
}
case OP_SETGLOBAL:
savedpc = pc; // Protect
vmSettable(function.getEnv(), k[ARGBx(i)],
stack.elementAt(base+a));
continue;
case OP_SETTABLE:
{
savedpc = pc; // Protect
Object t = stack.elementAt(base+a);
vmSettable(t, RK(k, ARGB(i)), RK(k, ARGC(i)));
continue;
}
case OP_NEWTABLE:
{
// :todo: use the b and c hints, currently ignored.
int b = ARGB(i);
int c = ARGC(i);
stack.setElementAt(new LuaTable(), base+a);
continue;
}
case OP_SELF:
{
int b = ARGB(i);
rb = stack.elementAt(base+b);
stack.setElementAt(rb, base+a+1);
savedpc = pc; // Protect
stack.setElementAt(vmGettable(rb, RK(k, ARGC(i))), base+a);
continue;
}
case OP_ADD:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double sum = ((Double)rb).doubleValue() +
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(sum), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double sum = NUMOP[0] + NUMOP[1];
stack.setElementAt(valueOfNumber(sum), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__add"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_SUB:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double difference = ((Double)rb).doubleValue() -
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(difference), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double difference = NUMOP[0] - NUMOP[1];
stack.setElementAt(valueOfNumber(difference), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__sub"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_MUL:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double product = ((Double)rb).doubleValue() *
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(product), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double product = NUMOP[0] * NUMOP[1];
stack.setElementAt(valueOfNumber(product), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__mul"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_DIV:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double quotient = ((Double)rb).doubleValue() /
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(quotient), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double quotient = NUMOP[0] / NUMOP[1];
stack.setElementAt(valueOfNumber(quotient), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__div"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_MOD:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double db = ((Double)rb).doubleValue();
double dc = ((Double)rc).doubleValue();
double modulus = modulus(db, dc);
stack.setElementAt(valueOfNumber(modulus), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double modulus = modulus(NUMOP[0], NUMOP[1]);
stack.setElementAt(valueOfNumber(modulus), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__mod"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_POW:
// There's no Math.pow. :todo: consider implementing.
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double result = iNumpow(((Double)rb).doubleValue(),
((Double)rc).doubleValue());
stack.setElementAt(valueOfNumber(result), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double result = iNumpow(NUMOP[0], NUMOP[1]);
stack.setElementAt(valueOfNumber(result), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__pow"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_UNM:
{
rb = stack.elementAt(base+ARGB(i));
if (rb instanceof Double)
{
double db = ((Double)rb).doubleValue();
stack.setElementAt(valueOfNumber(-db), base+a);
}
else if (tonumber(rb, NUMOP))
{
stack.setElementAt(valueOfNumber(-NUMOP[0]), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGB(i), base+a,
"__unm"))
{
gAritherror(base+ARGB(i), base+ARGB(i));
}
continue;
}
case OP_NOT:
{
Object ra = stack.elementAt(base+ARGB(i));
stack.setElementAt(valueOfBoolean(isFalse(ra)), base+a);
continue;
}
case OP_LEN:
rb = stack.elementAt(base+ARGB(i));
if (rb instanceof LuaTable)
{
LuaTable t = (LuaTable)rb;
stack.setElementAt(new Double(t.getn()), base+a);
continue;
}
else if (rb instanceof String)
{
String s = (String)rb;
stack.setElementAt(new Double(s.length()), base+a);
continue;
}
savedpc = pc; // Protect
if (!call_binTM(base+ARGB(i), base+ARGB(i), base+a, "__len"))
{
gTypeerror(rb, "get length of");
}
continue;
case OP_CONCAT:
{
int b = ARGB(i);
int c = ARGC(i);
savedpc = pc; // Protect
// :todo: It's possible that the compiler assumes that all
// stack locations _above_ b end up with junk in them. In
// which case we can improve the speed of vmConcat (by not
// converting each stack slot, but simply using
// StringBuffer.append on whatever is there).
vmConcat(c - b + 1, c);
stack.setElementAt(stack.elementAt(base+b), base+a);
continue;
}
case OP_JMP:
// dojump
pc += ARGsBx(i);
continue;
case OP_EQ:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (vmEqual(rb, rc) == (a != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_LT:
savedpc = pc; // Protect
if (vmLessthan(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_LE:
savedpc = pc; // Protect
if (vmLessequal(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_TEST:
if (isFalse(stack.elementAt(base+a)) != (ARGC(i) != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_TESTSET:
rb = stack.elementAt(base+ARGB(i));
if (isFalse(rb) != (ARGC(i) != 0))
{
stack.setElementAt(rb, base+a);
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_CALL:
{
int b = ARGB(i);
int nresults = ARGC(i) - 1;
if (b != 0)
{
stack.setSize(base+a+b);
}
savedpc = pc;
switch (vmPrecall(base+a, nresults))
{
case PCRLUA:
nexeccalls++;
continue reentry;
case PCRJ:
// Was Java function called by precall, adjust result
if (nresults >= 0)
{
stack.setSize(ci.top());
}
continue;
default:
return; // yield
}
}
case OP_TAILCALL:
{
int b = ARGB(i);
if (b != 0)
{
stack.setSize(base+a+b);
}
savedpc = pc;
// assert ARGC(i) - 1 == MULTRET
switch (vmPrecall(base+a, MULTRET))
{
case PCRLUA:
{
// tail call: put new frame in place of previous one.
CallInfo ci = (CallInfo)civ.elementAt(civ.size()-2);
int func = ci.function();
int pfunc = this.ci.function();
fClose(base);
base = func + (this.ci.base() - pfunc);
int aux; // loop index is used after loop ends
for (aux=0; pfunc+aux < stack.size(); ++aux)
{
// move frame down
stack.setElementAt(stack.elementAt(pfunc+aux), func+aux);
}
stack.setSize(func+aux); // correct top
// assert stack.size() == base + ((LuaFunction)stack.elementAt(func)).proto().maxstacksize();
ci.tailcall(base, stack.size());
dec_ci(); // remove new frame.
continue reentry;
}
case PCRJ: // It was a Java function
{
continue;
}
default:
{
return; // yield
}
}
}
case OP_RETURN:
{
fClose(base);
int b = ARGB(i);
if (b != 0)
{
int top = a + b - 1;
stack.setSize(base + top);
}
savedpc = pc;
// 'adjust' replaces aliased 'b' in PUC-Rio code.
boolean adjust = vmPoscall(base+a);
if (--nexeccalls == 0)
{
return;
}
if (adjust)
{
stack.setSize(ci.top());
}
continue reentry;
}
case OP_FORLOOP:
{
double step =
((Double)stack.elementAt(base+a+2)).doubleValue();
double idx =
((Double)stack.elementAt(base+a)).doubleValue() + step;
double limit =
((Double)stack.elementAt(base+a+1)).doubleValue();
if ((0 < step && idx <= limit) ||
(step <= 0 && limit <= idx))
{
// dojump
pc += ARGsBx(i);
Object d = valueOfNumber(idx);
stack.setElementAt(d, base+a); // internal index
stack.setElementAt(d, base+a+3); // external index
}
continue;
}
case OP_FORPREP:
{
int init = base+a;
int plimit = base+a+1;
int pstep = base+a+2;
savedpc = pc; // next steps may throw errors
if (!tonumber(init))
{
gRunerror("'for' initial value must be a number");
}
else if (!tonumber(plimit))
{
gRunerror("'for' limit must be a number");
}
else if (!tonumber(pstep))
{
gRunerror("'for' step must be a number");
}
double step =
((Double)stack.elementAt(pstep)).doubleValue();
double idx =
((Double)stack.elementAt(init)).doubleValue() - step;
stack.setElementAt(new Double(idx), init);
// dojump
pc += ARGsBx(i);
continue;
}
case OP_TFORLOOP:
{
int cb = base+a+3; // call base
stack.setElementAt(stack.elementAt(base+a+2), cb+2);
stack.setElementAt(stack.elementAt(base+a+1), cb+1);
stack.setElementAt(stack.elementAt(base+a), cb);
stack.setSize(cb+3);
savedpc = pc; // Protect
vmCall(cb, ARGC(i));
stack.setSize(ci.top());
if (NIL != stack.elementAt(cb)) // continue loop
{
stack.setElementAt(stack.elementAt(cb), cb-1);
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
}
case OP_SETLIST:
{
int n = ARGB(i);
int c = ARGC(i);
int last;
LuaTable t;
if (0 == n)
{
n = (stack.size() - a) - 1;
// :todo: check this against PUC-Rio
// stack.setSize ??
}
if (0 == c)
{
c = code[pc++];
}
t = (LuaTable)stack.elementAt(base+a);
last = ((c-1)*LFIELDS_PER_FLUSH) + n;
// :todo: consider expanding space in table
for (; n > 0; n--)
{
Object val = stack.elementAt(base+a+n);
t.putnum(last--, val);
}
continue;
}
case OP_CLOSE:
fClose(base+a);
continue;
case OP_CLOSURE:
{
Proto p = function.proto().proto()[ARGBx(i)];
int nup = p.nups();
UpVal[] up = new UpVal[nup];
for (int j=0; j<nup; j++, pc++)
{
int in = code[pc];
if (OPCODE(in) == OP_GETUPVAL)
{
up[j] = function.upVal(ARGB(in));
}
else
{
// assert OPCODE(in) == OP_MOVE;
up[j] = fFindupval(base + ARGB(in));
}
}
LuaFunction nf = new LuaFunction(p, up, function.getEnv());
stack.setElementAt(nf, base+a);
continue;
}
case OP_VARARG:
{
int b = ARGB(i)-1;
int n = (base - ci.function()) -
function.proto().numparams() - 1;
if (b == MULTRET)
{
// :todo: Protect
// :todo: check stack
b = n;
stack.setSize(base+a+n);
}
for (int j=0; j<b; ++j)
{
if (j < n)
{
Object src = stack.elementAt(base - n + j);
stack.setElementAt(src, base+a+j);
}
else
{
stack.setElementAt(NIL, base+a+j);
}
}
continue;
}
} /* switch */
} /* while */
} /* reentry: while */
}
|
private void vmExecute(int nexeccalls)
{
// This labelled while loop is used to simulate the effect of C's
// goto. The end of the while loop is never reached. The beginning
// of the while loop is branched to using a "continue reentry;"
// statement (when a Lua function is called or returns).
reentry:
while (true)
{
// assert stack.elementAt[ci.function()] instanceof LuaFunction;
LuaFunction function = (LuaFunction)stack.elementAt(ci.function());
Proto proto = function.proto();
int[] code = proto.code();
Object[] k = proto.constant();
int pc = savedpc;
while (true) // main loop of interpreter
{
// Where the PUC-Rio code used the Protect macro, this has been
// replaced with "savedpc = pc" and a "// Protect" comment.
// Where the PUC-Rio code used the dojump macro, this has been
// replaced with the equivalent increment of the pc and a
// "//dojump" comment.
int i = code[pc++]; // VM instruction.
// :todo: count and line hook
int a = ARGA(i); // its A field.
Object rb;
Object rc;
switch (OPCODE(i))
{
case OP_MOVE:
stack.setElementAt(stack.elementAt(base+ARGB(i)), base+a);
continue;
case OP_LOADK:
stack.setElementAt(k[ARGBx(i)], base+a);
continue;
case OP_LOADBOOL:
stack.setElementAt(valueOfBoolean(ARGB(i) != 0), base+a);
if (ARGC(i) != 0)
{
++pc;
}
continue;
case OP_LOADNIL:
{
int b = base + ARGB(i);
do
{
stack.setElementAt(NIL, b--);
} while (b >= base + a);
continue;
}
case OP_GETUPVAL:
{
int b = ARGB(i);
stack.setElementAt(function.upVal(b).getValue(), base+a);
continue;
}
case OP_GETGLOBAL:
rb = k[ARGBx(i)];
// assert rb instance of String;
savedpc = pc; // Protect
stack.setElementAt(vmGettable(function.getEnv(), rb), base+a);
continue;
case OP_GETTABLE:
{
savedpc = pc; // Protect
Object t = stack.elementAt(base+ARGB(i));
stack.setElementAt(vmGettable(t, RK(k, ARGC(i))), base+a);
continue;
}
case OP_SETUPVAL:
{
UpVal uv = function.upVal(ARGB(i));
uv.setValue(stack.elementAt(base+a));
continue;
}
case OP_SETGLOBAL:
savedpc = pc; // Protect
vmSettable(function.getEnv(), k[ARGBx(i)],
stack.elementAt(base+a));
continue;
case OP_SETTABLE:
{
savedpc = pc; // Protect
Object t = stack.elementAt(base+a);
vmSettable(t, RK(k, ARGB(i)), RK(k, ARGC(i)));
continue;
}
case OP_NEWTABLE:
{
// :todo: use the b and c hints, currently ignored.
int b = ARGB(i);
int c = ARGC(i);
stack.setElementAt(new LuaTable(), base+a);
continue;
}
case OP_SELF:
{
int b = ARGB(i);
rb = stack.elementAt(base+b);
stack.setElementAt(rb, base+a+1);
savedpc = pc; // Protect
stack.setElementAt(vmGettable(rb, RK(k, ARGC(i))), base+a);
continue;
}
case OP_ADD:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double sum = ((Double)rb).doubleValue() +
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(sum), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double sum = NUMOP[0] + NUMOP[1];
stack.setElementAt(valueOfNumber(sum), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__add"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_SUB:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double difference = ((Double)rb).doubleValue() -
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(difference), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double difference = NUMOP[0] - NUMOP[1];
stack.setElementAt(valueOfNumber(difference), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__sub"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_MUL:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double product = ((Double)rb).doubleValue() *
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(product), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double product = NUMOP[0] * NUMOP[1];
stack.setElementAt(valueOfNumber(product), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__mul"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_DIV:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double quotient = ((Double)rb).doubleValue() /
((Double)rc).doubleValue();
stack.setElementAt(valueOfNumber(quotient), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double quotient = NUMOP[0] / NUMOP[1];
stack.setElementAt(valueOfNumber(quotient), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__div"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_MOD:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double db = ((Double)rb).doubleValue();
double dc = ((Double)rc).doubleValue();
double modulus = modulus(db, dc);
stack.setElementAt(valueOfNumber(modulus), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double modulus = modulus(NUMOP[0], NUMOP[1]);
stack.setElementAt(valueOfNumber(modulus), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__mod"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_POW:
// There's no Math.pow. :todo: consider implementing.
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (rb instanceof Double && rc instanceof Double)
{
double result = iNumpow(((Double)rb).doubleValue(),
((Double)rc).doubleValue());
stack.setElementAt(valueOfNumber(result), base+a);
}
else if (toNumberPair(rb, rc, NUMOP))
{
double result = iNumpow(NUMOP[0], NUMOP[1]);
stack.setElementAt(valueOfNumber(result), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGC(i), base+a,
"__pow"))
{
gAritherror(base+ARGB(i), base+ARGC(i));
}
continue;
case OP_UNM:
{
rb = stack.elementAt(base+ARGB(i));
if (rb instanceof Double)
{
double db = ((Double)rb).doubleValue();
stack.setElementAt(valueOfNumber(-db), base+a);
}
else if (tonumber(rb, NUMOP))
{
stack.setElementAt(valueOfNumber(-NUMOP[0]), base+a);
}
else if (!call_binTM(base+ARGB(i), base+ARGB(i), base+a,
"__unm"))
{
gAritherror(base+ARGB(i), base+ARGB(i));
}
continue;
}
case OP_NOT:
{
Object ra = stack.elementAt(base+ARGB(i));
stack.setElementAt(valueOfBoolean(isFalse(ra)), base+a);
continue;
}
case OP_LEN:
rb = stack.elementAt(base+ARGB(i));
if (rb instanceof LuaTable)
{
LuaTable t = (LuaTable)rb;
stack.setElementAt(new Double(t.getn()), base+a);
continue;
}
else if (rb instanceof String)
{
String s = (String)rb;
stack.setElementAt(new Double(s.length()), base+a);
continue;
}
savedpc = pc; // Protect
if (!call_binTM(base+ARGB(i), base+ARGB(i), base+a, "__len"))
{
gTypeerror(rb, "get length of");
}
continue;
case OP_CONCAT:
{
int b = ARGB(i);
int c = ARGC(i);
savedpc = pc; // Protect
// :todo: It's possible that the compiler assumes that all
// stack locations _above_ b end up with junk in them. In
// which case we can improve the speed of vmConcat (by not
// converting each stack slot, but simply using
// StringBuffer.append on whatever is there).
vmConcat(c - b + 1, c);
stack.setElementAt(stack.elementAt(base+b), base+a);
continue;
}
case OP_JMP:
// dojump
pc += ARGsBx(i);
continue;
case OP_EQ:
rb = RK(k, ARGB(i));
rc = RK(k, ARGC(i));
if (vmEqual(rb, rc) == (a != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_LT:
savedpc = pc; // Protect
if (vmLessthan(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_LE:
savedpc = pc; // Protect
if (vmLessequal(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_TEST:
if (isFalse(stack.elementAt(base+a)) != (ARGC(i) != 0))
{
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_TESTSET:
rb = stack.elementAt(base+ARGB(i));
if (isFalse(rb) != (ARGC(i) != 0))
{
stack.setElementAt(rb, base+a);
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
case OP_CALL:
{
int b = ARGB(i);
int nresults = ARGC(i) - 1;
if (b != 0)
{
stack.setSize(base+a+b);
}
savedpc = pc;
switch (vmPrecall(base+a, nresults))
{
case PCRLUA:
nexeccalls++;
continue reentry;
case PCRJ:
// Was Java function called by precall, adjust result
if (nresults >= 0)
{
stack.setSize(ci.top());
}
continue;
default:
return; // yield
}
}
case OP_TAILCALL:
{
int b = ARGB(i);
if (b != 0)
{
stack.setSize(base+a+b);
}
savedpc = pc;
// assert ARGC(i) - 1 == MULTRET
switch (vmPrecall(base+a, MULTRET))
{
case PCRLUA:
{
// tail call: put new frame in place of previous one.
CallInfo ci = (CallInfo)civ.elementAt(civ.size()-2);
int func = ci.function();
int pfunc = this.ci.function();
fClose(ci.base());
base = func + (this.ci.base() - pfunc);
int aux; // loop index is used after loop ends
for (aux=0; pfunc+aux < stack.size(); ++aux)
{
// move frame down
stack.setElementAt(stack.elementAt(pfunc+aux), func+aux);
}
stack.setSize(func+aux); // correct top
// assert stack.size() == base + ((LuaFunction)stack.elementAt(func)).proto().maxstacksize();
ci.tailcall(base, stack.size());
dec_ci(); // remove new frame.
continue reentry;
}
case PCRJ: // It was a Java function
{
continue;
}
default:
{
return; // yield
}
}
}
case OP_RETURN:
{
fClose(base);
int b = ARGB(i);
if (b != 0)
{
int top = a + b - 1;
stack.setSize(base + top);
}
savedpc = pc;
// 'adjust' replaces aliased 'b' in PUC-Rio code.
boolean adjust = vmPoscall(base+a);
if (--nexeccalls == 0)
{
return;
}
if (adjust)
{
stack.setSize(ci.top());
}
continue reentry;
}
case OP_FORLOOP:
{
double step =
((Double)stack.elementAt(base+a+2)).doubleValue();
double idx =
((Double)stack.elementAt(base+a)).doubleValue() + step;
double limit =
((Double)stack.elementAt(base+a+1)).doubleValue();
if ((0 < step && idx <= limit) ||
(step <= 0 && limit <= idx))
{
// dojump
pc += ARGsBx(i);
Object d = valueOfNumber(idx);
stack.setElementAt(d, base+a); // internal index
stack.setElementAt(d, base+a+3); // external index
}
continue;
}
case OP_FORPREP:
{
int init = base+a;
int plimit = base+a+1;
int pstep = base+a+2;
savedpc = pc; // next steps may throw errors
if (!tonumber(init))
{
gRunerror("'for' initial value must be a number");
}
else if (!tonumber(plimit))
{
gRunerror("'for' limit must be a number");
}
else if (!tonumber(pstep))
{
gRunerror("'for' step must be a number");
}
double step =
((Double)stack.elementAt(pstep)).doubleValue();
double idx =
((Double)stack.elementAt(init)).doubleValue() - step;
stack.setElementAt(new Double(idx), init);
// dojump
pc += ARGsBx(i);
continue;
}
case OP_TFORLOOP:
{
int cb = base+a+3; // call base
stack.setElementAt(stack.elementAt(base+a+2), cb+2);
stack.setElementAt(stack.elementAt(base+a+1), cb+1);
stack.setElementAt(stack.elementAt(base+a), cb);
stack.setSize(cb+3);
savedpc = pc; // Protect
vmCall(cb, ARGC(i));
stack.setSize(ci.top());
if (NIL != stack.elementAt(cb)) // continue loop
{
stack.setElementAt(stack.elementAt(cb), cb-1);
// dojump
pc += ARGsBx(code[pc]);
}
++pc;
continue;
}
case OP_SETLIST:
{
int n = ARGB(i);
int c = ARGC(i);
int last;
LuaTable t;
if (0 == n)
{
n = (stack.size() - a) - 1;
// :todo: check this against PUC-Rio
// stack.setSize ??
}
if (0 == c)
{
c = code[pc++];
}
t = (LuaTable)stack.elementAt(base+a);
last = ((c-1)*LFIELDS_PER_FLUSH) + n;
// :todo: consider expanding space in table
for (; n > 0; n--)
{
Object val = stack.elementAt(base+a+n);
t.putnum(last--, val);
}
continue;
}
case OP_CLOSE:
fClose(base+a);
continue;
case OP_CLOSURE:
{
Proto p = function.proto().proto()[ARGBx(i)];
int nup = p.nups();
UpVal[] up = new UpVal[nup];
for (int j=0; j<nup; j++, pc++)
{
int in = code[pc];
if (OPCODE(in) == OP_GETUPVAL)
{
up[j] = function.upVal(ARGB(in));
}
else
{
// assert OPCODE(in) == OP_MOVE;
up[j] = fFindupval(base + ARGB(in));
}
}
LuaFunction nf = new LuaFunction(p, up, function.getEnv());
stack.setElementAt(nf, base+a);
continue;
}
case OP_VARARG:
{
int b = ARGB(i)-1;
int n = (base - ci.function()) -
function.proto().numparams() - 1;
if (b == MULTRET)
{
// :todo: Protect
// :todo: check stack
b = n;
stack.setSize(base+a+n);
}
for (int j=0; j<b; ++j)
{
if (j < n)
{
Object src = stack.elementAt(base - n + j);
stack.setElementAt(src, base+a+j);
}
else
{
stack.setElementAt(NIL, base+a+j);
}
}
continue;
}
} /* switch */
} /* while */
} /* reentry: while */
}
|
diff --git a/src/main/java/net/praqma/hudson/scm/PucmScm.java b/src/main/java/net/praqma/hudson/scm/PucmScm.java
index 7a77996..f895b37 100644
--- a/src/main/java/net/praqma/hudson/scm/PucmScm.java
+++ b/src/main/java/net/praqma/hudson/scm/PucmScm.java
@@ -1,585 +1,585 @@
package net.praqma.hudson.scm;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.BuildListener;
import hudson.model.TaskListener;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.scm.ChangeLogParser;
import hudson.scm.PollingResult;
import hudson.scm.SCMDescriptor;
import hudson.scm.SCMRevisionState;
import hudson.scm.SCM;
import hudson.util.FormValidation;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import net.praqma.clearcase.ucm.UCMException;
import net.praqma.clearcase.ucm.entities.Project;
import net.praqma.clearcase.ucm.entities.Baseline;
import net.praqma.clearcase.ucm.entities.Tag;
import net.praqma.clearcase.ucm.entities.Activity;
import net.praqma.clearcase.ucm.entities.Baseline.BaselineDiff;
import net.praqma.clearcase.ucm.entities.Component;
import net.praqma.clearcase.ucm.entities.Component.BaselineList;
import net.praqma.clearcase.ucm.entities.Stream;
import net.praqma.clearcase.ucm.entities.UCM;
import net.praqma.clearcase.ucm.entities.UCMEntity;
import net.praqma.clearcase.ucm.entities.UCMEntityException;
import net.praqma.clearcase.ucm.entities.Version;
import net.praqma.clearcase.ucm.persistence.UCMContext;
import net.praqma.clearcase.ucm.persistence.UCMStrategyCleartool;
import net.praqma.clearcase.ucm.utils.TagQuery;
import net.praqma.clearcase.ucm.view.SnapshotView;
import net.praqma.clearcase.ucm.view.SnapshotView.COMP;
import net.praqma.clearcase.ucm.view.UCMView;
import net.praqma.hudson.Config;
import net.praqma.utils.Debug;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
/**
* CC4HClass is responsible for everything regarding Hudsons connection to
* ClearCase pre-build. This class defines all the files required by the user.
* The information can be entered on the config page.
*
* @author Troels Selch S�rensen
* @author Margit Bennetzen
*
*/
public class PucmScm extends SCM
{
private String levelToPoll;
private String loadModule;
private String component;
private String stream;
private boolean newest;
private boolean newerThanRecommended;
private Baseline bl;
private List<String> levels = null;
private List<String> loadModules = null;
private BaselineList baselines;
private boolean compRevCalled;
private StringBuffer pollMsgs = new StringBuffer();
private Stream integrationstream;
private Component co;
private SnapshotView sv = null;
protected static Debug logger = Debug.GetLogger();
/**
* The constructor is used by Hudson to create the instance of the plugin
* needed for a connection to ClearCase. It is annotated with
* <code>@DataBoundConstructor</code> to tell Hudson where to put the
* information retrieved from the configuration page in the WebUI.
*
* @param component
* defines the component needed to find baselines.
* @param levelToPoll
* defines the level to poll ClearCase for.
* @param loadModule
* tells if we should load all modules or only the ones that are
* modifiable.
* @param stream
* defines the stream needed to find baselines.
* @param newest
* tells whether we should build only the newest baseline.
* @param newerThanRecommended
* tells whether we should look at all baselines or only ones
* newer than the recommended baseline
*/
@DataBoundConstructor
public PucmScm( String component, String levelToPoll, String loadModule, String stream, boolean newest, boolean newerThanRecommended, boolean testing )
{
logger.trace_function();
this.component = component;
this.levelToPoll = levelToPoll;
this.loadModule = loadModule;
this.stream = stream;
this.newest = newest;
this.newerThanRecommended = newerThanRecommended;
}
@Override
public boolean checkout( AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile ) throws IOException, InterruptedException
{
logger.trace_function();
boolean result = true;
//consoleOutput Printstream is from Hudson, so it can only be accessed here
PrintStream consoleOutput = listener.getLogger();
consoleOutput.println("Workspace: "+workspace);
String jobname = build.getParent().getDisplayName();
// compRevCalled tells whether we have polled for baselines to build -
// so if we haven't polled, we do it now
if ( !compRevCalled )
{
result = baselinesToBuild( jobname );
}
compRevCalled = false;
// pollMsgs are set in either compareRemoteRevisionWith() or
// baselinesToBuild()
consoleOutput.println( pollMsgs );
pollMsgs = new StringBuffer();
if ( result )
{
result = makeWorkspace( consoleOutput , workspace );
if( !result )
{
consoleOutput.println( "Could not make workspace. Marking baseline with:" );
}
}
if ( result )
{
BaselineDiff changes = bl.GetDiffs(sv);
consoleOutput.println( changes.size() + " elements changed" );
result = writeChangelog( changelogFile, changes, consoleOutput );
}
return result;
}
private boolean makeWorkspace( PrintStream hudsonOut, FilePath workspace )
{
boolean result = true;
// We know we have a stream (st), because it is set in baselinesToBuild()
// TODO verify viewtag
String viewtag = "Hudson_Server_dev_view";//"pucm_" + System.getenv( "COMPUTERNAME" );//TODO +hudsonjobname i stinavn
File viewroot = new File( workspace + "\\view\\"+viewtag );
try
{
if ( viewroot.mkdir() )
{
hudsonOut.println( "Created viewroot " + viewroot.toString() );
}
else
{
hudsonOut.println( "Reusing viewroot " + viewroot.toString() );
}
}
catch ( Exception e )
{
hudsonOut.println( "Could not make viewroot " + viewroot.toString() + ". Cause: " + e.getMessage() );
result = false;
}
if( result )
{
// Hvis der er et snaphotview med et givent viewtag i cleartool s�:
if ( UCMView.ViewExists( viewtag ) )
{
sv = UCMView.GetSnapshotView( viewroot );
try
{
sv.ViewrootIsValid();//(returns uuid)
} catch (UCMException ucmE)
{
// then viewroot is regenerated
//TODO SnapshotView.RegenerateViewDotDat( viewroot, viewtag );//venter p� at CHW laver den statisk :-) eller sletter viewroot/tag
}
//All below parameters according to LAK and CHW
//sv.Update( true, true, true, true/*chw fjerne force*/, false, COMP.valueOf( loadModule.toUpperCase() ), null );//components eller loadrules = null, det er loadmodules vi skal bruge
}
else
{
//TODO when CHW has made a function to make new snapshotview, it must be implemented
sv = UCMView.GetSnapshotView( viewroot );
}
if(sv==null)
{
result = false;
}
if( result )
{
Stream devstream = Config.devStream(); //view: Hudson_Server_dev_view
// Now we have to rebase - if a rebase is in progress, the old one must be stopped and the new started instead
if(devstream.IsRebaseInProgress())
{
devstream.CancelRebase();
}
//The last boolean, complete, must always be true from PUCM as we are always working on a read-only stream according to LAK
devstream.Rebase( sv, bl, true );
}
}
return result;
}
private boolean writeChangelog( File changelogFile, BaselineDiff changes, PrintStream hudsonOut ) throws IOException
{
boolean result;
logger.trace_function();
StringBuffer buffer = new StringBuffer();
// Here the .hudson/jobs/[project name]/builds/[buildnumber]/changelog.xml is written
hudsonOut.print( "Writing Hudson changelog..." );
try
{
buffer.append( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" );
buffer.append( "<changelog>" );
buffer.append( "<changeset>" );
buffer.append( "<entry>" );
buffer.append( ( "<blName>" + bl.GetShortname() + "</blName>" ) );
for ( Activity act : changes )
{
buffer.append( "<activity>" );
buffer.append( ( "<actName>" + act.GetShortname() + "</actName>" ) );
buffer.append( ( "<author>Hudson" + act.GetUser() + "</author>" ) );
List<Version> versions = act.changeset.versions;
String temp;
for ( Version v : versions )
{
temp = "<file>" + v.toString() + " " + v.Blame() + "</file>";
buffer.append( temp );
}
buffer.append( "</activity>" );
}
buffer.append( "</entry>" );
buffer.append( "</changeset>" );
buffer.append( "</changelog>" );
FileOutputStream fos = new FileOutputStream( changelogFile );
fos.write( buffer.toString().getBytes() );
fos.close();
hudsonOut.println( " DONE" );
result = true;
}
catch ( Exception e )
{
hudsonOut.println( "FAILED" );
logger.log( "Changelog failed with " + e.getMessage() );
result = false;
}
return result;
}
@Override
public ChangeLogParser createChangeLogParser()
{
logger.trace_function();
return new ChangeLogParserImpl();
}
@Override
public PollingResult compareRemoteRevisionWith( AbstractProject<?, ?> project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState baseline ) throws IOException, InterruptedException
{
logger.trace_function();
SCMRevisionStateImpl scmState = (SCMRevisionStateImpl) baseline;
PollingResult p;
if ( baselinesToBuild( scmState.getJobname() ) )
{
compRevCalled = true;
p = PollingResult.BUILD_NOW;
}
else
{
p = PollingResult.NO_CHANGES;
}
return p;
}
@Override
public SCMRevisionState calcRevisionsFromBuild( AbstractBuild<?, ?> build, Launcher launcher, TaskListener listener ) throws IOException, InterruptedException
{
logger.trace_function();
PrintStream hudsonOut = listener.getLogger();
SCMRevisionStateImpl scmRS = null;
if ( !( bl == null ) )
{
scmRS = new SCMRevisionStateImpl( build.getParent().getDisplayName(), String.valueOf( build.getNumber() ) );
}
return scmRS;
}
private boolean baselinesToBuild( String jobname )
{
logger.trace_function();
boolean result = true;
co = null;
integrationstream = null;
Stream devstream = null;
try
{
co = UCMEntity.GetComponent( "component:" + component, false );
integrationstream = UCMEntity.GetStream( "stream:" + stream, false );
pollMsgs.append("Integrationstream exists: "+integrationstream.toString());
//TODO: Afklaring med lak mht om vi overhovedet skal create stream, hvis ja, med hvilke parametre?
/*if(Stream.StreamExists( stream ))
{
} else
{
//Version2: kunne angive Hudson-projekt. Skal hardcodes i config.java CHRISTIAN - FIKS!!!! :-)
//TODO fiks: st = Stream.Create( pstream, nstream, readonly, null )CHW kommr med ny metode - m�ske
//nstream = gui-angivet stream, pstream fra config.java, readonly=true
}*/
}
catch ( UCMEntityException ucmEe )
{
pollMsgs.append( ucmEe.toString() + "\n" );
result = false;
}
if ( result )
{
try
{
pollMsgs.append( "Getting " );
pollMsgs.append( ( newerThanRecommended ? "baselines newer than the recomended baseline " : "all baselines " ) );
pollMsgs.append( "for stream " );
pollMsgs.append( stream );
pollMsgs.append( " and component " );
pollMsgs.append( component );
pollMsgs.append( " on promotionlevel " );
pollMsgs.append( levelToPoll );
pollMsgs.append( "\n" );
if ( newerThanRecommended )
{
baselines = co.GetBaselines( integrationstream, Project.Plevel.valueOf( levelToPoll ) ).NewerThanRecommended();
}
else
{
baselines = co.GetBaselines( integrationstream, Project.Plevel.valueOf( levelToPoll ) );
}
}
catch ( Exception e )
{
pollMsgs.append( "Could not retrieve baselines from repository\n" );
result = false;
}
}
if ( result )
{
if ( baselines.size() > 0 )
{
pollMsgs.append( "Retrieved baselines:\n" );
for ( Baseline b : baselines )
{
pollMsgs.append( b.GetShortname() );
pollMsgs.append( "\n" );
}
if ( newest )
{
- bl = baselines.get( 0 );
+ bl = baselines.get( baselines.size() - 1 );
pollMsgs.append( "Building newest baseline: " );
pollMsgs.append( bl );
pollMsgs.append( "\n" );
}
else
{
- bl = baselines.get( baselines.size() - 1 );
+ bl = baselines.get( 0 );
pollMsgs.append( "Building next baseline: " );
pollMsgs.append( bl );
pollMsgs.append( "\n" );
}
}
else
{
pollMsgs.append( "No baselines on chosen parameters.\n" );
result = false;
}
}
return result;
}
/*
* The following getters and booleans (six in all) are used to display saved
* userdata in Hudsons gui
*/
public String getLevelToPoll()
{
logger.trace_function();
return levelToPoll;
}
public String getComponent()
{
logger.trace_function();
return component;
}
public String getStream()
{
logger.trace_function();
return stream;
}
public String getLoadModule()
{
logger.trace_function();
return loadModule;
}
public boolean isNewest()
{
logger.trace_function();
return newest;
}
public boolean isNewerThanRecommended()
{
logger.trace_function();
return newerThanRecommended;
}
/*
* getStreamObject() and getBaseline() are used by PucmNotifier to get the
* Baseline and Stream in use
*/
public Stream getStreamObject()
{
logger.trace_function();
return integrationstream;
}
public Baseline getBaseline()
{
logger.trace_function();
return bl;
}
/**
* This class is used to describe the plugin to Hudson
*
* @author Troels Selch S�rensen
* @author Margit Bennetzen
*
*/
@Extension
public static class PucmScmDescriptor extends SCMDescriptor<PucmScm>
{
private String cleartool;
private List<String> levels;
private List<String> loadModules;
public PucmScmDescriptor()
{
super( PucmScm.class, null );
logger.trace_function();
levels = getLevels();
loadModules = getLoadModules();
load();
Config.setContext();
}
/**
* This method is called, when the user saves the global Hudson
* configuration.
*/
@Override
public boolean configure( org.kohsuke.stapler.StaplerRequest req, JSONObject json ) throws FormException
{
logger.trace_function();
cleartool = req.getParameter( "PUCM.cleartool" ).trim();
save();
return true;
}
/**
* This is called by Hudson to discover the plugin name
*/
@Override
public String getDisplayName()
{
logger.trace_function();
return "Praqmatic UCM";
}
/**
* This method is called by the scm/Pucm/global.jelly to validate the
* input without reloading the global configuration page
*
* @param value
* @return
*/
public FormValidation doExecutableCheck( @QueryParameter String value )
{
logger.trace_function();
return FormValidation.validateExecutable( value );
}
/**
* Called by Hudson. If the user does not input a command for Hudson to
* use when polling, default value is returned
*
* @return
*/
public String getCleartool()
{
logger.trace_function();
if ( cleartool == null || cleartool.equals( "" ) )
{
return "cleartool";
}
return cleartool;
}
/**
* Used by Hudson to display a list of valid promotion levels to build
* from. The list of promotion levels is hard coded in
* net.praqma.hudson.Config.java
*
* @return
*/
public List<String> getLevels()
{
logger.trace_function();
return Config.getLevels();
}
/**
* Used by Hudson to display a list of loadModules (whether to poll all
* or only modifiable elements
*
* @return
*/
public List<String> getLoadModules()
{
logger.trace_function();
loadModules = new ArrayList<String>();
loadModules.add( "All" );
loadModules.add( "Modifiable" );
return loadModules;
}
}
}
| false | true |
private boolean baselinesToBuild( String jobname )
{
logger.trace_function();
boolean result = true;
co = null;
integrationstream = null;
Stream devstream = null;
try
{
co = UCMEntity.GetComponent( "component:" + component, false );
integrationstream = UCMEntity.GetStream( "stream:" + stream, false );
pollMsgs.append("Integrationstream exists: "+integrationstream.toString());
//TODO: Afklaring med lak mht om vi overhovedet skal create stream, hvis ja, med hvilke parametre?
/*if(Stream.StreamExists( stream ))
{
} else
{
//Version2: kunne angive Hudson-projekt. Skal hardcodes i config.java CHRISTIAN - FIKS!!!! :-)
//TODO fiks: st = Stream.Create( pstream, nstream, readonly, null )CHW kommr med ny metode - m�ske
//nstream = gui-angivet stream, pstream fra config.java, readonly=true
}*/
}
catch ( UCMEntityException ucmEe )
{
pollMsgs.append( ucmEe.toString() + "\n" );
result = false;
}
if ( result )
{
try
{
pollMsgs.append( "Getting " );
pollMsgs.append( ( newerThanRecommended ? "baselines newer than the recomended baseline " : "all baselines " ) );
pollMsgs.append( "for stream " );
pollMsgs.append( stream );
pollMsgs.append( " and component " );
pollMsgs.append( component );
pollMsgs.append( " on promotionlevel " );
pollMsgs.append( levelToPoll );
pollMsgs.append( "\n" );
if ( newerThanRecommended )
{
baselines = co.GetBaselines( integrationstream, Project.Plevel.valueOf( levelToPoll ) ).NewerThanRecommended();
}
else
{
baselines = co.GetBaselines( integrationstream, Project.Plevel.valueOf( levelToPoll ) );
}
}
catch ( Exception e )
{
pollMsgs.append( "Could not retrieve baselines from repository\n" );
result = false;
}
}
if ( result )
{
if ( baselines.size() > 0 )
{
pollMsgs.append( "Retrieved baselines:\n" );
for ( Baseline b : baselines )
{
pollMsgs.append( b.GetShortname() );
pollMsgs.append( "\n" );
}
if ( newest )
{
bl = baselines.get( 0 );
pollMsgs.append( "Building newest baseline: " );
pollMsgs.append( bl );
pollMsgs.append( "\n" );
}
else
{
bl = baselines.get( baselines.size() - 1 );
pollMsgs.append( "Building next baseline: " );
pollMsgs.append( bl );
pollMsgs.append( "\n" );
}
}
else
{
pollMsgs.append( "No baselines on chosen parameters.\n" );
result = false;
}
}
return result;
}
|
private boolean baselinesToBuild( String jobname )
{
logger.trace_function();
boolean result = true;
co = null;
integrationstream = null;
Stream devstream = null;
try
{
co = UCMEntity.GetComponent( "component:" + component, false );
integrationstream = UCMEntity.GetStream( "stream:" + stream, false );
pollMsgs.append("Integrationstream exists: "+integrationstream.toString());
//TODO: Afklaring med lak mht om vi overhovedet skal create stream, hvis ja, med hvilke parametre?
/*if(Stream.StreamExists( stream ))
{
} else
{
//Version2: kunne angive Hudson-projekt. Skal hardcodes i config.java CHRISTIAN - FIKS!!!! :-)
//TODO fiks: st = Stream.Create( pstream, nstream, readonly, null )CHW kommr med ny metode - m�ske
//nstream = gui-angivet stream, pstream fra config.java, readonly=true
}*/
}
catch ( UCMEntityException ucmEe )
{
pollMsgs.append( ucmEe.toString() + "\n" );
result = false;
}
if ( result )
{
try
{
pollMsgs.append( "Getting " );
pollMsgs.append( ( newerThanRecommended ? "baselines newer than the recomended baseline " : "all baselines " ) );
pollMsgs.append( "for stream " );
pollMsgs.append( stream );
pollMsgs.append( " and component " );
pollMsgs.append( component );
pollMsgs.append( " on promotionlevel " );
pollMsgs.append( levelToPoll );
pollMsgs.append( "\n" );
if ( newerThanRecommended )
{
baselines = co.GetBaselines( integrationstream, Project.Plevel.valueOf( levelToPoll ) ).NewerThanRecommended();
}
else
{
baselines = co.GetBaselines( integrationstream, Project.Plevel.valueOf( levelToPoll ) );
}
}
catch ( Exception e )
{
pollMsgs.append( "Could not retrieve baselines from repository\n" );
result = false;
}
}
if ( result )
{
if ( baselines.size() > 0 )
{
pollMsgs.append( "Retrieved baselines:\n" );
for ( Baseline b : baselines )
{
pollMsgs.append( b.GetShortname() );
pollMsgs.append( "\n" );
}
if ( newest )
{
bl = baselines.get( baselines.size() - 1 );
pollMsgs.append( "Building newest baseline: " );
pollMsgs.append( bl );
pollMsgs.append( "\n" );
}
else
{
bl = baselines.get( 0 );
pollMsgs.append( "Building next baseline: " );
pollMsgs.append( bl );
pollMsgs.append( "\n" );
}
}
else
{
pollMsgs.append( "No baselines on chosen parameters.\n" );
result = false;
}
}
return result;
}
|
diff --git a/annis-gui/src/main/java/annis/gui/AboutWindow.java b/annis-gui/src/main/java/annis/gui/AboutWindow.java
index 1dfc3ee1a..0378f07ae 100644
--- a/annis-gui/src/main/java/annis/gui/AboutWindow.java
+++ b/annis-gui/src/main/java/annis/gui/AboutWindow.java
@@ -1,148 +1,148 @@
/*
* Copyright 2011 Corpuslinguistic working group Humboldt University Berlin.
*
* 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 annis.gui;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.ExternalResource;
import com.vaadin.server.ThemeResource;
import com.vaadin.server.VaadinService;
import com.vaadin.server.VaadinSession;
import com.vaadin.shared.Version;
import com.vaadin.ui.*;
import com.vaadin.ui.Button.ClickEvent;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author thomas
*/
public class AboutWindow extends Window
{
private static final Logger log = LoggerFactory.getLogger(AboutWindow.class);
private VerticalLayout layout;
public AboutWindow()
{
setSizeFull();
layout = new VerticalLayout();
setContent(layout);
layout.setSizeFull();
HorizontalLayout hLayout = new HorizontalLayout();
Embedded logoAnnis = new Embedded();
logoAnnis.setSource(new ThemeResource("annis-logo-128.png"));
logoAnnis.setType(Embedded.TYPE_IMAGE);
hLayout.addComponent(logoAnnis);
Embedded logoSfb = new Embedded();
logoSfb.setSource(new ThemeResource("sfb-logo.jpg"));
logoSfb.setType(Embedded.TYPE_IMAGE);
hLayout.addComponent(logoSfb);
Link lnkFork = new Link();
lnkFork.setResource(new ExternalResource("https://github.com/korpling/ANNIS"));
lnkFork.setIcon(new ExternalResource("https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"));
lnkFork.setTargetName("_blank");
hLayout.addComponent(lnkFork);
hLayout.setComponentAlignment(logoAnnis, Alignment.MIDDLE_LEFT);
hLayout.setComponentAlignment(logoSfb, Alignment.MIDDLE_RIGHT);
hLayout.setComponentAlignment(lnkFork, Alignment.TOP_RIGHT);
layout.addComponent(hLayout);
layout.addComponent(new Label("ANNIS is a project of the "
+ "<a href=\"http://www.sfb632.uni-potsdam.de/\">SFB632</a>.", Label.CONTENT_XHTML));
layout.addComponent(new Label("Homepage: "
- + "<a href=\"http://www.sfb632.uni-potsdam.de/d1/annis/\">"
- + "http://www.sfb632.uni-potsdam.de/d1/annis/</a>.", Label.CONTENT_XHTML));
+ + "<a href=\"http://www.sfb632.uni-potsdam.de/annis/\">"
+ + "http://www.sfb632.uni-potsdam.de/annis/</a>.", Label.CONTENT_XHTML));
layout.addComponent(new Label("Version: " + VaadinSession.getCurrent().getAttribute("annis-version")));
layout.addComponent(new Label("Vaadin-Version: " + Version.getFullVersion()));
TextArea txtThirdParty = new TextArea();
txtThirdParty.setSizeFull();
StringBuilder sb = new StringBuilder();
sb.append("The ANNIS team wants to thank these third party software that "
+ "made the ANNIS GUI possible:\n");
File thirdPartyFolder =
new File(VaadinService.getCurrent().getBaseDirectory(), "THIRD-PARTY");
if(thirdPartyFolder.isDirectory())
{
for(File c : thirdPartyFolder.listFiles((FileFilter) new WildcardFileFilter("*.txt")))
{
if(c.isFile())
{
try
{
sb.append(FileUtils.readFileToString(c)).append("\n");
}
catch (IOException ex)
{
log.error("Could not read file", ex);
}
}
}
}
txtThirdParty.setValue(sb.toString());
txtThirdParty.setReadOnly(true);
txtThirdParty.addStyleName("license");
txtThirdParty.setWordwrap(false);
layout.addComponent(txtThirdParty);
Button btOK = new Button("OK");
final AboutWindow finalThis = this;
btOK.addClickListener(new OkClickListener(finalThis));
layout.addComponent(btOK);
layout.setComponentAlignment(hLayout, Alignment.MIDDLE_CENTER);
layout.setComponentAlignment(btOK, Alignment.MIDDLE_CENTER);
layout.setExpandRatio(txtThirdParty, 1.0f);
}
private static class OkClickListener implements Button.ClickListener
{
private final AboutWindow finalThis;
public OkClickListener(AboutWindow finalThis)
{
this.finalThis = finalThis;
}
@Override
public void buttonClick(ClickEvent event)
{
UI.getCurrent().removeWindow(finalThis);
}
}
}
| true | true |
public AboutWindow()
{
setSizeFull();
layout = new VerticalLayout();
setContent(layout);
layout.setSizeFull();
HorizontalLayout hLayout = new HorizontalLayout();
Embedded logoAnnis = new Embedded();
logoAnnis.setSource(new ThemeResource("annis-logo-128.png"));
logoAnnis.setType(Embedded.TYPE_IMAGE);
hLayout.addComponent(logoAnnis);
Embedded logoSfb = new Embedded();
logoSfb.setSource(new ThemeResource("sfb-logo.jpg"));
logoSfb.setType(Embedded.TYPE_IMAGE);
hLayout.addComponent(logoSfb);
Link lnkFork = new Link();
lnkFork.setResource(new ExternalResource("https://github.com/korpling/ANNIS"));
lnkFork.setIcon(new ExternalResource("https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"));
lnkFork.setTargetName("_blank");
hLayout.addComponent(lnkFork);
hLayout.setComponentAlignment(logoAnnis, Alignment.MIDDLE_LEFT);
hLayout.setComponentAlignment(logoSfb, Alignment.MIDDLE_RIGHT);
hLayout.setComponentAlignment(lnkFork, Alignment.TOP_RIGHT);
layout.addComponent(hLayout);
layout.addComponent(new Label("ANNIS is a project of the "
+ "<a href=\"http://www.sfb632.uni-potsdam.de/\">SFB632</a>.", Label.CONTENT_XHTML));
layout.addComponent(new Label("Homepage: "
+ "<a href=\"http://www.sfb632.uni-potsdam.de/d1/annis/\">"
+ "http://www.sfb632.uni-potsdam.de/d1/annis/</a>.", Label.CONTENT_XHTML));
layout.addComponent(new Label("Version: " + VaadinSession.getCurrent().getAttribute("annis-version")));
layout.addComponent(new Label("Vaadin-Version: " + Version.getFullVersion()));
TextArea txtThirdParty = new TextArea();
txtThirdParty.setSizeFull();
StringBuilder sb = new StringBuilder();
sb.append("The ANNIS team wants to thank these third party software that "
+ "made the ANNIS GUI possible:\n");
File thirdPartyFolder =
new File(VaadinService.getCurrent().getBaseDirectory(), "THIRD-PARTY");
if(thirdPartyFolder.isDirectory())
{
for(File c : thirdPartyFolder.listFiles((FileFilter) new WildcardFileFilter("*.txt")))
{
if(c.isFile())
{
try
{
sb.append(FileUtils.readFileToString(c)).append("\n");
}
catch (IOException ex)
{
log.error("Could not read file", ex);
}
}
}
}
txtThirdParty.setValue(sb.toString());
txtThirdParty.setReadOnly(true);
txtThirdParty.addStyleName("license");
txtThirdParty.setWordwrap(false);
layout.addComponent(txtThirdParty);
Button btOK = new Button("OK");
final AboutWindow finalThis = this;
btOK.addClickListener(new OkClickListener(finalThis));
layout.addComponent(btOK);
layout.setComponentAlignment(hLayout, Alignment.MIDDLE_CENTER);
layout.setComponentAlignment(btOK, Alignment.MIDDLE_CENTER);
layout.setExpandRatio(txtThirdParty, 1.0f);
}
|
public AboutWindow()
{
setSizeFull();
layout = new VerticalLayout();
setContent(layout);
layout.setSizeFull();
HorizontalLayout hLayout = new HorizontalLayout();
Embedded logoAnnis = new Embedded();
logoAnnis.setSource(new ThemeResource("annis-logo-128.png"));
logoAnnis.setType(Embedded.TYPE_IMAGE);
hLayout.addComponent(logoAnnis);
Embedded logoSfb = new Embedded();
logoSfb.setSource(new ThemeResource("sfb-logo.jpg"));
logoSfb.setType(Embedded.TYPE_IMAGE);
hLayout.addComponent(logoSfb);
Link lnkFork = new Link();
lnkFork.setResource(new ExternalResource("https://github.com/korpling/ANNIS"));
lnkFork.setIcon(new ExternalResource("https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"));
lnkFork.setTargetName("_blank");
hLayout.addComponent(lnkFork);
hLayout.setComponentAlignment(logoAnnis, Alignment.MIDDLE_LEFT);
hLayout.setComponentAlignment(logoSfb, Alignment.MIDDLE_RIGHT);
hLayout.setComponentAlignment(lnkFork, Alignment.TOP_RIGHT);
layout.addComponent(hLayout);
layout.addComponent(new Label("ANNIS is a project of the "
+ "<a href=\"http://www.sfb632.uni-potsdam.de/\">SFB632</a>.", Label.CONTENT_XHTML));
layout.addComponent(new Label("Homepage: "
+ "<a href=\"http://www.sfb632.uni-potsdam.de/annis/\">"
+ "http://www.sfb632.uni-potsdam.de/annis/</a>.", Label.CONTENT_XHTML));
layout.addComponent(new Label("Version: " + VaadinSession.getCurrent().getAttribute("annis-version")));
layout.addComponent(new Label("Vaadin-Version: " + Version.getFullVersion()));
TextArea txtThirdParty = new TextArea();
txtThirdParty.setSizeFull();
StringBuilder sb = new StringBuilder();
sb.append("The ANNIS team wants to thank these third party software that "
+ "made the ANNIS GUI possible:\n");
File thirdPartyFolder =
new File(VaadinService.getCurrent().getBaseDirectory(), "THIRD-PARTY");
if(thirdPartyFolder.isDirectory())
{
for(File c : thirdPartyFolder.listFiles((FileFilter) new WildcardFileFilter("*.txt")))
{
if(c.isFile())
{
try
{
sb.append(FileUtils.readFileToString(c)).append("\n");
}
catch (IOException ex)
{
log.error("Could not read file", ex);
}
}
}
}
txtThirdParty.setValue(sb.toString());
txtThirdParty.setReadOnly(true);
txtThirdParty.addStyleName("license");
txtThirdParty.setWordwrap(false);
layout.addComponent(txtThirdParty);
Button btOK = new Button("OK");
final AboutWindow finalThis = this;
btOK.addClickListener(new OkClickListener(finalThis));
layout.addComponent(btOK);
layout.setComponentAlignment(hLayout, Alignment.MIDDLE_CENTER);
layout.setComponentAlignment(btOK, Alignment.MIDDLE_CENTER);
layout.setExpandRatio(txtThirdParty, 1.0f);
}
|
diff --git a/viewer/src/org/icepdf/ri/common/search/DocumentSearchControllerImpl.java b/viewer/src/org/icepdf/ri/common/search/DocumentSearchControllerImpl.java
index 4079ebd0..6e8a9fbf 100644
--- a/viewer/src/org/icepdf/ri/common/search/DocumentSearchControllerImpl.java
+++ b/viewer/src/org/icepdf/ri/common/search/DocumentSearchControllerImpl.java
@@ -1,490 +1,490 @@
package org.icepdf.ri.common.search;
import org.icepdf.core.pobjects.graphics.text.LineText;
import org.icepdf.core.pobjects.graphics.text.PageText;
import org.icepdf.core.pobjects.graphics.text.WordText;
import org.icepdf.core.search.DocumentSearchController;
import org.icepdf.core.search.SearchTerm;
import org.icepdf.ri.common.SwingController;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;
import java.util.logging.Level;
/**
* Document search controller used to manage document searches. This class
* class takes care of many of the performance issues of doing searches on
* larges documents and is also used by PageViewComponentImpl to highlight
* search results.
* <p/>
* This implementation uses simple search algorithm that will work well for most
* users. This class can be exteded and the method {@link #searchHighlightPage(int)}
* can be overridden for custom search implmentations.
*
* @since 4.0
*/
public class DocumentSearchControllerImpl implements DocumentSearchController {
private static final Logger logger =
Logger.getLogger(DocumentSearchControllerImpl.class.toString());
// search model contains caching and memory optimizations.
protected DocumentSearchModelImpl searchModel;
// parent controller used to get at RI controllers and models.
protected SwingController viewerController;
/**
* Create a news instnace of search controller. A search model is created
* for this instanc.e
*
* @param viewerController parent controller/mediator.
*/
public DocumentSearchControllerImpl(SwingController viewerController) {
this.viewerController = viewerController;
searchModel = new DocumentSearchModelImpl();
}
/**
* Searches the given page using the specified term and properties. The
* search model is updated to store the pages Page text as a weak reference
* which can be queried using isSearchHighlightNeeded to effiecently make
* sure that a pages text is highlighted even after a despose/init cycle.
* If the text state is no longer preseent then the search should be executed
* again.
* <p/>
* This method cleasr the serach results for the page before it searches. If
* you wich to have cumligive search results then searches terms should
* be added with {@link #addSearchTerm(String, boolean, boolean)} and the
* method {@link #searchPage(int)} should be called after each term is
* added or after all have been added.
*
* @param pageIndex page to search
* @param caseSensitive if true use case sensitive searches
* @param wholeWord if true use whole word searches
* @param term term to search for
* @return number for hits for this page.
*/
public int searchHighlightPage(int pageIndex, String term,
boolean caseSensitive, boolean wholeWord) {
// clear previous search
clearSearchHighlight(pageIndex);
// add the search term
addSearchTerm(term, caseSensitive, wholeWord);
// start the search and return the hit count.
return searchHighlightPage(pageIndex);
}
/**
* Searches the page index given the search terms that have been added
* with {@link #addSearchTerm(String, boolean, boolean)}. If search
* hits where detected then the Page's PageText is added to the cache.
* <p/>
* This method represent the core search algorithm for this
* DocumentSearchController implmentation. This method can be overriden
* if a different search algorithm or functinality is needed.
*
* @param pageIndex page index to search
* @return number of hits found for this page.
*/
public int searchHighlightPage(int pageIndex) {
// get search terms from model and search for each occurrence.
Collection<SearchTerm> terms = searchModel.getSearchTerms();
// search hit count
int hitCount = 0;
// get our our page text reference
PageText pageText = viewerController.getDocument()
.getPageText(pageIndex);
// some pages just don't have any text.
if (pageText == null){
return 0;
}
// we need to do the search for each term.
for (SearchTerm term : terms) {
// found word index to keep track of when we have found a hit
int searchPhraseHitCount = 0;
int searchPhraseFoundCount = term.getTerms().size();
// list of found words for highlighting, as hits can span
// lines and pages
ArrayList<WordText> searchPhraseHits =
new ArrayList<WordText>(searchPhraseFoundCount);
// start iteration over words.
ArrayList<LineText> pageLines = pageText.getPageLines();
for (LineText pageLine : pageLines) {
ArrayList<WordText> lineWords = pageLine.getWords();
// compare words against search terms.
String wordString;
for (WordText word : lineWords) {
// apply case sensitivity rule.
wordString = term.isCaseSensitive() ? word.toString() :
word.toString().toLowerCase();
// word matches, we have to match full word hits
if (term.isWholeWord()) {
if (wordString.equals(
term.getTerms().get(searchPhraseHitCount))) {
// add word to potentials
searchPhraseHits.add(word);
searchPhraseHitCount++;
}
// else if (wordString.length() == 1 &&
// WordText.isPunctuation(wordString.charAt(0))){
// // ignore punctuation
// searchPhraseHitCount++;
// }
// reset the counters.
else {
searchPhraseHits.clear();
searchPhraseHitCount = 0;
}
}
// otherwise we look for an index of hits
else {
// found a potential hit, depends on the length
// of searchPhrase.
if (wordString.indexOf(
term.getTerms().get(searchPhraseHitCount)) >= 0) {
// add word to potentials
searchPhraseHits.add(word);
searchPhraseHitCount++;
}
// else if (wordString.length() == 1 &&
// WordText.isPunctuation(wordString.charAt(0))){
// // ignore punctuation
// searchPhraseHitCount++;
// }
// reset the counters.
else {
searchPhraseHits.clear();
searchPhraseHitCount = 0;
}
}
// check if we have found what we're looking for
if (searchPhraseHitCount == searchPhraseFoundCount) {
// iterate of found, highlighting words
for (WordText wordHit : searchPhraseHits) {
wordHit.setHighlighted(true);
wordHit.setHasHighlight(true);
}
// rest counts and start over again.
hitCount++;
searchPhraseHits.clear();
searchPhraseHitCount = 0;
}
}
}
}
// if we have a hit we'll add it to the model cache
if (hitCount > 0) {
searchModel.addPageSearchHit(pageIndex, pageText);
if (logger.isLoggable(Level.FINE)){
logger.fine("Found search hits on page " + pageIndex +
" hit count " + hitCount);
}
}
return hitCount;
}
/**
* Searches the page index given the search terms that have been added
* with {@link #addSearchTerm(String, boolean, boolean)}. If search
* hits where detected then the Page's PageText is added to the cache.
* <p/>
* This class differences from {@link #searchHighlightPage(int)} in that
* is returns a list of lineText fragements for each hit but the LinText
* is padded by pre and post words that surround the hit in the page
* context.
* <p/>
* This method represent the core search algorithm for this
* DocumentSearchController implmentation. This method can be overriden
* if a different search algorithm or functinality is needed.
*
* @param pageIndex page index to search
* @param wordPadding word padding on either side of hit to give context
* to found woords in the returned LineText
* @return list of contectual hits for the give page. If no hits an empty
* list is returned.
*/
public ArrayList<LineText> searchHighlightPage(int pageIndex, int wordPadding){
// get search terms from model and search for each occurrence.
Collection<SearchTerm> terms = searchModel.getSearchTerms();
// search hit list
ArrayList<LineText>searchHits = new ArrayList<LineText>();
// get our our page text reference
PageText pageText = viewerController.getDocument()
.getPageText(pageIndex);
// some pages just don't have any text.
if (pageText == null){
return searchHits;
}
// we need to do the search for each term.
for (SearchTerm term : terms) {
// found word index to keep track of when we have found a hit
int searchPhraseHitCount = 0;
int searchPhraseFoundCount = term.getTerms().size();
// list of found words for highlighting, as hits can span
// lines and pages
ArrayList<WordText> searchPhraseHits =
new ArrayList<WordText>(searchPhraseFoundCount);
// start iteration over words.
ArrayList<LineText> pageLines = pageText.getPageLines();
for (LineText pageLine : pageLines) {
ArrayList<WordText> lineWords = pageLine.getWords();
// compare words against search terms.
String wordString;
WordText word;
for (int i= 0, max = lineWords.size(); i < max; i++) {
word = lineWords.get(i);
// apply case sensitivity rule.
wordString = term.isCaseSensitive() ? word.toString() :
word.toString().toLowerCase();
// word matches, we have to match full word hits
if (term.isWholeWord()) {
if (wordString.equals(
term.getTerms().get(searchPhraseHitCount))) {
// add word to potentials
searchPhraseHits.add(word);
searchPhraseHitCount++;
}
// reset the counters.
else {
searchPhraseHits.clear();
searchPhraseHitCount = 0;
}
}
// otherwise we look for an index of hits
else {
// found a potential hit, depends on the length
// of searchPhrase.
if (wordString.indexOf(
term.getTerms().get(searchPhraseHitCount)) >= 0) {
// add word to potentials
searchPhraseHits.add(word);
searchPhraseHitCount++;
}
// reset the counters.
else {
searchPhraseHits.clear();
searchPhraseHitCount = 0;
}
}
// check if we have found what we're looking for
if (searchPhraseHitCount == searchPhraseFoundCount) {
LineText lineText = new LineText();
int lineWordsSize = lineWords.size();
ArrayList<WordText> hitWords = lineText.getWords();
// add pre padding
int start = i - searchPhraseHitCount - wordPadding + 1;
start = start < 0? 0:start;
- int end = i ;
+ int end = i - searchPhraseHitCount + 1;
end = end < 0? 0:end;
for (int p = start; p < end; p++){
hitWords.add(lineWords.get(p));
}
// iterate of found, highlighting words
for (WordText wordHit : searchPhraseHits) {
wordHit.setHighlighted(true);
wordHit.setHasHighlight(true);
}
hitWords.addAll(searchPhraseHits);
// add word padding to front of line
start = i + 1;
start = start > lineWordsSize?lineWordsSize:start;
end = start + wordPadding;
end = end > lineWordsSize?lineWordsSize:end;
for (int p = start; p < end; p++){
hitWords.add(lineWords.get(p));
}
// add the hits to our list.
searchHits.add(lineText);
searchPhraseHits.clear();
searchPhraseHitCount = 0;
}
}
}
}
// if we have a hit we'll add it to the model cache
if (searchHits.size() > 0) {
searchModel.addPageSearchHit(pageIndex, pageText);
if (logger.isLoggable(Level.FINE)){
logger.fine("Found search hits on page " + pageIndex +
" hit count " + searchHits.size());
}
}
return searchHits;
}
/**
* Search page but only return words that are hits. Highlighting is till
* applied but this method can be used if other data needs to be extracted
* from the found words.
*
* @param pageIndex page to search
* @return list of words that match the term and search properites.
*/
public ArrayList<WordText> searchPage(int pageIndex) {
int hits = searchHighlightPage(pageIndex);
if (hits > 0) {
PageText searchText = searchModel.getPageTextHit(pageIndex);
if (searchText != null) {
ArrayList<WordText> words = new ArrayList<WordText>(hits);
ArrayList<LineText> pageLines = searchText.getPageLines();
for (LineText pageLine : pageLines) {
ArrayList<WordText> lineWords = pageLine.getWords();
for (WordText word : lineWords) {
if (word.isHighlighted()) {
words.add(word);
}
}
}
return words;
}
}
return null;
}
/**
* Add the search term to the list of search terms. The term is split
* into words based on white space and punctuation. No checks are done
* for duplication.
* <p/>
* A new search needs to be executed for this change to take place.
*
* @param term single word or phrace to search for.
* @param caseSensitive is search case sensitive.
* @param wholeWord is search whole word senstive.
* @return searchTerm newly create search term.
*/
public SearchTerm addSearchTerm(String term, boolean caseSensitive,
boolean wholeWord) {
// keep origional copy
String origionalTerm = new String(term);
// check criteria for case sensitivity.
if (!caseSensitive) {
term = term.toLowerCase();
}
// parse search term out into words, so we can match
// them against WordText
ArrayList<String> searchPhrase = searchPhraseParser(term);
// finally add the search term to the list and return it for management
SearchTerm searchTerm =
new SearchTerm(origionalTerm, searchPhrase, caseSensitive, wholeWord);
searchModel.addSearchTerm(searchTerm);
return searchTerm;
}
/**
* Removes the specified search term from the search. A new search needs
* to be executed for this change to take place.
*
* @param searchTerm search term to remove.
*/
public void removeSearchTerm(SearchTerm searchTerm) {
searchModel.removeSearchTerm(searchTerm);
}
/**
* Clear all searched items for specified page.
*
* @param pageIndex page indext to clear
*/
public void clearSearchHighlight(int pageIndex) {
// clear cache and terms list
searchModel.clearSearchResults(pageIndex);
}
/**
* Clears all highlighted text states for this this document. This optimized
* to use the the SearchHighlightModel to only clear pages that still have
* selected states.
*/
public void clearAllSearchHighlight() {
searchModel.clearSearchResults();
}
/**
* Test to see if a search highlight is needed. This is done by first
* check if there is a hit for this page and if the PageText object is the
* same as the one specified as a param. If they are not the same PageText
* object then we need to do refresh as the page was disposed and
* reinitialized with new content.
*
* @param pageIndex page index to text for restuls.
* @param pageText current pageText object associated with the pageIndex.
* @return true if refresh is needed, false otherwise.
*/
public boolean isSearchHighlightRefreshNeeded(int pageIndex, PageText pageText) {
// check model to see if pages pagTex still has reference
return searchModel.isPageTextMatch(pageIndex, pageText);
}
/**
* Disposes controller clearing resources.
*/
public void dispose() {
searchModel.clearSearchResults();
}
/**
* Utility for breaking the pattern up into searchable words. Breaks are
* done on white spaces and punctuation.
*
* @param phrase pattern to search words for.
* @return list of words that make up phrase, words, spaces, punctuation.
*/
protected ArrayList<String> searchPhraseParser(String phrase) {
// trim white space, not really useful.
phrase = phrase.trim();
// found words.
ArrayList<String> words = new ArrayList<String>();
char c;
for (int start = 0, curs = 0, max = phrase.length(); curs < max; curs++) {
c = phrase.charAt(curs);
if (WordText.isWhiteSpace(c) ||
WordText.isPunctuation(c)) {
// add word segment
if (start != curs) {
words.add(phrase.substring(start, curs));
}
// add white space as word too.
words.add(phrase.substring(curs, curs + 1));
// start
start = curs + 1 < max ? curs + 1 : start;
} else if (curs + 1 == max) {
words.add(phrase.substring(start, curs + 1));
}
}
return words;
}
}
| true | true |
public ArrayList<LineText> searchHighlightPage(int pageIndex, int wordPadding){
// get search terms from model and search for each occurrence.
Collection<SearchTerm> terms = searchModel.getSearchTerms();
// search hit list
ArrayList<LineText>searchHits = new ArrayList<LineText>();
// get our our page text reference
PageText pageText = viewerController.getDocument()
.getPageText(pageIndex);
// some pages just don't have any text.
if (pageText == null){
return searchHits;
}
// we need to do the search for each term.
for (SearchTerm term : terms) {
// found word index to keep track of when we have found a hit
int searchPhraseHitCount = 0;
int searchPhraseFoundCount = term.getTerms().size();
// list of found words for highlighting, as hits can span
// lines and pages
ArrayList<WordText> searchPhraseHits =
new ArrayList<WordText>(searchPhraseFoundCount);
// start iteration over words.
ArrayList<LineText> pageLines = pageText.getPageLines();
for (LineText pageLine : pageLines) {
ArrayList<WordText> lineWords = pageLine.getWords();
// compare words against search terms.
String wordString;
WordText word;
for (int i= 0, max = lineWords.size(); i < max; i++) {
word = lineWords.get(i);
// apply case sensitivity rule.
wordString = term.isCaseSensitive() ? word.toString() :
word.toString().toLowerCase();
// word matches, we have to match full word hits
if (term.isWholeWord()) {
if (wordString.equals(
term.getTerms().get(searchPhraseHitCount))) {
// add word to potentials
searchPhraseHits.add(word);
searchPhraseHitCount++;
}
// reset the counters.
else {
searchPhraseHits.clear();
searchPhraseHitCount = 0;
}
}
// otherwise we look for an index of hits
else {
// found a potential hit, depends on the length
// of searchPhrase.
if (wordString.indexOf(
term.getTerms().get(searchPhraseHitCount)) >= 0) {
// add word to potentials
searchPhraseHits.add(word);
searchPhraseHitCount++;
}
// reset the counters.
else {
searchPhraseHits.clear();
searchPhraseHitCount = 0;
}
}
// check if we have found what we're looking for
if (searchPhraseHitCount == searchPhraseFoundCount) {
LineText lineText = new LineText();
int lineWordsSize = lineWords.size();
ArrayList<WordText> hitWords = lineText.getWords();
// add pre padding
int start = i - searchPhraseHitCount - wordPadding + 1;
start = start < 0? 0:start;
int end = i ;
end = end < 0? 0:end;
for (int p = start; p < end; p++){
hitWords.add(lineWords.get(p));
}
// iterate of found, highlighting words
for (WordText wordHit : searchPhraseHits) {
wordHit.setHighlighted(true);
wordHit.setHasHighlight(true);
}
hitWords.addAll(searchPhraseHits);
// add word padding to front of line
start = i + 1;
start = start > lineWordsSize?lineWordsSize:start;
end = start + wordPadding;
end = end > lineWordsSize?lineWordsSize:end;
for (int p = start; p < end; p++){
hitWords.add(lineWords.get(p));
}
// add the hits to our list.
searchHits.add(lineText);
searchPhraseHits.clear();
searchPhraseHitCount = 0;
}
}
}
}
// if we have a hit we'll add it to the model cache
if (searchHits.size() > 0) {
searchModel.addPageSearchHit(pageIndex, pageText);
if (logger.isLoggable(Level.FINE)){
logger.fine("Found search hits on page " + pageIndex +
" hit count " + searchHits.size());
}
}
return searchHits;
}
|
public ArrayList<LineText> searchHighlightPage(int pageIndex, int wordPadding){
// get search terms from model and search for each occurrence.
Collection<SearchTerm> terms = searchModel.getSearchTerms();
// search hit list
ArrayList<LineText>searchHits = new ArrayList<LineText>();
// get our our page text reference
PageText pageText = viewerController.getDocument()
.getPageText(pageIndex);
// some pages just don't have any text.
if (pageText == null){
return searchHits;
}
// we need to do the search for each term.
for (SearchTerm term : terms) {
// found word index to keep track of when we have found a hit
int searchPhraseHitCount = 0;
int searchPhraseFoundCount = term.getTerms().size();
// list of found words for highlighting, as hits can span
// lines and pages
ArrayList<WordText> searchPhraseHits =
new ArrayList<WordText>(searchPhraseFoundCount);
// start iteration over words.
ArrayList<LineText> pageLines = pageText.getPageLines();
for (LineText pageLine : pageLines) {
ArrayList<WordText> lineWords = pageLine.getWords();
// compare words against search terms.
String wordString;
WordText word;
for (int i= 0, max = lineWords.size(); i < max; i++) {
word = lineWords.get(i);
// apply case sensitivity rule.
wordString = term.isCaseSensitive() ? word.toString() :
word.toString().toLowerCase();
// word matches, we have to match full word hits
if (term.isWholeWord()) {
if (wordString.equals(
term.getTerms().get(searchPhraseHitCount))) {
// add word to potentials
searchPhraseHits.add(word);
searchPhraseHitCount++;
}
// reset the counters.
else {
searchPhraseHits.clear();
searchPhraseHitCount = 0;
}
}
// otherwise we look for an index of hits
else {
// found a potential hit, depends on the length
// of searchPhrase.
if (wordString.indexOf(
term.getTerms().get(searchPhraseHitCount)) >= 0) {
// add word to potentials
searchPhraseHits.add(word);
searchPhraseHitCount++;
}
// reset the counters.
else {
searchPhraseHits.clear();
searchPhraseHitCount = 0;
}
}
// check if we have found what we're looking for
if (searchPhraseHitCount == searchPhraseFoundCount) {
LineText lineText = new LineText();
int lineWordsSize = lineWords.size();
ArrayList<WordText> hitWords = lineText.getWords();
// add pre padding
int start = i - searchPhraseHitCount - wordPadding + 1;
start = start < 0? 0:start;
int end = i - searchPhraseHitCount + 1;
end = end < 0? 0:end;
for (int p = start; p < end; p++){
hitWords.add(lineWords.get(p));
}
// iterate of found, highlighting words
for (WordText wordHit : searchPhraseHits) {
wordHit.setHighlighted(true);
wordHit.setHasHighlight(true);
}
hitWords.addAll(searchPhraseHits);
// add word padding to front of line
start = i + 1;
start = start > lineWordsSize?lineWordsSize:start;
end = start + wordPadding;
end = end > lineWordsSize?lineWordsSize:end;
for (int p = start; p < end; p++){
hitWords.add(lineWords.get(p));
}
// add the hits to our list.
searchHits.add(lineText);
searchPhraseHits.clear();
searchPhraseHitCount = 0;
}
}
}
}
// if we have a hit we'll add it to the model cache
if (searchHits.size() > 0) {
searchModel.addPageSearchHit(pageIndex, pageText);
if (logger.isLoggable(Level.FINE)){
logger.fine("Found search hits on page " + pageIndex +
" hit count " + searchHits.size());
}
}
return searchHits;
}
|
diff --git a/elex_common/elex/worldgen/WorldGenSaltLakes.java b/elex_common/elex/worldgen/WorldGenSaltLakes.java
index 12c2474..c6fd211 100644
--- a/elex_common/elex/worldgen/WorldGenSaltLakes.java
+++ b/elex_common/elex/worldgen/WorldGenSaltLakes.java
@@ -1,205 +1,205 @@
package elex.worldgen;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.world.EnumSkyBlock;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.gen.feature.WorldGenLakes;
import elex.configuration.ConfigurationSettings;
import elex.lib.BlockIds;
import elex.lib.FluidIds;
/**
* Elemental Experimentation
*
* WorldGenSaltLakes
*
* @author Myo-kun
* @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html)
*/
public class WorldGenSaltLakes extends WorldGenLakes {
private int blockIndex;
public WorldGenSaltLakes() {
super(FluidIds.SALT_WATER_BLOCK);
this.blockIndex = FluidIds.SALT_WATER_BLOCK;
}
@Override
public boolean generate(World world, Random random, int x, int y, int z)
{
x -= 8;
for (z -= 8; y > 5 && world.isAirBlock(x, y, z); --y)
{
;
}
if (y <= 4)
{
return false;
}
else
{
y -= 4;
boolean[] aboolean = new boolean[2048];
int l = random.nextInt(4) + 4;
int i1;
for (i1 = 0; i1 < l; ++i1)
{
double d0 = random.nextDouble() * 6.0D + 3.0D;
double d1 = random.nextDouble() * 4.0D + 2.0D;
double d2 = random.nextDouble() * 6.0D + 3.0D;
double d3 = random.nextDouble() * (16.0D - d0 - 2.0D) + 1.0D + d0 / 2.0D;
double d4 = random.nextDouble() * (8.0D - d1 - 4.0D) + 2.0D + d1 / 2.0D;
double d5 = random.nextDouble() * (16.0D - d2 - 2.0D) + 1.0D + d2 / 2.0D;
for (int j1 = 1; j1 < 15; ++j1)
{
for (int k1 = 1; k1 < 15; ++k1)
{
for (int l1 = 1; l1 < 7; ++l1)
{
double d6 = ((double)j1 - d3) / (d0 / 2.0D);
double d7 = ((double)l1 - d4) / (d1 / 2.0D);
double d8 = ((double)k1 - d5) / (d2 / 2.0D);
double d9 = d6 * d6 + d7 * d7 + d8 * d8;
if (d9 < 1.0D)
{
aboolean[(j1 * 16 + k1) * 8 + l1] = true;
}
}
}
}
}
int i2;
int j2;
boolean flag;
for (i1 = 0; i1 < 16; ++i1)
{
for (j2 = 0; j2 < 16; ++j2)
{
for (i2 = 0; i2 < 8; ++i2)
{
flag = !aboolean[(i1 * 16 + j2) * 8 + i2] && (i1 < 15 && aboolean[((i1 + 1) * 16 + j2) * 8 + i2] || i1 > 0 && aboolean[((i1 - 1) * 16 + j2) * 8 + i2] || j2 < 15 && aboolean[(i1 * 16 + j2 + 1) * 8 + i2] || j2 > 0 && aboolean[(i1 * 16 + (j2 - 1)) * 8 + i2] || i2 < 7 && aboolean[(i1 * 16 + j2) * 8 + i2 + 1] || i2 > 0 && aboolean[(i1 * 16 + j2) * 8 + (i2 - 1)]);
if (flag)
{
Material material = world.getBlockMaterial(x + i1, y + i2, z + j2);
if (i2 >= 4 && material.isLiquid())
{
return false;
}
if (i2 < 4 && !material.isSolid() && world.getBlockId(x + i1, y + i2, z + j2) != this.blockIndex)
{
return false;
}
}
}
}
}
for (i1 = 0; i1 < 16; ++i1)
{
for (j2 = 0; j2 < 16; ++j2)
{
for (i2 = 0; i2 < 8; ++i2)
{
if (aboolean[(i1 * 16 + j2) * 8 + i2])
{
world.setBlock(x + i1, y + i2, z
+ j2, i2 >= 4 ? 0 : this.blockIndex, 0,
2);
}
}
}
}
for (i1 = 0; i1 < 16; ++i1)
{
for (j2 = 0; j2 < 16; ++j2)
{
for (i2 = 4; i2 < 8; ++i2)
{
if (aboolean[(i1 * 16 + j2) * 8 + i2] && world.getBlockId(x + i1, y + i2 - 1, z + j2) == Block.dirt.blockID && world.getSavedLightValue(EnumSkyBlock.Sky, x + i1, y + i2, z + j2) > 0)
{
BiomeGenBase biomegenbase = world.getBiomeGenForCoords(x + i1, z + j2);
if (biomegenbase.topBlock == Block.mycelium.blockID)
{
world.setBlock(x + i1, y + i2 - 1, z + j2, Block.mycelium.blockID, 0, 2);
}
else
{
world.setBlock(x + i1, y + i2 - 1, z + j2, Block.grass.blockID, 0, 2);
}
}
}
}
}
for (i1 = 0; i1 < 16; ++i1)
{
for (j2 = 0; j2 < 16; ++j2)
{
for (i2 = 0; i2 < 8; ++i2)
{
flag = !aboolean[(i1 * 16 + j2) * 8 + i2] && (i1 < 15 && aboolean[((i1 + 1) * 16 + j2) * 8 + i2] || i1 > 0 && aboolean[((i1 - 1) * 16 + j2) * 8 + i2] || j2 < 15 && aboolean[(i1 * 16 + j2 + 1) * 8 + i2] || j2 > 0 && aboolean[(i1 * 16 + (j2 - 1)) * 8 + i2] || i2 < 7 && aboolean[(i1 * 16 + j2) * 8 + i2 + 1] || i2 > 0 && aboolean[(i1 * 16 + j2) * 8 + (i2 - 1)]);
if (flag && (i2 < 4 || random.nextInt(2) != 0) && world.getBlockMaterial(x + i1, y + i2, z + j2).isSolid())
{
world.setBlock(x + i1, y + i2, z + j2, Block.stone.blockID, 0, 2);
}
}
}
}
for (i1 = 0; i1 < 16; ++i1)
{
for (j2 = 0; j2 < 16; ++j2)
{
for (i2 = 0; i2 < 8; ++i2)
{
flag = !aboolean[(i1 * 16 + j2) * 8 + i2] && (i1 < 15 && aboolean[((i1 + 1) * 16 + j2) * 8 + i2] || i1 > 0 && aboolean[((i1 - 1) * 16 + j2) * 8 + i2] || j2 < 15 && aboolean[(i1 * 16 + j2 + 1) * 8 + i2] || j2 > 0 && aboolean[(i1 * 16 + (j2 - 1)) * 8 + i2] || i2 < 7 && aboolean[(i1 * 16 + j2) * 8 + i2 + 1] || i2 > 0 && aboolean[(i1 * 16 + j2) * 8 + (i2 - 1)]);
if (flag && (i2 < 4 || random.nextInt(2) != 0) && world.getBlockMaterial(x + i1, y + i2, z + j2).isSolid())
{
if (world.getBlockId(x + i1, y + i2, z + j2) == Block.stone.blockID) {
if (ConfigurationSettings.ORE_GEN_MASTER_SWITCH == true) {
if (random
.nextInt(ConfigurationSettings.EVAPORITE_RARITY) == 0) {
world.setBlock(x + i1, y + i2, z + j2,
BlockIds.ITEM_ELEX_ORE, 1, 2);
}
else if (random
.nextInt(ConfigurationSettings.EVAPORITE_RARITY) == 0) {
world.setBlock(x + i1, y + i2, z + j2,
BlockIds.ITEM_ELEX_ORE, 7, 2);
}
else if (random
.nextInt(ConfigurationSettings.EVAPORITE_RARITY) == 0) {
world.setBlock(x + i1, y + i2, z + j2,
- BlockIds.ITEM_ELEX_ORE, 10, 2);
+ BlockIds.ITEM_ELEX_ORE_2, 10, 2);
}
}
}
}
}
}
}
return true;
}
}
}
| true | true |
public boolean generate(World world, Random random, int x, int y, int z)
{
x -= 8;
for (z -= 8; y > 5 && world.isAirBlock(x, y, z); --y)
{
;
}
if (y <= 4)
{
return false;
}
else
{
y -= 4;
boolean[] aboolean = new boolean[2048];
int l = random.nextInt(4) + 4;
int i1;
for (i1 = 0; i1 < l; ++i1)
{
double d0 = random.nextDouble() * 6.0D + 3.0D;
double d1 = random.nextDouble() * 4.0D + 2.0D;
double d2 = random.nextDouble() * 6.0D + 3.0D;
double d3 = random.nextDouble() * (16.0D - d0 - 2.0D) + 1.0D + d0 / 2.0D;
double d4 = random.nextDouble() * (8.0D - d1 - 4.0D) + 2.0D + d1 / 2.0D;
double d5 = random.nextDouble() * (16.0D - d2 - 2.0D) + 1.0D + d2 / 2.0D;
for (int j1 = 1; j1 < 15; ++j1)
{
for (int k1 = 1; k1 < 15; ++k1)
{
for (int l1 = 1; l1 < 7; ++l1)
{
double d6 = ((double)j1 - d3) / (d0 / 2.0D);
double d7 = ((double)l1 - d4) / (d1 / 2.0D);
double d8 = ((double)k1 - d5) / (d2 / 2.0D);
double d9 = d6 * d6 + d7 * d7 + d8 * d8;
if (d9 < 1.0D)
{
aboolean[(j1 * 16 + k1) * 8 + l1] = true;
}
}
}
}
}
int i2;
int j2;
boolean flag;
for (i1 = 0; i1 < 16; ++i1)
{
for (j2 = 0; j2 < 16; ++j2)
{
for (i2 = 0; i2 < 8; ++i2)
{
flag = !aboolean[(i1 * 16 + j2) * 8 + i2] && (i1 < 15 && aboolean[((i1 + 1) * 16 + j2) * 8 + i2] || i1 > 0 && aboolean[((i1 - 1) * 16 + j2) * 8 + i2] || j2 < 15 && aboolean[(i1 * 16 + j2 + 1) * 8 + i2] || j2 > 0 && aboolean[(i1 * 16 + (j2 - 1)) * 8 + i2] || i2 < 7 && aboolean[(i1 * 16 + j2) * 8 + i2 + 1] || i2 > 0 && aboolean[(i1 * 16 + j2) * 8 + (i2 - 1)]);
if (flag)
{
Material material = world.getBlockMaterial(x + i1, y + i2, z + j2);
if (i2 >= 4 && material.isLiquid())
{
return false;
}
if (i2 < 4 && !material.isSolid() && world.getBlockId(x + i1, y + i2, z + j2) != this.blockIndex)
{
return false;
}
}
}
}
}
for (i1 = 0; i1 < 16; ++i1)
{
for (j2 = 0; j2 < 16; ++j2)
{
for (i2 = 0; i2 < 8; ++i2)
{
if (aboolean[(i1 * 16 + j2) * 8 + i2])
{
world.setBlock(x + i1, y + i2, z
+ j2, i2 >= 4 ? 0 : this.blockIndex, 0,
2);
}
}
}
}
for (i1 = 0; i1 < 16; ++i1)
{
for (j2 = 0; j2 < 16; ++j2)
{
for (i2 = 4; i2 < 8; ++i2)
{
if (aboolean[(i1 * 16 + j2) * 8 + i2] && world.getBlockId(x + i1, y + i2 - 1, z + j2) == Block.dirt.blockID && world.getSavedLightValue(EnumSkyBlock.Sky, x + i1, y + i2, z + j2) > 0)
{
BiomeGenBase biomegenbase = world.getBiomeGenForCoords(x + i1, z + j2);
if (biomegenbase.topBlock == Block.mycelium.blockID)
{
world.setBlock(x + i1, y + i2 - 1, z + j2, Block.mycelium.blockID, 0, 2);
}
else
{
world.setBlock(x + i1, y + i2 - 1, z + j2, Block.grass.blockID, 0, 2);
}
}
}
}
}
for (i1 = 0; i1 < 16; ++i1)
{
for (j2 = 0; j2 < 16; ++j2)
{
for (i2 = 0; i2 < 8; ++i2)
{
flag = !aboolean[(i1 * 16 + j2) * 8 + i2] && (i1 < 15 && aboolean[((i1 + 1) * 16 + j2) * 8 + i2] || i1 > 0 && aboolean[((i1 - 1) * 16 + j2) * 8 + i2] || j2 < 15 && aboolean[(i1 * 16 + j2 + 1) * 8 + i2] || j2 > 0 && aboolean[(i1 * 16 + (j2 - 1)) * 8 + i2] || i2 < 7 && aboolean[(i1 * 16 + j2) * 8 + i2 + 1] || i2 > 0 && aboolean[(i1 * 16 + j2) * 8 + (i2 - 1)]);
if (flag && (i2 < 4 || random.nextInt(2) != 0) && world.getBlockMaterial(x + i1, y + i2, z + j2).isSolid())
{
world.setBlock(x + i1, y + i2, z + j2, Block.stone.blockID, 0, 2);
}
}
}
}
for (i1 = 0; i1 < 16; ++i1)
{
for (j2 = 0; j2 < 16; ++j2)
{
for (i2 = 0; i2 < 8; ++i2)
{
flag = !aboolean[(i1 * 16 + j2) * 8 + i2] && (i1 < 15 && aboolean[((i1 + 1) * 16 + j2) * 8 + i2] || i1 > 0 && aboolean[((i1 - 1) * 16 + j2) * 8 + i2] || j2 < 15 && aboolean[(i1 * 16 + j2 + 1) * 8 + i2] || j2 > 0 && aboolean[(i1 * 16 + (j2 - 1)) * 8 + i2] || i2 < 7 && aboolean[(i1 * 16 + j2) * 8 + i2 + 1] || i2 > 0 && aboolean[(i1 * 16 + j2) * 8 + (i2 - 1)]);
if (flag && (i2 < 4 || random.nextInt(2) != 0) && world.getBlockMaterial(x + i1, y + i2, z + j2).isSolid())
{
if (world.getBlockId(x + i1, y + i2, z + j2) == Block.stone.blockID) {
if (ConfigurationSettings.ORE_GEN_MASTER_SWITCH == true) {
if (random
.nextInt(ConfigurationSettings.EVAPORITE_RARITY) == 0) {
world.setBlock(x + i1, y + i2, z + j2,
BlockIds.ITEM_ELEX_ORE, 1, 2);
}
else if (random
.nextInt(ConfigurationSettings.EVAPORITE_RARITY) == 0) {
world.setBlock(x + i1, y + i2, z + j2,
BlockIds.ITEM_ELEX_ORE, 7, 2);
}
else if (random
.nextInt(ConfigurationSettings.EVAPORITE_RARITY) == 0) {
world.setBlock(x + i1, y + i2, z + j2,
BlockIds.ITEM_ELEX_ORE, 10, 2);
}
}
}
}
}
}
}
return true;
}
}
|
public boolean generate(World world, Random random, int x, int y, int z)
{
x -= 8;
for (z -= 8; y > 5 && world.isAirBlock(x, y, z); --y)
{
;
}
if (y <= 4)
{
return false;
}
else
{
y -= 4;
boolean[] aboolean = new boolean[2048];
int l = random.nextInt(4) + 4;
int i1;
for (i1 = 0; i1 < l; ++i1)
{
double d0 = random.nextDouble() * 6.0D + 3.0D;
double d1 = random.nextDouble() * 4.0D + 2.0D;
double d2 = random.nextDouble() * 6.0D + 3.0D;
double d3 = random.nextDouble() * (16.0D - d0 - 2.0D) + 1.0D + d0 / 2.0D;
double d4 = random.nextDouble() * (8.0D - d1 - 4.0D) + 2.0D + d1 / 2.0D;
double d5 = random.nextDouble() * (16.0D - d2 - 2.0D) + 1.0D + d2 / 2.0D;
for (int j1 = 1; j1 < 15; ++j1)
{
for (int k1 = 1; k1 < 15; ++k1)
{
for (int l1 = 1; l1 < 7; ++l1)
{
double d6 = ((double)j1 - d3) / (d0 / 2.0D);
double d7 = ((double)l1 - d4) / (d1 / 2.0D);
double d8 = ((double)k1 - d5) / (d2 / 2.0D);
double d9 = d6 * d6 + d7 * d7 + d8 * d8;
if (d9 < 1.0D)
{
aboolean[(j1 * 16 + k1) * 8 + l1] = true;
}
}
}
}
}
int i2;
int j2;
boolean flag;
for (i1 = 0; i1 < 16; ++i1)
{
for (j2 = 0; j2 < 16; ++j2)
{
for (i2 = 0; i2 < 8; ++i2)
{
flag = !aboolean[(i1 * 16 + j2) * 8 + i2] && (i1 < 15 && aboolean[((i1 + 1) * 16 + j2) * 8 + i2] || i1 > 0 && aboolean[((i1 - 1) * 16 + j2) * 8 + i2] || j2 < 15 && aboolean[(i1 * 16 + j2 + 1) * 8 + i2] || j2 > 0 && aboolean[(i1 * 16 + (j2 - 1)) * 8 + i2] || i2 < 7 && aboolean[(i1 * 16 + j2) * 8 + i2 + 1] || i2 > 0 && aboolean[(i1 * 16 + j2) * 8 + (i2 - 1)]);
if (flag)
{
Material material = world.getBlockMaterial(x + i1, y + i2, z + j2);
if (i2 >= 4 && material.isLiquid())
{
return false;
}
if (i2 < 4 && !material.isSolid() && world.getBlockId(x + i1, y + i2, z + j2) != this.blockIndex)
{
return false;
}
}
}
}
}
for (i1 = 0; i1 < 16; ++i1)
{
for (j2 = 0; j2 < 16; ++j2)
{
for (i2 = 0; i2 < 8; ++i2)
{
if (aboolean[(i1 * 16 + j2) * 8 + i2])
{
world.setBlock(x + i1, y + i2, z
+ j2, i2 >= 4 ? 0 : this.blockIndex, 0,
2);
}
}
}
}
for (i1 = 0; i1 < 16; ++i1)
{
for (j2 = 0; j2 < 16; ++j2)
{
for (i2 = 4; i2 < 8; ++i2)
{
if (aboolean[(i1 * 16 + j2) * 8 + i2] && world.getBlockId(x + i1, y + i2 - 1, z + j2) == Block.dirt.blockID && world.getSavedLightValue(EnumSkyBlock.Sky, x + i1, y + i2, z + j2) > 0)
{
BiomeGenBase biomegenbase = world.getBiomeGenForCoords(x + i1, z + j2);
if (biomegenbase.topBlock == Block.mycelium.blockID)
{
world.setBlock(x + i1, y + i2 - 1, z + j2, Block.mycelium.blockID, 0, 2);
}
else
{
world.setBlock(x + i1, y + i2 - 1, z + j2, Block.grass.blockID, 0, 2);
}
}
}
}
}
for (i1 = 0; i1 < 16; ++i1)
{
for (j2 = 0; j2 < 16; ++j2)
{
for (i2 = 0; i2 < 8; ++i2)
{
flag = !aboolean[(i1 * 16 + j2) * 8 + i2] && (i1 < 15 && aboolean[((i1 + 1) * 16 + j2) * 8 + i2] || i1 > 0 && aboolean[((i1 - 1) * 16 + j2) * 8 + i2] || j2 < 15 && aboolean[(i1 * 16 + j2 + 1) * 8 + i2] || j2 > 0 && aboolean[(i1 * 16 + (j2 - 1)) * 8 + i2] || i2 < 7 && aboolean[(i1 * 16 + j2) * 8 + i2 + 1] || i2 > 0 && aboolean[(i1 * 16 + j2) * 8 + (i2 - 1)]);
if (flag && (i2 < 4 || random.nextInt(2) != 0) && world.getBlockMaterial(x + i1, y + i2, z + j2).isSolid())
{
world.setBlock(x + i1, y + i2, z + j2, Block.stone.blockID, 0, 2);
}
}
}
}
for (i1 = 0; i1 < 16; ++i1)
{
for (j2 = 0; j2 < 16; ++j2)
{
for (i2 = 0; i2 < 8; ++i2)
{
flag = !aboolean[(i1 * 16 + j2) * 8 + i2] && (i1 < 15 && aboolean[((i1 + 1) * 16 + j2) * 8 + i2] || i1 > 0 && aboolean[((i1 - 1) * 16 + j2) * 8 + i2] || j2 < 15 && aboolean[(i1 * 16 + j2 + 1) * 8 + i2] || j2 > 0 && aboolean[(i1 * 16 + (j2 - 1)) * 8 + i2] || i2 < 7 && aboolean[(i1 * 16 + j2) * 8 + i2 + 1] || i2 > 0 && aboolean[(i1 * 16 + j2) * 8 + (i2 - 1)]);
if (flag && (i2 < 4 || random.nextInt(2) != 0) && world.getBlockMaterial(x + i1, y + i2, z + j2).isSolid())
{
if (world.getBlockId(x + i1, y + i2, z + j2) == Block.stone.blockID) {
if (ConfigurationSettings.ORE_GEN_MASTER_SWITCH == true) {
if (random
.nextInt(ConfigurationSettings.EVAPORITE_RARITY) == 0) {
world.setBlock(x + i1, y + i2, z + j2,
BlockIds.ITEM_ELEX_ORE, 1, 2);
}
else if (random
.nextInt(ConfigurationSettings.EVAPORITE_RARITY) == 0) {
world.setBlock(x + i1, y + i2, z + j2,
BlockIds.ITEM_ELEX_ORE, 7, 2);
}
else if (random
.nextInt(ConfigurationSettings.EVAPORITE_RARITY) == 0) {
world.setBlock(x + i1, y + i2, z + j2,
BlockIds.ITEM_ELEX_ORE_2, 10, 2);
}
}
}
}
}
}
}
return true;
}
}
|
diff --git a/biz.aQute.bndlib/src/aQute/bnd/build/Project.java b/biz.aQute.bndlib/src/aQute/bnd/build/Project.java
index 050b34b91..4852cee83 100644
--- a/biz.aQute.bndlib/src/aQute/bnd/build/Project.java
+++ b/biz.aQute.bndlib/src/aQute/bnd/build/Project.java
@@ -1,2555 +1,2557 @@
package aQute.bnd.build;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.locks.*;
import java.util.jar.*;
import java.util.regex.*;
import aQute.bnd.header.*;
import aQute.bnd.help.*;
import aQute.bnd.maven.support.*;
import aQute.bnd.osgi.*;
import aQute.bnd.osgi.eclipse.*;
import aQute.bnd.service.*;
import aQute.bnd.service.RepositoryPlugin.PutResult;
import aQute.bnd.service.action.*;
import aQute.bnd.version.*;
import aQute.lib.collections.*;
import aQute.lib.io.*;
import aQute.lib.strings.*;
import aQute.libg.command.*;
import aQute.libg.generics.*;
import aQute.libg.glob.*;
import aQute.libg.reporter.*;
import aQute.libg.sed.*;
/**
* This class is NOT threadsafe
*/
public class Project extends Processor {
final static Pattern VERSION_ANNOTATION = Pattern
.compile("@\\s*(:?aQute\\.bnd\\.annotation\\.)?Version\\s*\\(\\s*(:?value\\s*=\\s*)?\"(\\d+(:?\\.\\d+(:?\\.\\d+(:?\\.[\\d\\w-_]+)?)?)?)\"\\s*\\)");
final static String DEFAULT_ACTIONS = "build; label='Build', test; label='Test', run; label='Run', clean; label='Clean', release; label='Release', refreshAll; label=Refresh, deploy;label=Deploy";
public final static String BNDFILE = "bnd.bnd";
public final static String BNDCNF = "cnf";
final Workspace workspace;
boolean preparedPaths;
final Collection<Project> dependson = new LinkedHashSet<Project>();
final Collection<Container> classpath = new LinkedHashSet<Container>();
final Collection<Container> buildpath = new LinkedHashSet<Container>();
final Collection<Container> testpath = new LinkedHashSet<Container>();
final Collection<Container> runpath = new LinkedHashSet<Container>();
final Collection<Container> runbundles = new LinkedHashSet<Container>();
final Collection<Container> runfw = new LinkedHashSet<Container>();
File runstorage;
final Collection<File> sourcepath = new LinkedHashSet<File>();
final Collection<File> allsourcepath = new LinkedHashSet<File>();
final Collection<Container> bootclasspath = new LinkedHashSet<Container>();
final Lock lock = new ReentrantLock(true);
volatile String lockingReason;
volatile Thread lockingThread;
File output;
File target;
boolean inPrepare;
int revision;
File files[];
static List<Project> trail = new ArrayList<Project>();
boolean delayRunDependencies = false;
final ProjectMessages msgs = ReporterMessages.base(this, ProjectMessages.class);
public Project(Workspace workspace, File projectDir, File buildFile) throws Exception {
super(workspace);
this.workspace = workspace;
setFileMustExist(false);
setProperties(buildFile);
assert workspace != null;
// For backward compatibility reasons, we also read
readBuildProperties();
}
public Project(Workspace workspace, File buildDir) throws Exception {
this(workspace, buildDir, new File(buildDir, BNDFILE));
}
private void readBuildProperties() throws Exception {
try {
File f = getFile("build.properties");
if (f.isFile()) {
Properties p = loadProperties(f);
for (Enumeration< ? > e = p.propertyNames(); e.hasMoreElements();) {
String key = (String) e.nextElement();
String newkey = key;
if (key.indexOf('$') >= 0) {
newkey = getReplacer().process(key);
}
setProperty(newkey, p.getProperty(key));
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public static Project getUnparented(File propertiesFile) throws Exception {
propertiesFile = propertiesFile.getAbsoluteFile();
Workspace workspace = new Workspace(propertiesFile.getParentFile());
Project project = new Project(workspace, propertiesFile.getParentFile());
project.setProperties(propertiesFile);
project.setFileMustExist(true);
return project;
}
public synchronized boolean isValid() {
return getBase().isDirectory() && getPropertiesFile().isFile();
}
/**
* Return a new builder that is nicely setup for this project. Please close
* this builder after use.
*
* @param parent
* The project builder to use as parent, use this project if null
* @return
* @throws Exception
*/
public synchronized ProjectBuilder getBuilder(ProjectBuilder parent) throws Exception {
ProjectBuilder builder;
if (parent == null)
builder = new ProjectBuilder(this);
else
builder = new ProjectBuilder(parent);
builder.setBase(getBase());
builder.setPedantic(isPedantic());
builder.setTrace(isTrace());
return builder;
}
public synchronized int getChanged() {
return revision;
}
/*
* Indicate a change in the external world that affects our build. This will
* clear any cached results.
*/
public synchronized void setChanged() {
// if (refresh()) {
preparedPaths = false;
files = null;
revision++;
// }
}
public Workspace getWorkspace() {
return workspace;
}
@Override
public String toString() {
return getBase().getName();
}
/**
* Set up all the paths
*/
public synchronized void prepare() throws Exception {
if (!isValid()) {
warning("Invalid project attempts to prepare: %s", this);
return;
}
if (inPrepare)
throw new CircularDependencyException(trail.toString() + "," + this);
trail.add(this);
try {
if (!preparedPaths) {
inPrepare = true;
try {
dependson.clear();
buildpath.clear();
sourcepath.clear();
allsourcepath.clear();
bootclasspath.clear();
testpath.clear();
runpath.clear();
runbundles.clear();
// We use a builder to construct all the properties for
// use.
setProperty("basedir", getBase().getAbsolutePath());
// If a bnd.bnd file exists, we read it.
// Otherwise, we just do the build properties.
if (!getPropertiesFile().isFile() && new File(getBase(), ".classpath").isFile()) {
// Get our Eclipse info, we might depend on other
// projects
// though ideally this should become empty and void
doEclipseClasspath();
}
// Calculate our source directory
File src = getSrc();
if (src.isDirectory()) {
sourcepath.add(src);
allsourcepath.add(src);
} else
sourcepath.add(getBase());
// Set default bin directory
output = getSrcOutput().getAbsoluteFile();
if (!output.exists()) {
if (!output.mkdirs()) {
throw new IOException("Could not create directory " + output);
}
getWorkspace().changedFile(output);
}
if (!output.isDirectory())
msgs.NoOutputDirectory_(output);
else {
Container c = new Container(this, output);
if (!buildpath.contains(c))
buildpath.add(c);
}
// Where we store all our generated stuff.
target = getTarget0();
// Where the launched OSGi framework stores stuff
String runStorageStr = getProperty(Constants.RUNSTORAGE);
runstorage = runStorageStr != null ? getFile(runStorageStr) : null;
// We might have some other projects we want build
// before we do anything, but these projects are not in
// our path. The -dependson allows you to build them before.
// The values are possibly negated globbing patterns.
// dependencies.add( getWorkspace().getProject("cnf"));
String dp = getProperty(Constants.DEPENDSON);
Set<String> requiredProjectNames = new LinkedHashSet<String>(new Parameters(dp).keySet());
// Allow DependencyConstributors to modify
// requiredProjectNames
List<DependencyContributor> dcs = getPlugins(DependencyContributor.class);
for (DependencyContributor dc : dcs)
dc.addDependencies(this, requiredProjectNames);
Instructions is = new Instructions(requiredProjectNames);
Set<Instruction> unused = new HashSet<Instruction>();
Collection<Project> projects = getWorkspace().getAllProjects();
Collection<Project> dependencies = is.select(projects, unused, false);
for (Instruction u : unused)
msgs.MissingDependson_(u.getInput());
// We have two paths that consists of repo files, projects,
// or some other stuff. The doPath routine adds them to the
// path and extracts the projects so we can build them
// before.
doPath(buildpath, dependencies, parseBuildpath(), bootclasspath, false, BUILDPATH);
doPath(testpath, dependencies, parseTestpath(), bootclasspath, false, TESTPATH);
if (!delayRunDependencies) {
doPath(runfw, dependencies, parseRunFw(), null, false, RUNFW);
doPath(runpath, dependencies, parseRunpath(), null, false, RUNPATH);
doPath(runbundles, dependencies, parseRunbundles(), null, true, RUNBUNDLES);
}
// We now know all dependent projects. But we also depend
// on whatever those projects depend on. This creates an
// ordered list without any duplicates. This of course
// assumes
// that there is no circularity. However, this is checked
// by the inPrepare flag, will throw an exception if we
// are circular.
Set<Project> done = new HashSet<Project>();
done.add(this);
allsourcepath.addAll(sourcepath);
for (Project project : dependencies)
project.traverse(dependson, done);
for (Project project : dependson) {
allsourcepath.addAll(project.getSourcePath());
}
- if (isOk())
- preparedPaths = true;
+ //[cs] Testing this commented out. If bad issues, never setting this to true means that
+ // TONS of extra preparing is done over and over again on the same projects.
+ //if (isOk())
+ preparedPaths = true;
}
finally {
inPrepare = false;
}
}
}
finally {
trail.remove(this);
}
}
/*
*
*/
private File getTarget0() throws IOException {
File target = getTargetDir();
if (!target.exists()) {
if (!target.mkdirs()) {
throw new IOException("Could not create directory " + target);
}
getWorkspace().changedFile(target);
}
return target;
}
public File getSrc() {
String deflt = Workspace.getDefaults().getProperty(Constants.DEFAULT_PROP_SRC_DIR);
return getFile(getProperty(Constants.DEFAULT_PROP_SRC_DIR, deflt));
}
public File getSrcOutput() {
String deflt = Workspace.getDefaults().getProperty(Constants.DEFAULT_PROP_BIN_DIR);
return getFile(getProperty(Constants.DEFAULT_PROP_BIN_DIR, deflt));
}
public File getTestSrc() {
String deflt = Workspace.getDefaults().getProperty(Constants.DEFAULT_PROP_TESTSRC_DIR);
return getFile(getProperty(Constants.DEFAULT_PROP_TESTSRC_DIR, deflt));
}
public File getTestOutput() {
String deflt = Workspace.getDefaults().getProperty(Constants.DEFAULT_PROP_TESTBIN_DIR);
return getFile(getProperty(Constants.DEFAULT_PROP_TESTBIN_DIR, deflt));
}
public File getTargetDir() {
String deflt = Workspace.getDefaults().getProperty(Constants.DEFAULT_PROP_TARGET_DIR);
return getFile(getProperty(Constants.DEFAULT_PROP_TARGET_DIR, deflt));
}
private void traverse(Collection<Project> dependencies, Set<Project> visited) throws Exception {
if (visited.contains(this))
return;
visited.add(this);
for (Project project : getDependson())
project.traverse(dependencies, visited);
dependencies.add(this);
}
/**
* Iterate over the entries and place the projects on the projects list and
* all the files of the entries on the resultpath.
*
* @param resultpath
* The list that gets all the files
* @param projects
* The list that gets any projects that are entries
* @param entries
* The input list of classpath entries
*/
private void doPath(Collection<Container> resultpath, Collection<Project> projects, Collection<Container> entries,
Collection<Container> bootclasspath, boolean noproject, String name) {
for (Container cpe : entries) {
if (cpe.getError() != null)
error(cpe.getError());
else {
if (cpe.getType() == Container.TYPE.PROJECT) {
projects.add(cpe.getProject());
if (noproject //
&& since(About._2_3) //
&& cpe.getAttributes() != null
&& VERSION_ATTR_PROJECT.equals(cpe.getAttributes().get(VERSION_ATTRIBUTE))) {
//
// we're trying to put a project's output directory on
// -runbundles list
//
error("%s is specified with version=project on %s. This version uses the project's output directory, which is not allowed since it must be an actual JAR file for this list.",
cpe.getBundleSymbolicName(), name);
}
}
if (bootclasspath != null
&& (cpe.getBundleSymbolicName().startsWith("ee.") || cpe.getAttributes().containsKey("boot")))
bootclasspath.add(cpe);
else
resultpath.add(cpe);
}
}
}
/**
* Parse the list of bundles that are a prerequisite to this project.
* Bundles are listed in repo specific names. So we just let our repo
* plugins iterate over the list of bundles and we get the highest version
* from them.
*
* @return
*/
private List<Container> parseBuildpath() throws Exception {
List<Container> bundles = getBundles(Strategy.LOWEST, getProperty(Constants.BUILDPATH), Constants.BUILDPATH);
return bundles;
}
private List<Container> parseRunpath() throws Exception {
return getBundles(Strategy.HIGHEST, getProperty(Constants.RUNPATH), Constants.RUNPATH);
}
private List<Container> parseRunbundles() throws Exception {
return getBundles(Strategy.HIGHEST, getProperty(Constants.RUNBUNDLES), Constants.RUNBUNDLES);
}
private List<Container> parseRunFw() throws Exception {
return getBundles(Strategy.HIGHEST, getProperty(Constants.RUNFW), Constants.RUNFW);
}
private List<Container> parseTestpath() throws Exception {
return getBundles(Strategy.HIGHEST, getProperty(Constants.TESTPATH), Constants.TESTPATH);
}
/**
* Analyze the header and return a list of files that should be on the
* build, test or some other path. The list is assumed to be a list of bsns
* with a version specification. The special case of version=project
* indicates there is a project in the same workspace. The path to the
* output directory is calculated. The default directory ${bin} can be
* overridden with the output attribute.
*
* @param strategy
* STRATEGY_LOWEST or STRATEGY_HIGHEST
* @param spec
* The header
* @return
*/
public List<Container> getBundles(Strategy strategyx, String spec, String source) throws Exception {
List<Container> result = new ArrayList<Container>();
Parameters bundles = new Parameters(spec);
try {
for (Iterator<Entry<String,Attrs>> i = bundles.entrySet().iterator(); i.hasNext();) {
Entry<String,Attrs> entry = i.next();
String bsn = removeDuplicateMarker(entry.getKey());
Map<String,String> attrs = entry.getValue();
Container found = null;
String versionRange = attrs.get("version");
if (versionRange != null) {
if (versionRange.equals(VERSION_ATTR_LATEST) || versionRange.equals(VERSION_ATTR_SNAPSHOT)) {
found = getBundle(bsn, versionRange, strategyx, attrs);
}
}
if (found == null) {
//
// TODO This looks like a duplicate
// of what is done in getBundle??
//
if (versionRange != null
&& (versionRange.equals(VERSION_ATTR_PROJECT) || versionRange.equals(VERSION_ATTR_LATEST))) {
//
// Use the bin directory ...
//
Project project = getWorkspace().getProject(bsn);
if (project != null && project.exists()) {
File f = project.getOutput();
found = new Container(project, bsn, versionRange, Container.TYPE.PROJECT, f, null, attrs,
null);
} else {
msgs.NoSuchProject(bsn, spec);
continue;
}
} else if (versionRange != null && versionRange.equals("file")) {
File f = getFile(bsn);
String error = null;
if (!f.exists())
error = "File does not exist: " + f.getAbsolutePath();
if (f.getName().endsWith(".lib")) {
found = new Container(this, bsn, "file", Container.TYPE.LIBRARY, f, error, attrs, null);
} else {
found = new Container(this, bsn, "file", Container.TYPE.EXTERNAL, f, error, attrs, null);
}
} else {
found = getBundle(bsn, versionRange, strategyx, attrs);
}
}
if (found != null) {
List<Container> libs = found.getMembers();
for (Container cc : libs) {
if (result.contains(cc)) {
if (isPedantic())
warning("Multiple bundles with the same final URL: %s, dropped duplicate", cc);
} else {
if (cc.getError() != null) {
warning("Cannot find %s", cc);
}
result.add(cc);
}
}
} else {
// Oops, not a bundle in sight :-(
Container x = new Container(this, bsn, versionRange, Container.TYPE.ERROR, null, bsn + ";version="
+ versionRange + " not found", attrs, null);
result.add(x);
warning("Can not find URL for bsn " + bsn);
}
}
}
catch (CircularDependencyException e) {
String message = e.getMessage();
if (source != null)
message = String.format("%s (from property: %s)", message, source);
msgs.CircularDependencyContext_Message_(getName(), message);
}
catch (Exception e) {
msgs.Unexpected_Error_(spec, e);
}
return result;
}
/**
* Just calls a new method with a default parm.
*
* @throws Exception
*/
Collection<Container> getBundles(Strategy strategy, String spec) throws Exception {
return getBundles(strategy, spec, null);
}
static void mergeNames(String names, Set<String> set) {
StringTokenizer tokenizer = new StringTokenizer(names, ",");
while (tokenizer.hasMoreTokens())
set.add(tokenizer.nextToken().trim());
}
static String flatten(Set<String> names) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (String name : names) {
if (!first)
builder.append(',');
builder.append(name);
first = false;
}
return builder.toString();
}
static void addToPackageList(Container container, String newPackageNames) {
Set<String> merged = new HashSet<String>();
String packageListStr = container.attributes.get("packages");
if (packageListStr != null)
mergeNames(packageListStr, merged);
if (newPackageNames != null)
mergeNames(newPackageNames, merged);
container.putAttribute("packages", flatten(merged));
}
/**
* The user selected pom in a path. This will place the pom as well as its
* dependencies on the list
*
* @param strategyx
* the strategy to use.
* @param result
* The list of result containers
* @param attrs
* The attributes
* @throws Exception
* anything goes wrong
*/
public void doMavenPom(Strategy strategyx, List<Container> result, String action) throws Exception {
File pomFile = getFile("pom.xml");
if (!pomFile.isFile())
msgs.MissingPom();
else {
ProjectPom pom = getWorkspace().getMaven().createProjectModel(pomFile);
if (action == null)
action = "compile";
Pom.Scope act = Pom.Scope.valueOf(action);
Set<Pom> dependencies = pom.getDependencies(act);
for (Pom sub : dependencies) {
File artifact = sub.getArtifact();
Container container = new Container(artifact, null);
result.add(container);
}
}
}
public Collection<Project> getDependson() throws Exception {
prepare();
return dependson;
}
public Collection<Container> getBuildpath() throws Exception {
prepare();
return buildpath;
}
public Collection<Container> getTestpath() throws Exception {
prepare();
return testpath;
}
/**
* Handle dependencies for paths that are calculated on demand.
*
* @param testpath2
* @param parseTestpath
*/
private void justInTime(Collection<Container> path, List<Container> entries, boolean noproject, String name) {
if (delayRunDependencies && path.isEmpty())
doPath(path, dependson, entries, null, noproject, name);
}
public Collection<Container> getRunpath() throws Exception {
prepare();
justInTime(runpath, parseRunpath(), false, RUNPATH);
return runpath;
}
public Collection<Container> getRunbundles() throws Exception {
prepare();
justInTime(runbundles, parseRunbundles(), true, RUNBUNDLES);
return runbundles;
}
/**
* Return the run framework
*
* @throws Exception
*/
public Collection<Container> getRunFw() throws Exception {
prepare();
justInTime(runfw, parseRunFw(), false, RUNFW);
return runfw;
}
public File getRunStorage() throws Exception {
prepare();
return runstorage;
}
public boolean getRunBuilds() {
boolean result;
String runBuildsStr = getProperty(Constants.RUNBUILDS);
if (runBuildsStr == null)
result = !getPropertiesFile().getName().toLowerCase().endsWith(Constants.DEFAULT_BNDRUN_EXTENSION);
else
result = Boolean.parseBoolean(runBuildsStr);
return result;
}
public Collection<File> getSourcePath() throws Exception {
prepare();
return sourcepath;
}
public Collection<File> getAllsourcepath() throws Exception {
prepare();
return allsourcepath;
}
public Collection<Container> getBootclasspath() throws Exception {
prepare();
return bootclasspath;
}
public File getOutput() throws Exception {
prepare();
return output;
}
private void doEclipseClasspath() throws Exception {
EclipseClasspath eclipse = new EclipseClasspath(this, getWorkspace().getBase(), getBase());
eclipse.setRecurse(false);
// We get the file directories but in this case we need
// to tell ant that the project names
for (File dependent : eclipse.getDependents()) {
Project required = workspace.getProject(dependent.getName());
dependson.add(required);
}
for (File f : eclipse.getClasspath()) {
buildpath.add(new Container(f, null));
}
for (File f : eclipse.getBootclasspath()) {
bootclasspath.add(new Container(f, null));
}
sourcepath.addAll(eclipse.getSourcepath());
allsourcepath.addAll(eclipse.getAllSources());
output = eclipse.getOutput();
}
public String _p_dependson(String args[]) throws Exception {
return list(args, toFiles(getDependson()));
}
private Collection< ? > toFiles(Collection<Project> projects) {
List<File> files = new ArrayList<File>();
for (Project p : projects) {
files.add(p.getBase());
}
return files;
}
public String _p_buildpath(String args[]) throws Exception {
return list(args, getBuildpath());
}
public String _p_testpath(String args[]) throws Exception {
return list(args, getRunpath());
}
public String _p_sourcepath(String args[]) throws Exception {
return list(args, getSourcePath());
}
public String _p_allsourcepath(String args[]) throws Exception {
return list(args, getAllsourcepath());
}
public String _p_bootclasspath(String args[]) throws Exception {
return list(args, getBootclasspath());
}
public String _p_output(String args[]) throws Exception {
if (args.length != 1)
throw new IllegalArgumentException("${output} should not have arguments");
return getOutput().getAbsolutePath();
}
private String list(String[] args, Collection< ? > list) {
if (args.length > 3)
throw new IllegalArgumentException("${" + args[0]
+ "[;<separator>]} can only take a separator as argument, has " + Arrays.toString(args));
String separator = ",";
if (args.length == 2) {
separator = args[1];
}
return join(list, separator);
}
@Override
protected Object[] getMacroDomains() {
return new Object[] {
workspace
};
}
public File release(String jarName, InputStream jarStream) throws Exception {
String name = getProperty(Constants.RELEASEREPO);
return release(name, jarName, jarStream);
}
public URI releaseURI(String jarName, InputStream jarStream) throws Exception {
String name = getProperty(Constants.RELEASEREPO);
return releaseURI(name, jarName, jarStream);
}
/**
* Release
*
* @param name
* The repository name
* @param jarName
* @param jarStream
* @return
* @throws Exception
*/
public File release(String name, String jarName, InputStream jarStream) throws Exception {
URI uri = releaseURI(name, jarName, jarStream);
if (uri != null && uri.getScheme().equals("file")) {
return new File(uri);
}
return null;
}
public URI releaseURI(String name, String jarName, InputStream jarStream) throws Exception {
trace("release to %s", name);
RepositoryPlugin repo = getReleaseRepo(name);
if (repo == null) {
if (name == null)
msgs.NoNameForReleaseRepository();
else
msgs.ReleaseRepository_NotFoundIn_(name, getPlugins(RepositoryPlugin.class));
return null;
}
try {
PutResult r = repo.put(jarStream, new RepositoryPlugin.PutOptions());
trace("Released %s to %s in repository %s", jarName, r.artifact, repo);
return r.artifact;
}
catch (Exception e) {
msgs.Release_Into_Exception_(jarName, repo, e);
return null;
}
}
RepositoryPlugin getReleaseRepo(String releaserepo) {
String name = releaserepo == null ? name = getProperty(RELEASEREPO) : releaserepo;
List<RepositoryPlugin> plugins = getPlugins(RepositoryPlugin.class);
for (RepositoryPlugin plugin : plugins) {
if (!plugin.canWrite())
continue;
if (name == null)
return plugin;
if (name.equals(plugin.getName()))
return plugin;
}
return null;
}
public void release(boolean test) throws Exception {
String name = getProperty(Constants.RELEASEREPO);
release(name, test);
}
/**
* Release
*
* @param name
* The respository name
* @param test
* Run testcases
* @throws Exception
*/
public void release(String name, boolean test) throws Exception {
trace("release");
File[] jars = build(test);
// If build fails jars will be null
if (jars == null) {
trace("no jars being build");
return;
}
trace("build ", Arrays.toString(jars));
for (File jar : jars) {
release(name, jar.getName(), new BufferedInputStream(new FileInputStream(jar)));
}
}
/**
* Get a bundle from one of the plugin repositories. If an exact version is
* required we just return the first repository found (in declaration order
* in the build.bnd file).
*
* @param bsn
* The bundle symbolic name
* @param range
* The version range
* @param lowest
* set to LOWEST or HIGHEST
* @return the file object that points to the bundle or null if not found
* @throws Exception
* when something goes wrong
*/
public Container getBundle(String bsn, String range, Strategy strategy, Map<String,String> attrs) throws Exception {
if (range == null)
range = "0";
if (VERSION_ATTR_SNAPSHOT.equals(range) || VERSION_ATTR_PROJECT.equals(range)) {
return getBundleFromProject(bsn, attrs);
}
Strategy useStrategy = strategy;
if (VERSION_ATTR_LATEST.equals(range)) {
Container c = getBundleFromProject(bsn, attrs);
if (c != null)
return c;
useStrategy = Strategy.HIGHEST;
}
useStrategy = overrideStrategy(attrs, useStrategy);
List<RepositoryPlugin> plugins = workspace.getRepositories();
if (useStrategy == Strategy.EXACT) {
if (!Verifier.isVersion(range))
return new Container(this, bsn, range, Container.TYPE.ERROR, null, bsn + ";version=" + range
+ " Invalid version", null, null);
// For an exact range we just iterate over the repos
// and return the first we find.
Version version = new Version(range);
for (RepositoryPlugin plugin : plugins) {
DownloadBlocker blocker = new DownloadBlocker(this);
File result = plugin.get(bsn, version, attrs, blocker);
if (result != null)
return toContainer(bsn, range, attrs, result, blocker);
}
} else {
VersionRange versionRange = VERSION_ATTR_LATEST.equals(range) ? new VersionRange("0") : new VersionRange(
range);
// We have a range search. Gather all the versions in all the repos
// and make a decision on that choice. If the same version is found
// in
// multiple repos we take the first
SortedMap<Version,RepositoryPlugin> versions = new TreeMap<Version,RepositoryPlugin>();
for (RepositoryPlugin plugin : plugins) {
try {
SortedSet<Version> vs = plugin.versions(bsn);
if (vs != null) {
for (Version v : vs) {
if (!versions.containsKey(v) && versionRange.includes(v))
versions.put(v, plugin);
}
}
}
catch (UnsupportedOperationException ose) {
// We have a plugin that cannot list versions, try
// if it has this specific version
// The main reaosn for this code was the Maven Remote
// Repository
// To query, we must have a real version
if (!versions.isEmpty() && Verifier.isVersion(range)) {
Version version = new Version(range);
DownloadBlocker blocker = new DownloadBlocker(this);
File file = plugin.get(bsn, version, attrs, blocker);
// and the entry must exist
// if it does, return this as a result
if (file != null)
return toContainer(bsn, range, attrs, file, blocker);
}
}
}
// Verify if we found any, if so, we use the strategy to pick
// the first or last
if (!versions.isEmpty()) {
Version provider = null;
switch (useStrategy) {
case HIGHEST :
provider = versions.lastKey();
break;
case LOWEST :
provider = versions.firstKey();
break;
case EXACT :
// TODO need to handle exact better
break;
}
if (provider != null) {
RepositoryPlugin repo = versions.get(provider);
String version = provider.toString();
DownloadBlocker blocker = new DownloadBlocker(this);
File result = repo.get(bsn, provider, attrs, blocker);
if (result != null)
return toContainer(bsn, version, attrs, result, blocker);
} else
msgs.FoundVersions_ForStrategy_ButNoProvider(versions, useStrategy);
}
}
//
// If we get this far we ran into an error somewhere
//
// Check if we try to find a BSN that is in the workspace but marked
// latest
//
if (!range.equals(VERSION_ATTR_LATEST)) {
Container c = getBundleFromProject(bsn, attrs);
return new Container(this, bsn, range, Container.TYPE.ERROR, null, bsn + ";version=" + range
+ " Not found because latest was not specified."
+ " It is, however, present in the workspace. Add '" + bsn
+ ";version=(latest|snapshot)' to see the bundle in the workspace.", null, null);
}
return new Container(this, bsn, range, Container.TYPE.ERROR, null, bsn + ";version=" + range + " Not found in "
+ plugins, null, null);
}
/**
* @param attrs
* @param useStrategy
* @return
*/
protected Strategy overrideStrategy(Map<String,String> attrs, Strategy useStrategy) {
if (attrs != null) {
String overrideStrategy = attrs.get("strategy");
if (overrideStrategy != null) {
if ("highest".equalsIgnoreCase(overrideStrategy))
useStrategy = Strategy.HIGHEST;
else if ("lowest".equalsIgnoreCase(overrideStrategy))
useStrategy = Strategy.LOWEST;
else if ("exact".equalsIgnoreCase(overrideStrategy))
useStrategy = Strategy.EXACT;
}
}
return useStrategy;
}
/**
* @param bsn
* @param range
* @param attrs
* @param result
* @return
*/
protected Container toContainer(String bsn, String range, Map<String,String> attrs, File result, DownloadBlocker db) {
File f = result;
if (f == null) {
msgs.ConfusedNoContainerFile();
f = new File("was null");
}
Container container;
if (f.getName().endsWith("lib"))
container = new Container(this, bsn, range, Container.TYPE.LIBRARY, f, null, attrs, db);
else
container = new Container(this, bsn, range, Container.TYPE.REPO, f, null, attrs, db);
return container;
}
/**
* Look for the bundle in the workspace. The premise is that the bsn must
* start with the project name.
*
* @param bsn
* The bsn
* @param attrs
* Any attributes
* @return
* @throws Exception
*/
private Container getBundleFromProject(String bsn, Map<String,String> attrs) throws Exception {
String pname = bsn;
while (true) {
Project p = getWorkspace().getProject(pname);
if (p != null && p.isValid()) {
Container c = p.getDeliverable(bsn, attrs);
return c;
}
int n = pname.lastIndexOf('.');
if (n <= 0)
return null;
pname = pname.substring(0, n);
}
}
/**
* Deploy the file (which must be a bundle) into the repository.
*
* @param name
* The repository name
* @param file
* bundle
*/
public void deploy(String name, File file) throws Exception {
List<RepositoryPlugin> plugins = getPlugins(RepositoryPlugin.class);
RepositoryPlugin rp = null;
for (RepositoryPlugin plugin : plugins) {
if (!plugin.canWrite()) {
continue;
}
if (name == null) {
rp = plugin;
break;
} else if (name.equals(plugin.getName())) {
rp = plugin;
break;
}
}
if (rp != null) {
try {
rp.put(new BufferedInputStream(new FileInputStream(file)), new RepositoryPlugin.PutOptions());
return;
}
catch (Exception e) {
msgs.DeployingFile_On_Exception_(file, rp.getName(), e);
}
return;
}
trace("No repo found " + file);
throw new IllegalArgumentException("No repository found for " + file);
}
/**
* Deploy the file (which must be a bundle) into the repository.
*
* @param file
* bundle
*/
public void deploy(File file) throws Exception {
String name = getProperty(Constants.DEPLOYREPO);
deploy(name, file);
}
/**
* Deploy the current project to a repository
*
* @throws Exception
*/
public void deploy() throws Exception {
Parameters deploy = new Parameters(getProperty(DEPLOY));
if (deploy.isEmpty()) {
warning("Deploying but %s is not set to any repo", DEPLOY);
return;
}
File[] outputs = getBuildFiles();
for (File output : outputs) {
for (Deploy d : getPlugins(Deploy.class)) {
trace("Deploying %s to: %s", output.getName(), d);
try {
if (d.deploy(this, output.getName(), new BufferedInputStream(new FileInputStream(output))))
trace("deployed %s successfully to %s", output, d);
}
catch (Exception e) {
msgs.Deploying(e);
}
}
}
}
/**
* Macro access to the repository ${repo;<bsn>[;<version>[;<low|high>]]}
*/
static String _repoHelp = "${repo ';'<bsn> [ ; <version> [; ('HIGHEST'|'LOWEST')]}";
public String _repo(String args[]) throws Exception {
if (args.length < 2) {
msgs.RepoTooFewArguments(_repoHelp, args);
return null;
}
String bsns = args[1];
String version = null;
Strategy strategy = Strategy.HIGHEST;
if (args.length > 2) {
version = args[2];
if (args.length == 4) {
if (args[3].equalsIgnoreCase("HIGHEST"))
strategy = Strategy.HIGHEST;
else if (args[3].equalsIgnoreCase("LOWEST"))
strategy = Strategy.LOWEST;
else if (args[3].equalsIgnoreCase("EXACT"))
strategy = Strategy.EXACT;
else
msgs.InvalidStrategy(_repoHelp, args);
}
}
Collection<String> parts = split(bsns);
List<String> paths = new ArrayList<String>();
for (String bsn : parts) {
Container container = getBundle(bsn, version, strategy, null);
if (container.getError() != null) {
error("${repo} macro refers to an artifact %s-%s (%s) that has an error: %s", bsn, version, strategy,
container.getError());
} else
add(paths, container);
}
return join(paths);
}
private void add(List<String> paths, Container container) throws Exception {
if (container.getType() == Container.TYPE.LIBRARY) {
List<Container> members = container.getMembers();
for (Container sub : members) {
add(paths, sub);
}
} else {
if (container.getError() == null)
paths.add(container.getFile().getAbsolutePath());
else {
paths.add("<<${repo} = " + container.getBundleSymbolicName() + "-" + container.getVersion() + " : "
+ container.getError() + ">>");
if (isPedantic()) {
warning("Could not expand repo path request: %s ", container);
}
}
}
}
public File getTarget() throws Exception {
prepare();
return target;
}
/**
* This is the external method that will pre-build any dependencies if it is
* out of date.
*
* @param underTest
* @return
* @throws Exception
*/
public File[] build(boolean underTest) throws Exception {
if (isNoBundles())
return null;
if (getProperty("-nope") != null) {
warning("Please replace -nope with %s", NOBUNDLES);
return null;
}
if (isStale()) {
trace("building " + this);
files = buildLocal(underTest);
}
return files;
}
/**
* Return the files
*/
public File[] getFiles() {
return files;
}
/**
* Check if this project needs building. This is defined as:
*/
public boolean isStale() throws Exception {
if (workspace == null || workspace.isOffline()) {
trace("working %s offline, so always stale", this);
return true;
}
Set<Project> visited = new HashSet<Project>();
return isStale(visited);
}
boolean isStale(Set<Project> visited) throws Exception {
// When we do not generate anything ...
if (isNoBundles())
return false;
if (visited.contains(this)) {
msgs.CircularDependencyContext_Message_(this.getName(), visited.toString());
return false;
}
visited.add(this);
long buildTime = 0;
files = getBuildFiles(false);
if (files == null)
return true;
for (File f : files) {
if (f.lastModified() < lastModified())
return true;
if (buildTime < f.lastModified())
buildTime = f.lastModified();
}
for (Project dependency : getDependson()) {
if (dependency == this)
continue;
if (dependency.isStale())
return true;
if (dependency.isNoBundles())
continue;
File[] deps = dependency.getBuildFiles();
for (File f : deps) {
if (f.lastModified() >= buildTime)
return true;
}
}
return false;
}
/**
* This method must only be called when it is sure that the project has been
* build before in the same session. It is a bit yucky, but ant creates
* different class spaces which makes it hard to detect we already build it.
* This method remembers the files in the appropriate instance vars.
*
* @return
*/
public File[] getBuildFiles() throws Exception {
return getBuildFiles(true);
}
public File[] getBuildFiles(boolean buildIfAbsent) throws Exception {
if (files != null)
return files;
File f = new File(getTarget(), BUILDFILES);
if (f.isFile()) {
BufferedReader rdr = IO.reader(f);
try {
List<File> files = newList();
for (String s = rdr.readLine(); s != null; s = rdr.readLine()) {
s = s.trim();
File ff = new File(s);
if (!ff.isFile()) {
// Originally we warned the user
// but lets just rebuild. That way
// the error is not noticed but
// it seems better to correct,
// See #154
rdr.close();
f.delete();
break;
}
files.add(ff);
}
return this.files = files.toArray(new File[files.size()]);
}
finally {
rdr.close();
}
}
if (buildIfAbsent)
return files = buildLocal(false);
return files = null;
}
/**
* Build without doing any dependency checking. Make sure any dependent
* projects are built first.
*
* @param underTest
* @return
* @throws Exception
*/
public File[] buildLocal(boolean underTest) throws Exception {
if (isNoBundles())
return null;
File bfs = new File(getTarget(), BUILDFILES);
bfs.delete();
files = null;
ProjectBuilder builder = getBuilder(null);
try {
if (underTest)
builder.setProperty(Constants.UNDERTEST, "true");
Jar jars[] = builder.builds();
File[] files = new File[jars.length];
getInfo(builder);
if (isOk()) {
this.files = files;
for (int i = 0; i < jars.length; i++) {
Jar jar = jars[i];
File file = saveBuild(jar);
if (file == null) {
getInfo(builder);
error("Could not save %s", jar.getName());
return this.files = null;
}
this.files[i] = file;
}
// Write out the filenames in the buildfiles file
// so we can get them later evenin another process
Writer fw = IO.writer(bfs);
try {
for (File f : files) {
fw.append(f.getAbsolutePath());
fw.append("\n");
}
}
finally {
fw.close();
}
getWorkspace().changedFile(bfs);
return files;
}
return null;
}
finally {
builder.close();
}
}
/**
* Answer if this project does not have any output
*
* @return
*/
public boolean isNoBundles() {
return getProperty(NOBUNDLES) != null;
}
public File saveBuild(Jar jar) throws Exception {
try {
File f = getOutputFile(jar.getBsn(), jar.getVersion());
String msg = "";
if (!f.exists() || f.lastModified() < jar.lastModified()) {
reportNewer(f.lastModified(), jar);
f.delete();
File fp = f.getParentFile();
if (!fp.isDirectory()) {
if (!fp.exists() && !fp.mkdirs()) {
throw new IOException("Could not create directory " + fp);
}
}
jar.write(f);
getWorkspace().changedFile(f);
} else {
msg = "(not modified since " + new Date(f.lastModified()) + ")";
}
trace(jar.getName() + " (" + f.getName() + ") " + jar.getResources().size() + " " + msg);
return f;
}
finally {
jar.close();
}
}
/**
* Calculate the file for a JAR. The default name is bsn.jar, but this can
* be overridden with an
*
* @param jar
* @return
* @throws Exception
*/
public File getOutputFile(String bsn, String version) throws Exception {
if (version == null)
version = "0";
Processor scoped = new Processor(this);
try {
scoped.setProperty("@bsn", bsn);
scoped.setProperty("@version", version.toString());
String path = scoped.getProperty(OUTPUTMASK, bsn + ".jar");
return IO.getFile(getTarget(), path);
}
finally {
scoped.close();
}
}
public File getOutputFile(String bsn) throws Exception {
return getOutputFile(bsn, "0.0.0");
}
private void reportNewer(long lastModified, Jar jar) {
if (isTrue(getProperty(Constants.REPORTNEWER))) {
StringBuilder sb = new StringBuilder();
String del = "Newer than " + new Date(lastModified);
for (Map.Entry<String,Resource> entry : jar.getResources().entrySet()) {
if (entry.getValue().lastModified() > lastModified) {
sb.append(del);
del = ", \n ";
sb.append(entry.getKey());
}
}
if (sb.length() > 0)
warning(sb.toString());
}
}
/**
* Refresh if we are based on stale data. This also implies our workspace.
*/
@Override
public boolean refresh() {
boolean changed = false;
if (isCnf()) {
changed = workspace.refresh();
}
return super.refresh() || changed;
}
public boolean isCnf() {
return getBase().getName().equals(Workspace.CNFDIR);
}
@Override
public void propertiesChanged() {
super.propertiesChanged();
preparedPaths = false;
files = null;
}
public String getName() {
return getBase().getName();
}
public Map<String,Action> getActions() {
Map<String,Action> all = newMap();
Map<String,Action> actions = newMap();
fillActions(all);
getWorkspace().fillActions(all);
for (Map.Entry<String,Action> action : all.entrySet()) {
String key = getReplacer().process(action.getKey());
if (key != null && key.trim().length() != 0)
actions.put(key, action.getValue());
}
return actions;
}
public void fillActions(Map<String,Action> all) {
List<NamedAction> plugins = getPlugins(NamedAction.class);
for (NamedAction a : plugins)
all.put(a.getName(), a);
Parameters actions = new Parameters(getProperty("-actions", DEFAULT_ACTIONS));
for (Entry<String,Attrs> entry : actions.entrySet()) {
String key = Processor.removeDuplicateMarker(entry.getKey());
Action action;
if (entry.getValue().get("script") != null) {
// TODO check for the type
action = new ScriptAction(entry.getValue().get("type"), entry.getValue().get("script"));
} else {
action = new ReflectAction(key);
}
String label = entry.getValue().get("label");
all.put(label.toLowerCase(), action);
}
}
public void release() throws Exception {
release(false);
}
@SuppressWarnings("resource")
public void export(String runFilePath, boolean keep, File output) throws Exception {
prepare();
OutputStream outStream = null;
try {
Project packageProject;
if (runFilePath == null || runFilePath.length() == 0 || ".".equals(runFilePath)) {
packageProject = this;
} else {
File runFile = new File(getBase(), runFilePath);
if (!runFile.isFile())
throw new IOException(String.format("Run file %s does not exist (or is not a file).",
runFile.getAbsolutePath()));
packageProject = new Project(getWorkspace(), getBase(), runFile);
packageProject.setParent(this);
}
packageProject.clear();
ProjectLauncher launcher = packageProject.getProjectLauncher();
launcher.setKeep(keep);
Jar jar = launcher.executable();
outStream = new FileOutputStream(output);
jar.write(outStream);
}
finally {
IO.close(outStream);
}
}
/**
* Release.
*
* @param name
* The repository name
* @throws Exception
*/
public void release(String name) throws Exception {
release(name, false);
}
public void clean() throws Exception {
File target = getTarget0();
if (target.isDirectory() && target.getParentFile() != null) {
IO.delete(target);
if (!target.exists() && !target.mkdirs()) {
throw new IOException("Could not create directory " + target);
}
}
File output = getSrcOutput().getAbsoluteFile();
if (getOutput().isDirectory())
IO.delete(output);
if (!output.exists() && !output.mkdirs()) {
throw new IOException("Could not create directory " + output);
}
}
public File[] build() throws Exception {
return build(false);
}
public void run() throws Exception {
ProjectLauncher pl = getProjectLauncher();
pl.setTrace(isTrace());
pl.launch();
}
public void test() throws Exception {
String testcases = getProperties().getProperty(Constants.TESTCASES);
if (testcases == null) {
warning("No %s set", Constants.TESTCASES);
return;
}
clear();
ProjectTester tester = getProjectTester();
tester.setContinuous(isTrue(getProperty(Constants.TESTCONTINUOUS)));
tester.prepare();
if (!isOk()) {
return;
}
int errors = tester.test();
if (errors == 0) {
System.err.println("No Errors");
} else {
if (errors > 0) {
System.err.println(errors + " Error(s)");
} else
System.err.println("Error " + errors);
}
}
/**
* Run JUnit
* @throws Exception
*/
public void junit() throws Exception {
JUnitLauncher launcher = new JUnitLauncher(this);
launcher.launch();
}
/**
* This methods attempts to turn any jar into a valid jar. If this is a
* bundle with manifest, a manifest is added based on defaults. If it is a
* bundle, but not r4, we try to add the r4 headers.
*
* @param descriptor
* @param in
* @return
* @throws Exception
*/
public Jar getValidJar(File f) throws Exception {
Jar jar = new Jar(f);
return getValidJar(jar, f.getAbsolutePath());
}
public Jar getValidJar(URL url) throws Exception {
InputStream in = url.openStream();
try {
Jar jar = new Jar(url.getFile().replace('/', '.'), in, System.currentTimeMillis());
return getValidJar(jar, url.toString());
}
finally {
in.close();
}
}
public Jar getValidJar(Jar jar, String id) throws Exception {
Manifest manifest = jar.getManifest();
if (manifest == null) {
trace("Wrapping with all defaults");
Builder b = new Builder(this);
this.addClose(b);
b.addClasspath(jar);
b.setProperty("Bnd-Message", "Wrapped from " + id + "because lacked manifest");
b.setProperty(Constants.EXPORT_PACKAGE, "*");
b.setProperty(Constants.IMPORT_PACKAGE, "*;resolution:=optional");
jar = b.build();
} else if (manifest.getMainAttributes().getValue(Constants.BUNDLE_MANIFESTVERSION) == null) {
trace("Not a release 4 bundle, wrapping with manifest as source");
Builder b = new Builder(this);
this.addClose(b);
b.addClasspath(jar);
b.setProperty(Constants.PRIVATE_PACKAGE, "*");
b.mergeManifest(manifest);
String imprts = manifest.getMainAttributes().getValue(Constants.IMPORT_PACKAGE);
if (imprts == null)
imprts = "";
else
imprts += ",";
imprts += "*;resolution=optional";
b.setProperty(Constants.IMPORT_PACKAGE, imprts);
b.setProperty("Bnd-Message", "Wrapped from " + id + "because had incomplete manifest");
jar = b.build();
}
return jar;
}
public String _project(@SuppressWarnings("unused")
String args[]) {
return getBase().getAbsolutePath();
}
/**
* Bump the version of this project. First check the main bnd file. If this
* does not contain a version, check the include files. If they still do not
* contain a version, then check ALL the sub builders. If not, add a version
* to the main bnd file.
*
* @param mask
* the mask for bumping, see {@link Macro#_version(String[])}
* @throws Exception
*/
public void bump(String mask) throws Exception {
String pattern = "(Bundle-Version\\s*(:|=)\\s*)(([0-9]+(\\.[0-9]+(\\.[0-9]+)?)?))";
String replace = "$1${version;" + mask + ";$3}";
try {
// First try our main bnd file
if (replace(getPropertiesFile(), pattern, replace))
return;
trace("no version in bnd.bnd");
// Try the included filed in reverse order (last has highest
// priority)
List<File> included = getIncluded();
if (included != null) {
List<File> copy = new ArrayList<File>(included);
Collections.reverse(copy);
for (File file : copy) {
if (replace(file, pattern, replace)) {
trace("replaced version in file %s", file);
return;
}
}
}
trace("no version in included files");
boolean found = false;
// Replace in all sub builders.
for (Builder sub : getSubBuilders()) {
found |= replace(sub.getPropertiesFile(), pattern, replace);
}
if (!found) {
trace("no version in sub builders, add it to bnd.bnd");
String bndfile = IO.collect(getPropertiesFile());
bndfile += "\n# Added by by bump\nBundle-Version: 0.0.0\n";
IO.store(bndfile, getPropertiesFile());
}
}
finally {
forceRefresh();
}
}
boolean replace(File f, String pattern, String replacement) throws IOException {
final Macro macro = getReplacer();
Sed sed = new Sed(new Replacer() {
public String process(String line) {
return macro.process(line);
}
}, f);
sed.replace(pattern, replacement);
return sed.doIt() > 0;
}
public void bump() throws Exception {
bump(getProperty(BUMPPOLICY, "=+0"));
}
public void action(String command) throws Exception {
Map<String,Action> actions = getActions();
Action a = actions.get(command);
if (a == null)
a = new ReflectAction(command);
before(this, command);
try {
a.execute(this, command);
}
catch (Exception t) {
after(this, command, t);
throw t;
}
}
/**
* Run all before command plugins
*/
void before(@SuppressWarnings("unused")
Project p, String a) {
List<CommandPlugin> testPlugins = getPlugins(CommandPlugin.class);
for (CommandPlugin testPlugin : testPlugins) {
testPlugin.before(this, a);
}
}
/**
* Run all after command plugins
*/
void after(@SuppressWarnings("unused")
Project p, String a, Throwable t) {
List<CommandPlugin> testPlugins = getPlugins(CommandPlugin.class);
for (int i = testPlugins.size() - 1; i >= 0; i--) {
testPlugins.get(i).after(this, a, t);
}
}
public String _findfile(String args[]) {
File f = getFile(args[1]);
List<String> files = new ArrayList<String>();
tree(files, f, "", new Instruction(args[2]));
return join(files);
}
void tree(List<String> list, File current, String path, Instruction instr) {
if (path.length() > 0)
path = path + "/";
String subs[] = current.list();
if (subs != null) {
for (String sub : subs) {
File f = new File(current, sub);
if (f.isFile()) {
if (instr.matches(sub) && !instr.isNegated())
list.add(path + sub);
} else
tree(list, f, path + sub, instr);
}
}
}
public void refreshAll() {
workspace.refresh();
refresh();
}
@SuppressWarnings("unchecked")
public void script(@SuppressWarnings("unused")
String type, String script) throws Exception {
// TODO check tyiping
List<Scripter> scripters = getPlugins(Scripter.class);
if (scripters.isEmpty()) {
msgs.NoScripters_(script);
return;
}
@SuppressWarnings("rawtypes")
Map x = getProperties();
scripters.get(0).eval(x, new StringReader(script));
}
public String _repos(@SuppressWarnings("unused")
String args[]) throws Exception {
List<RepositoryPlugin> repos = getPlugins(RepositoryPlugin.class);
List<String> names = new ArrayList<String>();
for (RepositoryPlugin rp : repos)
names.add(rp.getName());
return join(names, ", ");
}
public String _help(String args[]) throws Exception {
if (args.length == 1)
return "Specify the option or header you want information for";
Syntax syntax = Syntax.HELP.get(args[1]);
if (syntax == null)
return "No help for " + args[1];
String what = null;
if (args.length > 2)
what = args[2];
if (what == null || what.equals("lead"))
return syntax.getLead();
if (what.equals("example"))
return syntax.getExample();
if (what.equals("pattern"))
return syntax.getPattern();
if (what.equals("values"))
return syntax.getValues();
return "Invalid type specified for help: lead, example, pattern, values";
}
/**
* Returns containers for the deliverables of this project. The deliverables
* is the project builder for this project if no -sub is specified.
* Otherwise it contains all the sub bnd files.
*
* @return A collection of containers
* @throws Exception
*/
public Collection<Container> getDeliverables() throws Exception {
List<Container> result = new ArrayList<Container>();
Collection< ? extends Builder> builders = getSubBuilders();
for (Builder builder : builders) {
Container c = new Container(this, builder.getBsn(), builder.getVersion(), Container.TYPE.PROJECT,
getOutputFile(builder.getBsn()), null, null, null);
result.add(c);
}
return result;
}
/**
* Return the builder associated with the give bnd file or null. The bnd.bnd
* file can contain -sub option. This option allows specifying files in the
* same directory that should drive the generation of multiple deliverables.
* This method figures out if the bndFile is actually one of the bnd files
* of a deliverable.
*
* @param bndFile
* A file pointing to a bnd file.
* @return null or the builder for a sub file.
* @throws Exception
*/
public Builder getSubBuilder(File bndFile) throws Exception {
bndFile = bndFile.getCanonicalFile();
// Verify that we are inside the project.
File base = getBase().getCanonicalFile();
if (!bndFile.getAbsolutePath().startsWith(base.getAbsolutePath()))
return null;
Collection< ? extends Builder> builders = getSubBuilders();
for (Builder sub : builders) {
File propertiesFile = sub.getPropertiesFile();
if (propertiesFile != null) {
if (propertiesFile.getCanonicalFile().equals(bndFile)) {
// Found it!
return sub;
}
}
}
return null;
}
/**
* Return a build that maps to the sub file.
*
* @param string
* @throws Exception
*/
public ProjectBuilder getSubBuilder(String string) throws Exception {
Collection< ? extends Builder> builders = getSubBuilders();
for (Builder b : builders) {
if (b.getBsn().equals(string) || b.getBsn().endsWith("." + string))
return (ProjectBuilder) b;
}
return null;
}
/**
* Answer the container associated with a given bsn.
*
* @param bndFile
* A file pointing to a bnd file.
* @return null or the builder for a sub file.
* @throws Exception
*/
public Container getDeliverable(String bsn, @SuppressWarnings("unused")
Map<String,String> attrs) throws Exception {
Collection< ? extends Builder> builders = getSubBuilders();
for (Builder sub : builders) {
if (sub.getBsn().equals(bsn))
return new Container(this, getOutputFile(bsn, sub.getVersion()));
}
return null;
}
/**
* Get a list of the sub builders. A bnd.bnd file can contain the -sub
* option. This will generate multiple deliverables. This method returns the
* builders for each sub file. If no -sub option is present, the list will
* contain a builder for the bnd.bnd file.
*
* @return A list of builders.
* @throws Exception
*/
public Collection< ? extends Builder> getSubBuilders() throws Exception {
return getBuilder(null).getSubBuilders();
}
/**
* Calculate the classpath. We include our own runtime.jar which includes
* the test framework and we include the first of the test frameworks
* specified.
*
* @throws Exception
*/
Collection<File> toFile(Collection<Container> containers) throws Exception {
ArrayList<File> files = new ArrayList<File>();
for (Container container : containers) {
container.contributeFiles(files, this);
}
return files;
}
public Collection<String> getRunVM() {
Parameters hdr = getParameters(RUNVM);
return hdr.keySet();
}
public Collection<String> getRunProgramArgs() {
Parameters hdr = getParameters(RUNPROGRAMARGS);
return hdr.keySet();
}
public Map<String,String> getRunProperties() {
return OSGiHeader.parseProperties(getProperty(RUNPROPERTIES));
}
/**
* Get a launcher.
*
* @return
* @throws Exception
*/
public ProjectLauncher getProjectLauncher() throws Exception {
return getHandler(ProjectLauncher.class, getRunpath(), LAUNCHER_PLUGIN, "biz.aQute.launcher");
}
public ProjectTester getProjectTester() throws Exception {
return getHandler(ProjectTester.class, getTestpath(), TESTER_PLUGIN, "biz.aQute.junit");
}
private <T> T getHandler(Class<T> target, Collection<Container> containers, String header, String defaultHandler)
throws Exception {
Class< ? extends T> handlerClass = target;
// Make sure we find at least one handler, but hope to find an earlier
// one
List<Container> withDefault = Create.list();
withDefault.addAll(containers);
withDefault.addAll(getBundles(Strategy.HIGHEST, defaultHandler, null));
trace("candidates for tester %s", withDefault);
for (Container c : withDefault) {
Manifest manifest = c.getManifest();
if (manifest != null) {
String launcher = manifest.getMainAttributes().getValue(header);
if (launcher != null) {
Class< ? > clz = getClass(launcher, c.getFile());
if (clz != null) {
if (!target.isAssignableFrom(clz)) {
msgs.IncompatibleHandler_For_(launcher, defaultHandler);
} else {
trace("found handler %s from %s", defaultHandler, c);
handlerClass = clz.asSubclass(target);
Constructor< ? extends T> constructor = handlerClass.getConstructor(Project.class);
return constructor.newInstance(this);
}
}
}
}
}
throw new IllegalArgumentException("Default handler for " + header + " not found in " + defaultHandler);
}
/**
* Make this project delay the calculation of the run dependencies. The run
* dependencies calculation can be done in prepare or until the dependencies
* are actually needed.
*/
public void setDelayRunDependencies(boolean x) {
delayRunDependencies = x;
}
/**
* Sets the package version on an exported package
*
* @param packageName
* The package name
* @param version
* The new package version
*/
public void setPackageInfo(String packageName, Version version) {
try {
Version current = getPackageInfoJavaVersion(packageName);
boolean packageInfoJava = false;
if (current != null) {
updatePackageInfoJavaFile(packageName, version);
packageInfoJava = true;
}
if (!packageInfoJava || getPackageInfoFile(packageName).exists()) {
updatePackageInfoFile(packageName, version);
}
}
catch (Exception e) {
msgs.SettingPackageInfoException_(e);
}
}
void updatePackageInfoJavaFile(String packageName, final Version newVersion) throws Exception {
File file = getPackageInfoJavaFile(packageName);
if (!file.exists()) {
return;
}
// If package/classes are copied into the bundle through Private-Package
// etc, there will be no source
if (!file.getParentFile().exists()) {
return;
}
Version oldVersion = getPackageInfo(packageName);
if (newVersion.compareTo(oldVersion) == 0) {
return;
}
Sed sed = new Sed(new Replacer() {
public String process(String line) {
Matcher m = VERSION_ANNOTATION.matcher(line);
if (m.find()) {
return line.substring(0, m.start(3)) + newVersion.toString() + line.substring(m.end(3));
}
return line;
}
}, file);
sed.replace(VERSION_ANNOTATION.pattern(), "$0");
sed.setBackup(false);
sed.doIt();
}
void updatePackageInfoFile(String packageName, Version newVersion) throws Exception {
File file = getPackageInfoFile(packageName);
// If package/classes are copied into the bundle through Private-Package
// etc, there will be no source
if (!file.getParentFile().exists()) {
return;
}
Version oldVersion = getPackageInfoVersion(packageName);
if (oldVersion == null) {
oldVersion = Version.emptyVersion;
}
if (newVersion.compareTo(oldVersion) == 0) {
return;
}
PrintWriter pw = IO.writer(file);
pw.println("version " + newVersion);
pw.flush();
pw.close();
String path = packageName.replace('.', '/') + "/packageinfo";
File binary = IO.getFile(getOutput(), path);
File bp = binary.getParentFile();
if (!bp.exists() && !bp.mkdirs()) {
throw new IOException("Could not create directory " + bp);
}
IO.copy(file, binary);
}
File getPackageInfoFile(String packageName) {
String path = packageName.replace('.', '/') + "/packageinfo";
return IO.getFile(getSrc(), path);
}
File getPackageInfoJavaFile(String packageName) {
String path = packageName.replace('.', '/') + "/package-info.java";
return IO.getFile(getSrc(), path);
}
public Version getPackageInfo(String packageName) throws IOException {
Version version = getPackageInfoJavaVersion(packageName);
if (version != null) {
return version;
}
version = getPackageInfoVersion(packageName);
if (version != null) {
return version;
}
return Version.emptyVersion;
}
Version getPackageInfoVersion(String packageName) throws IOException {
File packageInfoFile = getPackageInfoFile(packageName);
if (!packageInfoFile.exists()) {
return null;
}
BufferedReader reader = IO.reader(packageInfoFile);
try {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.startsWith("version ")) {
return Version.parseVersion(line.substring(8));
}
}
}
finally {
IO.close(reader);
}
return null;
}
Version getPackageInfoJavaVersion(String packageName) throws IOException {
File packageInfoJavaFile = getPackageInfoJavaFile(packageName);
if (!packageInfoJavaFile.exists()) {
return null;
}
BufferedReader reader = null;
reader = IO.reader(packageInfoJavaFile);
try {
String line;
while ((line = reader.readLine()) != null) {
Matcher matcher = VERSION_ANNOTATION.matcher(line);
if (matcher.find()) {
return Version.parseVersion(matcher.group(3));
}
}
}
finally {
IO.close(reader);
}
return null;
}
/**
* bnd maintains a class path that is set by the environment, i.e. bnd is
* not in charge of it.
*/
public void addClasspath(File f) {
if (!f.isFile() && !f.isDirectory()) {
msgs.AddingNonExistentFileToClassPath_(f);
}
Container container = new Container(f, null);
classpath.add(container);
}
public void clearClasspath() {
classpath.clear();
}
public Collection<Container> getClasspath() {
return classpath;
}
/**
* Pack the project (could be a bndrun file) and save it on disk. Report
* errors if they happen.
*/
static List<String> ignore = new ExtList<String>(BUNDLE_SPECIFIC_HEADERS);
public Jar pack(String profile) throws Exception {
Collection< ? extends Builder> subBuilders = getSubBuilders();
if (subBuilders.size() != 1) {
error("Project has multiple bnd files, please select one of the bnd files");
return null;
}
Builder b = subBuilders.iterator().next();
ignore.remove(BUNDLE_SYMBOLICNAME);
ignore.remove(BUNDLE_VERSION);
ignore.add(SERVICE_COMPONENT);
ProjectLauncher launcher = getProjectLauncher();
launcher.getRunProperties().put("profile", profile); // TODO remove
launcher.getRunProperties().put(PROFILE, profile);
Jar jar = launcher.executable();
Manifest m = jar.getManifest();
Attributes main = m.getMainAttributes();
for (String key : getPropertyKeys(true)) {
if (Character.isUpperCase(key.charAt(0)) && !ignore.contains(key)) {
main.putValue(key, getProperty(key));
}
}
if (main.getValue(BUNDLE_SYMBOLICNAME) == null)
main.putValue(BUNDLE_SYMBOLICNAME, b.getBsn());
if (main.getValue(BUNDLE_SYMBOLICNAME) == null)
main.putValue(BUNDLE_SYMBOLICNAME, getName());
if (main.getValue(BUNDLE_VERSION) == null) {
main.putValue(BUNDLE_VERSION, Version.LOWEST.toString());
warning("No version set, uses 0.0.0");
}
jar.setManifest(m);
jar.calcChecksums(new String[] {
"SHA1", "MD5"
});
return jar;
}
/**
* Do a baseline for this project
*
* @throws Exception
*/
public void baseline() throws Exception {
ProjectBuilder b = getBuilder(null);
for (Builder pb : b.getSubBuilders()) {
ProjectBuilder ppb = (ProjectBuilder) pb;
Jar build = ppb.build();
getInfo(ppb);
}
getInfo(b);
}
/**
* Method to verify that the paths are correct, ie no missing dependencies
*
* @param test
* for test cases, also adds -testpath
* @throws Exception
*/
public void verifyDependencies(boolean test) throws Exception {
verifyDependencies(RUNBUNDLES, getRunbundles());
verifyDependencies(RUNPATH, getRunpath());
if (test)
verifyDependencies(TESTPATH, getTestpath());
verifyDependencies(BUILDPATH, getBuildpath());
}
private void verifyDependencies(String title, Collection<Container> path) throws Exception {
List<String> msgs = new ArrayList<String>();
for (Container c : new ArrayList<Container>(path)) {
for (Container cc : c.getMembers()) {
if (cc.getError() != null)
msgs.add(cc + " - " + cc.getError());
else if (!cc.getFile().isFile() && !cc.getFile().equals(cc.getProject().getOutput())
&& !cc.getFile().equals(cc.getProject().getTestOutput()))
msgs.add(cc + " file does not exists: " + cc.getFile());
}
}
if (msgs.isEmpty())
return;
error("%s: has errors: %s", title, Strings.join(msgs));
}
/**
* Report detailed info from this project
*
* @throws Exception
*/
public void report(Map<String,Object> table) throws Exception {
super.report(table);
report(table, true);
}
protected void report(Map<String,Object> table, boolean isProject) throws Exception {
if (isProject) {
table.put("Target", getTarget());
table.put("Source", getSrc());
table.put("Output", getOutput());
File[] buildFiles = getBuildFiles();
if (buildFiles != null)
table.put("BuildFiles", Arrays.asList(buildFiles));
table.put("Classpath", getClasspath());
table.put("Actions", getActions());
table.put("AllSourcePath", getAllsourcepath());
table.put("BootClassPath", getBootclasspath());
table.put("BuildPath", getBuildpath());
table.put("Deliverables", getDeliverables());
table.put("DependsOn", getDependson());
table.put("SourcePath", getSourcePath());
}
table.put("RunPath", getRunpath());
table.put("TestPath", getTestpath());
table.put("RunProgramArgs", getRunProgramArgs());
table.put("RunVM", getRunVM());
table.put("Runfw", getRunFw());
table.put("Runbundles", getRunbundles());
}
// TODO test format parametsr
public void compile(boolean test) throws Exception {
Command javac = getCommonJavac(false);
javac.add("-d", getOutput().getAbsolutePath());
StringBuilder buildpath = new StringBuilder();
String buildpathDel = "";
Collection<Container> bp = Container.flatten(getBuildpath());
trace("buildpath %s", getBuildpath());
for (Container c : bp) {
buildpath.append(buildpathDel).append(c.getFile().getAbsolutePath());
buildpathDel = File.pathSeparator;
}
if (buildpath.length() != 0) {
javac.add("-classpath", buildpath.toString());
}
List<File> sp = new ArrayList<File>(getAllsourcepath());
StringBuilder sourcepath = new StringBuilder();
String sourcepathDel = "";
for (File sourceDir : sp) {
sourcepath.append(sourcepathDel).append(sourceDir.getAbsolutePath());
sourcepathDel = File.pathSeparator;
}
javac.add("-sourcepath", sourcepath.toString());
Glob javaFiles = new Glob("*.java");
List<File> files = javaFiles.getFiles(getSrc(), true, false);
for (File file : files) {
javac.add(file.getAbsolutePath());
}
if (files.isEmpty()) {
trace("Not compiled, no source files");
} else
compile(javac, "src");
if (test) {
javac = getCommonJavac(true);
javac.add("-d", getTestOutput().getAbsolutePath());
Collection<Container> tp = Container.flatten(getTestpath());
for (Container c : tp) {
buildpath.append(buildpathDel).append(c.getFile().getAbsolutePath());
buildpathDel = File.pathSeparator;
}
if (buildpath.length() != 0) {
javac.add("-classpath", buildpath.toString());
}
sourcepath.append(sourcepathDel).append(getTestSrc().getAbsolutePath());
javac.add("-sourcepath", sourcepath.toString());
javaFiles.getFiles(getTestSrc(), files, true, false);
for (File file : files) {
javac.add(file.getAbsolutePath());
}
if (files.isEmpty()) {
trace("Not compiled for test, no test src files");
} else
compile(javac, "test");
}
}
private void compile(Command javac, String what) throws Exception {
trace("compile %s %s", what, javac);
StringBuilder stdout = new StringBuilder();
StringBuilder stderr = new StringBuilder();
int n = javac.execute(stdout, stderr);
trace("javac stdout: ", stdout);
trace("javac stderr: ", stderr);
if (n != 0) {
error("javac failed %s", stderr);
}
}
private Command getCommonJavac(boolean test) throws Exception {
Command javac = new Command();
javac.add(getProperty("javac", "javac"));
String target = getProperty("javac.target", "1.6");
String source = getProperty("javac.source", "1.6");
String debug = getProperty("javac.debug");
if ("on".equalsIgnoreCase(debug) || "true".equalsIgnoreCase(debug))
debug = "vars,source,lines";
Parameters options = new Parameters(getProperty("java.options"));
boolean deprecation = isTrue(getProperty("java.deprecation"));
javac.add("-encoding", "UTF-8");
javac.add("-source", source);
javac.add("-target", target);
if (deprecation)
javac.add("-deprecation");
if (test || debug == null) {
javac.add("-g:source,lines,vars" + debug);
} else {
javac.add("-g:" + debug);
}
for (String option : options.keySet())
javac.add(option);
StringBuilder bootclasspath = new StringBuilder();
String bootclasspathDel = "-Xbootclasspath/p:";
Collection<Container> bcp = Container.flatten(getBootclasspath());
for (Container c : bcp) {
bootclasspath.append(bootclasspathDel).append(c.getFile().getAbsolutePath());
bootclasspathDel = File.pathSeparator;
}
if (bootclasspath.length() != 0) {
javac.add(bootclasspath.toString());
}
return javac;
}
}
| true | true |
public synchronized void prepare() throws Exception {
if (!isValid()) {
warning("Invalid project attempts to prepare: %s", this);
return;
}
if (inPrepare)
throw new CircularDependencyException(trail.toString() + "," + this);
trail.add(this);
try {
if (!preparedPaths) {
inPrepare = true;
try {
dependson.clear();
buildpath.clear();
sourcepath.clear();
allsourcepath.clear();
bootclasspath.clear();
testpath.clear();
runpath.clear();
runbundles.clear();
// We use a builder to construct all the properties for
// use.
setProperty("basedir", getBase().getAbsolutePath());
// If a bnd.bnd file exists, we read it.
// Otherwise, we just do the build properties.
if (!getPropertiesFile().isFile() && new File(getBase(), ".classpath").isFile()) {
// Get our Eclipse info, we might depend on other
// projects
// though ideally this should become empty and void
doEclipseClasspath();
}
// Calculate our source directory
File src = getSrc();
if (src.isDirectory()) {
sourcepath.add(src);
allsourcepath.add(src);
} else
sourcepath.add(getBase());
// Set default bin directory
output = getSrcOutput().getAbsoluteFile();
if (!output.exists()) {
if (!output.mkdirs()) {
throw new IOException("Could not create directory " + output);
}
getWorkspace().changedFile(output);
}
if (!output.isDirectory())
msgs.NoOutputDirectory_(output);
else {
Container c = new Container(this, output);
if (!buildpath.contains(c))
buildpath.add(c);
}
// Where we store all our generated stuff.
target = getTarget0();
// Where the launched OSGi framework stores stuff
String runStorageStr = getProperty(Constants.RUNSTORAGE);
runstorage = runStorageStr != null ? getFile(runStorageStr) : null;
// We might have some other projects we want build
// before we do anything, but these projects are not in
// our path. The -dependson allows you to build them before.
// The values are possibly negated globbing patterns.
// dependencies.add( getWorkspace().getProject("cnf"));
String dp = getProperty(Constants.DEPENDSON);
Set<String> requiredProjectNames = new LinkedHashSet<String>(new Parameters(dp).keySet());
// Allow DependencyConstributors to modify
// requiredProjectNames
List<DependencyContributor> dcs = getPlugins(DependencyContributor.class);
for (DependencyContributor dc : dcs)
dc.addDependencies(this, requiredProjectNames);
Instructions is = new Instructions(requiredProjectNames);
Set<Instruction> unused = new HashSet<Instruction>();
Collection<Project> projects = getWorkspace().getAllProjects();
Collection<Project> dependencies = is.select(projects, unused, false);
for (Instruction u : unused)
msgs.MissingDependson_(u.getInput());
// We have two paths that consists of repo files, projects,
// or some other stuff. The doPath routine adds them to the
// path and extracts the projects so we can build them
// before.
doPath(buildpath, dependencies, parseBuildpath(), bootclasspath, false, BUILDPATH);
doPath(testpath, dependencies, parseTestpath(), bootclasspath, false, TESTPATH);
if (!delayRunDependencies) {
doPath(runfw, dependencies, parseRunFw(), null, false, RUNFW);
doPath(runpath, dependencies, parseRunpath(), null, false, RUNPATH);
doPath(runbundles, dependencies, parseRunbundles(), null, true, RUNBUNDLES);
}
// We now know all dependent projects. But we also depend
// on whatever those projects depend on. This creates an
// ordered list without any duplicates. This of course
// assumes
// that there is no circularity. However, this is checked
// by the inPrepare flag, will throw an exception if we
// are circular.
Set<Project> done = new HashSet<Project>();
done.add(this);
allsourcepath.addAll(sourcepath);
for (Project project : dependencies)
project.traverse(dependson, done);
for (Project project : dependson) {
allsourcepath.addAll(project.getSourcePath());
}
if (isOk())
preparedPaths = true;
}
finally {
inPrepare = false;
}
}
}
finally {
trail.remove(this);
}
}
|
public synchronized void prepare() throws Exception {
if (!isValid()) {
warning("Invalid project attempts to prepare: %s", this);
return;
}
if (inPrepare)
throw new CircularDependencyException(trail.toString() + "," + this);
trail.add(this);
try {
if (!preparedPaths) {
inPrepare = true;
try {
dependson.clear();
buildpath.clear();
sourcepath.clear();
allsourcepath.clear();
bootclasspath.clear();
testpath.clear();
runpath.clear();
runbundles.clear();
// We use a builder to construct all the properties for
// use.
setProperty("basedir", getBase().getAbsolutePath());
// If a bnd.bnd file exists, we read it.
// Otherwise, we just do the build properties.
if (!getPropertiesFile().isFile() && new File(getBase(), ".classpath").isFile()) {
// Get our Eclipse info, we might depend on other
// projects
// though ideally this should become empty and void
doEclipseClasspath();
}
// Calculate our source directory
File src = getSrc();
if (src.isDirectory()) {
sourcepath.add(src);
allsourcepath.add(src);
} else
sourcepath.add(getBase());
// Set default bin directory
output = getSrcOutput().getAbsoluteFile();
if (!output.exists()) {
if (!output.mkdirs()) {
throw new IOException("Could not create directory " + output);
}
getWorkspace().changedFile(output);
}
if (!output.isDirectory())
msgs.NoOutputDirectory_(output);
else {
Container c = new Container(this, output);
if (!buildpath.contains(c))
buildpath.add(c);
}
// Where we store all our generated stuff.
target = getTarget0();
// Where the launched OSGi framework stores stuff
String runStorageStr = getProperty(Constants.RUNSTORAGE);
runstorage = runStorageStr != null ? getFile(runStorageStr) : null;
// We might have some other projects we want build
// before we do anything, but these projects are not in
// our path. The -dependson allows you to build them before.
// The values are possibly negated globbing patterns.
// dependencies.add( getWorkspace().getProject("cnf"));
String dp = getProperty(Constants.DEPENDSON);
Set<String> requiredProjectNames = new LinkedHashSet<String>(new Parameters(dp).keySet());
// Allow DependencyConstributors to modify
// requiredProjectNames
List<DependencyContributor> dcs = getPlugins(DependencyContributor.class);
for (DependencyContributor dc : dcs)
dc.addDependencies(this, requiredProjectNames);
Instructions is = new Instructions(requiredProjectNames);
Set<Instruction> unused = new HashSet<Instruction>();
Collection<Project> projects = getWorkspace().getAllProjects();
Collection<Project> dependencies = is.select(projects, unused, false);
for (Instruction u : unused)
msgs.MissingDependson_(u.getInput());
// We have two paths that consists of repo files, projects,
// or some other stuff. The doPath routine adds them to the
// path and extracts the projects so we can build them
// before.
doPath(buildpath, dependencies, parseBuildpath(), bootclasspath, false, BUILDPATH);
doPath(testpath, dependencies, parseTestpath(), bootclasspath, false, TESTPATH);
if (!delayRunDependencies) {
doPath(runfw, dependencies, parseRunFw(), null, false, RUNFW);
doPath(runpath, dependencies, parseRunpath(), null, false, RUNPATH);
doPath(runbundles, dependencies, parseRunbundles(), null, true, RUNBUNDLES);
}
// We now know all dependent projects. But we also depend
// on whatever those projects depend on. This creates an
// ordered list without any duplicates. This of course
// assumes
// that there is no circularity. However, this is checked
// by the inPrepare flag, will throw an exception if we
// are circular.
Set<Project> done = new HashSet<Project>();
done.add(this);
allsourcepath.addAll(sourcepath);
for (Project project : dependencies)
project.traverse(dependson, done);
for (Project project : dependson) {
allsourcepath.addAll(project.getSourcePath());
}
//[cs] Testing this commented out. If bad issues, never setting this to true means that
// TONS of extra preparing is done over and over again on the same projects.
//if (isOk())
preparedPaths = true;
}
finally {
inPrepare = false;
}
}
}
finally {
trail.remove(this);
}
}
|
diff --git a/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JBIDE788Test.java b/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JBIDE788Test.java
index 4a55c8702..0b4e24355 100644
--- a/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JBIDE788Test.java
+++ b/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JBIDE788Test.java
@@ -1,361 +1,361 @@
/*******************************************************************************
* Copyright (c) 2007 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.jsf.vpe.jsf.test.jbide;
import java.io.IOException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.wst.sse.ui.StructuredTextViewerConfiguration;
import org.jboss.tools.jsf.vpe.jsf.test.JsfAllTests;
import org.jboss.tools.jst.jsp.contentassist.AutoContentAssistantProposal;
import org.jboss.tools.jst.jsp.jspeditor.JSPMultiPageEditor;
import org.jboss.tools.jst.jsp.jspeditor.JSPTextEditor;
import org.jboss.tools.vpe.ui.test.TestUtil;
import org.jboss.tools.vpe.ui.test.VpeTest;
/**
* @author Max Areshkau
*
* JUnit test for http://jira.jboss.com/jira/browse/JBIDE-788
*/
public class JBIDE788Test extends VpeTest {
private static final String CA_NAME = "org.eclipse.wst.html.HTML_DEFAULT"; //$NON-NLS-1$
private static final String REQUIRED_PROPOSAL = "prompt_message"; //$NON-NLS-1$
public JBIDE788Test(String name) {
super(name);
}
/**
* Tests inner nodes include URI
*
* @throws Throwable
*/
public void testCAforIncludeTaglibInInenerNodes() throws Throwable {
// wait
TestUtil.waitForJobs();
// set exception
setException(null);
// Tests CA
checkOfCAByStartString(CA_NAME, "JBIDE/788/TestChangeUriInInnerNodes.xhtml","s:validateFormat",11,2); //$NON-NLS-1$//$NON-NLS-2$
checkOfCAByStartString(CA_NAME, "JBIDE/788/TestChangeUriInInnerNodes.xhtml","rich:validateA", 14,14); //$NON-NLS-1$ //$NON-NLS-2$
checkOfCAByStartString(CA_NAME, "JBIDE/788/TestChangeUriInInnerNodes.xhtml","c:otherwi",18,6); //$NON-NLS-1$//$NON-NLS-2$
// check exception
if (getException() != null) {
throw getException();
}
}
//added by Maksim Areshkau, as test case for JBIE-6131.
//source code templates should be in ca proposals.
public void testCAforSourceCodeTemplatesProposals() throws Throwable {
// wait
TestUtil.waitForJobs();
// set exception
setException(null);
ICompletionProposal[] results = checkOfCAByStartString(CA_NAME, "JBIDE/6131/6131test.xhtml","Common",1,1,false); //$NON-NLS-1$ //$NON-NLS-2$
boolean proposalExists=false;
for (ICompletionProposal completionProposal : results) {
String displayString = ((ICompletionProposal) completionProposal).getDisplayString();
if(displayString.contains("Common Facelet Page")) { //$NON-NLS-1$
proposalExists = true;
break;
}
}
assertTrue("Common " + " should be in proposals", proposalExists);
// check exception
if (getException() != null) {
throw getException();
}
}
/**
* Tests Path proposals of CA
*/
public void testCAPathProposals() throws Throwable {
// wait
TestUtil.waitForJobs();
// set exception
setException(null);
// Tests CA
ICompletionProposal[] results = checkOfCAByStartString(CA_NAME, "JBIDE/788/testCAMessageBundlesAndEL.xhtml","",11,31,false); //$NON-NLS-1$ //$NON-NLS-2$
assertNotNull(results);
assertTrue("The length should be more than 0",results.length>0); //$NON-NLS-1$
boolean proposalExists=false;
for (ICompletionProposal completionProposal : results) {
String displayString = ((ICompletionProposal) completionProposal).getDisplayString();
if(displayString.contains(REQUIRED_PROPOSAL)) {
proposalExists = true;
break;
}
}
assertTrue(REQUIRED_PROPOSAL + " should be in proposals", proposalExists);
proposalExists=false;
results = checkOfCAByStartString(CA_NAME, "JBIDE/788/testCAPathProposals.xhtml","",11,41,false); //$NON-NLS-1$//$NON-NLS-2$
assertNotNull(results);
for(ICompletionProposal completionProposal : results) {
String displayString = ((ICompletionProposal) completionProposal).getDisplayString();
if(displayString.contains("templates")) { //$NON-NLS-1$ //$NON-NLS-2$
proposalExists=true;
}
}
assertEquals("path proposala should be in proposals",true, proposalExists);
// check exception
if (getException() != null) {
throw getException();
}
}
/**
* Tests CA for proposals for JSFC
*
* @throws Throwable
*/
public void testCAforForJSFCProposals() throws Throwable {
// wait
TestUtil.waitForJobs();
// set exception
setException(null);
// Tests CA
ICompletionProposal[] results =checkOfCAByStartString(CA_NAME, "JBIDE/788/testCAMessageBundlesAndEL.xhtml","",21,58); //$NON-NLS-1$//$NON-NLS-2$
assertNotNull(results);
assertTrue(results.length>=2);
for(ICompletionProposal completionProposal : results) {
if(completionProposal instanceof AutoContentAssistantProposal ) {
String displayString = ((ICompletionProposal) completionProposal).getDisplayString();
if(!(displayString.contains("h:command") || displayString.contains("New JSF EL"))) { //$NON-NLS-1$ //$NON-NLS-2$
fail("String doesn't matches"); //$NON-NLS-1$
}
}
}
// check exception
if (getException() != null) {
throw getException();
}
}
/**
* Tests CA on html files
*
* @throws Throwable
*/
public void testCAforHtmlFiles() throws Throwable {
// wait
TestUtil.waitForJobs();
// set exception
setException(null);
// Tests CA
ICompletionProposal[] results =checkOfCAByStartString(CA_NAME, "JBIDE/788/testCAforHtml.html", "", 5, 13,false); //$NON-NLS-1$//$NON-NLS-2$
assertNotNull(results);
assertTrue("The lenft should be more than 0",results.length>0); //$NON-NLS-1$
boolean isMatches=true;
for (ICompletionProposal completionProposal : results) {
if(completionProposal instanceof AutoContentAssistantProposal ) {
String displayString = ((ICompletionProposal) completionProposal).getDisplayString();
if(!displayString.startsWith("ta")) { //$NON-NLS-1$
isMatches=false;
}
}
}
assertTrue("Proposals doesn't match to entered string",isMatches); //$NON-NLS-1$
// check exception
if (getException() != null) {
throw getException();
}
}
/**
* Tests CA on jsp files
*
* @throws Throwable
*/
public void testCAforJSPFiles() throws Throwable {
// wait
TestUtil.waitForJobs();
// set exception
setException(null);
// Tests CA
// cursor will set after "outputText" tag
ICompletionProposal[] results = checkOfCAByStartString(CA_NAME, "JBIDE/788/testCAforJSP.jsp", "h:outp",26,14,false); //$NON-NLS-1$ //$NON-NLS-2$
for (ICompletionProposal completionProposal : results) {
String displayString = ((ICompletionProposal) completionProposal).getDisplayString();
if(completionProposal instanceof AutoContentAssistantProposal) {
assertTrue(displayString.startsWith("h:outp")) ; //$NON-NLS-1$
}
}
// check exception
if (getException() != null) {
throw getException();
}
}
/**
* Tests CA on jsp files
*
* @throws Throwable
*/
public void testCAforXHTMLFiles() throws Throwable {
// wait
TestUtil.waitForJobs();
// set exception
setException(null);
// cursor will set after "<" simbol
checkOfCAByStartString(CA_NAME, "JBIDE/788/testCAforXHTML.xhtml", "c", //$NON-NLS-1$ //$NON-NLS-2$
15,12);
// cursor will set after "outputText" tag
checkOfCAByStartString(CA_NAME, "JBIDE/788/testCAforXHTML.xhtml", "s", //$NON-NLS-1$//$NON-NLS-2$
19,43);
// check exception
if (getException() != null) {
throw getException();
}
}
/**
*
* @param caName
* @param testPagePath
* @param partOfString
* @param lineIndex
* @param linePosition
* @return
* @throws CoreException
* @throws IOException
*/
private ICompletionProposal[] checkOfCAByStartString(String caName, String testPagePath,
String partOfString, int lineIndex, int linePosition)
throws CoreException, IOException {
return this.checkOfCAByStartString(caName, testPagePath, partOfString, lineIndex, linePosition,true);
}
/**
*
* @param caName
* @param testPagePath
* @param partOfString
* @param lineIndex
* @param linePosition
* @param isCheck
* @return
* @throws CoreException
* @throws IOException
*/
private ICompletionProposal[] checkOfCAByStartString(String caName, String testPagePath,
String partOfString, int lineIndex, int linePosition,boolean isCheck) throws CoreException, IOException {
// get test page path
IFile file = (IFile) TestUtil.getComponentPath(testPagePath,
JsfAllTests.IMPORT_PROJECT_NAME);
assertNotNull("Could not open specified file. componentPage = " + testPagePath
+ ";projectName = " + JsfAllTests.IMPORT_PROJECT_NAME, file);//$NON-NLS-1$
IEditorInput input = new FileEditorInput(file);
assertNotNull("Editor input is null", input); //$NON-NLS-1$
// open and get editor
ICompletionProposal[] results;
try {
JSPMultiPageEditor part = openEditor(input);
int position = TestUtil.getLinePositionOffcet(part.getSourceEditor().getTextViewer(), lineIndex, linePosition);
// insert string
part.getSourceEditor().getTextViewer().getTextWidget()
.replaceTextRange(position, 0, partOfString);
int newPosition = position + partOfString.length();
// sets cursor position
part.getSourceEditor().getTextViewer().getTextWidget().setCaretOffset(
newPosition);
TestUtil.waitForJobs();
TestUtil.delay(1000);
SourceViewerConfiguration sourceViewerConfiguration = ((JSPTextEditor) part
.getSourceEditor()).getSourceViewerConfigurationForTest();
// errase errors which can be on start of editor(for example xuklunner
// not found)
setException(null);
StructuredTextViewerConfiguration stvc = (StructuredTextViewerConfiguration) sourceViewerConfiguration;
IContentAssistant iContentAssistant = stvc
.getContentAssistant((ISourceViewer) part.getSourceEditor()
.getAdapter(ISourceViewer.class));
//this method should be called for correct initialization of CA
iContentAssistant.showPossibleCompletions();
assertNotNull(iContentAssistant);
IContentAssistProcessor iContentAssistProcessor = iContentAssistant
.getContentAssistProcessor(caName);
assertNotNull(iContentAssistProcessor);
results = iContentAssistProcessor
.computeCompletionProposals(part.getSourceEditor()
.getTextViewer(), newPosition);
// remove inserted string
part.getSourceEditor().getTextViewer().getTextWidget()
.replaceTextRange(position, partOfString.length(), ""); //$NON-NLS-1$
assertNotNull(results);
- assertTrue("Number of ca proposals shouldn't be a null",results.length>0); //$NON-NLS-1$
+ assertTrue("Number of ca proposals shouldn't be a 0",results.length>0); //$NON-NLS-1$
if (isCheck) {
for (int i = 0; i < results.length; i++) {
if(results[i] instanceof AutoContentAssistantProposal ) {
String displayString = ((ICompletionProposal) results[i]).getDisplayString();
// Fixed due to satisfy the changes performed by fix for JBIDE-4877
// The proposal is valid if:
// - the display string starts with the mask specified
// - the tag name part (without a prefix and ":"-character) starts with the mask specified
String tagNamePart = displayString.indexOf(":") == -1 ?
displayString :
displayString.substring(displayString.indexOf(":") + 1);
assertNotNull(displayString);
assertEquals(true, displayString.startsWith(partOfString) || tagNamePart.startsWith(partOfString));
}
}
}
} finally {
closeEditors();
TestUtil.delay(1000L);
}
return results;
}
}
| true | true |
private ICompletionProposal[] checkOfCAByStartString(String caName, String testPagePath,
String partOfString, int lineIndex, int linePosition,boolean isCheck) throws CoreException, IOException {
// get test page path
IFile file = (IFile) TestUtil.getComponentPath(testPagePath,
JsfAllTests.IMPORT_PROJECT_NAME);
assertNotNull("Could not open specified file. componentPage = " + testPagePath
+ ";projectName = " + JsfAllTests.IMPORT_PROJECT_NAME, file);//$NON-NLS-1$
IEditorInput input = new FileEditorInput(file);
assertNotNull("Editor input is null", input); //$NON-NLS-1$
// open and get editor
ICompletionProposal[] results;
try {
JSPMultiPageEditor part = openEditor(input);
int position = TestUtil.getLinePositionOffcet(part.getSourceEditor().getTextViewer(), lineIndex, linePosition);
// insert string
part.getSourceEditor().getTextViewer().getTextWidget()
.replaceTextRange(position, 0, partOfString);
int newPosition = position + partOfString.length();
// sets cursor position
part.getSourceEditor().getTextViewer().getTextWidget().setCaretOffset(
newPosition);
TestUtil.waitForJobs();
TestUtil.delay(1000);
SourceViewerConfiguration sourceViewerConfiguration = ((JSPTextEditor) part
.getSourceEditor()).getSourceViewerConfigurationForTest();
// errase errors which can be on start of editor(for example xuklunner
// not found)
setException(null);
StructuredTextViewerConfiguration stvc = (StructuredTextViewerConfiguration) sourceViewerConfiguration;
IContentAssistant iContentAssistant = stvc
.getContentAssistant((ISourceViewer) part.getSourceEditor()
.getAdapter(ISourceViewer.class));
//this method should be called for correct initialization of CA
iContentAssistant.showPossibleCompletions();
assertNotNull(iContentAssistant);
IContentAssistProcessor iContentAssistProcessor = iContentAssistant
.getContentAssistProcessor(caName);
assertNotNull(iContentAssistProcessor);
results = iContentAssistProcessor
.computeCompletionProposals(part.getSourceEditor()
.getTextViewer(), newPosition);
// remove inserted string
part.getSourceEditor().getTextViewer().getTextWidget()
.replaceTextRange(position, partOfString.length(), ""); //$NON-NLS-1$
assertNotNull(results);
assertTrue("Number of ca proposals shouldn't be a null",results.length>0); //$NON-NLS-1$
if (isCheck) {
for (int i = 0; i < results.length; i++) {
if(results[i] instanceof AutoContentAssistantProposal ) {
String displayString = ((ICompletionProposal) results[i]).getDisplayString();
// Fixed due to satisfy the changes performed by fix for JBIDE-4877
// The proposal is valid if:
// - the display string starts with the mask specified
// - the tag name part (without a prefix and ":"-character) starts with the mask specified
String tagNamePart = displayString.indexOf(":") == -1 ?
displayString :
displayString.substring(displayString.indexOf(":") + 1);
assertNotNull(displayString);
assertEquals(true, displayString.startsWith(partOfString) || tagNamePart.startsWith(partOfString));
}
}
}
} finally {
closeEditors();
TestUtil.delay(1000L);
}
return results;
}
|
private ICompletionProposal[] checkOfCAByStartString(String caName, String testPagePath,
String partOfString, int lineIndex, int linePosition,boolean isCheck) throws CoreException, IOException {
// get test page path
IFile file = (IFile) TestUtil.getComponentPath(testPagePath,
JsfAllTests.IMPORT_PROJECT_NAME);
assertNotNull("Could not open specified file. componentPage = " + testPagePath
+ ";projectName = " + JsfAllTests.IMPORT_PROJECT_NAME, file);//$NON-NLS-1$
IEditorInput input = new FileEditorInput(file);
assertNotNull("Editor input is null", input); //$NON-NLS-1$
// open and get editor
ICompletionProposal[] results;
try {
JSPMultiPageEditor part = openEditor(input);
int position = TestUtil.getLinePositionOffcet(part.getSourceEditor().getTextViewer(), lineIndex, linePosition);
// insert string
part.getSourceEditor().getTextViewer().getTextWidget()
.replaceTextRange(position, 0, partOfString);
int newPosition = position + partOfString.length();
// sets cursor position
part.getSourceEditor().getTextViewer().getTextWidget().setCaretOffset(
newPosition);
TestUtil.waitForJobs();
TestUtil.delay(1000);
SourceViewerConfiguration sourceViewerConfiguration = ((JSPTextEditor) part
.getSourceEditor()).getSourceViewerConfigurationForTest();
// errase errors which can be on start of editor(for example xuklunner
// not found)
setException(null);
StructuredTextViewerConfiguration stvc = (StructuredTextViewerConfiguration) sourceViewerConfiguration;
IContentAssistant iContentAssistant = stvc
.getContentAssistant((ISourceViewer) part.getSourceEditor()
.getAdapter(ISourceViewer.class));
//this method should be called for correct initialization of CA
iContentAssistant.showPossibleCompletions();
assertNotNull(iContentAssistant);
IContentAssistProcessor iContentAssistProcessor = iContentAssistant
.getContentAssistProcessor(caName);
assertNotNull(iContentAssistProcessor);
results = iContentAssistProcessor
.computeCompletionProposals(part.getSourceEditor()
.getTextViewer(), newPosition);
// remove inserted string
part.getSourceEditor().getTextViewer().getTextWidget()
.replaceTextRange(position, partOfString.length(), ""); //$NON-NLS-1$
assertNotNull(results);
assertTrue("Number of ca proposals shouldn't be a 0",results.length>0); //$NON-NLS-1$
if (isCheck) {
for (int i = 0; i < results.length; i++) {
if(results[i] instanceof AutoContentAssistantProposal ) {
String displayString = ((ICompletionProposal) results[i]).getDisplayString();
// Fixed due to satisfy the changes performed by fix for JBIDE-4877
// The proposal is valid if:
// - the display string starts with the mask specified
// - the tag name part (without a prefix and ":"-character) starts with the mask specified
String tagNamePart = displayString.indexOf(":") == -1 ?
displayString :
displayString.substring(displayString.indexOf(":") + 1);
assertNotNull(displayString);
assertEquals(true, displayString.startsWith(partOfString) || tagNamePart.startsWith(partOfString));
}
}
}
} finally {
closeEditors();
TestUtil.delay(1000L);
}
return results;
}
|
diff --git a/src/simciv/builds/FarmLand.java b/src/simciv/builds/FarmLand.java
index a05f340..344bc32 100644
--- a/src/simciv/builds/FarmLand.java
+++ b/src/simciv/builds/FarmLand.java
@@ -1,185 +1,185 @@
package simciv.builds;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.state.StateBasedGame;
import simciv.Cheats;
import simciv.Game;
import simciv.MapGrid;
import simciv.Resource;
import simciv.ResourceSlot;
import simciv.Map;
import simciv.content.Content;
import simciv.units.Conveyer;
/**
* Farmlands are used to raise one type of plant.
* It will grow slowly (level) until it reaches the max level.
* At max level, the land can be farmed.
* @author Marc
*
*/
public class FarmLand extends Workplace
{
private static final long serialVersionUID = 1L;
private static BuildProperties properties;
private static byte MIN_LEVEL = 0;
private static byte MAX_LEVEL = 7;
private static byte ROTTEN_LEVEL = 8;
private byte cropsLevel;
private transient int ticksPerLevel; // how many ticks are needed to increase crops level?
private int ticksBeforeNextLevel; // how many ticks remains before the next level?
static
{
properties = new BuildProperties("Farmland");
properties
.setUnitsCapacity(5).setSize(3, 3, 0).setCost(10)
.setCategory(BuildCategory.FOOD)
.setRepeatable(true);
}
public FarmLand(Map m)
{
super(m);
ticksPerLevel = secondsToTicks(60);
ticksBeforeNextLevel = ticksPerLevel;
cropsLevel = MIN_LEVEL;
state = Build.STATE_NORMAL;
}
@Override
public void tick()
{
super.tick();
if(Cheats.isFastFarmlandGrow() && ticksBeforeNextLevel > secondsToTicks(1))
ticksBeforeNextLevel = secondsToTicks(1);
// Crops are growing
ticksBeforeNextLevel--;
if(ticksBeforeNextLevel <= 0)
{
onLevelUp();
ticksBeforeNextLevel = ticksPerLevel;
}
}
@Override
protected void tickSolidness()
{
// No solidness
}
private void onLevelUp()
{
if(state == Build.STATE_ACTIVE)
{
if(cropsLevel == ROTTEN_LEVEL)
cropsLevel = 0; // The field is cleaned up
else if(cropsLevel != MAX_LEVEL)
cropsLevel++; // Crops are growing normally
else
harvest();
}
else if(cropsLevel != 0)
cropsLevel = ROTTEN_LEVEL; // Not enough employees to take care of the field...
}
private void harvest()
{
if(cropsLevel != MAX_LEVEL)
return;
int harvestResult = (int) (50 + 25.f * Math.random());
Conveyer conveyers[] = new Conveyer[1];
conveyers[0] = new Conveyer(mapRef, this);
conveyers[0].addResourceCarriage(new ResourceSlot(Resource.WHEAT, harvestResult));
addAndSpawnUnitsAround(conveyers);
cropsLevel = 0; // The field is cleaned up
}
@Override
public void renderBuild(GameContainer gc, StateBasedGame game, Graphics gfx)
{
// Soil
if(state == Build.STATE_NORMAL || needEmployees())
gfx.drawImage(Content.sprites.buildFarmland.getSprite(0, 0), 0, 0);
else
gfx.drawImage(Content.sprites.buildFarmland.getSprite(1, 0), 0, 0);
// Crops
if(state == Build.STATE_ACTIVE || cropsLevel != 0)
{
for(int j = 0; j < 3; j++)
{
for(int i = 0; i < 3; i++)
{
if(cropsLevel != ROTTEN_LEVEL)
{
gfx.drawImage(
Content.sprites.buildFarmlandCrops.getSprite(cropsLevel, 0),
i * Game.tilesSize,
j * Game.tilesSize);
}
else
gfx.drawImage(
- Content.sprites.buildFarmlandCrops,
+ Content.sprites.buildFarmlandRottenCrops,
i * Game.tilesSize,
j * Game.tilesSize);
}
}
}
}
@Override
public BuildProperties getProperties()
{
return properties;
}
@Override
public int getProductionProgress()
{
if(cropsLevel == ROTTEN_LEVEL)
return 0;
return (int) (100.f * ((cropsLevel + 1.f - (float)ticksBeforeNextLevel / ticksPerLevel) / (MAX_LEVEL+1)));
}
@Override
protected int getTickTime()
{
return 500; // 1/2 second
}
@Override
public boolean canBePlaced(MapGrid map, int x, int y)
{
return super.canBePlaced(map, x, y) && map.isArable(x, y, getWidth(), getHeight());
}
@Override
protected void onActivityStart()
{
}
@Override
protected void onActivityStop()
{
}
@Override
protected void tickActivity()
{
}
}
| true | true |
public void renderBuild(GameContainer gc, StateBasedGame game, Graphics gfx)
{
// Soil
if(state == Build.STATE_NORMAL || needEmployees())
gfx.drawImage(Content.sprites.buildFarmland.getSprite(0, 0), 0, 0);
else
gfx.drawImage(Content.sprites.buildFarmland.getSprite(1, 0), 0, 0);
// Crops
if(state == Build.STATE_ACTIVE || cropsLevel != 0)
{
for(int j = 0; j < 3; j++)
{
for(int i = 0; i < 3; i++)
{
if(cropsLevel != ROTTEN_LEVEL)
{
gfx.drawImage(
Content.sprites.buildFarmlandCrops.getSprite(cropsLevel, 0),
i * Game.tilesSize,
j * Game.tilesSize);
}
else
gfx.drawImage(
Content.sprites.buildFarmlandCrops,
i * Game.tilesSize,
j * Game.tilesSize);
}
}
}
}
|
public void renderBuild(GameContainer gc, StateBasedGame game, Graphics gfx)
{
// Soil
if(state == Build.STATE_NORMAL || needEmployees())
gfx.drawImage(Content.sprites.buildFarmland.getSprite(0, 0), 0, 0);
else
gfx.drawImage(Content.sprites.buildFarmland.getSprite(1, 0), 0, 0);
// Crops
if(state == Build.STATE_ACTIVE || cropsLevel != 0)
{
for(int j = 0; j < 3; j++)
{
for(int i = 0; i < 3; i++)
{
if(cropsLevel != ROTTEN_LEVEL)
{
gfx.drawImage(
Content.sprites.buildFarmlandCrops.getSprite(cropsLevel, 0),
i * Game.tilesSize,
j * Game.tilesSize);
}
else
gfx.drawImage(
Content.sprites.buildFarmlandRottenCrops,
i * Game.tilesSize,
j * Game.tilesSize);
}
}
}
}
|
diff --git a/MythicDrops-Sockets/src/main/java/net/nunnerycode/bukkit/mythicdrops/sockets/MythicDropsSockets.java b/MythicDrops-Sockets/src/main/java/net/nunnerycode/bukkit/mythicdrops/sockets/MythicDropsSockets.java
index 465f11e9..41e43b60 100644
--- a/MythicDrops-Sockets/src/main/java/net/nunnerycode/bukkit/mythicdrops/sockets/MythicDropsSockets.java
+++ b/MythicDrops-Sockets/src/main/java/net/nunnerycode/bukkit/mythicdrops/sockets/MythicDropsSockets.java
@@ -1,1365 +1,1365 @@
package net.nunnerycode.bukkit.mythicdrops.sockets;
import com.conventnunnery.libraries.config.CommentedConventYamlConfiguration;
import com.conventnunnery.libraries.config.ConventYamlConfiguration;
import net.nunnerycode.bukkit.mythicdrops.utils.ItemUtil;
import net.nunnerycode.java.libraries.cannonball.DebugPrinter;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Effect;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.material.MaterialData;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffectType;
import se.ranzdo.bukkit.methodcommand.Arg;
import se.ranzdo.bukkit.methodcommand.Command;
import se.ranzdo.bukkit.methodcommand.CommandHandler;
import se.ranzdo.bukkit.methodcommand.FlagArg;
import se.ranzdo.bukkit.methodcommand.Flags;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
public class MythicDropsSockets extends JavaPlugin implements Listener {
private static MythicDropsSockets _INSTANCE;
private final Map<String, HeldItem> heldSocket = new HashMap<>();
private DebugPrinter debugPrinter;
private Map<String, String> language;
private String socketGemName;
private List<String> socketGemLore;
private String sockettedItemSocket;
private List<String> sockettedItemLore;
private ConventYamlConfiguration configYAML;
private ConventYamlConfiguration socketGemsYAML;
private boolean useAttackerItemInHand;
private boolean useAttackerArmorEquipped;
private boolean useDefenderItemInHand;
private boolean useDefenderArmorEquipped;
private double socketGemChanceToSpawn;
private List<MaterialData> socketGemMaterialIds;
private Map<String, SocketGem> socketGemMap;
private List<String> socketGemPrefixes;
private boolean preventMultipleChangesFromSockets;
private List<String> socketGemSuffixes;
public static MythicDropsSockets getInstance() {
return _INSTANCE;
}
public Map<String, SocketGem> getSocketGemMap() {
return Collections.unmodifiableMap(socketGemMap);
}
public List<String> getSocketGemPrefixes() {
return Collections.unmodifiableList(socketGemPrefixes);
}
public List<String> getSocketGemSuffixes() {
return Collections.unmodifiableList(socketGemSuffixes);
}
public String getSockettedItemSocket() {
return sockettedItemSocket;
}
public List<String> getSockettedItemLore() {
return sockettedItemLore;
}
public ConventYamlConfiguration getConfigYAML() {
return configYAML;
}
public ConventYamlConfiguration getSocketGemsYAML() {
return socketGemsYAML;
}
@Override
public void onDisable() {
debugPrinter.debug(Level.INFO, "v" + getDescription().getVersion() + " disabled");
}
@Override
public void onEnable() {
_INSTANCE = this;
debugPrinter = new DebugPrinter(getDataFolder().getPath(), "debug.log");
language = new HashMap<>();
socketGemMaterialIds = new ArrayList<>();
socketGemMap = new HashMap<>();
socketGemPrefixes = new ArrayList<>();
socketGemSuffixes = new ArrayList<>();
unpackConfigurationFiles(new String[]{"config.yml", "socketGems.yml"}, false);
configYAML = new ConventYamlConfiguration(new File(getDataFolder(), "config.yml"),
YamlConfiguration.loadConfiguration(getResource("config.yml")).getString("version"));
configYAML.options().backupOnUpdate(true);
configYAML.options().updateOnLoad(true);
configYAML.load();
socketGemsYAML = new ConventYamlConfiguration(new File(getDataFolder(), "socketGems.yml"),
YamlConfiguration.loadConfiguration(getResource("socketGems.yml")).getString("version"));
socketGemsYAML.options().backupOnUpdate(true);
socketGemsYAML.options().updateOnLoad(true);
socketGemsYAML.load();
loadSettings();
loadGems();
getServer().getPluginManager().registerEvents(this, this);
CommandHandler commandHandler = new CommandHandler(this);
commandHandler.registerCommands(this);
debugPrinter.debug(Level.INFO, "v" + getDescription().getVersion() + " enabled");
}
private void loadGems() {
socketGemMap.clear();
List<String> loadedSocketGems = new ArrayList<>();
if (!socketGemsYAML.isConfigurationSection("socket-gems")) {
return;
}
ConfigurationSection cs = socketGemsYAML.getConfigurationSection("socket-gems");
for (String key : cs.getKeys(false)) {
if (!cs.isConfigurationSection(key)) {
continue;
}
ConfigurationSection gemCS = cs.getConfigurationSection(key);
GemType gemType = GemType.getFromName(gemCS.getString("type"));
if (gemType == null) {
gemType = GemType.ANY;
}
List<SocketPotionEffect> socketPotionEffects = buildSocketPotionEffects(gemCS);
List<SocketParticleEffect> socketParticleEffects = buildSocketParticleEffects(gemCS);
double chance = gemCS.getDouble("chance");
String prefix = gemCS.getString("prefix");
if (prefix != null && !prefix.equalsIgnoreCase("")) {
socketGemPrefixes.add(prefix);
}
String suffix = gemCS.getString("suffix");
if (suffix != null && !suffix.equalsIgnoreCase("")) {
socketGemSuffixes.add(suffix);
}
List<String> lore = gemCS.getStringList("lore");
Map<Enchantment, Integer> enchantments = new HashMap<>();
if (gemCS.isConfigurationSection("enchantments")) {
ConfigurationSection enchCS = gemCS.getConfigurationSection("enchantments");
for (String key1 : enchCS.getKeys(false)) {
Enchantment ench = null;
for (Enchantment ec : Enchantment.values()) {
if (ec.getName().equalsIgnoreCase(key1)) {
ench = ec;
break;
}
}
if (ench == null) {
continue;
}
int level = enchCS.getInt(key1);
enchantments.put(ench, level);
}
}
List<String> commands = gemCS.getStringList("commands");
List<SocketCommand> socketCommands = new ArrayList<>();
for (String s : commands) {
SocketCommand sc = new SocketCommand(s);
socketCommands.add(sc);
}
SocketGem sg = new SocketGem(key, gemType, socketPotionEffects, socketParticleEffects, chance, prefix,
suffix, lore, enchantments, socketCommands);
socketGemMap.put(key, sg);
loadedSocketGems.add(key);
}
debugPrinter.debug(Level.INFO, "Loaded socket gems: " + loadedSocketGems.toString());
}
private List<SocketPotionEffect> buildSocketPotionEffects(ConfigurationSection cs) {
List<SocketPotionEffect> socketPotionEffectList = new ArrayList<>();
if (!cs.isConfigurationSection("potion-effects")) {
return socketPotionEffectList;
}
ConfigurationSection cs1 = cs.getConfigurationSection("potion-effects");
for (String key : cs1.getKeys(false)) {
PotionEffectType pet = PotionEffectType.getByName(key);
if (pet == null) {
continue;
}
int duration = cs1.getInt(key + ".duration");
int intensity = cs1.getInt(key + ".intensity");
int radius = cs1.getInt(key + ".radius");
String target = cs1.getString(key + ".target");
EffectTarget et = EffectTarget.getFromName(target);
if (et == null) {
et = EffectTarget.NONE;
}
boolean affectsWielder = cs1.getBoolean(key + ".affectsWielder");
boolean affectsTarget = cs1.getBoolean(key + ".affectsTarget");
socketPotionEffectList.add(new SocketPotionEffect(pet, intensity, duration, radius, et, affectsWielder,
affectsTarget));
}
return socketPotionEffectList;
}
private List<SocketParticleEffect> buildSocketParticleEffects(ConfigurationSection cs) {
List<SocketParticleEffect> socketParticleEffectList = new ArrayList<>();
if (!cs.isConfigurationSection("particle-effects")) {
return socketParticleEffectList;
}
ConfigurationSection cs1 = cs.getConfigurationSection("particle-effects");
for (String key : cs1.getKeys(false)) {
Effect pet;
try {
pet = Effect.valueOf(key);
} catch (Exception e) {
continue;
}
if (pet == null) {
continue;
}
int duration = cs1.getInt(key + ".duration");
int intensity = cs1.getInt(key + ".intensity");
int radius = cs1.getInt(key + ".radius");
String target = cs1.getString(key + ".target");
EffectTarget et = EffectTarget.getFromName(target);
if (et == null) {
et = EffectTarget.NONE;
}
boolean affectsWielder = cs1.getBoolean(key + ".affectsWielder");
boolean affectsTarget = cs1.getBoolean(key + ".affectsTarget");
socketParticleEffectList.add(new SocketParticleEffect(pet, intensity, duration, radius, et,
affectsWielder, affectsTarget));
}
return socketParticleEffectList;
}
private void loadSettings() {
useAttackerItemInHand = configYAML.getBoolean("options.use-attacker-item-in-hand", true);
useAttackerArmorEquipped = configYAML.getBoolean("options.use-attacker-armor-equipped", false);
useDefenderItemInHand = configYAML.getBoolean("options.use-defender-item-in-hand", false);
useDefenderArmorEquipped = configYAML.getBoolean("options.use-defender-armor-equipped", true);
socketGemChanceToSpawn = configYAML.getDouble("options.socket-gem-chance-to-spawn", 0.25);
preventMultipleChangesFromSockets = configYAML.getBoolean("options.prevent-multiple-changes-from-sockets",
true);
List<String> socketGemMats = configYAML.getStringList("options.socket-gem-material-ids");
for (String s : socketGemMats) {
int id;
byte data;
if (s.contains(";")) {
String[] split = s.split(";");
id = NumberUtils.toInt(split[0], 0);
data = (byte) NumberUtils.toInt(split[1], 0);
} else {
id = NumberUtils.toInt(s, 0);
data = 0;
}
if (id == 0) {
continue;
}
socketGemMaterialIds.add(new MaterialData(id, data));
}
socketGemName = configYAML.getString("items.socket-name", "&6Socket Gem - %socketgem%");
socketGemLore = configYAML.getStringList("items.socket-lore");
sockettedItemSocket = configYAML.getString("items.socketted-item-socket", "&6(Socket)");
sockettedItemLore = configYAML.getStringList("items.socketted-item-lore");
language.clear();
for (String key : configYAML.getConfigurationSection("language").getKeys(true)) {
if (configYAML.getConfigurationSection("language").isConfigurationSection(key)) {
continue;
}
language.put(key, configYAML.getConfigurationSection("language").getString(key, key));
}
}
private void unpackConfigurationFiles(String[] configurationFiles, boolean overwrite) {
for (String s : configurationFiles) {
YamlConfiguration yc = CommentedConventYamlConfiguration.loadConfiguration(getResource(s));
try {
File f = new File(getDataFolder(), s);
if (!f.exists()) {
yc.save(f);
continue;
}
if (overwrite) {
yc.save(f);
}
} catch (IOException e) {
getLogger().warning("Could not unpack " + s);
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onRightClick(PlayerInteractEvent event) {
if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) {
return;
}
if (event.getItem() == null) {
return;
}
Player player = event.getPlayer();
ItemStack itemInHand = event.getItem();
String itemType = ItemUtil.getItemTypeFromMaterialData(itemInHand.getData());
if (getSocketGemMaterialIds().contains(itemInHand.getData())) {
event.setUseItemInHand(Event.Result.DENY);
player.updateInventory();
}
if (itemType != null && ItemUtil.isArmor(itemType) && itemInHand.hasItemMeta()) {
event.setUseItemInHand(Event.Result.DENY);
player.updateInventory();
}
if (heldSocket.containsKey(player.getName())) {
socketItem(event, player, itemInHand, itemType);
heldSocket.remove(player.getName());
} else {
addHeldSocket(event, player, itemInHand);
}
}
public String getLanguageString(String key, String[][] args) {
String s = getLanguageString(key);
for (String[] arg : args) {
s = s.replace(arg[0], arg[1]);
}
return s;
}
public String getLanguageString(String key) {
return language.containsKey(key) ? language.get(key) : key;
}
public List<String> replaceArgs(List<String> strings, String[][] args) {
List<String> list = new ArrayList<>();
for (String s : strings) {
list.add(replaceArgs(s, args));
}
return list;
}
public String replaceArgs(String string, String[][] args) {
String s = string;
for (String[] arg : args) {
s = s.replace(arg[0], arg[1]);
}
return s;
}
public String getSocketGemName() {
return socketGemName;
}
public List<String> getSocketGemLore() {
return socketGemLore;
}
public double getSocketGemChanceToSpawn() {
return socketGemChanceToSpawn;
}
public boolean socketGemTypeMatchesItemStack(SocketGem socketGem, ItemStack itemStack) {
String itemType = ItemUtil.getItemTypeFromMaterialData(itemStack.getData());
if (itemType == null) {
return false;
}
switch (socketGem.getGemType()) {
case TOOL:
return ItemUtil.isTool(itemType);
case ARMOR:
return ItemUtil.isArmor(itemType);
case ANY:
return true;
default:
return false;
}
}
private void addHeldSocket(PlayerInteractEvent event, final Player player, ItemStack itemInHand) {
if (!getSocketGemMaterialIds().contains(itemInHand.getData())) {
return;
}
if (!itemInHand.hasItemMeta()) {
return;
}
ItemMeta im = itemInHand.getItemMeta();
if (!im.hasDisplayName()) {
return;
}
String replacedArgs = ChatColor.stripColor(replaceArgs(socketGemName, new String[][]{{"%socketgem%", ""}}).replace('&', '\u00A7').replace("\u00A7\u00A7", "&"));
String type = ChatColor.stripColor(im.getDisplayName().replace(replacedArgs, ""));
if (type == null) {
return;
}
SocketGem socketGem = socketGemMap.get(type);
if (socketGem == null) {
socketGem = getSocketGemFromName(type);
if (socketGem == null) {
return;
}
}
sendMessage(player, "messages.instructions", new String[][]{});
HeldItem hg = new HeldItem(socketGem.getName(), itemInHand);
heldSocket.put(player.getName(), hg);
Bukkit.getScheduler().runTaskLaterAsynchronously(this, new Runnable() {
@Override
public void run() {
heldSocket.remove(player.getName());
}
}, 30 * 20L);
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
player.updateInventory();
}
public boolean isPreventMultipleChangesFromSockets() {
return preventMultipleChangesFromSockets;
}
private void socketItem(PlayerInteractEvent event, Player player, ItemStack itemInHand, String itemType) {
if (ItemUtil.isArmor(itemType) || ItemUtil.isTool(itemType)) {
if (!itemInHand.hasItemMeta()) {
sendMessage(player, "messages.cannot-use", new String[][]{});
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
return;
}
ItemMeta im = itemInHand.getItemMeta();
if (!im.hasLore()) {
sendMessage(player, "messages.cannot-use", new String[][]{});
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
return;
}
- List<String> lore = new ArrayList<String>(im.getLore());
- String socketString = getFormattedLanguageString("items.socketted-item-socket");
+ List<String> lore = new ArrayList<>(im.getLore());
+ String socketString = getSockettedItemSocket().replace('&', '\u00A7').replace("\u00A7\u00A7", "&");
int index = indexOfStripColor(lore, socketString);
if (index < 0) {
sendMessage(player, "messages.cannot-use", new String[][]{});
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
return;
}
HeldItem heldSocket1 = heldSocket.get(player.getName());
String socketGemType = ChatColor.stripColor(heldSocket1
.getName());
SocketGem socketGem = getSocketGemFromName(socketGemType);
if (socketGem == null ||
!socketGemTypeMatchesItemStack(socketGem, itemInHand)) {
sendMessage(player, "messages.cannot-use", new String[][]{});
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
return;
}
lore.set(index, ChatColor.GOLD + socketGem.getName());
lore.removeAll(sockettedItemLore);
im.setLore(lore);
itemInHand.setItemMeta(im);
prefixItemStack(itemInHand, socketGem);
suffixItemStack(itemInHand, socketGem);
loreItemStack(itemInHand, socketGem);
enchantmentItemStack(itemInHand, socketGem);
if (player.getInventory().contains(heldSocket1.getItemStack())) {
int indexOfItem = player.getInventory().first(heldSocket1.getItemStack());
ItemStack inInventory = player.getInventory().getItem(indexOfItem);
inInventory.setAmount(inInventory.getAmount() - 1);
player.getInventory().setItem(indexOfItem, inInventory);
player.updateInventory();
} else {
sendMessage(player, "messages.do-not-have", new String[][]{});
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
return;
}
player.setItemInHand(itemInHand);
sendMessage(player, "messages.success", new String[][]{});
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
} else {
sendMessage(player, "messages.cannot-use", new String[][]{});
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
}
}
public int indexOfStripColor(List<String> list, String string) {
String[] array = list.toArray(new String[list.size()]);
for (int i = 0; i < array.length; i++) {
if (ChatColor.stripColor(array[i]).equalsIgnoreCase(ChatColor.stripColor(string))) {
return i;
}
}
return -1;
}
public int indexOfStripColor(String[] array, String string) {
for (int i = 0; i < array.length; i++) {
if (ChatColor.stripColor(array[i]).equalsIgnoreCase(ChatColor.stripColor(string))) {
return i;
}
}
return -1;
}
public ItemStack loreItemStack(ItemStack itemStack, SocketGem socketGem) {
ItemMeta im;
if (itemStack.hasItemMeta()) {
im = itemStack.getItemMeta();
} else {
im = Bukkit.getItemFactory().getItemMeta(itemStack.getType());
}
if (!im.hasLore()) {
im.setLore(new ArrayList<String>());
}
List<String> lore = new ArrayList<String>(im.getLore());
if (lore.containsAll(socketGem.getLore())) {
return itemStack;
}
for (String s : socketGem.getLore()) {
lore.add(s.replace('&', '\u00A7').replace("\u00A7\u00A7", "&"));
}
im.setLore(lore);
itemStack.setItemMeta(im);
return itemStack;
}
public ItemStack enchantmentItemStack(ItemStack itemStack, SocketGem socketGem) {
if (itemStack == null || socketGem == null) {
return itemStack;
}
Map<Enchantment, Integer> itemStackEnchantments =
new HashMap<Enchantment, Integer>(itemStack.getEnchantments());
for (Map.Entry<Enchantment, Integer> entry : socketGem.getEnchantments().entrySet()) {
if (itemStackEnchantments.containsKey(entry.getKey())) {
itemStack.removeEnchantment(entry.getKey());
int level = Math.abs(itemStackEnchantments.get(entry.getKey()) + entry.getValue());
if (level <= 0) {
continue;
}
itemStack.addUnsafeEnchantment(entry.getKey(), level);
} else {
itemStack.addUnsafeEnchantment(entry.getKey(),
entry.getValue() <= 0 ? Math.abs(entry.getValue()) == 0 ? 1 : Math.abs(entry.getValue()) :
entry.getValue());
}
}
return itemStack;
}
public ItemStack suffixItemStack(ItemStack itemStack, SocketGem socketGem) {
ItemMeta im;
if (!itemStack.hasItemMeta()) {
im = Bukkit.getItemFactory().getItemMeta(itemStack.getType());
} else {
im = itemStack.getItemMeta();
}
String name = im.getDisplayName();
if (name == null) {
return itemStack;
}
ChatColor beginColor = findColor(name);
String lastColors = ChatColor.getLastColors(name);
if (beginColor == null) {
beginColor = ChatColor.WHITE;
}
String suffix = socketGem.getSuffix();
if (suffix == null || suffix.equalsIgnoreCase("")) {
return itemStack;
}
if (isPreventMultipleChangesFromSockets() &&
ChatColor.stripColor(name).contains(suffix) ||
containsAnyFromList(ChatColor.stripColor(name), socketGemSuffixes)) {
return itemStack;
}
im.setDisplayName(name + " " + beginColor + suffix + lastColors);
itemStack.setItemMeta(im);
return itemStack;
}
public ItemStack prefixItemStack(ItemStack itemStack, SocketGem socketGem) {
ItemMeta im;
if (itemStack.hasItemMeta()) {
im = itemStack.getItemMeta();
} else {
im = Bukkit.getItemFactory().getItemMeta(itemStack.getType());
}
String name = im.getDisplayName();
if (name == null) {
return itemStack;
}
ChatColor beginColor = findColor(name);
if (beginColor == null) {
beginColor = ChatColor.WHITE;
}
String prefix = socketGem.getPrefix();
if (prefix == null || prefix.equalsIgnoreCase("")) {
return itemStack;
}
if (isPreventMultipleChangesFromSockets() &&
ChatColor.stripColor(name).contains(prefix) ||
containsAnyFromList(ChatColor.stripColor(name), socketGemPrefixes)) {
return itemStack;
}
im.setDisplayName(beginColor + prefix + " " + name);
itemStack.setItemMeta(im);
return itemStack;
}
public ChatColor findColor(final String s) {
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == (char) 167 && i + 1 < c.length) {
return ChatColor.getByChar(c[i + 1]);
}
}
return null;
}
public boolean containsAnyFromList(String string, List<String> list) {
for (String s : list) {
if (string.toUpperCase().contains(s.toUpperCase())) {
return true;
}
}
return false;
}
public void applyEffects(LivingEntity attacker, LivingEntity defender) {
if (attacker == null || defender == null) {
return;
}
// handle attacker
if (isUseAttackerArmorEquipped()) {
for (ItemStack attackersItem : attacker.getEquipment().getArmorContents()) {
if (attackersItem == null) {
continue;
}
List<SocketGem> attackerSocketGems = getSocketGems(attackersItem);
if (attackerSocketGems != null && !attackerSocketGems.isEmpty()) {
for (SocketGem sg : attackerSocketGems) {
if (sg == null) {
continue;
}
if (sg.getGemType() != GemType.TOOL && sg.getGemType() != GemType.ANY) {
continue;
}
for (SocketPotionEffect se : sg.getSocketPotionEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(attacker);
break;
case OTHER:
se.apply(defender);
break;
case AREA:
for (Entity e : attacker.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(defender)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(attacker);
}
break;
default:
break;
}
}
for (SocketParticleEffect se : sg.getSocketParticleEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(attacker);
break;
case OTHER:
se.apply(defender);
break;
case AREA:
for (Entity e : attacker.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(defender)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(attacker);
}
break;
default:
break;
}
}
}
}
}
}
if (isUseAttackerItemInHand() && attacker.getEquipment().getItemInHand() != null) {
List<SocketGem> attackerSocketGems = getSocketGems(attacker.getEquipment().getItemInHand());
if (attackerSocketGems != null && !attackerSocketGems.isEmpty()) {
for (SocketGem sg : attackerSocketGems) {
if (sg == null) {
continue;
}
if (sg.getGemType() != GemType.TOOL && sg.getGemType() != GemType.ANY) {
continue;
}
for (SocketPotionEffect se : sg.getSocketPotionEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(attacker);
break;
case OTHER:
se.apply(defender);
break;
case AREA:
for (Entity e : attacker.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(defender)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(attacker);
}
break;
default:
break;
}
}
for (SocketParticleEffect se : sg.getSocketParticleEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(attacker);
break;
case OTHER:
se.apply(defender);
break;
case AREA:
for (Entity e : attacker.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(defender)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(attacker);
}
break;
default:
break;
}
}
}
}
}
// handle defender
if (isUseDefenderArmorEquipped()) {
for (ItemStack defenderItem : defender.getEquipment().getArmorContents()) {
if (defenderItem == null) {
continue;
}
List<SocketGem> defenderSocketGems = getSocketGems(defenderItem);
for (SocketGem sg : defenderSocketGems) {
if (sg.getGemType() != GemType.ARMOR && sg.getGemType() != GemType.ANY) {
continue;
}
for (SocketPotionEffect se : sg.getSocketPotionEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(defender);
break;
case OTHER:
se.apply(attacker);
break;
case AREA:
for (Entity e : defender.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(attacker)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(defender);
}
break;
default:
break;
}
}
for (SocketParticleEffect se : sg.getSocketParticleEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(defender);
break;
case OTHER:
se.apply(attacker);
break;
case AREA:
for (Entity e : defender.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(attacker)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(defender);
}
break;
default:
break;
}
}
}
}
}
if (isUseDefenderItemInHand() && defender.getEquipment().getItemInHand() != null) {
List<SocketGem> defenderSocketGems = getSocketGems(defender.getEquipment().getItemInHand());
if (defenderSocketGems != null && !defenderSocketGems.isEmpty()) {
for (SocketGem sg : defenderSocketGems) {
if (sg.getGemType() != GemType.ARMOR && sg.getGemType() != GemType.ANY) {
continue;
}
for (SocketPotionEffect se : sg.getSocketPotionEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(defender);
break;
case OTHER:
se.apply(attacker);
break;
case AREA:
for (Entity e : defender.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(attacker)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(defender);
}
break;
default:
break;
}
}
for (SocketParticleEffect se : sg.getSocketParticleEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(defender);
break;
case OTHER:
se.apply(attacker);
break;
case AREA:
for (Entity e : defender.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(attacker)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(defender);
}
break;
default:
break;
}
}
}
}
}
}
public boolean isUseAttackerItemInHand() {
return useAttackerItemInHand;
}
public boolean isUseAttackerArmorEquipped() {
return useAttackerArmorEquipped;
}
public boolean isUseDefenderItemInHand() {
return useDefenderItemInHand;
}
public boolean isUseDefenderArmorEquipped() {
return useDefenderArmorEquipped;
}
public List<SocketGem> getSocketGems(ItemStack itemStack) {
List<SocketGem> socketGemList = new ArrayList<SocketGem>();
ItemMeta im;
if (itemStack.hasItemMeta()) {
im = itemStack.getItemMeta();
} else {
return socketGemList;
}
List<String> lore = im.getLore();
if (lore == null) {
return socketGemList;
}
for (String s : lore) {
SocketGem sg = getSocketGemFromName(ChatColor.stripColor(s));
if (sg == null) {
continue;
}
socketGemList.add(sg);
}
return socketGemList;
}
public void runCommands(LivingEntity attacker, LivingEntity defender) {
if (attacker == null || defender == null) {
return;
}
if (attacker instanceof Player) {
if (isUseAttackerArmorEquipped()) {
for (ItemStack attackersItem : attacker.getEquipment().getArmorContents()) {
if (attackersItem == null) {
continue;
}
List<SocketGem> attackerSocketGems = getSocketGems(attackersItem);
if (attackerSocketGems != null && !attackerSocketGems.isEmpty()) {
for (SocketGem sg : attackerSocketGems) {
if (sg == null) {
continue;
}
for (SocketCommand sc : sg.getCommands()) {
if (sc.getRunner() == SocketCommandRunner.CONSOLE) {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) attacker).getName());
}
if (command.contains("%target%")) {
if (defender instanceof Player) {
command = command.replace("%target%", ((Player) defender).getName());
} else {
continue;
}
}
}
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
} else {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) attacker).getName());
}
if (command.contains("%target%")) {
if (defender instanceof Player) {
command = command.replace("%target%", ((Player) defender).getName());
} else {
continue;
}
}
}
((Player) attacker).chat("/" + command);
}
}
}
}
}
}
if (isUseAttackerItemInHand() && attacker.getEquipment().getItemInHand() != null) {
List<SocketGem> attackerSocketGems = getSocketGems(attacker.getEquipment().getItemInHand());
if (attackerSocketGems != null && !attackerSocketGems.isEmpty()) {
for (SocketGem sg : attackerSocketGems) {
if (sg == null) {
continue;
}
for (SocketCommand sc : sg.getCommands()) {
if (sc.getRunner() == SocketCommandRunner.CONSOLE) {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) attacker).getName());
}
if (command.contains("%target%")) {
if (defender instanceof Player) {
command = command.replace("%target%", ((Player) defender).getName());
} else {
continue;
}
}
}
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
} else {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) attacker).getName());
}
if (command.contains("%target%")) {
if (defender instanceof Player) {
command = command.replace("%target%", ((Player) defender).getName());
} else {
continue;
}
}
}
((Player) attacker).chat("/" + command);
}
}
}
}
}
}
if (defender instanceof Player) {
if (isUseDefenderArmorEquipped()) {
for (ItemStack defendersItem : defender.getEquipment().getArmorContents()) {
if (defendersItem == null) {
continue;
}
List<SocketGem> defenderSocketGems = getSocketGems(defendersItem);
if (defenderSocketGems != null && !defenderSocketGems.isEmpty()) {
for (SocketGem sg : defenderSocketGems) {
if (sg == null) {
continue;
}
for (SocketCommand sc : sg.getCommands()) {
if (sc.getRunner() == SocketCommandRunner.CONSOLE) {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) defender).getName());
}
if (command.contains("%target%")) {
if (attacker instanceof Player) {
command = command.replace("%target%", ((Player) attacker).getName());
} else {
continue;
}
}
}
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
} else {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) defender).getName());
}
if (command.contains("%target%")) {
if (attacker instanceof Player) {
command = command.replace("%target%", ((Player) attacker).getName());
} else {
continue;
}
}
}
((Player) defender).chat("/" + command);
}
}
}
}
}
}
if (isUseDefenderItemInHand() && defender.getEquipment().getItemInHand() != null) {
List<SocketGem> defenderSocketGems = getSocketGems(defender.getEquipment().getItemInHand());
if (defenderSocketGems != null && !defenderSocketGems.isEmpty()) {
for (SocketGem sg : defenderSocketGems) {
if (sg == null) {
continue;
}
for (SocketCommand sc : sg.getCommands()) {
if (sc.getRunner() == SocketCommandRunner.CONSOLE) {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) defender).getName());
}
if (command.contains("%target%")) {
if (attacker instanceof Player) {
command = command.replace("%target%", ((Player) attacker).getName());
} else {
continue;
}
}
}
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
} else {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) defender).getName());
}
if (command.contains("%target%")) {
if (attacker instanceof Player) {
command = command.replace("%target%", ((Player) attacker).getName());
} else {
continue;
}
}
}
((Player) defender).chat("/" + command);
}
}
}
}
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) {
if (event.isCancelled()) {
return;
}
Entity e = event.getEntity();
Entity d = event.getDamager();
if (!(e instanceof LivingEntity)) {
return;
}
LivingEntity lee = (LivingEntity) e;
LivingEntity led;
if (d instanceof LivingEntity) {
led = (LivingEntity) d;
} else if (d instanceof Projectile) {
led = ((Projectile) d).getShooter();
} else {
return;
}
applyEffects(led, lee);
runCommands(led, lee);
}
@Command(identifier = "mythicdropssockets gem", description = "Gives MythicDrops gems",
permissions = "mythicdrops.command.gem")
@Flags(identifier = {"a", "g"}, description = {"Amount to spawn", "Socket Gem to spawn"})
public void customSubcommand(CommandSender sender, @Arg(name = "player", def = "self") String playerName,
@Arg(name = "amount", def = "1")
@FlagArg("a") int amount, @Arg(name = "item", def = "*") @FlagArg("g") String
itemName) {
Player player;
if (playerName.equalsIgnoreCase("self")) {
if (sender instanceof Player) {
player = (Player) sender;
} else {
sendMessage(sender, "command.no-access", new String[][]{});
return;
}
} else {
player = Bukkit.getPlayer(playerName);
}
if (player == null) {
sendMessage(sender, "command.player-does-not-exist", new String[][]{});
return;
}
SocketGem socketGem = null;
if (!itemName.equalsIgnoreCase("*")) {
try {
socketGem = getSocketGemFromName(itemName);
} catch (NullPointerException e) {
e.printStackTrace();
sendMessage(sender, "command.socket-gem-does-not-exist", new String[][]{});
return;
}
}
int amountGiven = 0;
for (int i = 0; i < amount; i++) {
try {
ItemStack itemStack;
if (socketGem == null) {
itemStack = new SocketItem(getRandomSocketGemMaterial(), getRandomSocketGemWithChance());
} else {
itemStack = new SocketItem(getRandomSocketGemMaterial(), socketGem);
}
itemStack.setDurability((short) 0);
player.getInventory().addItem(itemStack);
amountGiven++;
} catch (Exception ignored) {
ignored.printStackTrace();
}
}
sendMessage(player, "command.give-gem-receiver",
new String[][]{{"%amount%", String.valueOf(amountGiven)}});
sendMessage(sender, "command.give-gem-sender", new String[][]{{"%amount%",
String.valueOf(amountGiven)}, {"%receiver%", player.getName()}});
}
public void sendMessage(CommandSender reciever, String path, String[][] arguments) {
String message = getFormattedLanguageString(path, arguments);
if (message == null) {
return;
}
reciever.sendMessage(message);
}
public String getFormattedLanguageString(String key, String[][] args) {
String s = getFormattedLanguageString(key);
for (String[] arg : args) {
s = s.replace(arg[0], arg[1]);
}
return s;
}
public String getFormattedLanguageString(String key) {
return getLanguageString(key).replace('&', '\u00A7').replace("\u00A7\u00A7", "&");
}
public SocketGem getRandomSocketGemWithChance() {
if (socketGemMap == null || socketGemMap.isEmpty()) {
return null;
}
Set<SocketGem> zeroChanceSocketGems = new HashSet<>();
while (zeroChanceSocketGems.size() != socketGemMap.size()) {
for (SocketGem socket : socketGemMap.values()) {
if (socket.getChance() <= 0.0D) {
zeroChanceSocketGems.add(socket);
continue;
}
if (RandomUtils.nextDouble() < socket.getChance()) {
return socket;
}
}
}
return null;
}
public MaterialData getRandomSocketGemMaterial() {
if (getSocketGemMaterialIds() == null || getSocketGemMaterialIds().isEmpty()) {
return null;
}
return getSocketGemMaterialIds().get(RandomUtils.nextInt(getSocketGemMaterialIds().size()));
}
public List<MaterialData> getSocketGemMaterialIds() {
return socketGemMaterialIds;
}
public SocketGem getSocketGemFromName(String name) {
for (SocketGem sg : socketGemMap.values()) {
if (sg.getName().equalsIgnoreCase(name)) {
return sg;
}
}
return null;
}
private class HeldItem {
private final String name;
private final ItemStack itemStack;
public HeldItem(String name, ItemStack itemStack) {
this.name = name;
this.itemStack = itemStack;
}
public String getName() {
return name;
}
public ItemStack getItemStack() {
return itemStack;
}
}
}
| true | true |
private void addHeldSocket(PlayerInteractEvent event, final Player player, ItemStack itemInHand) {
if (!getSocketGemMaterialIds().contains(itemInHand.getData())) {
return;
}
if (!itemInHand.hasItemMeta()) {
return;
}
ItemMeta im = itemInHand.getItemMeta();
if (!im.hasDisplayName()) {
return;
}
String replacedArgs = ChatColor.stripColor(replaceArgs(socketGemName, new String[][]{{"%socketgem%", ""}}).replace('&', '\u00A7').replace("\u00A7\u00A7", "&"));
String type = ChatColor.stripColor(im.getDisplayName().replace(replacedArgs, ""));
if (type == null) {
return;
}
SocketGem socketGem = socketGemMap.get(type);
if (socketGem == null) {
socketGem = getSocketGemFromName(type);
if (socketGem == null) {
return;
}
}
sendMessage(player, "messages.instructions", new String[][]{});
HeldItem hg = new HeldItem(socketGem.getName(), itemInHand);
heldSocket.put(player.getName(), hg);
Bukkit.getScheduler().runTaskLaterAsynchronously(this, new Runnable() {
@Override
public void run() {
heldSocket.remove(player.getName());
}
}, 30 * 20L);
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
player.updateInventory();
}
public boolean isPreventMultipleChangesFromSockets() {
return preventMultipleChangesFromSockets;
}
private void socketItem(PlayerInteractEvent event, Player player, ItemStack itemInHand, String itemType) {
if (ItemUtil.isArmor(itemType) || ItemUtil.isTool(itemType)) {
if (!itemInHand.hasItemMeta()) {
sendMessage(player, "messages.cannot-use", new String[][]{});
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
return;
}
ItemMeta im = itemInHand.getItemMeta();
if (!im.hasLore()) {
sendMessage(player, "messages.cannot-use", new String[][]{});
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
return;
}
List<String> lore = new ArrayList<String>(im.getLore());
String socketString = getFormattedLanguageString("items.socketted-item-socket");
int index = indexOfStripColor(lore, socketString);
if (index < 0) {
sendMessage(player, "messages.cannot-use", new String[][]{});
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
return;
}
HeldItem heldSocket1 = heldSocket.get(player.getName());
String socketGemType = ChatColor.stripColor(heldSocket1
.getName());
SocketGem socketGem = getSocketGemFromName(socketGemType);
if (socketGem == null ||
!socketGemTypeMatchesItemStack(socketGem, itemInHand)) {
sendMessage(player, "messages.cannot-use", new String[][]{});
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
return;
}
lore.set(index, ChatColor.GOLD + socketGem.getName());
lore.removeAll(sockettedItemLore);
im.setLore(lore);
itemInHand.setItemMeta(im);
prefixItemStack(itemInHand, socketGem);
suffixItemStack(itemInHand, socketGem);
loreItemStack(itemInHand, socketGem);
enchantmentItemStack(itemInHand, socketGem);
if (player.getInventory().contains(heldSocket1.getItemStack())) {
int indexOfItem = player.getInventory().first(heldSocket1.getItemStack());
ItemStack inInventory = player.getInventory().getItem(indexOfItem);
inInventory.setAmount(inInventory.getAmount() - 1);
player.getInventory().setItem(indexOfItem, inInventory);
player.updateInventory();
} else {
sendMessage(player, "messages.do-not-have", new String[][]{});
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
return;
}
player.setItemInHand(itemInHand);
sendMessage(player, "messages.success", new String[][]{});
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
} else {
sendMessage(player, "messages.cannot-use", new String[][]{});
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
}
}
public int indexOfStripColor(List<String> list, String string) {
String[] array = list.toArray(new String[list.size()]);
for (int i = 0; i < array.length; i++) {
if (ChatColor.stripColor(array[i]).equalsIgnoreCase(ChatColor.stripColor(string))) {
return i;
}
}
return -1;
}
public int indexOfStripColor(String[] array, String string) {
for (int i = 0; i < array.length; i++) {
if (ChatColor.stripColor(array[i]).equalsIgnoreCase(ChatColor.stripColor(string))) {
return i;
}
}
return -1;
}
public ItemStack loreItemStack(ItemStack itemStack, SocketGem socketGem) {
ItemMeta im;
if (itemStack.hasItemMeta()) {
im = itemStack.getItemMeta();
} else {
im = Bukkit.getItemFactory().getItemMeta(itemStack.getType());
}
if (!im.hasLore()) {
im.setLore(new ArrayList<String>());
}
List<String> lore = new ArrayList<String>(im.getLore());
if (lore.containsAll(socketGem.getLore())) {
return itemStack;
}
for (String s : socketGem.getLore()) {
lore.add(s.replace('&', '\u00A7').replace("\u00A7\u00A7", "&"));
}
im.setLore(lore);
itemStack.setItemMeta(im);
return itemStack;
}
public ItemStack enchantmentItemStack(ItemStack itemStack, SocketGem socketGem) {
if (itemStack == null || socketGem == null) {
return itemStack;
}
Map<Enchantment, Integer> itemStackEnchantments =
new HashMap<Enchantment, Integer>(itemStack.getEnchantments());
for (Map.Entry<Enchantment, Integer> entry : socketGem.getEnchantments().entrySet()) {
if (itemStackEnchantments.containsKey(entry.getKey())) {
itemStack.removeEnchantment(entry.getKey());
int level = Math.abs(itemStackEnchantments.get(entry.getKey()) + entry.getValue());
if (level <= 0) {
continue;
}
itemStack.addUnsafeEnchantment(entry.getKey(), level);
} else {
itemStack.addUnsafeEnchantment(entry.getKey(),
entry.getValue() <= 0 ? Math.abs(entry.getValue()) == 0 ? 1 : Math.abs(entry.getValue()) :
entry.getValue());
}
}
return itemStack;
}
public ItemStack suffixItemStack(ItemStack itemStack, SocketGem socketGem) {
ItemMeta im;
if (!itemStack.hasItemMeta()) {
im = Bukkit.getItemFactory().getItemMeta(itemStack.getType());
} else {
im = itemStack.getItemMeta();
}
String name = im.getDisplayName();
if (name == null) {
return itemStack;
}
ChatColor beginColor = findColor(name);
String lastColors = ChatColor.getLastColors(name);
if (beginColor == null) {
beginColor = ChatColor.WHITE;
}
String suffix = socketGem.getSuffix();
if (suffix == null || suffix.equalsIgnoreCase("")) {
return itemStack;
}
if (isPreventMultipleChangesFromSockets() &&
ChatColor.stripColor(name).contains(suffix) ||
containsAnyFromList(ChatColor.stripColor(name), socketGemSuffixes)) {
return itemStack;
}
im.setDisplayName(name + " " + beginColor + suffix + lastColors);
itemStack.setItemMeta(im);
return itemStack;
}
public ItemStack prefixItemStack(ItemStack itemStack, SocketGem socketGem) {
ItemMeta im;
if (itemStack.hasItemMeta()) {
im = itemStack.getItemMeta();
} else {
im = Bukkit.getItemFactory().getItemMeta(itemStack.getType());
}
String name = im.getDisplayName();
if (name == null) {
return itemStack;
}
ChatColor beginColor = findColor(name);
if (beginColor == null) {
beginColor = ChatColor.WHITE;
}
String prefix = socketGem.getPrefix();
if (prefix == null || prefix.equalsIgnoreCase("")) {
return itemStack;
}
if (isPreventMultipleChangesFromSockets() &&
ChatColor.stripColor(name).contains(prefix) ||
containsAnyFromList(ChatColor.stripColor(name), socketGemPrefixes)) {
return itemStack;
}
im.setDisplayName(beginColor + prefix + " " + name);
itemStack.setItemMeta(im);
return itemStack;
}
public ChatColor findColor(final String s) {
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == (char) 167 && i + 1 < c.length) {
return ChatColor.getByChar(c[i + 1]);
}
}
return null;
}
public boolean containsAnyFromList(String string, List<String> list) {
for (String s : list) {
if (string.toUpperCase().contains(s.toUpperCase())) {
return true;
}
}
return false;
}
public void applyEffects(LivingEntity attacker, LivingEntity defender) {
if (attacker == null || defender == null) {
return;
}
// handle attacker
if (isUseAttackerArmorEquipped()) {
for (ItemStack attackersItem : attacker.getEquipment().getArmorContents()) {
if (attackersItem == null) {
continue;
}
List<SocketGem> attackerSocketGems = getSocketGems(attackersItem);
if (attackerSocketGems != null && !attackerSocketGems.isEmpty()) {
for (SocketGem sg : attackerSocketGems) {
if (sg == null) {
continue;
}
if (sg.getGemType() != GemType.TOOL && sg.getGemType() != GemType.ANY) {
continue;
}
for (SocketPotionEffect se : sg.getSocketPotionEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(attacker);
break;
case OTHER:
se.apply(defender);
break;
case AREA:
for (Entity e : attacker.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(defender)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(attacker);
}
break;
default:
break;
}
}
for (SocketParticleEffect se : sg.getSocketParticleEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(attacker);
break;
case OTHER:
se.apply(defender);
break;
case AREA:
for (Entity e : attacker.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(defender)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(attacker);
}
break;
default:
break;
}
}
}
}
}
}
if (isUseAttackerItemInHand() && attacker.getEquipment().getItemInHand() != null) {
List<SocketGem> attackerSocketGems = getSocketGems(attacker.getEquipment().getItemInHand());
if (attackerSocketGems != null && !attackerSocketGems.isEmpty()) {
for (SocketGem sg : attackerSocketGems) {
if (sg == null) {
continue;
}
if (sg.getGemType() != GemType.TOOL && sg.getGemType() != GemType.ANY) {
continue;
}
for (SocketPotionEffect se : sg.getSocketPotionEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(attacker);
break;
case OTHER:
se.apply(defender);
break;
case AREA:
for (Entity e : attacker.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(defender)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(attacker);
}
break;
default:
break;
}
}
for (SocketParticleEffect se : sg.getSocketParticleEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(attacker);
break;
case OTHER:
se.apply(defender);
break;
case AREA:
for (Entity e : attacker.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(defender)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(attacker);
}
break;
default:
break;
}
}
}
}
}
// handle defender
if (isUseDefenderArmorEquipped()) {
for (ItemStack defenderItem : defender.getEquipment().getArmorContents()) {
if (defenderItem == null) {
continue;
}
List<SocketGem> defenderSocketGems = getSocketGems(defenderItem);
for (SocketGem sg : defenderSocketGems) {
if (sg.getGemType() != GemType.ARMOR && sg.getGemType() != GemType.ANY) {
continue;
}
for (SocketPotionEffect se : sg.getSocketPotionEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(defender);
break;
case OTHER:
se.apply(attacker);
break;
case AREA:
for (Entity e : defender.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(attacker)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(defender);
}
break;
default:
break;
}
}
for (SocketParticleEffect se : sg.getSocketParticleEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(defender);
break;
case OTHER:
se.apply(attacker);
break;
case AREA:
for (Entity e : defender.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(attacker)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(defender);
}
break;
default:
break;
}
}
}
}
}
if (isUseDefenderItemInHand() && defender.getEquipment().getItemInHand() != null) {
List<SocketGem> defenderSocketGems = getSocketGems(defender.getEquipment().getItemInHand());
if (defenderSocketGems != null && !defenderSocketGems.isEmpty()) {
for (SocketGem sg : defenderSocketGems) {
if (sg.getGemType() != GemType.ARMOR && sg.getGemType() != GemType.ANY) {
continue;
}
for (SocketPotionEffect se : sg.getSocketPotionEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(defender);
break;
case OTHER:
se.apply(attacker);
break;
case AREA:
for (Entity e : defender.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(attacker)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(defender);
}
break;
default:
break;
}
}
for (SocketParticleEffect se : sg.getSocketParticleEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(defender);
break;
case OTHER:
se.apply(attacker);
break;
case AREA:
for (Entity e : defender.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(attacker)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(defender);
}
break;
default:
break;
}
}
}
}
}
}
public boolean isUseAttackerItemInHand() {
return useAttackerItemInHand;
}
public boolean isUseAttackerArmorEquipped() {
return useAttackerArmorEquipped;
}
public boolean isUseDefenderItemInHand() {
return useDefenderItemInHand;
}
public boolean isUseDefenderArmorEquipped() {
return useDefenderArmorEquipped;
}
public List<SocketGem> getSocketGems(ItemStack itemStack) {
List<SocketGem> socketGemList = new ArrayList<SocketGem>();
ItemMeta im;
if (itemStack.hasItemMeta()) {
im = itemStack.getItemMeta();
} else {
return socketGemList;
}
List<String> lore = im.getLore();
if (lore == null) {
return socketGemList;
}
for (String s : lore) {
SocketGem sg = getSocketGemFromName(ChatColor.stripColor(s));
if (sg == null) {
continue;
}
socketGemList.add(sg);
}
return socketGemList;
}
public void runCommands(LivingEntity attacker, LivingEntity defender) {
if (attacker == null || defender == null) {
return;
}
if (attacker instanceof Player) {
if (isUseAttackerArmorEquipped()) {
for (ItemStack attackersItem : attacker.getEquipment().getArmorContents()) {
if (attackersItem == null) {
continue;
}
List<SocketGem> attackerSocketGems = getSocketGems(attackersItem);
if (attackerSocketGems != null && !attackerSocketGems.isEmpty()) {
for (SocketGem sg : attackerSocketGems) {
if (sg == null) {
continue;
}
for (SocketCommand sc : sg.getCommands()) {
if (sc.getRunner() == SocketCommandRunner.CONSOLE) {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) attacker).getName());
}
if (command.contains("%target%")) {
if (defender instanceof Player) {
command = command.replace("%target%", ((Player) defender).getName());
} else {
continue;
}
}
}
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
} else {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) attacker).getName());
}
if (command.contains("%target%")) {
if (defender instanceof Player) {
command = command.replace("%target%", ((Player) defender).getName());
} else {
continue;
}
}
}
((Player) attacker).chat("/" + command);
}
}
}
}
}
}
if (isUseAttackerItemInHand() && attacker.getEquipment().getItemInHand() != null) {
List<SocketGem> attackerSocketGems = getSocketGems(attacker.getEquipment().getItemInHand());
if (attackerSocketGems != null && !attackerSocketGems.isEmpty()) {
for (SocketGem sg : attackerSocketGems) {
if (sg == null) {
continue;
}
for (SocketCommand sc : sg.getCommands()) {
if (sc.getRunner() == SocketCommandRunner.CONSOLE) {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) attacker).getName());
}
if (command.contains("%target%")) {
if (defender instanceof Player) {
command = command.replace("%target%", ((Player) defender).getName());
} else {
continue;
}
}
}
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
} else {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) attacker).getName());
}
if (command.contains("%target%")) {
if (defender instanceof Player) {
command = command.replace("%target%", ((Player) defender).getName());
} else {
continue;
}
}
}
((Player) attacker).chat("/" + command);
}
}
}
}
}
}
if (defender instanceof Player) {
if (isUseDefenderArmorEquipped()) {
for (ItemStack defendersItem : defender.getEquipment().getArmorContents()) {
if (defendersItem == null) {
continue;
}
List<SocketGem> defenderSocketGems = getSocketGems(defendersItem);
if (defenderSocketGems != null && !defenderSocketGems.isEmpty()) {
for (SocketGem sg : defenderSocketGems) {
if (sg == null) {
continue;
}
for (SocketCommand sc : sg.getCommands()) {
if (sc.getRunner() == SocketCommandRunner.CONSOLE) {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) defender).getName());
}
if (command.contains("%target%")) {
if (attacker instanceof Player) {
command = command.replace("%target%", ((Player) attacker).getName());
} else {
continue;
}
}
}
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
} else {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) defender).getName());
}
if (command.contains("%target%")) {
if (attacker instanceof Player) {
command = command.replace("%target%", ((Player) attacker).getName());
} else {
continue;
}
}
}
((Player) defender).chat("/" + command);
}
}
}
}
}
}
if (isUseDefenderItemInHand() && defender.getEquipment().getItemInHand() != null) {
List<SocketGem> defenderSocketGems = getSocketGems(defender.getEquipment().getItemInHand());
if (defenderSocketGems != null && !defenderSocketGems.isEmpty()) {
for (SocketGem sg : defenderSocketGems) {
if (sg == null) {
continue;
}
for (SocketCommand sc : sg.getCommands()) {
if (sc.getRunner() == SocketCommandRunner.CONSOLE) {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) defender).getName());
}
if (command.contains("%target%")) {
if (attacker instanceof Player) {
command = command.replace("%target%", ((Player) attacker).getName());
} else {
continue;
}
}
}
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
} else {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) defender).getName());
}
if (command.contains("%target%")) {
if (attacker instanceof Player) {
command = command.replace("%target%", ((Player) attacker).getName());
} else {
continue;
}
}
}
((Player) defender).chat("/" + command);
}
}
}
}
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) {
if (event.isCancelled()) {
return;
}
Entity e = event.getEntity();
Entity d = event.getDamager();
if (!(e instanceof LivingEntity)) {
return;
}
LivingEntity lee = (LivingEntity) e;
LivingEntity led;
if (d instanceof LivingEntity) {
led = (LivingEntity) d;
} else if (d instanceof Projectile) {
led = ((Projectile) d).getShooter();
} else {
return;
}
applyEffects(led, lee);
runCommands(led, lee);
}
@Command(identifier = "mythicdropssockets gem", description = "Gives MythicDrops gems",
permissions = "mythicdrops.command.gem")
@Flags(identifier = {"a", "g"}, description = {"Amount to spawn", "Socket Gem to spawn"})
public void customSubcommand(CommandSender sender, @Arg(name = "player", def = "self") String playerName,
@Arg(name = "amount", def = "1")
@FlagArg("a") int amount, @Arg(name = "item", def = "*") @FlagArg("g") String
itemName) {
Player player;
if (playerName.equalsIgnoreCase("self")) {
if (sender instanceof Player) {
player = (Player) sender;
} else {
sendMessage(sender, "command.no-access", new String[][]{});
return;
}
} else {
player = Bukkit.getPlayer(playerName);
}
if (player == null) {
sendMessage(sender, "command.player-does-not-exist", new String[][]{});
return;
}
SocketGem socketGem = null;
if (!itemName.equalsIgnoreCase("*")) {
try {
socketGem = getSocketGemFromName(itemName);
} catch (NullPointerException e) {
e.printStackTrace();
sendMessage(sender, "command.socket-gem-does-not-exist", new String[][]{});
return;
}
}
int amountGiven = 0;
for (int i = 0; i < amount; i++) {
try {
ItemStack itemStack;
if (socketGem == null) {
itemStack = new SocketItem(getRandomSocketGemMaterial(), getRandomSocketGemWithChance());
} else {
itemStack = new SocketItem(getRandomSocketGemMaterial(), socketGem);
}
itemStack.setDurability((short) 0);
player.getInventory().addItem(itemStack);
amountGiven++;
} catch (Exception ignored) {
ignored.printStackTrace();
}
}
sendMessage(player, "command.give-gem-receiver",
new String[][]{{"%amount%", String.valueOf(amountGiven)}});
sendMessage(sender, "command.give-gem-sender", new String[][]{{"%amount%",
String.valueOf(amountGiven)}, {"%receiver%", player.getName()}});
}
|
private void addHeldSocket(PlayerInteractEvent event, final Player player, ItemStack itemInHand) {
if (!getSocketGemMaterialIds().contains(itemInHand.getData())) {
return;
}
if (!itemInHand.hasItemMeta()) {
return;
}
ItemMeta im = itemInHand.getItemMeta();
if (!im.hasDisplayName()) {
return;
}
String replacedArgs = ChatColor.stripColor(replaceArgs(socketGemName, new String[][]{{"%socketgem%", ""}}).replace('&', '\u00A7').replace("\u00A7\u00A7", "&"));
String type = ChatColor.stripColor(im.getDisplayName().replace(replacedArgs, ""));
if (type == null) {
return;
}
SocketGem socketGem = socketGemMap.get(type);
if (socketGem == null) {
socketGem = getSocketGemFromName(type);
if (socketGem == null) {
return;
}
}
sendMessage(player, "messages.instructions", new String[][]{});
HeldItem hg = new HeldItem(socketGem.getName(), itemInHand);
heldSocket.put(player.getName(), hg);
Bukkit.getScheduler().runTaskLaterAsynchronously(this, new Runnable() {
@Override
public void run() {
heldSocket.remove(player.getName());
}
}, 30 * 20L);
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
player.updateInventory();
}
public boolean isPreventMultipleChangesFromSockets() {
return preventMultipleChangesFromSockets;
}
private void socketItem(PlayerInteractEvent event, Player player, ItemStack itemInHand, String itemType) {
if (ItemUtil.isArmor(itemType) || ItemUtil.isTool(itemType)) {
if (!itemInHand.hasItemMeta()) {
sendMessage(player, "messages.cannot-use", new String[][]{});
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
return;
}
ItemMeta im = itemInHand.getItemMeta();
if (!im.hasLore()) {
sendMessage(player, "messages.cannot-use", new String[][]{});
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
return;
}
List<String> lore = new ArrayList<>(im.getLore());
String socketString = getSockettedItemSocket().replace('&', '\u00A7').replace("\u00A7\u00A7", "&");
int index = indexOfStripColor(lore, socketString);
if (index < 0) {
sendMessage(player, "messages.cannot-use", new String[][]{});
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
return;
}
HeldItem heldSocket1 = heldSocket.get(player.getName());
String socketGemType = ChatColor.stripColor(heldSocket1
.getName());
SocketGem socketGem = getSocketGemFromName(socketGemType);
if (socketGem == null ||
!socketGemTypeMatchesItemStack(socketGem, itemInHand)) {
sendMessage(player, "messages.cannot-use", new String[][]{});
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
return;
}
lore.set(index, ChatColor.GOLD + socketGem.getName());
lore.removeAll(sockettedItemLore);
im.setLore(lore);
itemInHand.setItemMeta(im);
prefixItemStack(itemInHand, socketGem);
suffixItemStack(itemInHand, socketGem);
loreItemStack(itemInHand, socketGem);
enchantmentItemStack(itemInHand, socketGem);
if (player.getInventory().contains(heldSocket1.getItemStack())) {
int indexOfItem = player.getInventory().first(heldSocket1.getItemStack());
ItemStack inInventory = player.getInventory().getItem(indexOfItem);
inInventory.setAmount(inInventory.getAmount() - 1);
player.getInventory().setItem(indexOfItem, inInventory);
player.updateInventory();
} else {
sendMessage(player, "messages.do-not-have", new String[][]{});
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
return;
}
player.setItemInHand(itemInHand);
sendMessage(player, "messages.success", new String[][]{});
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
} else {
sendMessage(player, "messages.cannot-use", new String[][]{});
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldSocket.remove(player.getName());
player.updateInventory();
}
}
public int indexOfStripColor(List<String> list, String string) {
String[] array = list.toArray(new String[list.size()]);
for (int i = 0; i < array.length; i++) {
if (ChatColor.stripColor(array[i]).equalsIgnoreCase(ChatColor.stripColor(string))) {
return i;
}
}
return -1;
}
public int indexOfStripColor(String[] array, String string) {
for (int i = 0; i < array.length; i++) {
if (ChatColor.stripColor(array[i]).equalsIgnoreCase(ChatColor.stripColor(string))) {
return i;
}
}
return -1;
}
public ItemStack loreItemStack(ItemStack itemStack, SocketGem socketGem) {
ItemMeta im;
if (itemStack.hasItemMeta()) {
im = itemStack.getItemMeta();
} else {
im = Bukkit.getItemFactory().getItemMeta(itemStack.getType());
}
if (!im.hasLore()) {
im.setLore(new ArrayList<String>());
}
List<String> lore = new ArrayList<String>(im.getLore());
if (lore.containsAll(socketGem.getLore())) {
return itemStack;
}
for (String s : socketGem.getLore()) {
lore.add(s.replace('&', '\u00A7').replace("\u00A7\u00A7", "&"));
}
im.setLore(lore);
itemStack.setItemMeta(im);
return itemStack;
}
public ItemStack enchantmentItemStack(ItemStack itemStack, SocketGem socketGem) {
if (itemStack == null || socketGem == null) {
return itemStack;
}
Map<Enchantment, Integer> itemStackEnchantments =
new HashMap<Enchantment, Integer>(itemStack.getEnchantments());
for (Map.Entry<Enchantment, Integer> entry : socketGem.getEnchantments().entrySet()) {
if (itemStackEnchantments.containsKey(entry.getKey())) {
itemStack.removeEnchantment(entry.getKey());
int level = Math.abs(itemStackEnchantments.get(entry.getKey()) + entry.getValue());
if (level <= 0) {
continue;
}
itemStack.addUnsafeEnchantment(entry.getKey(), level);
} else {
itemStack.addUnsafeEnchantment(entry.getKey(),
entry.getValue() <= 0 ? Math.abs(entry.getValue()) == 0 ? 1 : Math.abs(entry.getValue()) :
entry.getValue());
}
}
return itemStack;
}
public ItemStack suffixItemStack(ItemStack itemStack, SocketGem socketGem) {
ItemMeta im;
if (!itemStack.hasItemMeta()) {
im = Bukkit.getItemFactory().getItemMeta(itemStack.getType());
} else {
im = itemStack.getItemMeta();
}
String name = im.getDisplayName();
if (name == null) {
return itemStack;
}
ChatColor beginColor = findColor(name);
String lastColors = ChatColor.getLastColors(name);
if (beginColor == null) {
beginColor = ChatColor.WHITE;
}
String suffix = socketGem.getSuffix();
if (suffix == null || suffix.equalsIgnoreCase("")) {
return itemStack;
}
if (isPreventMultipleChangesFromSockets() &&
ChatColor.stripColor(name).contains(suffix) ||
containsAnyFromList(ChatColor.stripColor(name), socketGemSuffixes)) {
return itemStack;
}
im.setDisplayName(name + " " + beginColor + suffix + lastColors);
itemStack.setItemMeta(im);
return itemStack;
}
public ItemStack prefixItemStack(ItemStack itemStack, SocketGem socketGem) {
ItemMeta im;
if (itemStack.hasItemMeta()) {
im = itemStack.getItemMeta();
} else {
im = Bukkit.getItemFactory().getItemMeta(itemStack.getType());
}
String name = im.getDisplayName();
if (name == null) {
return itemStack;
}
ChatColor beginColor = findColor(name);
if (beginColor == null) {
beginColor = ChatColor.WHITE;
}
String prefix = socketGem.getPrefix();
if (prefix == null || prefix.equalsIgnoreCase("")) {
return itemStack;
}
if (isPreventMultipleChangesFromSockets() &&
ChatColor.stripColor(name).contains(prefix) ||
containsAnyFromList(ChatColor.stripColor(name), socketGemPrefixes)) {
return itemStack;
}
im.setDisplayName(beginColor + prefix + " " + name);
itemStack.setItemMeta(im);
return itemStack;
}
public ChatColor findColor(final String s) {
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == (char) 167 && i + 1 < c.length) {
return ChatColor.getByChar(c[i + 1]);
}
}
return null;
}
public boolean containsAnyFromList(String string, List<String> list) {
for (String s : list) {
if (string.toUpperCase().contains(s.toUpperCase())) {
return true;
}
}
return false;
}
public void applyEffects(LivingEntity attacker, LivingEntity defender) {
if (attacker == null || defender == null) {
return;
}
// handle attacker
if (isUseAttackerArmorEquipped()) {
for (ItemStack attackersItem : attacker.getEquipment().getArmorContents()) {
if (attackersItem == null) {
continue;
}
List<SocketGem> attackerSocketGems = getSocketGems(attackersItem);
if (attackerSocketGems != null && !attackerSocketGems.isEmpty()) {
for (SocketGem sg : attackerSocketGems) {
if (sg == null) {
continue;
}
if (sg.getGemType() != GemType.TOOL && sg.getGemType() != GemType.ANY) {
continue;
}
for (SocketPotionEffect se : sg.getSocketPotionEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(attacker);
break;
case OTHER:
se.apply(defender);
break;
case AREA:
for (Entity e : attacker.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(defender)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(attacker);
}
break;
default:
break;
}
}
for (SocketParticleEffect se : sg.getSocketParticleEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(attacker);
break;
case OTHER:
se.apply(defender);
break;
case AREA:
for (Entity e : attacker.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(defender)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(attacker);
}
break;
default:
break;
}
}
}
}
}
}
if (isUseAttackerItemInHand() && attacker.getEquipment().getItemInHand() != null) {
List<SocketGem> attackerSocketGems = getSocketGems(attacker.getEquipment().getItemInHand());
if (attackerSocketGems != null && !attackerSocketGems.isEmpty()) {
for (SocketGem sg : attackerSocketGems) {
if (sg == null) {
continue;
}
if (sg.getGemType() != GemType.TOOL && sg.getGemType() != GemType.ANY) {
continue;
}
for (SocketPotionEffect se : sg.getSocketPotionEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(attacker);
break;
case OTHER:
se.apply(defender);
break;
case AREA:
for (Entity e : attacker.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(defender)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(attacker);
}
break;
default:
break;
}
}
for (SocketParticleEffect se : sg.getSocketParticleEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(attacker);
break;
case OTHER:
se.apply(defender);
break;
case AREA:
for (Entity e : attacker.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(defender)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(attacker);
}
break;
default:
break;
}
}
}
}
}
// handle defender
if (isUseDefenderArmorEquipped()) {
for (ItemStack defenderItem : defender.getEquipment().getArmorContents()) {
if (defenderItem == null) {
continue;
}
List<SocketGem> defenderSocketGems = getSocketGems(defenderItem);
for (SocketGem sg : defenderSocketGems) {
if (sg.getGemType() != GemType.ARMOR && sg.getGemType() != GemType.ANY) {
continue;
}
for (SocketPotionEffect se : sg.getSocketPotionEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(defender);
break;
case OTHER:
se.apply(attacker);
break;
case AREA:
for (Entity e : defender.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(attacker)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(defender);
}
break;
default:
break;
}
}
for (SocketParticleEffect se : sg.getSocketParticleEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(defender);
break;
case OTHER:
se.apply(attacker);
break;
case AREA:
for (Entity e : defender.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(attacker)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(defender);
}
break;
default:
break;
}
}
}
}
}
if (isUseDefenderItemInHand() && defender.getEquipment().getItemInHand() != null) {
List<SocketGem> defenderSocketGems = getSocketGems(defender.getEquipment().getItemInHand());
if (defenderSocketGems != null && !defenderSocketGems.isEmpty()) {
for (SocketGem sg : defenderSocketGems) {
if (sg.getGemType() != GemType.ARMOR && sg.getGemType() != GemType.ANY) {
continue;
}
for (SocketPotionEffect se : sg.getSocketPotionEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(defender);
break;
case OTHER:
se.apply(attacker);
break;
case AREA:
for (Entity e : defender.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(attacker)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(defender);
}
break;
default:
break;
}
}
for (SocketParticleEffect se : sg.getSocketParticleEffects()) {
if (se == null) {
continue;
}
switch (se.getEffectTarget()) {
case SELF:
se.apply(defender);
break;
case OTHER:
se.apply(attacker);
break;
case AREA:
for (Entity e : defender.getNearbyEntities(se.getRadius(), se.getRadius(),
se.getRadius())) {
if (!(e instanceof LivingEntity)) {
continue;
}
if (!se.isAffectsTarget() && e.equals(attacker)) {
continue;
}
se.apply((LivingEntity) e);
}
if (se.isAffectsWielder()) {
se.apply(defender);
}
break;
default:
break;
}
}
}
}
}
}
public boolean isUseAttackerItemInHand() {
return useAttackerItemInHand;
}
public boolean isUseAttackerArmorEquipped() {
return useAttackerArmorEquipped;
}
public boolean isUseDefenderItemInHand() {
return useDefenderItemInHand;
}
public boolean isUseDefenderArmorEquipped() {
return useDefenderArmorEquipped;
}
public List<SocketGem> getSocketGems(ItemStack itemStack) {
List<SocketGem> socketGemList = new ArrayList<SocketGem>();
ItemMeta im;
if (itemStack.hasItemMeta()) {
im = itemStack.getItemMeta();
} else {
return socketGemList;
}
List<String> lore = im.getLore();
if (lore == null) {
return socketGemList;
}
for (String s : lore) {
SocketGem sg = getSocketGemFromName(ChatColor.stripColor(s));
if (sg == null) {
continue;
}
socketGemList.add(sg);
}
return socketGemList;
}
public void runCommands(LivingEntity attacker, LivingEntity defender) {
if (attacker == null || defender == null) {
return;
}
if (attacker instanceof Player) {
if (isUseAttackerArmorEquipped()) {
for (ItemStack attackersItem : attacker.getEquipment().getArmorContents()) {
if (attackersItem == null) {
continue;
}
List<SocketGem> attackerSocketGems = getSocketGems(attackersItem);
if (attackerSocketGems != null && !attackerSocketGems.isEmpty()) {
for (SocketGem sg : attackerSocketGems) {
if (sg == null) {
continue;
}
for (SocketCommand sc : sg.getCommands()) {
if (sc.getRunner() == SocketCommandRunner.CONSOLE) {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) attacker).getName());
}
if (command.contains("%target%")) {
if (defender instanceof Player) {
command = command.replace("%target%", ((Player) defender).getName());
} else {
continue;
}
}
}
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
} else {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) attacker).getName());
}
if (command.contains("%target%")) {
if (defender instanceof Player) {
command = command.replace("%target%", ((Player) defender).getName());
} else {
continue;
}
}
}
((Player) attacker).chat("/" + command);
}
}
}
}
}
}
if (isUseAttackerItemInHand() && attacker.getEquipment().getItemInHand() != null) {
List<SocketGem> attackerSocketGems = getSocketGems(attacker.getEquipment().getItemInHand());
if (attackerSocketGems != null && !attackerSocketGems.isEmpty()) {
for (SocketGem sg : attackerSocketGems) {
if (sg == null) {
continue;
}
for (SocketCommand sc : sg.getCommands()) {
if (sc.getRunner() == SocketCommandRunner.CONSOLE) {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) attacker).getName());
}
if (command.contains("%target%")) {
if (defender instanceof Player) {
command = command.replace("%target%", ((Player) defender).getName());
} else {
continue;
}
}
}
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
} else {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) attacker).getName());
}
if (command.contains("%target%")) {
if (defender instanceof Player) {
command = command.replace("%target%", ((Player) defender).getName());
} else {
continue;
}
}
}
((Player) attacker).chat("/" + command);
}
}
}
}
}
}
if (defender instanceof Player) {
if (isUseDefenderArmorEquipped()) {
for (ItemStack defendersItem : defender.getEquipment().getArmorContents()) {
if (defendersItem == null) {
continue;
}
List<SocketGem> defenderSocketGems = getSocketGems(defendersItem);
if (defenderSocketGems != null && !defenderSocketGems.isEmpty()) {
for (SocketGem sg : defenderSocketGems) {
if (sg == null) {
continue;
}
for (SocketCommand sc : sg.getCommands()) {
if (sc.getRunner() == SocketCommandRunner.CONSOLE) {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) defender).getName());
}
if (command.contains("%target%")) {
if (attacker instanceof Player) {
command = command.replace("%target%", ((Player) attacker).getName());
} else {
continue;
}
}
}
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
} else {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) defender).getName());
}
if (command.contains("%target%")) {
if (attacker instanceof Player) {
command = command.replace("%target%", ((Player) attacker).getName());
} else {
continue;
}
}
}
((Player) defender).chat("/" + command);
}
}
}
}
}
}
if (isUseDefenderItemInHand() && defender.getEquipment().getItemInHand() != null) {
List<SocketGem> defenderSocketGems = getSocketGems(defender.getEquipment().getItemInHand());
if (defenderSocketGems != null && !defenderSocketGems.isEmpty()) {
for (SocketGem sg : defenderSocketGems) {
if (sg == null) {
continue;
}
for (SocketCommand sc : sg.getCommands()) {
if (sc.getRunner() == SocketCommandRunner.CONSOLE) {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) defender).getName());
}
if (command.contains("%target%")) {
if (attacker instanceof Player) {
command = command.replace("%target%", ((Player) attacker).getName());
} else {
continue;
}
}
}
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
} else {
String command = sc.getCommand();
if (command.contains("%wielder%") || command.contains("%target%")) {
if (command.contains("%wielder%")) {
command = command.replace("%wielder%", ((Player) defender).getName());
}
if (command.contains("%target%")) {
if (attacker instanceof Player) {
command = command.replace("%target%", ((Player) attacker).getName());
} else {
continue;
}
}
}
((Player) defender).chat("/" + command);
}
}
}
}
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) {
if (event.isCancelled()) {
return;
}
Entity e = event.getEntity();
Entity d = event.getDamager();
if (!(e instanceof LivingEntity)) {
return;
}
LivingEntity lee = (LivingEntity) e;
LivingEntity led;
if (d instanceof LivingEntity) {
led = (LivingEntity) d;
} else if (d instanceof Projectile) {
led = ((Projectile) d).getShooter();
} else {
return;
}
applyEffects(led, lee);
runCommands(led, lee);
}
@Command(identifier = "mythicdropssockets gem", description = "Gives MythicDrops gems",
permissions = "mythicdrops.command.gem")
@Flags(identifier = {"a", "g"}, description = {"Amount to spawn", "Socket Gem to spawn"})
public void customSubcommand(CommandSender sender, @Arg(name = "player", def = "self") String playerName,
@Arg(name = "amount", def = "1")
@FlagArg("a") int amount, @Arg(name = "item", def = "*") @FlagArg("g") String
itemName) {
Player player;
if (playerName.equalsIgnoreCase("self")) {
if (sender instanceof Player) {
player = (Player) sender;
} else {
sendMessage(sender, "command.no-access", new String[][]{});
return;
}
} else {
player = Bukkit.getPlayer(playerName);
}
if (player == null) {
sendMessage(sender, "command.player-does-not-exist", new String[][]{});
return;
}
SocketGem socketGem = null;
if (!itemName.equalsIgnoreCase("*")) {
try {
socketGem = getSocketGemFromName(itemName);
} catch (NullPointerException e) {
e.printStackTrace();
sendMessage(sender, "command.socket-gem-does-not-exist", new String[][]{});
return;
}
}
int amountGiven = 0;
for (int i = 0; i < amount; i++) {
try {
ItemStack itemStack;
if (socketGem == null) {
itemStack = new SocketItem(getRandomSocketGemMaterial(), getRandomSocketGemWithChance());
} else {
itemStack = new SocketItem(getRandomSocketGemMaterial(), socketGem);
}
itemStack.setDurability((short) 0);
player.getInventory().addItem(itemStack);
amountGiven++;
} catch (Exception ignored) {
ignored.printStackTrace();
}
}
sendMessage(player, "command.give-gem-receiver",
new String[][]{{"%amount%", String.valueOf(amountGiven)}});
sendMessage(sender, "command.give-gem-sender", new String[][]{{"%amount%",
String.valueOf(amountGiven)}, {"%receiver%", player.getName()}});
}
|
diff --git a/fds/src/main/java/org/intalio/tempo/workflow/fds/FormDispatcherConfiguration.java b/fds/src/main/java/org/intalio/tempo/workflow/fds/FormDispatcherConfiguration.java
index 7a88447a..b0e64a92 100644
--- a/fds/src/main/java/org/intalio/tempo/workflow/fds/FormDispatcherConfiguration.java
+++ b/fds/src/main/java/org/intalio/tempo/workflow/fds/FormDispatcherConfiguration.java
@@ -1,182 +1,182 @@
/**
* Copyright (c) 2005-2006 Intalio 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:
* Intalio inc. - initial API and implementation
*/
package org.intalio.tempo.workflow.fds;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class holds the configuration of the FDS. <br>
* It implements the <i>Singleton</i> pattern.
* <p>
* The configuration is loaded from a resource by the name of
* <code>fds-config.xml</code>
* <p>
* Its format is straightforward and XML-based. See the default instance for
* details.
* <p>
* If the configuration loading fails, an error is logged and defaults are used.
*
* @author Iwan Memruk
* @version $Revision: 842 $
*/
public final class FormDispatcherConfiguration {
/**
* Configuration file location property
*/
public static final String CONFIG_DIR_PROPERTY = "org.intalio.tempo.configDirectory";
/**
* The name of the resource containing the configuration.
*/
private static final String _CONFIG_RESOURCE_NAME = "fds-config.xml";
/**
* The Log4j logger for this class.
*/
private static Logger _log = LoggerFactory.getLogger(FormDispatcherConfiguration.class);
/**
* The shared singleton instance of this class.
*/
private static FormDispatcherConfiguration _instance = new FormDispatcherConfiguration();
/**
* The base URL of PXE deployment. <br>
* The initialization value is the default.
*/
private String _pxeBaseUrl = "http://localhost:8080/ode";
/**
* The FDS endpoint
*/
private String _fdsUrl = "http://localhost:8080/fds/workflow/ib4p";
/**
* The URL of the Workflow Processes, relative to the base URL of PXE
* deployment. <br>
* The initialization value is the default.
*/
private String _workflowProcessesRelativeUrl = "/workflow/ib4p";
/**
* Endpoint for the Task Management Service
*/
private String _tmsUrl = "http://localhost:8080/axis2/services/TaskManagementServices";
/**
* Timeout when sending messages
*/
private int _httpTimeout = 10000;
/**
* Returns the shared singleton instance of this class.
*
* @return The shared singleton instance of this class.
*/
public static FormDispatcherConfiguration getInstance() {
return _instance;
}
/**
* Returns the base URL of PXE deployment.
*
* @return The base URL of PXE deployment.
*/
public String getPxeBaseUrl() {
return _pxeBaseUrl;
}
public int getHttpTimeout() {
return _httpTimeout;
}
public void setHttpTimeout(int httpTimeout) {
_httpTimeout = httpTimeout;
}
/**
* Returns the endpoint for FDS
*
* @return the FDS endpoint
*/
public String getFdsUrl() {
return _fdsUrl;
}
/**
* Returns the URL of the Workflow Processes, relative to the base URL of
* PXE deployment.
*
* @return The URL of the Workflow Processes, relative to the base URL of
* PXE deployment.
*/
public String getWorkflowProcessesRelativeUrl() {
return _workflowProcessesRelativeUrl;
}
/**
* Returns the TMS endpoint
*
* @return the TMS endpoint
*/
public String getTmsUrl() {
return _tmsUrl;
}
/**
* Instance constructor. <br>
* Tries to load the configuration from the configuration resource. <br>
* If the loading fails, logs an error and uses the defaults.
*/
private FormDispatcherConfiguration() {
try {
String configDir = System.getProperty(CONFIG_DIR_PROPERTY);
if (configDir == null) {
_log.error("Property " + CONFIG_DIR_PROPERTY + " not set; using configuration defaults for FDS");
return;
}
File f = new File(configDir, _CONFIG_RESOURCE_NAME);
if (!f.exists()) {
_log.error("Missing FDS configuration file: " + f.toString());
return;
}
InputStream configInputStream = new FileInputStream(f);
Document configDocument = new SAXReader().read(configInputStream);
String pxeBaseUrl = configDocument.valueOf("/config/pxeBaseUrl");
String workflowProcessesRelativeUrl = configDocument.valueOf("/config/workflowProcessesRelativeUrl");
String tmsUrl = configDocument.valueOf("/config/tmsUrl");
String fdsUrl = configDocument.valueOf("/config/fdsUrl");
try {
- _httpTimeout = Integer.parseInt(configDocument.valueOf("/config/fdsUrl"));
+ _httpTimeout = Integer.parseInt(configDocument.valueOf("/config/httpTimeout"));
} catch (Exception e) {
_log.error("Not using invalid value for httptimeout");
}
_pxeBaseUrl = pxeBaseUrl;
_workflowProcessesRelativeUrl = workflowProcessesRelativeUrl;
_tmsUrl = tmsUrl;
_fdsUrl = fdsUrl;
} catch (Exception e) {
_log.error("Failed to load the configuration: " + e.getMessage());
}
}
}
| true | true |
private FormDispatcherConfiguration() {
try {
String configDir = System.getProperty(CONFIG_DIR_PROPERTY);
if (configDir == null) {
_log.error("Property " + CONFIG_DIR_PROPERTY + " not set; using configuration defaults for FDS");
return;
}
File f = new File(configDir, _CONFIG_RESOURCE_NAME);
if (!f.exists()) {
_log.error("Missing FDS configuration file: " + f.toString());
return;
}
InputStream configInputStream = new FileInputStream(f);
Document configDocument = new SAXReader().read(configInputStream);
String pxeBaseUrl = configDocument.valueOf("/config/pxeBaseUrl");
String workflowProcessesRelativeUrl = configDocument.valueOf("/config/workflowProcessesRelativeUrl");
String tmsUrl = configDocument.valueOf("/config/tmsUrl");
String fdsUrl = configDocument.valueOf("/config/fdsUrl");
try {
_httpTimeout = Integer.parseInt(configDocument.valueOf("/config/fdsUrl"));
} catch (Exception e) {
_log.error("Not using invalid value for httptimeout");
}
_pxeBaseUrl = pxeBaseUrl;
_workflowProcessesRelativeUrl = workflowProcessesRelativeUrl;
_tmsUrl = tmsUrl;
_fdsUrl = fdsUrl;
} catch (Exception e) {
_log.error("Failed to load the configuration: " + e.getMessage());
}
}
|
private FormDispatcherConfiguration() {
try {
String configDir = System.getProperty(CONFIG_DIR_PROPERTY);
if (configDir == null) {
_log.error("Property " + CONFIG_DIR_PROPERTY + " not set; using configuration defaults for FDS");
return;
}
File f = new File(configDir, _CONFIG_RESOURCE_NAME);
if (!f.exists()) {
_log.error("Missing FDS configuration file: " + f.toString());
return;
}
InputStream configInputStream = new FileInputStream(f);
Document configDocument = new SAXReader().read(configInputStream);
String pxeBaseUrl = configDocument.valueOf("/config/pxeBaseUrl");
String workflowProcessesRelativeUrl = configDocument.valueOf("/config/workflowProcessesRelativeUrl");
String tmsUrl = configDocument.valueOf("/config/tmsUrl");
String fdsUrl = configDocument.valueOf("/config/fdsUrl");
try {
_httpTimeout = Integer.parseInt(configDocument.valueOf("/config/httpTimeout"));
} catch (Exception e) {
_log.error("Not using invalid value for httptimeout");
}
_pxeBaseUrl = pxeBaseUrl;
_workflowProcessesRelativeUrl = workflowProcessesRelativeUrl;
_tmsUrl = tmsUrl;
_fdsUrl = fdsUrl;
} catch (Exception e) {
_log.error("Failed to load the configuration: " + e.getMessage());
}
}
|
diff --git a/dvn-app/trunk/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/study/Metadata.java b/dvn-app/trunk/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/study/Metadata.java
index 58469246b..d0aa4bd2b 100644
--- a/dvn-app/trunk/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/study/Metadata.java
+++ b/dvn-app/trunk/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/study/Metadata.java
@@ -1,2919 +1,2919 @@
/*
* 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
*/
/*
* Metadata.java
*
* Created on June 1, 2008 2:44 PM
*
*/
package edu.harvard.iq.dvn.core.study;
import edu.harvard.iq.dvn.core.util.StringUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.persistence.*;
/**
*
* @author Ellen Kraffmiller
*/
@Entity
public class Metadata implements java.io.Serializable {
/**
* Holds value of property id.
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* Getter for property id.
* @return Value of property id.
*/
public Long getId() {
return this.id;
}
/**
* Setter for property id.
* @param id New value of property id.
*/
public void setId(Long id) {
this.id = id;
}
@OneToOne(mappedBy="metadata")
private StudyVersion studyVersion;
public StudyVersion getStudyVersion() {
return studyVersion;
}
public void setStudyVersion(StudyVersion studyVersion) {
this.studyVersion = studyVersion;
}
@OneToOne(mappedBy="metadata")
private Template template;
public Template getTemplate() {
return template;
}
public void setTemplate(Template template) {
this.template = template;
}
public Metadata () {
}
private boolean copyField(TemplateField tf, boolean copyHidden, boolean copyDisabled) {
return (!tf.isHidden() && !tf.isDisabled()) ||
(copyHidden && tf.isHidden() ) ||
(copyDisabled && tf.isDisabled());
}
public Metadata(Metadata source, boolean copyHidden, boolean copyDisabled ) {
this.setUNF(source.UNF);
this.setStudyFieldValues(new ArrayList<StudyFieldValue>());
Template sourceTemplate = source.getTemplate() != null ? source.getTemplate() : source.getStudyVersion().getStudy().getTemplate();
// create a Map so we can look up each template field and check its field input level
Map<String,TemplateField> tfMap = new HashMap();
for (TemplateField tf : sourceTemplate.getTemplateFields()){
tfMap.put(tf.getStudyField().getName(), tf);
}
if( copyField(tfMap.get(StudyFieldConstant.accessToSources), copyHidden, copyDisabled) ) {
this.setAccessToSources(source.accessToSources);
}
if( copyField(tfMap.get(StudyFieldConstant.actionsToMinimizeLoss), copyHidden, copyDisabled) ) {
this.setActionsToMinimizeLoss(source.actionsToMinimizeLoss);
}
if( copyField(tfMap.get(StudyFieldConstant.availabilityStatus), copyHidden, copyDisabled) ) {
this.setAvailabilityStatus(source.availabilityStatus);
}
if( copyField(tfMap.get(StudyFieldConstant.characteristicOfSources), copyHidden, copyDisabled) ) {
this.setCharacteristicOfSources(source.characteristicOfSources);
}
if( copyField(tfMap.get(StudyFieldConstant.citationRequirements), copyHidden, copyDisabled) ) {
this.setCitationRequirements(source.citationRequirements);
}
if( copyField(tfMap.get(StudyFieldConstant.cleaningOperations), copyHidden, copyDisabled) ) {
this.setCleaningOperations(source.cleaningOperations);
}
if( copyField(tfMap.get(StudyFieldConstant.collectionMode), copyHidden, copyDisabled) ) {
this.setCollectionMode(source.collectionMode);
}
if( copyField(tfMap.get(StudyFieldConstant.collectionSize), copyHidden, copyDisabled) ) {
this.setCollectionSize(source.collectionSize);
}
if( copyField(tfMap.get(StudyFieldConstant.conditions), copyHidden, copyDisabled) ) {
this.setConditions(source.conditions);
}
if( copyField(tfMap.get(StudyFieldConstant.confidentialityDeclaration), copyHidden, copyDisabled) ) {
this.setConfidentialityDeclaration(source.confidentialityDeclaration);
}
if( copyField(tfMap.get(StudyFieldConstant.contact), copyHidden, copyDisabled) ) {
this.setContact(source.contact);
}
if( copyField(tfMap.get(StudyFieldConstant.controlOperations), copyHidden, copyDisabled) ) {
this.setControlOperations(source.controlOperations);
}
if( copyField(tfMap.get(StudyFieldConstant.country), copyHidden, copyDisabled) ) {
this.setCountry(source.country);
}
if( copyField(tfMap.get(StudyFieldConstant.dataCollectionSituation), copyHidden, copyDisabled) ) {
this.setDataCollectionSituation(source.dataCollectionSituation);
}
if( copyField(tfMap.get(StudyFieldConstant.dataCollector), copyHidden, copyDisabled) ) {
this.setDataCollector(source.dataCollector);
}
if( copyField(tfMap.get(StudyFieldConstant.dataSources), copyHidden, copyDisabled) ) {
this.setDataSources(source.dataSources);
}
if( copyField(tfMap.get(StudyFieldConstant.dateOfCollectionEnd), copyHidden, copyDisabled) ) {
this.setDateOfCollectionEnd(source.dateOfCollectionEnd);
}
if( copyField(tfMap.get(StudyFieldConstant.dateOfCollectionStart), copyHidden, copyDisabled) ) {
- this.setAccessToSources(source.dateOfCollectionStart);
+ this.setDateOfCollectionStart(source.dateOfCollectionStart);
}
if( copyField(tfMap.get(StudyFieldConstant.dateOfDeposit), copyHidden, copyDisabled) ) {
- this.setDateOfCollectionStart(source.dateOfDeposit);
+ this.setDateOfDeposit(source.dateOfDeposit);
}
if( copyField(tfMap.get(StudyFieldConstant.depositor), copyHidden, copyDisabled) ) {
this.setDepositor(source.depositor);
}
if( copyField(tfMap.get(StudyFieldConstant.depositorRequirements), copyHidden, copyDisabled) ) {
this.setDepositorRequirements(source.depositorRequirements);
}
if( copyField(tfMap.get(StudyFieldConstant.deviationsFromSampleDesign), copyHidden, copyDisabled) ) {
this.setDeviationsFromSampleDesign(source.deviationsFromSampleDesign);
}
if( copyField(tfMap.get(StudyFieldConstant.disclaimer), copyHidden, copyDisabled) ) {
this.setDisclaimer(source.disclaimer);
}
if( copyField(tfMap.get(StudyFieldConstant.distributionDate), copyHidden, copyDisabled) ) {
this.setDistributionDate(source.distributionDate);
}
if( copyField(tfMap.get(StudyFieldConstant.distributorContact), copyHidden, copyDisabled) ) {
this.setDistributorContact(source.distributorContact);
}
if( copyField(tfMap.get(StudyFieldConstant.distributorContactAffiliation), copyHidden, copyDisabled) ) {
this.setDistributorContactAffiliation(source.distributorContactAffiliation);
}
if( copyField(tfMap.get(StudyFieldConstant.distributorContactEmail), copyHidden, copyDisabled) ) {
this.setDistributorContactEmail(source.distributorContactEmail);
}
if( copyField(tfMap.get(StudyFieldConstant.frequencyOfDataCollection), copyHidden, copyDisabled) ) {
this.setFrequencyOfDataCollection(source.frequencyOfDataCollection);
}
if( copyField(tfMap.get(StudyFieldConstant.fundingAgency), copyHidden, copyDisabled) ) {
this.setFundingAgency(source.fundingAgency);
}
if( copyField(tfMap.get(StudyFieldConstant.geographicCoverage), copyHidden, copyDisabled) ) {
this.setGeographicCoverage(source.geographicCoverage);
}
if( copyField(tfMap.get(StudyFieldConstant.geographicUnit), copyHidden, copyDisabled) ) {
this.setGeographicUnit(source.geographicUnit);
}
if (copyField(tfMap.get(StudyFieldConstant.kindOfData), copyHidden, copyDisabled)) {
this.setKindOfData(source.kindOfData);
}
if (copyField(tfMap.get(StudyFieldConstant.originOfSources), copyHidden, copyDisabled)) {
this.setOriginOfSources(source.originOfSources);
}
if (copyField(tfMap.get(StudyFieldConstant.originalArchive), copyHidden, copyDisabled)) {
this.setOriginalArchive(source.originalArchive);
}
if (copyField(tfMap.get(StudyFieldConstant.otherDataAppraisal), copyHidden, copyDisabled)) {
this.setOtherDataAppraisal(source.otherDataAppraisal);
}
if (copyField(tfMap.get(StudyFieldConstant.placeOfAccess), copyHidden, copyDisabled)) {
this.setPlaceOfAccess(source.placeOfAccess);
}
if (copyField(tfMap.get(StudyFieldConstant.productionDate), copyHidden, copyDisabled)) {
this.setProductionDate(source.productionDate);
}
if (copyField(tfMap.get(StudyFieldConstant.productionPlace), copyHidden, copyDisabled)) {
this.setProductionPlace(source.productionPlace);
}
if (copyField(tfMap.get(StudyFieldConstant.replicationFor), copyHidden, copyDisabled)) {
this.setReplicationFor(source.replicationFor);
}
if (copyField(tfMap.get(StudyFieldConstant.researchInstrument), copyHidden, copyDisabled)) {
this.setResearchInstrument(source.researchInstrument);
}
if (copyField(tfMap.get(StudyFieldConstant.responseRate), copyHidden, copyDisabled)) {
this.setResponseRate(source.responseRate);
}
if (copyField(tfMap.get(StudyFieldConstant.restrictions), copyHidden, copyDisabled)) {
this.setRestrictions(source.restrictions);
}
if (copyField(tfMap.get(StudyFieldConstant.samplingErrorEstimates), copyHidden, copyDisabled)) {
this.setSamplingErrorEstimate(source.samplingErrorEstimate);
}
if (copyField(tfMap.get(StudyFieldConstant.samplingProcedure), copyHidden, copyDisabled)) {
this.setSamplingProcedure(source.samplingProcedure);
}
if (copyField(tfMap.get(StudyFieldConstant.seriesInformation), copyHidden, copyDisabled)) {
this.setSeriesInformation(source.seriesInformation);
}
if (copyField(tfMap.get(StudyFieldConstant.seriesName), copyHidden, copyDisabled)) {
this.setSeriesName(source.seriesName);
}
if (copyField(tfMap.get(StudyFieldConstant.specialPermissions), copyHidden, copyDisabled)) {
this.setSpecialPermissions(source.specialPermissions);
}
if (copyField(tfMap.get(StudyFieldConstant.studyVersion), copyHidden, copyDisabled)) {
this.setStudyVersionText(source.studyVersionText);
}
if (copyField(tfMap.get(StudyFieldConstant.subTitle), copyHidden, copyDisabled)) {
this.setSubTitle(source.subTitle);
}
if (copyField(tfMap.get(StudyFieldConstant.timeMethod), copyHidden, copyDisabled)) {
this.setTimeMethod(source.timeMethod);
}
if (copyField(tfMap.get(StudyFieldConstant.timePeriodCoveredEnd), copyHidden, copyDisabled)) {
this.setTimePeriodCoveredEnd(source.timePeriodCoveredEnd);
}
if (copyField(tfMap.get(StudyFieldConstant.timePeriodCoveredStart), copyHidden, copyDisabled)) {
this.setTimePeriodCoveredStart(source.timePeriodCoveredStart);
}
if (copyField(tfMap.get(StudyFieldConstant.title), copyHidden, copyDisabled)) {
this.setTitle(source.title);
}
if (copyField(tfMap.get(StudyFieldConstant.unitOfAnalysis), copyHidden, copyDisabled)) {
this.setUnitOfAnalysis(source.unitOfAnalysis);
}
if (copyField(tfMap.get(StudyFieldConstant.universe), copyHidden, copyDisabled)) {
this.setUniverse(source.universe);
}
if (copyField(tfMap.get(StudyFieldConstant.versionDate), copyHidden, copyDisabled)) {
this.setVersionDate(source.versionDate);
}
if (copyField(tfMap.get(StudyFieldConstant.weighting), copyHidden, copyDisabled)) {
this.setWeighting(source.weighting);
}
if (copyField(tfMap.get(StudyFieldConstant.studyLevelErrorNotes), copyHidden, copyDisabled)) {
this.setStudyLevelErrorNotes(source.studyLevelErrorNotes);
}
if (copyField(tfMap.get(StudyFieldConstant.studyCompletion), copyHidden, copyDisabled)) {
this.setStudyCompletion(source.studyCompletion);
}
if (copyField(tfMap.get(StudyFieldConstant.abstractText), copyHidden, copyDisabled)) {
this.setStudyAbstracts(new ArrayList<StudyAbstract>());
for (StudyAbstract sa : source.studyAbstracts) {
StudyAbstract cloneAbstract = new StudyAbstract();
cloneAbstract.setDate(sa.getDate());
cloneAbstract.setDisplayOrder(sa.getDisplayOrder());
cloneAbstract.setMetadata(this);
cloneAbstract.setText(sa.getText());
this.getStudyAbstracts().add(cloneAbstract);
}
}
if (copyField(tfMap.get(StudyFieldConstant.authorName), copyHidden, copyDisabled)) {
this.setStudyAuthors(new ArrayList<StudyAuthor>());
for (StudyAuthor author : source.studyAuthors) {
StudyAuthor cloneAuthor = new StudyAuthor();
cloneAuthor.setAffiliation(author.getAffiliation());
cloneAuthor.setDisplayOrder(author.getDisplayOrder());
cloneAuthor.setMetadata(this);
cloneAuthor.setName(author.getName());
this.getStudyAuthors().add(cloneAuthor);
}
}
if (copyField(tfMap.get(StudyFieldConstant.distributorName), copyHidden, copyDisabled)) {
this.setStudyDistributors(new ArrayList<StudyDistributor>());
for (StudyDistributor dist : source.studyDistributors) {
StudyDistributor cloneDist = new StudyDistributor();
cloneDist.setAbbreviation(dist.getAbbreviation());
cloneDist.setAffiliation(dist.getAffiliation());
cloneDist.setDisplayOrder(dist.getDisplayOrder());
cloneDist.setMetadata(this);
cloneDist.setLogo(dist.getLogo());
cloneDist.setName(dist.getName());
cloneDist.setUrl(dist.getUrl());
this.getStudyDistributors().add(cloneDist);
}
}
if (copyField(tfMap.get(StudyFieldConstant.westLongitude), copyHidden, copyDisabled)) {
this.setStudyGeoBoundings(new ArrayList<StudyGeoBounding>());
for (StudyGeoBounding geo : source.studyGeoBoundings) {
StudyGeoBounding cloneGeo = new StudyGeoBounding();
cloneGeo.setDisplayOrder(geo.getDisplayOrder());
cloneGeo.setMetadata(this);
cloneGeo.setEastLongitude(geo.getEastLongitude());
cloneGeo.setNorthLatitude(geo.getNorthLatitude());
cloneGeo.setSouthLatitude(geo.getSouthLatitude());
cloneGeo.setWestLongitude(geo.getWestLongitude());
this.getStudyGeoBoundings().add(cloneGeo);
}
}
if (copyField(tfMap.get(StudyFieldConstant.grantNumber), copyHidden, copyDisabled)) {
this.setStudyGrants(new ArrayList<StudyGrant>());
for (StudyGrant grant : source.studyGrants) {
StudyGrant cloneGrant = new StudyGrant();
cloneGrant.setAgency(grant.getAgency());
cloneGrant.setDisplayOrder(grant.getDisplayOrder());
cloneGrant.setMetadata(this);
cloneGrant.setNumber(grant.getNumber());
this.getStudyGrants().add(cloneGrant);
}
}
if (copyField(tfMap.get(StudyFieldConstant.keywordValue), copyHidden, copyDisabled)) {
this.setStudyKeywords(new ArrayList<StudyKeyword>());
for (StudyKeyword key : source.studyKeywords) {
StudyKeyword cloneKey = new StudyKeyword();
cloneKey.setDisplayOrder(key.getDisplayOrder());
cloneKey.setMetadata(this);
cloneKey.setValue(key.getValue());
cloneKey.setVocab(key.getVocab());
cloneKey.setVocabURI(key.getVocabURI());
this.getStudyKeywords().add(cloneKey);
}
}
if (copyField(tfMap.get(StudyFieldConstant.notesInformationType), copyHidden, copyDisabled)) {
this.setStudyNotes(new ArrayList<StudyNote>());
for (StudyNote note : source.studyNotes) {
StudyNote cloneNote = new StudyNote();
cloneNote.setDisplayOrder(note.getDisplayOrder());
cloneNote.setMetadata(this);
cloneNote.setSubject(note.getSubject());
cloneNote.setText(note.getText());
cloneNote.setType(note.getType());
this.getStudyNotes().add(cloneNote);
}
}
if (copyField(tfMap.get(StudyFieldConstant.otherId), copyHidden, copyDisabled)) {
this.setStudyOtherIds(new ArrayList<StudyOtherId>());
for (StudyOtherId id : source.studyOtherIds) {
StudyOtherId cloneId = new StudyOtherId();
cloneId.setAgency(id.getAgency());
cloneId.setDisplayOrder(id.getDisplayOrder());
cloneId.setMetadata(this);
cloneId.setOtherId(id.getOtherId());
this.getStudyOtherIds().add(cloneId);
}
}
if (copyField(tfMap.get(StudyFieldConstant.otherReferences), copyHidden, copyDisabled)) {
this.setStudyOtherRefs(new ArrayList<StudyOtherRef>());
for (StudyOtherRef ref : source.studyOtherRefs) {
StudyOtherRef cloneRef = new StudyOtherRef();
cloneRef.setDisplayOrder(ref.getDisplayOrder());
cloneRef.setMetadata(this);
cloneRef.setText(ref.getText());
this.getStudyOtherRefs().add(cloneRef);
}
}
if (copyField(tfMap.get(StudyFieldConstant.producerName), copyHidden, copyDisabled)) {
this.setStudyProducers(new ArrayList<StudyProducer>());
for (StudyProducer prod : source.studyProducers) {
StudyProducer cloneProd = new StudyProducer();
cloneProd.setAbbreviation(prod.getAbbreviation());
cloneProd.setAffiliation(prod.getAffiliation());
cloneProd.setDisplayOrder(prod.getDisplayOrder());
cloneProd.setLogo(prod.getLogo());
cloneProd.setMetadata(this);
cloneProd.setName(prod.getName());
cloneProd.setUrl(prod.getUrl());
this.getStudyProducers().add(cloneProd);
}
}
if (copyField(tfMap.get(StudyFieldConstant.relatedMaterial), copyHidden, copyDisabled)) {
this.setStudyRelMaterials(new ArrayList<StudyRelMaterial>());
for (StudyRelMaterial rel : source.studyRelMaterials) {
StudyRelMaterial cloneRel = new StudyRelMaterial();
cloneRel.setDisplayOrder(rel.getDisplayOrder());
cloneRel.setMetadata(this);
cloneRel.setText(rel.getText());
this.getStudyRelMaterials().add(cloneRel);
}
}
if (copyField(tfMap.get(StudyFieldConstant.relatedPublications), copyHidden, copyDisabled)) {
this.setStudyRelPublications(new ArrayList<StudyRelPublication>());
for (StudyRelPublication rel : source.studyRelPublications) {
StudyRelPublication cloneRel = new StudyRelPublication();
cloneRel.setDisplayOrder(rel.getDisplayOrder());
cloneRel.setMetadata(this);
cloneRel.setText(rel.getText());
this.getStudyRelPublications().add(cloneRel);
}
}
if (copyField(tfMap.get(StudyFieldConstant.relatedStudies), copyHidden, copyDisabled)) {
this.setStudyRelStudies(new ArrayList<StudyRelStudy>());
for (StudyRelStudy rel : source.studyRelStudies) {
StudyRelStudy cloneRel = new StudyRelStudy();
cloneRel.setDisplayOrder(rel.getDisplayOrder());
cloneRel.setMetadata(this);
cloneRel.setText(rel.getText());
this.getStudyRelStudies().add(cloneRel);
}
}
if (copyField(tfMap.get(StudyFieldConstant.softwareName), copyHidden, copyDisabled)) {
this.setStudySoftware(new ArrayList<StudySoftware>());
for (StudySoftware soft : source.studySoftware) {
StudySoftware cloneSoft = new StudySoftware();
cloneSoft.setDisplayOrder(soft.getDisplayOrder());
cloneSoft.setMetadata(this);
cloneSoft.setName(soft.getName());
cloneSoft.setSoftwareVersion(soft.getSoftwareVersion());
this.getStudySoftware().add(cloneSoft);
}
}
if (copyField(tfMap.get(StudyFieldConstant.topicClassValue), copyHidden, copyDisabled)) {
this.setStudyTopicClasses(new ArrayList<StudyTopicClass>());
for (StudyTopicClass topic : source.studyTopicClasses) {
StudyTopicClass cloneTopic = new StudyTopicClass();
cloneTopic.setDisplayOrder(topic.getDisplayOrder());
cloneTopic.setMetadata(this);
cloneTopic.setValue(topic.getValue());
cloneTopic.setVocab(topic.getVocab());
cloneTopic.setVocabURI(topic.getVocabURI());
this.getStudyTopicClasses().add(cloneTopic);
}
}
// custom values
for (StudyField sf : source.getStudyFields()) {
if( copyField(tfMap.get(sf.getName()), copyHidden, copyDisabled) ) {
for (StudyFieldValue sfv: sf.getStudyFieldValues()){
StudyFieldValue cloneSfv = new StudyFieldValue();
cloneSfv.setDisplayOrder(sfv.getDisplayOrder());
cloneSfv.setStudyField(sfv.getStudyField());
cloneSfv.setStrValue(sfv.getStrValue());
cloneSfv.setMetadata(this);
this.getStudyFieldValues().add(cloneSfv);
}
}
}
}
// This constructor is for an exact clone, regarldes of field input levels
public Metadata(Metadata source ) {
this.setUNF(source.UNF);
this.setAccessToSources(source.accessToSources);
this.setActionsToMinimizeLoss(source.actionsToMinimizeLoss);
this.setAvailabilityStatus(source.availabilityStatus);
this.setCharacteristicOfSources(source.characteristicOfSources);
this.setCitationRequirements(source.citationRequirements);
this.setCleaningOperations(source.cleaningOperations);
this.setCollectionMode(source.collectionMode);
this.setCollectionSize(source.collectionSize);
this.setConditions(source.conditions);
this.setConfidentialityDeclaration(source.confidentialityDeclaration);
this.setContact(source.contact);
this.setControlOperations(source.controlOperations);
this.setCountry(source.country);
this.setDataCollectionSituation(source.dataCollectionSituation);
this.setDataCollector(source.dataCollector);
this.setDataSources(source.dataSources);
this.setDateOfCollectionEnd(source.dateOfCollectionEnd);
this.setDateOfCollectionStart(source.dateOfCollectionStart);
this.setDateOfDeposit(source.dateOfDeposit);
this.setDepositor(source.depositor);
this.setDepositorRequirements(source.depositorRequirements);
this.setDeviationsFromSampleDesign(source.deviationsFromSampleDesign);
this.setDisclaimer(source.disclaimer);
this.setDistributionDate(source.distributionDate);
this.setDistributorContact(source.distributorContact);
this.setDistributorContactAffiliation(source.distributorContactAffiliation);
this.setDistributorContactEmail(source.distributorContactEmail);
this.setFrequencyOfDataCollection(source.frequencyOfDataCollection);
this.setFundingAgency(source.fundingAgency);
this.setGeographicCoverage(source.geographicCoverage);
this.setGeographicUnit(source.geographicUnit);
this.setKindOfData(source.kindOfData);
this.setOriginOfSources(source.originOfSources);
this.setOriginalArchive(source.originalArchive);
this.setOtherDataAppraisal(source.otherDataAppraisal);
this.setPlaceOfAccess(source.placeOfAccess);
this.setProductionDate(source.productionDate);
this.setProductionPlace(source.productionPlace);
this.setReplicationFor(source.replicationFor);
this.setResearchInstrument(source.researchInstrument);
this.setResponseRate(source.responseRate);
this.setRestrictions(source.restrictions);
this.setSamplingErrorEstimate(source.samplingErrorEstimate);
this.setSamplingProcedure(source.samplingProcedure);
this.setSeriesInformation(source.seriesInformation);
this.setSeriesName(source.seriesName);
this.setSpecialPermissions(source.specialPermissions);
this.setStudyVersionText(source.studyVersionText);
this.setSubTitle(source.subTitle);
this.setTimeMethod(source.timeMethod);
this.setTimePeriodCoveredEnd(source.timePeriodCoveredEnd);
this.setTimePeriodCoveredStart(source.timePeriodCoveredStart);
this.setTitle(source.title);
this.setUnitOfAnalysis(source.unitOfAnalysis);
this.setUniverse(source.universe);
this.setVersionDate(source.versionDate);
this.setWeighting(source.weighting);
this.setStudyLevelErrorNotes(source.studyLevelErrorNotes);
this.setStudyCompletion(source.studyCompletion);
this.setStudyAbstracts(new ArrayList<StudyAbstract>());
for(StudyAbstract sa: source.studyAbstracts) {
StudyAbstract cloneAbstract = new StudyAbstract();
cloneAbstract.setDate(sa.getDate());
cloneAbstract.setDisplayOrder(sa.getDisplayOrder());
cloneAbstract.setMetadata(this);
cloneAbstract.setText(sa.getText());
this.getStudyAbstracts().add(cloneAbstract);
}
this.setStudyAuthors(new ArrayList<StudyAuthor>());
for (StudyAuthor author: source.studyAuthors) {
StudyAuthor cloneAuthor = new StudyAuthor();
cloneAuthor.setAffiliation(author.getAffiliation());
cloneAuthor.setDisplayOrder(author.getDisplayOrder());
cloneAuthor.setMetadata(this);
cloneAuthor.setName(author.getName());
this.getStudyAuthors().add(cloneAuthor);
}
this.setStudyDistributors(new ArrayList<StudyDistributor>());
for (StudyDistributor dist: source.studyDistributors){
StudyDistributor cloneDist = new StudyDistributor();
cloneDist.setAbbreviation(dist.getAbbreviation());
cloneDist.setAffiliation(dist.getAffiliation());
cloneDist.setDisplayOrder(dist.getDisplayOrder());
cloneDist.setMetadata(this);
cloneDist.setLogo(dist.getLogo());
cloneDist.setName(dist.getName());
cloneDist.setUrl(dist.getUrl());
this.getStudyDistributors().add(cloneDist);
}
this.setStudyGeoBoundings(new ArrayList<StudyGeoBounding>());
for(StudyGeoBounding geo: source.studyGeoBoundings) {
StudyGeoBounding cloneGeo = new StudyGeoBounding();
cloneGeo.setDisplayOrder(geo.getDisplayOrder());
cloneGeo.setMetadata(this);
cloneGeo.setEastLongitude(geo.getEastLongitude());
cloneGeo.setNorthLatitude(geo.getNorthLatitude());
cloneGeo.setSouthLatitude(geo.getSouthLatitude());
cloneGeo.setWestLongitude(geo.getWestLongitude());
this.getStudyGeoBoundings().add(cloneGeo);
}
this.setStudyGrants(new ArrayList<StudyGrant>());
for(StudyGrant grant: source.studyGrants) {
StudyGrant cloneGrant = new StudyGrant();
cloneGrant.setAgency(grant.getAgency());
cloneGrant.setDisplayOrder(grant.getDisplayOrder());
cloneGrant.setMetadata(this);
cloneGrant.setNumber(grant.getNumber());
this.getStudyGrants().add(cloneGrant);
}
this.setStudyKeywords(new ArrayList<StudyKeyword>());
for(StudyKeyword key: source.studyKeywords) {
StudyKeyword cloneKey = new StudyKeyword();
cloneKey.setDisplayOrder(key.getDisplayOrder());
cloneKey.setMetadata(this);
cloneKey.setValue(key.getValue());
cloneKey.setVocab(key.getVocab());
cloneKey.setVocabURI(key.getVocabURI());
this.getStudyKeywords().add(cloneKey);
}
this.setStudyNotes(new ArrayList<StudyNote>());
for(StudyNote note: source.studyNotes) {
StudyNote cloneNote = new StudyNote();
cloneNote.setDisplayOrder(note.getDisplayOrder());
cloneNote.setMetadata(this);
cloneNote.setSubject(note.getSubject());
cloneNote.setText(note.getText());
cloneNote.setType(note.getType());
this.getStudyNotes().add(cloneNote);
}
this.setStudyOtherIds(new ArrayList<StudyOtherId>());
for(StudyOtherId id: source.studyOtherIds) {
StudyOtherId cloneId = new StudyOtherId();
cloneId.setAgency(id.getAgency());
cloneId.setDisplayOrder(id.getDisplayOrder());
cloneId.setMetadata(this);
cloneId.setOtherId(id.getOtherId());
this.getStudyOtherIds().add(cloneId);
}
this.setStudyOtherRefs(new ArrayList<StudyOtherRef>());
for(StudyOtherRef ref: source.studyOtherRefs) {
StudyOtherRef cloneRef = new StudyOtherRef();
cloneRef.setDisplayOrder(ref.getDisplayOrder());
cloneRef.setMetadata(this);
cloneRef.setText(ref.getText());
this.getStudyOtherRefs().add(cloneRef);
}
this.setStudyProducers(new ArrayList<StudyProducer>());
for(StudyProducer prod: source.studyProducers) {
StudyProducer cloneProd = new StudyProducer();
cloneProd.setAbbreviation(prod.getAbbreviation());
cloneProd.setAffiliation(prod.getAffiliation());
cloneProd.setDisplayOrder(prod.getDisplayOrder());
cloneProd.setLogo(prod.getLogo());
cloneProd.setMetadata(this);
cloneProd.setName(prod.getName());
cloneProd.setUrl(prod.getUrl());
this.getStudyProducers().add(cloneProd);
}
this.setStudyRelMaterials(new ArrayList<StudyRelMaterial>());
for(StudyRelMaterial rel: source.studyRelMaterials) {
StudyRelMaterial cloneRel = new StudyRelMaterial();
cloneRel.setDisplayOrder(rel.getDisplayOrder());
cloneRel.setMetadata(this);
cloneRel.setText(rel.getText());
this.getStudyRelMaterials().add(cloneRel);
}
this.setStudyRelPublications(new ArrayList<StudyRelPublication>());
for(StudyRelPublication rel: source.studyRelPublications){
StudyRelPublication cloneRel = new StudyRelPublication();
cloneRel.setDisplayOrder(rel.getDisplayOrder());
cloneRel.setMetadata(this);
cloneRel.setText(rel.getText());
this.getStudyRelPublications().add(cloneRel);
}
this.setStudyRelStudies(new ArrayList<StudyRelStudy>());
for(StudyRelStudy rel: source.studyRelStudies){
StudyRelStudy cloneRel = new StudyRelStudy();
cloneRel.setDisplayOrder(rel.getDisplayOrder());
cloneRel.setMetadata(this);
cloneRel.setText(rel.getText());
this.getStudyRelStudies().add(cloneRel);
}
this.setStudySoftware(new ArrayList<StudySoftware>());
for(StudySoftware soft: source.studySoftware){
StudySoftware cloneSoft = new StudySoftware();
cloneSoft.setDisplayOrder(soft.getDisplayOrder());
cloneSoft.setMetadata(this);
cloneSoft.setName(soft.getName());
cloneSoft.setSoftwareVersion(soft.getSoftwareVersion());
this.getStudySoftware().add(cloneSoft);
}
this.setStudyTopicClasses(new ArrayList<StudyTopicClass>());
for (StudyTopicClass topic: source.studyTopicClasses){
StudyTopicClass cloneTopic = new StudyTopicClass();
cloneTopic.setDisplayOrder(topic.getDisplayOrder());
cloneTopic.setMetadata(this);
cloneTopic.setValue(topic.getValue());
cloneTopic.setVocab(topic.getVocab());
cloneTopic.setVocabURI(topic.getVocabURI());
this.getStudyTopicClasses().add(cloneTopic);
}
this.setStudyFieldValues(new ArrayList<StudyFieldValue>());
for (StudyFieldValue sfv: source.getStudyFieldValues()){
StudyFieldValue cloneSfv = new StudyFieldValue();
cloneSfv.setDisplayOrder(sfv.getDisplayOrder());
cloneSfv.setStudyField(sfv.getStudyField());
cloneSfv.setStrValue(sfv.getStrValue());
cloneSfv.setMetadata(this);
this.getStudyFieldValues().add(cloneSfv);
}
}
public String getAuthorsStr() {
return getAuthorsStr(true);
}
public String getAuthorsStr(boolean affiliation) {
String str="";
for (Iterator<StudyAuthor> it = getStudyAuthors().iterator(); it.hasNext();) {
StudyAuthor sa = it.next();
if (str.trim().length()>1) {
str+="; ";
}
str += sa.getName();
if (affiliation) {
if (!StringUtil.isEmpty(sa.getAffiliation())) {
str+=" ("+sa.getAffiliation()+")";
}
}
}
return str;
}
public String getDistributorNames() {
String str="";
for (Iterator<StudyDistributor> it = this.getStudyDistributors().iterator(); it.hasNext();) {
StudyDistributor sd = it.next();
if (str.trim().length()>1) {
str+=";";
}
str += sd.getName();
}
return str;
}
@Column(columnDefinition="TEXT")
private String UNF;
public String getUNF() {
return UNF;
}
public void setUNF(String UNF) {
this.UNF=UNF;
}
@Column(columnDefinition="TEXT")
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@OneToMany (mappedBy="metadata", cascade={ CascadeType.REMOVE, CascadeType.MERGE,CascadeType.PERSIST})
@OrderBy ("displayOrder")
private List<StudyFieldValue> studyFieldValues;
public List<StudyFieldValue> getStudyFieldValues() {
return studyFieldValues;
}
public void setStudyFieldValues(List<StudyFieldValue> studyFieldValues) {
this.studyFieldValues = studyFieldValues;
}
@OneToMany(mappedBy="metadata", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST})
@OrderBy("displayOrder")
private java.util.List<StudyAuthor> studyAuthors;
public java.util.List<StudyAuthor> getStudyAuthors() {
return studyAuthors;
}
public void setStudyAuthors(java.util.List<StudyAuthor> studyAuthors) {
this.studyAuthors = studyAuthors;
}
@OneToMany(mappedBy="metadata", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST})
@OrderBy("displayOrder")
private java.util.List<StudyKeyword> studyKeywords;
public java.util.List<StudyKeyword> getStudyKeywords() {
return studyKeywords;
}
public void setStudyKeywords(java.util.List<StudyKeyword> studyKeywords) {
this.studyKeywords = studyKeywords;
}
/**
* Holds value of property version.
*/
@Version
private Long version;
/**
* Getter for property version.
* @return Value of property version.
*/
public Long getVersion() {
return this.version;
}
/**
* Setter for property version.
* @param version New value of property version.
*/
public void setVersion(Long version) {
this.version = version;
}
/**
* Holds value of property studyProducers.
*/
@OneToMany(mappedBy="metadata", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST})
@OrderBy("displayOrder")
private List<StudyProducer> studyProducers;
/**
* Getter for property studyProducers.
* @return Value of property studyProducers.
*/
public List<StudyProducer> getStudyProducers() {
return this.studyProducers;
}
/**
* Setter for property studyProducers.
* @param studyProducers New value of property studyProducers.
*/
public void setStudyProducers(List<StudyProducer> studyProducers) {
this.studyProducers = studyProducers;
}
/**
* Holds value of property studySoftware.
*/
@OneToMany(mappedBy="metadata", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST})
@OrderBy("displayOrder")
private List<StudySoftware> studySoftware;
/**
* Getter for property studySoftware.
* @return Value of property studySoftware.
*/
public List<StudySoftware> getStudySoftware() {
return this.studySoftware;
}
/**
* Setter for property studySoftware.
* @param studySoftware New value of property studySoftware.
*/
public void setStudySoftware(List<StudySoftware> studySoftware) {
this.studySoftware = studySoftware;
}
/**
* Holds value of property studyDistributors.
*/
@OneToMany(mappedBy="metadata", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST})
@OrderBy("displayOrder")
private List<StudyDistributor> studyDistributors;
/**
* Getter for property studyDistributors.
* @return Value of property studyDistributors.
*/
public List<StudyDistributor> getStudyDistributors() {
return this.studyDistributors;
}
/**
* Setter for property studyDistributors.
* @param studyDistributors New value of property studyDistributors.
*/
public void setStudyDistributors(List<StudyDistributor> studyDistributors) {
this.studyDistributors = studyDistributors;
}
/**
* Holds value of property studyTopicClasses.
*/
@OneToMany(mappedBy="metadata", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST})
@OrderBy("displayOrder")
private List<StudyTopicClass> studyTopicClasses;
/**
* Getter for property studyTopicClasses.
* @return Value of property studyTopicClasses.
*/
public List<StudyTopicClass> getStudyTopicClasses() {
return this.studyTopicClasses;
}
/**
* Setter for property studyTopicClasses.
* @param studyTopicClasses New value of property studyTopicClasses.
*/
public void setStudyTopicClasses(List<StudyTopicClass> studyTopicClasses) {
this.studyTopicClasses = studyTopicClasses;
}
/**
* Holds value of property studyAbstracts.
*/
@OneToMany(mappedBy="metadata", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST})
@OrderBy("displayOrder")
private List<StudyAbstract> studyAbstracts;
/**
* Getter for property studyAbstracts.
* @return Value of property studyAbstracts.
*/
public List<StudyAbstract> getStudyAbstracts() {
return this.studyAbstracts;
}
/**
* Setter for property studyAbstracts.
* @param studyAbstracts New value of property studyAbstracts.
*/
public void setStudyAbstracts(List<StudyAbstract> studyAbstracts) {
this.studyAbstracts = studyAbstracts;
}
/**
* Holds value of property studyNotes.
*/
@OneToMany(mappedBy="metadata", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST})
@OrderBy("displayOrder")
private List<StudyNote> studyNotes;
/**
* Getter for property studyNotes.
* @return Value of property studyNotes.
*/
public List<StudyNote> getStudyNotes() {
return this.studyNotes;
}
/**
* Setter for property studyNotes.
* @param studyNotes New value of property studyNotes.
*/
public void setStudyNotes(List<StudyNote> studyNotes) {
this.studyNotes = studyNotes;
}
/**
* Holds value of property fundingAgency.
*/
@Column(columnDefinition="TEXT")
private String fundingAgency;
/**
* Getter for property fundingAgency.
* @return Value of property fundingAgency.
*/
public String getFundingAgency() {
return this.fundingAgency;
}
/**
* Setter for property fundingAgency.
* @param fundingAgency New value of property fundingAgency.
*/
public void setFundingAgency(String fundingAgency) {
this.fundingAgency = fundingAgency;
}
/**
* Holds value of property seriesName.
*/
@Column(columnDefinition="TEXT")
private String seriesName;
/**
* Getter for property seriesName.
* @return Value of property seriesName.
*/
public String getSeriesName() {
return this.seriesName;
}
/**
* Setter for property seriesName.
* @param seriesName New value of property seriesName.
*/
public void setSeriesName(String seriesName) {
this.seriesName = seriesName;
}
/**
* Holds value of property seriesInformation.
*/
@Column(columnDefinition="TEXT")
private String seriesInformation;
/**
* Getter for property seriesInformation.
* @return Value of property seriesInformation.
*/
public String getSeriesInformation() {
return this.seriesInformation;
}
/**
* Setter for property seriesInformation.
* @param seriesInformation New value of property seriesInformation.
*/
public void setSeriesInformation(String seriesInformation) {
this.seriesInformation = seriesInformation;
}
/**
* Holds value of property studyVersion.
*/
@Column(name="studyVersion",columnDefinition="TEXT")
private String studyVersionText;
/**
* Getter for property studyVersion.
* @return Value of property studyVersion.
*/
public String getStudyVersionText() {
return this.studyVersionText;
}
/**
* Setter for property studyVersion.
* @param studyVersion New value of property studyVersion.
*/
public void setStudyVersionText(String studyVersionText) {
this.studyVersionText = studyVersionText;
}
/**
* Holds value of property timePeriodCoveredStart.
*/
@Column(columnDefinition="TEXT")
private String timePeriodCoveredStart;
/**
* Getter for property timePeriodCoveredStart.
* @return Value of property timePeriodCoveredStart.
*/
public String getTimePeriodCoveredStart() {
return this.timePeriodCoveredStart;
}
/**
* Setter for property timePeriodCoveredStart.
* @param timePeriodCoveredStart New value of property timePeriodCoveredStart.
*/
public void setTimePeriodCoveredStart(String timePeriodCoveredStart) {
this.timePeriodCoveredStart = timePeriodCoveredStart;
}
/**
* Holds value of property timePeriodCoveredEnd.
*/
@Column(columnDefinition="TEXT")
private String timePeriodCoveredEnd;
/**
* Getter for property timePeriodCoveredEnd.
* @return Value of property timePeriodCoveredEnd.
*/
public String getTimePeriodCoveredEnd() {
return this.timePeriodCoveredEnd;
}
/**
* Setter for property timePeriodCoveredEnd.
* @param timePeriodCoveredEnd New value of property timePeriodCoveredEnd.
*/
public void setTimePeriodCoveredEnd(String timePeriodCoveredEnd) {
this.timePeriodCoveredEnd = timePeriodCoveredEnd;
}
/**
* Holds value of property dateOfCollectionStart.
*/
@Column(columnDefinition="TEXT")
private String dateOfCollectionStart;
/**
* Getter for property dateOfCollectionStart.
* @return Value of property dateOfCollectionStart.
*/
public String getDateOfCollectionStart() {
return this.dateOfCollectionStart;
}
/**
* Setter for property dateOfCollectionStart.
* @param dateOfCollectionStart New value of property dateOfCollectionStart.
*/
public void setDateOfCollectionStart(String dateOfCollectionStart) {
this.dateOfCollectionStart = dateOfCollectionStart;
}
/**
* Holds value of property dateOfCollectionEnd.
*/
@Column(columnDefinition="TEXT")
private String dateOfCollectionEnd;
/**
* Getter for property dateOfCollectionEnd.
* @return Value of property dateOfCollectionEnd.
*/
public String getDateOfCollectionEnd() {
return this.dateOfCollectionEnd;
}
/**
* Setter for property dateOfCollectionEnd.
* @param dateOfCollectionEnd New value of property dateOfCollectionEnd.
*/
public void setDateOfCollectionEnd(String dateOfCollectionEnd) {
this.dateOfCollectionEnd = dateOfCollectionEnd;
}
/**
* Holds value of property country.
*/
@Column(columnDefinition="TEXT")
private String country;
/**
* Getter for property country.
* @return Value of property country.
*/
public String getCountry() {
return this.country;
}
/**
* Setter for property country.
* @param country New value of property country.
*/
public void setCountry(String country) {
this.country = country;
}
/**
* Holds value of property geographicCoverage.
*/
@Column(columnDefinition="TEXT")
private String geographicCoverage;
/**
* Getter for property geographicCoverage.
* @return Value of property geographicCoverage.
*/
public String getGeographicCoverage() {
return this.geographicCoverage;
}
/**
* Setter for property geographicCoverage.
* @param geographicCoverage New value of property geographicCoverage.
*/
public void setGeographicCoverage(String geographicCoverage) {
this.geographicCoverage = geographicCoverage;
}
/**
* Holds value of property geographicUnit.
*/
@Column(columnDefinition="TEXT")
private String geographicUnit;
/**
* Getter for property geographicUnit.
* @return Value of property geographicUnit.
*/
public String getGeographicUnit() {
return this.geographicUnit;
}
/**
* Setter for property geographicUnit.
* @param geographicUnit New value of property geographicUnit.
*/
public void setGeographicUnit(String geographicUnit) {
this.geographicUnit = geographicUnit;
}
/**
* Holds value of property unitOfAnalysis.
*/
@Column(columnDefinition="TEXT")
private String unitOfAnalysis;
/**
* Getter for property unitOfAnalysis.
* @return Value of property unitOfAnalysis.
*/
public String getUnitOfAnalysis() {
return this.unitOfAnalysis;
}
/**
* Setter for property unitOfAnalysis.
* @param unitOfAnalysis New value of property unitOfAnalysis.
*/
public void setUnitOfAnalysis(String unitOfAnalysis) {
this.unitOfAnalysis = unitOfAnalysis;
}
/**
* Holds value of property universe.
*/
@Column(columnDefinition="TEXT")
private String universe;
/**
* Getter for property universe.
* @return Value of property universe.
*/
public String getUniverse() {
return this.universe;
}
/**
* Setter for property universe.
* @param universe New value of property universe.
*/
public void setUniverse(String universe) {
this.universe = universe;
}
/**
* Holds value of property kindOfData.
*/
@Column(columnDefinition="TEXT")
private String kindOfData;
/**
* Getter for property kindOfData.
* @return Value of property kindOfData.
*/
public String getKindOfData() {
return this.kindOfData;
}
/**
* Setter for property kindOfData.
* @param kindOfData New value of property kindOfData.
*/
public void setKindOfData(String kindOfData) {
this.kindOfData = kindOfData;
}
/**
* Holds value of property timeMethod.
*/
@Column(columnDefinition="TEXT")
private String timeMethod;
/**
* Getter for property timeMethod.
* @return Value of property timeMethod.
*/
public String getTimeMethod() {
return this.timeMethod;
}
/**
* Setter for property timeMethod.
* @param timeMethod New value of property timeMethod.
*/
public void setTimeMethod(String timeMethod) {
this.timeMethod = timeMethod;
}
/**
* Holds value of property dataCollector.
*/
@Column(columnDefinition="TEXT")
private String dataCollector;
/**
* Getter for property dataCollector.
* @return Value of property dataCollector.
*/
public String getDataCollector() {
return this.dataCollector;
}
/**
* Setter for property dataCollector.
* @param dataCollector New value of property dataCollector.
*/
public void setDataCollector(String dataCollector) {
this.dataCollector = dataCollector;
}
/**
* Holds value of property frequencyOfDataCollection.
*/
@Column(columnDefinition="TEXT")
private String frequencyOfDataCollection;
/**
* Getter for property frequencyOfDataCollection.
* @return Value of property frequencyOfDataCollection.
*/
public String getFrequencyOfDataCollection() {
return this.frequencyOfDataCollection;
}
/**
* Setter for property frequencyOfDataCollection.
* @param frequencyOfDataCollection New value of property frequencyOfDataCollection.
*/
public void setFrequencyOfDataCollection(String frequencyOfDataCollection) {
this.frequencyOfDataCollection = frequencyOfDataCollection;
}
/**
* Holds value of property samplingProcedure.
*/
@Column(columnDefinition="TEXT")
private String samplingProcedure;
/**
* Getter for property samplingProdedure.
* @return Value of property samplingProdedure.
*/
public String getSamplingProcedure() {
return this.samplingProcedure;
}
/**
* Setter for property samplingProdedure.
* @param samplingProdedure New value of property samplingProdedure.
*/
public void setSamplingProcedure(String samplingProcedure) {
this.samplingProcedure = samplingProcedure;
}
/**
* Holds value of property deviationsFromSampleDesign.
*/
@Column(columnDefinition="TEXT")
private String deviationsFromSampleDesign;
/**
* Getter for property deviationsFromSampleDesign.
* @return Value of property deviationsFromSampleDesign.
*/
public String getDeviationsFromSampleDesign() {
return this.deviationsFromSampleDesign;
}
/**
* Setter for property deviationsFromSampleDesign.
* @param deviationsFromSampleDesign New value of property deviationsFromSampleDesign.
*/
public void setDeviationsFromSampleDesign(String deviationsFromSampleDesign) {
this.deviationsFromSampleDesign = deviationsFromSampleDesign;
}
/**
* Holds value of property collectionMode.
*/
@Column(columnDefinition="TEXT")
private String collectionMode;
/**
* Getter for property collectionMode.
* @return Value of property collectionMode.
*/
public String getCollectionMode() {
return this.collectionMode;
}
/**
* Setter for property collectionMode.
* @param collectionMode New value of property collectionMode.
*/
public void setCollectionMode(String collectionMode) {
this.collectionMode = collectionMode;
}
/**
* Holds value of property researchInstrument.
*/
@Column(columnDefinition="TEXT")
private String researchInstrument;
/**
* Getter for property researchInstrument.
* @return Value of property researchInstrument.
*/
public String getResearchInstrument() {
return this.researchInstrument;
}
/**
* Setter for property researchInstrument.
* @param researchInstrument New value of property researchInstrument.
*/
public void setResearchInstrument(String researchInstrument) {
this.researchInstrument = researchInstrument;
}
/**
* Holds value of property dataSources.
*/
@Column(columnDefinition="TEXT")
private String dataSources;
/**
* Getter for property dataSources.
* @return Value of property dataSources.
*/
public String getDataSources() {
return this.dataSources;
}
/**
* Setter for property dataSources.
* @param dataSources New value of property dataSources.
*/
public void setDataSources(String dataSources) {
this.dataSources = dataSources;
}
/**
* Holds value of property originOfSources.
*/
@Column(columnDefinition="TEXT")
private String originOfSources;
/**
* Getter for property originOfSources.
* @return Value of property originOfSources.
*/
public String getOriginOfSources() {
return this.originOfSources;
}
/**
* Setter for property originOfSources.
* @param originOfSources New value of property originOfSources.
*/
public void setOriginOfSources(String originOfSources) {
this.originOfSources = originOfSources;
}
/**
* Holds value of property characteristicOfSources.
*/
@Column(columnDefinition="TEXT")
private String characteristicOfSources;
/**
* Getter for property characteristicOfSources.
* @return Value of property characteristicOfSources.
*/
public String getCharacteristicOfSources() {
return this.characteristicOfSources;
}
/**
* Setter for property characteristicOfSources.
* @param characteristicOfSources New value of property characteristicOfSources.
*/
public void setCharacteristicOfSources(String characteristicOfSources) {
this.characteristicOfSources = characteristicOfSources;
}
/**
* Holds value of property accessToSources.
*/
@Column(columnDefinition="TEXT")
private String accessToSources;
/**
* Getter for property accessToSources.
* @return Value of property accessToSources.
*/
public String getAccessToSources() {
return this.accessToSources;
}
/**
* Setter for property accessToSources.
* @param accessToSources New value of property accessToSources.
*/
public void setAccessToSources(String accessToSources) {
this.accessToSources = accessToSources;
}
/**
* Holds value of property dataCollectionSituation.
*/
@Column(columnDefinition="TEXT")
private String dataCollectionSituation;
/**
* Getter for property dataCollectionSituation.
* @return Value of property dataCollectionSituation.
*/
public String getDataCollectionSituation() {
return this.dataCollectionSituation;
}
/**
* Setter for property dataCollectionSituation.
* @param dataCollectionSituation New value of property dataCollectionSituation.
*/
public void setDataCollectionSituation(String dataCollectionSituation) {
this.dataCollectionSituation = dataCollectionSituation;
}
/**
* Holds value of property actionsToMinimizeLoss.
*/
@Column(columnDefinition="TEXT")
private String actionsToMinimizeLoss;
/**
* Getter for property actionsToMinimizeLoss.
* @return Value of property actionsToMinimizeLoss.
*/
public String getActionsToMinimizeLoss() {
return this.actionsToMinimizeLoss;
}
/**
* Setter for property actionsToMinimizeLoss.
* @param actionsToMinimizeLoss New value of property actionsToMinimizeLoss.
*/
public void setActionsToMinimizeLoss(String actionsToMinimizeLoss) {
this.actionsToMinimizeLoss = actionsToMinimizeLoss;
}
/**
* Holds value of property controlOperations.
*/
@Column(columnDefinition="TEXT")
private String controlOperations;
/**
* Getter for property controlOperations.
* @return Value of property controlOperations.
*/
public String getControlOperations() {
return this.controlOperations;
}
/**
* Setter for property controlOperations.
* @param controlOperations New value of property controlOperations.
*/
public void setControlOperations(String controlOperations) {
this.controlOperations = controlOperations;
}
/**
* Holds value of property weighting.
*/
@Column(columnDefinition="TEXT")
private String weighting;
/**
* Getter for property weighting.
* @return Value of property weighting.
*/
public String getWeighting() {
return this.weighting;
}
/**
* Setter for property weighting.
* @param weighting New value of property weighting.
*/
public void setWeighting(String weighting) {
this.weighting = weighting;
}
/**
* Holds value of property cleaningOperations.
*/
@Column(columnDefinition="TEXT")
private String cleaningOperations;
/**
* Getter for property cleaningOperations.
* @return Value of property cleaningOperations.
*/
public String getCleaningOperations() {
return this.cleaningOperations;
}
/**
* Setter for property cleaningOperations.
* @param cleaningOperations New value of property cleaningOperations.
*/
public void setCleaningOperations(String cleaningOperations) {
this.cleaningOperations = cleaningOperations;
}
/**
* Holds value of property studyLevelErrorNotes.
*/
@Column(columnDefinition="TEXT")
private String studyLevelErrorNotes;
/**
* Getter for property studyLevelErrorNotes.
* @return Value of property studyLevelErrorNotes.
*/
public String getStudyLevelErrorNotes() {
return this.studyLevelErrorNotes;
}
/**
* Setter for property studyLevelErrorNotes.
* @param studyLevelErrorNotes New value of property studyLevelErrorNotes.
*/
public void setStudyLevelErrorNotes(String studyLevelErrorNotes) {
this.studyLevelErrorNotes = studyLevelErrorNotes;
}
/**
* Holds value of property responseRate.
*/
@Column(columnDefinition="TEXT")
private String responseRate;
/**
* Getter for property responseRate.
* @return Value of property responseRate.
*/
public String getResponseRate() {
return this.responseRate;
}
/**
* Setter for property responseRate.
* @param responseRate New value of property responseRate.
*/
public void setResponseRate(String responseRate) {
this.responseRate = responseRate;
}
/**
* Holds value of property samplingErrorEstimate.
*/
@Column(columnDefinition="TEXT")
private String samplingErrorEstimate;
/**
* Getter for property samplingErrorEstimate.
* @return Value of property samplingErrorEstimate.
*/
public String getSamplingErrorEstimate() {
return this.samplingErrorEstimate;
}
/**
* Setter for property samplingErrorEstimate.
* @param samplingErrorEstimate New value of property samplingErrorEstimate.
*/
public void setSamplingErrorEstimate(String samplingErrorEstimate) {
this.samplingErrorEstimate = samplingErrorEstimate;
}
/**
* Holds value of property otherDataAppraisal.
*/
@Column(columnDefinition="TEXT")
private String otherDataAppraisal;
/**
* Getter for property dataAppraisal.
* @return Value of property dataAppraisal.
*/
public String getOtherDataAppraisal() {
return this.otherDataAppraisal;
}
/**
* Setter for property dataAppraisal.
* @param dataAppraisal New value of property dataAppraisal.
*/
public void setOtherDataAppraisal(String otherDataAppraisal) {
this.otherDataAppraisal = otherDataAppraisal;
}
/**
* Holds value of property placeOfAccess.
*/
@Column(columnDefinition="TEXT")
private String placeOfAccess;
/**
* Getter for property placeOfAccess.
* @return Value of property placeOfAccess.
*/
public String getPlaceOfAccess() {
return this.placeOfAccess;
}
/**
* Setter for property placeOfAccess.
* @param placeOfAccess New value of property placeOfAccess.
*/
public void setPlaceOfAccess(String placeOfAccess) {
this.placeOfAccess = placeOfAccess;
}
/**
* Holds value of property originalArchive.
*/
@Column(columnDefinition="TEXT")
private String originalArchive;
/**
* Getter for property originalArchive.
* @return Value of property originalArchive.
*/
public String getOriginalArchive() {
return this.originalArchive;
}
/**
* Setter for property originalArchive.
* @param originalArchive New value of property originalArchive.
*/
public void setOriginalArchive(String originalArchive) {
this.originalArchive = originalArchive;
}
/**
* Holds value of property availabilityStatus.
*/
@Column(columnDefinition="TEXT")
private String availabilityStatus;
/**
* Getter for property availabilityStatus.
* @return Value of property availabilityStatus.
*/
public String getAvailabilityStatus() {
return this.availabilityStatus;
}
/**
* Setter for property availabilityStatus.
* @param availabilityStatus New value of property availabilityStatus.
*/
public void setAvailabilityStatus(String availabilityStatus) {
this.availabilityStatus = availabilityStatus;
}
/**
* Holds value of property collectionSize.
*/
@Column(columnDefinition="TEXT")
private String collectionSize;
/**
* Getter for property collectionSize.
* @return Value of property collectionSize.
*/
public String getCollectionSize() {
return this.collectionSize;
}
/**
* Setter for property collectionSize.
* @param collectionSize New value of property collectionSize.
*/
public void setCollectionSize(String collectionSize) {
this.collectionSize = collectionSize;
}
/**
* Holds value of property studyCompletion.
*/
@Column(columnDefinition="TEXT")
private String studyCompletion;
/**
* Getter for property studyCompletion.
* @return Value of property studyCompletion.
*/
public String getStudyCompletion() {
return this.studyCompletion;
}
/**
* Setter for property studyCompletion.
* @param studyCompletion New value of property studyCompletion.
*/
public void setStudyCompletion(String studyCompletion) {
this.studyCompletion = studyCompletion;
}
/**
* Holds value of property restrictions.
*/
@Column(columnDefinition="TEXT")
private String specialPermissions;
/**
* Getter for property specialPermissions.
* @return Value of property specialPermissions.
*/
public String getSpecialPermissions() {
return this.specialPermissions;
}
/**
* Setter for property specialPermissions.
* @param specialPermissions New value of property specialPermissions.
*/
public void setSpecialPermissions(String specialPermissions) {
this.specialPermissions = specialPermissions;
}
/**
* Holds value of property restrictions.
*/
@Column(columnDefinition="TEXT")
private String restrictions;
/**
* Getter for property restrictions.
* @return Value of property restrictions.
*/
public String getRestrictions() {
return this.restrictions;
}
/**
* Setter for property restrictions.
* @param restrictions New value of property restrictions.
*/
public void setRestrictions(String restrictions) {
this.restrictions = restrictions;
}
/**
* Holds value of property contact.
*/
@Column(columnDefinition="TEXT")
private String contact;
/**
* Getter for property contact.
* @return Value of property contact.
*/
public String getContact() {
return this.contact;
}
/**
* Setter for property contact.
* @param contact New value of property contact.
*/
public void setContact(String contact) {
this.contact = contact;
}
/**
* Holds value of property citationRequirements.
*/
@Column(columnDefinition="TEXT")
private String citationRequirements;
/**
* Getter for property citationRequirements.
* @return Value of property citationRequirements.
*/
public String getCitationRequirements() {
return this.citationRequirements;
}
/**
* Setter for property citationRequirements.
* @param citationRequirements New value of property citationRequirements.
*/
public void setCitationRequirements(String citationRequirements) {
this.citationRequirements = citationRequirements;
}
/**
* Holds value of property depositorRequirements.
*/
@Column(columnDefinition="TEXT")
private String depositorRequirements;
/**
* Getter for property dipositorRequirements.
* @return Value of property dipositorRequirements.
*/
public String getDepositorRequirements() {
return this.depositorRequirements;
}
/**
* Setter for property dipositorRequirements.
* @param dipositorRequirements New value of property dipositorRequirements.
*/
public void setDepositorRequirements(String depositorRequirements) {
this.depositorRequirements = depositorRequirements;
}
/**
* Holds value of property conditions.
*/
@Column(columnDefinition="TEXT")
private String conditions;
/**
* Getter for property conditions.
* @return Value of property conditions.
*/
public String getConditions() {
return this.conditions;
}
/**
* Setter for property conditions.
* @param conditions New value of property conditions.
*/
public void setConditions(String conditions) {
this.conditions = conditions;
}
/**
* Holds value of property disclaimer.
*/
@Column(columnDefinition="TEXT")
private String disclaimer;
/**
* Getter for property disclaimer.
* @return Value of property disclaimer.
*/
public String getDisclaimer() {
return this.disclaimer;
}
/**
* Setter for property disclaimer.
* @param disclaimer New value of property disclaimer.
*/
public void setDisclaimer(String disclaimer) {
this.disclaimer = disclaimer;
}
/**
* Holds value of property productionDate.
*/
@Column(columnDefinition="TEXT")
private String productionDate;
/**
* Getter for property productionDate.
* @return Value of property productionDate.
*/
public String getProductionDate() {
return this.productionDate;
}
/**
* Setter for property productionDate.
* @param productionDate New value of property productionDate.
*/
public void setProductionDate(String productionDate) {
this.productionDate = productionDate;
}
/**
* Holds value of property productionPlace.
*/
@Column(columnDefinition="TEXT")
private String productionPlace;
/**
* Getter for property productionPlace.
* @return Value of property productionPlace.
*/
public String getProductionPlace() {
return this.productionPlace;
}
/**
* Setter for property productionPlace.
* @param productionPlace New value of property productionPlace.
*/
public void setProductionPlace(String productionPlace) {
this.productionPlace = productionPlace;
}
/**
* Holds value of property confidentialityDeclaration.
*/
@Column(columnDefinition="TEXT")
private String confidentialityDeclaration;
/**
* Getter for property confidentialityDeclaration.
* @return Value of property confidentialityDeclaration.
*/
public String getConfidentialityDeclaration() {
return this.confidentialityDeclaration;
}
/**
* Setter for property confidentialityDeclaration.
* @param confidentialityDeclaration New value of property confidentialityDeclaration.
*/
public void setConfidentialityDeclaration(String confidentialityDeclaration) {
this.confidentialityDeclaration = confidentialityDeclaration;
}
/**
* Holds value of property studyGrants.
*/
@OneToMany(mappedBy="metadata", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST})
@OrderBy("displayOrder")
private List<StudyGrant> studyGrants;
/**
* Getter for property studyGrants.
* @return Value of property studyGrants.
*/
public List<StudyGrant> getStudyGrants() {
return this.studyGrants;
}
/**
* Setter for property studyGrants.
* @param studyGrants New value of property studyGrants.
*/
public void setStudyGrants(List<StudyGrant> studyGrants) {
this.studyGrants = studyGrants;
}
/**
* Holds value of property distributionDate.
*/
@Column(columnDefinition="TEXT")
private String distributionDate;
/**
* Getter for property distributionDate.
* @return Value of property distributionDate.
*/
public String getDistributionDate() {
return this.distributionDate;
}
/**
* Setter for property distributionDate.
* @param distributionDate New value of property distributionDate.
*/
public void setDistributionDate(String distributionDate) {
this.distributionDate = distributionDate;
}
/**
* Holds value of property distributorContact.
*/
@Column(columnDefinition="TEXT")
private String distributorContact;
/**
* Getter for property distributorContact.
* @return Value of property distributorContact.
*/
public String getDistributorContact() {
return this.distributorContact;
}
/**
* Setter for property distributorContact.
* @param distributorContact New value of property distributorContact.
*/
public void setDistributorContact(String distributorContact) {
this.distributorContact = distributorContact;
}
/**
* Holds value of property distributorContactAffiliation.
*/
@Column(columnDefinition="TEXT")
private String distributorContactAffiliation;
/**
* Getter for property distributorContactAffiliation.
* @return Value of property distributorContactAffiliation.
*/
public String getDistributorContactAffiliation() {
return this.distributorContactAffiliation;
}
/**
* Setter for property distributorContactAffiliation.
* @param distributorContactAffiliation New value of property distributorContactAffiliation.
*/
public void setDistributorContactAffiliation(String distributorContactAffiliation) {
this.distributorContactAffiliation = distributorContactAffiliation;
}
/**
* Holds value of property distributorContactEmail.
*/
@Column(columnDefinition="TEXT")
private String distributorContactEmail;
/**
* Getter for property distributorContactEmail.
* @return Value of property distributorContactEmail.
*/
public String getDistributorContactEmail() {
return this.distributorContactEmail;
}
/**
* Setter for property distributorContactEmail.
* @param distributorContactEmail New value of property distributorContactEmail.
*/
public void setDistributorContactEmail(String distributorContactEmail) {
this.distributorContactEmail = distributorContactEmail;
}
/**
* Holds value of property depositor.
*/
@Column(columnDefinition="TEXT")
private String depositor;
/**
* Getter for property depositor.
* @return Value of property depositor.
*/
public String getDepositor() {
return this.depositor;
}
/**
* Setter for property depositor.
* @param depositor New value of property depositor.
*/
public void setDepositor(String depositor) {
this.depositor = depositor;
}
/**
* Holds value of property dateOfDeposit.
*/
@Column(columnDefinition="TEXT")
private String dateOfDeposit;
/**
* Getter for property dateOfDeposit.
* @return Value of property dateOfDeposit.
*/
public String getDateOfDeposit() {
return this.dateOfDeposit;
}
/**
* Setter for property dateOfDeposit.
* @param dateOfDeposit New value of property dateOfDeposit.
*/
public void setDateOfDeposit(String dateOfDeposit) {
this.dateOfDeposit = dateOfDeposit;
}
/**
* Holds value of property studyOtherIds.
*/
@OneToMany(mappedBy="metadata", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST})
@OrderBy("displayOrder")
private List<StudyOtherId> studyOtherIds;
/**
* Getter for property studyOtherIds.
* @return Value of property studyOtherIds.
*/
public List<StudyOtherId> getStudyOtherIds() {
return this.studyOtherIds;
}
/**
* Setter for property studyOtherIds.
* @param studyOtherIds New value of property studyOtherIds.
*/
public void setStudyOtherIds(List<StudyOtherId> studyOtherIds) {
this.studyOtherIds = studyOtherIds;
}
/**
* Holds value of property versionDate.
*/
@Column(columnDefinition="TEXT")
private String versionDate;
/**
* Getter for property versionDate.
* @return Value of property versionDate.
*/
public String getVersionDate() {
return this.versionDate;
}
/**
* Setter for property versionDate.
* @param versionDate New value of property versionDate.
*/
public void setVersionDate(String versionDate) {
this.versionDate = versionDate;
}
/**
* Holds value of property replicationFor.
*/
@Column(columnDefinition="TEXT")
private String replicationFor;
/**
* Getter for property replicationFor.
* @return Value of property replicationFor.
*/
public String getReplicationFor() {
return this.replicationFor;
}
/**
* Setter for property replicationFor.
* @param replicationFor New value of property replicationFor.
*/
public void setReplicationFor(String replicationFor) {
this.replicationFor = replicationFor;
}
/**
* Holds value of property subTitle.
*/
@Column(columnDefinition="TEXT")
private String subTitle;
/**
* Getter for property subTitle.
* @return Value of property subTitle.
*/
public String getSubTitle() {
return this.subTitle;
}
/**
* Setter for property subTitle.
* @param subTitle New value of property subTitle.
*/
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
@OneToMany(mappedBy="metadata", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST})
@OrderBy("displayOrder")
private java.util.List<StudyGeoBounding> studyGeoBoundings;
public java.util.List<StudyGeoBounding> getStudyGeoBoundings() {
return studyGeoBoundings;
}
public void setStudyGeoBoundings(java.util.List<StudyGeoBounding> studyGeoBoundings) {
this.studyGeoBoundings = studyGeoBoundings;
}
/**
* Holds value of property studyOtherRefs.
*/
@OneToMany(mappedBy="metadata", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST})
@OrderBy("displayOrder")
private List<StudyOtherRef> studyOtherRefs;
/**
* Getter for property studyOtherRefs.
* @return Value of property studyOtherRefs.
*/
public List<StudyOtherRef> getStudyOtherRefs() {
return this.studyOtherRefs;
}
/**
* Setter for property studyOtherRefs.
* @param studyOtherRefs New value of property studyOtherRefs.
*/
public void setStudyOtherRefs(List<StudyOtherRef> studyOtherRefs) {
this.studyOtherRefs = studyOtherRefs;
}
/**
* Holds value of property studyRelMaterials.
*/
@OneToMany(mappedBy="metadata", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST})
@OrderBy("displayOrder")
private List<StudyRelMaterial> studyRelMaterials;
/**
* Getter for property studyRelMaterial.
* @return Value of property studyRelMaterial.
*/
public List<StudyRelMaterial> getStudyRelMaterials() {
return this.studyRelMaterials;
}
/**
* Setter for property studyRelMaterial.
* @param studyRelMaterial New value of property studyRelMaterial.
*/
public void setStudyRelMaterials(List<StudyRelMaterial> studyRelMaterials) {
this.studyRelMaterials = studyRelMaterials;
}
/**
* Holds value of property studyRelPublications.
*/
@OneToMany(mappedBy="metadata", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST})
@OrderBy("displayOrder")
private List<StudyRelPublication> studyRelPublications;
/**
* Getter for property studyRelPublications.
* @return Value of property studyRelPublications.
*/
public List<StudyRelPublication> getStudyRelPublications() {
return this.studyRelPublications;
}
/**
* Setter for property studyRelPublications.
* @param studyRelPublications New value of property studyRelPublications.
*/
public void setStudyRelPublications(List<StudyRelPublication> studyRelPublications) {
this.studyRelPublications = studyRelPublications;
}
/**
* Holds value of property studyRelStudies.
*/
@OneToMany(mappedBy="metadata", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST})
@OrderBy("displayOrder")
private List<StudyRelStudy> studyRelStudies;
/**
* Getter for property studyRelStudies.
* @return Value of property studyRelStudies.
*/
public List<StudyRelStudy> getStudyRelStudies() {
return this.studyRelStudies;
}
/**
* Setter for property studyRelStudies.
* @param studyRelStudies New value of property studyRelStudies.
*/
public void setStudyRelStudies(List<StudyRelStudy> studyRelStudies) {
this.studyRelStudies = studyRelStudies;
}
public int hashCode() {
int hash = 0;
hash += (this.id != null ? this.id.hashCode() : 0);
return hash;
}
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Metadata)) {
return false;
}
Metadata other = (Metadata)object;
if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) return false;
return true;
}
private String harvestHoldings;
public String getHarvestHoldings() {
return harvestHoldings;
}
public void setHarvestHoldings(String harvestHoldings) {
this.harvestHoldings = harvestHoldings;
}
@Column(columnDefinition="TEXT")
private String harvestDVTermsOfUse;
@Column(columnDefinition="TEXT")
private String harvestDVNTermsOfUse;
public String getHarvestDVTermsOfUse() {
return harvestDVTermsOfUse;
}
public void setHarvestDVTermsOfUse(String harvestDVTermsOfUse) {
this.harvestDVTermsOfUse = harvestDVTermsOfUse;
}
public String getHarvestDVNTermsOfUse() {
return harvestDVNTermsOfUse;
}
public void setHarvestDVNTermsOfUse(String harvestDVNTermsOfUse) {
this.harvestDVNTermsOfUse = harvestDVNTermsOfUse;
}
private String getCitation() {
return getCitation(true);
}
public String getTextCitation() {
return getCitation(false);
}
public String getWebCitation() {
return getCitation(true);
}
public String getCitation(boolean isOnlineVersion) {
Study study = getStudy();
String str = "";
boolean includeAffiliation = false;
String authors = getAuthorsStr(includeAffiliation);
if (!StringUtil.isEmpty(authors)) {
str += authors;
}
if (!StringUtil.isEmpty(getDistributionDate())) {
if (!StringUtil.isEmpty(str)) {
str += ", ";
}
str += getDistributionDate();
} else {
if (!StringUtil.isEmpty(getProductionDate())) {
if (!StringUtil.isEmpty(str)) {
str += ", ";
}
str += getProductionDate();
}
}
if (!StringUtil.isEmpty(getTitle())) {
if (!StringUtil.isEmpty(str)) {
str += ", ";
}
str += "\"" + getTitle() + "\"";
}
if (!StringUtil.isEmpty(study.getStudyId())) {
if (!StringUtil.isEmpty(str)) {
str += ", ";
}
if (isOnlineVersion) {
str += "<a href=\"" + study.getHandleURL() + "\">" + study.getGlobalId() + "</a>";
} else {
str += study.getHandleURL();
}
}
if (!StringUtil.isEmpty(getUNF())) {
if (!StringUtil.isEmpty(str)) {
str += " ";
}
str += getUNF();
}
String distributorNames = getDistributorNames();
if (distributorNames.length() > 0) {
str += " " + distributorNames;
str += " [Distributor]";
}
if (getStudyVersion().getVersionNumber() != null) {
str += " V" + getStudyVersion().getVersionNumber();
str += " [Version]";
}
return str;
}
public boolean isTermsOfUseEnabled() {
// we might make this a true boolean stored in the db at some point;
// for now, just check if any of the "terms of use" fields are not empty
// terms of use fields are those from the "use statement" part of the ddi
if ( !StringUtil.isEmpty(getConfidentialityDeclaration()) ) { return true; }
if ( !StringUtil.isEmpty(getSpecialPermissions()) ) { return true; }
if ( !StringUtil.isEmpty(getRestrictions()) ) { return true; }
if ( !StringUtil.isEmpty(getContact()) ) { return true; }
if ( !StringUtil.isEmpty(getCitationRequirements()) ) { return true; }
if ( !StringUtil.isEmpty(getDepositorRequirements()) ) { return true; }
if ( !StringUtil.isEmpty(getConditions()) ) { return true; }
if ( !StringUtil.isEmpty(getDisclaimer()) ) { return true; }
if ( !StringUtil.isEmpty(getHarvestDVNTermsOfUse()) ) { return true; }
if ( !StringUtil.isEmpty(getHarvestDVTermsOfUse()) ) { return true; }
return false;
}
// Return all the Terms of Use-related metadata fields concatenated as
// one string, if available:
public String getTermsOfUseAsString() {
String touString = "";
if ( !StringUtil.isEmpty(getConfidentialityDeclaration()) ) {
touString = touString.concat(getConfidentialityDeclaration());
}
if ( !StringUtil.isEmpty(getSpecialPermissions()) ) {
touString = touString.concat(getSpecialPermissions());
}
if ( !StringUtil.isEmpty(getRestrictions()) ) {
touString = touString.concat(getRestrictions());
}
if ( !StringUtil.isEmpty(getContact()) ) {
touString = touString.concat(getContact());
}
if ( !StringUtil.isEmpty(getCitationRequirements()) ) {
touString = touString.concat(getCitationRequirements());
}
if ( !StringUtil.isEmpty(getDepositorRequirements()) ) {
touString = touString.concat(getDepositorRequirements());
}
if ( !StringUtil.isEmpty(getConditions()) ) {
touString = touString.concat(getConditions());
}
if ( !StringUtil.isEmpty(getDisclaimer()) ) {
touString = touString.concat(getDisclaimer());
}
return !StringUtil.isEmpty(touString) ? touString : null;
}
public Study getStudy() {
return getStudyVersion().getStudy();
}
/**
* This method populates the dependent collections with at least one element.
* It's necessary to do this before displaying the metadata in a form, because
* we need empty elements for the users to enter data into.
*/
public void initCollections() {
if ( this.getStudyOtherIds()==null || this.getStudyOtherIds().size()==0) {
StudyOtherId elem = new StudyOtherId();
elem.setMetadata(this);
List otherIds = new ArrayList();
otherIds.add(elem);
this.setStudyOtherIds(otherIds);
}
if ( this.getStudyAuthors()==null || this.getStudyAuthors().size()==0) {
List authors = new ArrayList();
StudyAuthor anAuthor = new StudyAuthor();
anAuthor.setMetadata(this);
authors.add(anAuthor);
this.setStudyAuthors(authors);
}
if ( this.getStudyAbstracts()==null || this.getStudyAbstracts().size()==0) {
List abstracts = new ArrayList();
StudyAbstract elem = new StudyAbstract();
elem.setMetadata(this);
abstracts.add(elem);
this.setStudyAbstracts(abstracts);
}
if (this.getStudyDistributors()==null || this.getStudyDistributors().size()==0) {
List distributors = new ArrayList();
StudyDistributor elem = new StudyDistributor();
elem.setMetadata(this);
distributors.add(elem);
this.setStudyDistributors(distributors);
}
if (this.getStudyGrants()==null || this.getStudyGrants().size()==0) {
List grants = new ArrayList();
StudyGrant elem = new StudyGrant();
elem.setMetadata(this);
grants.add(elem);
this.setStudyGrants(grants);
}
if (this.getStudyKeywords()==null || this.getStudyKeywords().size()==0 ) {
List keywords = new ArrayList();
StudyKeyword elem = new StudyKeyword();
elem.setMetadata(this);
keywords.add(elem);
this.setStudyKeywords(keywords);
}
if (this.getStudyTopicClasses()==null || this.getStudyTopicClasses().size()==0 ) {
List topicClasses = new ArrayList();
StudyTopicClass elem = new StudyTopicClass();
elem.setMetadata(this);
topicClasses.add(elem);
this.setStudyTopicClasses(topicClasses);
}
if (this.getStudyNotes()==null || this.getStudyNotes().size()==0) {
List notes = new ArrayList();
StudyNote elem = new StudyNote();
elem.setMetadata(this);
notes.add(elem);
this.setStudyNotes(notes);
}
if (this.getStudyProducers()==null || this.getStudyProducers().size()==0) {
List producers = new ArrayList();
StudyProducer elem = new StudyProducer();
elem.setMetadata(this);
producers.add(elem);
this.setStudyProducers(producers);
}
if (this.getStudySoftware()==null || this.getStudySoftware().size()==0) {
List software = new ArrayList();
StudySoftware elem = new StudySoftware();
elem.setMetadata(this);
software.add(elem);
this.setStudySoftware(software);
}
if (this.getStudyGeoBoundings()==null || this.getStudyGeoBoundings().size()==0) {
List boundings = new ArrayList();
StudyGeoBounding elem = new StudyGeoBounding();
elem.setMetadata(this);
boundings.add(elem);
this.setStudyGeoBoundings(boundings);
}
if (this.getStudyRelMaterials()==null || this.getStudyRelMaterials().size()==0) {
List mats = new ArrayList();
StudyRelMaterial elem = new StudyRelMaterial();
elem.setMetadata(this);
mats.add(elem);
this.setStudyRelMaterials(mats);
}
if (this.getStudyRelPublications()==null || this.getStudyRelPublications().size()==0) {
List list = new ArrayList();
StudyRelPublication elem = new StudyRelPublication();
elem.setMetadata(this);
list.add(elem);
this.setStudyRelPublications(list);
}
if (this.getStudyRelStudies()==null || this.getStudyRelStudies().size()==0) {
List list = new ArrayList();
StudyRelStudy elem = new StudyRelStudy();
elem.setMetadata(this);
list.add(elem);
this.setStudyRelStudies(list);
}
if (this.getStudyOtherRefs()==null || this.getStudyOtherRefs().size()==0) {
List list = new ArrayList();
StudyOtherRef elem = new StudyOtherRef();
elem.setMetadata(this);
list.add(elem);
this.setStudyOtherRefs(list);
}
// custom fields
for (StudyField sf : this.getStudyFields()) {
if (sf.getStudyFieldValues()==null || sf.getStudyFieldValues().size()==0) {
List list = new ArrayList();
StudyFieldValue elem = new StudyFieldValue();
elem.setStudyField(sf);
elem.setMetadata(this);
list.add(elem);
sf.setStudyFieldValues(list);
}
}
}
public void setDisplayOrders() {
int i = 0;
for (StudyAuthor elem : this.getStudyAuthors()) {
elem.setDisplayOrder(i++);
}
i = 0;
for (StudyAbstract elem : this.getStudyAbstracts()) {
elem.setDisplayOrder(i++);
}
i = 0;
for (StudyDistributor elem : this.getStudyDistributors()) {
elem.setDisplayOrder(i++);
}
i = 0;
for (StudyGeoBounding elem : this.getStudyGeoBoundings()) {
elem.setDisplayOrder(i++);
}
i = 0;
for (StudyGrant elem : this.getStudyGrants()) {
elem.setDisplayOrder(i++);
}
i = 0;
for (StudyKeyword elem : this.getStudyKeywords()) {
elem.setDisplayOrder(i++);
}
i = 0;
for (StudyNote elem : this.getStudyNotes()) {
elem.setDisplayOrder(i++);
}
i = 0;
for (StudyOtherId elem : this.getStudyOtherIds()) {
elem.setDisplayOrder(i++);
}
i = 0;
for (StudyOtherRef elem : this.getStudyOtherRefs()) {
elem.setDisplayOrder(i++);
}
i = 0;
for (StudyProducer elem : this.getStudyProducers()) {
elem.setDisplayOrder(i++);
}
i = 0;
for (StudyRelPublication elem : this.getStudyRelPublications()) {
elem.setDisplayOrder(i++);
}
i = 0;
for (StudyRelStudy elem : this.getStudyRelStudies()) {
elem.setDisplayOrder(i++);
}
i = 0;
for (StudyRelMaterial elem : this.getStudyRelMaterials()) {
elem.setDisplayOrder(i++);
}
i = 0;
for (StudySoftware elem : this.getStudySoftware()) {
elem.setDisplayOrder(i++);
}
i = 0;
for (StudyTopicClass elem : this.getStudyTopicClasses()) {
elem.setDisplayOrder(i++);
}
// custom fields
for (StudyField studyField : this.getStudyFields()) {
i = 0;
for (StudyFieldValue elem : studyField.getStudyFieldValues()) {
elem.setDisplayOrder(i++);
}
}
}
// this is a transient list of the study fields, so we can initialize it on the first get and then store it here
@Transient
List<StudyField> studyFields;
public List<StudyField> getStudyFields() {
if (studyFields == null) {
studyFields = new ArrayList();
Template templateIn = this.getTemplate() != null ? this.getTemplate() : this.getStudyVersion().getStudy().getTemplate();
for (TemplateField tf : templateIn.getTemplateFields()) {
StudyField sf = tf.getStudyField();
if (sf.isDcmField()) {
List sfvList = new ArrayList();
// now iterate through values and map accordingly
if (studyFieldValues != null){
for (StudyFieldValue sfv : studyFieldValues) {
if (sf.equals(sfv.getStudyField())) {
sfvList.add(sfv);
}
}
}
sf.setStudyFieldValues(sfvList);
studyFields.add(sf);
}
}
}
return studyFields;
}
}
| false | true |
public Metadata(Metadata source, boolean copyHidden, boolean copyDisabled ) {
this.setUNF(source.UNF);
this.setStudyFieldValues(new ArrayList<StudyFieldValue>());
Template sourceTemplate = source.getTemplate() != null ? source.getTemplate() : source.getStudyVersion().getStudy().getTemplate();
// create a Map so we can look up each template field and check its field input level
Map<String,TemplateField> tfMap = new HashMap();
for (TemplateField tf : sourceTemplate.getTemplateFields()){
tfMap.put(tf.getStudyField().getName(), tf);
}
if( copyField(tfMap.get(StudyFieldConstant.accessToSources), copyHidden, copyDisabled) ) {
this.setAccessToSources(source.accessToSources);
}
if( copyField(tfMap.get(StudyFieldConstant.actionsToMinimizeLoss), copyHidden, copyDisabled) ) {
this.setActionsToMinimizeLoss(source.actionsToMinimizeLoss);
}
if( copyField(tfMap.get(StudyFieldConstant.availabilityStatus), copyHidden, copyDisabled) ) {
this.setAvailabilityStatus(source.availabilityStatus);
}
if( copyField(tfMap.get(StudyFieldConstant.characteristicOfSources), copyHidden, copyDisabled) ) {
this.setCharacteristicOfSources(source.characteristicOfSources);
}
if( copyField(tfMap.get(StudyFieldConstant.citationRequirements), copyHidden, copyDisabled) ) {
this.setCitationRequirements(source.citationRequirements);
}
if( copyField(tfMap.get(StudyFieldConstant.cleaningOperations), copyHidden, copyDisabled) ) {
this.setCleaningOperations(source.cleaningOperations);
}
if( copyField(tfMap.get(StudyFieldConstant.collectionMode), copyHidden, copyDisabled) ) {
this.setCollectionMode(source.collectionMode);
}
if( copyField(tfMap.get(StudyFieldConstant.collectionSize), copyHidden, copyDisabled) ) {
this.setCollectionSize(source.collectionSize);
}
if( copyField(tfMap.get(StudyFieldConstant.conditions), copyHidden, copyDisabled) ) {
this.setConditions(source.conditions);
}
if( copyField(tfMap.get(StudyFieldConstant.confidentialityDeclaration), copyHidden, copyDisabled) ) {
this.setConfidentialityDeclaration(source.confidentialityDeclaration);
}
if( copyField(tfMap.get(StudyFieldConstant.contact), copyHidden, copyDisabled) ) {
this.setContact(source.contact);
}
if( copyField(tfMap.get(StudyFieldConstant.controlOperations), copyHidden, copyDisabled) ) {
this.setControlOperations(source.controlOperations);
}
if( copyField(tfMap.get(StudyFieldConstant.country), copyHidden, copyDisabled) ) {
this.setCountry(source.country);
}
if( copyField(tfMap.get(StudyFieldConstant.dataCollectionSituation), copyHidden, copyDisabled) ) {
this.setDataCollectionSituation(source.dataCollectionSituation);
}
if( copyField(tfMap.get(StudyFieldConstant.dataCollector), copyHidden, copyDisabled) ) {
this.setDataCollector(source.dataCollector);
}
if( copyField(tfMap.get(StudyFieldConstant.dataSources), copyHidden, copyDisabled) ) {
this.setDataSources(source.dataSources);
}
if( copyField(tfMap.get(StudyFieldConstant.dateOfCollectionEnd), copyHidden, copyDisabled) ) {
this.setDateOfCollectionEnd(source.dateOfCollectionEnd);
}
if( copyField(tfMap.get(StudyFieldConstant.dateOfCollectionStart), copyHidden, copyDisabled) ) {
this.setAccessToSources(source.dateOfCollectionStart);
}
if( copyField(tfMap.get(StudyFieldConstant.dateOfDeposit), copyHidden, copyDisabled) ) {
this.setDateOfCollectionStart(source.dateOfDeposit);
}
if( copyField(tfMap.get(StudyFieldConstant.depositor), copyHidden, copyDisabled) ) {
this.setDepositor(source.depositor);
}
if( copyField(tfMap.get(StudyFieldConstant.depositorRequirements), copyHidden, copyDisabled) ) {
this.setDepositorRequirements(source.depositorRequirements);
}
if( copyField(tfMap.get(StudyFieldConstant.deviationsFromSampleDesign), copyHidden, copyDisabled) ) {
this.setDeviationsFromSampleDesign(source.deviationsFromSampleDesign);
}
if( copyField(tfMap.get(StudyFieldConstant.disclaimer), copyHidden, copyDisabled) ) {
this.setDisclaimer(source.disclaimer);
}
if( copyField(tfMap.get(StudyFieldConstant.distributionDate), copyHidden, copyDisabled) ) {
this.setDistributionDate(source.distributionDate);
}
if( copyField(tfMap.get(StudyFieldConstant.distributorContact), copyHidden, copyDisabled) ) {
this.setDistributorContact(source.distributorContact);
}
if( copyField(tfMap.get(StudyFieldConstant.distributorContactAffiliation), copyHidden, copyDisabled) ) {
this.setDistributorContactAffiliation(source.distributorContactAffiliation);
}
if( copyField(tfMap.get(StudyFieldConstant.distributorContactEmail), copyHidden, copyDisabled) ) {
this.setDistributorContactEmail(source.distributorContactEmail);
}
if( copyField(tfMap.get(StudyFieldConstant.frequencyOfDataCollection), copyHidden, copyDisabled) ) {
this.setFrequencyOfDataCollection(source.frequencyOfDataCollection);
}
if( copyField(tfMap.get(StudyFieldConstant.fundingAgency), copyHidden, copyDisabled) ) {
this.setFundingAgency(source.fundingAgency);
}
if( copyField(tfMap.get(StudyFieldConstant.geographicCoverage), copyHidden, copyDisabled) ) {
this.setGeographicCoverage(source.geographicCoverage);
}
if( copyField(tfMap.get(StudyFieldConstant.geographicUnit), copyHidden, copyDisabled) ) {
this.setGeographicUnit(source.geographicUnit);
}
if (copyField(tfMap.get(StudyFieldConstant.kindOfData), copyHidden, copyDisabled)) {
this.setKindOfData(source.kindOfData);
}
if (copyField(tfMap.get(StudyFieldConstant.originOfSources), copyHidden, copyDisabled)) {
this.setOriginOfSources(source.originOfSources);
}
if (copyField(tfMap.get(StudyFieldConstant.originalArchive), copyHidden, copyDisabled)) {
this.setOriginalArchive(source.originalArchive);
}
if (copyField(tfMap.get(StudyFieldConstant.otherDataAppraisal), copyHidden, copyDisabled)) {
this.setOtherDataAppraisal(source.otherDataAppraisal);
}
if (copyField(tfMap.get(StudyFieldConstant.placeOfAccess), copyHidden, copyDisabled)) {
this.setPlaceOfAccess(source.placeOfAccess);
}
if (copyField(tfMap.get(StudyFieldConstant.productionDate), copyHidden, copyDisabled)) {
this.setProductionDate(source.productionDate);
}
if (copyField(tfMap.get(StudyFieldConstant.productionPlace), copyHidden, copyDisabled)) {
this.setProductionPlace(source.productionPlace);
}
if (copyField(tfMap.get(StudyFieldConstant.replicationFor), copyHidden, copyDisabled)) {
this.setReplicationFor(source.replicationFor);
}
if (copyField(tfMap.get(StudyFieldConstant.researchInstrument), copyHidden, copyDisabled)) {
this.setResearchInstrument(source.researchInstrument);
}
if (copyField(tfMap.get(StudyFieldConstant.responseRate), copyHidden, copyDisabled)) {
this.setResponseRate(source.responseRate);
}
if (copyField(tfMap.get(StudyFieldConstant.restrictions), copyHidden, copyDisabled)) {
this.setRestrictions(source.restrictions);
}
if (copyField(tfMap.get(StudyFieldConstant.samplingErrorEstimates), copyHidden, copyDisabled)) {
this.setSamplingErrorEstimate(source.samplingErrorEstimate);
}
if (copyField(tfMap.get(StudyFieldConstant.samplingProcedure), copyHidden, copyDisabled)) {
this.setSamplingProcedure(source.samplingProcedure);
}
if (copyField(tfMap.get(StudyFieldConstant.seriesInformation), copyHidden, copyDisabled)) {
this.setSeriesInformation(source.seriesInformation);
}
if (copyField(tfMap.get(StudyFieldConstant.seriesName), copyHidden, copyDisabled)) {
this.setSeriesName(source.seriesName);
}
if (copyField(tfMap.get(StudyFieldConstant.specialPermissions), copyHidden, copyDisabled)) {
this.setSpecialPermissions(source.specialPermissions);
}
if (copyField(tfMap.get(StudyFieldConstant.studyVersion), copyHidden, copyDisabled)) {
this.setStudyVersionText(source.studyVersionText);
}
if (copyField(tfMap.get(StudyFieldConstant.subTitle), copyHidden, copyDisabled)) {
this.setSubTitle(source.subTitle);
}
if (copyField(tfMap.get(StudyFieldConstant.timeMethod), copyHidden, copyDisabled)) {
this.setTimeMethod(source.timeMethod);
}
if (copyField(tfMap.get(StudyFieldConstant.timePeriodCoveredEnd), copyHidden, copyDisabled)) {
this.setTimePeriodCoveredEnd(source.timePeriodCoveredEnd);
}
if (copyField(tfMap.get(StudyFieldConstant.timePeriodCoveredStart), copyHidden, copyDisabled)) {
this.setTimePeriodCoveredStart(source.timePeriodCoveredStart);
}
if (copyField(tfMap.get(StudyFieldConstant.title), copyHidden, copyDisabled)) {
this.setTitle(source.title);
}
if (copyField(tfMap.get(StudyFieldConstant.unitOfAnalysis), copyHidden, copyDisabled)) {
this.setUnitOfAnalysis(source.unitOfAnalysis);
}
if (copyField(tfMap.get(StudyFieldConstant.universe), copyHidden, copyDisabled)) {
this.setUniverse(source.universe);
}
if (copyField(tfMap.get(StudyFieldConstant.versionDate), copyHidden, copyDisabled)) {
this.setVersionDate(source.versionDate);
}
if (copyField(tfMap.get(StudyFieldConstant.weighting), copyHidden, copyDisabled)) {
this.setWeighting(source.weighting);
}
if (copyField(tfMap.get(StudyFieldConstant.studyLevelErrorNotes), copyHidden, copyDisabled)) {
this.setStudyLevelErrorNotes(source.studyLevelErrorNotes);
}
if (copyField(tfMap.get(StudyFieldConstant.studyCompletion), copyHidden, copyDisabled)) {
this.setStudyCompletion(source.studyCompletion);
}
if (copyField(tfMap.get(StudyFieldConstant.abstractText), copyHidden, copyDisabled)) {
this.setStudyAbstracts(new ArrayList<StudyAbstract>());
for (StudyAbstract sa : source.studyAbstracts) {
StudyAbstract cloneAbstract = new StudyAbstract();
cloneAbstract.setDate(sa.getDate());
cloneAbstract.setDisplayOrder(sa.getDisplayOrder());
cloneAbstract.setMetadata(this);
cloneAbstract.setText(sa.getText());
this.getStudyAbstracts().add(cloneAbstract);
}
}
if (copyField(tfMap.get(StudyFieldConstant.authorName), copyHidden, copyDisabled)) {
this.setStudyAuthors(new ArrayList<StudyAuthor>());
for (StudyAuthor author : source.studyAuthors) {
StudyAuthor cloneAuthor = new StudyAuthor();
cloneAuthor.setAffiliation(author.getAffiliation());
cloneAuthor.setDisplayOrder(author.getDisplayOrder());
cloneAuthor.setMetadata(this);
cloneAuthor.setName(author.getName());
this.getStudyAuthors().add(cloneAuthor);
}
}
if (copyField(tfMap.get(StudyFieldConstant.distributorName), copyHidden, copyDisabled)) {
this.setStudyDistributors(new ArrayList<StudyDistributor>());
for (StudyDistributor dist : source.studyDistributors) {
StudyDistributor cloneDist = new StudyDistributor();
cloneDist.setAbbreviation(dist.getAbbreviation());
cloneDist.setAffiliation(dist.getAffiliation());
cloneDist.setDisplayOrder(dist.getDisplayOrder());
cloneDist.setMetadata(this);
cloneDist.setLogo(dist.getLogo());
cloneDist.setName(dist.getName());
cloneDist.setUrl(dist.getUrl());
this.getStudyDistributors().add(cloneDist);
}
}
if (copyField(tfMap.get(StudyFieldConstant.westLongitude), copyHidden, copyDisabled)) {
this.setStudyGeoBoundings(new ArrayList<StudyGeoBounding>());
for (StudyGeoBounding geo : source.studyGeoBoundings) {
StudyGeoBounding cloneGeo = new StudyGeoBounding();
cloneGeo.setDisplayOrder(geo.getDisplayOrder());
cloneGeo.setMetadata(this);
cloneGeo.setEastLongitude(geo.getEastLongitude());
cloneGeo.setNorthLatitude(geo.getNorthLatitude());
cloneGeo.setSouthLatitude(geo.getSouthLatitude());
cloneGeo.setWestLongitude(geo.getWestLongitude());
this.getStudyGeoBoundings().add(cloneGeo);
}
}
if (copyField(tfMap.get(StudyFieldConstant.grantNumber), copyHidden, copyDisabled)) {
this.setStudyGrants(new ArrayList<StudyGrant>());
for (StudyGrant grant : source.studyGrants) {
StudyGrant cloneGrant = new StudyGrant();
cloneGrant.setAgency(grant.getAgency());
cloneGrant.setDisplayOrder(grant.getDisplayOrder());
cloneGrant.setMetadata(this);
cloneGrant.setNumber(grant.getNumber());
this.getStudyGrants().add(cloneGrant);
}
}
if (copyField(tfMap.get(StudyFieldConstant.keywordValue), copyHidden, copyDisabled)) {
this.setStudyKeywords(new ArrayList<StudyKeyword>());
for (StudyKeyword key : source.studyKeywords) {
StudyKeyword cloneKey = new StudyKeyword();
cloneKey.setDisplayOrder(key.getDisplayOrder());
cloneKey.setMetadata(this);
cloneKey.setValue(key.getValue());
cloneKey.setVocab(key.getVocab());
cloneKey.setVocabURI(key.getVocabURI());
this.getStudyKeywords().add(cloneKey);
}
}
if (copyField(tfMap.get(StudyFieldConstant.notesInformationType), copyHidden, copyDisabled)) {
this.setStudyNotes(new ArrayList<StudyNote>());
for (StudyNote note : source.studyNotes) {
StudyNote cloneNote = new StudyNote();
cloneNote.setDisplayOrder(note.getDisplayOrder());
cloneNote.setMetadata(this);
cloneNote.setSubject(note.getSubject());
cloneNote.setText(note.getText());
cloneNote.setType(note.getType());
this.getStudyNotes().add(cloneNote);
}
}
if (copyField(tfMap.get(StudyFieldConstant.otherId), copyHidden, copyDisabled)) {
this.setStudyOtherIds(new ArrayList<StudyOtherId>());
for (StudyOtherId id : source.studyOtherIds) {
StudyOtherId cloneId = new StudyOtherId();
cloneId.setAgency(id.getAgency());
cloneId.setDisplayOrder(id.getDisplayOrder());
cloneId.setMetadata(this);
cloneId.setOtherId(id.getOtherId());
this.getStudyOtherIds().add(cloneId);
}
}
if (copyField(tfMap.get(StudyFieldConstant.otherReferences), copyHidden, copyDisabled)) {
this.setStudyOtherRefs(new ArrayList<StudyOtherRef>());
for (StudyOtherRef ref : source.studyOtherRefs) {
StudyOtherRef cloneRef = new StudyOtherRef();
cloneRef.setDisplayOrder(ref.getDisplayOrder());
cloneRef.setMetadata(this);
cloneRef.setText(ref.getText());
this.getStudyOtherRefs().add(cloneRef);
}
}
if (copyField(tfMap.get(StudyFieldConstant.producerName), copyHidden, copyDisabled)) {
this.setStudyProducers(new ArrayList<StudyProducer>());
for (StudyProducer prod : source.studyProducers) {
StudyProducer cloneProd = new StudyProducer();
cloneProd.setAbbreviation(prod.getAbbreviation());
cloneProd.setAffiliation(prod.getAffiliation());
cloneProd.setDisplayOrder(prod.getDisplayOrder());
cloneProd.setLogo(prod.getLogo());
cloneProd.setMetadata(this);
cloneProd.setName(prod.getName());
cloneProd.setUrl(prod.getUrl());
this.getStudyProducers().add(cloneProd);
}
}
if (copyField(tfMap.get(StudyFieldConstant.relatedMaterial), copyHidden, copyDisabled)) {
this.setStudyRelMaterials(new ArrayList<StudyRelMaterial>());
for (StudyRelMaterial rel : source.studyRelMaterials) {
StudyRelMaterial cloneRel = new StudyRelMaterial();
cloneRel.setDisplayOrder(rel.getDisplayOrder());
cloneRel.setMetadata(this);
cloneRel.setText(rel.getText());
this.getStudyRelMaterials().add(cloneRel);
}
}
if (copyField(tfMap.get(StudyFieldConstant.relatedPublications), copyHidden, copyDisabled)) {
this.setStudyRelPublications(new ArrayList<StudyRelPublication>());
for (StudyRelPublication rel : source.studyRelPublications) {
StudyRelPublication cloneRel = new StudyRelPublication();
cloneRel.setDisplayOrder(rel.getDisplayOrder());
cloneRel.setMetadata(this);
cloneRel.setText(rel.getText());
this.getStudyRelPublications().add(cloneRel);
}
}
if (copyField(tfMap.get(StudyFieldConstant.relatedStudies), copyHidden, copyDisabled)) {
this.setStudyRelStudies(new ArrayList<StudyRelStudy>());
for (StudyRelStudy rel : source.studyRelStudies) {
StudyRelStudy cloneRel = new StudyRelStudy();
cloneRel.setDisplayOrder(rel.getDisplayOrder());
cloneRel.setMetadata(this);
cloneRel.setText(rel.getText());
this.getStudyRelStudies().add(cloneRel);
}
}
if (copyField(tfMap.get(StudyFieldConstant.softwareName), copyHidden, copyDisabled)) {
this.setStudySoftware(new ArrayList<StudySoftware>());
for (StudySoftware soft : source.studySoftware) {
StudySoftware cloneSoft = new StudySoftware();
cloneSoft.setDisplayOrder(soft.getDisplayOrder());
cloneSoft.setMetadata(this);
cloneSoft.setName(soft.getName());
cloneSoft.setSoftwareVersion(soft.getSoftwareVersion());
this.getStudySoftware().add(cloneSoft);
}
}
if (copyField(tfMap.get(StudyFieldConstant.topicClassValue), copyHidden, copyDisabled)) {
this.setStudyTopicClasses(new ArrayList<StudyTopicClass>());
for (StudyTopicClass topic : source.studyTopicClasses) {
StudyTopicClass cloneTopic = new StudyTopicClass();
cloneTopic.setDisplayOrder(topic.getDisplayOrder());
cloneTopic.setMetadata(this);
cloneTopic.setValue(topic.getValue());
cloneTopic.setVocab(topic.getVocab());
cloneTopic.setVocabURI(topic.getVocabURI());
this.getStudyTopicClasses().add(cloneTopic);
}
}
// custom values
for (StudyField sf : source.getStudyFields()) {
if( copyField(tfMap.get(sf.getName()), copyHidden, copyDisabled) ) {
for (StudyFieldValue sfv: sf.getStudyFieldValues()){
StudyFieldValue cloneSfv = new StudyFieldValue();
cloneSfv.setDisplayOrder(sfv.getDisplayOrder());
cloneSfv.setStudyField(sfv.getStudyField());
cloneSfv.setStrValue(sfv.getStrValue());
cloneSfv.setMetadata(this);
this.getStudyFieldValues().add(cloneSfv);
}
}
}
}
|
public Metadata(Metadata source, boolean copyHidden, boolean copyDisabled ) {
this.setUNF(source.UNF);
this.setStudyFieldValues(new ArrayList<StudyFieldValue>());
Template sourceTemplate = source.getTemplate() != null ? source.getTemplate() : source.getStudyVersion().getStudy().getTemplate();
// create a Map so we can look up each template field and check its field input level
Map<String,TemplateField> tfMap = new HashMap();
for (TemplateField tf : sourceTemplate.getTemplateFields()){
tfMap.put(tf.getStudyField().getName(), tf);
}
if( copyField(tfMap.get(StudyFieldConstant.accessToSources), copyHidden, copyDisabled) ) {
this.setAccessToSources(source.accessToSources);
}
if( copyField(tfMap.get(StudyFieldConstant.actionsToMinimizeLoss), copyHidden, copyDisabled) ) {
this.setActionsToMinimizeLoss(source.actionsToMinimizeLoss);
}
if( copyField(tfMap.get(StudyFieldConstant.availabilityStatus), copyHidden, copyDisabled) ) {
this.setAvailabilityStatus(source.availabilityStatus);
}
if( copyField(tfMap.get(StudyFieldConstant.characteristicOfSources), copyHidden, copyDisabled) ) {
this.setCharacteristicOfSources(source.characteristicOfSources);
}
if( copyField(tfMap.get(StudyFieldConstant.citationRequirements), copyHidden, copyDisabled) ) {
this.setCitationRequirements(source.citationRequirements);
}
if( copyField(tfMap.get(StudyFieldConstant.cleaningOperations), copyHidden, copyDisabled) ) {
this.setCleaningOperations(source.cleaningOperations);
}
if( copyField(tfMap.get(StudyFieldConstant.collectionMode), copyHidden, copyDisabled) ) {
this.setCollectionMode(source.collectionMode);
}
if( copyField(tfMap.get(StudyFieldConstant.collectionSize), copyHidden, copyDisabled) ) {
this.setCollectionSize(source.collectionSize);
}
if( copyField(tfMap.get(StudyFieldConstant.conditions), copyHidden, copyDisabled) ) {
this.setConditions(source.conditions);
}
if( copyField(tfMap.get(StudyFieldConstant.confidentialityDeclaration), copyHidden, copyDisabled) ) {
this.setConfidentialityDeclaration(source.confidentialityDeclaration);
}
if( copyField(tfMap.get(StudyFieldConstant.contact), copyHidden, copyDisabled) ) {
this.setContact(source.contact);
}
if( copyField(tfMap.get(StudyFieldConstant.controlOperations), copyHidden, copyDisabled) ) {
this.setControlOperations(source.controlOperations);
}
if( copyField(tfMap.get(StudyFieldConstant.country), copyHidden, copyDisabled) ) {
this.setCountry(source.country);
}
if( copyField(tfMap.get(StudyFieldConstant.dataCollectionSituation), copyHidden, copyDisabled) ) {
this.setDataCollectionSituation(source.dataCollectionSituation);
}
if( copyField(tfMap.get(StudyFieldConstant.dataCollector), copyHidden, copyDisabled) ) {
this.setDataCollector(source.dataCollector);
}
if( copyField(tfMap.get(StudyFieldConstant.dataSources), copyHidden, copyDisabled) ) {
this.setDataSources(source.dataSources);
}
if( copyField(tfMap.get(StudyFieldConstant.dateOfCollectionEnd), copyHidden, copyDisabled) ) {
this.setDateOfCollectionEnd(source.dateOfCollectionEnd);
}
if( copyField(tfMap.get(StudyFieldConstant.dateOfCollectionStart), copyHidden, copyDisabled) ) {
this.setDateOfCollectionStart(source.dateOfCollectionStart);
}
if( copyField(tfMap.get(StudyFieldConstant.dateOfDeposit), copyHidden, copyDisabled) ) {
this.setDateOfDeposit(source.dateOfDeposit);
}
if( copyField(tfMap.get(StudyFieldConstant.depositor), copyHidden, copyDisabled) ) {
this.setDepositor(source.depositor);
}
if( copyField(tfMap.get(StudyFieldConstant.depositorRequirements), copyHidden, copyDisabled) ) {
this.setDepositorRequirements(source.depositorRequirements);
}
if( copyField(tfMap.get(StudyFieldConstant.deviationsFromSampleDesign), copyHidden, copyDisabled) ) {
this.setDeviationsFromSampleDesign(source.deviationsFromSampleDesign);
}
if( copyField(tfMap.get(StudyFieldConstant.disclaimer), copyHidden, copyDisabled) ) {
this.setDisclaimer(source.disclaimer);
}
if( copyField(tfMap.get(StudyFieldConstant.distributionDate), copyHidden, copyDisabled) ) {
this.setDistributionDate(source.distributionDate);
}
if( copyField(tfMap.get(StudyFieldConstant.distributorContact), copyHidden, copyDisabled) ) {
this.setDistributorContact(source.distributorContact);
}
if( copyField(tfMap.get(StudyFieldConstant.distributorContactAffiliation), copyHidden, copyDisabled) ) {
this.setDistributorContactAffiliation(source.distributorContactAffiliation);
}
if( copyField(tfMap.get(StudyFieldConstant.distributorContactEmail), copyHidden, copyDisabled) ) {
this.setDistributorContactEmail(source.distributorContactEmail);
}
if( copyField(tfMap.get(StudyFieldConstant.frequencyOfDataCollection), copyHidden, copyDisabled) ) {
this.setFrequencyOfDataCollection(source.frequencyOfDataCollection);
}
if( copyField(tfMap.get(StudyFieldConstant.fundingAgency), copyHidden, copyDisabled) ) {
this.setFundingAgency(source.fundingAgency);
}
if( copyField(tfMap.get(StudyFieldConstant.geographicCoverage), copyHidden, copyDisabled) ) {
this.setGeographicCoverage(source.geographicCoverage);
}
if( copyField(tfMap.get(StudyFieldConstant.geographicUnit), copyHidden, copyDisabled) ) {
this.setGeographicUnit(source.geographicUnit);
}
if (copyField(tfMap.get(StudyFieldConstant.kindOfData), copyHidden, copyDisabled)) {
this.setKindOfData(source.kindOfData);
}
if (copyField(tfMap.get(StudyFieldConstant.originOfSources), copyHidden, copyDisabled)) {
this.setOriginOfSources(source.originOfSources);
}
if (copyField(tfMap.get(StudyFieldConstant.originalArchive), copyHidden, copyDisabled)) {
this.setOriginalArchive(source.originalArchive);
}
if (copyField(tfMap.get(StudyFieldConstant.otherDataAppraisal), copyHidden, copyDisabled)) {
this.setOtherDataAppraisal(source.otherDataAppraisal);
}
if (copyField(tfMap.get(StudyFieldConstant.placeOfAccess), copyHidden, copyDisabled)) {
this.setPlaceOfAccess(source.placeOfAccess);
}
if (copyField(tfMap.get(StudyFieldConstant.productionDate), copyHidden, copyDisabled)) {
this.setProductionDate(source.productionDate);
}
if (copyField(tfMap.get(StudyFieldConstant.productionPlace), copyHidden, copyDisabled)) {
this.setProductionPlace(source.productionPlace);
}
if (copyField(tfMap.get(StudyFieldConstant.replicationFor), copyHidden, copyDisabled)) {
this.setReplicationFor(source.replicationFor);
}
if (copyField(tfMap.get(StudyFieldConstant.researchInstrument), copyHidden, copyDisabled)) {
this.setResearchInstrument(source.researchInstrument);
}
if (copyField(tfMap.get(StudyFieldConstant.responseRate), copyHidden, copyDisabled)) {
this.setResponseRate(source.responseRate);
}
if (copyField(tfMap.get(StudyFieldConstant.restrictions), copyHidden, copyDisabled)) {
this.setRestrictions(source.restrictions);
}
if (copyField(tfMap.get(StudyFieldConstant.samplingErrorEstimates), copyHidden, copyDisabled)) {
this.setSamplingErrorEstimate(source.samplingErrorEstimate);
}
if (copyField(tfMap.get(StudyFieldConstant.samplingProcedure), copyHidden, copyDisabled)) {
this.setSamplingProcedure(source.samplingProcedure);
}
if (copyField(tfMap.get(StudyFieldConstant.seriesInformation), copyHidden, copyDisabled)) {
this.setSeriesInformation(source.seriesInformation);
}
if (copyField(tfMap.get(StudyFieldConstant.seriesName), copyHidden, copyDisabled)) {
this.setSeriesName(source.seriesName);
}
if (copyField(tfMap.get(StudyFieldConstant.specialPermissions), copyHidden, copyDisabled)) {
this.setSpecialPermissions(source.specialPermissions);
}
if (copyField(tfMap.get(StudyFieldConstant.studyVersion), copyHidden, copyDisabled)) {
this.setStudyVersionText(source.studyVersionText);
}
if (copyField(tfMap.get(StudyFieldConstant.subTitle), copyHidden, copyDisabled)) {
this.setSubTitle(source.subTitle);
}
if (copyField(tfMap.get(StudyFieldConstant.timeMethod), copyHidden, copyDisabled)) {
this.setTimeMethod(source.timeMethod);
}
if (copyField(tfMap.get(StudyFieldConstant.timePeriodCoveredEnd), copyHidden, copyDisabled)) {
this.setTimePeriodCoveredEnd(source.timePeriodCoveredEnd);
}
if (copyField(tfMap.get(StudyFieldConstant.timePeriodCoveredStart), copyHidden, copyDisabled)) {
this.setTimePeriodCoveredStart(source.timePeriodCoveredStart);
}
if (copyField(tfMap.get(StudyFieldConstant.title), copyHidden, copyDisabled)) {
this.setTitle(source.title);
}
if (copyField(tfMap.get(StudyFieldConstant.unitOfAnalysis), copyHidden, copyDisabled)) {
this.setUnitOfAnalysis(source.unitOfAnalysis);
}
if (copyField(tfMap.get(StudyFieldConstant.universe), copyHidden, copyDisabled)) {
this.setUniverse(source.universe);
}
if (copyField(tfMap.get(StudyFieldConstant.versionDate), copyHidden, copyDisabled)) {
this.setVersionDate(source.versionDate);
}
if (copyField(tfMap.get(StudyFieldConstant.weighting), copyHidden, copyDisabled)) {
this.setWeighting(source.weighting);
}
if (copyField(tfMap.get(StudyFieldConstant.studyLevelErrorNotes), copyHidden, copyDisabled)) {
this.setStudyLevelErrorNotes(source.studyLevelErrorNotes);
}
if (copyField(tfMap.get(StudyFieldConstant.studyCompletion), copyHidden, copyDisabled)) {
this.setStudyCompletion(source.studyCompletion);
}
if (copyField(tfMap.get(StudyFieldConstant.abstractText), copyHidden, copyDisabled)) {
this.setStudyAbstracts(new ArrayList<StudyAbstract>());
for (StudyAbstract sa : source.studyAbstracts) {
StudyAbstract cloneAbstract = new StudyAbstract();
cloneAbstract.setDate(sa.getDate());
cloneAbstract.setDisplayOrder(sa.getDisplayOrder());
cloneAbstract.setMetadata(this);
cloneAbstract.setText(sa.getText());
this.getStudyAbstracts().add(cloneAbstract);
}
}
if (copyField(tfMap.get(StudyFieldConstant.authorName), copyHidden, copyDisabled)) {
this.setStudyAuthors(new ArrayList<StudyAuthor>());
for (StudyAuthor author : source.studyAuthors) {
StudyAuthor cloneAuthor = new StudyAuthor();
cloneAuthor.setAffiliation(author.getAffiliation());
cloneAuthor.setDisplayOrder(author.getDisplayOrder());
cloneAuthor.setMetadata(this);
cloneAuthor.setName(author.getName());
this.getStudyAuthors().add(cloneAuthor);
}
}
if (copyField(tfMap.get(StudyFieldConstant.distributorName), copyHidden, copyDisabled)) {
this.setStudyDistributors(new ArrayList<StudyDistributor>());
for (StudyDistributor dist : source.studyDistributors) {
StudyDistributor cloneDist = new StudyDistributor();
cloneDist.setAbbreviation(dist.getAbbreviation());
cloneDist.setAffiliation(dist.getAffiliation());
cloneDist.setDisplayOrder(dist.getDisplayOrder());
cloneDist.setMetadata(this);
cloneDist.setLogo(dist.getLogo());
cloneDist.setName(dist.getName());
cloneDist.setUrl(dist.getUrl());
this.getStudyDistributors().add(cloneDist);
}
}
if (copyField(tfMap.get(StudyFieldConstant.westLongitude), copyHidden, copyDisabled)) {
this.setStudyGeoBoundings(new ArrayList<StudyGeoBounding>());
for (StudyGeoBounding geo : source.studyGeoBoundings) {
StudyGeoBounding cloneGeo = new StudyGeoBounding();
cloneGeo.setDisplayOrder(geo.getDisplayOrder());
cloneGeo.setMetadata(this);
cloneGeo.setEastLongitude(geo.getEastLongitude());
cloneGeo.setNorthLatitude(geo.getNorthLatitude());
cloneGeo.setSouthLatitude(geo.getSouthLatitude());
cloneGeo.setWestLongitude(geo.getWestLongitude());
this.getStudyGeoBoundings().add(cloneGeo);
}
}
if (copyField(tfMap.get(StudyFieldConstant.grantNumber), copyHidden, copyDisabled)) {
this.setStudyGrants(new ArrayList<StudyGrant>());
for (StudyGrant grant : source.studyGrants) {
StudyGrant cloneGrant = new StudyGrant();
cloneGrant.setAgency(grant.getAgency());
cloneGrant.setDisplayOrder(grant.getDisplayOrder());
cloneGrant.setMetadata(this);
cloneGrant.setNumber(grant.getNumber());
this.getStudyGrants().add(cloneGrant);
}
}
if (copyField(tfMap.get(StudyFieldConstant.keywordValue), copyHidden, copyDisabled)) {
this.setStudyKeywords(new ArrayList<StudyKeyword>());
for (StudyKeyword key : source.studyKeywords) {
StudyKeyword cloneKey = new StudyKeyword();
cloneKey.setDisplayOrder(key.getDisplayOrder());
cloneKey.setMetadata(this);
cloneKey.setValue(key.getValue());
cloneKey.setVocab(key.getVocab());
cloneKey.setVocabURI(key.getVocabURI());
this.getStudyKeywords().add(cloneKey);
}
}
if (copyField(tfMap.get(StudyFieldConstant.notesInformationType), copyHidden, copyDisabled)) {
this.setStudyNotes(new ArrayList<StudyNote>());
for (StudyNote note : source.studyNotes) {
StudyNote cloneNote = new StudyNote();
cloneNote.setDisplayOrder(note.getDisplayOrder());
cloneNote.setMetadata(this);
cloneNote.setSubject(note.getSubject());
cloneNote.setText(note.getText());
cloneNote.setType(note.getType());
this.getStudyNotes().add(cloneNote);
}
}
if (copyField(tfMap.get(StudyFieldConstant.otherId), copyHidden, copyDisabled)) {
this.setStudyOtherIds(new ArrayList<StudyOtherId>());
for (StudyOtherId id : source.studyOtherIds) {
StudyOtherId cloneId = new StudyOtherId();
cloneId.setAgency(id.getAgency());
cloneId.setDisplayOrder(id.getDisplayOrder());
cloneId.setMetadata(this);
cloneId.setOtherId(id.getOtherId());
this.getStudyOtherIds().add(cloneId);
}
}
if (copyField(tfMap.get(StudyFieldConstant.otherReferences), copyHidden, copyDisabled)) {
this.setStudyOtherRefs(new ArrayList<StudyOtherRef>());
for (StudyOtherRef ref : source.studyOtherRefs) {
StudyOtherRef cloneRef = new StudyOtherRef();
cloneRef.setDisplayOrder(ref.getDisplayOrder());
cloneRef.setMetadata(this);
cloneRef.setText(ref.getText());
this.getStudyOtherRefs().add(cloneRef);
}
}
if (copyField(tfMap.get(StudyFieldConstant.producerName), copyHidden, copyDisabled)) {
this.setStudyProducers(new ArrayList<StudyProducer>());
for (StudyProducer prod : source.studyProducers) {
StudyProducer cloneProd = new StudyProducer();
cloneProd.setAbbreviation(prod.getAbbreviation());
cloneProd.setAffiliation(prod.getAffiliation());
cloneProd.setDisplayOrder(prod.getDisplayOrder());
cloneProd.setLogo(prod.getLogo());
cloneProd.setMetadata(this);
cloneProd.setName(prod.getName());
cloneProd.setUrl(prod.getUrl());
this.getStudyProducers().add(cloneProd);
}
}
if (copyField(tfMap.get(StudyFieldConstant.relatedMaterial), copyHidden, copyDisabled)) {
this.setStudyRelMaterials(new ArrayList<StudyRelMaterial>());
for (StudyRelMaterial rel : source.studyRelMaterials) {
StudyRelMaterial cloneRel = new StudyRelMaterial();
cloneRel.setDisplayOrder(rel.getDisplayOrder());
cloneRel.setMetadata(this);
cloneRel.setText(rel.getText());
this.getStudyRelMaterials().add(cloneRel);
}
}
if (copyField(tfMap.get(StudyFieldConstant.relatedPublications), copyHidden, copyDisabled)) {
this.setStudyRelPublications(new ArrayList<StudyRelPublication>());
for (StudyRelPublication rel : source.studyRelPublications) {
StudyRelPublication cloneRel = new StudyRelPublication();
cloneRel.setDisplayOrder(rel.getDisplayOrder());
cloneRel.setMetadata(this);
cloneRel.setText(rel.getText());
this.getStudyRelPublications().add(cloneRel);
}
}
if (copyField(tfMap.get(StudyFieldConstant.relatedStudies), copyHidden, copyDisabled)) {
this.setStudyRelStudies(new ArrayList<StudyRelStudy>());
for (StudyRelStudy rel : source.studyRelStudies) {
StudyRelStudy cloneRel = new StudyRelStudy();
cloneRel.setDisplayOrder(rel.getDisplayOrder());
cloneRel.setMetadata(this);
cloneRel.setText(rel.getText());
this.getStudyRelStudies().add(cloneRel);
}
}
if (copyField(tfMap.get(StudyFieldConstant.softwareName), copyHidden, copyDisabled)) {
this.setStudySoftware(new ArrayList<StudySoftware>());
for (StudySoftware soft : source.studySoftware) {
StudySoftware cloneSoft = new StudySoftware();
cloneSoft.setDisplayOrder(soft.getDisplayOrder());
cloneSoft.setMetadata(this);
cloneSoft.setName(soft.getName());
cloneSoft.setSoftwareVersion(soft.getSoftwareVersion());
this.getStudySoftware().add(cloneSoft);
}
}
if (copyField(tfMap.get(StudyFieldConstant.topicClassValue), copyHidden, copyDisabled)) {
this.setStudyTopicClasses(new ArrayList<StudyTopicClass>());
for (StudyTopicClass topic : source.studyTopicClasses) {
StudyTopicClass cloneTopic = new StudyTopicClass();
cloneTopic.setDisplayOrder(topic.getDisplayOrder());
cloneTopic.setMetadata(this);
cloneTopic.setValue(topic.getValue());
cloneTopic.setVocab(topic.getVocab());
cloneTopic.setVocabURI(topic.getVocabURI());
this.getStudyTopicClasses().add(cloneTopic);
}
}
// custom values
for (StudyField sf : source.getStudyFields()) {
if( copyField(tfMap.get(sf.getName()), copyHidden, copyDisabled) ) {
for (StudyFieldValue sfv: sf.getStudyFieldValues()){
StudyFieldValue cloneSfv = new StudyFieldValue();
cloneSfv.setDisplayOrder(sfv.getDisplayOrder());
cloneSfv.setStudyField(sfv.getStudyField());
cloneSfv.setStrValue(sfv.getStrValue());
cloneSfv.setMetadata(this);
this.getStudyFieldValues().add(cloneSfv);
}
}
}
}
|
diff --git a/src/org/e2k/GW.java b/src/org/e2k/GW.java
index b8f5bb8..855811e 100644
--- a/src/org/e2k/GW.java
+++ b/src/org/e2k/GW.java
@@ -1,606 +1,608 @@
// 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.
// Rivet Copyright (C) 2011 Ian Wraith
// This program comes with ABSOLUTELY NO WARRANTY
package org.e2k;
import java.awt.Color;
import java.util.List;
import javax.swing.JOptionPane;
public class GW extends FSK {
private int state=0;
private double samplesPerSymbol100;
private Rivet theApp;
public long sampleCount=0;
private long symbolCounter=0;
private int highTone;
private int lowTone;
private int highBin;
private int lowBin;
private double adjBuffer[]=new double[1];
private int adjCounter=0;
private CircularBitSet dataBitSet=new CircularBitSet();
private int characterCount=0;
private int bitCount;
private StringBuilder positionReport=new StringBuilder();
private boolean receivingPositionReport=false;
private String lastPositionFragment;
private int positionFragmentCounter=0;
private long fragmentStartTime=0;
public GW (Rivet tapp) {
theApp=tapp;
dataBitSet.setTotalLength(200);
}
// The main decode routine
public void decode (CircularDataBuffer circBuf,WaveData waveData) {
// Initial startup
if (state==0) {
// Check the sample rate
if (waveData.getSampleRate()!=8000.0) {
state=-1;
JOptionPane.showMessageDialog(null,"WAV files containing\nGW FSK recordings must have\nbeen recorded at a sample rate\nof 8 KHz.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return;
}
// Check this is a mono recording
if (waveData.getChannels()!=1) {
state=-1;
JOptionPane.showMessageDialog(null,"Rivet can only process\nmono WAV files.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return;
}
// Check this is a 16 bit WAV file
if (waveData.getSampleSizeInBits()!=16) {
state=-1;
JOptionPane.showMessageDialog(null,"Rivet can only process\n16 bit WAV files.","Rivet", JOptionPane.INFORMATION_MESSAGE);
return;
}
// sampleCount must start negative to account for the buffer gradually filling
sampleCount=0-circBuf.retMax();
symbolCounter=0;
samplesPerSymbol100=samplesPerSymbol(100.0,waveData.getSampleRate());
setState(1);
return;
}
else if (state==1) {
if (sampleCount>0) {
if (syncSequenceHunt(circBuf,waveData)==true) {
setState(2);
bitCount=0;
dataBitSet.totalClear();
}
}
}
else if (state==2) {
// Only do this at the start of each symbol
if (symbolCounter>=samplesPerSymbol100) {
symbolCounter=0;
boolean ibit=gwFreqHalf(circBuf,waveData,0);
dataBitSet.add(ibit);
// Debug only
if (theApp.isDebug()==true) {
if (ibit==true) theApp.writeChar("1",Color.BLACK,theApp.boldFont);
else theApp.writeChar("0",Color.BLACK,theApp.boldFont);
characterCount++;
// Have we reached the end of a line
if (characterCount==80) {
characterCount=0;
theApp.newLineWrite();
}
}
// Increment the bit counter
bitCount++;
}
}
sampleCount++;
symbolCounter++;
return;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state=state;
if (state==1) theApp.setStatusLabel("Sync Hunt");
else if (state==2) theApp.setStatusLabel("Msg Hunt");
}
// Get the frequency at a certain symbol
private int getSymbolFreq (CircularDataBuffer circBuf,WaveData waveData,int start) {
int fr=do100baudFFT(circBuf,waveData,start);
return fr;
}
// The "normal" way of determining the frequency of a GW FSK symbol
// is to do two FFTs of the first and last halves of the symbol
// that allows us to use the data for the early/late gate and to detect a half bit (which is used as a stop bit)
private boolean gwFreqHalf (CircularDataBuffer circBuf,WaveData waveData,int pos) {
boolean out;
int sp=(int)samplesPerSymbol100/2;
// First half
double early[]=do100baudFSKHalfSymbolBinRequest(circBuf,pos,lowBin,highBin);
// Last half
double late[]=do100baudFSKHalfSymbolBinRequest(circBuf,(pos+sp),lowBin,highBin);
// Feed the early late difference into a buffer
if ((early[0]+late[0])>(early[1]+late[1])) addToAdjBuffer(getPercentageDifference(early[0],late[0]));
else addToAdjBuffer(getPercentageDifference(early[1],late[1]));
// Calculate the symbol timing correction
symbolCounter=adjAdjust();
// Now work out the binary state represented by this symbol
double lowTotal=early[0]+late[0];
double highTotal=early[1]+late[1];
// Calculate the bit value
if (theApp.isInvertSignal()==false) {
if (lowTotal>highTotal) out=true;
else out=false;
}
else {
// If inverted is set invert the bit returned
if (lowTotal>highTotal) out=false;
else out=true;
}
// Is the bit stream being recorded ?
if (theApp.isBitStreamOut()==true) {
if (out==true) theApp.bitStreamWrite("1");
else theApp.bitStreamWrite("0");
}
return out;
}
// Add a comparator output to a circular buffer of values
private void addToAdjBuffer (double in) {
// If the percentage difference is more than 45% then we have lost the signal
if (in>45.0) {
processGWData();
setState(1);
}
else {
adjBuffer[adjCounter]=in;
adjCounter++;
if (adjCounter==adjBuffer.length) adjCounter=0;
}
}
// Return the average of the circular buffer
private double adjAverage() {
int a;
double total=0.0;
for (a=0;a<adjBuffer.length;a++) {
total=total+adjBuffer[a];
}
return (total/adjBuffer.length);
}
// Get the average value and return an adjustment value
private int adjAdjust() {
double av=adjAverage();
double r=Math.abs(av)/15;
if (av<0) r=0-r;
return (int)r;
}
// Hunt for a two bit alternating sequence with a 200 Hz difference
private boolean syncSequenceHunt(CircularDataBuffer circBuf,WaveData waveData) {
int pos=0,b0,b1;
int f0=getSymbolFreq(circBuf,waveData,pos);
b0=getFreqBin();
// Check this first tone isn't just noise the highest bin must make up 10% of the total
if (getPercentageOfTotal()<10.0) return false;
pos=(int)samplesPerSymbol100*1;
int f1=getSymbolFreq(circBuf,waveData,pos);
b1=getFreqBin();
// Check this second tone isn't just noise the highest bin must make up 10% of the total
if (getPercentageOfTotal()<10.0) return false;
if (f0==f1) return false;
if (f0>f1) {
highTone=f0;
highBin=b0;
lowTone=f1;
lowBin=b1;
}
else {
highTone=f1;
highBin=b1;
lowTone=f0;
lowBin=b0;
}
// If either the low bin or the high bin are zero there is a problem so return false
if ((lowBin==0)||(highBin==0)) return false;
// The shift for GW FSK should be should be 200 Hz
if ((highTone-lowTone)!=200) return false;
else return true;
}
// Return the GW station name
private String stationName (int id) {
// Rogaland was 0x33 and Bern was 0xcc
if (id==0xcc) return "LFI, Rogaland, Norway";
// HLF was 0x47
else if (id==0xb8) return "HLF, Seoul, South Korea";
else if (id==0x4e) return "VCS, Halifax, Canada";
else if (id==0x5d) return "KEJ, Honolulu, Hawaii ";
else if (id==0x5e) return "CPK, Santa Cruz, Bolivia";
// A9M was 0x5f
else if (id==0xbe) return "A9M, Hamala, Bahrain";
else if (id==0x63) return "9HD, Malta";
// XSV was 0xc3
else if (id==0xf0) return "XSV, Tianjin, China";
else if (id==0xc6) return "9MG, Georgetown, Malaysia";
else if (id==0xc9) return "ZLA, Awanui, New Zealand";
else if (id==0xd2) return "ZSC, Capetown, RSA";
// KPH was 0xd7
else if (id==0xfa) return "KPH, San Franisco, USA";
else if (id==0xd8) return "WNU, Slidell Radio, USA";
else if (id==0xdb) return "KHF, Agana, Guam";
// KFS was 0xdc
else if (id==0xce) return "KFS, Palo Alto, USA";
// LSD836 was 0xdd
else if (id==0xee) return "LSD836, Buenos Airos, Argentina";
else if (id==0xde) return "SAB, Goeteborg, Sweden";
else if (id==0xe3) return "8PO, Bridgetown, Barbados";
else return "Unknown";
}
// The main method to process GW traffic
private void processGWData () {
// Turn the data into a string
String sData=dataBitSet.extractSectionFromStart(0,bitCount);
// Possible channel free marker
if (bitCount>144) {
// Hunt for 0x38A3 or 0011100010100011
int pos=sData.indexOf("0011100010100011");
if (pos<8) return;
pos=pos-8;
List<Integer> frame=dataBitSet.returnIntsFromStart(pos);
// Make sure the frame collection contains more than 18 elements
if (frame.size()<18) return;
// Free Channel Marker
// frame[] 8 to 10 should be 0xf2 & frame[] 11 to 16 should all be the same
if ((frame.get(8).equals(0xf2))&&(frame.get(9).equals(0xf2))&&(frame.get(10).equals(0xf2))&&(frame.get(11).equals(frame.get(12)))&&(frame.get(12).equals(frame.get(13)))&&(frame.get(13).equals(frame.get(14)))&&(frame.get(14).equals(frame.get(15)))&&(frame.get(15).equals(frame.get(16)))&&(frame.get(17).equals(0xff))) {
StringBuilder lo=new StringBuilder();
lo.append(theApp.getTimeStamp());
lo.append(" GW Free Channel Marker from Station Code 0x"+Integer.toHexString(frame.get(12))+" ("+stationName(frame.get(12))+") ");
int a;
for (a=0;a<18;a++) {
lo.append(" "+Integer.toHexString(frame.get(a))+" ");
}
if (theApp.isViewGWChannelMarkers()==true) theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
return;
}
}
else if ((bitCount>63)&&(bitCount<95)) {
// Ensure this starts with 10 which seems to be a part of the sync sequence
if ((sData.charAt(0)!='1')||(sData.charAt(1)!='0')) return;
StringBuilder lo=new StringBuilder();
lo.append(theApp.getTimeStamp()+" GW");
int type=0,packetCounter=0,subType=0;
// Type
if (sData.charAt(2)=='1') type=8;
if (sData.charAt(3)=='1') type=type+4;
if (sData.charAt(4)=='1') type=type+2;
if (sData.charAt(5)=='1') type++;
// Counter
if (sData.charAt(6)=='1') packetCounter=1;
// Sub type
if (sData.charAt(7)=='1') subType=64;
if (sData.charAt(8)=='1') subType=subType+32;
if (sData.charAt(9)=='1') subType=subType+16;
if (sData.charAt(10)=='1') subType=subType+8;
if (sData.charAt(11)=='1') subType=subType+4;
if (sData.charAt(12)=='1') subType=subType+2;
if (sData.charAt(13)=='1') subType++;
// Setup the display
lo.append(" Type="+Integer.toString(type)+" Count="+Integer.toString(packetCounter)+" Subtype="+Integer.toString(subType)+" (");
// Display the header as binary
lo.append(dataBitSet.extractSectionFromStart(0,14));
lo.append(") ("+displayGWAsHex(0)+")");
// If we have been in receiving position report for over 60 seconds it is never going to come so reset
if (receivingPositionReport==true) {
long difTime=(System.currentTimeMillis()/1000)-fragmentStartTime;
// Only do this if positionFragmentCounter>0 to preven this appearing when monitoring
// shore side GW broadcasts
if ((difTime>60)&&(positionFragmentCounter>0)) {
String line=theApp.getTimeStamp()+" position report timeout (fragment Count is "+Integer.toString(positionFragmentCounter)+")";
theApp.writeLine(line,Color.RED,theApp.boldFont);
receivingPositionReport=false;
}
}
// Is this the start of a position report ?
if ((type==5)&&(subType==102)) {
// Clear the position report StringBuilder object
positionReport.delete(0,positionReport.length());
lastPositionFragment="";
receivingPositionReport=true;
positionFragmentCounter=0;
// Record the fragment starting time
fragmentStartTime=System.currentTimeMillis()/1000;
//positionReport.append(theApp.getTimeStamp()+" "+displayGWAsAscii(0));
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
// Display the content
theApp.writeLine(displayGWAsAscii(0),Color.BLUE,theApp.boldFont);
return;
}
// An ongoing position report
else if ((type==5)&&(subType==86)) {
// Check if this fragment of the position report is a repeat and can be ignored
String curFrag=displayGWAsAscii(0);
// If this starts with a "$" then clear everything
if (curFrag.startsWith("$")==true) {
positionFragmentCounter=0;
positionReport.delete(0,positionReport.length());
}
// Check if this is a repeat
else if (curFrag.equals(lastPositionFragment)) return;
// It isn't so add this to the position report StringBuilder
positionReport.append(curFrag);
// Store this fragment to check against the next fragment
lastPositionFragment=curFrag;
// Count the number of fragment sent
positionFragmentCounter++;
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
theApp.writeLine(displayGWAsAscii(0),Color.BLUE,theApp.boldFont);
return;
}
// End of a position report
// Type 5 Subtype 118
else if ((type==5)&&(subType==118)) {
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
// Display the content
theApp.writeLine(displayGWAsAscii(0),Color.BLUE,theApp.boldFont);
// Have we a complete position report here ?
createPositionReportLine();
return;
}
// Type 5 Subtype 54
else if ((type==5)&&(subType==54)) {
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
// Display the content
theApp.writeLine(displayGWAsAscii(0),Color.BLUE,theApp.boldFont);
// Have we a complete position report here ?
createPositionReportLine();
return;
}
// Type 2 Subtype 106
else if ((type==2)&&(subType==106)) {
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
// Display the content
theApp.writeLine(displayGWAsAscii(0),Color.BLUE,theApp.boldFont);
return;
}
// Type 2 Subtype 101
else if ((type==2)&&(subType==101)) {
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
// Convert the payload to ints
List<Integer> mInts=dataBitSet.returnIntsFromStart(14);
// Display the MMSI and contents
Color colour;
String mLine;
// Is this a shore side 2/101 ? (0xe2,0x72,0xff,0xff,0xe7,0xe6)
if ((mInts.get(0)==0xe2)&&(mInts.get(1)==0x72)&&(mInts.get(2)==0xff)&&(mInts.get(3)==0xff)&&(mInts.get(4)==0xe7)&&(mInts.get(5)==0xe6)) {
mLine="GW Network ID 1094";
}
else {
// Does this line contain an error report ?
mLine=getGW_MMSI(mInts);
}
// Display in red if there is an error with ships.xml and blue otherwise
if (mLine.contains("ERROR")) colour=Color.RED;
else colour=Color.BLUE;
theApp.writeLine(mLine,colour,theApp.boldFont);
return;
}
// Type 5 Subtype 41
else if ((type==5)&&(subType==41)) {
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
+ return;
}
// Type 5 Subtype 63
else if ((type==5)&&(subType==63)) {
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
+ return;
}
// If selected display possible bad packets
if (theApp.isDisplayBadPackets()==true) theApp.writeLine(lo.toString(),Color.RED,theApp.boldFont);
return;
}
// Handle very short packets
// These packets are only 8 bits long and may be ACKs
// Reports suggest they are 10010101 (0x95) but we need to see if this is always the case
else if ((bitCount>7)&&(bitCount<12)) {
StringBuilder lo=new StringBuilder();
String shortContent=dataBitSet.extractSectionFromStart(0,6);
if ((shortContent.equals("010101"))||(shortContent.equals("101010"))) {
lo.append(theApp.getTimeStamp()+" GW ACK");
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
}
return;
}
}
// Display a GW packet as ASCII
private String displayGWAsAscii (int sPos) {
StringBuilder lo=new StringBuilder();
List<Integer> aInts=dataBitSet.returnIntsFromStart(sPos+14);
int a;
for (a=0;a<6;a++) {
lo.append(getGWChar(aInts.get(a)));
}
return lo.toString();
}
// Display a GW packet as hex
private String displayGWAsHex (int sPos) {
StringBuilder lo=new StringBuilder();
List<Integer> aInts=dataBitSet.returnIntsFromStart(sPos+14);
int a;
for (a=0;a<6;a++) {
if (a>0) lo.append(",");
lo.append("0x"+Integer.toHexString(aInts.get(a)));
}
return lo.toString();
}
// Convert from a byte to the GW character
private String getGWChar(int c) {
if (c==0x60) return "0";
else if (c==0x20) return "1";
else if (c==0x40) return "2";
else if (c==0x00) return "3";
else if (c==0x70) return "4";
else if (c==0x30) return "5";
else if (c==0x50) return "6";
else if (c==0x10) return "7";
else if (c==0x68) return "8";
else if (c==0x28) return "9";
else if ((c==0x78)||(c==0x3e)||(c==0x4e)||(c==0xf8)) return "<";
else if ((c==0x2e)||(c==0x7c)) return ",";
else if (c==0x5c) return ".";
else if (c==0x74) return "$";
else if (c==0x4c) return "*";
else if (c==0x27) return "A";
else if ((c==0x47)||(c==0x3f)) return "B";
else if ((c==0x37)||(c==0x07)) return "E";
else if (c==0x17) return "G";
else if ((c==0x7f)||(c==0x63)) return "L";
else if (c==0x5f) return "N";
else if ((c==0x1f)||(c==0x43)) return "O";
else if (c==0x13) return "W";
else return ("[0x"+Integer.toHexString(c)+"]");
}
// Decode the 2/101 packets contents into a MMSI and see if we have any details of this ship
private String getGW_MMSI (List<Integer> mm) {
UserIdentifier uid=new UserIdentifier();
// Decode the MMSI
String sMMSI=displayGW_MMSI(mm,9);
// See if we have a match for this MMSI
Ship ship=uid.getShipDetails(sMMSI);
// If nothing returned just return the MMSI
if (ship==null) {
String ret="MMSI : "+sMMSI;
// Do we have an error from the identifier
if (uid.getErrorMessage()!=null) ret=ret+" (ERROR "+uid.getErrorMessage()+" )";
return ret;
}
else {
StringBuilder sb=new StringBuilder();
sb.append("MMSI : "+sMMSI+" ("+ship.getName()+","+ship.getFlag()+")");
return sb.toString();
}
}
// Convert a List of Ints from a 2/101 packet into an MMSI
public String displayGW_MMSI (List<Integer> mm,int totalDigits) {
StringBuilder sb=new StringBuilder();
int a,digitCounter=0;
for (a=0;a<6;a++) {
// High nibble
int hn=(mm.get(a)&240)>>4;
// Low nibble
int ln=mm.get(a)&15;
// The following nibble
int followingNibble;
// Look at the next byte for this unless this is the last byte
if (a<5) followingNibble=(mm.get(a+1)&240)>>4;
else followingNibble=0;
boolean alternate;
// Low nibble
// If the nibble following the low nibble (which is in the next byte) is 0x8 or greater
// then we use the alternate numbering method
if (followingNibble>=0x8) alternate=true;
else alternate=false;
sb.append(convertMMSI(ln,alternate));
digitCounter++;
// Once digit counter is totalDigits then we are done
if (digitCounter==totalDigits) return sb.toString();
// High nibble
// If the nibble following the high nibble (which is the low nibble) is 0x8 or greater
// then we use the alternate numbering scheme
if (ln>=0x8) alternate=true;
else alternate=false;
sb.append(convertMMSI(hn,alternate));
digitCounter++;
// Once the digit counter is totalDigits then we are done
if (digitCounter==totalDigits) return sb.toString();
}
return sb.toString();
}
// Convert a 4 bit nibble into a number
// GW use this method for encoding ships MMSIs in 2/101 FSK packets
// I really don't understand the theory behind this encoding method.
// Big thanks to Alan W for all his help working out the encoding method used here
private String convertMMSI (int n,boolean alternate) {
if (n==0x0) return "3";
else if (n==0x1) return "7";
else if (n==0x2) {
if (alternate==false) return "1";
else return "9";
}
else if (n==0x3) return "5";
else if (n==0x4) return "2";
else if (n==0x5) return "6";
else if (n==0x6) {
if (alternate==false) return "0";
else return "8";
}
else if (n==0x7) return "4";
else if (n==0x8) return "3";
else if (n==0x9) return "7";
else if (n==0xa) {
if (alternate==false) return "1";
else return "9";
}
else if (n==0xb) return "5";
else if (n==0xc) return "2";
else if (n==0xd) return "6";
else if (n==0xe) {
if (alternate==false) return "0";
else return "8";
}
else if (n==0xf) return "4";
else return ("[0x"+Integer.toHexString(n)+"]");
}
// Check if we have a complete position report and if we have then display it
private void createPositionReportLine () {
if (receivingPositionReport==false) return;
else receivingPositionReport=false;
// Check enough position fragments have been received
if (positionFragmentCounter<10) {
String line="Position fragment count is "+Integer.toString(positionFragmentCounter);
theApp.writeLine(line,Color.RED,theApp.boldFont);
return;
}
String curFrag=displayGWAsAscii(0);
if (curFrag.equals(lastPositionFragment)) return;
// It isn't so add this to the position report StringBuilder
else positionReport.append(curFrag);
// Display this position report
theApp.writeLine(positionReport.toString(),Color.BLUE,theApp.boldFont);
}
}
| false | true |
private void processGWData () {
// Turn the data into a string
String sData=dataBitSet.extractSectionFromStart(0,bitCount);
// Possible channel free marker
if (bitCount>144) {
// Hunt for 0x38A3 or 0011100010100011
int pos=sData.indexOf("0011100010100011");
if (pos<8) return;
pos=pos-8;
List<Integer> frame=dataBitSet.returnIntsFromStart(pos);
// Make sure the frame collection contains more than 18 elements
if (frame.size()<18) return;
// Free Channel Marker
// frame[] 8 to 10 should be 0xf2 & frame[] 11 to 16 should all be the same
if ((frame.get(8).equals(0xf2))&&(frame.get(9).equals(0xf2))&&(frame.get(10).equals(0xf2))&&(frame.get(11).equals(frame.get(12)))&&(frame.get(12).equals(frame.get(13)))&&(frame.get(13).equals(frame.get(14)))&&(frame.get(14).equals(frame.get(15)))&&(frame.get(15).equals(frame.get(16)))&&(frame.get(17).equals(0xff))) {
StringBuilder lo=new StringBuilder();
lo.append(theApp.getTimeStamp());
lo.append(" GW Free Channel Marker from Station Code 0x"+Integer.toHexString(frame.get(12))+" ("+stationName(frame.get(12))+") ");
int a;
for (a=0;a<18;a++) {
lo.append(" "+Integer.toHexString(frame.get(a))+" ");
}
if (theApp.isViewGWChannelMarkers()==true) theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
return;
}
}
else if ((bitCount>63)&&(bitCount<95)) {
// Ensure this starts with 10 which seems to be a part of the sync sequence
if ((sData.charAt(0)!='1')||(sData.charAt(1)!='0')) return;
StringBuilder lo=new StringBuilder();
lo.append(theApp.getTimeStamp()+" GW");
int type=0,packetCounter=0,subType=0;
// Type
if (sData.charAt(2)=='1') type=8;
if (sData.charAt(3)=='1') type=type+4;
if (sData.charAt(4)=='1') type=type+2;
if (sData.charAt(5)=='1') type++;
// Counter
if (sData.charAt(6)=='1') packetCounter=1;
// Sub type
if (sData.charAt(7)=='1') subType=64;
if (sData.charAt(8)=='1') subType=subType+32;
if (sData.charAt(9)=='1') subType=subType+16;
if (sData.charAt(10)=='1') subType=subType+8;
if (sData.charAt(11)=='1') subType=subType+4;
if (sData.charAt(12)=='1') subType=subType+2;
if (sData.charAt(13)=='1') subType++;
// Setup the display
lo.append(" Type="+Integer.toString(type)+" Count="+Integer.toString(packetCounter)+" Subtype="+Integer.toString(subType)+" (");
// Display the header as binary
lo.append(dataBitSet.extractSectionFromStart(0,14));
lo.append(") ("+displayGWAsHex(0)+")");
// If we have been in receiving position report for over 60 seconds it is never going to come so reset
if (receivingPositionReport==true) {
long difTime=(System.currentTimeMillis()/1000)-fragmentStartTime;
// Only do this if positionFragmentCounter>0 to preven this appearing when monitoring
// shore side GW broadcasts
if ((difTime>60)&&(positionFragmentCounter>0)) {
String line=theApp.getTimeStamp()+" position report timeout (fragment Count is "+Integer.toString(positionFragmentCounter)+")";
theApp.writeLine(line,Color.RED,theApp.boldFont);
receivingPositionReport=false;
}
}
// Is this the start of a position report ?
if ((type==5)&&(subType==102)) {
// Clear the position report StringBuilder object
positionReport.delete(0,positionReport.length());
lastPositionFragment="";
receivingPositionReport=true;
positionFragmentCounter=0;
// Record the fragment starting time
fragmentStartTime=System.currentTimeMillis()/1000;
//positionReport.append(theApp.getTimeStamp()+" "+displayGWAsAscii(0));
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
// Display the content
theApp.writeLine(displayGWAsAscii(0),Color.BLUE,theApp.boldFont);
return;
}
// An ongoing position report
else if ((type==5)&&(subType==86)) {
// Check if this fragment of the position report is a repeat and can be ignored
String curFrag=displayGWAsAscii(0);
// If this starts with a "$" then clear everything
if (curFrag.startsWith("$")==true) {
positionFragmentCounter=0;
positionReport.delete(0,positionReport.length());
}
// Check if this is a repeat
else if (curFrag.equals(lastPositionFragment)) return;
// It isn't so add this to the position report StringBuilder
positionReport.append(curFrag);
// Store this fragment to check against the next fragment
lastPositionFragment=curFrag;
// Count the number of fragment sent
positionFragmentCounter++;
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
theApp.writeLine(displayGWAsAscii(0),Color.BLUE,theApp.boldFont);
return;
}
// End of a position report
// Type 5 Subtype 118
else if ((type==5)&&(subType==118)) {
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
// Display the content
theApp.writeLine(displayGWAsAscii(0),Color.BLUE,theApp.boldFont);
// Have we a complete position report here ?
createPositionReportLine();
return;
}
// Type 5 Subtype 54
else if ((type==5)&&(subType==54)) {
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
// Display the content
theApp.writeLine(displayGWAsAscii(0),Color.BLUE,theApp.boldFont);
// Have we a complete position report here ?
createPositionReportLine();
return;
}
// Type 2 Subtype 106
else if ((type==2)&&(subType==106)) {
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
// Display the content
theApp.writeLine(displayGWAsAscii(0),Color.BLUE,theApp.boldFont);
return;
}
// Type 2 Subtype 101
else if ((type==2)&&(subType==101)) {
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
// Convert the payload to ints
List<Integer> mInts=dataBitSet.returnIntsFromStart(14);
// Display the MMSI and contents
Color colour;
String mLine;
// Is this a shore side 2/101 ? (0xe2,0x72,0xff,0xff,0xe7,0xe6)
if ((mInts.get(0)==0xe2)&&(mInts.get(1)==0x72)&&(mInts.get(2)==0xff)&&(mInts.get(3)==0xff)&&(mInts.get(4)==0xe7)&&(mInts.get(5)==0xe6)) {
mLine="GW Network ID 1094";
}
else {
// Does this line contain an error report ?
mLine=getGW_MMSI(mInts);
}
// Display in red if there is an error with ships.xml and blue otherwise
if (mLine.contains("ERROR")) colour=Color.RED;
else colour=Color.BLUE;
theApp.writeLine(mLine,colour,theApp.boldFont);
return;
}
// Type 5 Subtype 41
else if ((type==5)&&(subType==41)) {
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
}
// Type 5 Subtype 63
else if ((type==5)&&(subType==63)) {
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
}
// If selected display possible bad packets
if (theApp.isDisplayBadPackets()==true) theApp.writeLine(lo.toString(),Color.RED,theApp.boldFont);
return;
}
// Handle very short packets
// These packets are only 8 bits long and may be ACKs
// Reports suggest they are 10010101 (0x95) but we need to see if this is always the case
else if ((bitCount>7)&&(bitCount<12)) {
StringBuilder lo=new StringBuilder();
String shortContent=dataBitSet.extractSectionFromStart(0,6);
if ((shortContent.equals("010101"))||(shortContent.equals("101010"))) {
lo.append(theApp.getTimeStamp()+" GW ACK");
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
}
return;
}
}
|
private void processGWData () {
// Turn the data into a string
String sData=dataBitSet.extractSectionFromStart(0,bitCount);
// Possible channel free marker
if (bitCount>144) {
// Hunt for 0x38A3 or 0011100010100011
int pos=sData.indexOf("0011100010100011");
if (pos<8) return;
pos=pos-8;
List<Integer> frame=dataBitSet.returnIntsFromStart(pos);
// Make sure the frame collection contains more than 18 elements
if (frame.size()<18) return;
// Free Channel Marker
// frame[] 8 to 10 should be 0xf2 & frame[] 11 to 16 should all be the same
if ((frame.get(8).equals(0xf2))&&(frame.get(9).equals(0xf2))&&(frame.get(10).equals(0xf2))&&(frame.get(11).equals(frame.get(12)))&&(frame.get(12).equals(frame.get(13)))&&(frame.get(13).equals(frame.get(14)))&&(frame.get(14).equals(frame.get(15)))&&(frame.get(15).equals(frame.get(16)))&&(frame.get(17).equals(0xff))) {
StringBuilder lo=new StringBuilder();
lo.append(theApp.getTimeStamp());
lo.append(" GW Free Channel Marker from Station Code 0x"+Integer.toHexString(frame.get(12))+" ("+stationName(frame.get(12))+") ");
int a;
for (a=0;a<18;a++) {
lo.append(" "+Integer.toHexString(frame.get(a))+" ");
}
if (theApp.isViewGWChannelMarkers()==true) theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
return;
}
}
else if ((bitCount>63)&&(bitCount<95)) {
// Ensure this starts with 10 which seems to be a part of the sync sequence
if ((sData.charAt(0)!='1')||(sData.charAt(1)!='0')) return;
StringBuilder lo=new StringBuilder();
lo.append(theApp.getTimeStamp()+" GW");
int type=0,packetCounter=0,subType=0;
// Type
if (sData.charAt(2)=='1') type=8;
if (sData.charAt(3)=='1') type=type+4;
if (sData.charAt(4)=='1') type=type+2;
if (sData.charAt(5)=='1') type++;
// Counter
if (sData.charAt(6)=='1') packetCounter=1;
// Sub type
if (sData.charAt(7)=='1') subType=64;
if (sData.charAt(8)=='1') subType=subType+32;
if (sData.charAt(9)=='1') subType=subType+16;
if (sData.charAt(10)=='1') subType=subType+8;
if (sData.charAt(11)=='1') subType=subType+4;
if (sData.charAt(12)=='1') subType=subType+2;
if (sData.charAt(13)=='1') subType++;
// Setup the display
lo.append(" Type="+Integer.toString(type)+" Count="+Integer.toString(packetCounter)+" Subtype="+Integer.toString(subType)+" (");
// Display the header as binary
lo.append(dataBitSet.extractSectionFromStart(0,14));
lo.append(") ("+displayGWAsHex(0)+")");
// If we have been in receiving position report for over 60 seconds it is never going to come so reset
if (receivingPositionReport==true) {
long difTime=(System.currentTimeMillis()/1000)-fragmentStartTime;
// Only do this if positionFragmentCounter>0 to preven this appearing when monitoring
// shore side GW broadcasts
if ((difTime>60)&&(positionFragmentCounter>0)) {
String line=theApp.getTimeStamp()+" position report timeout (fragment Count is "+Integer.toString(positionFragmentCounter)+")";
theApp.writeLine(line,Color.RED,theApp.boldFont);
receivingPositionReport=false;
}
}
// Is this the start of a position report ?
if ((type==5)&&(subType==102)) {
// Clear the position report StringBuilder object
positionReport.delete(0,positionReport.length());
lastPositionFragment="";
receivingPositionReport=true;
positionFragmentCounter=0;
// Record the fragment starting time
fragmentStartTime=System.currentTimeMillis()/1000;
//positionReport.append(theApp.getTimeStamp()+" "+displayGWAsAscii(0));
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
// Display the content
theApp.writeLine(displayGWAsAscii(0),Color.BLUE,theApp.boldFont);
return;
}
// An ongoing position report
else if ((type==5)&&(subType==86)) {
// Check if this fragment of the position report is a repeat and can be ignored
String curFrag=displayGWAsAscii(0);
// If this starts with a "$" then clear everything
if (curFrag.startsWith("$")==true) {
positionFragmentCounter=0;
positionReport.delete(0,positionReport.length());
}
// Check if this is a repeat
else if (curFrag.equals(lastPositionFragment)) return;
// It isn't so add this to the position report StringBuilder
positionReport.append(curFrag);
// Store this fragment to check against the next fragment
lastPositionFragment=curFrag;
// Count the number of fragment sent
positionFragmentCounter++;
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
theApp.writeLine(displayGWAsAscii(0),Color.BLUE,theApp.boldFont);
return;
}
// End of a position report
// Type 5 Subtype 118
else if ((type==5)&&(subType==118)) {
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
// Display the content
theApp.writeLine(displayGWAsAscii(0),Color.BLUE,theApp.boldFont);
// Have we a complete position report here ?
createPositionReportLine();
return;
}
// Type 5 Subtype 54
else if ((type==5)&&(subType==54)) {
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
// Display the content
theApp.writeLine(displayGWAsAscii(0),Color.BLUE,theApp.boldFont);
// Have we a complete position report here ?
createPositionReportLine();
return;
}
// Type 2 Subtype 106
else if ((type==2)&&(subType==106)) {
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
// Display the content
theApp.writeLine(displayGWAsAscii(0),Color.BLUE,theApp.boldFont);
return;
}
// Type 2 Subtype 101
else if ((type==2)&&(subType==101)) {
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
// Convert the payload to ints
List<Integer> mInts=dataBitSet.returnIntsFromStart(14);
// Display the MMSI and contents
Color colour;
String mLine;
// Is this a shore side 2/101 ? (0xe2,0x72,0xff,0xff,0xe7,0xe6)
if ((mInts.get(0)==0xe2)&&(mInts.get(1)==0x72)&&(mInts.get(2)==0xff)&&(mInts.get(3)==0xff)&&(mInts.get(4)==0xe7)&&(mInts.get(5)==0xe6)) {
mLine="GW Network ID 1094";
}
else {
// Does this line contain an error report ?
mLine=getGW_MMSI(mInts);
}
// Display in red if there is an error with ships.xml and blue otherwise
if (mLine.contains("ERROR")) colour=Color.RED;
else colour=Color.BLUE;
theApp.writeLine(mLine,colour,theApp.boldFont);
return;
}
// Type 5 Subtype 41
else if ((type==5)&&(subType==41)) {
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
return;
}
// Type 5 Subtype 63
else if ((type==5)&&(subType==63)) {
// Display the packet details
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
return;
}
// If selected display possible bad packets
if (theApp.isDisplayBadPackets()==true) theApp.writeLine(lo.toString(),Color.RED,theApp.boldFont);
return;
}
// Handle very short packets
// These packets are only 8 bits long and may be ACKs
// Reports suggest they are 10010101 (0x95) but we need to see if this is always the case
else if ((bitCount>7)&&(bitCount<12)) {
StringBuilder lo=new StringBuilder();
String shortContent=dataBitSet.extractSectionFromStart(0,6);
if ((shortContent.equals("010101"))||(shortContent.equals("101010"))) {
lo.append(theApp.getTimeStamp()+" GW ACK");
theApp.writeLine(lo.toString(),Color.BLACK,theApp.boldFont);
}
return;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.