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/code/src/com/kpro/parser/P3PParser.java b/code/src/com/kpro/parser/P3PParser.java
index 4f77a34..e69abbb 100644
--- a/code/src/com/kpro/parser/P3PParser.java
+++ b/code/src/com/kpro/parser/P3PParser.java
@@ -1,372 +1,388 @@
package com.kpro.parser;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import com.kpro.dataobjects.Action;
import com.kpro.dataobjects.Case;
import com.kpro.dataobjects.Category;
import com.kpro.dataobjects.Context;
import com.kpro.dataobjects.PolicyObject;
import com.kpro.dataobjects.Purpose;
import com.kpro.dataobjects.Recipient;
import com.kpro.dataobjects.Retention;
public class P3PParser
{
private PolicyObject policy;
private String tempKey;
/**
* Constructor for P3PParser
*
* @author ernie
*/
public P3PParser()
{
policy = new PolicyObject();
}
class XMLParserHandler extends DefaultHandler
{
// CASE
private ArrayList<Purpose> purpose;
private ArrayList<Retention> retention;
private ArrayList<Recipient> recipients;
private ArrayList<Category> categories;
// CONTEXT
private String url;
private Date accessTime, creationTime;
// ACTION
private boolean accepted, userOverride;
private ArrayList<String> domains;
private Boolean statementTag = false,
categoriesTag = false,
dataTag = false,
entityTag = false,
purposeTag = false,
recipientTag = false,
retentionTag = false,
contextTag = false,
actionTag = false,
urlTag = false,
accessTimeTag = false,
creationTimeTag = false,
acceptedTag = false,
domainTag = false,
userOverrideTag = false;
/**
* Function that parses all of first instances of a tag
*
* @author ernie
* @param nsURI input String
* @param strippedName input String
* @param tagName input String
* @param attributes input Attributes
* @throws SAXException
*/
public void startElement(String nsURI, String strippedName, String tagName, Attributes attributes) throws SAXException
{
//System.out.println("TAG: " + tagName + ", ATTRS: " + attributes.getValue(0));
String formattedTagName = tagName.replace('-', '_').toUpperCase();
// IF TAG HAS ALREADY BEEN FOUND, ADD SUBTAG
if(statementTag)
{
if(purposeTag)
{
+ try {
purpose.add(Purpose.valueOf(formattedTagName));
+ } catch(IllegalArgumentException e) {
+ // SKIPPING
+ }
}
if(recipientTag)
{
- recipients.add(Recipient.valueOf(formattedTagName));
+ try {
+ recipients.add(Recipient.valueOf(formattedTagName));
+ } catch(IllegalArgumentException e) {
+ // SKIPPING
+ }
}
if(retentionTag)
{
+ try {
retention.add(Retention.valueOf(formattedTagName));
+ } catch(IllegalArgumentException e) {
+ // SKIPPING
+ }
}
if(categoriesTag)
{
+ try {
categories.add(Category.valueOf(formattedTagName));
+ } catch(IllegalArgumentException e) {
+ // SKIPPING
+ }
}
}
// IF TAG IS TO BE FOUND, SET IT TO TRUE
if(tagName.equalsIgnoreCase("entity"))
{
entityTag = true;
}
if(tagName.equalsIgnoreCase("statement"))
{
statementTag = true;
}
if(tagName.equalsIgnoreCase("data"))
{
tempKey = attributes.getValue(0);
dataTag = true;
}
if(tagName.equalsIgnoreCase("categories"))
{
categoriesTag = true;
categories = new ArrayList<Category>();
}
if(tagName.equalsIgnoreCase("purpose"))
{
purposeTag = true;
purpose = new ArrayList<Purpose>();
}
if(tagName.equalsIgnoreCase("recipient"))
{
recipientTag = true;
recipients = new ArrayList<Recipient>();
}
if(tagName.equalsIgnoreCase("retention"))
{
retentionTag = true;
retention = new ArrayList<Retention>();
}
if(tagName.equalsIgnoreCase("context"))
{
contextTag = true;
}
if(tagName.equalsIgnoreCase("url"))
{
urlTag = true;
}
if(tagName.equalsIgnoreCase("accesstime"))
{
accessTimeTag = true;
}
if(tagName.equalsIgnoreCase("creationtime"))
{
creationTimeTag = true;
}
if(tagName.equalsIgnoreCase("action"))
{
actionTag = true;
}
if(tagName.equalsIgnoreCase("accepted"))
{
acceptedTag = true;
}
if(tagName.equalsIgnoreCase("reasons"))
{
domains = new ArrayList<String>();
}
if(tagName.equalsIgnoreCase("domain"))
{
domainTag = true;
}
if(tagName.equalsIgnoreCase("useroverride"))
{
userOverrideTag = true;
}
}
/**
* Function that parses content of a tag
*
* @author ernie
* @param ch input char
* @param start input int
* @param length input int
* @throws SAXException
*/
public void characters(char ch[], int start, int length) throws SAXException
{
String content = new String(ch, start, length);
if(dataTag && entityTag)
{
policy.addEntityData(tempKey, content);
}
if(contextTag)
{
if(urlTag)
{
url = content;
}
if(accessTimeTag)
{
try {
accessTime = new SimpleDateFormat("yyyyMMdd").parse(content);
} catch (ParseException e) {
e.printStackTrace();
}
}
if(creationTimeTag)
{
try {
creationTime = new SimpleDateFormat("yyyyMMdd").parse(content);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
if(actionTag)
{
if(acceptedTag)
{
if(content.equalsIgnoreCase("true"))
{
accepted = true;
} else {
accepted = false;
}
}
if(domainTag)
{
domains.add(content);
}
if(userOverrideTag)
{
if(content.equalsIgnoreCase("true"))
{
userOverride = true;
} else {
userOverride = false;
}
}
}
}
/**
* Function that parses all of last instances of a tag
*
* @author ernie
* @param nsURI input String
* @param strippedName input String
* @param tagName input String
* @throws SAXException
*/
public void endElement(String nsURI, String strippedName, String tagName) throws SAXException
{
// IF TAG ENDS, SET IT TO FALSE
if(tagName.equalsIgnoreCase("entity"))
{
entityTag = false;
}
if(tagName.equalsIgnoreCase("data"))
{
dataTag = false;
if(statementTag)
{
Case policyCase = new Case(purpose, retention, recipients, categories, tempKey);
policy.addCase(policyCase);
}
}
if(tagName.equalsIgnoreCase("categories"))
{
categoriesTag = false;
}
if(tagName.equalsIgnoreCase("purpose"))
{
purposeTag = false;
}
if(tagName.equalsIgnoreCase("recipient"))
{
recipientTag = false;
}
if(tagName.equalsIgnoreCase("retention"))
{
retentionTag = false;
}
if(tagName.equalsIgnoreCase("statement"))
{
statementTag = false;
}
if(tagName.equalsIgnoreCase("context"))
{
contextTag = false;
Context context = new Context(accessTime, creationTime, url);
policy.setContext(context);
}
if(tagName.equalsIgnoreCase("action"))
{
actionTag = false;
Action action = new Action(accepted, domains, 0, userOverride);
policy.setAction(action);
}
if(tagName.equalsIgnoreCase("url"))
{
urlTag = false;
}
if(tagName.equalsIgnoreCase("accesstime"))
{
accessTimeTag = false;
}
if(tagName.equalsIgnoreCase("creationtime"))
{
creationTimeTag = false;
}
if(tagName.equalsIgnoreCase("accepted"))
{
acceptedTag = false;
}
if(tagName.equalsIgnoreCase("domain"))
{
domainTag = false;
}
if(tagName.equalsIgnoreCase("useroverride"))
{
userOverrideTag = false;
}
}
}
/**
* Parses a P3P Policy by URL
*
* @author ernie
* @param p3p input String
* @return Parsed P3P Policy as PolicyObject
* @throws Exception
*/
public PolicyObject parse(String p3p)
{
XMLReader parser;
try {
parser = XMLReaderFactory.createXMLReader("org.apache.crimson.parser.XMLReaderImpl");
parser.setContentHandler(new XMLParserHandler( ));
parser.parse(p3p);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return policy;
}
/*
public static void main(String[] args) {
P3PParser parser = new P3PParser();
PolicyObject policy = new PolicyObject();
//policy = parser.parse("http://info.yahoo.com/privacy/w3c/p3p_policy.xml");
//policy = parser.parse("http://pages.ebay.com/w3c/p3p-policy.xml#policy");
//policy = parser.parse("http://www.microsoft.com/w3c/p3policy.xml");
policy = parser.parse("http://www.epicbytes.net/p3p.xml");
policy.debug_print();
}
*/
}
| false | true | public void startElement(String nsURI, String strippedName, String tagName, Attributes attributes) throws SAXException
{
//System.out.println("TAG: " + tagName + ", ATTRS: " + attributes.getValue(0));
String formattedTagName = tagName.replace('-', '_').toUpperCase();
// IF TAG HAS ALREADY BEEN FOUND, ADD SUBTAG
if(statementTag)
{
if(purposeTag)
{
purpose.add(Purpose.valueOf(formattedTagName));
}
if(recipientTag)
{
recipients.add(Recipient.valueOf(formattedTagName));
}
if(retentionTag)
{
retention.add(Retention.valueOf(formattedTagName));
}
if(categoriesTag)
{
categories.add(Category.valueOf(formattedTagName));
}
}
// IF TAG IS TO BE FOUND, SET IT TO TRUE
if(tagName.equalsIgnoreCase("entity"))
{
entityTag = true;
}
if(tagName.equalsIgnoreCase("statement"))
{
statementTag = true;
}
if(tagName.equalsIgnoreCase("data"))
{
tempKey = attributes.getValue(0);
dataTag = true;
}
if(tagName.equalsIgnoreCase("categories"))
{
categoriesTag = true;
categories = new ArrayList<Category>();
}
if(tagName.equalsIgnoreCase("purpose"))
{
purposeTag = true;
purpose = new ArrayList<Purpose>();
}
if(tagName.equalsIgnoreCase("recipient"))
{
recipientTag = true;
recipients = new ArrayList<Recipient>();
}
if(tagName.equalsIgnoreCase("retention"))
{
retentionTag = true;
retention = new ArrayList<Retention>();
}
if(tagName.equalsIgnoreCase("context"))
{
contextTag = true;
}
if(tagName.equalsIgnoreCase("url"))
{
urlTag = true;
}
if(tagName.equalsIgnoreCase("accesstime"))
{
accessTimeTag = true;
}
if(tagName.equalsIgnoreCase("creationtime"))
{
creationTimeTag = true;
}
if(tagName.equalsIgnoreCase("action"))
{
actionTag = true;
}
if(tagName.equalsIgnoreCase("accepted"))
{
acceptedTag = true;
}
if(tagName.equalsIgnoreCase("reasons"))
{
domains = new ArrayList<String>();
}
if(tagName.equalsIgnoreCase("domain"))
{
domainTag = true;
}
if(tagName.equalsIgnoreCase("useroverride"))
{
userOverrideTag = true;
}
}
| public void startElement(String nsURI, String strippedName, String tagName, Attributes attributes) throws SAXException
{
//System.out.println("TAG: " + tagName + ", ATTRS: " + attributes.getValue(0));
String formattedTagName = tagName.replace('-', '_').toUpperCase();
// IF TAG HAS ALREADY BEEN FOUND, ADD SUBTAG
if(statementTag)
{
if(purposeTag)
{
try {
purpose.add(Purpose.valueOf(formattedTagName));
} catch(IllegalArgumentException e) {
// SKIPPING
}
}
if(recipientTag)
{
try {
recipients.add(Recipient.valueOf(formattedTagName));
} catch(IllegalArgumentException e) {
// SKIPPING
}
}
if(retentionTag)
{
try {
retention.add(Retention.valueOf(formattedTagName));
} catch(IllegalArgumentException e) {
// SKIPPING
}
}
if(categoriesTag)
{
try {
categories.add(Category.valueOf(formattedTagName));
} catch(IllegalArgumentException e) {
// SKIPPING
}
}
}
// IF TAG IS TO BE FOUND, SET IT TO TRUE
if(tagName.equalsIgnoreCase("entity"))
{
entityTag = true;
}
if(tagName.equalsIgnoreCase("statement"))
{
statementTag = true;
}
if(tagName.equalsIgnoreCase("data"))
{
tempKey = attributes.getValue(0);
dataTag = true;
}
if(tagName.equalsIgnoreCase("categories"))
{
categoriesTag = true;
categories = new ArrayList<Category>();
}
if(tagName.equalsIgnoreCase("purpose"))
{
purposeTag = true;
purpose = new ArrayList<Purpose>();
}
if(tagName.equalsIgnoreCase("recipient"))
{
recipientTag = true;
recipients = new ArrayList<Recipient>();
}
if(tagName.equalsIgnoreCase("retention"))
{
retentionTag = true;
retention = new ArrayList<Retention>();
}
if(tagName.equalsIgnoreCase("context"))
{
contextTag = true;
}
if(tagName.equalsIgnoreCase("url"))
{
urlTag = true;
}
if(tagName.equalsIgnoreCase("accesstime"))
{
accessTimeTag = true;
}
if(tagName.equalsIgnoreCase("creationtime"))
{
creationTimeTag = true;
}
if(tagName.equalsIgnoreCase("action"))
{
actionTag = true;
}
if(tagName.equalsIgnoreCase("accepted"))
{
acceptedTag = true;
}
if(tagName.equalsIgnoreCase("reasons"))
{
domains = new ArrayList<String>();
}
if(tagName.equalsIgnoreCase("domain"))
{
domainTag = true;
}
if(tagName.equalsIgnoreCase("useroverride"))
{
userOverrideTag = true;
}
}
|
diff --git a/core/src/test/java/org/infinispan/expiry/ExpiryTest.java b/core/src/test/java/org/infinispan/expiry/ExpiryTest.java
index 82c63f3a66..065a7bf824 100644
--- a/core/src/test/java/org/infinispan/expiry/ExpiryTest.java
+++ b/core/src/test/java/org/infinispan/expiry/ExpiryTest.java
@@ -1,204 +1,208 @@
package org.infinispan.expiry;
import org.infinispan.Cache;
import org.infinispan.container.DataContainer;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.manager.CacheContainer;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
@Test(groups = "functional", testName = "expiry.ExpiryTest")
public class ExpiryTest extends AbstractInfinispanTest {
CacheContainer cm;
@BeforeMethod
public void setUp() {
cm = TestCacheManagerFactory.createLocalCacheManager();
}
@AfterMethod
public void tearDown() {
TestingUtil.killCacheManagers(cm);
cm = null;
}
public void testLifespanExpiryInPut() throws InterruptedException {
Cache cache = cm.getCache();
long lifespan = 1000;
cache.put("k", "v", lifespan, MILLISECONDS);
DataContainer dc = cache.getAdvancedCache().getDataContainer();
InternalCacheEntry se = dc.get("k");
assert se.getKey().equals("k");
assert se.getValue().equals("v");
assert se.getLifespan() == lifespan;
assert se.getMaxIdle() == -1;
assert !se.isExpired();
assert cache.get("k").equals("v");
Thread.sleep(1100);
assert se.isExpired();
assert cache.get("k") == null;
}
public void testIdleExpiryInPut() throws InterruptedException {
Cache cache = cm.getCache();
long idleTime = 1000;
cache.put("k", "v", -1, MILLISECONDS, idleTime, MILLISECONDS);
DataContainer dc = cache.getAdvancedCache().getDataContainer();
InternalCacheEntry se = dc.get("k");
assert se.getKey().equals("k");
assert se.getValue().equals("v");
assert se.getLifespan() == -1;
assert se.getMaxIdle() == idleTime;
assert !se.isExpired();
assert cache.get("k").equals("v");
Thread.sleep(1100);
assert se.isExpired();
assert cache.get("k") == null;
}
public void testLifespanExpiryInPutAll() throws InterruptedException {
Cache cache = cm.getCache();
long startTime = System.currentTimeMillis();
long lifespan = 1000;
Map m = new HashMap();
m.put("k1", "v");
m.put("k2", "v");
cache.putAll(m, lifespan, MILLISECONDS);
while (System.currentTimeMillis() < startTime + lifespan) {
assert cache.get("k1").equals("v");
assert cache.get("k2").equals("v");
Thread.sleep(50);
}
//make sure that in the next 2 secs data is removed
while (System.currentTimeMillis() < startTime + lifespan + 2000) {
if (cache.get("k1") == null && cache.get("k2") == null) return;
}
assert cache.get("k1") == null;
assert cache.get("k2") == null;
}
public void testIdleExpiryInPutAll() throws InterruptedException {
Cache cache = cm.getCache();
long idleTime = 10000;
Map m = new HashMap();
m.put("k1", "v");
m.put("k2", "v");
cache.putAll(m, -1, MILLISECONDS, idleTime, MILLISECONDS);
assert cache.get("k1").equals("v");
assert cache.get("k2").equals("v");
Thread.sleep(idleTime + 100);
assert cache.get("k1") == null;
assert cache.get("k2") == null;
}
public void testLifespanExpiryInPutIfAbsent() throws InterruptedException {
Cache cache = cm.getCache();
long startTime = System.currentTimeMillis();
long lifespan = 1000;
assert cache.putIfAbsent("k", "v", lifespan, MILLISECONDS) == null;
while (System.currentTimeMillis() < startTime + lifespan) {
assert cache.get("k").equals("v");
Thread.sleep(50);
}
//make sure that in the next 2 secs data is removed
while (System.currentTimeMillis() < startTime + lifespan + 2000) {
if (cache.get("k") == null) break;
Thread.sleep(50);
}
assert cache.get("k") == null;
cache.put("k", "v");
assert cache.putIfAbsent("k", "v", lifespan, MILLISECONDS) != null;
}
public void testIdleExpiryInPutIfAbsent() throws InterruptedException {
Cache cache = cm.getCache();
long idleTime = 10000;
assert cache.putIfAbsent("k", "v", -1, MILLISECONDS, idleTime, MILLISECONDS) == null;
assert cache.get("k").equals("v");
Thread.sleep(idleTime + 100);
assert cache.get("k") == null;
cache.put("k", "v");
assert cache.putIfAbsent("k", "v", -1, MILLISECONDS, idleTime, MILLISECONDS) != null;
}
public void testLifespanExpiryInReplace() throws InterruptedException {
Cache cache = cm.getCache();
long lifespan = 10000;
assert cache.get("k") == null;
assert cache.replace("k", "v", lifespan, MILLISECONDS) == null;
assert cache.get("k") == null;
cache.put("k", "v-old");
assert cache.get("k").equals("v-old");
long startTime = System.currentTimeMillis();
assert cache.replace("k", "v", lifespan, MILLISECONDS) != null;
assert cache.get("k").equals("v");
while (System.currentTimeMillis() < startTime + lifespan) {
assert cache.get("k").equals("v");
Thread.sleep(50);
}
//make sure that in the next 2 secs data is removed
while (System.currentTimeMillis() < startTime + lifespan + 2000) {
if (cache.get("k") == null) break;
Thread.sleep(50);
}
assert cache.get("k") == null;
startTime = System.currentTimeMillis();
cache.put("k", "v");
assert cache.replace("k", "v", "v2", lifespan, MILLISECONDS);
while (System.currentTimeMillis() < startTime + lifespan) {
- assert cache.get("k").equals("v2");
+ Object val = cache.get("k");
+ //only run the assertion if the time condition still stands
+ if (System.currentTimeMillis() < startTime + lifespan) {
+ assert val.equals("v2");
+ }
Thread.sleep(50);
}
//make sure that in the next 2 secs data is removed
while (System.currentTimeMillis() < startTime + lifespan + 2000) {
if (cache.get("k") == null) break;
Thread.sleep(50);
}
assert cache.get("k") == null;
}
public void testIdleExpiryInReplace() throws InterruptedException {
Cache cache = cm.getCache();
long idleTime = 10000;
assert cache.get("k") == null;
assert cache.replace("k", "v", -1, MILLISECONDS, idleTime, MILLISECONDS) == null;
assert cache.get("k") == null;
cache.put("k", "v-old");
assert cache.get("k").equals("v-old");
assert cache.replace("k", "v", -1, MILLISECONDS, idleTime, MILLISECONDS) != null;
assertEquals(cache.get("k"), "v");
Thread.sleep(idleTime + 100);
assert cache.get("k") == null;
cache.put("k", "v");
assert cache.replace("k", "v", "v2", -1, MILLISECONDS, idleTime, MILLISECONDS);
Thread.sleep(idleTime + 100);
assert cache.get("k") == null;
}
}
| true | true | public void testLifespanExpiryInReplace() throws InterruptedException {
Cache cache = cm.getCache();
long lifespan = 10000;
assert cache.get("k") == null;
assert cache.replace("k", "v", lifespan, MILLISECONDS) == null;
assert cache.get("k") == null;
cache.put("k", "v-old");
assert cache.get("k").equals("v-old");
long startTime = System.currentTimeMillis();
assert cache.replace("k", "v", lifespan, MILLISECONDS) != null;
assert cache.get("k").equals("v");
while (System.currentTimeMillis() < startTime + lifespan) {
assert cache.get("k").equals("v");
Thread.sleep(50);
}
//make sure that in the next 2 secs data is removed
while (System.currentTimeMillis() < startTime + lifespan + 2000) {
if (cache.get("k") == null) break;
Thread.sleep(50);
}
assert cache.get("k") == null;
startTime = System.currentTimeMillis();
cache.put("k", "v");
assert cache.replace("k", "v", "v2", lifespan, MILLISECONDS);
while (System.currentTimeMillis() < startTime + lifespan) {
assert cache.get("k").equals("v2");
Thread.sleep(50);
}
//make sure that in the next 2 secs data is removed
while (System.currentTimeMillis() < startTime + lifespan + 2000) {
if (cache.get("k") == null) break;
Thread.sleep(50);
}
assert cache.get("k") == null;
}
| public void testLifespanExpiryInReplace() throws InterruptedException {
Cache cache = cm.getCache();
long lifespan = 10000;
assert cache.get("k") == null;
assert cache.replace("k", "v", lifespan, MILLISECONDS) == null;
assert cache.get("k") == null;
cache.put("k", "v-old");
assert cache.get("k").equals("v-old");
long startTime = System.currentTimeMillis();
assert cache.replace("k", "v", lifespan, MILLISECONDS) != null;
assert cache.get("k").equals("v");
while (System.currentTimeMillis() < startTime + lifespan) {
assert cache.get("k").equals("v");
Thread.sleep(50);
}
//make sure that in the next 2 secs data is removed
while (System.currentTimeMillis() < startTime + lifespan + 2000) {
if (cache.get("k") == null) break;
Thread.sleep(50);
}
assert cache.get("k") == null;
startTime = System.currentTimeMillis();
cache.put("k", "v");
assert cache.replace("k", "v", "v2", lifespan, MILLISECONDS);
while (System.currentTimeMillis() < startTime + lifespan) {
Object val = cache.get("k");
//only run the assertion if the time condition still stands
if (System.currentTimeMillis() < startTime + lifespan) {
assert val.equals("v2");
}
Thread.sleep(50);
}
//make sure that in the next 2 secs data is removed
while (System.currentTimeMillis() < startTime + lifespan + 2000) {
if (cache.get("k") == null) break;
Thread.sleep(50);
}
assert cache.get("k") == null;
}
|
diff --git a/src/test/java/org/webbitserver/rest/chat/Main.java b/src/test/java/org/webbitserver/rest/chat/Main.java
index 90d64e9..daad708 100644
--- a/src/test/java/org/webbitserver/rest/chat/Main.java
+++ b/src/test/java/org/webbitserver/rest/chat/Main.java
@@ -1,25 +1,25 @@
package org.webbitserver.rest.chat;
import org.webbitserver.WebServer;
import org.webbitserver.handler.EmbeddedResourceHandler;
import org.webbitserver.handler.logging.LoggingHandler;
import org.webbitserver.handler.logging.SimpleLogSink;
import org.webbitserver.rest.resteasy.ResteasyHandler;
import static org.webbitserver.WebServers.createWebServer;
public class Main {
public static void main(String[] args) throws Exception {
Chatroom chatroom = new Chatroom();
WebServer webServer = createWebServer(9876)
.add(new LoggingHandler(new SimpleLogSink()))
- .add(new EmbeddedResourceHandler("org/webbitserver/rest/chat/content"))
+ .add(new EmbeddedResourceHandler("org/webbitserver/rest/chat"))
.add("/message-publisher", chatroom)
.add(new ResteasyHandler(chatroom.resources()))
.start();
System.out.println("Chat room running on: " + webServer.getUri());
}
}
| true | true | public static void main(String[] args) throws Exception {
Chatroom chatroom = new Chatroom();
WebServer webServer = createWebServer(9876)
.add(new LoggingHandler(new SimpleLogSink()))
.add(new EmbeddedResourceHandler("org/webbitserver/rest/chat/content"))
.add("/message-publisher", chatroom)
.add(new ResteasyHandler(chatroom.resources()))
.start();
System.out.println("Chat room running on: " + webServer.getUri());
}
| public static void main(String[] args) throws Exception {
Chatroom chatroom = new Chatroom();
WebServer webServer = createWebServer(9876)
.add(new LoggingHandler(new SimpleLogSink()))
.add(new EmbeddedResourceHandler("org/webbitserver/rest/chat"))
.add("/message-publisher", chatroom)
.add(new ResteasyHandler(chatroom.resources()))
.start();
System.out.println("Chat room running on: " + webServer.getUri());
}
|
diff --git a/src/com/awsmithson/tcx2nikeplus/http/NikePlus.java b/src/com/awsmithson/tcx2nikeplus/http/NikePlus.java
index 930f1d4..00f4c98 100644
--- a/src/com/awsmithson/tcx2nikeplus/http/NikePlus.java
+++ b/src/com/awsmithson/tcx2nikeplus/http/NikePlus.java
@@ -1,343 +1,343 @@
package com.awsmithson.tcx2nikeplus.http;
import static com.awsmithson.tcx2nikeplus.Constants.*;
import com.awsmithson.tcx2nikeplus.util.Log;
import com.awsmithson.tcx2nikeplus.util.Util;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class NikePlus
{
private static final String URL_GENERATE_PIN = "https://secure-nikerunning.nike.com/nikeplus/v2/services/app/generate_pin.jsp";
private static final String URL_CHECK_PIN_STATUS = "https://secure-nikerunning.nike.com/nikeplus/v2/services/device/get_pin_status.jsp";
private static final String URL_DATA_SYNC_NON_GPS = "https://secure-nikerunning.nike.com/nikeplus/v2/services/device/sync.jsp";
private static final String URL_DATA_SYNC_GPS = "https://secure-nikerunning.nike.com/gps/sync/plus/iphone";
private static final String URL_DATA_SYNC_COMPLETE = "https://secure-nikerunning.nike.com/nikeplus/v2/services/device/sync_complete.jsp";
private static final String USER_AGENT = "iTunes/9.0.3 (Macintosh; N; Intel)";
private static final Log log = Log.getInstance();
public NikePlus() {
}
/**
* Retrieves the pin from nike+ for the given login/password..
* @param login The login String (email address).
* @param password The login password.
* @return Nike+ pin.
* @throws IOException
* @throws MalformedURLException
* @throws ParserConfigurationException
* @throws SAXException
* @throws UnsupportedEncodingException
*/
public String generatePin(String login, String password) throws IOException, MalformedURLException, ParserConfigurationException, SAXException, UnsupportedEncodingException {
// Send data
URL url = new URL(String.format("%s?%s&%s", URL_GENERATE_PIN, Util.generateHttpParameter("login", login), Util.generateHttpParameter("password", password)));
URLConnection conn = url.openConnection();
conn.setRequestProperty("user-agent", USER_AGENT);
// Get the response
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(conn.getInputStream());
doc.normalize();
//log.out(Util.DocumentToString(doc));
String pinStatus = Util.getSimpleNodeValue(doc, "status");
if (!(pinStatus.equals("success")))
throw new IllegalArgumentException("The email and password supplied are not valid");
return Util.getSimpleNodeValue(doc, "pin");
}
/**
* Calls fullSync converting the File objects to Document.
* @param pin Nike+ pin.
* @param runXml Nike+ workout xml.
* @param gpxXml Nike+ gpx xml.
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
* @throws MalformedURLException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
private void fullSync(String pin, File runXml, File gpxXml) throws ParserConfigurationException, SAXException, IOException, MalformedURLException, NoSuchAlgorithmException, KeyManagementException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
fullSync(pin, db.parse(runXml), ((gpxXml != null) ? db.parse(gpxXml) : null));
}
/**
* Does a full synchronisation cycle (check-pin-status, sync, end-sync) with nike+ for the given pin and xml document(s).
* @param pin Nike+ pin.
* @param runXml Nike+ workout xml.
* @param gpxXml Nike+ gpx xml.
* @throws IOException
* @throws MalformedURLException
* @throws ParserConfigurationException
* @throws SAXException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public void fullSync(String pin, Document runXml, Document gpxXml) throws IOException, MalformedURLException, ParserConfigurationException, SAXException, NoSuchAlgorithmException, KeyManagementException {
boolean haveGpx = (gpxXml != null);
runXml.normalizeDocument();
if (haveGpx) gpxXml.normalizeDocument();
log.out("Uploading to Nike+...");
try {
log.out(" - Checking pin status...");
checkPinStatus(pin);
log.out(" - Syncing data...");
Document nikeResponse = (haveGpx)
? syncDataGps(pin, runXml, gpxXml)
: syncDataNonGps(pin, runXml)
;
//<?xml version="1.0" encoding="UTF-8" standalone="no"?><plusService><status>success</status></plusService>
if (Util.getSimpleNodeValue(nikeResponse, "status").equals(NIKE_SUCCESS)) {
log.out(" - Sync successful.");
return;
}
//<?xml version="1.0" encoding="UTF-8" standalone="no"?><plusService><status>failure</status><serviceException errorCode="InvalidRunError">snapshot duration greater than run (threshold 30000 ms): 82980</serviceException></plusService>
NodeList nikeServiceExceptionL = nikeResponse.getElementsByTagName("serviceException");
if ((nikeServiceExceptionL != null) && (nikeServiceExceptionL.getLength() > 0)) {
Node nikeServiceException = nikeServiceExceptionL.item(0);
throw new RuntimeException(String.format("%s: %s", nikeServiceException.getAttributes().item(0).getNodeValue(), Util.getSimpleNodeValue(nikeServiceException)));
}
else {
log.out(Util.DocumentToString(nikeResponse));
String nikeError = Util.getSimpleNodeValue(nikeResponse, "error");
log.out(nikeError);
if (nikeError.indexOf("<?xml ") == -1)
- throw new RuntimeException(String.format("Nike+ Error: %s", nikeError));
+ throw new RuntimeException(String.format("Nike+ Error: %s.\nThis is likely to be a problem at Nike+'s end.\nPlease try again later, contact me if the problem persists.", nikeError));
else {
/*
2011-02-19 - Oh dear nikeplus... What is this xml nonsense you are coming out with?!? Representing an xml document within an xml node? Tasty.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<response>
<status>failure</status>
<error>
<![CDATA[Failed to sync runXml: problem syncing runXML response from device sync service:
<?xml version="1.0" encoding="UTF-8"?>
<plusService>
<status>failure</status>
<serviceException errorCode="InvalidRunError">snapshot pace invalid. dist: 5.0 duration: -4074967</serviceException>
</plusService>]]>
</error>
</response>
*/
// Failed to sync runXml: problem syncing runXML response from device sync service:<?xml version="1.0" encoding="UTF-8"?><plusService><status>failure</status><serviceException errorCode="InvalidRunError">snapshot pace invalid. dist: 5.0 duration: -4074967</serviceException></plusService>
nikeError = nikeError.substring(nikeError.indexOf("<?xml"));
log.out(nikeError);
nikeResponse = Util.generateDocument(nikeError);
Node nikeServiceException = nikeResponse.getElementsByTagName("serviceException").item(0);
//InvalidRunError: snapshot pace invalid. dist: 5.0 duration: -4074967
throw new RuntimeException(String.format("%s: %s", nikeServiceException.getAttributes().item(0).getNodeValue(), Util.getSimpleNodeValue(nikeServiceException)));
}
}
}
finally {
log.out(" - Ending sync...");
Document nikeResponse = endSync(pin);
log.out((Util.getSimpleNodeValue(nikeResponse, "status").equals(NIKE_SUCCESS))
? " - End sync successful."
: String.format(" - End sync failed: %s", Util.DocumentToString(nikeResponse))
);
}
}
private void checkPinStatus(String pin) throws IOException, MalformedURLException, ParserConfigurationException, SAXException, UnsupportedEncodingException {
// Send data
URL url = new URL(String.format("%s?%s", URL_CHECK_PIN_STATUS, Util.generateHttpParameter("pin", pin)));
URLConnection conn = url.openConnection();
conn.setRequestProperty("user-agent", USER_AGENT);
// Get the response
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(conn.getInputStream());
doc.normalize();
//log.out(Util.DocumentToString(doc));
String pinStatus = Util.getSimpleNodeValue(doc, "pinStatus");
if (!(pinStatus.equals("confirmed")))
throw new IllegalArgumentException("The PIN supplied is not valid");
}
private Document syncDataNonGps(String pin, Document doc) throws MalformedURLException, IOException, ParserConfigurationException, SAXException {
String data = Util.generateStringOutput(doc);
// Send data
URL url = new URL(URL_DATA_SYNC_NON_GPS);
URLConnection conn = url.openConnection();
conn.setRequestProperty("user-agent", USER_AGENT);
conn.setRequestProperty("pin", URLEncoder.encode(pin, "UTF-8"));
conn.setRequestProperty("content-type", "text/xml");
conn.setRequestProperty("content-length", String.valueOf(data.length()));
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
Document outDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(conn.getInputStream());
wr.close();
outDoc.normalize();
//log.out(" %s", Util.DocumentToString(outDoc));
return outDoc;
}
private Document syncDataGps(String pin, Document runXml, Document gpxXml) throws IOException, ParserConfigurationException, SAXException, NoSuchAlgorithmException, KeyManagementException {
HttpClient client = new DefaultHttpClient();
client = HttpClientNaiveSsl.wrapClient(client);
HttpPost post = new HttpPost(URL_DATA_SYNC_GPS);
post.addHeader("user-agent", "NPConnect");
post.addHeader("pin", URLEncoder.encode(pin, "UTF-8"));
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT);
reqEntity.addPart("runXML", new SpoofFileBody(Util.generateStringOutput(runXml), "runXML.xml"));
reqEntity.addPart("gpxXML", new SpoofFileBody(Util.generateStringOutput(gpxXml), "gpxXML.xml"));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
Document outDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(entity.getContent());
EntityUtils.consume(entity);
outDoc.normalize();
return outDoc;
}
private Document endSync(final String pin) throws MalformedURLException, IOException, ParserConfigurationException, SAXException {
URL url = new URL(String.format("%s?%s", URL_DATA_SYNC_COMPLETE, Util.generateHttpParameter("pin", pin)));
URLConnection conn = url.openConnection();
conn.setRequestProperty("user-agent", USER_AGENT);
// Get the response
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(conn.getInputStream());
doc.normalize();
//log.out("end sync reply: %s", Util.DocumentToString(doc));
return doc;
/*
Thread t = new Thread(new Runnable() {
public void run() {
OutputStreamWriter wr = null;
try {
// Send data
URL url = new URL(String.format("%s?%s", URL_DATA_SYNC_COMPLETE, Util.generateHttpParameter("pin", pin)));
URLConnection conn = url.openConnection();
conn.setRequestProperty("user-agent", USER_AGENT);
}
catch (Throwable t) {
log.out(t);
}
finally {
try {
if (wr != null) wr.close();
}
catch (Throwable t) {
log.out(t);
}
}
}
});
// Start the end-sync thread - and leave it to run in the background.
t.start();
*/
}
public static void main(String[] args) {
String pin = args[0];
File runXml = new File(args[1]);
File gpxXml = (args.length > 2) ? new File(args[2]) : null;
NikePlus u = new NikePlus();
try {
u.fullSync(pin, runXml, gpxXml);
}
catch (Throwable t) {
t.printStackTrace();
}
}
}
/*
private void syncDataNonGps(String pin, File file) throws MalformedURLException, IOException, ParserConfigurationException, SAXException {
// Load the file, ensuring it is valid xml
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.normalize();
syncDataNonGps(pin, doc);
}
private void syncDataGps(String pin, File runXml, File gpxXml) throws MalformedURLException, IOException, ParserConfigurationException, SAXException, NoSuchAlgorithmException, KeyManagementException {
// Load the file, ensuring it is valid xml
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document runXmlDoc = db.parse(runXml);
runXmlDoc.normalize();
Document gpxXmlDoc = db.parse(gpxXml);
runXmlDoc.normalize();
syncDataGps(pin, runXmlDoc, gpxXmlDoc);
}
*/
| true | true | public void fullSync(String pin, Document runXml, Document gpxXml) throws IOException, MalformedURLException, ParserConfigurationException, SAXException, NoSuchAlgorithmException, KeyManagementException {
boolean haveGpx = (gpxXml != null);
runXml.normalizeDocument();
if (haveGpx) gpxXml.normalizeDocument();
log.out("Uploading to Nike+...");
try {
log.out(" - Checking pin status...");
checkPinStatus(pin);
log.out(" - Syncing data...");
Document nikeResponse = (haveGpx)
? syncDataGps(pin, runXml, gpxXml)
: syncDataNonGps(pin, runXml)
;
//<?xml version="1.0" encoding="UTF-8" standalone="no"?><plusService><status>success</status></plusService>
if (Util.getSimpleNodeValue(nikeResponse, "status").equals(NIKE_SUCCESS)) {
log.out(" - Sync successful.");
return;
}
//<?xml version="1.0" encoding="UTF-8" standalone="no"?><plusService><status>failure</status><serviceException errorCode="InvalidRunError">snapshot duration greater than run (threshold 30000 ms): 82980</serviceException></plusService>
NodeList nikeServiceExceptionL = nikeResponse.getElementsByTagName("serviceException");
if ((nikeServiceExceptionL != null) && (nikeServiceExceptionL.getLength() > 0)) {
Node nikeServiceException = nikeServiceExceptionL.item(0);
throw new RuntimeException(String.format("%s: %s", nikeServiceException.getAttributes().item(0).getNodeValue(), Util.getSimpleNodeValue(nikeServiceException)));
}
else {
log.out(Util.DocumentToString(nikeResponse));
String nikeError = Util.getSimpleNodeValue(nikeResponse, "error");
log.out(nikeError);
if (nikeError.indexOf("<?xml ") == -1)
throw new RuntimeException(String.format("Nike+ Error: %s", nikeError));
else {
/*
2011-02-19 - Oh dear nikeplus... What is this xml nonsense you are coming out with?!? Representing an xml document within an xml node? Tasty.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<response>
<status>failure</status>
<error>
<![CDATA[Failed to sync runXml: problem syncing runXML response from device sync service:
<?xml version="1.0" encoding="UTF-8"?>
<plusService>
<status>failure</status>
<serviceException errorCode="InvalidRunError">snapshot pace invalid. dist: 5.0 duration: -4074967</serviceException>
</plusService>]]>
</error>
</response>
*/
// Failed to sync runXml: problem syncing runXML response from device sync service:<?xml version="1.0" encoding="UTF-8"?><plusService><status>failure</status><serviceException errorCode="InvalidRunError">snapshot pace invalid. dist: 5.0 duration: -4074967</serviceException></plusService>
nikeError = nikeError.substring(nikeError.indexOf("<?xml"));
log.out(nikeError);
nikeResponse = Util.generateDocument(nikeError);
Node nikeServiceException = nikeResponse.getElementsByTagName("serviceException").item(0);
//InvalidRunError: snapshot pace invalid. dist: 5.0 duration: -4074967
throw new RuntimeException(String.format("%s: %s", nikeServiceException.getAttributes().item(0).getNodeValue(), Util.getSimpleNodeValue(nikeServiceException)));
}
}
}
finally {
log.out(" - Ending sync...");
Document nikeResponse = endSync(pin);
log.out((Util.getSimpleNodeValue(nikeResponse, "status").equals(NIKE_SUCCESS))
? " - End sync successful."
: String.format(" - End sync failed: %s", Util.DocumentToString(nikeResponse))
);
}
}
| public void fullSync(String pin, Document runXml, Document gpxXml) throws IOException, MalformedURLException, ParserConfigurationException, SAXException, NoSuchAlgorithmException, KeyManagementException {
boolean haveGpx = (gpxXml != null);
runXml.normalizeDocument();
if (haveGpx) gpxXml.normalizeDocument();
log.out("Uploading to Nike+...");
try {
log.out(" - Checking pin status...");
checkPinStatus(pin);
log.out(" - Syncing data...");
Document nikeResponse = (haveGpx)
? syncDataGps(pin, runXml, gpxXml)
: syncDataNonGps(pin, runXml)
;
//<?xml version="1.0" encoding="UTF-8" standalone="no"?><plusService><status>success</status></plusService>
if (Util.getSimpleNodeValue(nikeResponse, "status").equals(NIKE_SUCCESS)) {
log.out(" - Sync successful.");
return;
}
//<?xml version="1.0" encoding="UTF-8" standalone="no"?><plusService><status>failure</status><serviceException errorCode="InvalidRunError">snapshot duration greater than run (threshold 30000 ms): 82980</serviceException></plusService>
NodeList nikeServiceExceptionL = nikeResponse.getElementsByTagName("serviceException");
if ((nikeServiceExceptionL != null) && (nikeServiceExceptionL.getLength() > 0)) {
Node nikeServiceException = nikeServiceExceptionL.item(0);
throw new RuntimeException(String.format("%s: %s", nikeServiceException.getAttributes().item(0).getNodeValue(), Util.getSimpleNodeValue(nikeServiceException)));
}
else {
log.out(Util.DocumentToString(nikeResponse));
String nikeError = Util.getSimpleNodeValue(nikeResponse, "error");
log.out(nikeError);
if (nikeError.indexOf("<?xml ") == -1)
throw new RuntimeException(String.format("Nike+ Error: %s.\nThis is likely to be a problem at Nike+'s end.\nPlease try again later, contact me if the problem persists.", nikeError));
else {
/*
2011-02-19 - Oh dear nikeplus... What is this xml nonsense you are coming out with?!? Representing an xml document within an xml node? Tasty.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<response>
<status>failure</status>
<error>
<![CDATA[Failed to sync runXml: problem syncing runXML response from device sync service:
<?xml version="1.0" encoding="UTF-8"?>
<plusService>
<status>failure</status>
<serviceException errorCode="InvalidRunError">snapshot pace invalid. dist: 5.0 duration: -4074967</serviceException>
</plusService>]]>
</error>
</response>
*/
// Failed to sync runXml: problem syncing runXML response from device sync service:<?xml version="1.0" encoding="UTF-8"?><plusService><status>failure</status><serviceException errorCode="InvalidRunError">snapshot pace invalid. dist: 5.0 duration: -4074967</serviceException></plusService>
nikeError = nikeError.substring(nikeError.indexOf("<?xml"));
log.out(nikeError);
nikeResponse = Util.generateDocument(nikeError);
Node nikeServiceException = nikeResponse.getElementsByTagName("serviceException").item(0);
//InvalidRunError: snapshot pace invalid. dist: 5.0 duration: -4074967
throw new RuntimeException(String.format("%s: %s", nikeServiceException.getAttributes().item(0).getNodeValue(), Util.getSimpleNodeValue(nikeServiceException)));
}
}
}
finally {
log.out(" - Ending sync...");
Document nikeResponse = endSync(pin);
log.out((Util.getSimpleNodeValue(nikeResponse, "status").equals(NIKE_SUCCESS))
? " - End sync successful."
: String.format(" - End sync failed: %s", Util.DocumentToString(nikeResponse))
);
}
}
|
diff --git a/domains/report/plaintext/src/test/java/org/openengsb/domains/report/plaintext/internal/PlaintextReportFactoryTest.java b/domains/report/plaintext/src/test/java/org/openengsb/domains/report/plaintext/internal/PlaintextReportFactoryTest.java
index 35a80a735..c3b00442a 100755
--- a/domains/report/plaintext/src/test/java/org/openengsb/domains/report/plaintext/internal/PlaintextReportFactoryTest.java
+++ b/domains/report/plaintext/src/test/java/org/openengsb/domains/report/plaintext/internal/PlaintextReportFactoryTest.java
@@ -1,44 +1,45 @@
/**
* Copyright 2010 OpenEngSB Division, Vienna University of Technology
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openengsb.domains.report.plaintext.internal;
import java.util.HashMap;
import java.util.Map;
import junit.framework.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.openengsb.domains.report.common.ReportStore;
import org.openengsb.domains.report.common.ReportStoreFactory;
public class PlaintextReportFactoryTest {
@Test
public void testCreatePlaintextReportService() throws Exception {
ReportStoreFactory storeFactory = Mockito.mock(ReportStoreFactory.class);
- Mockito.when(storeFactory.createReportStore(Mockito.anyString())).thenReturn(Mockito.mock(ReportStore.class));
+ ReportStore store = Mockito.mock(ReportStore.class);
+ Mockito.when(storeFactory.createReportStore(Mockito.anyString())).thenReturn(store);
PlaintextReportFactory factory = new PlaintextReportFactory(storeFactory);
Map<String, String> attributes = new HashMap<String, String>();
PlaintextReportService reportService = factory.createServiceInstance("id", attributes);
Assert.assertNotNull(reportService);
Assert.assertNotNull(reportService.getStore());
Assert.assertEquals("id", reportService.getId());
}
}
| true | true | public void testCreatePlaintextReportService() throws Exception {
ReportStoreFactory storeFactory = Mockito.mock(ReportStoreFactory.class);
Mockito.when(storeFactory.createReportStore(Mockito.anyString())).thenReturn(Mockito.mock(ReportStore.class));
PlaintextReportFactory factory = new PlaintextReportFactory(storeFactory);
Map<String, String> attributes = new HashMap<String, String>();
PlaintextReportService reportService = factory.createServiceInstance("id", attributes);
Assert.assertNotNull(reportService);
Assert.assertNotNull(reportService.getStore());
Assert.assertEquals("id", reportService.getId());
}
| public void testCreatePlaintextReportService() throws Exception {
ReportStoreFactory storeFactory = Mockito.mock(ReportStoreFactory.class);
ReportStore store = Mockito.mock(ReportStore.class);
Mockito.when(storeFactory.createReportStore(Mockito.anyString())).thenReturn(store);
PlaintextReportFactory factory = new PlaintextReportFactory(storeFactory);
Map<String, String> attributes = new HashMap<String, String>();
PlaintextReportService reportService = factory.createServiceInstance("id", attributes);
Assert.assertNotNull(reportService);
Assert.assertNotNull(reportService.getStore());
Assert.assertEquals("id", reportService.getId());
}
|
diff --git a/src/android/Capture.java b/src/android/Capture.java
index 780d092..a5a6ef7 100644
--- a/src/android/Capture.java
+++ b/src/android/Capture.java
@@ -1,447 +1,454 @@
/*
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.cordova.core;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.os.Build;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.LOG;
import org.apache.cordova.PluginResult;
import org.apache.cordova.FileHelper;
import org.apache.cordova.DirectoryManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
public class Capture extends CordovaPlugin {
private static final String VIDEO_3GPP = "video/3gpp";
private static final String VIDEO_MP4 = "video/mp4";
private static final String AUDIO_3GPP = "audio/3gpp";
private static final String IMAGE_JPEG = "image/jpeg";
private static final int CAPTURE_AUDIO = 0; // Constant for capture audio
private static final int CAPTURE_IMAGE = 1; // Constant for capture image
private static final int CAPTURE_VIDEO = 2; // Constant for capture video
private static final String LOG_TAG = "Capture";
private static final int CAPTURE_INTERNAL_ERR = 0;
// private static final int CAPTURE_APPLICATION_BUSY = 1;
// private static final int CAPTURE_INVALID_ARGUMENT = 2;
private static final int CAPTURE_NO_MEDIA_FILES = 3;
private CallbackContext callbackContext; // The callback context from which we were invoked.
private long limit; // the number of pics/vids/clips to take
private int duration; // optional max duration of video recording in seconds
private JSONArray results; // The array of results to be returned to the user
private int numPics; // Number of pictures before capture activity
//private CordovaInterface cordova;
// public void setContext(Context mCtx)
// {
// if (CordovaInterface.class.isInstance(mCtx))
// cordova = (CordovaInterface) mCtx;
// else
// LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity");
// }
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
this.callbackContext = callbackContext;
this.limit = 1;
this.duration = 0;
this.results = new JSONArray();
JSONObject options = args.optJSONObject(0);
if (options != null) {
limit = options.optLong("limit", 1);
duration = options.optInt("duration", 0);
}
if (action.equals("getFormatData")) {
JSONObject obj = getFormatData(args.getString(0), args.getString(1));
callbackContext.success(obj);
return true;
}
else if (action.equals("captureAudio")) {
this.captureAudio();
}
else if (action.equals("captureImage")) {
this.captureImage();
}
else if (action.equals("captureVideo")) {
this.captureVideo(duration);
}
else {
return false;
}
return true;
}
/**
* Provides the media data file data depending on it's mime type
*
* @param filePath path to the file
* @param mimeType of the file
* @return a MediaFileData object
*/
private JSONObject getFormatData(String filePath, String mimeType) throws JSONException {
JSONObject obj = new JSONObject();
// setup defaults
obj.put("height", 0);
obj.put("width", 0);
obj.put("bitrate", 0);
obj.put("duration", 0);
obj.put("codecs", "");
// If the mimeType isn't set the rest will fail
// so let's see if we can determine it.
if (mimeType == null || mimeType.equals("") || "null".equals(mimeType)) {
mimeType = FileHelper.getMimeType(filePath, cordova);
}
Log.d(LOG_TAG, "Mime type = " + mimeType);
if (mimeType.equals(IMAGE_JPEG) || filePath.endsWith(".jpg")) {
obj = getImageData(filePath, obj);
}
else if (mimeType.endsWith(AUDIO_3GPP)) {
obj = getAudioVideoData(filePath, obj, false);
}
else if (mimeType.equals(VIDEO_3GPP) || mimeType.equals(VIDEO_MP4)) {
obj = getAudioVideoData(filePath, obj, true);
}
return obj;
}
/**
* Get the Image specific attributes
*
* @param filePath path to the file
* @param obj represents the Media File Data
* @return a JSONObject that represents the Media File Data
* @throws JSONException
*/
private JSONObject getImageData(String filePath, JSONObject obj) throws JSONException {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(FileHelper.stripFileProtocol(filePath), options);
obj.put("height", options.outHeight);
obj.put("width", options.outWidth);
return obj;
}
/**
* Get the Image specific attributes
*
* @param filePath path to the file
* @param obj represents the Media File Data
* @param video if true get video attributes as well
* @return a JSONObject that represents the Media File Data
* @throws JSONException
*/
private JSONObject getAudioVideoData(String filePath, JSONObject obj, boolean video) throws JSONException {
MediaPlayer player = new MediaPlayer();
try {
player.setDataSource(filePath);
player.prepare();
obj.put("duration", player.getDuration() / 1000);
if (video) {
obj.put("height", player.getVideoHeight());
obj.put("width", player.getVideoWidth());
}
} catch (IOException e) {
Log.d(LOG_TAG, "Error: loading video file");
}
return obj;
}
/**
* Sets up an intent to capture audio. Result handled by onActivityResult()
*/
private void captureAudio() {
Intent intent = new Intent(android.provider.MediaStore.Audio.Media.RECORD_SOUND_ACTION);
this.cordova.startActivityForResult((CordovaPlugin) this, intent, CAPTURE_AUDIO);
}
/**
* Sets up an intent to capture images. Result handled by onActivityResult()
*/
private void captureImage() {
// Save the number of images currently on disk for later
this.numPics = queryImgDB(whichContentStore()).getCount();
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// Specify file so that large image is captured and returned
File photo = new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()), "Capture.jpg");
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
this.cordova.startActivityForResult((CordovaPlugin) this, intent, CAPTURE_IMAGE);
}
/**
* Sets up an intent to capture video. Result handled by onActivityResult()
*/
private void captureVideo(int duration) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
if(Build.VERSION.SDK_INT > 7){
intent.putExtra("android.intent.extra.durationLimit", duration);
}
this.cordova.startActivityForResult((CordovaPlugin) this, intent, CAPTURE_VIDEO);
}
/**
* Called when the video view exits.
*
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
* @throws JSONException
*/
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// Result received okay
if (resultCode == Activity.RESULT_OK) {
// An audio clip was requested
if (requestCode == CAPTURE_AUDIO) {
// Get the uri of the audio clip
Uri data = intent.getData();
// create a file object from the uri
results.put(createMediaFile(data));
if (results.length() >= limit) {
// Send Uri back to JavaScript for listening to audio
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
} else {
// still need to capture more audio clips
captureAudio();
}
} else if (requestCode == CAPTURE_IMAGE) {
// For some reason if I try to do:
// Uri data = intent.getData();
// It crashes in the emulator and on my phone with a null pointer exception
// To work around it I had to grab the code from CameraLauncher.java
try {
// Create entry in media store for image
// (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
ContentValues values = new ContentValues();
values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, IMAGE_JPEG);
Uri uri = null;
try {
uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException e) {
LOG.d(LOG_TAG, "Can't write to external media storage.");
try {
uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException ex) {
LOG.d(LOG_TAG, "Can't write to internal media storage.");
this.fail(createErrorObject(CAPTURE_INTERNAL_ERR, "Error capturing image - no media storage found."));
return;
}
}
FileInputStream fis = new FileInputStream(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()) + "/Capture.jpg");
OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
byte[] buffer = new byte[4096];
int len;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.flush();
os.close();
fis.close();
// Add image to results
results.put(createMediaFile(uri));
checkForDuplicateImage();
if (results.length() >= limit) {
// Send Uri back to JavaScript for viewing image
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
} else {
// still need to capture more images
captureImage();
}
} catch (IOException e) {
e.printStackTrace();
this.fail(createErrorObject(CAPTURE_INTERNAL_ERR, "Error capturing image."));
}
} else if (requestCode == CAPTURE_VIDEO) {
// Get the uri of the video clip
Uri data = intent.getData();
// create a file object from the uri
- results.put(createMediaFile(data));
+ if(data == null)
+ {
+ this.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Error: data is null"));
+ }
+ else
+ {
+ results.put(createMediaFile(data));
- if (results.length() >= limit) {
- // Send Uri back to JavaScript for viewing video
- this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
- } else {
- // still need to capture more video clips
- captureVideo(duration);
+ if (results.length() >= limit) {
+ // Send Uri back to JavaScript for viewing video
+ this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
+ } else {
+ // still need to capture more video clips
+ captureVideo(duration);
+ }
}
}
}
// If canceled
else if (resultCode == Activity.RESULT_CANCELED) {
// If we have partial results send them back to the user
if (results.length() > 0) {
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
}
// user canceled the action
else {
this.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Canceled."));
}
}
// If something else
else {
// If we have partial results send them back to the user
if (results.length() > 0) {
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
}
// something bad happened
else {
this.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Did not complete!"));
}
}
}
/**
* Creates a JSONObject that represents a File from the Uri
*
* @param data the Uri of the audio/image/video
* @return a JSONObject that represents a File
* @throws IOException
*/
private JSONObject createMediaFile(Uri data) {
File fp = new File(FileHelper.getRealPath(data, this.cordova));
JSONObject obj = new JSONObject();
try {
// File properties
obj.put("name", fp.getName());
obj.put("fullPath", "file://" + fp.getAbsolutePath());
// Because of an issue with MimeTypeMap.getMimeTypeFromExtension() all .3gpp files
// are reported as video/3gpp. I'm doing this hacky check of the URI to see if it
// is stored in the audio or video content store.
if (fp.getAbsoluteFile().toString().endsWith(".3gp") || fp.getAbsoluteFile().toString().endsWith(".3gpp")) {
if (data.toString().contains("/audio/")) {
obj.put("type", AUDIO_3GPP);
} else {
obj.put("type", VIDEO_3GPP);
}
} else {
obj.put("type", FileHelper.getMimeType(fp.getAbsolutePath(), cordova));
}
obj.put("lastModifiedDate", fp.lastModified());
obj.put("size", fp.length());
} catch (JSONException e) {
// this will never happen
e.printStackTrace();
}
return obj;
}
private JSONObject createErrorObject(int code, String message) {
JSONObject obj = new JSONObject();
try {
obj.put("code", code);
obj.put("message", message);
} catch (JSONException e) {
// This will never happen
}
return obj;
}
/**
* Send error message to JavaScript.
*
* @param err
*/
public void fail(JSONObject err) {
this.callbackContext.error(err);
}
/**
* Creates a cursor that can be used to determine how many images we have.
*
* @return a cursor
*/
private Cursor queryImgDB(Uri contentStore) {
return this.cordova.getActivity().getContentResolver().query(
contentStore,
new String[] { MediaStore.Images.Media._ID },
null,
null,
null);
}
/**
* Used to find out if we are in a situation where the Camera Intent adds to images
* to the content store.
*/
private void checkForDuplicateImage() {
Uri contentStore = whichContentStore();
Cursor cursor = queryImgDB(contentStore);
int currentNumOfImages = cursor.getCount();
// delete the duplicate file if the difference is 2
if ((currentNumOfImages - numPics) == 2) {
cursor.moveToLast();
int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID))) - 1;
Uri uri = Uri.parse(contentStore + "/" + id);
this.cordova.getActivity().getContentResolver().delete(uri, null, null);
}
}
/**
* Determine if we are storing the images in internal or external storage
* @return Uri
*/
private Uri whichContentStore() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else {
return android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI;
}
}
}
| false | true | public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// Result received okay
if (resultCode == Activity.RESULT_OK) {
// An audio clip was requested
if (requestCode == CAPTURE_AUDIO) {
// Get the uri of the audio clip
Uri data = intent.getData();
// create a file object from the uri
results.put(createMediaFile(data));
if (results.length() >= limit) {
// Send Uri back to JavaScript for listening to audio
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
} else {
// still need to capture more audio clips
captureAudio();
}
} else if (requestCode == CAPTURE_IMAGE) {
// For some reason if I try to do:
// Uri data = intent.getData();
// It crashes in the emulator and on my phone with a null pointer exception
// To work around it I had to grab the code from CameraLauncher.java
try {
// Create entry in media store for image
// (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
ContentValues values = new ContentValues();
values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, IMAGE_JPEG);
Uri uri = null;
try {
uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException e) {
LOG.d(LOG_TAG, "Can't write to external media storage.");
try {
uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException ex) {
LOG.d(LOG_TAG, "Can't write to internal media storage.");
this.fail(createErrorObject(CAPTURE_INTERNAL_ERR, "Error capturing image - no media storage found."));
return;
}
}
FileInputStream fis = new FileInputStream(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()) + "/Capture.jpg");
OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
byte[] buffer = new byte[4096];
int len;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.flush();
os.close();
fis.close();
// Add image to results
results.put(createMediaFile(uri));
checkForDuplicateImage();
if (results.length() >= limit) {
// Send Uri back to JavaScript for viewing image
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
} else {
// still need to capture more images
captureImage();
}
} catch (IOException e) {
e.printStackTrace();
this.fail(createErrorObject(CAPTURE_INTERNAL_ERR, "Error capturing image."));
}
} else if (requestCode == CAPTURE_VIDEO) {
// Get the uri of the video clip
Uri data = intent.getData();
// create a file object from the uri
results.put(createMediaFile(data));
if (results.length() >= limit) {
// Send Uri back to JavaScript for viewing video
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
} else {
// still need to capture more video clips
captureVideo(duration);
}
}
}
// If canceled
else if (resultCode == Activity.RESULT_CANCELED) {
// If we have partial results send them back to the user
if (results.length() > 0) {
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
}
// user canceled the action
else {
this.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Canceled."));
}
}
// If something else
else {
// If we have partial results send them back to the user
if (results.length() > 0) {
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
}
// something bad happened
else {
this.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Did not complete!"));
}
}
}
| public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// Result received okay
if (resultCode == Activity.RESULT_OK) {
// An audio clip was requested
if (requestCode == CAPTURE_AUDIO) {
// Get the uri of the audio clip
Uri data = intent.getData();
// create a file object from the uri
results.put(createMediaFile(data));
if (results.length() >= limit) {
// Send Uri back to JavaScript for listening to audio
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
} else {
// still need to capture more audio clips
captureAudio();
}
} else if (requestCode == CAPTURE_IMAGE) {
// For some reason if I try to do:
// Uri data = intent.getData();
// It crashes in the emulator and on my phone with a null pointer exception
// To work around it I had to grab the code from CameraLauncher.java
try {
// Create entry in media store for image
// (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
ContentValues values = new ContentValues();
values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, IMAGE_JPEG);
Uri uri = null;
try {
uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException e) {
LOG.d(LOG_TAG, "Can't write to external media storage.");
try {
uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException ex) {
LOG.d(LOG_TAG, "Can't write to internal media storage.");
this.fail(createErrorObject(CAPTURE_INTERNAL_ERR, "Error capturing image - no media storage found."));
return;
}
}
FileInputStream fis = new FileInputStream(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()) + "/Capture.jpg");
OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
byte[] buffer = new byte[4096];
int len;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.flush();
os.close();
fis.close();
// Add image to results
results.put(createMediaFile(uri));
checkForDuplicateImage();
if (results.length() >= limit) {
// Send Uri back to JavaScript for viewing image
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
} else {
// still need to capture more images
captureImage();
}
} catch (IOException e) {
e.printStackTrace();
this.fail(createErrorObject(CAPTURE_INTERNAL_ERR, "Error capturing image."));
}
} else if (requestCode == CAPTURE_VIDEO) {
// Get the uri of the video clip
Uri data = intent.getData();
// create a file object from the uri
if(data == null)
{
this.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Error: data is null"));
}
else
{
results.put(createMediaFile(data));
if (results.length() >= limit) {
// Send Uri back to JavaScript for viewing video
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
} else {
// still need to capture more video clips
captureVideo(duration);
}
}
}
}
// If canceled
else if (resultCode == Activity.RESULT_CANCELED) {
// If we have partial results send them back to the user
if (results.length() > 0) {
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
}
// user canceled the action
else {
this.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Canceled."));
}
}
// If something else
else {
// If we have partial results send them back to the user
if (results.length() > 0) {
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
}
// something bad happened
else {
this.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Did not complete!"));
}
}
}
|
diff --git a/src/com/sk/PhpCommunicator.java b/src/com/sk/PhpCommunicator.java
index 17dd91d..d8b4030 100644
--- a/src/com/sk/PhpCommunicator.java
+++ b/src/com/sk/PhpCommunicator.java
@@ -1,103 +1,102 @@
package com.sk;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import org.apache.commons.codec.binary.Base64;
import com.google.gson.JsonObject;
import com.sk.stat.PersonStatistics;
import com.sk.stat.StatisticsController;
import com.sk.util.PersonalDataStorage;
public class PhpCommunicator implements Runnable {
private final Socket sock;
private final SearchController searcher;
private MessageDigest digest;
private final String receiveShake = "GrabName";
private final String sendShake = "NameGrabber";
public PhpCommunicator(Socket sock, SearchController searcher) {
this.sock = sock;
this.searcher = searcher;
try {
this.digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
@Override
public void run() {
System.out.println("Talking to socket");
try {
if (sock.isClosed() || sock.isInputShutdown() || sock.isOutputShutdown() || !sock.isConnected()) {
System.out.println("Bad socket on start");
return;
}
sock.setKeepAlive(true);
BufferedReader read = new BufferedReader(new InputStreamReader(sock.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())));
String line = read.readLine();
System.out.println("Received handshake " + line);
String[] parts = line.split("[|]");
if (parts.length != 2 || parts[0].length() < 5) {
System.out.println("Bad input handshake");
sock.close();
return;
}
if (!Arrays.equals(digest.digest((parts[0] + receiveShake).getBytes()), Base64.decodeBase64(parts[1])))
return;
String curTime = System.currentTimeMillis() + "";
out.println(curTime + "|" + Base64.encodeBase64String(digest.digest((curTime + sendShake).getBytes())));
out.flush();
String request = read.readLine();
System.out.println("Received names " + request);
String[] names = request.split("[|]");
if (names.length != 2) {
System.out.println("Bad names separation");
sock.close();
return;
}
JsonObject result = new JsonObject();
String first = URLDecoder.decode(names[0], "UTF-8"), last = URLDecoder.decode(names[1], "UTF-8");
long start = System.currentTimeMillis();
if (!searcher.lookForName(first, last)) {
result.addProperty("error", "Could not find names");
} else {
PersonalDataStorage store = searcher.getDataStorage();
if (store == null) {
result.addProperty("error", "Failed to get data storage");
} else {
System.out.printf("Found %d results in %d millis%n", store.size(), System.currentTimeMillis()
- start);
PersonStatistics stat = StatisticsController.get().generateStat(first, last, store.toArray());
if (stat == null) {
result.addProperty("error", "Failed to generate statistics");
} else {
result.add("stat", Driver.getGson().toJsonTree(stat, PersonStatistics.class));
}
}
}
out.println(result);
out.flush();
- out.close();
sock.close();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
System.out.println("Done talking");
}
}
}
| true | true | public void run() {
System.out.println("Talking to socket");
try {
if (sock.isClosed() || sock.isInputShutdown() || sock.isOutputShutdown() || !sock.isConnected()) {
System.out.println("Bad socket on start");
return;
}
sock.setKeepAlive(true);
BufferedReader read = new BufferedReader(new InputStreamReader(sock.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())));
String line = read.readLine();
System.out.println("Received handshake " + line);
String[] parts = line.split("[|]");
if (parts.length != 2 || parts[0].length() < 5) {
System.out.println("Bad input handshake");
sock.close();
return;
}
if (!Arrays.equals(digest.digest((parts[0] + receiveShake).getBytes()), Base64.decodeBase64(parts[1])))
return;
String curTime = System.currentTimeMillis() + "";
out.println(curTime + "|" + Base64.encodeBase64String(digest.digest((curTime + sendShake).getBytes())));
out.flush();
String request = read.readLine();
System.out.println("Received names " + request);
String[] names = request.split("[|]");
if (names.length != 2) {
System.out.println("Bad names separation");
sock.close();
return;
}
JsonObject result = new JsonObject();
String first = URLDecoder.decode(names[0], "UTF-8"), last = URLDecoder.decode(names[1], "UTF-8");
long start = System.currentTimeMillis();
if (!searcher.lookForName(first, last)) {
result.addProperty("error", "Could not find names");
} else {
PersonalDataStorage store = searcher.getDataStorage();
if (store == null) {
result.addProperty("error", "Failed to get data storage");
} else {
System.out.printf("Found %d results in %d millis%n", store.size(), System.currentTimeMillis()
- start);
PersonStatistics stat = StatisticsController.get().generateStat(first, last, store.toArray());
if (stat == null) {
result.addProperty("error", "Failed to generate statistics");
} else {
result.add("stat", Driver.getGson().toJsonTree(stat, PersonStatistics.class));
}
}
}
out.println(result);
out.flush();
out.close();
sock.close();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
System.out.println("Done talking");
}
}
| public void run() {
System.out.println("Talking to socket");
try {
if (sock.isClosed() || sock.isInputShutdown() || sock.isOutputShutdown() || !sock.isConnected()) {
System.out.println("Bad socket on start");
return;
}
sock.setKeepAlive(true);
BufferedReader read = new BufferedReader(new InputStreamReader(sock.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())));
String line = read.readLine();
System.out.println("Received handshake " + line);
String[] parts = line.split("[|]");
if (parts.length != 2 || parts[0].length() < 5) {
System.out.println("Bad input handshake");
sock.close();
return;
}
if (!Arrays.equals(digest.digest((parts[0] + receiveShake).getBytes()), Base64.decodeBase64(parts[1])))
return;
String curTime = System.currentTimeMillis() + "";
out.println(curTime + "|" + Base64.encodeBase64String(digest.digest((curTime + sendShake).getBytes())));
out.flush();
String request = read.readLine();
System.out.println("Received names " + request);
String[] names = request.split("[|]");
if (names.length != 2) {
System.out.println("Bad names separation");
sock.close();
return;
}
JsonObject result = new JsonObject();
String first = URLDecoder.decode(names[0], "UTF-8"), last = URLDecoder.decode(names[1], "UTF-8");
long start = System.currentTimeMillis();
if (!searcher.lookForName(first, last)) {
result.addProperty("error", "Could not find names");
} else {
PersonalDataStorage store = searcher.getDataStorage();
if (store == null) {
result.addProperty("error", "Failed to get data storage");
} else {
System.out.printf("Found %d results in %d millis%n", store.size(), System.currentTimeMillis()
- start);
PersonStatistics stat = StatisticsController.get().generateStat(first, last, store.toArray());
if (stat == null) {
result.addProperty("error", "Failed to generate statistics");
} else {
result.add("stat", Driver.getGson().toJsonTree(stat, PersonStatistics.class));
}
}
}
out.println(result);
out.flush();
sock.close();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
System.out.println("Done talking");
}
}
|
diff --git a/Varargs/src/VarargsTest.java b/Varargs/src/VarargsTest.java
index 9bd6dae..ac24ec6 100644
--- a/Varargs/src/VarargsTest.java
+++ b/Varargs/src/VarargsTest.java
@@ -1,42 +1,42 @@
public class VarargsTest {
/**
* @param args
*/
public static void main(String[] args) {
passMeVarArgs(1, 2, 3, 4, 5);
System.out.println("\r\n+++++++++++++++++++");
passMeVarArgs();
- System.out.println("\r\n+++++++++++++++++++");
+ System.out.println("+++++++++++++++++++");
passMeVarArgs(1, 3, 5);
System.out.println("\r\n+++++++++++++++++++");
try {
passMeVarArgs(null);
} catch (IllegalArgumentException e) {
System.out.println("[null]");
}
}
private static void passMeVarArgs(int... args) {
if(args == null){
throw new IllegalArgumentException("Argument 'args' must not be null");
}
if(args.length == 0){
System.out.println("[empty]");
return;
}
for (int i : args) {
System.out.print(i);
}
}
}
| true | true | public static void main(String[] args) {
passMeVarArgs(1, 2, 3, 4, 5);
System.out.println("\r\n+++++++++++++++++++");
passMeVarArgs();
System.out.println("\r\n+++++++++++++++++++");
passMeVarArgs(1, 3, 5);
System.out.println("\r\n+++++++++++++++++++");
try {
passMeVarArgs(null);
} catch (IllegalArgumentException e) {
System.out.println("[null]");
}
}
| public static void main(String[] args) {
passMeVarArgs(1, 2, 3, 4, 5);
System.out.println("\r\n+++++++++++++++++++");
passMeVarArgs();
System.out.println("+++++++++++++++++++");
passMeVarArgs(1, 3, 5);
System.out.println("\r\n+++++++++++++++++++");
try {
passMeVarArgs(null);
} catch (IllegalArgumentException e) {
System.out.println("[null]");
}
}
|
diff --git a/src/main/java/grisu/gricli/command/SetCommand.java b/src/main/java/grisu/gricli/command/SetCommand.java
index 2786591..18d7d61 100644
--- a/src/main/java/grisu/gricli/command/SetCommand.java
+++ b/src/main/java/grisu/gricli/command/SetCommand.java
@@ -1,165 +1,165 @@
package grisu.gricli.command;
import grisu.gricli.GricliRuntimeException;
import grisu.gricli.completors.VarCompletor;
import grisu.gricli.completors.VarValueCompletor;
import grisu.gricli.environment.GricliEnvironment;
import grisu.gricli.environment.GricliVar;
import grisu.jcommons.constants.Constants;
import grisu.jcommons.constants.JobSubmissionProperty;
import grisu.model.info.ApplicationInformation;
import grisu.model.info.dto.DtoProperty;
import grisu.model.info.dto.JobQueueMatch;
import grisu.model.info.dto.Queue;
import grisu.model.job.JobDescription;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Maps;
public class SetCommand implements GricliCommand {
static final Logger myLogger = LoggerFactory.getLogger(SetCommand.class
.getName());
private final String global;
private final String[] values;
@SyntaxDescription(command = { "unset" }, arguments = { "var" })
@AutoComplete(completors = { VarCompletor.class })
public SetCommand(String global) {
this(global, null);
}
@SyntaxDescription(command = { "set" }, arguments = { "var", "value" })
@AutoComplete(completors = { VarCompletor.class, VarValueCompletor.class })
public SetCommand(String global, String value) {
this.global = global;
this.values = new String[] { value };
}
public void execute(final GricliEnvironment env)
throws GricliRuntimeException {
validate(env);
env.getVariable(global).set(values);
}
private void validate(GricliEnvironment env) throws GricliRuntimeException {
if (Constants.QUEUE_KEY.equals(global)) {
if (StringUtils.isBlank(values[0])
|| Constants.NO_SUBMISSION_LOCATION_INDICATOR_STRING
.equals(values[0])) {
return;
}
JobDescription j = env.getJob();
Map<JobSubmissionProperty, String> props = Maps.newHashMap(j
.getJobSubmissionPropertyMap());
final String fqan = env.group.get();
final String app = env.application.get();
final ApplicationInformation ai = env.getGrisuRegistry()
.getApplicationInformation(app);
final List<JobQueueMatch> allQueues = ai.getMatches(props, fqan);
JobQueueMatch match = JobQueueMatch.getMatch(allQueues, values[0]);
if (match == null) {
throw new GricliRuntimeException("Queue '" + values[0]
+ "' not a valid queuename.");
}
if (!match.isValid()) {
String message = "\nQueue '" + values[0]
+ "' not valid for current job setup:\n\n";
for (DtoProperty prop : match.getPropertiesDetails()
.getProperties()) {
message = message
+ ("\t" + prop.getKey() + ":\t" + prop.getValue() + "\n");
}
throw new GricliRuntimeException(message);
}
} else {
GricliVar<String> queueVar = (GricliVar<String>) env
.getVariable(Constants.QUEUE_KEY);
String queue = queueVar.get();
if (queue == null) {
if ("package".equals(global)) {
- String[] newValue = values;
+// String[] newValue = values;
GricliVar<String> packageName = (GricliVar<String>) env.getVariable("package");
Object oldPackage = null;
if ( packageName != null ) {
oldPackage = packageName.get();
}
- if ( values.length == 1 && ! values[0].equals(oldPackage) ) {
+ if ( values != null && values.length == 1 && ! values[0].equals(oldPackage) ) {
GricliVar<String> version = (GricliVar<String>)env.getVariable("version");
version.set((String)null);
}
}
myLogger.debug("Queue not set, not checking whether global is valid in this context.");
return;
}
GricliVar<String> version = (GricliVar<String>) env.getVariable("version");
Object oldVersion = null;
if ( version != null ) {
oldVersion = version.get();
}
if ("package".equals(global)) {
version.set((String)null);
}
GricliVar<?> var = env.getVariable(global);
Object oldValue = var.get();
env.getVariable(global).set(values);
JobDescription j = env.getJob();
Map<JobSubmissionProperty, String> props = Maps.newHashMap(j
.getJobSubmissionPropertyMap());
final String fqan = env.group.get();
final String app = env.application.get();
final ApplicationInformation ai = env.getGrisuRegistry()
.getApplicationInformation(app);
final List<Queue> queues = ai.getQueues(props, fqan);
Queue q = Queue.getQueue(queues, queue);
if (q == null) {
env.getVariable(global).setValue(oldValue);
if ( oldVersion != null ) {
version.setValue(oldVersion);
}
throw new GricliRuntimeException(
"Can't set global "
+ global
+ ": outside of specifications of currently set queue '"
+ queue
+ "'. Either change value or unset/change the queue.");
}
}
}
}
| false | true | private void validate(GricliEnvironment env) throws GricliRuntimeException {
if (Constants.QUEUE_KEY.equals(global)) {
if (StringUtils.isBlank(values[0])
|| Constants.NO_SUBMISSION_LOCATION_INDICATOR_STRING
.equals(values[0])) {
return;
}
JobDescription j = env.getJob();
Map<JobSubmissionProperty, String> props = Maps.newHashMap(j
.getJobSubmissionPropertyMap());
final String fqan = env.group.get();
final String app = env.application.get();
final ApplicationInformation ai = env.getGrisuRegistry()
.getApplicationInformation(app);
final List<JobQueueMatch> allQueues = ai.getMatches(props, fqan);
JobQueueMatch match = JobQueueMatch.getMatch(allQueues, values[0]);
if (match == null) {
throw new GricliRuntimeException("Queue '" + values[0]
+ "' not a valid queuename.");
}
if (!match.isValid()) {
String message = "\nQueue '" + values[0]
+ "' not valid for current job setup:\n\n";
for (DtoProperty prop : match.getPropertiesDetails()
.getProperties()) {
message = message
+ ("\t" + prop.getKey() + ":\t" + prop.getValue() + "\n");
}
throw new GricliRuntimeException(message);
}
} else {
GricliVar<String> queueVar = (GricliVar<String>) env
.getVariable(Constants.QUEUE_KEY);
String queue = queueVar.get();
if (queue == null) {
if ("package".equals(global)) {
String[] newValue = values;
GricliVar<String> packageName = (GricliVar<String>) env.getVariable("package");
Object oldPackage = null;
if ( packageName != null ) {
oldPackage = packageName.get();
}
if ( values.length == 1 && ! values[0].equals(oldPackage) ) {
GricliVar<String> version = (GricliVar<String>)env.getVariable("version");
version.set((String)null);
}
}
myLogger.debug("Queue not set, not checking whether global is valid in this context.");
return;
}
GricliVar<String> version = (GricliVar<String>) env.getVariable("version");
Object oldVersion = null;
if ( version != null ) {
oldVersion = version.get();
}
if ("package".equals(global)) {
version.set((String)null);
}
GricliVar<?> var = env.getVariable(global);
Object oldValue = var.get();
env.getVariable(global).set(values);
JobDescription j = env.getJob();
Map<JobSubmissionProperty, String> props = Maps.newHashMap(j
.getJobSubmissionPropertyMap());
final String fqan = env.group.get();
final String app = env.application.get();
final ApplicationInformation ai = env.getGrisuRegistry()
.getApplicationInformation(app);
final List<Queue> queues = ai.getQueues(props, fqan);
Queue q = Queue.getQueue(queues, queue);
if (q == null) {
env.getVariable(global).setValue(oldValue);
if ( oldVersion != null ) {
version.setValue(oldVersion);
}
throw new GricliRuntimeException(
"Can't set global "
+ global
+ ": outside of specifications of currently set queue '"
+ queue
+ "'. Either change value or unset/change the queue.");
}
}
}
| private void validate(GricliEnvironment env) throws GricliRuntimeException {
if (Constants.QUEUE_KEY.equals(global)) {
if (StringUtils.isBlank(values[0])
|| Constants.NO_SUBMISSION_LOCATION_INDICATOR_STRING
.equals(values[0])) {
return;
}
JobDescription j = env.getJob();
Map<JobSubmissionProperty, String> props = Maps.newHashMap(j
.getJobSubmissionPropertyMap());
final String fqan = env.group.get();
final String app = env.application.get();
final ApplicationInformation ai = env.getGrisuRegistry()
.getApplicationInformation(app);
final List<JobQueueMatch> allQueues = ai.getMatches(props, fqan);
JobQueueMatch match = JobQueueMatch.getMatch(allQueues, values[0]);
if (match == null) {
throw new GricliRuntimeException("Queue '" + values[0]
+ "' not a valid queuename.");
}
if (!match.isValid()) {
String message = "\nQueue '" + values[0]
+ "' not valid for current job setup:\n\n";
for (DtoProperty prop : match.getPropertiesDetails()
.getProperties()) {
message = message
+ ("\t" + prop.getKey() + ":\t" + prop.getValue() + "\n");
}
throw new GricliRuntimeException(message);
}
} else {
GricliVar<String> queueVar = (GricliVar<String>) env
.getVariable(Constants.QUEUE_KEY);
String queue = queueVar.get();
if (queue == null) {
if ("package".equals(global)) {
// String[] newValue = values;
GricliVar<String> packageName = (GricliVar<String>) env.getVariable("package");
Object oldPackage = null;
if ( packageName != null ) {
oldPackage = packageName.get();
}
if ( values != null && values.length == 1 && ! values[0].equals(oldPackage) ) {
GricliVar<String> version = (GricliVar<String>)env.getVariable("version");
version.set((String)null);
}
}
myLogger.debug("Queue not set, not checking whether global is valid in this context.");
return;
}
GricliVar<String> version = (GricliVar<String>) env.getVariable("version");
Object oldVersion = null;
if ( version != null ) {
oldVersion = version.get();
}
if ("package".equals(global)) {
version.set((String)null);
}
GricliVar<?> var = env.getVariable(global);
Object oldValue = var.get();
env.getVariable(global).set(values);
JobDescription j = env.getJob();
Map<JobSubmissionProperty, String> props = Maps.newHashMap(j
.getJobSubmissionPropertyMap());
final String fqan = env.group.get();
final String app = env.application.get();
final ApplicationInformation ai = env.getGrisuRegistry()
.getApplicationInformation(app);
final List<Queue> queues = ai.getQueues(props, fqan);
Queue q = Queue.getQueue(queues, queue);
if (q == null) {
env.getVariable(global).setValue(oldValue);
if ( oldVersion != null ) {
version.setValue(oldVersion);
}
throw new GricliRuntimeException(
"Can't set global "
+ global
+ ": outside of specifications of currently set queue '"
+ queue
+ "'. Either change value or unset/change the queue.");
}
}
}
|
diff --git a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/util/HTML2Content.java b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/util/HTML2Content.java
index 57efd7ccb..c2b79ea52 100644
--- a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/util/HTML2Content.java
+++ b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/util/HTML2Content.java
@@ -1,689 +1,689 @@
/***********************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
***********************************************************************/
package org.eclipse.birt.report.engine.layout.pdf.util;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.birt.report.engine.content.IContainerContent;
import org.eclipse.birt.report.engine.content.IContent;
import org.eclipse.birt.report.engine.content.IForeignContent;
import org.eclipse.birt.report.engine.content.IImageContent;
import org.eclipse.birt.report.engine.content.ILabelContent;
import org.eclipse.birt.report.engine.content.IReportContent;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.content.impl.ActionContent;
import org.eclipse.birt.report.engine.content.impl.ReportContent;
import org.eclipse.birt.report.engine.content.impl.TextContent;
import org.eclipse.birt.report.engine.css.dom.StyleDeclaration;
import org.eclipse.birt.report.engine.css.engine.value.css.CSSValueConstants;
import org.eclipse.birt.report.engine.ir.DimensionType;
import org.eclipse.birt.report.engine.ir.EngineIRConstants;
import org.eclipse.birt.report.engine.parser.TextParser;
import org.eclipse.birt.report.engine.util.FileUtil;
import org.eclipse.birt.report.model.api.IResourceLocator;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.css.CSSValue;
public class HTML2Content
{
protected static final HashSet htmlDisplayMode = new HashSet( );
protected static final HashMap textTypeMapping = new HashMap( );
static
{
// block-level elements
htmlDisplayMode.add( "dd" ); //$NON-NLS-1$
htmlDisplayMode.add( "div" ); //$NON-NLS-1$
htmlDisplayMode.add( "dl" ); //$NON-NLS-1$
htmlDisplayMode.add( "dt" ); //$NON-NLS-1$
htmlDisplayMode.add( "h1" ); //$NON-NLS-1$
htmlDisplayMode.add( "h2" ); //$NON-NLS-1$
htmlDisplayMode.add( "h3" ); //$NON-NLS-1$
htmlDisplayMode.add( "h4" ); //$NON-NLS-1$
htmlDisplayMode.add( "h5" ); //$NON-NLS-1$
htmlDisplayMode.add( "h6" ); //$NON-NLS-1$
htmlDisplayMode.add( "hr" ); //$NON-NLS-1$
htmlDisplayMode.add( "ol" ); //$NON-NLS-1$
htmlDisplayMode.add( "p" ); //$NON-NLS-1$
htmlDisplayMode.add( "pre" ); //$NON-NLS-1$
htmlDisplayMode.add( "ul" ); //$NON-NLS-1$
htmlDisplayMode.add( "li" ); //$NON-NLS-1$
htmlDisplayMode.add( "address" ); //$NON-NLS-1$
htmlDisplayMode.add( "body" ); //$NON-NLS-1$
htmlDisplayMode.add( "center" ); //$NON-NLS-1$
htmlDisplayMode.add( "table" ); //$NON-NLS-1$
textTypeMapping.put( IForeignContent.HTML_TYPE,
TextParser.TEXT_TYPE_HTML );
textTypeMapping.put( IForeignContent.TEXT_TYPE,
TextParser.TEXT_TYPE_PLAIN );
textTypeMapping.put( IForeignContent.UNKNOWN_TYPE,
TextParser.TEXT_TYPE_AUTO );
}
public static void html2Content( IForeignContent foreign )
{
processForeignData( foreign );
}
protected static void processForeignData( IForeignContent foreign )
{
if ( foreign.getChildren( ) != null
&& foreign.getChildren( ).size( ) > 0 )
{
return;
}
HashMap styleMap = new HashMap( );
ReportDesignHandle reportDesign = foreign.getReportContent( )
.getDesign( ).getReportDesign( );
HTMLStyleProcessor htmlProcessor = new HTMLStyleProcessor( reportDesign );
Object rawValue = foreign.getRawValue( );
Document doc = null;
if ( null != rawValue )
{
doc = new TextParser( ).parse( foreign.getRawValue( ).toString( ),
(String) textTypeMapping.get( foreign.getRawType( ) ) );
}
Element body = null;
if ( doc != null )
{
Node node = doc.getFirstChild( );
// The following must be true
if ( node instanceof Element )
{
body = (Element) node;
}
}
if ( body != null )
{
htmlProcessor.execute( body, styleMap );
IContainerContent container = foreign.getReportContent( )
.createContainerContent( );
IStyle parentStyle = foreign.getStyle( );
if ( CSSValueConstants.INLINE_VALUE.equals( parentStyle
.getProperty( IStyle.STYLE_DISPLAY ) ) )
{
container.getStyle( ).setProperty( IStyle.STYLE_DISPLAY,
CSSValueConstants.INLINE_VALUE );
}
addChild( foreign, container );
processNodes( body, styleMap, container, null );
formalizeInlineContainer( new ArrayList( ), foreign, container );
}
}
/**
* Visits the children nodes of the specific node
*
* @param ele
* the specific node
* @param needEscape
* the flag indicating the content needs escaping
* @param cssStyles
* @param content
* the parent content of the element
*
*/
static void processNodes( Element ele, Map cssStyles, IContent content,
ActionContent action )
{
int level = 0;
for ( Node node = ele.getFirstChild( ); node != null; node = node
.getNextSibling( ) )
{
if ( node.getNodeName( ).equals( "value-of" ) ) //$NON-NLS-1$
{
if ( node.getFirstChild( ) instanceof Element )
{
processNodes( (Element) node.getFirstChild( ), cssStyles,
content, action );
}
}
else if ( node.getNodeName( ).equals( "image" ) ) //$NON-NLS-1$
{
if ( node.getFirstChild( ) instanceof Element )
{
processNodes( (Element) node.getFirstChild( ), cssStyles,
content, action );
}
}
else if ( node.getNodeType( ) == Node.TEXT_NODE )
{
ILabelContent label = content.getReportContent( )
.createLabelContent( );
addChild( content, label );
label.setText( node.getNodeValue( ) );
StyleDeclaration inlineStyle = new StyleDeclaration( content
.getCSSEngine( ) );
inlineStyle.setProperty( IStyle.STYLE_DISPLAY,
CSSValueConstants.INLINE_VALUE );
label.setInlineStyle( inlineStyle );
if ( action != null )
{
label.setHyperlinkAction( action );
}
}
else if ( // supportedHTMLElementTags.contains(node.getNodeName().toUpperCase())
// &&
node.getNodeType( ) == Node.ELEMENT_NODE )
{
handleElement( (Element) node, cssStyles, content, action,
++level );
}
}
}
static void handleElement( Element ele, Map cssStyles, IContent content,
ActionContent action, int index )
{
IStyle cssStyle = (IStyle) cssStyles.get( ele );
if ( cssStyle != null )
{
if ( "none".equals( cssStyle.getDisplay( ) ) ) //$NON-NLS-1$
{
// Check if the display mode is none.
return;
}
}
String tagName = ele.getTagName( );
if ( tagName.toLowerCase( ).equals( "a" ) ) //$NON-NLS-1$
{
IContainerContent container = content.getReportContent( )
.createContainerContent( );
addChild( content, container );
handleStyle( ele, cssStyles, container );
ActionContent actionContent = handleAnchor( ele, container, action );
processNodes( ele, cssStyles, content, actionContent );
}
else if ( tagName.toLowerCase( ).equals( "img" ) ) //$NON-NLS-1$
{
outputImg( ele, cssStyles, content );
}
else if ( tagName.toLowerCase( ).equals( "br" ) ) //$NON-NLS-1$
{
ILabelContent label = content.getReportContent( )
.createLabelContent( );
addChild( content, label );
label.setText( "\n" ); //$NON-NLS-1$
StyleDeclaration inlineStyle = new StyleDeclaration( content
.getCSSEngine( ) );
inlineStyle.setProperty( IStyle.STYLE_DISPLAY,
CSSValueConstants.INLINE_VALUE );
label.setInlineStyle( inlineStyle );
}
else if ( tagName.toLowerCase( ).equals( "li" ) //$NON-NLS-1$
&& ele.getParentNode( ).getNodeType( ) == Node.ELEMENT_NODE )
{
StyleDeclaration style = new StyleDeclaration( content
.getCSSEngine( ) );
style.setProperty( IStyle.STYLE_DISPLAY,
CSSValueConstants.BLOCK_VALUE );
style.setProperty( IStyle.STYLE_VERTICAL_ALIGN,
CSSValueConstants.MIDDLE_VALUE );
IContainerContent container = content.getReportContent( )
.createContainerContent( );
container.setInlineStyle( style );
addChild( content, container );
handleStyle( ele, cssStyles, container );
// fix scr 157259In PDF <li> effect is incorrect when page break
// happens.
// add a container to number serial, keep consistent page-break
style = new StyleDeclaration( content.getCSSEngine( ) );
style.setProperty( IStyle.STYLE_DISPLAY,
CSSValueConstants.INLINE_VALUE );
style.setProperty( IStyle.STYLE_VERTICAL_ALIGN,
CSSValueConstants.TOP_VALUE );
IContainerContent orderContainer = content.getReportContent( )
.createContainerContent( );
CSSValue fontSizeValue = content.getComputedStyle( ).getProperty(
IStyle.STYLE_FONT_SIZE );
orderContainer.setWidth( new DimensionType( 2.1 * PropertyUtil
.getDimensionValue( fontSizeValue ) / 1000.0,
EngineIRConstants.UNITS_PT ) );
orderContainer.setInlineStyle( style );
addChild( container, orderContainer );
TextContent text = (TextContent) content.getReportContent( )
.createTextContent( );
addChild( orderContainer, text );
if ( ele.getParentNode( ).getNodeName( ).equals( "ol" ) ) //$NON-NLS-1$
{
- text.setText( new Integer( index ).toString( ) + "." ); //$NON-NLS-1$
+ text.setText( new Integer( index ).toString( ) + ". " ); //$NON-NLS-1$
}
else if ( ele.getParentNode( ).getNodeName( ).equals( "ul" ) ) //$NON-NLS-1$
{
text.setText( new String( new char[]{'\u2022', ' ', ' ', ' ', ' '} ) );
}
text.setInlineStyle( style );
IContainerContent childContainer = content.getReportContent( )
.createContainerContent( );
addChild( container, childContainer );
childContainer.setInlineStyle( style );
processNodes( ele, cssStyles, childContainer, action );
}
else if ( tagName.toLowerCase( ).equals( "dd" ) || tagName.toLowerCase( ).equals( "dt" ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
IContainerContent container = content.getReportContent( )
.createContainerContent( );
addChild( content, container );
handleStyle( ele, cssStyles, container );
if ( tagName.toLowerCase( ).equals( "dd" ) ) //$NON-NLS-1$
{
StyleDeclaration style = new StyleDeclaration( content
.getCSSEngine( ) );
style.setProperty( IStyle.STYLE_DISPLAY,
CSSValueConstants.INLINE_VALUE );
style.setProperty( IStyle.STYLE_VERTICAL_ALIGN,
CSSValueConstants.TOP_VALUE );
TextContent text = (TextContent) content.getReportContent( )
.createTextContent( );
addChild( container, text );
if ( ele.getParentNode( ).getNodeName( ).equals( "dl" ) ) //$NON-NLS-1$
{
text.setText( " " ); //$NON-NLS-1$
}
style.setTextIndent( "2em" ); //$NON-NLS-1$
text.setInlineStyle( style );
IContainerContent childContainer = content.getReportContent( )
.createContainerContent( );
childContainer.setInlineStyle( style );
addChild( container, childContainer );
processNodes( ele, cssStyles, container, action );
}
else
{
processNodes( ele, cssStyles, container, action );
}
}
else if ( "table".equals( tagName.toLowerCase( ) ) ) //$NON-NLS-1$
{
TableProcessor.processTable( ele, cssStyles, content, action );
}
else
{
IContainerContent container = content.getReportContent( )
.createContainerContent( );
handleStyle( ele, cssStyles, container );
addChild( content, container );
// handleStyle(ele, cssStyles, container);
processNodes( ele, cssStyles, container, action );
}
}
/**
* Checks if the content inside the DOM should be escaped.
*
* @param doc
* the root of the DOM tree
* @return true if the content needs escaping, otherwise false.
*/
private static boolean checkEscapeSpace( Node doc )
{
String textType = null;
if ( doc != null && doc.getFirstChild( ) != null
&& doc.getFirstChild( ) instanceof Element )
{
textType = ( (Element) doc.getFirstChild( ) )
.getAttribute( "text-type" ); //$NON-NLS-1$
return ( !TextParser.TEXT_TYPE_HTML.equalsIgnoreCase( textType ) );
}
return true;
}
/**
* Outputs the A element
*
* @param ele
* the A element instance
*/
protected static ActionContent handleAnchor( Element ele, IContent content,
ActionContent defaultAction )
{
// If the "id" attribute is not empty, then use it,
// otherwise use the "name" attribute.
ActionContent result = defaultAction;
if ( ele.getAttribute( "id" ).trim( ).length( ) != 0 ) //$NON-NLS-1$
{
content.setBookmark( ele.getAttribute( "id" ) ); //$NON-NLS-1$
}
else
{
content.setBookmark( ele.getAttribute( "name" ) );//$NON-NLS-1$
}
if ( ele.getAttribute( "href" ).length( ) > 0 ) //$NON-NLS-1$
{
String href = ele.getAttribute( "href" ); //$NON-NLS-1$
if ( null != href && !"".equals( href ) ) //$NON-NLS-1$
{
ActionContent action = new ActionContent( );
if ( href.startsWith( "#" ) ) //$NON-NLS-1$
{
action.setBookmark( href.substring( 1 ) );
}
else
{
String target = ele.getAttribute( "target" );
if ( "".equals( target ) )
{
target = "_blank";
}
action.setHyperlink( href, target );
}
result = action;
}
}
return result;
}
static void handleStyle( Element ele, Map cssStyles, IContent content )
{
String tagName = ele.getTagName( );
StyleDeclaration style = new StyleDeclaration( content.getCSSEngine( ) );
if ( "font".equals( tagName ) ) //$NON-NLS-1$
{
String attr = ele.getAttribute( "size" ); //$NON-NLS-1$
if ( null != attr && !"".equals( attr ) ) //$NON-NLS-1$
{
style.setFontSize( attr );
}
attr = ele.getAttribute( "color" ); //$NON-NLS-1$
if ( null != attr && !"".equals( attr ) ) //$NON-NLS-1$
{
style.setColor( attr );
}
attr = ele.getAttribute( "face" ); //$NON-NLS-1$
if ( null != attr && !"".equals( attr ) ) //$NON-NLS-1$
{
style.setFontFamily( attr );
}
}
if ( htmlDisplayMode.contains( tagName ) )
{
style.setDisplay( "block" ); //$NON-NLS-1$
}
else
{
style.setDisplay( "inline" ); //$NON-NLS-1$
}
IStyle inlineStyle = (IStyle) cssStyles.get( ele );
if ( inlineStyle != null )
{
style.setProperties( inlineStyle );
}
StyleProcessor tag2Style = StyleProcessor.getStyleProcess( tagName );
if ( tag2Style != null )
{
tag2Style.process( style );
}
content.setInlineStyle( style );
}
/**
* Outputs the image
*
* @param ele
* the IMG element instance
*/
protected static void outputImg( Element ele, Map cssStyles,
IContent content )
{
String src = ele.getAttribute( "src" ); //$NON-NLS-1$
if ( src != null )
{
IImageContent image = content.getReportContent( )
.createImageContent( );
addChild( content, image );
handleStyle( ele, cssStyles, image );
if ( !FileUtil.isLocalResource( src ) )
{
image.setImageSource( IImageContent.IMAGE_URL );
image.setURI( src );
}
else
{
ReportDesignHandle handle = content.getReportContent( )
.getDesign( ).getReportDesign( );
URL url = handle.findResource( src, IResourceLocator.IMAGE );
if ( url != null )
{
src = url.toString( );
}
image.setImageSource( IImageContent.IMAGE_FILE );
image.setURI( src );
}
if ( null != ele.getAttribute( "width" ) && !"".equals( ele.getAttribute( "width" ) ) ) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
{
image.setWidth( PropertyUtil.getDimensionAttribute( ele,
"width" ) ); //$NON-NLS-1$
}
if ( ele.getAttribute( "height" ) != null && !"".equals( ele.getAttribute( "height" ) ) ) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
{
image.setHeight( PropertyUtil.getDimensionAttribute( ele,
"height" ) ); //$NON-NLS-1$
}
if ( ele.getAttribute( "alt" ) != null && !"".equals( ele.getAttribute( "alt" ) ) ) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
{
image.setAltText( ele.getAttribute( "alt" ) ); //$NON-NLS-1$
}
}
}
protected static void addChild( IContent parent, IContent child )
{
if ( parent != null && child != null )
{
Collection children = parent.getChildren( );
if ( !children.contains( child ) )
{
children.add( child );
child.setParent( parent );
}
}
}
protected static void formalizeInlineContainer( List parentChildren,
IContent parent, IContent content )
{
IStyle style = content.getStyle( );
CSSValue display = style.getProperty( IStyle.STYLE_DISPLAY );
if ( CSSValueConstants.INLINE_VALUE.equals( display ) )
{
Iterator iter = content.getChildren( ).iterator( );
ArrayList contentChildren = new ArrayList( );
IContainerContent clonedBlock = null;
while ( iter.hasNext( ) )
{
IContent child = (IContent) iter.next( );
boolean isContainer = child.getChildren( ).size( ) > 0;
if ( isContainer )
{
formalizeInlineContainer( contentChildren, content, child );
}
if ( clonedBlock == null )
{
CSSValue childDisplay = child.getStyle( ).getProperty(
IStyle.STYLE_DISPLAY );
if ( CSSValueConstants.BLOCK_VALUE.equals( childDisplay ) )
{
IReportContent report = content.getReportContent( );
clonedBlock = report.createContainerContent( );
IStyle clonedStyle = report.createStyle( );
clonedStyle.setProperties( content.getStyle( ) );
clonedStyle.setProperty( IStyle.STYLE_DISPLAY,
CSSValueConstants.BLOCK_VALUE );
clonedBlock.setInlineStyle( clonedStyle );
clonedBlock.getChildren( ).add( child );
}
else
{
if ( !isContainer )
{
contentChildren.add( child );
}
}
}
else
{
iter.remove( );
clonedBlock.getChildren( ).add( child );
}
}
content.getChildren( ).clear( );
if ( contentChildren.size( ) > 0 )
{
content.getChildren( ).addAll( contentChildren );
}
if ( content.getChildren( ).size( ) > 0 )
{
parentChildren.add( content );
}
if ( clonedBlock != null )
{
parentChildren.add( clonedBlock );
}
}
else
{
Iterator iter = content.getChildren( ).iterator( );
ArrayList newChildren = new ArrayList( );
while ( iter.hasNext( ) )
{
IContent child = (IContent) iter.next( );
boolean isContainer = child.getChildren( ).size( ) > 0;
if ( isContainer )
{
formalizeInlineContainer( newChildren, content, child );
}
else
{
newChildren.add( child );
}
}
content.getChildren( ).clear( );
if ( newChildren.size( ) > 0 )
{
content.getChildren( ).addAll( newChildren );
parentChildren.add( content );
}
}
}
public static void main( String[] args )
{
/*
* ReportContent report = new ReportContent( ); IContent root =
* createBlockContent( report ); IContent block = createBlockContent(
* report ); root.getChildren( ).add( block ); IContent inlineContent =
* createInlineContent( report ); block.getChildren( ).add(
* createBlockContent( report ) ); block.getChildren( ).add(
* inlineContent ); block.getChildren( ).add( createInlineContent(
* report ) ); inlineContent.getChildren( ).add( createInlineContent(
* report ) ); inlineContent.getChildren( ).add( createBlockContent(
* report ) ); inlineContent.getChildren( ).add( createInlineContent(
* report ) ); ArrayList list = new ArrayList( );
*/
/*
* ReportContent report = new ReportContent( ); IContent root =
* createBlockContent( report ); IContent inline = createInlineContent(
* report ); root.getChildren( ).add( inline ); IContent inlineContent =
* createInlineContent( report ); inlineContent.getChildren( ).add(
* createInlineContent( report ) ); inline.getChildren( ).add(
* inlineContent ); ArrayList list = new ArrayList( );
*/
/*
* ReportContent report = new ReportContent( ); IContent root =
* createBlockContent( report ); IContent inline = createInlineContent(
* report ); root.getChildren( ).add( inline ); IContent inlineContent =
* createInlineContent( report ); inline.getChildren( ).add(
* inlineContent ); inline.getChildren( ).add( createBlockContent(
* report ) ); ArrayList list = new ArrayList( );
*/
ReportContent report = new ReportContent( );
IContent root = createBlockContent( report );
IContent inline = createInlineContent( report );
root.getChildren( ).add( inline );
IContent inlineContent = createInlineContent( report );
inline.getChildren( ).add( inlineContent );
inline.getChildren( ).add( createBlockContent( report ) );
ArrayList list = new ArrayList( );
formalizeInlineContainer( list, root, inline );
root.getChildren( ).clear( );
if ( list.size( ) > 0 )
{
root.getChildren( ).addAll( list );
}
int i = 0;
}
protected static IContent createInlineContent( ReportContent report )
{
IContent content = report.createContainerContent( );
content.getStyle( ).setProperty( IStyle.STYLE_DISPLAY,
CSSValueConstants.INLINE_VALUE );
return content;
}
protected static IContent createBlockContent( ReportContent report )
{
IContent content = report.createContainerContent( );
content.getStyle( ).setProperty( IStyle.STYLE_DISPLAY,
CSSValueConstants.BLOCK_VALUE );
return content;
}
}
| true | true | static void handleElement( Element ele, Map cssStyles, IContent content,
ActionContent action, int index )
{
IStyle cssStyle = (IStyle) cssStyles.get( ele );
if ( cssStyle != null )
{
if ( "none".equals( cssStyle.getDisplay( ) ) ) //$NON-NLS-1$
{
// Check if the display mode is none.
return;
}
}
String tagName = ele.getTagName( );
if ( tagName.toLowerCase( ).equals( "a" ) ) //$NON-NLS-1$
{
IContainerContent container = content.getReportContent( )
.createContainerContent( );
addChild( content, container );
handleStyle( ele, cssStyles, container );
ActionContent actionContent = handleAnchor( ele, container, action );
processNodes( ele, cssStyles, content, actionContent );
}
else if ( tagName.toLowerCase( ).equals( "img" ) ) //$NON-NLS-1$
{
outputImg( ele, cssStyles, content );
}
else if ( tagName.toLowerCase( ).equals( "br" ) ) //$NON-NLS-1$
{
ILabelContent label = content.getReportContent( )
.createLabelContent( );
addChild( content, label );
label.setText( "\n" ); //$NON-NLS-1$
StyleDeclaration inlineStyle = new StyleDeclaration( content
.getCSSEngine( ) );
inlineStyle.setProperty( IStyle.STYLE_DISPLAY,
CSSValueConstants.INLINE_VALUE );
label.setInlineStyle( inlineStyle );
}
else if ( tagName.toLowerCase( ).equals( "li" ) //$NON-NLS-1$
&& ele.getParentNode( ).getNodeType( ) == Node.ELEMENT_NODE )
{
StyleDeclaration style = new StyleDeclaration( content
.getCSSEngine( ) );
style.setProperty( IStyle.STYLE_DISPLAY,
CSSValueConstants.BLOCK_VALUE );
style.setProperty( IStyle.STYLE_VERTICAL_ALIGN,
CSSValueConstants.MIDDLE_VALUE );
IContainerContent container = content.getReportContent( )
.createContainerContent( );
container.setInlineStyle( style );
addChild( content, container );
handleStyle( ele, cssStyles, container );
// fix scr 157259In PDF <li> effect is incorrect when page break
// happens.
// add a container to number serial, keep consistent page-break
style = new StyleDeclaration( content.getCSSEngine( ) );
style.setProperty( IStyle.STYLE_DISPLAY,
CSSValueConstants.INLINE_VALUE );
style.setProperty( IStyle.STYLE_VERTICAL_ALIGN,
CSSValueConstants.TOP_VALUE );
IContainerContent orderContainer = content.getReportContent( )
.createContainerContent( );
CSSValue fontSizeValue = content.getComputedStyle( ).getProperty(
IStyle.STYLE_FONT_SIZE );
orderContainer.setWidth( new DimensionType( 2.1 * PropertyUtil
.getDimensionValue( fontSizeValue ) / 1000.0,
EngineIRConstants.UNITS_PT ) );
orderContainer.setInlineStyle( style );
addChild( container, orderContainer );
TextContent text = (TextContent) content.getReportContent( )
.createTextContent( );
addChild( orderContainer, text );
if ( ele.getParentNode( ).getNodeName( ).equals( "ol" ) ) //$NON-NLS-1$
{
text.setText( new Integer( index ).toString( ) + "." ); //$NON-NLS-1$
}
else if ( ele.getParentNode( ).getNodeName( ).equals( "ul" ) ) //$NON-NLS-1$
{
text.setText( new String( new char[]{'\u2022', ' ', ' ', ' ', ' '} ) );
}
text.setInlineStyle( style );
IContainerContent childContainer = content.getReportContent( )
.createContainerContent( );
addChild( container, childContainer );
childContainer.setInlineStyle( style );
processNodes( ele, cssStyles, childContainer, action );
}
else if ( tagName.toLowerCase( ).equals( "dd" ) || tagName.toLowerCase( ).equals( "dt" ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
IContainerContent container = content.getReportContent( )
.createContainerContent( );
addChild( content, container );
handleStyle( ele, cssStyles, container );
if ( tagName.toLowerCase( ).equals( "dd" ) ) //$NON-NLS-1$
{
StyleDeclaration style = new StyleDeclaration( content
.getCSSEngine( ) );
style.setProperty( IStyle.STYLE_DISPLAY,
CSSValueConstants.INLINE_VALUE );
style.setProperty( IStyle.STYLE_VERTICAL_ALIGN,
CSSValueConstants.TOP_VALUE );
TextContent text = (TextContent) content.getReportContent( )
.createTextContent( );
addChild( container, text );
if ( ele.getParentNode( ).getNodeName( ).equals( "dl" ) ) //$NON-NLS-1$
{
text.setText( " " ); //$NON-NLS-1$
}
style.setTextIndent( "2em" ); //$NON-NLS-1$
text.setInlineStyle( style );
IContainerContent childContainer = content.getReportContent( )
.createContainerContent( );
childContainer.setInlineStyle( style );
addChild( container, childContainer );
processNodes( ele, cssStyles, container, action );
}
else
{
processNodes( ele, cssStyles, container, action );
}
}
else if ( "table".equals( tagName.toLowerCase( ) ) ) //$NON-NLS-1$
{
TableProcessor.processTable( ele, cssStyles, content, action );
}
else
{
IContainerContent container = content.getReportContent( )
.createContainerContent( );
handleStyle( ele, cssStyles, container );
addChild( content, container );
// handleStyle(ele, cssStyles, container);
processNodes( ele, cssStyles, container, action );
}
}
| static void handleElement( Element ele, Map cssStyles, IContent content,
ActionContent action, int index )
{
IStyle cssStyle = (IStyle) cssStyles.get( ele );
if ( cssStyle != null )
{
if ( "none".equals( cssStyle.getDisplay( ) ) ) //$NON-NLS-1$
{
// Check if the display mode is none.
return;
}
}
String tagName = ele.getTagName( );
if ( tagName.toLowerCase( ).equals( "a" ) ) //$NON-NLS-1$
{
IContainerContent container = content.getReportContent( )
.createContainerContent( );
addChild( content, container );
handleStyle( ele, cssStyles, container );
ActionContent actionContent = handleAnchor( ele, container, action );
processNodes( ele, cssStyles, content, actionContent );
}
else if ( tagName.toLowerCase( ).equals( "img" ) ) //$NON-NLS-1$
{
outputImg( ele, cssStyles, content );
}
else if ( tagName.toLowerCase( ).equals( "br" ) ) //$NON-NLS-1$
{
ILabelContent label = content.getReportContent( )
.createLabelContent( );
addChild( content, label );
label.setText( "\n" ); //$NON-NLS-1$
StyleDeclaration inlineStyle = new StyleDeclaration( content
.getCSSEngine( ) );
inlineStyle.setProperty( IStyle.STYLE_DISPLAY,
CSSValueConstants.INLINE_VALUE );
label.setInlineStyle( inlineStyle );
}
else if ( tagName.toLowerCase( ).equals( "li" ) //$NON-NLS-1$
&& ele.getParentNode( ).getNodeType( ) == Node.ELEMENT_NODE )
{
StyleDeclaration style = new StyleDeclaration( content
.getCSSEngine( ) );
style.setProperty( IStyle.STYLE_DISPLAY,
CSSValueConstants.BLOCK_VALUE );
style.setProperty( IStyle.STYLE_VERTICAL_ALIGN,
CSSValueConstants.MIDDLE_VALUE );
IContainerContent container = content.getReportContent( )
.createContainerContent( );
container.setInlineStyle( style );
addChild( content, container );
handleStyle( ele, cssStyles, container );
// fix scr 157259In PDF <li> effect is incorrect when page break
// happens.
// add a container to number serial, keep consistent page-break
style = new StyleDeclaration( content.getCSSEngine( ) );
style.setProperty( IStyle.STYLE_DISPLAY,
CSSValueConstants.INLINE_VALUE );
style.setProperty( IStyle.STYLE_VERTICAL_ALIGN,
CSSValueConstants.TOP_VALUE );
IContainerContent orderContainer = content.getReportContent( )
.createContainerContent( );
CSSValue fontSizeValue = content.getComputedStyle( ).getProperty(
IStyle.STYLE_FONT_SIZE );
orderContainer.setWidth( new DimensionType( 2.1 * PropertyUtil
.getDimensionValue( fontSizeValue ) / 1000.0,
EngineIRConstants.UNITS_PT ) );
orderContainer.setInlineStyle( style );
addChild( container, orderContainer );
TextContent text = (TextContent) content.getReportContent( )
.createTextContent( );
addChild( orderContainer, text );
if ( ele.getParentNode( ).getNodeName( ).equals( "ol" ) ) //$NON-NLS-1$
{
text.setText( new Integer( index ).toString( ) + ". " ); //$NON-NLS-1$
}
else if ( ele.getParentNode( ).getNodeName( ).equals( "ul" ) ) //$NON-NLS-1$
{
text.setText( new String( new char[]{'\u2022', ' ', ' ', ' ', ' '} ) );
}
text.setInlineStyle( style );
IContainerContent childContainer = content.getReportContent( )
.createContainerContent( );
addChild( container, childContainer );
childContainer.setInlineStyle( style );
processNodes( ele, cssStyles, childContainer, action );
}
else if ( tagName.toLowerCase( ).equals( "dd" ) || tagName.toLowerCase( ).equals( "dt" ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
IContainerContent container = content.getReportContent( )
.createContainerContent( );
addChild( content, container );
handleStyle( ele, cssStyles, container );
if ( tagName.toLowerCase( ).equals( "dd" ) ) //$NON-NLS-1$
{
StyleDeclaration style = new StyleDeclaration( content
.getCSSEngine( ) );
style.setProperty( IStyle.STYLE_DISPLAY,
CSSValueConstants.INLINE_VALUE );
style.setProperty( IStyle.STYLE_VERTICAL_ALIGN,
CSSValueConstants.TOP_VALUE );
TextContent text = (TextContent) content.getReportContent( )
.createTextContent( );
addChild( container, text );
if ( ele.getParentNode( ).getNodeName( ).equals( "dl" ) ) //$NON-NLS-1$
{
text.setText( " " ); //$NON-NLS-1$
}
style.setTextIndent( "2em" ); //$NON-NLS-1$
text.setInlineStyle( style );
IContainerContent childContainer = content.getReportContent( )
.createContainerContent( );
childContainer.setInlineStyle( style );
addChild( container, childContainer );
processNodes( ele, cssStyles, container, action );
}
else
{
processNodes( ele, cssStyles, container, action );
}
}
else if ( "table".equals( tagName.toLowerCase( ) ) ) //$NON-NLS-1$
{
TableProcessor.processTable( ele, cssStyles, content, action );
}
else
{
IContainerContent container = content.getReportContent( )
.createContainerContent( );
handleStyle( ele, cssStyles, container );
addChild( content, container );
// handleStyle(ele, cssStyles, container);
processNodes( ele, cssStyles, container, action );
}
}
|
diff --git a/src/soot/jimple/infoflow/InfoflowProblem.java b/src/soot/jimple/infoflow/InfoflowProblem.java
index 0e43c7e..13af83f 100644
--- a/src/soot/jimple/infoflow/InfoflowProblem.java
+++ b/src/soot/jimple/infoflow/InfoflowProblem.java
@@ -1,786 +1,805 @@
package soot.jimple.infoflow;
import heros.FlowFunction;
import heros.FlowFunctions;
import heros.InterproceduralCFG;
import heros.flowfunc.Identity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import soot.Local;
import soot.NullType;
import soot.PointsToAnalysis;
import soot.PointsToSet;
import soot.PrimType;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.SootField;
import soot.SootFieldRef;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.Constant;
import soot.jimple.DefinitionStmt;
import soot.jimple.IdentityStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.Jimple;
import soot.jimple.ReturnStmt;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.infoflow.data.Abstraction;
import soot.jimple.infoflow.data.AbstractionWithPath;
import soot.jimple.infoflow.source.DefaultSourceSinkManager;
import soot.jimple.infoflow.source.SourceSinkManager;
import soot.jimple.infoflow.util.BaseSelector;
import soot.jimple.internal.JAssignStmt;
import soot.jimple.internal.JInstanceFieldRef;
import soot.jimple.internal.JInvokeStmt;
import soot.jimple.internal.JimpleLocal;
import soot.jimple.toolkits.ide.icfg.JimpleBasedBiDiICFG;
public class InfoflowProblem extends AbstractInfoflowProblem {
private final static boolean DEBUG = false;
final SourceSinkManager sourceSinkManager;
Abstraction zeroValue = null;
/**
* Computes the taints produced by a taint wrapper object
* @param iStmt The call statement the taint wrapper shall check for well-
* known methods that introduce black-box taint propagation
* @param callArgs The actual parameters with which the method in invoked
* @param source The taint source
* @return The taints computed by the wrapper
*/
private Set<Abstraction> computeWrapperTaints
(final Stmt iStmt,
final List<Value> callArgs,
Abstraction source) {
Set<Abstraction> res = new HashSet<Abstraction>();
if(taintWrapper == null || !taintWrapper.supportsTaintWrappingForClass(iStmt.getInvokeExpr().getMethod().getDeclaringClass()))
return Collections.emptySet();
int taintedPos = -1;
for(int i=0; i< callArgs.size(); i++){
if(source.getAccessPath().isLocal() && callArgs.get(i).equals(source.getAccessPath().getPlainValue())){
taintedPos = i;
break;
}
}
Value taintedBase = null;
if(iStmt.getInvokeExpr() instanceof InstanceInvokeExpr){
InstanceInvokeExpr iiExpr = (InstanceInvokeExpr) iStmt.getInvokeExpr();
if(iiExpr.getBase().equals(source.getAccessPath().getPlainValue())){
if(source.getAccessPath().isLocal()){
taintedBase = iiExpr.getBase();
}
else if(source.getAccessPath().isInstanceFieldRef()){
// The taint refers to the actual type of the field, not the formal type,
// so we must check whether we have the tainted field at all
SootClass callerClass = interproceduralCFG().getMethodOf(iStmt).getDeclaringClass();
if (callerClass.getFields().contains(source.getAccessPath().getField()))
taintedBase = new JInstanceFieldRef(iiExpr.getBase(),
callerClass.getFieldByName(source.getAccessPath().getField().getName()).makeRef());
}
}
// For the moment, we don't implement static taints on wrappers
if(source.getAccessPath().isStaticFieldRef()){
//TODO
}
}
List<Value> vals = taintWrapper.getTaintsForMethod(iStmt, taintedPos, taintedBase);
if(vals != null)
for (Value val : vals)
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(val, (AbstractionWithPath) source).addPathElement(iStmt));
else
res.add(new Abstraction(val, source));
return res;
}
/**
* Checks whether a taint wrapper is exclusive for a specific invocation statement
* @param iStmt The call statement the taint wrapper shall check for well-
* known methods that introduce black-box taint propagation
* @param callArgs The actual parameters with which the method in invoked
* @param source The taint source
* @return True if the wrapper is exclusive, otherwise false
*/
private boolean isWrapperExclusive
(final Stmt iStmt,
final List<Value> callArgs,
Abstraction source) {
if(taintWrapper == null || !taintWrapper.supportsTaintWrappingForClass(iStmt.getInvokeExpr().getMethod().getDeclaringClass()))
return false;
int taintedPos = -1;
for(int i=0; i< callArgs.size(); i++){
if(source.getAccessPath().isLocal() && callArgs.get(i).equals(source.getAccessPath().getPlainValue())){
taintedPos = i;
break;
}
}
Value taintedBase = null;
if(iStmt.getInvokeExpr() instanceof InstanceInvokeExpr){
InstanceInvokeExpr iiExpr = (InstanceInvokeExpr) iStmt.getInvokeExpr();
if(iiExpr.getBase().equals(source.getAccessPath().getPlainValue())){
if(source.getAccessPath().isLocal()){
taintedBase = iiExpr.getBase();
}else if(source.getAccessPath().isInstanceFieldRef()){
// The taint refers to the actual type of the field, not the formal type,
// so we must check whether we have the tainted field at all
SootClass callerClass = interproceduralCFG().getMethodOf(iStmt).getDeclaringClass();
if (callerClass.getFields().contains(source.getAccessPath().getField()))
taintedBase = new JInstanceFieldRef(iiExpr.getBase(),
callerClass.getFieldByName(source.getAccessPath().getField().getName()).makeRef());
}
}
if(source.getAccessPath().isStaticFieldRef()){
//TODO
}
}
return taintWrapper.isExclusive(iStmt, taintedPos, taintedBase);
}
@Override
public FlowFunctions<Unit, Abstraction, SootMethod> createFlowFunctionsFactory() {
return new FlowFunctions<Unit, Abstraction, SootMethod>() {
/**
* Creates a new taint abstraction for the given value
* @param src The source statement from which the taint originated
* @param targetValue The target value that shall now be tainted
* @param source The incoming taint abstraction from the source
* @param taintSet The taint set to which to add all newly produced
* taints
*/
private void addTaintViaStmt
(final Unit src,
final Value targetValue,
Abstraction source,
Set<Abstraction> taintSet) {
taintSet.add(source);
if (pathTracking == PathTrackingMethod.ForwardTracking)
taintSet.add(new AbstractionWithPath(targetValue,
(AbstractionWithPath) source).addPathElement(src));
else
taintSet.add(new Abstraction(targetValue, source));
SootMethod m = interproceduralCFG().getMethodOf(src);
if (targetValue instanceof InstanceFieldRef) {
InstanceFieldRef ifr = (InstanceFieldRef) targetValue;
Set<Value> aliases = getAliasesinMethod(m.getActiveBody().getUnits(), src, ifr.getBase(), ifr.getFieldRef());
for (Value v : aliases) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
taintSet.add(new AbstractionWithPath(v,
(AbstractionWithPath) source).addPathElement(src));
else
taintSet.add(new Abstraction(v, source));
}
}
}
@Override
public FlowFunction<Abstraction> getNormalFlowFunction(final Unit src, final Unit dest) {
// If we compute flows on parameters, we create the initial
// flow fact here
if (src instanceof IdentityStmt) {
final IdentityStmt is = (IdentityStmt) src;
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
Set<Abstraction> res = new HashSet<Abstraction>();
res.add(source);
if (sourceSinkManager.isSource(is, interproceduralCFG())) {
if (pathTracking != PathTrackingMethod.NoTracking)
res.add(new AbstractionWithPath(is.getLeftOp(),
is.getRightOp(),
is).addPathElement(is));
else
res.add(new Abstraction(is.getLeftOp(),
is.getRightOp(), is));
}
return res;
}
};
}
// taint is propagated with assignStmt
else if (src instanceof AssignStmt) {
AssignStmt assignStmt = (AssignStmt) src;
Value right = assignStmt.getRightOp();
Value left = assignStmt.getLeftOp();
final Value leftValue = BaseSelector.selectBase(left, false);
final Set<Value> rightVals = BaseSelector.selectBaseList(right, true);
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
boolean addLeftValue = false;
Set<Abstraction> res = new HashSet<Abstraction>();
PointsToAnalysis pta = Scene.v().getPointsToAnalysis();
// shortcuts:
// on NormalFlow taint cannot be created:
if (source.equals(zeroValue)) {
return Collections.singleton(source);
}
for (Value rightValue : rightVals) {
// check if static variable is tainted (same name, same class)
if (source.getAccessPath().isStaticFieldRef()) {
if (rightValue instanceof StaticFieldRef) {
StaticFieldRef rightRef = (StaticFieldRef) rightValue;
if (source.getAccessPath().getField().equals(rightRef.getField())) {
addLeftValue = true;
}
}
} else {
// if both are fields, we have to compare their fieldName via equals and their bases via PTS
// might happen that source is local because of max(length(accesspath)) == 1
if (rightValue instanceof InstanceFieldRef) {
InstanceFieldRef rightRef = (InstanceFieldRef) rightValue;
Local rightBase = (Local) rightRef.getBase();
PointsToSet ptsRight = pta.reachingObjects(rightBase);
Local sourceBase = (Local) source.getAccessPath().getPlainValue();
PointsToSet ptsSource = pta.reachingObjects(sourceBase);
if (ptsRight.hasNonEmptyIntersection(ptsSource)) {
if (source.getAccessPath().isInstanceFieldRef()) {
if (rightRef.getField().equals(source.getAccessPath().getField())) {
addLeftValue = true;
}
} else {
addLeftValue = true;
}
}
}
// indirect taint propagation:
// if rightvalue is local and source is instancefield of this local:
if (rightValue instanceof Local && source.getAccessPath().isInstanceFieldRef()) {
Local base = (Local) source.getAccessPath().getPlainValue(); // ?
PointsToSet ptsSourceBase = pta.reachingObjects(base);
PointsToSet ptsRight = pta.reachingObjects((Local) rightValue);
if (ptsSourceBase.hasNonEmptyIntersection(ptsRight)) {
if (leftValue instanceof Local) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(source.getAccessPath().copyWithNewValue(leftValue),
(AbstractionWithPath) source).addPathElement(src));
else
res.add(new Abstraction(source.getAccessPath().copyWithNewValue(leftValue),
source));
} else {
// access path length = 1 - taint entire value if left is field reference
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(leftValue,
((AbstractionWithPath) source).addPathElement(src)));
else
res.add(new Abstraction(leftValue, source));
}
}
}
if (rightValue instanceof ArrayRef) {
Local rightBase = (Local) ((ArrayRef) rightValue).getBase();
if (rightBase.equals(source.getAccessPath().getPlainValue()) || (source.getAccessPath().isLocal() && pta.reachingObjects(rightBase).hasNonEmptyIntersection(pta.reachingObjects((Local) source.getAccessPath().getPlainValue())))) {
addLeftValue = true;
}
}
// generic case, is true for Locals, ArrayRefs that are equal etc..
if (rightValue.equals(source.getAccessPath().getPlainValue())) {
addLeftValue = true;
}
}
}
// if one of them is true -> add leftValue
if (addLeftValue) {
addTaintViaStmt(src, leftValue, source, res);
return res;
}
//if leftvalue contains the tainted value -> it is overwritten - remove taint:
+ //but not for arrayRefs:
+ if(((AssignStmt)src).getLeftOp() instanceof ArrayRef){
+ return Collections.singleton(source);
+ }
if(source.getAccessPath().isInstanceFieldRef()){
if(leftValue instanceof InstanceFieldRef && ((InstanceFieldRef)leftValue).getField().equals(source.getAccessPath().getField()) && ((InstanceFieldRef)leftValue).getBase().equals(source.getAccessPath().getPlainValue())){
return Collections.emptySet();
}
//we have to check for PTS as well:
if (leftValue instanceof InstanceFieldRef) {
InstanceFieldRef leftRef = (InstanceFieldRef) leftValue;
PointsToSet ptsLeft = pta.reachingObjects((Local)leftRef.getBase());
Local sourceBase = (Local) source.getAccessPath().getPlainValue();
PointsToSet ptsSource = pta.reachingObjects(sourceBase);
if (ptsLeft.hasNonEmptyIntersection(ptsSource)) {
if (leftRef.getField().equals(source.getAccessPath().getField())) {
return Collections.emptySet();
}
}
//leftValue might be the base object as well:
}else if (leftValue instanceof Local){
PointsToSet ptsLeft = pta.reachingObjects((Local) leftValue);
Local sourceBase = (Local) source.getAccessPath().getPlainValue();
PointsToSet ptsSource = pta.reachingObjects(sourceBase);
if (ptsLeft.hasNonEmptyIntersection(ptsSource)) {
return Collections.emptySet();
}
}
}else if(source.getAccessPath().isStaticFieldRef()){
if(leftValue instanceof StaticFieldRef && ((StaticFieldRef)leftValue).getField().equals(source.getAccessPath().getField())){
return Collections.emptySet();
}
}
//no ELSE - when the fields of an object are tainted, but the base object is overwritten then the fields should not be tainted any more
if(leftValue.equals(source.getAccessPath().getPlainValue())){
return Collections.emptySet(); //TODO: fix this for *-Operator
}
return Collections.singleton(source);
}
};
}
return Identity.v();
}
@Override
public FlowFunction<Abstraction> getCallFlowFunction(final Unit src, final SootMethod dest) {
final Stmt stmt = (Stmt) src;
final InvokeExpr ie = stmt.getInvokeExpr();
final List<Value> callArgs = ie.getArgs();
final List<Value> paramLocals = new ArrayList<Value>();
for (int i = 0; i < dest.getParameterCount(); i++) {
paramLocals.add(dest.getActiveBody().getParameterLocal(i));
}
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
if (source.equals(zeroValue)) {
return Collections.singleton(source);
}
if(isWrapperExclusive(stmt, callArgs, source)) {
//taint is propagated in CallToReturnFunction, so we do not need any taint here:
return Collections.emptySet();
}
Set<Abstraction> res = new HashSet<Abstraction>();
Value base = source.getAccessPath().getPlainValue();
PointsToAnalysis pta = Scene.v().getPointsToAnalysis();
// if taintedobject is instancefieldRef we have to check if the object is delivered..
if (source.getAccessPath().isInstanceFieldRef()) {
// second, they might be changed as param - check this
// first, instancefieldRefs must be propagated if they come from the same class:
if (ie instanceof InstanceInvokeExpr) {
InstanceInvokeExpr vie = (InstanceInvokeExpr) ie;
PointsToSet ptsSource = pta.reachingObjects((Local) base);
PointsToSet ptsCall = pta.reachingObjects((Local) vie.getBase());
if (ptsCall.hasNonEmptyIntersection(ptsSource)) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath
(source.getAccessPath().copyWithNewValue(dest.getActiveBody().getThisLocal()),
(AbstractionWithPath) source).addPathElement(stmt));
else
res.add(new Abstraction
(source.getAccessPath().copyWithNewValue(dest.getActiveBody().getThisLocal()),
source));
}
}
}
// check if whole object is tainted (happens with strings, for example:)
if (!dest.isStatic() && ie instanceof InstanceInvokeExpr && source.getAccessPath().isLocal()) {
InstanceInvokeExpr vie = (InstanceInvokeExpr) ie;
// this might be enough because every call must happen with a local variable which is tainted itself:
if (vie.getBase().equals(source.getAccessPath().getPlainValue())) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(dest.getActiveBody().getThisLocal(),
(AbstractionWithPath) source).addPathElement(stmt));
else
res.add(new Abstraction(dest.getActiveBody().getThisLocal(),
source));
}
}
// check if param is tainted:
for (int i = 0; i < callArgs.size(); i++) {
if (callArgs.get(i).equals(base)) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(source.getAccessPath().copyWithNewValue(paramLocals.get(i)),
(AbstractionWithPath) source).addPathElement(stmt));
else
res.add(new Abstraction(source.getAccessPath().copyWithNewValue(paramLocals.get(i)),
source));
}
}
// staticfieldRefs must be analyzed even if they are not part of the params:
if (source.getAccessPath().isStaticFieldRef()) {
res.add(source);
}
return res;
}
};
}
@Override
public FlowFunction<Abstraction> getReturnFlowFunction(Unit callSite, SootMethod callee, final Unit exitStmt, final Unit retSite) {
final SootMethod calleeMethod = callee;
final Unit callUnit = callSite;
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
if (source.equals(zeroValue)) {
return Collections.singleton(source);
}
Set<Abstraction> res = new HashSet<Abstraction>();
// if we have a returnStmt we have to look at the returned value:
if (exitStmt instanceof ReturnStmt) {
ReturnStmt returnStmt = (ReturnStmt) exitStmt;
Value retLocal = returnStmt.getOp();
if (callUnit instanceof DefinitionStmt) {
DefinitionStmt defnStmt = (DefinitionStmt) callUnit;
Value leftOp = defnStmt.getLeftOp();
if (retLocal.equals(source.getAccessPath().getPlainValue())) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(source.getAccessPath().copyWithNewValue(leftOp),
(AbstractionWithPath) source).addPathElement(exitStmt));
else
res.add(new Abstraction(source.getAccessPath().copyWithNewValue(leftOp),
source));
}
// this is required for sublists, because they assign the list to the return variable and call a method that taints the list afterwards
Set<Value> aliases = getAliasesinMethod(calleeMethod.getActiveBody().getUnits(), retSite, retLocal, null);
for (Value v : aliases) {
if (v.equals(source.getAccessPath().getPlainValue())) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(source.getAccessPath().copyWithNewValue(leftOp),
(AbstractionWithPath) source).addPathElement(exitStmt));
else
res.add(new Abstraction(source.getAccessPath().copyWithNewValue(leftOp),
source));
}
}
}
// Check whether this return is treated as a sink
boolean isSink = false;
if (source.getAccessPath().isStaticFieldRef())
isSink = source.getAccessPath().getField().equals(returnStmt.getOp()); //TODO: getOp is always Local? check
else
isSink = source.getAccessPath().getPlainValue().equals(returnStmt.getOp());
if (isSink && sourceSinkManager.isSink(returnStmt, interproceduralCFG())) {
if (pathTracking != PathTrackingMethod.NoTracking)
results.addResult(returnStmt.getOp(), returnStmt,
source.getSource(),
source.getSourceContext(),
((AbstractionWithPath) source).getPropagationPathAsString(interproceduralCFG()),
interproceduralCFG().getMethodOf(returnStmt) + ": " + returnStmt.toString());
else
results.addResult(returnStmt.getOp(), returnStmt,
source.getSource(), source.getSourceContext());
}
}
// easy: static
if (source.getAccessPath().isStaticFieldRef()) {
res.add(source);
}
// checks: this/params/fields
// check one of the call params are tainted (not if simple type)
Value sourceBase = source.getAccessPath().getPlainValue();
Value originalCallArg = null;
for (int i = 0; i < calleeMethod.getParameterCount(); i++) {
if (calleeMethod.getActiveBody().getParameterLocal(i).equals(sourceBase)) { // or pts?
if (callUnit instanceof Stmt) {
Stmt iStmt = (Stmt) callUnit;
originalCallArg = iStmt.getInvokeExpr().getArg(i);
if (!(originalCallArg instanceof Constant) && !(originalCallArg.getType() instanceof PrimType)
&& !isStringType(originalCallArg.getType())) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(source.getAccessPath().copyWithNewValue(originalCallArg),
(AbstractionWithPath) source).addPathElement(exitStmt));
else
res.add(new Abstraction(source.getAccessPath().copyWithNewValue(originalCallArg),
source));
}
}
}
}
// Do not try to construct a PTS if we have no base (i.e. we have a static
// reference) or if the base is some constant
if (sourceBase != null && sourceBase instanceof Local) {
Local thisL = null;
PointsToAnalysis pta = Scene.v().getPointsToAnalysis();
PointsToSet ptsSource = pta.reachingObjects((Local) sourceBase);
if (!calleeMethod.isStatic()) {
thisL = calleeMethod.getActiveBody().getThisLocal();
}
if (thisL != null) {
if (thisL.equals(sourceBase)) {
// TODO: either remove PTS check here or remove the if-condition above!
// there is only one case in which this must be added, too: if the caller-Method has the same thisLocal - check this:
// for super-calls we have to use pts
PointsToSet ptsThis = pta.reachingObjects(thisL);
if (ptsSource.hasNonEmptyIntersection(ptsThis) || sourceBase.equals(thisL)) {
boolean param = false;
// check if it is not one of the params (then we have already fixed it)
for (int i = 0; i < calleeMethod.getParameterCount(); i++) {
if (calleeMethod.getActiveBody().getParameterLocal(i).equals(sourceBase)) {
param = true;
}
}
if (!param) {
if (callUnit instanceof Stmt) {
Stmt stmt = (Stmt) callUnit;
if (stmt.getInvokeExpr() instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iIExpr = (InstanceInvokeExpr) stmt.getInvokeExpr();
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(source.getAccessPath().copyWithNewValue(iIExpr.getBase()),
(AbstractionWithPath) source).addPathElement(exitStmt));
else
res.add(new Abstraction(source.getAccessPath().copyWithNewValue(iIExpr.getBase()),
source));
}
}
}
}
}
// remember that we only support max(length(accesspath))==1 -> if source is a fieldref, only its base is taken!
+ //bugfix: we have to check if source is Local or fields have the same name:
for (SootField globalField : calleeMethod.getDeclaringClass().getFields()) {
- if (!globalField.isStatic()) { // else is checked later
+ if((source.getAccessPath().isLocal() || (source.getAccessPath().getField() != null && globalField.getName().equals(source.getAccessPath().getField().getName()))) && !globalField.isStatic()) { // else is checked later
PointsToSet ptsGlobal = pta.reachingObjects(calleeMethod.getActiveBody().getThisLocal(), globalField);
if (ptsGlobal.hasNonEmptyIntersection(ptsSource)) {
Local callBaseVar = null;
if (callUnit instanceof JAssignStmt) {
callBaseVar = (Local) ((InstanceInvokeExpr) ((JAssignStmt) callUnit).getInvokeExpr()).getBase();
}
if (callUnit instanceof JInvokeStmt) {
JInvokeStmt iStmt = (JInvokeStmt) callUnit;
Value v = iStmt.getInvokeExprBox().getValue();
InstanceInvokeExpr jvie = (InstanceInvokeExpr) v;
callBaseVar = (Local) jvie.getBase();
}
if (callBaseVar != null) {
SootFieldRef ref = globalField.makeRef();
InstanceFieldRef fRef = Jimple.v().newInstanceFieldRef(callBaseVar, ref);
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(fRef,
(AbstractionWithPath) source).addPathElement(exitStmt));
else
res.add(new Abstraction(fRef, source));
}
}
}
}
}
for (SootField globalField : calleeMethod.getDeclaringClass().getFields()) {
- if (globalField.isStatic()) {
+ if ((source.getAccessPath().isLocal() || (source.getAccessPath().getField() != null && globalField.getName().equals(source.getAccessPath().getField().getName()))) && globalField.isStatic()) {
PointsToSet ptsGlobal = pta.reachingObjects(globalField);
if (ptsSource.hasNonEmptyIntersection(ptsGlobal)) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(Jimple.v().newStaticFieldRef(globalField.makeRef()),
(AbstractionWithPath) source).addPathElement(exitStmt));
else
res.add(new Abstraction(Jimple.v().newStaticFieldRef(globalField.makeRef()),
source));
}
}
}
}
+ //look for aliases in caller:
+ Set<Abstraction> aliasSet = new HashSet<Abstraction>();
+ for (Abstraction abs : res) {
+ if (abs.getAccessPath().isInstanceFieldRef()) { //TODO: or || abs.getAccessPath().isStaticFieldRef()? -> can't take plainValue then
+ Set<Value> aliases = getAliasesinMethod(interproceduralCFG().getMethodOf(retSite).getActiveBody().getUnits(), retSite, abs.getAccessPath().getPlainValue(), null);
+ for (Value v : aliases) {
+ if (pathTracking == PathTrackingMethod.ForwardTracking)
+ aliasSet.add(new AbstractionWithPath(source.getAccessPath().copyWithNewValue(v), (AbstractionWithPath) source).addPathElement(exitStmt));
+ else
+ aliasSet.add(new Abstraction(source.getAccessPath().copyWithNewValue(v), source));
+ }
+ }
+ }
+ res.addAll(aliasSet);
return res;
}
private boolean isStringType(Type type) {
if (!(type instanceof RefType))
return false;
RefType rt = (RefType) type;
return rt.getSootClass().getName().equals("java.lang.String");
}
};
}
@Override
public FlowFunction<Abstraction> getCallToReturnFlowFunction(final Unit call, final Unit returnSite) {
// special treatment for native methods:
if (call instanceof Stmt) {
final Stmt iStmt = (Stmt) call;
final List<Value> callArgs = iStmt.getInvokeExpr().getArgs();
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
Set<Abstraction> res = new HashSet<Abstraction>();
res.add(source);
res.addAll(computeWrapperTaints(iStmt, callArgs, source));
if (iStmt.getInvokeExpr().getMethod().isNative()) {
if (callArgs.contains(source.getAccessPath().getPlainValue())) {
// java uses call by value, but fields of complex objects can be changed (and tainted), so use this conservative approach:
res.addAll(ncHandler.getTaintedValues(iStmt, source, callArgs));
}
}
if (iStmt instanceof JAssignStmt) {
final JAssignStmt stmt = (JAssignStmt) iStmt;
if (sourceSinkManager.isSource(stmt, interproceduralCFG())) {
if (DEBUG)
System.out.println("Found source: " + stmt.getInvokeExpr().getMethod());
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(stmt.getLeftOp(),
stmt.getInvokeExpr(),
stmt).addPathElement(call));
else
res.add(new Abstraction(stmt.getLeftOp(),
stmt.getInvokeExpr(),
stmt));
res.remove(zeroValue);
}
}
// if we have called a sink we have to store the path from the source - in case one of the params is tainted!
if (sourceSinkManager.isSink(iStmt, interproceduralCFG())) {
boolean taintedParam = false;
for (int i = 0; i < callArgs.size(); i++) {
if (callArgs.get(i).equals(source.getAccessPath().getPlainValue())) {
taintedParam = true;
break;
}
}
if (taintedParam) {
if (pathTracking != PathTrackingMethod.NoTracking)
results.addResult(iStmt.getInvokeExpr(), iStmt,
source.getSource(),
source.getSourceContext(),
((AbstractionWithPath) source).getPropagationPathAsString(interproceduralCFG()),
interproceduralCFG().getMethodOf(call) + ": " + call.toString());
else
results.addResult(iStmt.getInvokeExpr(), iStmt,
source.getSource(), source.getSourceContext());
}
//if the base object which executes the method is tainted the sink is reached, too.
if (iStmt.getInvokeExpr() instanceof InstanceInvokeExpr) {
InstanceInvokeExpr vie = (InstanceInvokeExpr) iStmt.getInvokeExpr();
if (vie.getBase().equals(source.getAccessPath().getPlainValue())) {
if (pathTracking != PathTrackingMethod.NoTracking)
results.addResult(iStmt.getInvokeExpr(), iStmt,
source.getSource(),
source.getSourceContext(),
((AbstractionWithPath) source).getPropagationPathAsString(interproceduralCFG()),
interproceduralCFG().getMethodOf(call) + ": " + call.toString());
else
results.addResult(iStmt.getInvokeExpr(), iStmt,
source.getSource(), source.getSourceContext());
}
}
}
return res;
}
};
}
return Identity.v();
}
};
}
public InfoflowProblem(List<String> sourceList, List<String> sinkList) {
super(new JimpleBasedBiDiICFG());
this.sourceSinkManager = new DefaultSourceSinkManager(sourceList, sinkList);
}
public InfoflowProblem(SourceSinkManager sourceSinkManager) {
super(new JimpleBasedBiDiICFG());
this.sourceSinkManager = sourceSinkManager;
}
public InfoflowProblem(InterproceduralCFG<Unit, SootMethod> icfg, List<String> sourceList, List<String> sinkList) {
super(icfg);
this.sourceSinkManager = new DefaultSourceSinkManager(sourceList, sinkList);
}
public InfoflowProblem(InterproceduralCFG<Unit, SootMethod> icfg, SourceSinkManager sourceSinkManager) {
super(icfg);
this.sourceSinkManager = sourceSinkManager;
}
public InfoflowProblem(SourceSinkManager mySourceSinkManager, Set<Unit> analysisSeeds) {
super(new JimpleBasedBiDiICFG());
this.sourceSinkManager = mySourceSinkManager;
this.initialSeeds.addAll(analysisSeeds);
}
@Override
public Abstraction createZeroValue() {
if (zeroValue == null) {
zeroValue = this.pathTracking == PathTrackingMethod.NoTracking ?
new Abstraction(new JimpleLocal("zero", NullType.v()), null, null) :
new AbstractionWithPath(new JimpleLocal("zero", NullType.v()), null);
}
return zeroValue;
}
@Override
public Set<Unit> initialSeeds() {
return initialSeeds;
}
@Override
public boolean autoAddZero() {
return false;
}
}
| false | true | public FlowFunctions<Unit, Abstraction, SootMethod> createFlowFunctionsFactory() {
return new FlowFunctions<Unit, Abstraction, SootMethod>() {
/**
* Creates a new taint abstraction for the given value
* @param src The source statement from which the taint originated
* @param targetValue The target value that shall now be tainted
* @param source The incoming taint abstraction from the source
* @param taintSet The taint set to which to add all newly produced
* taints
*/
private void addTaintViaStmt
(final Unit src,
final Value targetValue,
Abstraction source,
Set<Abstraction> taintSet) {
taintSet.add(source);
if (pathTracking == PathTrackingMethod.ForwardTracking)
taintSet.add(new AbstractionWithPath(targetValue,
(AbstractionWithPath) source).addPathElement(src));
else
taintSet.add(new Abstraction(targetValue, source));
SootMethod m = interproceduralCFG().getMethodOf(src);
if (targetValue instanceof InstanceFieldRef) {
InstanceFieldRef ifr = (InstanceFieldRef) targetValue;
Set<Value> aliases = getAliasesinMethod(m.getActiveBody().getUnits(), src, ifr.getBase(), ifr.getFieldRef());
for (Value v : aliases) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
taintSet.add(new AbstractionWithPath(v,
(AbstractionWithPath) source).addPathElement(src));
else
taintSet.add(new Abstraction(v, source));
}
}
}
@Override
public FlowFunction<Abstraction> getNormalFlowFunction(final Unit src, final Unit dest) {
// If we compute flows on parameters, we create the initial
// flow fact here
if (src instanceof IdentityStmt) {
final IdentityStmt is = (IdentityStmt) src;
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
Set<Abstraction> res = new HashSet<Abstraction>();
res.add(source);
if (sourceSinkManager.isSource(is, interproceduralCFG())) {
if (pathTracking != PathTrackingMethod.NoTracking)
res.add(new AbstractionWithPath(is.getLeftOp(),
is.getRightOp(),
is).addPathElement(is));
else
res.add(new Abstraction(is.getLeftOp(),
is.getRightOp(), is));
}
return res;
}
};
}
// taint is propagated with assignStmt
else if (src instanceof AssignStmt) {
AssignStmt assignStmt = (AssignStmt) src;
Value right = assignStmt.getRightOp();
Value left = assignStmt.getLeftOp();
final Value leftValue = BaseSelector.selectBase(left, false);
final Set<Value> rightVals = BaseSelector.selectBaseList(right, true);
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
boolean addLeftValue = false;
Set<Abstraction> res = new HashSet<Abstraction>();
PointsToAnalysis pta = Scene.v().getPointsToAnalysis();
// shortcuts:
// on NormalFlow taint cannot be created:
if (source.equals(zeroValue)) {
return Collections.singleton(source);
}
for (Value rightValue : rightVals) {
// check if static variable is tainted (same name, same class)
if (source.getAccessPath().isStaticFieldRef()) {
if (rightValue instanceof StaticFieldRef) {
StaticFieldRef rightRef = (StaticFieldRef) rightValue;
if (source.getAccessPath().getField().equals(rightRef.getField())) {
addLeftValue = true;
}
}
} else {
// if both are fields, we have to compare their fieldName via equals and their bases via PTS
// might happen that source is local because of max(length(accesspath)) == 1
if (rightValue instanceof InstanceFieldRef) {
InstanceFieldRef rightRef = (InstanceFieldRef) rightValue;
Local rightBase = (Local) rightRef.getBase();
PointsToSet ptsRight = pta.reachingObjects(rightBase);
Local sourceBase = (Local) source.getAccessPath().getPlainValue();
PointsToSet ptsSource = pta.reachingObjects(sourceBase);
if (ptsRight.hasNonEmptyIntersection(ptsSource)) {
if (source.getAccessPath().isInstanceFieldRef()) {
if (rightRef.getField().equals(source.getAccessPath().getField())) {
addLeftValue = true;
}
} else {
addLeftValue = true;
}
}
}
// indirect taint propagation:
// if rightvalue is local and source is instancefield of this local:
if (rightValue instanceof Local && source.getAccessPath().isInstanceFieldRef()) {
Local base = (Local) source.getAccessPath().getPlainValue(); // ?
PointsToSet ptsSourceBase = pta.reachingObjects(base);
PointsToSet ptsRight = pta.reachingObjects((Local) rightValue);
if (ptsSourceBase.hasNonEmptyIntersection(ptsRight)) {
if (leftValue instanceof Local) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(source.getAccessPath().copyWithNewValue(leftValue),
(AbstractionWithPath) source).addPathElement(src));
else
res.add(new Abstraction(source.getAccessPath().copyWithNewValue(leftValue),
source));
} else {
// access path length = 1 - taint entire value if left is field reference
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(leftValue,
((AbstractionWithPath) source).addPathElement(src)));
else
res.add(new Abstraction(leftValue, source));
}
}
}
if (rightValue instanceof ArrayRef) {
Local rightBase = (Local) ((ArrayRef) rightValue).getBase();
if (rightBase.equals(source.getAccessPath().getPlainValue()) || (source.getAccessPath().isLocal() && pta.reachingObjects(rightBase).hasNonEmptyIntersection(pta.reachingObjects((Local) source.getAccessPath().getPlainValue())))) {
addLeftValue = true;
}
}
// generic case, is true for Locals, ArrayRefs that are equal etc..
if (rightValue.equals(source.getAccessPath().getPlainValue())) {
addLeftValue = true;
}
}
}
// if one of them is true -> add leftValue
if (addLeftValue) {
addTaintViaStmt(src, leftValue, source, res);
return res;
}
//if leftvalue contains the tainted value -> it is overwritten - remove taint:
if(source.getAccessPath().isInstanceFieldRef()){
if(leftValue instanceof InstanceFieldRef && ((InstanceFieldRef)leftValue).getField().equals(source.getAccessPath().getField()) && ((InstanceFieldRef)leftValue).getBase().equals(source.getAccessPath().getPlainValue())){
return Collections.emptySet();
}
//we have to check for PTS as well:
if (leftValue instanceof InstanceFieldRef) {
InstanceFieldRef leftRef = (InstanceFieldRef) leftValue;
PointsToSet ptsLeft = pta.reachingObjects((Local)leftRef.getBase());
Local sourceBase = (Local) source.getAccessPath().getPlainValue();
PointsToSet ptsSource = pta.reachingObjects(sourceBase);
if (ptsLeft.hasNonEmptyIntersection(ptsSource)) {
if (leftRef.getField().equals(source.getAccessPath().getField())) {
return Collections.emptySet();
}
}
//leftValue might be the base object as well:
}else if (leftValue instanceof Local){
PointsToSet ptsLeft = pta.reachingObjects((Local) leftValue);
Local sourceBase = (Local) source.getAccessPath().getPlainValue();
PointsToSet ptsSource = pta.reachingObjects(sourceBase);
if (ptsLeft.hasNonEmptyIntersection(ptsSource)) {
return Collections.emptySet();
}
}
}else if(source.getAccessPath().isStaticFieldRef()){
if(leftValue instanceof StaticFieldRef && ((StaticFieldRef)leftValue).getField().equals(source.getAccessPath().getField())){
return Collections.emptySet();
}
}
//no ELSE - when the fields of an object are tainted, but the base object is overwritten then the fields should not be tainted any more
if(leftValue.equals(source.getAccessPath().getPlainValue())){
return Collections.emptySet(); //TODO: fix this for *-Operator
}
return Collections.singleton(source);
}
};
}
return Identity.v();
}
@Override
public FlowFunction<Abstraction> getCallFlowFunction(final Unit src, final SootMethod dest) {
final Stmt stmt = (Stmt) src;
final InvokeExpr ie = stmt.getInvokeExpr();
final List<Value> callArgs = ie.getArgs();
final List<Value> paramLocals = new ArrayList<Value>();
for (int i = 0; i < dest.getParameterCount(); i++) {
paramLocals.add(dest.getActiveBody().getParameterLocal(i));
}
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
if (source.equals(zeroValue)) {
return Collections.singleton(source);
}
if(isWrapperExclusive(stmt, callArgs, source)) {
//taint is propagated in CallToReturnFunction, so we do not need any taint here:
return Collections.emptySet();
}
Set<Abstraction> res = new HashSet<Abstraction>();
Value base = source.getAccessPath().getPlainValue();
PointsToAnalysis pta = Scene.v().getPointsToAnalysis();
// if taintedobject is instancefieldRef we have to check if the object is delivered..
if (source.getAccessPath().isInstanceFieldRef()) {
// second, they might be changed as param - check this
// first, instancefieldRefs must be propagated if they come from the same class:
if (ie instanceof InstanceInvokeExpr) {
InstanceInvokeExpr vie = (InstanceInvokeExpr) ie;
PointsToSet ptsSource = pta.reachingObjects((Local) base);
PointsToSet ptsCall = pta.reachingObjects((Local) vie.getBase());
if (ptsCall.hasNonEmptyIntersection(ptsSource)) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath
(source.getAccessPath().copyWithNewValue(dest.getActiveBody().getThisLocal()),
(AbstractionWithPath) source).addPathElement(stmt));
else
res.add(new Abstraction
(source.getAccessPath().copyWithNewValue(dest.getActiveBody().getThisLocal()),
source));
}
}
}
// check if whole object is tainted (happens with strings, for example:)
if (!dest.isStatic() && ie instanceof InstanceInvokeExpr && source.getAccessPath().isLocal()) {
InstanceInvokeExpr vie = (InstanceInvokeExpr) ie;
// this might be enough because every call must happen with a local variable which is tainted itself:
if (vie.getBase().equals(source.getAccessPath().getPlainValue())) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(dest.getActiveBody().getThisLocal(),
(AbstractionWithPath) source).addPathElement(stmt));
else
res.add(new Abstraction(dest.getActiveBody().getThisLocal(),
source));
}
}
// check if param is tainted:
for (int i = 0; i < callArgs.size(); i++) {
if (callArgs.get(i).equals(base)) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(source.getAccessPath().copyWithNewValue(paramLocals.get(i)),
(AbstractionWithPath) source).addPathElement(stmt));
else
res.add(new Abstraction(source.getAccessPath().copyWithNewValue(paramLocals.get(i)),
source));
}
}
// staticfieldRefs must be analyzed even if they are not part of the params:
if (source.getAccessPath().isStaticFieldRef()) {
res.add(source);
}
return res;
}
};
}
@Override
public FlowFunction<Abstraction> getReturnFlowFunction(Unit callSite, SootMethod callee, final Unit exitStmt, final Unit retSite) {
final SootMethod calleeMethod = callee;
final Unit callUnit = callSite;
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
if (source.equals(zeroValue)) {
return Collections.singleton(source);
}
Set<Abstraction> res = new HashSet<Abstraction>();
// if we have a returnStmt we have to look at the returned value:
if (exitStmt instanceof ReturnStmt) {
ReturnStmt returnStmt = (ReturnStmt) exitStmt;
Value retLocal = returnStmt.getOp();
if (callUnit instanceof DefinitionStmt) {
DefinitionStmt defnStmt = (DefinitionStmt) callUnit;
Value leftOp = defnStmt.getLeftOp();
if (retLocal.equals(source.getAccessPath().getPlainValue())) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(source.getAccessPath().copyWithNewValue(leftOp),
(AbstractionWithPath) source).addPathElement(exitStmt));
else
res.add(new Abstraction(source.getAccessPath().copyWithNewValue(leftOp),
source));
}
// this is required for sublists, because they assign the list to the return variable and call a method that taints the list afterwards
Set<Value> aliases = getAliasesinMethod(calleeMethod.getActiveBody().getUnits(), retSite, retLocal, null);
for (Value v : aliases) {
if (v.equals(source.getAccessPath().getPlainValue())) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(source.getAccessPath().copyWithNewValue(leftOp),
(AbstractionWithPath) source).addPathElement(exitStmt));
else
res.add(new Abstraction(source.getAccessPath().copyWithNewValue(leftOp),
source));
}
}
}
// Check whether this return is treated as a sink
boolean isSink = false;
if (source.getAccessPath().isStaticFieldRef())
isSink = source.getAccessPath().getField().equals(returnStmt.getOp()); //TODO: getOp is always Local? check
else
isSink = source.getAccessPath().getPlainValue().equals(returnStmt.getOp());
if (isSink && sourceSinkManager.isSink(returnStmt, interproceduralCFG())) {
if (pathTracking != PathTrackingMethod.NoTracking)
results.addResult(returnStmt.getOp(), returnStmt,
source.getSource(),
source.getSourceContext(),
((AbstractionWithPath) source).getPropagationPathAsString(interproceduralCFG()),
interproceduralCFG().getMethodOf(returnStmt) + ": " + returnStmt.toString());
else
results.addResult(returnStmt.getOp(), returnStmt,
source.getSource(), source.getSourceContext());
}
}
// easy: static
if (source.getAccessPath().isStaticFieldRef()) {
res.add(source);
}
// checks: this/params/fields
// check one of the call params are tainted (not if simple type)
Value sourceBase = source.getAccessPath().getPlainValue();
Value originalCallArg = null;
for (int i = 0; i < calleeMethod.getParameterCount(); i++) {
if (calleeMethod.getActiveBody().getParameterLocal(i).equals(sourceBase)) { // or pts?
if (callUnit instanceof Stmt) {
Stmt iStmt = (Stmt) callUnit;
originalCallArg = iStmt.getInvokeExpr().getArg(i);
if (!(originalCallArg instanceof Constant) && !(originalCallArg.getType() instanceof PrimType)
&& !isStringType(originalCallArg.getType())) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(source.getAccessPath().copyWithNewValue(originalCallArg),
(AbstractionWithPath) source).addPathElement(exitStmt));
else
res.add(new Abstraction(source.getAccessPath().copyWithNewValue(originalCallArg),
source));
}
}
}
}
// Do not try to construct a PTS if we have no base (i.e. we have a static
// reference) or if the base is some constant
if (sourceBase != null && sourceBase instanceof Local) {
Local thisL = null;
PointsToAnalysis pta = Scene.v().getPointsToAnalysis();
PointsToSet ptsSource = pta.reachingObjects((Local) sourceBase);
if (!calleeMethod.isStatic()) {
thisL = calleeMethod.getActiveBody().getThisLocal();
}
if (thisL != null) {
if (thisL.equals(sourceBase)) {
// TODO: either remove PTS check here or remove the if-condition above!
// there is only one case in which this must be added, too: if the caller-Method has the same thisLocal - check this:
// for super-calls we have to use pts
PointsToSet ptsThis = pta.reachingObjects(thisL);
if (ptsSource.hasNonEmptyIntersection(ptsThis) || sourceBase.equals(thisL)) {
boolean param = false;
// check if it is not one of the params (then we have already fixed it)
for (int i = 0; i < calleeMethod.getParameterCount(); i++) {
if (calleeMethod.getActiveBody().getParameterLocal(i).equals(sourceBase)) {
param = true;
}
}
if (!param) {
if (callUnit instanceof Stmt) {
Stmt stmt = (Stmt) callUnit;
if (stmt.getInvokeExpr() instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iIExpr = (InstanceInvokeExpr) stmt.getInvokeExpr();
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(source.getAccessPath().copyWithNewValue(iIExpr.getBase()),
(AbstractionWithPath) source).addPathElement(exitStmt));
else
res.add(new Abstraction(source.getAccessPath().copyWithNewValue(iIExpr.getBase()),
source));
}
}
}
}
}
// remember that we only support max(length(accesspath))==1 -> if source is a fieldref, only its base is taken!
for (SootField globalField : calleeMethod.getDeclaringClass().getFields()) {
if (!globalField.isStatic()) { // else is checked later
PointsToSet ptsGlobal = pta.reachingObjects(calleeMethod.getActiveBody().getThisLocal(), globalField);
if (ptsGlobal.hasNonEmptyIntersection(ptsSource)) {
Local callBaseVar = null;
if (callUnit instanceof JAssignStmt) {
callBaseVar = (Local) ((InstanceInvokeExpr) ((JAssignStmt) callUnit).getInvokeExpr()).getBase();
}
if (callUnit instanceof JInvokeStmt) {
JInvokeStmt iStmt = (JInvokeStmt) callUnit;
Value v = iStmt.getInvokeExprBox().getValue();
InstanceInvokeExpr jvie = (InstanceInvokeExpr) v;
callBaseVar = (Local) jvie.getBase();
}
if (callBaseVar != null) {
SootFieldRef ref = globalField.makeRef();
InstanceFieldRef fRef = Jimple.v().newInstanceFieldRef(callBaseVar, ref);
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(fRef,
(AbstractionWithPath) source).addPathElement(exitStmt));
else
res.add(new Abstraction(fRef, source));
}
}
}
}
}
for (SootField globalField : calleeMethod.getDeclaringClass().getFields()) {
if (globalField.isStatic()) {
PointsToSet ptsGlobal = pta.reachingObjects(globalField);
if (ptsSource.hasNonEmptyIntersection(ptsGlobal)) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(Jimple.v().newStaticFieldRef(globalField.makeRef()),
(AbstractionWithPath) source).addPathElement(exitStmt));
else
res.add(new Abstraction(Jimple.v().newStaticFieldRef(globalField.makeRef()),
source));
}
}
}
}
return res;
}
private boolean isStringType(Type type) {
if (!(type instanceof RefType))
return false;
RefType rt = (RefType) type;
return rt.getSootClass().getName().equals("java.lang.String");
}
};
}
@Override
public FlowFunction<Abstraction> getCallToReturnFlowFunction(final Unit call, final Unit returnSite) {
// special treatment for native methods:
if (call instanceof Stmt) {
final Stmt iStmt = (Stmt) call;
final List<Value> callArgs = iStmt.getInvokeExpr().getArgs();
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
Set<Abstraction> res = new HashSet<Abstraction>();
res.add(source);
res.addAll(computeWrapperTaints(iStmt, callArgs, source));
if (iStmt.getInvokeExpr().getMethod().isNative()) {
if (callArgs.contains(source.getAccessPath().getPlainValue())) {
// java uses call by value, but fields of complex objects can be changed (and tainted), so use this conservative approach:
res.addAll(ncHandler.getTaintedValues(iStmt, source, callArgs));
}
}
if (iStmt instanceof JAssignStmt) {
final JAssignStmt stmt = (JAssignStmt) iStmt;
if (sourceSinkManager.isSource(stmt, interproceduralCFG())) {
if (DEBUG)
System.out.println("Found source: " + stmt.getInvokeExpr().getMethod());
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(stmt.getLeftOp(),
stmt.getInvokeExpr(),
stmt).addPathElement(call));
else
res.add(new Abstraction(stmt.getLeftOp(),
stmt.getInvokeExpr(),
stmt));
res.remove(zeroValue);
}
}
// if we have called a sink we have to store the path from the source - in case one of the params is tainted!
if (sourceSinkManager.isSink(iStmt, interproceduralCFG())) {
boolean taintedParam = false;
for (int i = 0; i < callArgs.size(); i++) {
if (callArgs.get(i).equals(source.getAccessPath().getPlainValue())) {
taintedParam = true;
break;
}
}
if (taintedParam) {
if (pathTracking != PathTrackingMethod.NoTracking)
results.addResult(iStmt.getInvokeExpr(), iStmt,
source.getSource(),
source.getSourceContext(),
((AbstractionWithPath) source).getPropagationPathAsString(interproceduralCFG()),
interproceduralCFG().getMethodOf(call) + ": " + call.toString());
else
results.addResult(iStmt.getInvokeExpr(), iStmt,
source.getSource(), source.getSourceContext());
}
//if the base object which executes the method is tainted the sink is reached, too.
if (iStmt.getInvokeExpr() instanceof InstanceInvokeExpr) {
InstanceInvokeExpr vie = (InstanceInvokeExpr) iStmt.getInvokeExpr();
if (vie.getBase().equals(source.getAccessPath().getPlainValue())) {
if (pathTracking != PathTrackingMethod.NoTracking)
results.addResult(iStmt.getInvokeExpr(), iStmt,
source.getSource(),
source.getSourceContext(),
((AbstractionWithPath) source).getPropagationPathAsString(interproceduralCFG()),
interproceduralCFG().getMethodOf(call) + ": " + call.toString());
else
results.addResult(iStmt.getInvokeExpr(), iStmt,
source.getSource(), source.getSourceContext());
}
}
}
return res;
}
};
}
return Identity.v();
}
};
}
| public FlowFunctions<Unit, Abstraction, SootMethod> createFlowFunctionsFactory() {
return new FlowFunctions<Unit, Abstraction, SootMethod>() {
/**
* Creates a new taint abstraction for the given value
* @param src The source statement from which the taint originated
* @param targetValue The target value that shall now be tainted
* @param source The incoming taint abstraction from the source
* @param taintSet The taint set to which to add all newly produced
* taints
*/
private void addTaintViaStmt
(final Unit src,
final Value targetValue,
Abstraction source,
Set<Abstraction> taintSet) {
taintSet.add(source);
if (pathTracking == PathTrackingMethod.ForwardTracking)
taintSet.add(new AbstractionWithPath(targetValue,
(AbstractionWithPath) source).addPathElement(src));
else
taintSet.add(new Abstraction(targetValue, source));
SootMethod m = interproceduralCFG().getMethodOf(src);
if (targetValue instanceof InstanceFieldRef) {
InstanceFieldRef ifr = (InstanceFieldRef) targetValue;
Set<Value> aliases = getAliasesinMethod(m.getActiveBody().getUnits(), src, ifr.getBase(), ifr.getFieldRef());
for (Value v : aliases) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
taintSet.add(new AbstractionWithPath(v,
(AbstractionWithPath) source).addPathElement(src));
else
taintSet.add(new Abstraction(v, source));
}
}
}
@Override
public FlowFunction<Abstraction> getNormalFlowFunction(final Unit src, final Unit dest) {
// If we compute flows on parameters, we create the initial
// flow fact here
if (src instanceof IdentityStmt) {
final IdentityStmt is = (IdentityStmt) src;
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
Set<Abstraction> res = new HashSet<Abstraction>();
res.add(source);
if (sourceSinkManager.isSource(is, interproceduralCFG())) {
if (pathTracking != PathTrackingMethod.NoTracking)
res.add(new AbstractionWithPath(is.getLeftOp(),
is.getRightOp(),
is).addPathElement(is));
else
res.add(new Abstraction(is.getLeftOp(),
is.getRightOp(), is));
}
return res;
}
};
}
// taint is propagated with assignStmt
else if (src instanceof AssignStmt) {
AssignStmt assignStmt = (AssignStmt) src;
Value right = assignStmt.getRightOp();
Value left = assignStmt.getLeftOp();
final Value leftValue = BaseSelector.selectBase(left, false);
final Set<Value> rightVals = BaseSelector.selectBaseList(right, true);
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
boolean addLeftValue = false;
Set<Abstraction> res = new HashSet<Abstraction>();
PointsToAnalysis pta = Scene.v().getPointsToAnalysis();
// shortcuts:
// on NormalFlow taint cannot be created:
if (source.equals(zeroValue)) {
return Collections.singleton(source);
}
for (Value rightValue : rightVals) {
// check if static variable is tainted (same name, same class)
if (source.getAccessPath().isStaticFieldRef()) {
if (rightValue instanceof StaticFieldRef) {
StaticFieldRef rightRef = (StaticFieldRef) rightValue;
if (source.getAccessPath().getField().equals(rightRef.getField())) {
addLeftValue = true;
}
}
} else {
// if both are fields, we have to compare their fieldName via equals and their bases via PTS
// might happen that source is local because of max(length(accesspath)) == 1
if (rightValue instanceof InstanceFieldRef) {
InstanceFieldRef rightRef = (InstanceFieldRef) rightValue;
Local rightBase = (Local) rightRef.getBase();
PointsToSet ptsRight = pta.reachingObjects(rightBase);
Local sourceBase = (Local) source.getAccessPath().getPlainValue();
PointsToSet ptsSource = pta.reachingObjects(sourceBase);
if (ptsRight.hasNonEmptyIntersection(ptsSource)) {
if (source.getAccessPath().isInstanceFieldRef()) {
if (rightRef.getField().equals(source.getAccessPath().getField())) {
addLeftValue = true;
}
} else {
addLeftValue = true;
}
}
}
// indirect taint propagation:
// if rightvalue is local and source is instancefield of this local:
if (rightValue instanceof Local && source.getAccessPath().isInstanceFieldRef()) {
Local base = (Local) source.getAccessPath().getPlainValue(); // ?
PointsToSet ptsSourceBase = pta.reachingObjects(base);
PointsToSet ptsRight = pta.reachingObjects((Local) rightValue);
if (ptsSourceBase.hasNonEmptyIntersection(ptsRight)) {
if (leftValue instanceof Local) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(source.getAccessPath().copyWithNewValue(leftValue),
(AbstractionWithPath) source).addPathElement(src));
else
res.add(new Abstraction(source.getAccessPath().copyWithNewValue(leftValue),
source));
} else {
// access path length = 1 - taint entire value if left is field reference
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(leftValue,
((AbstractionWithPath) source).addPathElement(src)));
else
res.add(new Abstraction(leftValue, source));
}
}
}
if (rightValue instanceof ArrayRef) {
Local rightBase = (Local) ((ArrayRef) rightValue).getBase();
if (rightBase.equals(source.getAccessPath().getPlainValue()) || (source.getAccessPath().isLocal() && pta.reachingObjects(rightBase).hasNonEmptyIntersection(pta.reachingObjects((Local) source.getAccessPath().getPlainValue())))) {
addLeftValue = true;
}
}
// generic case, is true for Locals, ArrayRefs that are equal etc..
if (rightValue.equals(source.getAccessPath().getPlainValue())) {
addLeftValue = true;
}
}
}
// if one of them is true -> add leftValue
if (addLeftValue) {
addTaintViaStmt(src, leftValue, source, res);
return res;
}
//if leftvalue contains the tainted value -> it is overwritten - remove taint:
//but not for arrayRefs:
if(((AssignStmt)src).getLeftOp() instanceof ArrayRef){
return Collections.singleton(source);
}
if(source.getAccessPath().isInstanceFieldRef()){
if(leftValue instanceof InstanceFieldRef && ((InstanceFieldRef)leftValue).getField().equals(source.getAccessPath().getField()) && ((InstanceFieldRef)leftValue).getBase().equals(source.getAccessPath().getPlainValue())){
return Collections.emptySet();
}
//we have to check for PTS as well:
if (leftValue instanceof InstanceFieldRef) {
InstanceFieldRef leftRef = (InstanceFieldRef) leftValue;
PointsToSet ptsLeft = pta.reachingObjects((Local)leftRef.getBase());
Local sourceBase = (Local) source.getAccessPath().getPlainValue();
PointsToSet ptsSource = pta.reachingObjects(sourceBase);
if (ptsLeft.hasNonEmptyIntersection(ptsSource)) {
if (leftRef.getField().equals(source.getAccessPath().getField())) {
return Collections.emptySet();
}
}
//leftValue might be the base object as well:
}else if (leftValue instanceof Local){
PointsToSet ptsLeft = pta.reachingObjects((Local) leftValue);
Local sourceBase = (Local) source.getAccessPath().getPlainValue();
PointsToSet ptsSource = pta.reachingObjects(sourceBase);
if (ptsLeft.hasNonEmptyIntersection(ptsSource)) {
return Collections.emptySet();
}
}
}else if(source.getAccessPath().isStaticFieldRef()){
if(leftValue instanceof StaticFieldRef && ((StaticFieldRef)leftValue).getField().equals(source.getAccessPath().getField())){
return Collections.emptySet();
}
}
//no ELSE - when the fields of an object are tainted, but the base object is overwritten then the fields should not be tainted any more
if(leftValue.equals(source.getAccessPath().getPlainValue())){
return Collections.emptySet(); //TODO: fix this for *-Operator
}
return Collections.singleton(source);
}
};
}
return Identity.v();
}
@Override
public FlowFunction<Abstraction> getCallFlowFunction(final Unit src, final SootMethod dest) {
final Stmt stmt = (Stmt) src;
final InvokeExpr ie = stmt.getInvokeExpr();
final List<Value> callArgs = ie.getArgs();
final List<Value> paramLocals = new ArrayList<Value>();
for (int i = 0; i < dest.getParameterCount(); i++) {
paramLocals.add(dest.getActiveBody().getParameterLocal(i));
}
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
if (source.equals(zeroValue)) {
return Collections.singleton(source);
}
if(isWrapperExclusive(stmt, callArgs, source)) {
//taint is propagated in CallToReturnFunction, so we do not need any taint here:
return Collections.emptySet();
}
Set<Abstraction> res = new HashSet<Abstraction>();
Value base = source.getAccessPath().getPlainValue();
PointsToAnalysis pta = Scene.v().getPointsToAnalysis();
// if taintedobject is instancefieldRef we have to check if the object is delivered..
if (source.getAccessPath().isInstanceFieldRef()) {
// second, they might be changed as param - check this
// first, instancefieldRefs must be propagated if they come from the same class:
if (ie instanceof InstanceInvokeExpr) {
InstanceInvokeExpr vie = (InstanceInvokeExpr) ie;
PointsToSet ptsSource = pta.reachingObjects((Local) base);
PointsToSet ptsCall = pta.reachingObjects((Local) vie.getBase());
if (ptsCall.hasNonEmptyIntersection(ptsSource)) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath
(source.getAccessPath().copyWithNewValue(dest.getActiveBody().getThisLocal()),
(AbstractionWithPath) source).addPathElement(stmt));
else
res.add(new Abstraction
(source.getAccessPath().copyWithNewValue(dest.getActiveBody().getThisLocal()),
source));
}
}
}
// check if whole object is tainted (happens with strings, for example:)
if (!dest.isStatic() && ie instanceof InstanceInvokeExpr && source.getAccessPath().isLocal()) {
InstanceInvokeExpr vie = (InstanceInvokeExpr) ie;
// this might be enough because every call must happen with a local variable which is tainted itself:
if (vie.getBase().equals(source.getAccessPath().getPlainValue())) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(dest.getActiveBody().getThisLocal(),
(AbstractionWithPath) source).addPathElement(stmt));
else
res.add(new Abstraction(dest.getActiveBody().getThisLocal(),
source));
}
}
// check if param is tainted:
for (int i = 0; i < callArgs.size(); i++) {
if (callArgs.get(i).equals(base)) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(source.getAccessPath().copyWithNewValue(paramLocals.get(i)),
(AbstractionWithPath) source).addPathElement(stmt));
else
res.add(new Abstraction(source.getAccessPath().copyWithNewValue(paramLocals.get(i)),
source));
}
}
// staticfieldRefs must be analyzed even if they are not part of the params:
if (source.getAccessPath().isStaticFieldRef()) {
res.add(source);
}
return res;
}
};
}
@Override
public FlowFunction<Abstraction> getReturnFlowFunction(Unit callSite, SootMethod callee, final Unit exitStmt, final Unit retSite) {
final SootMethod calleeMethod = callee;
final Unit callUnit = callSite;
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
if (source.equals(zeroValue)) {
return Collections.singleton(source);
}
Set<Abstraction> res = new HashSet<Abstraction>();
// if we have a returnStmt we have to look at the returned value:
if (exitStmt instanceof ReturnStmt) {
ReturnStmt returnStmt = (ReturnStmt) exitStmt;
Value retLocal = returnStmt.getOp();
if (callUnit instanceof DefinitionStmt) {
DefinitionStmt defnStmt = (DefinitionStmt) callUnit;
Value leftOp = defnStmt.getLeftOp();
if (retLocal.equals(source.getAccessPath().getPlainValue())) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(source.getAccessPath().copyWithNewValue(leftOp),
(AbstractionWithPath) source).addPathElement(exitStmt));
else
res.add(new Abstraction(source.getAccessPath().copyWithNewValue(leftOp),
source));
}
// this is required for sublists, because they assign the list to the return variable and call a method that taints the list afterwards
Set<Value> aliases = getAliasesinMethod(calleeMethod.getActiveBody().getUnits(), retSite, retLocal, null);
for (Value v : aliases) {
if (v.equals(source.getAccessPath().getPlainValue())) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(source.getAccessPath().copyWithNewValue(leftOp),
(AbstractionWithPath) source).addPathElement(exitStmt));
else
res.add(new Abstraction(source.getAccessPath().copyWithNewValue(leftOp),
source));
}
}
}
// Check whether this return is treated as a sink
boolean isSink = false;
if (source.getAccessPath().isStaticFieldRef())
isSink = source.getAccessPath().getField().equals(returnStmt.getOp()); //TODO: getOp is always Local? check
else
isSink = source.getAccessPath().getPlainValue().equals(returnStmt.getOp());
if (isSink && sourceSinkManager.isSink(returnStmt, interproceduralCFG())) {
if (pathTracking != PathTrackingMethod.NoTracking)
results.addResult(returnStmt.getOp(), returnStmt,
source.getSource(),
source.getSourceContext(),
((AbstractionWithPath) source).getPropagationPathAsString(interproceduralCFG()),
interproceduralCFG().getMethodOf(returnStmt) + ": " + returnStmt.toString());
else
results.addResult(returnStmt.getOp(), returnStmt,
source.getSource(), source.getSourceContext());
}
}
// easy: static
if (source.getAccessPath().isStaticFieldRef()) {
res.add(source);
}
// checks: this/params/fields
// check one of the call params are tainted (not if simple type)
Value sourceBase = source.getAccessPath().getPlainValue();
Value originalCallArg = null;
for (int i = 0; i < calleeMethod.getParameterCount(); i++) {
if (calleeMethod.getActiveBody().getParameterLocal(i).equals(sourceBase)) { // or pts?
if (callUnit instanceof Stmt) {
Stmt iStmt = (Stmt) callUnit;
originalCallArg = iStmt.getInvokeExpr().getArg(i);
if (!(originalCallArg instanceof Constant) && !(originalCallArg.getType() instanceof PrimType)
&& !isStringType(originalCallArg.getType())) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(source.getAccessPath().copyWithNewValue(originalCallArg),
(AbstractionWithPath) source).addPathElement(exitStmt));
else
res.add(new Abstraction(source.getAccessPath().copyWithNewValue(originalCallArg),
source));
}
}
}
}
// Do not try to construct a PTS if we have no base (i.e. we have a static
// reference) or if the base is some constant
if (sourceBase != null && sourceBase instanceof Local) {
Local thisL = null;
PointsToAnalysis pta = Scene.v().getPointsToAnalysis();
PointsToSet ptsSource = pta.reachingObjects((Local) sourceBase);
if (!calleeMethod.isStatic()) {
thisL = calleeMethod.getActiveBody().getThisLocal();
}
if (thisL != null) {
if (thisL.equals(sourceBase)) {
// TODO: either remove PTS check here or remove the if-condition above!
// there is only one case in which this must be added, too: if the caller-Method has the same thisLocal - check this:
// for super-calls we have to use pts
PointsToSet ptsThis = pta.reachingObjects(thisL);
if (ptsSource.hasNonEmptyIntersection(ptsThis) || sourceBase.equals(thisL)) {
boolean param = false;
// check if it is not one of the params (then we have already fixed it)
for (int i = 0; i < calleeMethod.getParameterCount(); i++) {
if (calleeMethod.getActiveBody().getParameterLocal(i).equals(sourceBase)) {
param = true;
}
}
if (!param) {
if (callUnit instanceof Stmt) {
Stmt stmt = (Stmt) callUnit;
if (stmt.getInvokeExpr() instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iIExpr = (InstanceInvokeExpr) stmt.getInvokeExpr();
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(source.getAccessPath().copyWithNewValue(iIExpr.getBase()),
(AbstractionWithPath) source).addPathElement(exitStmt));
else
res.add(new Abstraction(source.getAccessPath().copyWithNewValue(iIExpr.getBase()),
source));
}
}
}
}
}
// remember that we only support max(length(accesspath))==1 -> if source is a fieldref, only its base is taken!
//bugfix: we have to check if source is Local or fields have the same name:
for (SootField globalField : calleeMethod.getDeclaringClass().getFields()) {
if((source.getAccessPath().isLocal() || (source.getAccessPath().getField() != null && globalField.getName().equals(source.getAccessPath().getField().getName()))) && !globalField.isStatic()) { // else is checked later
PointsToSet ptsGlobal = pta.reachingObjects(calleeMethod.getActiveBody().getThisLocal(), globalField);
if (ptsGlobal.hasNonEmptyIntersection(ptsSource)) {
Local callBaseVar = null;
if (callUnit instanceof JAssignStmt) {
callBaseVar = (Local) ((InstanceInvokeExpr) ((JAssignStmt) callUnit).getInvokeExpr()).getBase();
}
if (callUnit instanceof JInvokeStmt) {
JInvokeStmt iStmt = (JInvokeStmt) callUnit;
Value v = iStmt.getInvokeExprBox().getValue();
InstanceInvokeExpr jvie = (InstanceInvokeExpr) v;
callBaseVar = (Local) jvie.getBase();
}
if (callBaseVar != null) {
SootFieldRef ref = globalField.makeRef();
InstanceFieldRef fRef = Jimple.v().newInstanceFieldRef(callBaseVar, ref);
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(fRef,
(AbstractionWithPath) source).addPathElement(exitStmt));
else
res.add(new Abstraction(fRef, source));
}
}
}
}
}
for (SootField globalField : calleeMethod.getDeclaringClass().getFields()) {
if ((source.getAccessPath().isLocal() || (source.getAccessPath().getField() != null && globalField.getName().equals(source.getAccessPath().getField().getName()))) && globalField.isStatic()) {
PointsToSet ptsGlobal = pta.reachingObjects(globalField);
if (ptsSource.hasNonEmptyIntersection(ptsGlobal)) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(Jimple.v().newStaticFieldRef(globalField.makeRef()),
(AbstractionWithPath) source).addPathElement(exitStmt));
else
res.add(new Abstraction(Jimple.v().newStaticFieldRef(globalField.makeRef()),
source));
}
}
}
}
//look for aliases in caller:
Set<Abstraction> aliasSet = new HashSet<Abstraction>();
for (Abstraction abs : res) {
if (abs.getAccessPath().isInstanceFieldRef()) { //TODO: or || abs.getAccessPath().isStaticFieldRef()? -> can't take plainValue then
Set<Value> aliases = getAliasesinMethod(interproceduralCFG().getMethodOf(retSite).getActiveBody().getUnits(), retSite, abs.getAccessPath().getPlainValue(), null);
for (Value v : aliases) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
aliasSet.add(new AbstractionWithPath(source.getAccessPath().copyWithNewValue(v), (AbstractionWithPath) source).addPathElement(exitStmt));
else
aliasSet.add(new Abstraction(source.getAccessPath().copyWithNewValue(v), source));
}
}
}
res.addAll(aliasSet);
return res;
}
private boolean isStringType(Type type) {
if (!(type instanceof RefType))
return false;
RefType rt = (RefType) type;
return rt.getSootClass().getName().equals("java.lang.String");
}
};
}
@Override
public FlowFunction<Abstraction> getCallToReturnFlowFunction(final Unit call, final Unit returnSite) {
// special treatment for native methods:
if (call instanceof Stmt) {
final Stmt iStmt = (Stmt) call;
final List<Value> callArgs = iStmt.getInvokeExpr().getArgs();
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
Set<Abstraction> res = new HashSet<Abstraction>();
res.add(source);
res.addAll(computeWrapperTaints(iStmt, callArgs, source));
if (iStmt.getInvokeExpr().getMethod().isNative()) {
if (callArgs.contains(source.getAccessPath().getPlainValue())) {
// java uses call by value, but fields of complex objects can be changed (and tainted), so use this conservative approach:
res.addAll(ncHandler.getTaintedValues(iStmt, source, callArgs));
}
}
if (iStmt instanceof JAssignStmt) {
final JAssignStmt stmt = (JAssignStmt) iStmt;
if (sourceSinkManager.isSource(stmt, interproceduralCFG())) {
if (DEBUG)
System.out.println("Found source: " + stmt.getInvokeExpr().getMethod());
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(stmt.getLeftOp(),
stmt.getInvokeExpr(),
stmt).addPathElement(call));
else
res.add(new Abstraction(stmt.getLeftOp(),
stmt.getInvokeExpr(),
stmt));
res.remove(zeroValue);
}
}
// if we have called a sink we have to store the path from the source - in case one of the params is tainted!
if (sourceSinkManager.isSink(iStmt, interproceduralCFG())) {
boolean taintedParam = false;
for (int i = 0; i < callArgs.size(); i++) {
if (callArgs.get(i).equals(source.getAccessPath().getPlainValue())) {
taintedParam = true;
break;
}
}
if (taintedParam) {
if (pathTracking != PathTrackingMethod.NoTracking)
results.addResult(iStmt.getInvokeExpr(), iStmt,
source.getSource(),
source.getSourceContext(),
((AbstractionWithPath) source).getPropagationPathAsString(interproceduralCFG()),
interproceduralCFG().getMethodOf(call) + ": " + call.toString());
else
results.addResult(iStmt.getInvokeExpr(), iStmt,
source.getSource(), source.getSourceContext());
}
//if the base object which executes the method is tainted the sink is reached, too.
if (iStmt.getInvokeExpr() instanceof InstanceInvokeExpr) {
InstanceInvokeExpr vie = (InstanceInvokeExpr) iStmt.getInvokeExpr();
if (vie.getBase().equals(source.getAccessPath().getPlainValue())) {
if (pathTracking != PathTrackingMethod.NoTracking)
results.addResult(iStmt.getInvokeExpr(), iStmt,
source.getSource(),
source.getSourceContext(),
((AbstractionWithPath) source).getPropagationPathAsString(interproceduralCFG()),
interproceduralCFG().getMethodOf(call) + ": " + call.toString());
else
results.addResult(iStmt.getInvokeExpr(), iStmt,
source.getSource(), source.getSourceContext());
}
}
}
return res;
}
};
}
return Identity.v();
}
};
}
|
diff --git a/AdventureBook/src/c301/AdventureBook/EditStoryActivity.java b/AdventureBook/src/c301/AdventureBook/EditStoryActivity.java
index 6e46b8f..092a638 100644
--- a/AdventureBook/src/c301/AdventureBook/EditStoryActivity.java
+++ b/AdventureBook/src/c301/AdventureBook/EditStoryActivity.java
@@ -1,259 +1,260 @@
/*
* Copyright (C) <2013> <Justin Hoy>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package c301.AdventureBook;
import java.io.Serializable;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.TextView;
import c301.AdventureBook.Controllers.StoryManager;
import c301.AdventureBook.Models.Page;
import c301.AdventureBook.Models.Story;
import com.example.adventurebook.R;
/**
* The edit story activity allows the author to edit the contents of a story by
* adding or removing story fragments.
*
* @author Justin
*
*/
public class EditStoryActivity extends Activity implements OnMenuItemClickListener, Serializable{
private final static int EDIT_PAGE = 1;
private final static int DELETE_PAGE = 2;
private ExpandableListAdapter adpt;
private ExpandableListView lstView;
private TextView title;
private TextView author;
private TextView description;
private EditText editTitle;
private EditText editAuthor;
private EditText editDescription;
private TextView date;
private Button createPage;
private Button returnLocalLib;
private PopupMenu popupMenu;
StoryManager sManagerInst;
private Story someStory;
private Page clickedPage;
private Typeface font;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.example.adventurebook.R.layout.edit_story_pages);
font = Typeface.createFromAsset(getAssets(), "fonts/straightline.ttf");
title = (TextView)findViewById(com.example.adventurebook.R.id.title);
title.setTypeface(font);
author = (TextView)findViewById(com.example.adventurebook.R.id.author);
author.setTypeface(font);
description = (TextView)findViewById(com.example.adventurebook.R.id.description);
description.setTypeface(font);
editTitle = (EditText)findViewById(com.example.adventurebook.R.id.editTitle);
editAuthor = (EditText)findViewById(com.example.adventurebook.R.id.editAuthor);
editDescription = (EditText)findViewById(com.example.adventurebook.R.id.editDescription);
editDescription.setMovementMethod(new ScrollingMovementMethod());
date = (TextView)findViewById(com.example.adventurebook.R.id.date);
date.setTypeface(font);
lstView = (ExpandableListView)findViewById(R.id.expList);
createPage = (Button) findViewById(R.id.create_new_page);
returnLocalLib = (Button) findViewById(R.id.return_local_lib);
popupMenu = new PopupMenu(this, findViewById(R.id.expList));
popupMenu.getMenu().add(Menu.NONE, EDIT_PAGE, Menu.NONE, "Edit Page");
popupMenu.getMenu().add(Menu.NONE, DELETE_PAGE, Menu.NONE, "Delete Page");
popupMenu.setOnMenuItemClickListener(this);
sManagerInst = StoryManager.getInstance();
sManagerInst.initContext(this);
fillData();
createPage.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sManagerInst.createPage();
fillData();
}
});
returnLocalLib.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
saveState();
Intent i = new Intent(EditStoryActivity.this, OfflineLibraryActivity.class);
startActivity(i);
}
});
lstView.setOnGroupExpandListener(new OnGroupExpandListener()
{
@Override
public void onGroupExpand(int position) {
+ clickedPage = (Page)adpt.getGroup(position);
popupMenu.show();
}
});
/*
lstView.setOnChildClickListener(new OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
Option subPage= (Option)adpt.getChild(groupPosition, childPosition);
// update the text view with the country
return true;
}
});
*/
}
/**
* Provides actions to take upon clicking an option on the popup menu
*
* @param item in popup menu clicked
* @return a boolean indicating task handled
*/
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
// User selects edit page
case EDIT_PAGE:
saveState();
sManagerInst.setCurrentPage(clickedPage);
Intent i = new Intent(EditStoryActivity.this, EditPageActivity.class);
startActivityForResult(i, EDIT_PAGE);
break;
// User selects delete page
case DELETE_PAGE:
// Ask for a confirmation from user by:
// Instantiating an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(EditStoryActivity.this);
// Add buttons
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
sManagerInst.deletePage(clickedPage);
fillData();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Chain together various setter methods to set the dialog characteristics
builder.setMessage(R.string.delete_page_confirm);
// Get the AlertDialog from create()
AlertDialog dialog = builder.create();
dialog.show();
break;
}
return false;
}
/**
* Populates the list view with a list of all the pages in the story
*/
private void fillData() {
//load model here
someStory = sManagerInst.getCurrentStory();
editTitle.setText(someStory.getTitle());
editAuthor.setText(someStory.getDescription());
editDescription.setText(someStory.getAuthor());
date.setText(someStory.getDate());
List<Page> storyPages = someStory.getPages();
adpt = new ExpandableListAdapter(this, lstView, storyPages);
lstView.setAdapter(adpt);
}
/**
* Refills view for all pages upon resuming activity
*
*/
@Override
public void onResume(){
super.onResume();
fillData();
}
private void saveState() {
String title = editTitle.getText().toString();
String author = editAuthor.getText().toString();
String description = editDescription.getText().toString();
someStory.setTitle(title);
someStory.setAuthor(author);
someStory.setDescription(description);
}
/* Do we want a context menu instead?
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case DELETE_ID:
//AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
//mDbHelper.deletePage(info.id);
fillData();
return true;
}
return super.onContextItemSelected(item);
}
*/
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.example.adventurebook.R.layout.edit_story_pages);
font = Typeface.createFromAsset(getAssets(), "fonts/straightline.ttf");
title = (TextView)findViewById(com.example.adventurebook.R.id.title);
title.setTypeface(font);
author = (TextView)findViewById(com.example.adventurebook.R.id.author);
author.setTypeface(font);
description = (TextView)findViewById(com.example.adventurebook.R.id.description);
description.setTypeface(font);
editTitle = (EditText)findViewById(com.example.adventurebook.R.id.editTitle);
editAuthor = (EditText)findViewById(com.example.adventurebook.R.id.editAuthor);
editDescription = (EditText)findViewById(com.example.adventurebook.R.id.editDescription);
editDescription.setMovementMethod(new ScrollingMovementMethod());
date = (TextView)findViewById(com.example.adventurebook.R.id.date);
date.setTypeface(font);
lstView = (ExpandableListView)findViewById(R.id.expList);
createPage = (Button) findViewById(R.id.create_new_page);
returnLocalLib = (Button) findViewById(R.id.return_local_lib);
popupMenu = new PopupMenu(this, findViewById(R.id.expList));
popupMenu.getMenu().add(Menu.NONE, EDIT_PAGE, Menu.NONE, "Edit Page");
popupMenu.getMenu().add(Menu.NONE, DELETE_PAGE, Menu.NONE, "Delete Page");
popupMenu.setOnMenuItemClickListener(this);
sManagerInst = StoryManager.getInstance();
sManagerInst.initContext(this);
fillData();
createPage.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sManagerInst.createPage();
fillData();
}
});
returnLocalLib.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
saveState();
Intent i = new Intent(EditStoryActivity.this, OfflineLibraryActivity.class);
startActivity(i);
}
});
lstView.setOnGroupExpandListener(new OnGroupExpandListener()
{
@Override
public void onGroupExpand(int position) {
popupMenu.show();
}
});
/*
lstView.setOnChildClickListener(new OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
Option subPage= (Option)adpt.getChild(groupPosition, childPosition);
// update the text view with the country
return true;
}
});
*/
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.example.adventurebook.R.layout.edit_story_pages);
font = Typeface.createFromAsset(getAssets(), "fonts/straightline.ttf");
title = (TextView)findViewById(com.example.adventurebook.R.id.title);
title.setTypeface(font);
author = (TextView)findViewById(com.example.adventurebook.R.id.author);
author.setTypeface(font);
description = (TextView)findViewById(com.example.adventurebook.R.id.description);
description.setTypeface(font);
editTitle = (EditText)findViewById(com.example.adventurebook.R.id.editTitle);
editAuthor = (EditText)findViewById(com.example.adventurebook.R.id.editAuthor);
editDescription = (EditText)findViewById(com.example.adventurebook.R.id.editDescription);
editDescription.setMovementMethod(new ScrollingMovementMethod());
date = (TextView)findViewById(com.example.adventurebook.R.id.date);
date.setTypeface(font);
lstView = (ExpandableListView)findViewById(R.id.expList);
createPage = (Button) findViewById(R.id.create_new_page);
returnLocalLib = (Button) findViewById(R.id.return_local_lib);
popupMenu = new PopupMenu(this, findViewById(R.id.expList));
popupMenu.getMenu().add(Menu.NONE, EDIT_PAGE, Menu.NONE, "Edit Page");
popupMenu.getMenu().add(Menu.NONE, DELETE_PAGE, Menu.NONE, "Delete Page");
popupMenu.setOnMenuItemClickListener(this);
sManagerInst = StoryManager.getInstance();
sManagerInst.initContext(this);
fillData();
createPage.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sManagerInst.createPage();
fillData();
}
});
returnLocalLib.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
saveState();
Intent i = new Intent(EditStoryActivity.this, OfflineLibraryActivity.class);
startActivity(i);
}
});
lstView.setOnGroupExpandListener(new OnGroupExpandListener()
{
@Override
public void onGroupExpand(int position) {
clickedPage = (Page)adpt.getGroup(position);
popupMenu.show();
}
});
/*
lstView.setOnChildClickListener(new OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
Option subPage= (Option)adpt.getChild(groupPosition, childPosition);
// update the text view with the country
return true;
}
});
*/
}
|
diff --git a/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ovf/OvfVmReader.java b/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ovf/OvfVmReader.java
index b6ae02783..85d8f4a12 100644
--- a/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ovf/OvfVmReader.java
+++ b/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ovf/OvfVmReader.java
@@ -1,368 +1,370 @@
package org.ovirt.engine.core.utils.ovf;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.common.businessentities.BootSequence;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.DisplayType;
import org.ovirt.engine.core.common.businessentities.OriginType;
import org.ovirt.engine.core.common.businessentities.Snapshot;
import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotStatus;
import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotType;
import org.ovirt.engine.core.common.businessentities.UsbPolicy;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmNetworkInterface;
import org.ovirt.engine.core.common.businessentities.VmOsType;
import org.ovirt.engine.core.common.businessentities.VmStatic;
import org.ovirt.engine.core.common.businessentities.VmType;
import org.ovirt.engine.core.common.utils.VmDeviceCommonUtils;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.core.compat.backendcompat.XmlDocument;
import org.ovirt.engine.core.compat.backendcompat.XmlNode;
import org.ovirt.engine.core.compat.backendcompat.XmlNodeList;
import org.ovirt.engine.core.utils.linq.LinqUtils;
import org.ovirt.engine.core.utils.linq.Predicate;
public class OvfVmReader extends OvfReader {
private static final String EXPORT_ONLY_PREFIX = "exportonly_";
protected VM _vm;
public OvfVmReader(XmlDocument document,
VM vm,
ArrayList<DiskImage> images,
ArrayList<VmNetworkInterface> interfaces) {
super(document, images, interfaces);
_vm = vm;
_vm.setInterfaces(interfaces);
}
@Override
protected void ReadOsSection(XmlNode section) {
_vm.getStaticData().setId(new Guid(section.Attributes.get("ovf:id").getValue()));
XmlNode node = section.SelectSingleNode("Description");
if (node != null) {
_vm.getStaticData().setos(VmOsType.valueOf(node.InnerText));
} else {
_vm.getStaticData().setos(VmOsType.Unassigned);
}
}
@Override
protected void ReadHardwareSection(XmlNode section) {
XmlNodeList list = section.SelectNodes("Item");
for (XmlNode node : list) {
String resourceType = node.SelectSingleNode("rasd:ResourceType", _xmlNS).InnerText;
if (StringHelper.EqOp(resourceType, OvfHardware.CPU)) {
_vm.getStaticData().setnum_of_sockets(
Integer.parseInt(node.SelectSingleNode("rasd:num_of_sockets", _xmlNS).InnerText));
_vm.getStaticData().setcpu_per_socket(
Integer.parseInt(node.SelectSingleNode("rasd:cpu_per_socket", _xmlNS).InnerText));
} else if (StringHelper.EqOp(resourceType, OvfHardware.Memory)) {
_vm.getStaticData().setmem_size_mb(
Integer.parseInt(node.SelectSingleNode("rasd:VirtualQuantity", _xmlNS).InnerText));
} else if (StringHelper.EqOp(resourceType, OvfHardware.DiskImage)) {
final Guid guid = new Guid(node.SelectSingleNode("rasd:InstanceId", _xmlNS).InnerText);
DiskImage image = LinqUtils.firstOrNull(_images, new Predicate<DiskImage>() {
@Override
public boolean eval(DiskImage diskImage) {
return diskImage.getImageId().equals(guid);
}
});
image.setId(OvfParser.GetImageGrupIdFromImageFile(node.SelectSingleNode(
"rasd:HostResource", _xmlNS).InnerText));
if (!StringHelper.isNullOrEmpty(node.SelectSingleNode("rasd:Parent", _xmlNS).InnerText)) {
image.setParentId(new Guid(node.SelectSingleNode("rasd:Parent", _xmlNS).InnerText));
}
if (!StringHelper.isNullOrEmpty(node.SelectSingleNode("rasd:Template", _xmlNS).InnerText)) {
image.setit_guid(new Guid(node.SelectSingleNode("rasd:Template", _xmlNS).InnerText));
}
image.setappList(node.SelectSingleNode("rasd:ApplicationList", _xmlNS).InnerText);
if (!StringHelper.isNullOrEmpty(node.SelectSingleNode("rasd:StorageId", _xmlNS).InnerText)) {
image.setstorage_ids(new ArrayList<Guid>(Arrays.asList(new Guid(node.SelectSingleNode("rasd:StorageId", _xmlNS).InnerText))));
}
if (!StringHelper.isNullOrEmpty(node.SelectSingleNode("rasd:StoragePoolId", _xmlNS).InnerText)) {
image.setstorage_pool_id(new Guid(node.SelectSingleNode("rasd:StoragePoolId", _xmlNS).InnerText));
}
final Date creationDate = OvfParser.UtcDateStringToLocaDate(
node.SelectSingleNode("rasd:CreationDate", _xmlNS).InnerText);
if (creationDate == null) {
image.setcreation_date(creationDate);
}
final Date lastModified = OvfParser.UtcDateStringToLocaDate(
node.SelectSingleNode("rasd:LastModified", _xmlNS).InnerText);
if (lastModified != null) {
image.setlastModified(lastModified);
}
final Date last_modified_date = OvfParser.UtcDateStringToLocaDate(
node.SelectSingleNode("rasd:last_modified_date", _xmlNS).InnerText);
if (last_modified_date != null) {
image.setlast_modified_date(last_modified_date);
}
readVmDevice(node, _vm.getStaticData(), image.getId(), Boolean.TRUE);
} else if (StringHelper.EqOp(resourceType, OvfHardware.Network)) {
VmNetworkInterface iface = getNetwotkInterface(node);
updateSingleNic(node, iface);
_vm.getInterfaces().add(iface);
readVmDevice(node, _vm.getStaticData(), iface.getId(), Boolean.TRUE);
} else if (StringHelper.EqOp(resourceType, OvfHardware.USB)) {
_vm.getStaticData().setusb_policy(
UsbPolicy.forStringValue(node.SelectSingleNode("rasd:UsbPolicy", _xmlNS).InnerText));
} else if (StringHelper.EqOp(resourceType, OvfHardware.Monitor)) {
_vm.getStaticData().setnum_of_monitors(
Integer.parseInt(node.SelectSingleNode("rasd:VirtualQuantity", _xmlNS).InnerText));
readVmDevice(node, _vm.getStaticData(), Guid.NewGuid(), Boolean.TRUE);
} else if (StringHelper.EqOp(resourceType, OvfHardware.CD)) {
readVmDevice(node, _vm.getStaticData(), Guid.NewGuid(), Boolean.TRUE);
} else if (StringHelper.EqOp(resourceType, OvfHardware.OTHER)) {
if (node.SelectSingleNode(OvfProperties.VMD_TYPE, _xmlNS) != null
&& !StringHelper.isNullOrEmpty(node.SelectSingleNode(OvfProperties.VMD_TYPE, _xmlNS).InnerText)) {
String type = String.valueOf(node.SelectSingleNode(OvfProperties.VMD_TYPE, _xmlNS).InnerText);
String device = String.valueOf(node.SelectSingleNode(OvfProperties.VMD_DEVICE, _xmlNS).InnerText);
// special devices are treated as managed devices but still have the OTHER OVF ResourceType
if (VmDeviceCommonUtils.isSpecialDevice(device, type)) {
readVmDevice(node, _vm.getStaticData(), Guid.NewGuid(), Boolean.TRUE);
} else {
readVmDevice(node, _vm.getStaticData(), Guid.NewGuid(), Boolean.FALSE);
}
} else {
readVmDevice(node, _vm.getStaticData(), Guid.NewGuid(), Boolean.FALSE);
}
}
}
}
@Override
protected void ReadGeneralData() {
// General Vm
XmlNode content = _document.SelectSingleNode("//*/Content");
XmlNode node = content.SelectSingleNode("Name");
if (node != null) {
_vm.getStaticData().setvm_name(node.InnerText);
name = _vm.getStaticData().getvm_name();
}
node = content.SelectSingleNode("TemplateId");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.getStaticData().setvmt_guid(new Guid(node.InnerText));
}
}
node = content.SelectSingleNode("TemplateName");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setvmt_name(node.InnerText);
}
}
node = content.SelectSingleNode("Description");
if (node != null) {
_vm.getStaticData().setdescription(node.InnerText);
}
node = content.SelectSingleNode("Domain");
if (node != null) {
_vm.getStaticData().setdomain(node.InnerText);
}
node = content.SelectSingleNode("CreationDate");
final Date creationDate = OvfParser.UtcDateStringToLocaDate(node.InnerText);
if (creationDate != null) {
_vm.getStaticData().setcreation_date(creationDate);
}
node = content.SelectSingleNode("ExportDate");
- final Date exportDate = OvfParser.UtcDateStringToLocaDate(node.InnerText);
- if (exportDate != null) {
- _vm.getStaticData().setExportDate(exportDate);
+ if (node != null) {
+ final Date exportDate = OvfParser.UtcDateStringToLocaDate(node.InnerText);
+ if (exportDate != null) {
+ _vm.getStaticData().setExportDate(exportDate);
+ }
}
node = content.SelectSingleNode("IsInitilized");
if (node != null) {
_vm.getStaticData().setis_initialized(Boolean.parseBoolean(node.InnerText));
}
node = content.SelectSingleNode("IsAutoSuspend");
if (node != null) {
_vm.getStaticData().setis_auto_suspend(Boolean.parseBoolean(node.InnerText));
}
node = content.SelectSingleNode("TimeZone");
if (node != null) {
_vm.getStaticData().settime_zone(node.InnerText);
}
node = content.SelectSingleNode("IsStateless");
if (node != null) {
_vm.getStaticData().setis_stateless(Boolean.parseBoolean(node.InnerText));
}
XmlNodeList list = content.SelectNodes("Section");
for (XmlNode section : list) {
String value = section.Attributes.get("xsi:type").getValue();
if (StringHelper.EqOp(value, "ovf:OperatingSystemSection_Type")) {
ReadOsSection(section);
}
else if (StringHelper.EqOp(value, "ovf:VirtualHardwareSection_Type")) {
ReadHardwareSection(section);
} else if (StringUtils.equals(value, "ovf:SnapshotsSection_Type")) {
readSnapshotsSection(section);
}
}
node = content.SelectSingleNode("Origin");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setorigin(OriginType.forValue(Integer.parseInt(node.InnerText)));
}
}
node = content.SelectSingleNode("initrd_url");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setinitrd_url((node.InnerText));
}
}
node = content.SelectSingleNode("default_boot_sequence");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setdefault_boot_sequence(BootSequence.forValue(Integer.parseInt(node.InnerText)));
}
}
node = content.SelectSingleNode("kernel_url");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setkernel_url((node.InnerText));
}
}
node = content.SelectSingleNode("kernel_params");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setkernel_params((node.InnerText));
}
}
OvfLogEventHandler<VmStatic> handler = new VMStaticOvfLogHandler(_vm.getStaticData());
// Gets a list of all the aliases of the fields that should be logged in
// ovd For each one of these fields, the proper value will be read from
// the ovf and field in vm static
List<String> aliases = handler.getAliases();
for (String alias : aliases) {
String value = readEventLogValue(content, alias);
if (!StringHelper.isNullOrEmpty(value)) {
handler.addValueForAlias(alias, value);
}
}
node = content.SelectSingleNode("app_list");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setapp_list(node.InnerText);
}
}
// if no app list in VM, get it from one of the leafs
else if(_images != null && _images.size() > 0) {
int root = GetFirstImage(_images, _images.get(0));
if (root != -1) {
for(int i=0; i<_images.size(); i++) {
int x = GetNextImage(_images, _images.get(i));
if (x == -1) {
_vm.setapp_list(_images.get(i).getappList());
}
}
} else {
_vm.setapp_list(_images.get(0).getappList());
}
}
node = content.SelectSingleNode("VmType");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setvm_type(VmType.forValue(Integer.parseInt(node.InnerText)));
}
}
node = content.SelectSingleNode("DefaultDisplayType");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setdefault_display_type(DisplayType.forValue(Integer.parseInt(node.InnerText)));
}
}
node = content.SelectSingleNode("MinAllocatedMem");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setMinAllocatedMem(Integer.parseInt(node.InnerText));
}
}
}
// function returns the index of the image that has no parent
private static int GetFirstImage(java.util.ArrayList<DiskImage> images, DiskImage curr) {
for (int i = 0; i < images.size(); i++) {
if (curr.getParentId().equals(images.get(i).getImageId())) {
return i;
}
}
return -1;
}
// function returns the index of image that is it's child
private static int GetNextImage(java.util.ArrayList<DiskImage> images, DiskImage curr) {
for (int i = 0; i < images.size(); i++) {
if (images.get(i).getParentId().equals(curr.getImageId())) {
return i;
}
}
return -1;
}
private String readEventLogValue(XmlNode content, String name) {
StringBuilder fullNameSB = new StringBuilder(EXPORT_ONLY_PREFIX);
fullNameSB.append(name);
XmlNode node = content.SelectSingleNode(fullNameSB.toString());
if (node != null) {
return node.InnerText;
}
return null;
}
private void readSnapshotsSection(XmlNode section) {
XmlNodeList list = section.SelectNodes("Snapshot");
ArrayList<Snapshot> snapshots = new ArrayList<Snapshot>();
_vm.setSnapshots(snapshots);
for (XmlNode node : list) {
XmlNode vmConfiguration = node.SelectSingleNode("VmConfiguration", _xmlNS);
Snapshot snapshot = new Snapshot(vmConfiguration != null);
snapshot.setId(new Guid(node.Attributes.get("ovf:id").getValue()));
snapshot.setVmId(_vm.getId());
snapshot.setType(SnapshotType.valueOf(node.SelectSingleNode("Type", _xmlNS).InnerText));
snapshot.setStatus(SnapshotStatus.OK);
snapshot.setDescription(node.SelectSingleNode("Description", _xmlNS).InnerText);
final Date creationDate = OvfParser.UtcDateStringToLocaDate(node.SelectSingleNode("CreationDate", _xmlNS).InnerText);
if (creationDate != null) {
snapshot.setCreationDate(creationDate);
}
snapshot.setVmConfiguration(vmConfiguration == null
? null : new String(Base64.decodeBase64(vmConfiguration.InnerText)));
XmlNode appList = node.SelectSingleNode("ApplicationList", _xmlNS);
if (appList != null) {
snapshot.setAppList(appList.InnerText);
}
snapshots.add(snapshot);
}
}
@Override
protected void buildNicReference() {
}
}
| true | true | protected void ReadGeneralData() {
// General Vm
XmlNode content = _document.SelectSingleNode("//*/Content");
XmlNode node = content.SelectSingleNode("Name");
if (node != null) {
_vm.getStaticData().setvm_name(node.InnerText);
name = _vm.getStaticData().getvm_name();
}
node = content.SelectSingleNode("TemplateId");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.getStaticData().setvmt_guid(new Guid(node.InnerText));
}
}
node = content.SelectSingleNode("TemplateName");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setvmt_name(node.InnerText);
}
}
node = content.SelectSingleNode("Description");
if (node != null) {
_vm.getStaticData().setdescription(node.InnerText);
}
node = content.SelectSingleNode("Domain");
if (node != null) {
_vm.getStaticData().setdomain(node.InnerText);
}
node = content.SelectSingleNode("CreationDate");
final Date creationDate = OvfParser.UtcDateStringToLocaDate(node.InnerText);
if (creationDate != null) {
_vm.getStaticData().setcreation_date(creationDate);
}
node = content.SelectSingleNode("ExportDate");
final Date exportDate = OvfParser.UtcDateStringToLocaDate(node.InnerText);
if (exportDate != null) {
_vm.getStaticData().setExportDate(exportDate);
}
node = content.SelectSingleNode("IsInitilized");
if (node != null) {
_vm.getStaticData().setis_initialized(Boolean.parseBoolean(node.InnerText));
}
node = content.SelectSingleNode("IsAutoSuspend");
if (node != null) {
_vm.getStaticData().setis_auto_suspend(Boolean.parseBoolean(node.InnerText));
}
node = content.SelectSingleNode("TimeZone");
if (node != null) {
_vm.getStaticData().settime_zone(node.InnerText);
}
node = content.SelectSingleNode("IsStateless");
if (node != null) {
_vm.getStaticData().setis_stateless(Boolean.parseBoolean(node.InnerText));
}
XmlNodeList list = content.SelectNodes("Section");
for (XmlNode section : list) {
String value = section.Attributes.get("xsi:type").getValue();
if (StringHelper.EqOp(value, "ovf:OperatingSystemSection_Type")) {
ReadOsSection(section);
}
else if (StringHelper.EqOp(value, "ovf:VirtualHardwareSection_Type")) {
ReadHardwareSection(section);
} else if (StringUtils.equals(value, "ovf:SnapshotsSection_Type")) {
readSnapshotsSection(section);
}
}
node = content.SelectSingleNode("Origin");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setorigin(OriginType.forValue(Integer.parseInt(node.InnerText)));
}
}
node = content.SelectSingleNode("initrd_url");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setinitrd_url((node.InnerText));
}
}
node = content.SelectSingleNode("default_boot_sequence");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setdefault_boot_sequence(BootSequence.forValue(Integer.parseInt(node.InnerText)));
}
}
node = content.SelectSingleNode("kernel_url");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setkernel_url((node.InnerText));
}
}
node = content.SelectSingleNode("kernel_params");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setkernel_params((node.InnerText));
}
}
OvfLogEventHandler<VmStatic> handler = new VMStaticOvfLogHandler(_vm.getStaticData());
// Gets a list of all the aliases of the fields that should be logged in
// ovd For each one of these fields, the proper value will be read from
// the ovf and field in vm static
List<String> aliases = handler.getAliases();
for (String alias : aliases) {
String value = readEventLogValue(content, alias);
if (!StringHelper.isNullOrEmpty(value)) {
handler.addValueForAlias(alias, value);
}
}
node = content.SelectSingleNode("app_list");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setapp_list(node.InnerText);
}
}
// if no app list in VM, get it from one of the leafs
else if(_images != null && _images.size() > 0) {
int root = GetFirstImage(_images, _images.get(0));
if (root != -1) {
for(int i=0; i<_images.size(); i++) {
int x = GetNextImage(_images, _images.get(i));
if (x == -1) {
_vm.setapp_list(_images.get(i).getappList());
}
}
} else {
_vm.setapp_list(_images.get(0).getappList());
}
}
node = content.SelectSingleNode("VmType");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setvm_type(VmType.forValue(Integer.parseInt(node.InnerText)));
}
}
node = content.SelectSingleNode("DefaultDisplayType");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setdefault_display_type(DisplayType.forValue(Integer.parseInt(node.InnerText)));
}
}
node = content.SelectSingleNode("MinAllocatedMem");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setMinAllocatedMem(Integer.parseInt(node.InnerText));
}
}
}
| protected void ReadGeneralData() {
// General Vm
XmlNode content = _document.SelectSingleNode("//*/Content");
XmlNode node = content.SelectSingleNode("Name");
if (node != null) {
_vm.getStaticData().setvm_name(node.InnerText);
name = _vm.getStaticData().getvm_name();
}
node = content.SelectSingleNode("TemplateId");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.getStaticData().setvmt_guid(new Guid(node.InnerText));
}
}
node = content.SelectSingleNode("TemplateName");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setvmt_name(node.InnerText);
}
}
node = content.SelectSingleNode("Description");
if (node != null) {
_vm.getStaticData().setdescription(node.InnerText);
}
node = content.SelectSingleNode("Domain");
if (node != null) {
_vm.getStaticData().setdomain(node.InnerText);
}
node = content.SelectSingleNode("CreationDate");
final Date creationDate = OvfParser.UtcDateStringToLocaDate(node.InnerText);
if (creationDate != null) {
_vm.getStaticData().setcreation_date(creationDate);
}
node = content.SelectSingleNode("ExportDate");
if (node != null) {
final Date exportDate = OvfParser.UtcDateStringToLocaDate(node.InnerText);
if (exportDate != null) {
_vm.getStaticData().setExportDate(exportDate);
}
}
node = content.SelectSingleNode("IsInitilized");
if (node != null) {
_vm.getStaticData().setis_initialized(Boolean.parseBoolean(node.InnerText));
}
node = content.SelectSingleNode("IsAutoSuspend");
if (node != null) {
_vm.getStaticData().setis_auto_suspend(Boolean.parseBoolean(node.InnerText));
}
node = content.SelectSingleNode("TimeZone");
if (node != null) {
_vm.getStaticData().settime_zone(node.InnerText);
}
node = content.SelectSingleNode("IsStateless");
if (node != null) {
_vm.getStaticData().setis_stateless(Boolean.parseBoolean(node.InnerText));
}
XmlNodeList list = content.SelectNodes("Section");
for (XmlNode section : list) {
String value = section.Attributes.get("xsi:type").getValue();
if (StringHelper.EqOp(value, "ovf:OperatingSystemSection_Type")) {
ReadOsSection(section);
}
else if (StringHelper.EqOp(value, "ovf:VirtualHardwareSection_Type")) {
ReadHardwareSection(section);
} else if (StringUtils.equals(value, "ovf:SnapshotsSection_Type")) {
readSnapshotsSection(section);
}
}
node = content.SelectSingleNode("Origin");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setorigin(OriginType.forValue(Integer.parseInt(node.InnerText)));
}
}
node = content.SelectSingleNode("initrd_url");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setinitrd_url((node.InnerText));
}
}
node = content.SelectSingleNode("default_boot_sequence");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setdefault_boot_sequence(BootSequence.forValue(Integer.parseInt(node.InnerText)));
}
}
node = content.SelectSingleNode("kernel_url");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setkernel_url((node.InnerText));
}
}
node = content.SelectSingleNode("kernel_params");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setkernel_params((node.InnerText));
}
}
OvfLogEventHandler<VmStatic> handler = new VMStaticOvfLogHandler(_vm.getStaticData());
// Gets a list of all the aliases of the fields that should be logged in
// ovd For each one of these fields, the proper value will be read from
// the ovf and field in vm static
List<String> aliases = handler.getAliases();
for (String alias : aliases) {
String value = readEventLogValue(content, alias);
if (!StringHelper.isNullOrEmpty(value)) {
handler.addValueForAlias(alias, value);
}
}
node = content.SelectSingleNode("app_list");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setapp_list(node.InnerText);
}
}
// if no app list in VM, get it from one of the leafs
else if(_images != null && _images.size() > 0) {
int root = GetFirstImage(_images, _images.get(0));
if (root != -1) {
for(int i=0; i<_images.size(); i++) {
int x = GetNextImage(_images, _images.get(i));
if (x == -1) {
_vm.setapp_list(_images.get(i).getappList());
}
}
} else {
_vm.setapp_list(_images.get(0).getappList());
}
}
node = content.SelectSingleNode("VmType");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setvm_type(VmType.forValue(Integer.parseInt(node.InnerText)));
}
}
node = content.SelectSingleNode("DefaultDisplayType");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setdefault_display_type(DisplayType.forValue(Integer.parseInt(node.InnerText)));
}
}
node = content.SelectSingleNode("MinAllocatedMem");
if (node != null) {
if (!StringHelper.isNullOrEmpty(node.InnerText)) {
_vm.setMinAllocatedMem(Integer.parseInt(node.InnerText));
}
}
}
|
diff --git a/src/main/java/com/mvplugin/downloader/DefaultFileLink.java b/src/main/java/com/mvplugin/downloader/DefaultFileLink.java
index d7e99c6..9c3d8ea 100644
--- a/src/main/java/com/mvplugin/downloader/DefaultFileLink.java
+++ b/src/main/java/com/mvplugin/downloader/DefaultFileLink.java
@@ -1,257 +1,257 @@
package com.mvplugin.downloader;
import com.mvplugin.downloader.api.FileLink;
import com.mvplugin.downloader.api.VersionType;
import org.bukkit.ChatColor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
/**
* Our default implementation of a FileLink.
*/
class DefaultFileLink implements FileLink {
private static final String LS = "\n";
private final String pluginName;
private final URL filePageURL;
private final String version;
private final URL downloadURL;
private final long fileSize;
private final String fileName;
private final String gameVersion;
private final VersionType versionType;
private final int downloadCount;
private final Date uploadDate;
private final String changeLog;
private final String knownCaveats;
private final String md5CheckSum;
DefaultFileLink(final String link, final String pluginName) throws MalformedURLException, IOException {
this.pluginName = pluginName;
this.filePageURL = new URL(link);
final URLConnection urlConn = filePageURL.openConnection();
BufferedReader reader = null;
// Used for detecting elements
int sizeLine = -1;
int titleLine = -1;
int gameVersionLine = -1;
int versionTypeLine = -1;
int downloadCountLine = -1;
int uploadDateLine = -1;
int md5Line = -1;
int changeLogLine = -1;
int knownCaveatsLine = -1;
// Temp storage
String downloadLink = "";
String fileName = "";
String gameVersion = "";
long fileSize = -1;
String title = "";
String versionType = "";
String downloadCount = "";
String uploadDate = "";
String md5 = "";
final StringBuilder changeLog = new StringBuilder();
final StringBuilder knownCaveats = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
int counter = 0;
String line;
while((line = reader.readLine()) != null) {
counter++;
// Search for the download link
if(line.contains("<li class=\"user-action user-action-download\">")) {
// Get the raw link
downloadLink = line.split("<a href=\"")[1].split("\">Download</a>")[0];
String[] split = downloadLink.split("/");
fileName = split[split.length - 1].trim();
}
// Search for size
else if (line.contains("<dt>Size</dt>")) {
sizeLine = counter + 1;
} else if(counter == sizeLine) {
String size = line.replaceAll("<dd>", "").replaceAll("</dd>", "").trim();
int multiplier = size.contains("MiB") ? 1048576 : 1024;
size = size.replace(" KiB", "").replace(" MiB", "");
fileSize = (long)(Double.parseDouble(size) * multiplier);
}
// Search for version title
else if (line.contains("<header class=\"main-header\"><div class=\"line\">")) {
titleLine = counter + 2;
} else if (counter == titleLine) {
title = line.trim();
}
// Search for game version
else if (line.contains("<dt>Game version</dt>")) {
gameVersionLine = counter + 1;
} else if (counter == gameVersionLine) {
- gameVersion = line.replaceAll("<dd>.*<li>", "").replaceAll("</li>.*</dd>", "").trim();
+ gameVersion = line.replaceAll("<dd>.*?<li>", "").replaceAll("</li>.*</dd>", "").trim();
}
// Search for version Type
else if (line.contains("<dt>Type</dt>")) {
versionTypeLine = counter + 1;
} else if (counter == versionTypeLine) {
- versionType = line.replaceAll("<dd>.*-b\">", "").replaceAll("</span></dd>", "").trim();
+ versionType = line.replaceAll("<dd>.*?\">", "").replaceAll("</span></dd>", "").trim();
}
// Search for download count
else if (line.contains("<dt>Downloads</dt>")) {
downloadCountLine = counter + 1;
} else if (counter == downloadCountLine) {
- downloadCount = line.replaceAll("<dd>.*e=\"", "").replaceAll("\">.*</dd>", "").trim();
+ downloadCount = line.replaceAll("<dd>.*?e=\"", "").replaceAll("\">.*</dd>", "").trim();
}
// Search for download count
else if (line.contains("<dt>Uploaded on</dt>")) {
uploadDateLine = counter + 1;
} else if (counter == uploadDateLine) {
- uploadDate = line.replaceAll("<dd>.*epoch=\"", "").replaceAll("\"\\sdata.*</dd>", "").trim();
+ uploadDate = line.replaceAll("<dd>.*?epoch=\"", "").replaceAll("\"\\sdata.*?</dd>", "").trim();
}
// Search for md5
else if (line.contains("<dt>MD5</dt>")) {
md5Line = counter + 1;
} else if (counter == md5Line) {
md5 = line.replaceAll("<dd>", "").replaceAll("</dd>", "").trim();
}
// Search for change log
else if (line.contains("<div class=\"content-box\"><div class=\"content-box-inner\"><h3>Change log</h3>")) {
changeLog.append(parseHtmlLine(line.replace("<div class=\"content-box\"><div class=\"content-box-inner\"><h3>Change log</h3>", ""))).append(LS);
changeLogLine = counter + 1;
} else if (counter == changeLogLine) {
if (line.contains("</div></div>")) {
continue;
}
changeLog.append(parseHtmlLine(line)).append(LS);
changeLogLine++;
}
// Search for known caveats
else if (line.contains("<div class=\"content-box\"><div class=\"content-box-inner\"><h3>Known caveats</h3>")) {
knownCaveats.append(parseHtmlLine(line.replace("<div class=\"content-box\"><div class=\"content-box-inner\"><h3>Known caveats</h3>", ""))).append(LS);
knownCaveatsLine = counter + 1;
} else if (counter == knownCaveatsLine) {
if (line.contains("</div></div>")) {
continue;
}
knownCaveats.append(parseHtmlLine(line)).append(LS);
knownCaveatsLine++;
}
}
} finally {
if (reader != null) {
reader.close();
}
}
if (downloadLink == null) {
// TODO make this better
throw new IOException();
}
this.downloadURL = new URL(downloadLink);
this.fileSize = fileSize;
this.version = title;
this.fileName = fileName;
this.gameVersion = gameVersion;
VersionType tempType = VersionType.UNKNOWN;
try {
tempType = VersionType.valueOf(versionType.toUpperCase());
} catch (IllegalArgumentException ignore) { }
this.versionType = tempType;
int downloads = -1;
try {
downloads = Integer.parseInt(downloadCount);
} catch (NumberFormatException ignore) { }
this.downloadCount = downloads;
long epochTime = -1;
try {
epochTime = Long.parseLong(uploadDate);
} catch (NumberFormatException ignore) { }
if (epochTime == -1) {
this.uploadDate = new Date();
} else {
this.uploadDate = new Date(epochTime);
}
this.md5CheckSum = md5;
this.changeLog = changeLog.toString();
this.knownCaveats = knownCaveats.toString();
}
private String parseHtmlLine(final String line) {
return line
.replaceAll("<li>", " * ")
.replaceAll("<strong>", ChatColor.BOLD.toString())
.replaceAll("</strong>", ChatColor.RESET.toString())
.replaceAll("<em>", ChatColor.ITALIC.toString())
.replaceAll("</em>", ChatColor.RESET.toString())
//.replaceAll("<a\\s.*\">", "")
.replaceAll("<.+?>", "");
}
@Override
public String getPluginName() {
return pluginName;
}
@Override
public URL getDownloadLink() {
return downloadURL;
}
@Override
public String getVersion() {
return version;
}
@Override
public String getGameVersion() {
return gameVersion;
}
@Override
public String getFileName() {
return fileName;
}
@Override
public long getFileSize() {
return fileSize;
}
@Override
public VersionType getType() {
return versionType;
}
@Override
public String getMD5CheckSum() {
return md5CheckSum;
}
@Override
public int getDownloadCount() {
return downloadCount;
}
@Override
public Date getUploadedDate() {
return uploadDate;
}
@Override
public String getChangeLog() {
return changeLog;
}
@Override
public String getKnownCaveats() {
return knownCaveats;
}
}
| false | true | DefaultFileLink(final String link, final String pluginName) throws MalformedURLException, IOException {
this.pluginName = pluginName;
this.filePageURL = new URL(link);
final URLConnection urlConn = filePageURL.openConnection();
BufferedReader reader = null;
// Used for detecting elements
int sizeLine = -1;
int titleLine = -1;
int gameVersionLine = -1;
int versionTypeLine = -1;
int downloadCountLine = -1;
int uploadDateLine = -1;
int md5Line = -1;
int changeLogLine = -1;
int knownCaveatsLine = -1;
// Temp storage
String downloadLink = "";
String fileName = "";
String gameVersion = "";
long fileSize = -1;
String title = "";
String versionType = "";
String downloadCount = "";
String uploadDate = "";
String md5 = "";
final StringBuilder changeLog = new StringBuilder();
final StringBuilder knownCaveats = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
int counter = 0;
String line;
while((line = reader.readLine()) != null) {
counter++;
// Search for the download link
if(line.contains("<li class=\"user-action user-action-download\">")) {
// Get the raw link
downloadLink = line.split("<a href=\"")[1].split("\">Download</a>")[0];
String[] split = downloadLink.split("/");
fileName = split[split.length - 1].trim();
}
// Search for size
else if (line.contains("<dt>Size</dt>")) {
sizeLine = counter + 1;
} else if(counter == sizeLine) {
String size = line.replaceAll("<dd>", "").replaceAll("</dd>", "").trim();
int multiplier = size.contains("MiB") ? 1048576 : 1024;
size = size.replace(" KiB", "").replace(" MiB", "");
fileSize = (long)(Double.parseDouble(size) * multiplier);
}
// Search for version title
else if (line.contains("<header class=\"main-header\"><div class=\"line\">")) {
titleLine = counter + 2;
} else if (counter == titleLine) {
title = line.trim();
}
// Search for game version
else if (line.contains("<dt>Game version</dt>")) {
gameVersionLine = counter + 1;
} else if (counter == gameVersionLine) {
gameVersion = line.replaceAll("<dd>.*<li>", "").replaceAll("</li>.*</dd>", "").trim();
}
// Search for version Type
else if (line.contains("<dt>Type</dt>")) {
versionTypeLine = counter + 1;
} else if (counter == versionTypeLine) {
versionType = line.replaceAll("<dd>.*-b\">", "").replaceAll("</span></dd>", "").trim();
}
// Search for download count
else if (line.contains("<dt>Downloads</dt>")) {
downloadCountLine = counter + 1;
} else if (counter == downloadCountLine) {
downloadCount = line.replaceAll("<dd>.*e=\"", "").replaceAll("\">.*</dd>", "").trim();
}
// Search for download count
else if (line.contains("<dt>Uploaded on</dt>")) {
uploadDateLine = counter + 1;
} else if (counter == uploadDateLine) {
uploadDate = line.replaceAll("<dd>.*epoch=\"", "").replaceAll("\"\\sdata.*</dd>", "").trim();
}
// Search for md5
else if (line.contains("<dt>MD5</dt>")) {
md5Line = counter + 1;
} else if (counter == md5Line) {
md5 = line.replaceAll("<dd>", "").replaceAll("</dd>", "").trim();
}
// Search for change log
else if (line.contains("<div class=\"content-box\"><div class=\"content-box-inner\"><h3>Change log</h3>")) {
changeLog.append(parseHtmlLine(line.replace("<div class=\"content-box\"><div class=\"content-box-inner\"><h3>Change log</h3>", ""))).append(LS);
changeLogLine = counter + 1;
} else if (counter == changeLogLine) {
if (line.contains("</div></div>")) {
continue;
}
changeLog.append(parseHtmlLine(line)).append(LS);
changeLogLine++;
}
// Search for known caveats
else if (line.contains("<div class=\"content-box\"><div class=\"content-box-inner\"><h3>Known caveats</h3>")) {
knownCaveats.append(parseHtmlLine(line.replace("<div class=\"content-box\"><div class=\"content-box-inner\"><h3>Known caveats</h3>", ""))).append(LS);
knownCaveatsLine = counter + 1;
} else if (counter == knownCaveatsLine) {
if (line.contains("</div></div>")) {
continue;
}
knownCaveats.append(parseHtmlLine(line)).append(LS);
knownCaveatsLine++;
}
}
} finally {
if (reader != null) {
reader.close();
}
}
if (downloadLink == null) {
// TODO make this better
throw new IOException();
}
this.downloadURL = new URL(downloadLink);
this.fileSize = fileSize;
this.version = title;
this.fileName = fileName;
this.gameVersion = gameVersion;
VersionType tempType = VersionType.UNKNOWN;
try {
tempType = VersionType.valueOf(versionType.toUpperCase());
} catch (IllegalArgumentException ignore) { }
this.versionType = tempType;
int downloads = -1;
try {
downloads = Integer.parseInt(downloadCount);
} catch (NumberFormatException ignore) { }
this.downloadCount = downloads;
long epochTime = -1;
try {
epochTime = Long.parseLong(uploadDate);
} catch (NumberFormatException ignore) { }
if (epochTime == -1) {
this.uploadDate = new Date();
} else {
this.uploadDate = new Date(epochTime);
}
this.md5CheckSum = md5;
this.changeLog = changeLog.toString();
this.knownCaveats = knownCaveats.toString();
}
| DefaultFileLink(final String link, final String pluginName) throws MalformedURLException, IOException {
this.pluginName = pluginName;
this.filePageURL = new URL(link);
final URLConnection urlConn = filePageURL.openConnection();
BufferedReader reader = null;
// Used for detecting elements
int sizeLine = -1;
int titleLine = -1;
int gameVersionLine = -1;
int versionTypeLine = -1;
int downloadCountLine = -1;
int uploadDateLine = -1;
int md5Line = -1;
int changeLogLine = -1;
int knownCaveatsLine = -1;
// Temp storage
String downloadLink = "";
String fileName = "";
String gameVersion = "";
long fileSize = -1;
String title = "";
String versionType = "";
String downloadCount = "";
String uploadDate = "";
String md5 = "";
final StringBuilder changeLog = new StringBuilder();
final StringBuilder knownCaveats = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
int counter = 0;
String line;
while((line = reader.readLine()) != null) {
counter++;
// Search for the download link
if(line.contains("<li class=\"user-action user-action-download\">")) {
// Get the raw link
downloadLink = line.split("<a href=\"")[1].split("\">Download</a>")[0];
String[] split = downloadLink.split("/");
fileName = split[split.length - 1].trim();
}
// Search for size
else if (line.contains("<dt>Size</dt>")) {
sizeLine = counter + 1;
} else if(counter == sizeLine) {
String size = line.replaceAll("<dd>", "").replaceAll("</dd>", "").trim();
int multiplier = size.contains("MiB") ? 1048576 : 1024;
size = size.replace(" KiB", "").replace(" MiB", "");
fileSize = (long)(Double.parseDouble(size) * multiplier);
}
// Search for version title
else if (line.contains("<header class=\"main-header\"><div class=\"line\">")) {
titleLine = counter + 2;
} else if (counter == titleLine) {
title = line.trim();
}
// Search for game version
else if (line.contains("<dt>Game version</dt>")) {
gameVersionLine = counter + 1;
} else if (counter == gameVersionLine) {
gameVersion = line.replaceAll("<dd>.*?<li>", "").replaceAll("</li>.*</dd>", "").trim();
}
// Search for version Type
else if (line.contains("<dt>Type</dt>")) {
versionTypeLine = counter + 1;
} else if (counter == versionTypeLine) {
versionType = line.replaceAll("<dd>.*?\">", "").replaceAll("</span></dd>", "").trim();
}
// Search for download count
else if (line.contains("<dt>Downloads</dt>")) {
downloadCountLine = counter + 1;
} else if (counter == downloadCountLine) {
downloadCount = line.replaceAll("<dd>.*?e=\"", "").replaceAll("\">.*</dd>", "").trim();
}
// Search for download count
else if (line.contains("<dt>Uploaded on</dt>")) {
uploadDateLine = counter + 1;
} else if (counter == uploadDateLine) {
uploadDate = line.replaceAll("<dd>.*?epoch=\"", "").replaceAll("\"\\sdata.*?</dd>", "").trim();
}
// Search for md5
else if (line.contains("<dt>MD5</dt>")) {
md5Line = counter + 1;
} else if (counter == md5Line) {
md5 = line.replaceAll("<dd>", "").replaceAll("</dd>", "").trim();
}
// Search for change log
else if (line.contains("<div class=\"content-box\"><div class=\"content-box-inner\"><h3>Change log</h3>")) {
changeLog.append(parseHtmlLine(line.replace("<div class=\"content-box\"><div class=\"content-box-inner\"><h3>Change log</h3>", ""))).append(LS);
changeLogLine = counter + 1;
} else if (counter == changeLogLine) {
if (line.contains("</div></div>")) {
continue;
}
changeLog.append(parseHtmlLine(line)).append(LS);
changeLogLine++;
}
// Search for known caveats
else if (line.contains("<div class=\"content-box\"><div class=\"content-box-inner\"><h3>Known caveats</h3>")) {
knownCaveats.append(parseHtmlLine(line.replace("<div class=\"content-box\"><div class=\"content-box-inner\"><h3>Known caveats</h3>", ""))).append(LS);
knownCaveatsLine = counter + 1;
} else if (counter == knownCaveatsLine) {
if (line.contains("</div></div>")) {
continue;
}
knownCaveats.append(parseHtmlLine(line)).append(LS);
knownCaveatsLine++;
}
}
} finally {
if (reader != null) {
reader.close();
}
}
if (downloadLink == null) {
// TODO make this better
throw new IOException();
}
this.downloadURL = new URL(downloadLink);
this.fileSize = fileSize;
this.version = title;
this.fileName = fileName;
this.gameVersion = gameVersion;
VersionType tempType = VersionType.UNKNOWN;
try {
tempType = VersionType.valueOf(versionType.toUpperCase());
} catch (IllegalArgumentException ignore) { }
this.versionType = tempType;
int downloads = -1;
try {
downloads = Integer.parseInt(downloadCount);
} catch (NumberFormatException ignore) { }
this.downloadCount = downloads;
long epochTime = -1;
try {
epochTime = Long.parseLong(uploadDate);
} catch (NumberFormatException ignore) { }
if (epochTime == -1) {
this.uploadDate = new Date();
} else {
this.uploadDate = new Date(epochTime);
}
this.md5CheckSum = md5;
this.changeLog = changeLog.toString();
this.knownCaveats = knownCaveats.toString();
}
|
diff --git a/bundles/org.eclipse.core.jobs/src/org/eclipse/core/internal/jobs/WorkerPool.java b/bundles/org.eclipse.core.jobs/src/org/eclipse/core/internal/jobs/WorkerPool.java
index dd5b117c7..95d42cb24 100644
--- a/bundles/org.eclipse.core.jobs/src/org/eclipse/core/internal/jobs/WorkerPool.java
+++ b/bundles/org.eclipse.core.jobs/src/org/eclipse/core/internal/jobs/WorkerPool.java
@@ -1,247 +1,250 @@
/*******************************************************************************
* Copyright (c) 2003, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
*******************************************************************************/
package org.eclipse.core.internal.jobs;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.jobs.Job;
/**
* Maintains a pool of worker threads. Threads are constructed lazily as
* required, and are eventually discarded if not in use for awhile. This class
* maintains the thread creation/destruction policies for the job manager.
*
* Implementation note: all the data structures of this class are protected
* by the instance's object monitor. To avoid deadlock with third party code,
* this lock is never held when calling methods outside this class that may in
* turn use locks.
*/
class WorkerPool {
/**
* Threads not used by their best before timestamp are destroyed.
*/
private static final int BEST_BEFORE = 60000;
/**
* There will always be at least MIN_THREADS workers in the pool.
*/
private static final int MIN_THREADS = 1;
/**
* Use the busy thread count to avoid starting new threads when a living
* thread is just doing house cleaning (notifying listeners, etc).
*/
private int busyThreads = 0;
/**
* The default context class loader to use when creating worker threads.
*/
protected final ClassLoader defaultContextLoader;
/**
* Records whether new worker threads should be daemon threads.
*/
private boolean isDaemon = false;
private JobManager manager;
/**
* The number of workers in the threads array
*/
private int numThreads = 0;
/**
* The number of threads that are currently sleeping
*/
private int sleepingThreads = 0;
/**
* The living set of workers in this pool.
*/
private Worker[] threads = new Worker[10];
protected WorkerPool(JobManager manager) {
this.manager = manager;
this.defaultContextLoader = Thread.currentThread().getContextClassLoader();
}
/**
* Adds a worker to the list of workers.
*/
private synchronized void add(Worker worker) {
int size = threads.length;
if (numThreads + 1 > size) {
Worker[] newThreads = new Worker[2 * size];
System.arraycopy(threads, 0, newThreads, 0, size);
threads = newThreads;
}
threads[numThreads++] = worker;
}
private synchronized void decrementBusyThreads() {
//impossible to have less than zero busy threads
if (--busyThreads < 0) {
if (JobManager.DEBUG)
Assert.isTrue(false, Integer.toString(busyThreads));
busyThreads = 0;
}
}
/**
* Signals the end of a job. Note that this method can be called under
* OutOfMemoryError conditions and thus must be paranoid about allocating objects.
*/
protected void endJob(InternalJob job, IStatus result) {
decrementBusyThreads();
//need to end rule in graph before ending job so that 2 threads
//do not become the owners of the same rule in the graph
if ((job.getRule() != null) && !(job instanceof ThreadJob)) {
//remove any locks this thread may be owning on that rule
manager.getLockManager().removeLockCompletely(Thread.currentThread(), job.getRule());
}
manager.endJob(job, result, true);
//ensure this thread no longer owns any scheduling rules
manager.implicitJobs.endJob(job);
}
/**
* Signals the death of a worker thread. Note that this method can be called under
* OutOfMemoryError conditions and thus must be paranoid about allocating objects.
*/
protected synchronized void endWorker(Worker worker) {
if (remove(worker) && JobManager.DEBUG)
JobManager.debug("worker removed from pool: " + worker); //$NON-NLS-1$
}
private synchronized void incrementBusyThreads() {
//impossible to have more busy threads than there are threads
if (++busyThreads > numThreads) {
if (JobManager.DEBUG)
Assert.isTrue(false, Integer.toString(busyThreads) + ',' + numThreads);
busyThreads = numThreads;
}
}
/**
* Notification that a job has been added to the queue. Wake a worker,
* creating a new worker if necessary. The provided job may be null.
*/
protected synchronized void jobQueued() {
//if there is a sleeping thread, wake it up
if (sleepingThreads > 0) {
notify();
return;
}
//create a thread if all threads are busy
if (busyThreads >= numThreads) {
Worker worker = new Worker(this);
worker.setDaemon(isDaemon);
add(worker);
if (JobManager.DEBUG)
JobManager.debug("worker added to pool: " + worker); //$NON-NLS-1$
worker.start();
return;
}
}
/**
* Remove a worker thread from our list.
* @return true if a worker was removed, and false otherwise.
*/
private synchronized boolean remove(Worker worker) {
for (int i = 0; i < threads.length; i++) {
if (threads[i] == worker) {
System.arraycopy(threads, i + 1, threads, i, numThreads - i - 1);
threads[--numThreads] = null;
return true;
}
}
return false;
}
/**
* Sets whether threads created in the worker pool should be daemon threads.
*/
void setDaemon(boolean value) {
this.isDaemon = value;
}
protected synchronized void shutdown() {
notifyAll();
}
/**
* Sleep for the given duration or until woken.
*/
private synchronized void sleep(long duration) {
sleepingThreads++;
busyThreads--;
if (JobManager.DEBUG)
JobManager.debug("worker sleeping for: " + duration + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
try {
wait(duration);
} catch (InterruptedException e) {
if (JobManager.DEBUG)
JobManager.debug("worker interrupted while waiting... :-|"); //$NON-NLS-1$
} finally {
sleepingThreads--;
busyThreads++;
}
}
/**
* Returns a new job to run. Returns null if the thread should die.
*/
protected InternalJob startJob(Worker worker) {
//if we're above capacity, kill the thread
synchronized (this) {
if (!manager.isActive()) {
//must remove the worker immediately to prevent all threads from expiring
endWorker(worker);
return null;
}
//set the thread to be busy now in case of reentrant scheduling
incrementBusyThreads();
}
Job job = null;
try {
job = manager.startJob();
//spin until a job is found or until we have been idle for too long
long idleStart = System.currentTimeMillis();
while (manager.isActive() && job == null) {
long hint = manager.sleepHint();
if (hint > 0)
sleep(Math.min(hint, BEST_BEFORE));
job = manager.startJob();
//if we were already idle, and there are still no new jobs, then
// the thread can expire
synchronized (this) {
if (job == null && (System.currentTimeMillis() - idleStart > BEST_BEFORE) && (numThreads - busyThreads) > MIN_THREADS) {
//must remove the worker immediately to prevent all threads from expiring
endWorker(worker);
return null;
}
}
+ //if we didn't sleep but there was no job available, make sure we sleep to avoid a tight loop (bug 260724)
+ if (hint <= 0 && job == null)
+ sleep(50);
}
if (job != null) {
//if this job has a rule, then we are essentially acquiring a lock
if ((job.getRule() != null) && !(job instanceof ThreadJob)) {
//don't need to re-acquire locks because it was not recorded in the graph
//that this thread waited to get this rule
manager.getLockManager().addLockThread(Thread.currentThread(), job.getRule());
}
//see if we need to wake another worker
if (manager.sleepHint() <= 0)
jobQueued();
}
} finally {
//decrement busy thread count if we're not running a job
if (job == null)
decrementBusyThreads();
}
return job;
}
}
| true | true | protected InternalJob startJob(Worker worker) {
//if we're above capacity, kill the thread
synchronized (this) {
if (!manager.isActive()) {
//must remove the worker immediately to prevent all threads from expiring
endWorker(worker);
return null;
}
//set the thread to be busy now in case of reentrant scheduling
incrementBusyThreads();
}
Job job = null;
try {
job = manager.startJob();
//spin until a job is found or until we have been idle for too long
long idleStart = System.currentTimeMillis();
while (manager.isActive() && job == null) {
long hint = manager.sleepHint();
if (hint > 0)
sleep(Math.min(hint, BEST_BEFORE));
job = manager.startJob();
//if we were already idle, and there are still no new jobs, then
// the thread can expire
synchronized (this) {
if (job == null && (System.currentTimeMillis() - idleStart > BEST_BEFORE) && (numThreads - busyThreads) > MIN_THREADS) {
//must remove the worker immediately to prevent all threads from expiring
endWorker(worker);
return null;
}
}
}
if (job != null) {
//if this job has a rule, then we are essentially acquiring a lock
if ((job.getRule() != null) && !(job instanceof ThreadJob)) {
//don't need to re-acquire locks because it was not recorded in the graph
//that this thread waited to get this rule
manager.getLockManager().addLockThread(Thread.currentThread(), job.getRule());
}
//see if we need to wake another worker
if (manager.sleepHint() <= 0)
jobQueued();
}
} finally {
//decrement busy thread count if we're not running a job
if (job == null)
decrementBusyThreads();
}
return job;
}
| protected InternalJob startJob(Worker worker) {
//if we're above capacity, kill the thread
synchronized (this) {
if (!manager.isActive()) {
//must remove the worker immediately to prevent all threads from expiring
endWorker(worker);
return null;
}
//set the thread to be busy now in case of reentrant scheduling
incrementBusyThreads();
}
Job job = null;
try {
job = manager.startJob();
//spin until a job is found or until we have been idle for too long
long idleStart = System.currentTimeMillis();
while (manager.isActive() && job == null) {
long hint = manager.sleepHint();
if (hint > 0)
sleep(Math.min(hint, BEST_BEFORE));
job = manager.startJob();
//if we were already idle, and there are still no new jobs, then
// the thread can expire
synchronized (this) {
if (job == null && (System.currentTimeMillis() - idleStart > BEST_BEFORE) && (numThreads - busyThreads) > MIN_THREADS) {
//must remove the worker immediately to prevent all threads from expiring
endWorker(worker);
return null;
}
}
//if we didn't sleep but there was no job available, make sure we sleep to avoid a tight loop (bug 260724)
if (hint <= 0 && job == null)
sleep(50);
}
if (job != null) {
//if this job has a rule, then we are essentially acquiring a lock
if ((job.getRule() != null) && !(job instanceof ThreadJob)) {
//don't need to re-acquire locks because it was not recorded in the graph
//that this thread waited to get this rule
manager.getLockManager().addLockThread(Thread.currentThread(), job.getRule());
}
//see if we need to wake another worker
if (manager.sleepHint() <= 0)
jobQueued();
}
} finally {
//decrement busy thread count if we're not running a job
if (job == null)
decrementBusyThreads();
}
return job;
}
|
diff --git a/NewsBlurPlus/src/com/asafge/newsblurplus/NewsBlurPlus.java b/NewsBlurPlus/src/com/asafge/newsblurplus/NewsBlurPlus.java
index a78997c..fed8492 100644
--- a/NewsBlurPlus/src/com/asafge/newsblurplus/NewsBlurPlus.java
+++ b/NewsBlurPlus/src/com/asafge/newsblurplus/NewsBlurPlus.java
@@ -1,371 +1,373 @@
package com.asafge.newsblurplus;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.os.RemoteException;
import android.util.Log;
import com.noinnion.android.reader.api.ReaderException;
import com.noinnion.android.reader.api.ReaderExtension;
import com.noinnion.android.reader.api.internal.IItemIdListHandler;
import com.noinnion.android.reader.api.internal.IItemListHandler;
import com.noinnion.android.reader.api.internal.ISubscriptionListHandler;
import com.noinnion.android.reader.api.internal.ITagListHandler;
import com.noinnion.android.reader.api.provider.IItem;
import com.noinnion.android.reader.api.provider.ISubscription;
public class NewsBlurPlus extends ReaderExtension {
private Context c;
/*
* Constructor
*/
@Override
public void onCreate() {
super.onCreate();
c = getApplicationContext();
};
/*
* Main sync function to get folders, feeds, and counts.
* 1. Get the folders (tags) and their feeds.
* 2. Ask NewsBlur to Refresh feed counts + save to feeds.
* 3. Send handler the tags and feeds.
*/
@Override
public void handleReaderList(ITagListHandler tagHandler, ISubscriptionListHandler subHandler, long syncTime) throws ReaderException {
SubsStruct.InstanceRefresh(c);
APIHelper.updateFeedCounts(c, SubsStruct.Instance(c).Subs);
if (SubsStruct.Instance(c).Subs.size() == 0)
throw new ReaderException("No subscriptions available");
try {
subHandler.subscriptions(SubsStruct.Instance(c).Subs);
tagHandler.tags(SubsStruct.Instance(c).Tags);
}
catch (RemoteException e) {
throw new ReaderException("Sub/tag handler error", e);
}
}
/*
* Get a list of unread story IDS (URLs), UI will mark all other as read.
* This really speeds up the sync process.
*/
@Override
public void handleItemIdList(IItemIdListHandler handler, long syncTime) throws ReaderException {
try {
int limit = handler.limit();
String uid = handler.stream();
if (uid.startsWith(ReaderExtension.STATE_STARRED))
handler.items(APIHelper.getStarredHashes(c, limit, null));
else if (uid.startsWith(ReaderExtension.STATE_READING_LIST)) {
List<String> hashes = APIHelper.getUnreadHashes(c, limit, null, null);
if (SubsStruct.Instance(c).IsPremium)
hashes = APIHelper.filterLowIntelligence(hashes, c);
handler.items(hashes);
}
else {
Log.e("NewsBlur+ Debug", "Unknown reading state: " + uid);
throw new ReaderException("Unknown reading state");
}
}
catch (RemoteException e) {
throw new ReaderException("ItemID handler error", e);
}
}
/*
* Handle a single item list (a feed or a folder).
* This functions calls the parseItemList function.
*/
@Override
public void handleItemList(IItemListHandler handler, long syncTime) throws ReaderException {
try {
String uid = handler.stream();
+ String url = APICall.API_URL_RIVER;
int limit = handler.limit();
int chunk = (SubsStruct.Instance(c).IsPremium ? 100 : 5 );
List<String> hashes;
// Load the seen hashes from prefs
if (uid.startsWith(ReaderExtension.STATE_READING_LIST) && (handler.startTime() <= 0))
Prefs.setHashesList(c, "");
RotateQueue<String> seenHashes = new RotateQueue<String>(1000, Prefs.getHashesList(c));
if (uid.startsWith(ReaderExtension.STATE_STARRED)) {
hashes = APIHelper.getStarredHashes(c, limit, seenHashes);
+ url = APICall.API_URL_STARRED_STORIES;
}
else if (uid.startsWith("FEED:")) {
hashes = APIHelper.getUnreadHashes(c, limit, Arrays.asList(APIHelper.getFeedIdFromFeedUrl(uid)), seenHashes);
}
else if (uid.startsWith(ReaderExtension.STATE_READING_LIST)) {
List<String> unread_hashes = APIHelper.getUnreadHashes(c, limit, null, seenHashes);
hashes = new ArrayList<String>();
for (String h : unread_hashes)
if (!handler.excludedStreams().contains(APIHelper.getFeedUrlFromFeedId(h)))
hashes.add(h);
}
else {
Log.e("NewsBlur+ Debug", "Unknown reading state: " + uid);
throw new ReaderException("Unknown reading state");
}
Log.w("NewsBlur+ debug", "Hashes: " + Arrays.toString(hashes.toArray()));
Log.w("NewsBlur+ debug", "chunk: " + String.valueOf(chunk));
for (int start=0; start < hashes.size(); start += chunk) {
- APICall ac = new APICall(APICall.API_URL_RIVER, c);
+ APICall ac = new APICall(url, c);
int end = (start+chunk < hashes.size()) ? start + chunk : hashes.size();
ac.addGetParams("h", hashes.subList(start, end));
ac.sync();
parseItemList(ac.Json, handler, seenHashes);
}
// Save the seen hashes as a serialized String
Prefs.setHashesList(c, seenHashes.toString());
}
catch (RemoteException e) {
throw new ReaderException("ItemList handler error", e);
}
}
/*
* Parse an array of items that are in the NewsBlur JSON format.
*/
public void parseItemList(JSONObject json, IItemListHandler handler, RotateQueue<String> seenHashes) throws ReaderException {
try {
int length = 0;
List<IItem> items = new ArrayList<IItem>();
JSONArray arr = json.getJSONArray("stories");
for (int i=0; i<arr.length(); i++) {
JSONObject story = arr.getJSONObject(i);
IItem item = new IItem();
item.subUid = APIHelper.getFeedUrlFromFeedId(story.getString("story_feed_id"));
item.title = story.getString("story_title");
item.link = story.getString("story_permalink");
item.uid = story.getString("story_hash");
item.author = story.getString("story_authors");
item.updatedTime = story.getLong("story_timestamp");
item.publishedTime = story.getLong("story_timestamp");
item.read = (story.getInt("read_status") == 1) || (APIHelper.getIntelligence(story) < 0);
item.content = story.getString("story_content");
item.starred = (story.has("starred") && story.getString("starred") == "true");
if (item.starred)
item.addCategory(StarredTag.get().uid);
items.add(item);
seenHashes.AddElement(item.uid);
length += item.getLength();
if (items.size() % 200 == 0 || length > 300000) {
handler.items(items, 0);
items.clear();
length = 0;
}
}
handler.items(items, 0);
}
catch (JSONException e) {
Log.e("NewsBlur+ Debug", "JSONExceotion: " + e.getMessage());
Log.e("NewsBlur+ Debug", "JSON: " + json.toString());
throw new ReaderException("ParseItemList parse error", e);
}
catch (RemoteException e) {
throw new ReaderException("SingleItem handler error", e);
}
}
/*
* Main function for marking stories (and their feeds) as read/unread.
*/
private boolean markAs(boolean read, String[] itemUids, String[] subUIds) throws ReaderException {
APICall ac;
if (itemUids == null && subUIds == null) {
ac = new APICall(APICall.API_URL_MARK_ALL_AS_READ, c);
}
else {
if (itemUids == null) {
ac = new APICall(APICall.API_URL_MARK_FEED_AS_READ, c);
for (String sub : subUIds)
ac.addGetParam("feed_id", sub);
}
else {
if (read) {
ac = new APICall(APICall.API_URL_MARK_STORY_AS_READ, c);
ac.addGetParams("story_hash", Arrays.asList(itemUids));
}
else {
ac = new APICall(APICall.API_URL_MARK_STORY_AS_UNREAD, c);
for (int i=0; i<itemUids.length; i++) {
ac.addPostParam("story_id", itemUids[i]);
ac.addPostParam("feed_id", APIHelper.getFeedIdFromFeedUrl(subUIds[i]));
}
}
}
}
return ac.syncGetResultOk();
}
/*
* Mark a list of stories (and their feeds) as read
*/
@Override
public boolean markAsRead(String[] itemUids, String[] subUIds) throws ReaderException {
return markAs(true, itemUids, subUIds);
}
/*
* Mark a list of stories (and their feeds) as unread
*/
@Override
public boolean markAsUnread(String[] itemUids, String[] subUids, boolean keepUnread) throws ReaderException {
return markAs(false, itemUids, subUids);
}
/*
* Mark all stories on all feeds as read. Iterate all feeds in order to avoid marking excluded feeds as read.
* Note: s = subscription (feed), t = tag
*/
@Override
public boolean markAllAsRead(String s, String t, String[] excluded_subs, long syncTime) throws ReaderException {
if (s != null && s.startsWith("FEED:")) {
String[] feed = { APIHelper.getFeedIdFromFeedUrl(s) };
return this.markAs(true, null, feed);
}
else {
List<String> excluded = (excluded_subs != null) ? Arrays.asList(excluded_subs) : new ArrayList<String>();
List<String> subUIDs = new ArrayList<String>();
if (s == null && t == null) {
for (ISubscription sub : SubsStruct.Instance(c).Subs)
if (!excluded.contains(sub.uid))
subUIDs.add(sub.uid);
return subUIDs.isEmpty() ? false : this.markAs(true, null, subUIDs.toArray(new String[0]));
}
else if (s.startsWith("FOL:")) {
for (ISubscription sub : SubsStruct.Instance(c).Subs)
if (!excluded.contains(sub.uid) && sub.getCategories().contains(s))
subUIDs.add(APIHelper.getFeedIdFromFeedUrl(sub.uid));
return subUIDs.isEmpty() ? false : this.markAs(true, null, subUIDs.toArray(new String[0]));
}
return false;
}
}
/*
* Edit an item's tag - currently supports only starring/unstarring items
*/
@Override
public boolean editItemTag(String[] itemUids, String[] subUids, String[] addTags, String[] removeTags) throws ReaderException {
for (int i=0; i<itemUids.length; i++) {
String url;
if ((addTags != null) && addTags[i].startsWith(StarredTag.get().uid)) {
url = APICall.API_URL_MARK_STORY_AS_STARRED;
}
else if ((removeTags != null) && removeTags[i].startsWith(StarredTag.get().uid)) {
url = APICall.API_URL_MARK_STORY_AS_UNSTARRED;
}
else {
throw new ReaderException("Unsupported tag type");
}
APICall ac = new APICall(url, c);
ac.addPostParam("story_id", itemUids[i]);
ac.addPostParam("feed_id", APIHelper.getFeedIdFromFeedUrl(subUids[i]));
if (!ac.syncGetResultOk())
return false;
}
return true;
}
/*
* Rename a top level folder both in News+ and in NewsBlur server
*/
@Override
public boolean renameTag(String tagUid, String oldLabel, String newLabel) throws ReaderException {
if (!tagUid.startsWith("FOL:"))
return false;
else {
APICall ac = new APICall(APICall.API_URL_FOLDER_RENAME, c);
ac.addPostParam("folder_to_rename", oldLabel);
ac.addPostParam("new_folder_name", newLabel);
ac.addPostParam("in_folder", "");
return ac.syncGetResultOk();
}
}
/*
* Delete a top level folder both in News+ and in NewsBlur server
* This just removes the folder, not the feeds in it
*/
@Override
public boolean disableTag(String tagUid, String label) throws ReaderException {
if (tagUid.startsWith("STAR:"))
return false;
else {
for (ISubscription sub : SubsStruct.Instance(c).Subs)
if ((sub.getCategories().contains(label) && !APIHelper.moveFeedToFolder(c, APIHelper.getFeedIdFromFeedUrl(sub.uid), label, "")))
return false;
APICall ac = new APICall(APICall.API_URL_FOLDER_DEL, c);
ac.addPostParam("folder_to_delete", label);
return ac.syncGetResultOk();
}
}
/*
* Main function for editing subscriptions - add/delete/rename/change-folder
*/
@Override
public boolean editSubscription(String uid, String title, String feed_url, String[] tags, int action, long syncTime) throws ReaderException {
switch (action) {
// Feed - add/delete/rename
case ReaderExtension.SUBSCRIPTION_ACTION_SUBCRIBE: {
APICall ac = new APICall(APICall.API_URL_FEED_ADD, c);
ac.addPostParam("url", feed_url);
return ac.syncGetResultOk() && SubsStruct.Instance(c).Refresh();
}
case ReaderExtension.SUBSCRIPTION_ACTION_UNSUBCRIBE: {
String feedID = APIHelper.getFeedIdFromFeedUrl(uid);
APIHelper.clearUnsubscribedHashes(c, feedID);
APICall ac = new APICall(APICall.API_URL_FEED_DEL, c);
ac.addPostParam("feed_id", feedID);
return ac.syncGetResultOk() && SubsStruct.Instance(c).Refresh();
}
case ReaderExtension.SUBSCRIPTION_ACTION_EDIT: {
APICall ac = new APICall(APICall.API_URL_FEED_RENAME, c);
ac.addPostParam("feed_id", APIHelper.getFeedIdFromFeedUrl(uid));
ac.addPostParam("feed_title", title);
return ac.syncGetResultOk();
}
// Feed's parent folder - new_folder/add_to_folder/delete_from_folder
case ReaderExtension.SUBSCRIPTION_ACTION_NEW_LABEL: {
APICall ac = new APICall(APICall.API_URL_FOLDER_ADD, c);
String newTag = tags[0].replace("FOL:", "");
ac.addPostParam("folder", newTag);
return ac.syncGetResultOk();
}
case ReaderExtension.SUBSCRIPTION_ACTION_ADD_LABEL: {
String newTag = tags[0].replace("FOL:", "");
return APIHelper.moveFeedToFolder(c, APIHelper.getFeedIdFromFeedUrl(uid), "", newTag);
}
case ReaderExtension.SUBSCRIPTION_ACTION_REMOVE_LABEL: {
String newTag = tags[0].replace("FOL:", "");
return APIHelper.moveFeedToFolder(c, APIHelper.getFeedIdFromFeedUrl(uid), newTag, "");
}
default: {
Log.e("NewsBlur+ Debug", "Unknown action: " + String.valueOf(action));
return false;
}
}
}
}
| false | true | public void handleItemList(IItemListHandler handler, long syncTime) throws ReaderException {
try {
String uid = handler.stream();
int limit = handler.limit();
int chunk = (SubsStruct.Instance(c).IsPremium ? 100 : 5 );
List<String> hashes;
// Load the seen hashes from prefs
if (uid.startsWith(ReaderExtension.STATE_READING_LIST) && (handler.startTime() <= 0))
Prefs.setHashesList(c, "");
RotateQueue<String> seenHashes = new RotateQueue<String>(1000, Prefs.getHashesList(c));
if (uid.startsWith(ReaderExtension.STATE_STARRED)) {
hashes = APIHelper.getStarredHashes(c, limit, seenHashes);
}
else if (uid.startsWith("FEED:")) {
hashes = APIHelper.getUnreadHashes(c, limit, Arrays.asList(APIHelper.getFeedIdFromFeedUrl(uid)), seenHashes);
}
else if (uid.startsWith(ReaderExtension.STATE_READING_LIST)) {
List<String> unread_hashes = APIHelper.getUnreadHashes(c, limit, null, seenHashes);
hashes = new ArrayList<String>();
for (String h : unread_hashes)
if (!handler.excludedStreams().contains(APIHelper.getFeedUrlFromFeedId(h)))
hashes.add(h);
}
else {
Log.e("NewsBlur+ Debug", "Unknown reading state: " + uid);
throw new ReaderException("Unknown reading state");
}
Log.w("NewsBlur+ debug", "Hashes: " + Arrays.toString(hashes.toArray()));
Log.w("NewsBlur+ debug", "chunk: " + String.valueOf(chunk));
for (int start=0; start < hashes.size(); start += chunk) {
APICall ac = new APICall(APICall.API_URL_RIVER, c);
int end = (start+chunk < hashes.size()) ? start + chunk : hashes.size();
ac.addGetParams("h", hashes.subList(start, end));
ac.sync();
parseItemList(ac.Json, handler, seenHashes);
}
// Save the seen hashes as a serialized String
Prefs.setHashesList(c, seenHashes.toString());
}
catch (RemoteException e) {
throw new ReaderException("ItemList handler error", e);
}
}
| public void handleItemList(IItemListHandler handler, long syncTime) throws ReaderException {
try {
String uid = handler.stream();
String url = APICall.API_URL_RIVER;
int limit = handler.limit();
int chunk = (SubsStruct.Instance(c).IsPremium ? 100 : 5 );
List<String> hashes;
// Load the seen hashes from prefs
if (uid.startsWith(ReaderExtension.STATE_READING_LIST) && (handler.startTime() <= 0))
Prefs.setHashesList(c, "");
RotateQueue<String> seenHashes = new RotateQueue<String>(1000, Prefs.getHashesList(c));
if (uid.startsWith(ReaderExtension.STATE_STARRED)) {
hashes = APIHelper.getStarredHashes(c, limit, seenHashes);
url = APICall.API_URL_STARRED_STORIES;
}
else if (uid.startsWith("FEED:")) {
hashes = APIHelper.getUnreadHashes(c, limit, Arrays.asList(APIHelper.getFeedIdFromFeedUrl(uid)), seenHashes);
}
else if (uid.startsWith(ReaderExtension.STATE_READING_LIST)) {
List<String> unread_hashes = APIHelper.getUnreadHashes(c, limit, null, seenHashes);
hashes = new ArrayList<String>();
for (String h : unread_hashes)
if (!handler.excludedStreams().contains(APIHelper.getFeedUrlFromFeedId(h)))
hashes.add(h);
}
else {
Log.e("NewsBlur+ Debug", "Unknown reading state: " + uid);
throw new ReaderException("Unknown reading state");
}
Log.w("NewsBlur+ debug", "Hashes: " + Arrays.toString(hashes.toArray()));
Log.w("NewsBlur+ debug", "chunk: " + String.valueOf(chunk));
for (int start=0; start < hashes.size(); start += chunk) {
APICall ac = new APICall(url, c);
int end = (start+chunk < hashes.size()) ? start + chunk : hashes.size();
ac.addGetParams("h", hashes.subList(start, end));
ac.sync();
parseItemList(ac.Json, handler, seenHashes);
}
// Save the seen hashes as a serialized String
Prefs.setHashesList(c, seenHashes.toString());
}
catch (RemoteException e) {
throw new ReaderException("ItemList handler error", e);
}
}
|
diff --git a/proj/TransactionLayer.java b/proj/TransactionLayer.java
index 89ed878..6c6cfa1 100644
--- a/proj/TransactionLayer.java
+++ b/proj/TransactionLayer.java
@@ -1,479 +1,479 @@
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import edu.washington.cs.cse490h.lib.Utility;
public class TransactionLayer {
public final static int MASTER_NODE = 0;
private DistNode n;
private ReliableInOrderMsgLayer RIOLayer;
private Map<String, File> cache;
private int lastTXNnum;
private Transaction txn;
/**
* key = addr of node uploading its commit
* value = list of commands received so far of the commit
*/
private Map<Integer, List<Command>> commitQueue;
/**
* key = addr of node trying to commit
* value = commit status
*/
private Map<Integer, Commit> waitingQueue;
public TransactionLayer(RIONode n, ReliableInOrderMsgLayer RIOLayer){
this.cache = new HashMap<String, File>();
this.n = (DistNode)n;
this.RIOLayer = RIOLayer;
this.lastTXNnum = n.addr;
this.commitQueue = this.n.addr == MASTER_NODE ? new HashMap<Integer, List<Command>>() : null;
this.waitingQueue = new HashMap<Integer, Commit>();
}
public void send(int server, int protocol, byte[] payload) {
TXNPacket pkt = new TXNPacket(protocol, payload);
this.RIOLayer.sendRIO(server, Protocol.TXN, pkt.pack());
}
public void onReceive(int from, byte[] payload) {
TXNPacket packet = TXNPacket.unpack(payload);
if(packet.getProtocol() == TXNProtocol.HB)
this.sendHB(from);
else if(this.n.addr == MASTER_NODE){
masterReceive(from, packet);
}else
slaveReceive(packet);
}
public void sendHB(int dest){
this.RIOLayer.sendRIO(dest, TXNProtocol.HB, new byte[0]);
}
public void onTimeout(int dest, byte[] payload){
TXNPacket pkt = TXNPacket.unpack(payload);
if(this.n.addr == MASTER_NODE){
for(Integer committer : waitingQueue.keySet()){
Commit com = waitingQueue.get(committer);
for(Integer dep : com){
if(dep == dest){
this.send(committer, TXNProtocol.ABORT, new byte[0]);
break;
}
}
}
}else
this.n.printError(DistNode.buildErrorString(dest, this.n.addr, pkt.getProtocol(), Utility.byteArrayToString(pkt.getPayload()), Error.ERR_20));
}
private void masterReceive(int from, TXNPacket pkt){
MasterFile f;
String contents, fileName;
int i, lastSpace;
switch(pkt.getProtocol()){
case TXNProtocol.WQ:
fileName = Utility.byteArrayToString(pkt.getPayload());
f = (MasterFile)this.getFileFromCache(fileName);
if(f.getState() == File.INV){
- String payload = DistNode.buildErrorString(this.n.addr, from, TXNProtocol.WQ, fileName, Error.ERR_10);
+ String payload = fileName + " " + DistNode.buildErrorString(this.n.addr, from, TXNProtocol.WQ, fileName, Error.ERR_10);
this.send(from, TXNProtocol.ERROR, Utility.stringToByteArray(payload));
}else if(!f.isCheckedOut()){
try{
byte[] payload = Utility.stringToByteArray(f.getName() + " " + f.getVersion() + " " + this.n.get(fileName));
f.addDep(from, MASTER_NODE);
this.send(from, TXNProtocol.WD, payload);
}catch(IOException e){
- String payload = DistNode.buildErrorString(this.n.addr, from, TXNProtocol.WQ, fileName, Error.ERR_10);
+ String payload = fileName + " " + DistNode.buildErrorString(this.n.addr, from, TXNProtocol.WQ, fileName, Error.ERR_10);
this.send(from, TXNProtocol.ERROR, Utility.stringToByteArray(payload));
}
}else{
f.requestor = from;
for(Integer client : f){
f.changePermissions(client, MasterFile.WF);
this.send(client, TXNProtocol.WF, Utility.stringToByteArray(f.getName()));
}
}
break;
case TXNProtocol.WD:
contents = Utility.byteArrayToString(pkt.getPayload());
i = contents.indexOf(' ');
fileName = contents.substring(0, i);
lastSpace = i + 1;
int version = Integer.parseInt(contents.substring(lastSpace, i));
contents = contents.substring(i + 1);
f = (MasterFile)this.getFileFromCache(fileName);
f.changePermissions(from, MasterFile.FREE);
if(this.txn.getVersion(f) < version){
f.propose(contents, version, from);
}
if(!f.isWaiting()){
Update u = f.chooseProp(f.requestor);
this.send(f.requestor, TXNProtocol.WD, Utility.stringToByteArray(fileName + " " + u.version + " " + u.contents));
f.requestor = -1;
}
break;
case TXNProtocol.ERROR:
String[] parts = Utility.byteArrayToString(pkt.getPayload()).split(" ");
if(parts.length == 2){
fileName = parts[0];
int errCode = Integer.parseInt(parts[1]);
if(errCode == Error.ERR_10){
//This is a client saying it doesn't have a file after the server sent it a WF
//This means the MasterFile has some corrupted state, change permissions for that client to invalid.
f = (MasterFile)this.getFileFromCache(fileName);
f.changePermissions(from, File.INV);
}
}
break;
case TXNProtocol.COMMIT_DATA:
if(!this.commitQueue.containsKey(from))
this.commitQueue.put(from, new ArrayList<Command>());
contents = Utility.byteArrayToString(pkt.getPayload());
i = contents.indexOf(' ');
fileName = contents.substring(0, i);
lastSpace = i + 1;
int commandType = Integer.parseInt(contents.substring(lastSpace, i));
f = (MasterFile)this.getFileFromCache(fileName);
Command c;
if(commandType == Command.APPEND || commandType == Command.PUT || commandType == Command.UPDATE){
contents = contents.substring(i + 1);
c = new Command(MASTER_NODE, commandType, f, contents);
}else{
c = new Command(MASTER_NODE, commandType, f);
}
this.commitQueue.get(from).add(c);
break;
case TXNProtocol.COMMIT:
this.commit(from, Integer.parseInt(Utility.byteArrayToString(pkt.getPayload())));
break;
}
}
private void commit(int client, int size){
List<Command> commands = this.commitQueue.get(client);
if(size != commands.size()){
this.send(client, TXNProtocol.ERROR, Utility.stringToByteArray(Error.ERROR_STRINGS[Error.ERR_40]));
}else{
Log log = new Log(commands);
Commit c = new Commit(client, log);
if(c.abort()){
for(MasterFile f : log)
f.abort(client);
this.send(client, TXNProtocol.ABORT, new byte[0]);
}else if(c.isWaiting()){
//add commit to queue and send heartbeat to nodes that the commit is waiting for
for(Integer addr : c){
this.send(addr, TXNProtocol.HB, new byte[0]);
}
this.waitingQueue.put(client, c);
}else{
//push changes to disk and put most recent version in memory in MasterFile
for(MasterFile f : log){
try{
int version = f.getVersion();
String contents = this.n.get(f.getName());
for(Command cmd : log.getCommands(f)){
if(cmd.getType() == Command.APPEND){
contents += cmd.getContents();
version++;
}else if(cmd.getType() == Command.PUT){
contents = cmd.getContents();
version++;
}
}
this.n.write(f.getName(), contents, false, true);
f.commit(client);
}catch(IOException e){
//TODO: send back error to client
return;
}
}
this.send(client, TXNProtocol.COMMIT, new byte[0]);
}
}
}
private void slaveReceive(TXNPacket pkt){
String fileName;
File f;
switch(pkt.getProtocol()){
case TXNProtocol.WF:
fileName = Utility.byteArrayToString(pkt.getPayload());
f = this.getFileFromCache(fileName);
try {
byte[] payload = this.txn.getVersion(f, this.n.get(fileName));
this.send(MASTER_NODE, TXNProtocol.WD, payload);
} catch (IOException e) {
this.send(MASTER_NODE, TXNProtocol.ERROR, Utility.stringToByteArray(fileName + " " + Error.ERR_10));
}
break;
case TXNProtocol.WD:
String contents = Utility.byteArrayToString(pkt.getPayload());
int i = contents.indexOf(' ');
fileName = contents.substring(0, i);
int lastSpace = i + 1;
int version = Integer.parseInt(contents.substring(lastSpace, i));
contents = contents.substring(i + 1);
f = this.getFileFromCache(fileName);
Command c = (Command)f.execute(); //Get command that originally requested this Query
try {
this.n.write(fileName, contents, false, true);
f.setState(File.RW);
f.setVersion(version);
this.txn.add(new Command(MASTER_NODE, Command.UPDATE, f, version + ""));
this.txn.add(c);
this.n.printSuccess(c);
} catch (IOException e) {
this.n.printError("Fatal Error: Couldn't update file: " + fileName + " to version: " + version);
}
executeCommandQueue(f);
break;
case TXNProtocol.ABORT:
this.abort();
break;
case TXNProtocol.COMMIT:
this.commitChangesLocally();
this.commitConfirm();
break;
}
}
public void commitChangesLocally() {
for( Command c : this.txn ) {
try {
int type = c.getType();
switch( type ) {
case Command.GET :
this.n.printData(this.n.get(c.getFileName() ));
break;
case Command.APPEND:
this.n.write(c.getFileName(), c.getContents(), true, false);
break;
case Command.PUT:
this.n.write(c.getFileName(), c.getContents(), false, false);
break;
case Command.CREATE:
this.n.create(c.getFileName());
break;
case Command.DELETE:
this.n.delete(c.getFileName());
break;
}
} catch(IOException e) {
this.n.printError("Fatal Error: When applying commit locally on: " + c.getFileName() + " command: " + c ) ;
}
this.n.printSuccess(c);
}
}
public void executeCommandQueue(File f){
Command c = (Command)f.peek();
boolean stop = false;
while(c != null && !stop){
switch(c.getType()){
case Command.APPEND:
stop = !append(c, f);
break;
case Command.CREATE:
stop = !create(c, f);
break;
case Command.DELETE:
stop = !delete(c, f);
break;
case Command.PUT:
stop = !put(c, f);
break;
case Command.GET:
stop = !get(c, f);
break;
}
c = (Command)f.peek();
}
}
/*=====================================================
* Methods DistNode uses to talk to TXNLayer
*=====================================================*/
public boolean get(String filename){
File f = this.cache.get( filename );
Command c = new Command(MASTER_NODE, Command.GET, f);
if(f.execute(c)){
return get(c, f);
}
return false;
}
private boolean get(Command c, File f){
if(f.getState() == File.INV){
this.send(MASTER_NODE, RPCProtocol.GET, Utility.stringToByteArray(f.getName()));
return false;
}else{
f.execute();
//this.n.printData(this.txn.getVersion( this.n.get(f.getName()) ));
this.txn.add( c );
return true;
}
}
//TODO: Decide what to do for creates/deletes and transactions
public boolean create(String filename){
boolean rtn = false;
File f = getFileFromCache( filename );
Command c = new Command(MASTER_NODE, Command.CREATE, f, "");
if(f.execute(c)){
return create(c, f);
}
return rtn;
}
private boolean create(Command c, File f){
if(f.getState() == File.INV){
this.send(MASTER_NODE, RPCProtocol.CREATE, Utility.stringToByteArray(f.getName()));
return false;
}else{
f.execute();
this.n.printError(c, Error.ERR_11);
return true;
}
}
public boolean put(String filename, String content){
File f = getFileFromCache( filename );
Command c = new Command(MASTER_NODE, Command.PUT, f, content);
if(f.execute(c)){
return put(c, f);
}
return false;
}
private boolean put(Command c, File f){
if(f.getState() == File.INV){
this.send(MASTER_NODE, RPCProtocol.GET, Utility.stringToByteArray(f.getName() + " " + File.RW)); //WQ
return false;
}else{
f.execute();
this.txn.add( c );
//this.n.printSuccess(c);
return true;
}
}
public boolean append(String filename, String content){
File f = getFileFromCache( filename );
Command c = new Command(MASTER_NODE, Command.APPEND, f, content);
if(f.execute(c)) {
return append(c, f);
}
return false;
}
private boolean append(Command c, File f){
if(f.getState() != File.RW) {
this.send(MASTER_NODE, RPCProtocol.GET, Utility.stringToByteArray(f.getName() + " " + File.RW)); //WQ
return false;
}else{
f.execute();
this.txn.add(c);
//this.n.printSuccess(c);
return true;
}
}
//TODO: Decide what to do for creates/deletes and transactions
public boolean delete(String filename){
File f = getFileFromCache( filename );
Command c = new Command(MASTER_NODE, Command.DELETE, f);
if(f.execute(c)) {
return delete(c, f);
}
return false;
}
private boolean delete(Command c, File f){
if(f.getState() != File.RW) {
this.send(MASTER_NODE, RPCProtocol.DELETE, Utility.stringToByteArray(f.getName()));
return false;//WQ
} else {
f.execute();
return true;
}
}
public void abort() {
this.txn = null;
}
public void commit() {
//Send all of our commands to the master node
for( Command c : this.txn ) {
String payload = c.getType() + " " + c.getFileName();
if( c.getType() == Command.PUT || c.getType() == Command.APPEND ) {
payload += " " + c.getContents();
}
this.send(MASTER_NODE, TXNProtocol.COMMIT_DATA, Utility.stringToByteArray(payload));
}
//Send the final commit message
this.send(MASTER_NODE, TXNProtocol.COMMIT, Utility.stringToByteArray(this.txn.id + "") );
}
public void commitConfirm() {
this.txn = null;
}
public void start() {
if( this.txn != null ) {
int newTXNnum = this.lastTXNnum + RIONode.NUM_NODES;
//start a new transaction by creating a new transaction object
this.txn = new Transaction( newTXNnum );
} else {
this.n.printError("ERROR: Transaction in progress: can not start new transaction");
}
}
private File getFileFromCache(String fileName) {
File f = this.cache.get(fileName);
if(f == null){
f = this.n.addr == MASTER_NODE ? new MasterFile(fileName, "") : new File(File.INV, fileName);
this.cache.put(fileName, f);
}
return f;
}
}
| false | true | private void masterReceive(int from, TXNPacket pkt){
MasterFile f;
String contents, fileName;
int i, lastSpace;
switch(pkt.getProtocol()){
case TXNProtocol.WQ:
fileName = Utility.byteArrayToString(pkt.getPayload());
f = (MasterFile)this.getFileFromCache(fileName);
if(f.getState() == File.INV){
String payload = DistNode.buildErrorString(this.n.addr, from, TXNProtocol.WQ, fileName, Error.ERR_10);
this.send(from, TXNProtocol.ERROR, Utility.stringToByteArray(payload));
}else if(!f.isCheckedOut()){
try{
byte[] payload = Utility.stringToByteArray(f.getName() + " " + f.getVersion() + " " + this.n.get(fileName));
f.addDep(from, MASTER_NODE);
this.send(from, TXNProtocol.WD, payload);
}catch(IOException e){
String payload = DistNode.buildErrorString(this.n.addr, from, TXNProtocol.WQ, fileName, Error.ERR_10);
this.send(from, TXNProtocol.ERROR, Utility.stringToByteArray(payload));
}
}else{
f.requestor = from;
for(Integer client : f){
f.changePermissions(client, MasterFile.WF);
this.send(client, TXNProtocol.WF, Utility.stringToByteArray(f.getName()));
}
}
break;
case TXNProtocol.WD:
contents = Utility.byteArrayToString(pkt.getPayload());
i = contents.indexOf(' ');
fileName = contents.substring(0, i);
lastSpace = i + 1;
int version = Integer.parseInt(contents.substring(lastSpace, i));
contents = contents.substring(i + 1);
f = (MasterFile)this.getFileFromCache(fileName);
f.changePermissions(from, MasterFile.FREE);
if(this.txn.getVersion(f) < version){
f.propose(contents, version, from);
}
if(!f.isWaiting()){
Update u = f.chooseProp(f.requestor);
this.send(f.requestor, TXNProtocol.WD, Utility.stringToByteArray(fileName + " " + u.version + " " + u.contents));
f.requestor = -1;
}
break;
case TXNProtocol.ERROR:
String[] parts = Utility.byteArrayToString(pkt.getPayload()).split(" ");
if(parts.length == 2){
fileName = parts[0];
int errCode = Integer.parseInt(parts[1]);
if(errCode == Error.ERR_10){
//This is a client saying it doesn't have a file after the server sent it a WF
//This means the MasterFile has some corrupted state, change permissions for that client to invalid.
f = (MasterFile)this.getFileFromCache(fileName);
f.changePermissions(from, File.INV);
}
}
break;
case TXNProtocol.COMMIT_DATA:
if(!this.commitQueue.containsKey(from))
this.commitQueue.put(from, new ArrayList<Command>());
contents = Utility.byteArrayToString(pkt.getPayload());
i = contents.indexOf(' ');
fileName = contents.substring(0, i);
lastSpace = i + 1;
int commandType = Integer.parseInt(contents.substring(lastSpace, i));
f = (MasterFile)this.getFileFromCache(fileName);
Command c;
if(commandType == Command.APPEND || commandType == Command.PUT || commandType == Command.UPDATE){
contents = contents.substring(i + 1);
c = new Command(MASTER_NODE, commandType, f, contents);
}else{
c = new Command(MASTER_NODE, commandType, f);
}
this.commitQueue.get(from).add(c);
break;
case TXNProtocol.COMMIT:
this.commit(from, Integer.parseInt(Utility.byteArrayToString(pkt.getPayload())));
break;
}
}
| private void masterReceive(int from, TXNPacket pkt){
MasterFile f;
String contents, fileName;
int i, lastSpace;
switch(pkt.getProtocol()){
case TXNProtocol.WQ:
fileName = Utility.byteArrayToString(pkt.getPayload());
f = (MasterFile)this.getFileFromCache(fileName);
if(f.getState() == File.INV){
String payload = fileName + " " + DistNode.buildErrorString(this.n.addr, from, TXNProtocol.WQ, fileName, Error.ERR_10);
this.send(from, TXNProtocol.ERROR, Utility.stringToByteArray(payload));
}else if(!f.isCheckedOut()){
try{
byte[] payload = Utility.stringToByteArray(f.getName() + " " + f.getVersion() + " " + this.n.get(fileName));
f.addDep(from, MASTER_NODE);
this.send(from, TXNProtocol.WD, payload);
}catch(IOException e){
String payload = fileName + " " + DistNode.buildErrorString(this.n.addr, from, TXNProtocol.WQ, fileName, Error.ERR_10);
this.send(from, TXNProtocol.ERROR, Utility.stringToByteArray(payload));
}
}else{
f.requestor = from;
for(Integer client : f){
f.changePermissions(client, MasterFile.WF);
this.send(client, TXNProtocol.WF, Utility.stringToByteArray(f.getName()));
}
}
break;
case TXNProtocol.WD:
contents = Utility.byteArrayToString(pkt.getPayload());
i = contents.indexOf(' ');
fileName = contents.substring(0, i);
lastSpace = i + 1;
int version = Integer.parseInt(contents.substring(lastSpace, i));
contents = contents.substring(i + 1);
f = (MasterFile)this.getFileFromCache(fileName);
f.changePermissions(from, MasterFile.FREE);
if(this.txn.getVersion(f) < version){
f.propose(contents, version, from);
}
if(!f.isWaiting()){
Update u = f.chooseProp(f.requestor);
this.send(f.requestor, TXNProtocol.WD, Utility.stringToByteArray(fileName + " " + u.version + " " + u.contents));
f.requestor = -1;
}
break;
case TXNProtocol.ERROR:
String[] parts = Utility.byteArrayToString(pkt.getPayload()).split(" ");
if(parts.length == 2){
fileName = parts[0];
int errCode = Integer.parseInt(parts[1]);
if(errCode == Error.ERR_10){
//This is a client saying it doesn't have a file after the server sent it a WF
//This means the MasterFile has some corrupted state, change permissions for that client to invalid.
f = (MasterFile)this.getFileFromCache(fileName);
f.changePermissions(from, File.INV);
}
}
break;
case TXNProtocol.COMMIT_DATA:
if(!this.commitQueue.containsKey(from))
this.commitQueue.put(from, new ArrayList<Command>());
contents = Utility.byteArrayToString(pkt.getPayload());
i = contents.indexOf(' ');
fileName = contents.substring(0, i);
lastSpace = i + 1;
int commandType = Integer.parseInt(contents.substring(lastSpace, i));
f = (MasterFile)this.getFileFromCache(fileName);
Command c;
if(commandType == Command.APPEND || commandType == Command.PUT || commandType == Command.UPDATE){
contents = contents.substring(i + 1);
c = new Command(MASTER_NODE, commandType, f, contents);
}else{
c = new Command(MASTER_NODE, commandType, f);
}
this.commitQueue.get(from).add(c);
break;
case TXNProtocol.COMMIT:
this.commit(from, Integer.parseInt(Utility.byteArrayToString(pkt.getPayload())));
break;
}
}
|
diff --git a/src/com/codebutler/farebot/transit/OVChipTransitData.java b/src/com/codebutler/farebot/transit/OVChipTransitData.java
index 7461c00..da03535 100644
--- a/src/com/codebutler/farebot/transit/OVChipTransitData.java
+++ b/src/com/codebutler/farebot/transit/OVChipTransitData.java
@@ -1,329 +1,337 @@
/*
* OVChipTransitData.java
*
* Copyright (C) 2012 Eric Butler
*
* Authors:
* Wilbert Duijvenvoorde <[email protected]>
* Eric Butler <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.codebutler.farebot.transit;
import android.os.Parcel;
import com.codebutler.farebot.FareBotApplication;
import com.codebutler.farebot.HeaderListItem;
import com.codebutler.farebot.ListItem;
import com.codebutler.farebot.R;
import com.codebutler.farebot.Utils;
import com.codebutler.farebot.card.Card;
import com.codebutler.farebot.card.classic.ClassicCard;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Currency;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class OVChipTransitData extends TransitData {
public static final int PROCESS_PURCHASE = 0x00;
public static final int PROCESS_CHECKIN = 0x01;
public static final int PROCESS_CHECKOUT = 0x02;
public static final int PROCESS_TRANSFER = 0x06;
public static final int PROCESS_BANNED = 0x07;
public static final int PROCESS_CREDIT = -0x02;
public static final int PROCESS_NODATA = -0x03;
public static final int AGENCY_TLS = 0x00;
public static final int AGENCY_CONNEXXION = 0x01;
public static final int AGENCY_GVB = 0x02;
public static final int AGENCY_HTM = 0x03;
public static final int AGENCY_NS = 0x04;
public static final int AGENCY_RET = 0x05;
public static final int AGENCY_VEOLIA = 0x07;
public static final int AGENCY_ARRIVA = 0x08;
public static final int AGENCY_SYNTUS = 0x09;
public static final int AGENCY_QBUZZ = 0x0A;
public static final int AGENCY_DUO = 0x0C; // Could also be 2C though... ( http://www.ov-chipkaart.me/forum/viewtopic.php?f=10&t=299 )
public static final int AGENCY_STORE = 0x19;
private static final byte[] OVC_MANUFACTURER = { (byte) 0x98, (byte) 0x02, (byte) 0x00 /*, (byte) 0x64, (byte) 0x8E */ };
private static final byte[] OVC_HEADER = new byte[11];
static {
OVC_HEADER[0] = -124;
OVC_HEADER[4] = 6;
OVC_HEADER[5] = 3;
OVC_HEADER[6] = -96;
OVC_HEADER[8] = 19;
OVC_HEADER[9] = -82;
OVC_HEADER[10] = -28;
}
private static Map<Integer, String> sAgencies = new HashMap<Integer, String>() {{
put(AGENCY_TLS, "Trans Link Systems");
put(AGENCY_CONNEXXION, "Connexxion");
put(AGENCY_GVB, "Gemeentelijk Vervoersbedrijf");
put(AGENCY_HTM, "Haagsche Tramweg-Maatschappij");
put(AGENCY_NS, "Nederlandse Spoorwegen");
put(AGENCY_RET, "Rotterdamse Elektrische Tram");
put(AGENCY_VEOLIA, "Veolia");
put(AGENCY_ARRIVA, "Arriva");
put(AGENCY_SYNTUS, "Syntus");
put(AGENCY_QBUZZ, "Qbuzz");
put(AGENCY_DUO, "Dienst Uitvoering Onderwijs");
put(AGENCY_STORE, "Reseller");
}};
private static Map<Integer, String> sShortAgencies = new HashMap<Integer, String>() {{
put(AGENCY_TLS, "TLS");
put(AGENCY_CONNEXXION, "Connexxion"); /* or Breng, Hermes, GVU */
put(AGENCY_GVB, "GVB");
put(AGENCY_HTM, "HTM");
put(AGENCY_NS, "NS");
put(AGENCY_RET, "RET");
put(AGENCY_VEOLIA, "Veolia");
put(AGENCY_ARRIVA, "Arriva"); /* or Aquabus */
put(AGENCY_SYNTUS, "Syntus");
put(AGENCY_QBUZZ, "Qbuzz");
put(AGENCY_DUO, "DUO");
put(AGENCY_STORE, "Reseller"); /* used by Albert Heijn, Primera and Hermes busses and maybe even more */
}};
private final OVChipIndex mIndex;
private final OVChipPreamble mPreamble;
private final OVChipInfo mInfo;
private final OVChipCredit mCredit;
private final OVChipTrip[] mTrips;
private final OVChipSubscription[] mSubscriptions;
public Creator<OVChipTransitData> CREATOR = new Creator<OVChipTransitData>() {
public OVChipTransitData createFromParcel(Parcel parcel) {
return new OVChipTransitData(parcel);
}
public OVChipTransitData[] newArray(int size) {
return new OVChipTransitData[size];
}
};
public static boolean check(Card card) {
if (!(card instanceof ClassicCard))
return false;
ClassicCard classicCard = (ClassicCard) card;
if (classicCard.getSectors().length != 40)
return false;
// Starting at 0×010, 8400 0000 0603 a000 13ae e401 xxxx 0e80 80e8 seems to exist on all OVC's (with xxxx different).
// http://www.ov-chipkaart.de/back-up/3-8-11/www.ov-chipkaart.me/blog/index7e09.html?page_id=132
byte[] blockData = classicCard.getSector(0).readBlocks(1, 1);
return Arrays.equals(Arrays.copyOfRange(blockData, 0, 11), OVC_HEADER);
}
public static TransitIdentity parseTransitIdentity (Card card) {
String hex = Utils.getHexString(((ClassicCard) card).getSector(0).getBlock(0).getData(), null);
String id = hex.substring(0, 8);
return new TransitIdentity("OV-chipkaart", id);
}
public OVChipTransitData(Parcel parcel) {
mTrips = new OVChipTrip[parcel.readInt()];
parcel.readTypedArray(mTrips, OVChipTrip.CREATOR);
mSubscriptions = new OVChipSubscription[parcel.readInt()];
parcel.readTypedArray(mSubscriptions, OVChipSubscription.CREATOR);
mIndex = parcel.readParcelable(OVChipIndex.class.getClassLoader());
mPreamble = parcel.readParcelable(OVChipPreamble.class.getClassLoader());
mInfo = parcel.readParcelable(OVChipInfo.class.getClassLoader());
mCredit = parcel.readParcelable(OVChipCredit.class.getClassLoader());
}
public OVChipTransitData(ClassicCard card) {
mIndex = new OVChipIndex(card.getSector(39).readBlocks(11, 4));
OVChipParser parser = new OVChipParser(card, mIndex);
mCredit = parser.getCredit();
mPreamble = parser.getPreamble();
mInfo = parser.getInfo();
List<OVChipTransaction> transactions = new ArrayList<OVChipTransaction>(Arrays.asList(parser.getTransactions()));
Collections.sort(transactions, OVChipTransaction.ID_ORDER);
List<OVChipTrip> trips = new ArrayList<OVChipTrip>();
for (int i = 0; i < transactions.size(); i++) {
OVChipTransaction transaction = transactions.get(i);
if (transaction.getValid() != 1) {
continue;
}
if (i < (transactions.size() - 1)) {
OVChipTransaction nextTransaction = transactions.get(i + 1);
- if (transaction.isSameTrip(nextTransaction)) {
+ if (transaction.getId() == nextTransaction.getId()) { // handle two consecutive (duplicate) logins, skip the first one
+ continue;
+ } else if (transaction.isSameTrip(nextTransaction)) {
trips.add(new OVChipTrip(transaction, nextTransaction));
i++;
+ if (i < (transactions.size() - 2)) { // check for two consecutive (duplicate) logouts, skip the second one
+ OVChipTransaction followingTransaction = transactions.get(i + 1);
+ if (nextTransaction.getId() == followingTransaction.getId()) {
+ i++;
+ }
+ }
continue;
}
}
trips.add(new OVChipTrip(transaction));
}
Collections.sort(trips, OVChipTrip.ID_ORDER);
mTrips = trips.toArray(new OVChipTrip[trips.size()]);
List<OVChipSubscription> subs = new ArrayList<OVChipSubscription>();
subs.addAll(Arrays.asList(parser.getSubscriptions()));
Collections.sort(subs, new Comparator<OVChipSubscription>() {
@Override
public int compare(OVChipSubscription s1, OVChipSubscription s2) {
return Integer.valueOf(s1.getId()).compareTo(s2.getId());
}
});
mSubscriptions = subs.toArray(new OVChipSubscription[subs.size()]);
}
public static Date convertDate(int date) {
return convertDate(date, 0);
}
public static Date convertDate(int date, int time) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 1997);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, time / 60);
calendar.set(Calendar.MINUTE, time % 60);
calendar.add(Calendar.DATE, date);
return calendar.getTime();
}
public static String convertAmount(int amount) {
DecimalFormat formatter = (DecimalFormat)NumberFormat.getCurrencyInstance();
formatter.setCurrency(Currency.getInstance("EUR"));
String symbol = formatter.getCurrency().getSymbol();
formatter.setNegativePrefix(symbol + "-");
formatter.setNegativeSuffix("");
return formatter.format((double)amount / 100.0);
}
@Override
public String getCardName () {
return "OV-Chipkaart";
}
public static String getAgencyName(int agency) {
if (sAgencies.containsKey(agency)) {
return sAgencies.get(agency);
}
return FareBotApplication.getInstance().getString(R.string.unknown_format, "0x" + Long.toString(agency, 16));
}
public static String getShortAgencyName (int agency) {
if (sShortAgencies.containsKey(agency)) {
return sShortAgencies.get(agency);
}
return FareBotApplication.getInstance().getString(R.string.unknown_format, "0x" + Long.toString(agency, 16));
}
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeInt(mTrips.length);
parcel.writeTypedArray(mTrips, flags);
parcel.writeInt(mSubscriptions.length);
parcel.writeTypedArray(mSubscriptions, flags);
parcel.writeParcelable(mIndex, flags);
parcel.writeParcelable(mPreamble, flags);
parcel.writeParcelable(mInfo, flags);
parcel.writeParcelable(mCredit, flags);
}
@Override
public String getBalanceString() {
return OVChipTransitData.convertAmount(mCredit.getCredit());
}
@Override
public String getSerialNumber() {
return null;
}
@Override
public Trip[] getTrips() {
return mTrips;
}
@Override
public Refill[] getRefills() {
return null;
}
public Subscription[] getSubscriptions() {
return mSubscriptions;
}
@Override
public List<ListItem> getInfo() {
ArrayList<ListItem> items = new ArrayList<ListItem>();
items.add(new HeaderListItem("Hardware Information"));
items.add(new ListItem("Manufacturer ID", mPreamble.getManufacturer()));
items.add(new ListItem("Publisher ID", mPreamble.getPublisher()));
items.add(new HeaderListItem("General Information"));
items.add(new ListItem("Serial Number", mPreamble.getId()));
items.add(new ListItem("Expiration Date", DateFormat.getDateInstance(DateFormat.LONG).format(OVChipTransitData.convertDate(mPreamble.getExpdate()))));
items.add(new ListItem("Card Type", (mPreamble.getType() == 2 ? "Personal" : "Anonymous")));
items.add(new ListItem("Banned", ((mCredit.getBanbits() & (byte)0xC0) == (byte)0xC0) ? "Yes" : "No"));
if (mPreamble.getType() == 2) {
items.add(new HeaderListItem("Personal Information"));
items.add(new ListItem("Birthdate", DateFormat.getDateInstance(DateFormat.LONG).format(mInfo.getBirthdate())));
}
items.add(new HeaderListItem("Credit Information"));
items.add(new ListItem("Credit Slot ID", Integer.toString(mCredit.getId())));
items.add(new ListItem("Last Credit ID", Integer.toString(mCredit.getCreditId())));
items.add(new ListItem("Credit", OVChipTransitData.convertAmount(mCredit.getCredit())));
items.add(new ListItem("Autocharge", (mInfo.getActive() == (byte)0x05 ? "Yes" : "No")));
items.add(new ListItem("Autocharge Limit", OVChipTransitData.convertAmount(mInfo.getLimit())));
items.add(new ListItem("Autocharge Charge", OVChipTransitData.convertAmount(mInfo.getCharge())));
items.add(new HeaderListItem("Recent Slots"));
items.add(new ListItem("Transaction Slot", "0x" + Integer.toHexString((char)mIndex.getRecentTransactionSlot())));
items.add(new ListItem("Info Slot", "0x" + Integer.toHexString((char)mIndex.getRecentInfoSlot())));
items.add(new ListItem("Subscription Slot", "0x" + Integer.toHexString((char)mIndex.getRecentSubscriptionSlot())));
items.add(new ListItem("Travelhistory Slot", "0x" + Integer.toHexString((char)mIndex.getRecentTravelhistorySlot())));
items.add(new ListItem("Credit Slot", "0x" + Integer.toHexString((char)mIndex.getRecentCreditSlot())));
return items;
}
}
| false | true | public OVChipTransitData(ClassicCard card) {
mIndex = new OVChipIndex(card.getSector(39).readBlocks(11, 4));
OVChipParser parser = new OVChipParser(card, mIndex);
mCredit = parser.getCredit();
mPreamble = parser.getPreamble();
mInfo = parser.getInfo();
List<OVChipTransaction> transactions = new ArrayList<OVChipTransaction>(Arrays.asList(parser.getTransactions()));
Collections.sort(transactions, OVChipTransaction.ID_ORDER);
List<OVChipTrip> trips = new ArrayList<OVChipTrip>();
for (int i = 0; i < transactions.size(); i++) {
OVChipTransaction transaction = transactions.get(i);
if (transaction.getValid() != 1) {
continue;
}
if (i < (transactions.size() - 1)) {
OVChipTransaction nextTransaction = transactions.get(i + 1);
if (transaction.isSameTrip(nextTransaction)) {
trips.add(new OVChipTrip(transaction, nextTransaction));
i++;
continue;
}
}
trips.add(new OVChipTrip(transaction));
}
Collections.sort(trips, OVChipTrip.ID_ORDER);
mTrips = trips.toArray(new OVChipTrip[trips.size()]);
List<OVChipSubscription> subs = new ArrayList<OVChipSubscription>();
subs.addAll(Arrays.asList(parser.getSubscriptions()));
Collections.sort(subs, new Comparator<OVChipSubscription>() {
@Override
public int compare(OVChipSubscription s1, OVChipSubscription s2) {
return Integer.valueOf(s1.getId()).compareTo(s2.getId());
}
});
mSubscriptions = subs.toArray(new OVChipSubscription[subs.size()]);
}
| public OVChipTransitData(ClassicCard card) {
mIndex = new OVChipIndex(card.getSector(39).readBlocks(11, 4));
OVChipParser parser = new OVChipParser(card, mIndex);
mCredit = parser.getCredit();
mPreamble = parser.getPreamble();
mInfo = parser.getInfo();
List<OVChipTransaction> transactions = new ArrayList<OVChipTransaction>(Arrays.asList(parser.getTransactions()));
Collections.sort(transactions, OVChipTransaction.ID_ORDER);
List<OVChipTrip> trips = new ArrayList<OVChipTrip>();
for (int i = 0; i < transactions.size(); i++) {
OVChipTransaction transaction = transactions.get(i);
if (transaction.getValid() != 1) {
continue;
}
if (i < (transactions.size() - 1)) {
OVChipTransaction nextTransaction = transactions.get(i + 1);
if (transaction.getId() == nextTransaction.getId()) { // handle two consecutive (duplicate) logins, skip the first one
continue;
} else if (transaction.isSameTrip(nextTransaction)) {
trips.add(new OVChipTrip(transaction, nextTransaction));
i++;
if (i < (transactions.size() - 2)) { // check for two consecutive (duplicate) logouts, skip the second one
OVChipTransaction followingTransaction = transactions.get(i + 1);
if (nextTransaction.getId() == followingTransaction.getId()) {
i++;
}
}
continue;
}
}
trips.add(new OVChipTrip(transaction));
}
Collections.sort(trips, OVChipTrip.ID_ORDER);
mTrips = trips.toArray(new OVChipTrip[trips.size()]);
List<OVChipSubscription> subs = new ArrayList<OVChipSubscription>();
subs.addAll(Arrays.asList(parser.getSubscriptions()));
Collections.sort(subs, new Comparator<OVChipSubscription>() {
@Override
public int compare(OVChipSubscription s1, OVChipSubscription s2) {
return Integer.valueOf(s1.getId()).compareTo(s2.getId());
}
});
mSubscriptions = subs.toArray(new OVChipSubscription[subs.size()]);
}
|
diff --git a/src/main/java/com/spartansoftwareinc/otter/TMXEventWriter.java b/src/main/java/com/spartansoftwareinc/otter/TMXEventWriter.java
index 9e45046..8d2250e 100644
--- a/src/main/java/com/spartansoftwareinc/otter/TMXEventWriter.java
+++ b/src/main/java/com/spartansoftwareinc/otter/TMXEventWriter.java
@@ -1,268 +1,267 @@
package com.spartansoftwareinc.otter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import static com.spartansoftwareinc.otter.TMXConstants.*;
public class TMXEventWriter {
public static TMXEventWriter createTMXEventWriter(Writer w)
throws XMLStreamException {
return new TMXEventWriter(w);
}
private XMLEventWriter xmlWriter;
private XMLEventFactory eventFactory;
private TMXEventWriter(Writer w) throws XMLStreamException {
XMLOutputFactory factory = XMLOutputFactory.newFactory();
xmlWriter = factory.createXMLEventWriter(w);
eventFactory = XMLEventFactory.newInstance();
}
public void writeEvent(TMXEvent event) throws XMLStreamException {
switch (event.getEventType()) {
case START_TMX:
startTMX();
break;
case END_TMX:
endTMX();
break;
case START_HEADER:
startHeader(event.getHeader());
break;
case END_HEADER:
endHeader();
break;
case START_BODY:
startBody();
break;
case END_BODY:
endBody();
break;
case HEADER_PROPERTY:
Property p = event.getProperty();
writeProperty(p.type, p.value);
break;
case HEADER_NOTE:
Note n = event.getNote();
writeNote(n.getContent());
break;
case TU:
writeTu(event.getTU());
break;
default:
- TODO();
- break;
+ throw new UnsupportedOperationException();
}
}
public void startTMX() throws XMLStreamException {
xmlWriter.add(eventFactory.createStartDocument());
ArrayList<Attribute> attrs = new ArrayList<Attribute>();
attrs.add(eventFactory.createAttribute(VERSION, "1.4"));
xmlWriter.add(eventFactory.createStartElement(TMX, attrs.iterator(), null));
}
public void endTMX() throws XMLStreamException {
xmlWriter.add(eventFactory.createEndElement(TMX, null));
xmlWriter.add(eventFactory.createEndDocument());
}
public void startHeader(Header h) throws XMLStreamException {
ArrayList<Attribute> attrs = new ArrayList<Attribute>();
// TODO: enforce attr requirements
addAttr(attrs, CREATIONID, h.getCreationId());
if (h.getCreationDate() != null) {
addAttr(attrs, CREATIONDATE, Util.writeTMXDate(h.getCreationDate()));
}
addAttr(attrs, CREATIONTOOL, h.getCreationTool());
addAttr(attrs, CREATIONTOOLVERSION, h.getCreationToolVersion());
addAttr(attrs, SEGTYPE, h.getSegType());
addAttr(attrs, TMF, h.getTmf());
addAttr(attrs, ADMINLANG, h.getAdminLang());
addAttr(attrs, SRCLANG, h.getSrcLang());
addAttr(attrs, SEGTYPE, h.getSegType());
if (h.getChangeDate() != null) {
addAttr(attrs, CHANGEDATE, Util.writeTMXDate(h.getChangeDate()));
}
addAttr(attrs, CHANGEID, h.getChangeId());
addAttr(attrs, ENCODING, h.getEncoding());
addAttr(attrs, DATATYPE, h.getDataType());
xmlWriter.add(eventFactory.createStartElement(HEADER, attrs.iterator(), null));
}
private void addAttr(List<Attribute> attrs, QName qname, String value) {
if (value != null) {
attrs.add(eventFactory.createAttribute(qname, value));
}
}
public void endHeader() throws XMLStreamException {
xmlWriter.add(eventFactory.createEndElement(HEADER, null));
}
public void writeProperty(String type, String value) throws XMLStreamException {
ArrayList<Attribute> attrs = new ArrayList<Attribute>();
attrs.add(eventFactory.createAttribute(TYPE, type));
xmlWriter.add(eventFactory.createStartElement(PROPERTY, attrs.iterator(), null));
xmlWriter.add(eventFactory.createCharacters(value));
xmlWriter.add(eventFactory.createEndElement(PROPERTY, null));
}
public void writeNote(String value) throws XMLStreamException {
xmlWriter.add(eventFactory.createStartElement(NOTE, null, null));
xmlWriter.add(eventFactory.createCharacters(value));
xmlWriter.add(eventFactory.createEndElement(NOTE, null));
}
public void startBody() throws XMLStreamException {
xmlWriter.add(eventFactory.createStartElement(BODY, null, null));
}
public void endBody() throws XMLStreamException {
xmlWriter.add(eventFactory.createEndElement(BODY, null));
}
public void writeTu(TU tu) throws XMLStreamException {
ArrayList<Attribute> tuAttrs = new ArrayList<Attribute>();
attr(tuAttrs, TUID, tu.getId());
attr(tuAttrs, ENCODING, tu.getEncoding());
attr(tuAttrs, DATATYPE, tu.getDatatype());
if (tu.getUsageCount() != null) {
attr(tuAttrs, USAGECOUNT, tu.getUsageCount().toString());
}
dateAttr(tuAttrs, LASTUSAGEDATE, tu.getLastUsageDate());
attr(tuAttrs, CREATIONTOOL, tu.getCreationTool());
attr(tuAttrs, CREATIONTOOLVERSION, tu.getCreationToolVersion());
dateAttr(tuAttrs, CREATIONDATE, tu.getCreationDate());
attr(tuAttrs, CREATIONID, tu.getCreationId());
dateAttr(tuAttrs, CHANGEDATE, tu.getChangeDate());
attr(tuAttrs, SEGTYPE, tu.getSegType());
attr(tuAttrs, CHANGEID, tu.getChangeId());
attr(tuAttrs, TMF, tu.getTmf());
attr(tuAttrs, SRCLANG, tu.getSrcLang());
xmlWriter.add(eventFactory.createStartElement(TU, tuAttrs.iterator(), null));
// TODO: Always print the source first
Map<String, TUV> tuvs = tu.getTuvs();
for (Map.Entry<String, TUV> e : tuvs.entrySet()) {
ArrayList<Attribute> attrs = new ArrayList<Attribute>();
attr(attrs, XMLLANG, e.getKey());
xmlWriter.add(eventFactory.createStartElement(TUV, attrs.iterator(), null));
xmlWriter.add(eventFactory.createStartElement(SEG, null, null));
for (TUVContent content : e.getValue().getContents()) {
writeContent(content);
}
xmlWriter.add(eventFactory.createEndElement(SEG, null));
xmlWriter.add(eventFactory.createEndElement(TUV, null));
}
xmlWriter.add(eventFactory.createEndElement(TU, null));
}
private void writeTag(QName qname, List<Attribute> attrs, List<TUVContent> contents)
throws XMLStreamException {
xmlWriter.add(eventFactory.createStartElement(qname, attrs.iterator(), null));
for (TUVContent content : contents) {
writeContent(content);
}
xmlWriter.add(eventFactory.createEndElement(qname, null));
}
private void writeContent(TUVContent content) throws XMLStreamException {
if (content instanceof SimpleContent) {
xmlWriter.add(eventFactory.createCharacters(((SimpleContent)content).getValue()));
}
else if (content instanceof PhTag) {
writePh((PhTag)content);
}
else if (content instanceof BptTag) {
writeBpt((BptTag)content);
}
else if (content instanceof EptTag) {
writeEpt((EptTag)content);
}
else if (content instanceof ItTag) {
writeIt((ItTag)content);
}
else if (content instanceof HiTag) {
writeHi((HiTag)content);
}
else if (content instanceof Subflow) {
writeSubflow((Subflow)content);
}
}
private void writePh(PhTag ph) throws XMLStreamException {
ArrayList<Attribute> attrs = new ArrayList<Attribute>();
if (ph.getX() != PhTag.NO_VALUE) {
attrs.add(eventFactory.createAttribute(X, Integer.toString(ph.getX())));
}
attr(attrs, TYPE, ph.getType());
attr(attrs, ASSOC, ph.getAssoc());
writeTag(PH, attrs, ph.getContents());
}
private void writeBpt(BptTag bpt) throws XMLStreamException {
ArrayList<Attribute> attrs = new ArrayList<Attribute>();
attrs.add(eventFactory.createAttribute(I, Integer.toString(bpt.getI())));
if (bpt.getX() != BptTag.NO_VALUE) {
attrs.add(eventFactory.createAttribute(X, Integer.toString(bpt.getX())));
}
attr(attrs, TYPE, bpt.getType());
writeTag(BPT, attrs, bpt.getContents());
}
private void writeEpt(EptTag ept) throws XMLStreamException {
ArrayList<Attribute> attrs = new ArrayList<Attribute>();
attrs.add(eventFactory.createAttribute(I, Integer.toString(ept.getI())));
writeTag(EPT, attrs, ept.getContents());
}
private void writeIt(ItTag it) throws XMLStreamException {
ArrayList<Attribute> attrs = new ArrayList<Attribute>();
attrs.add(eventFactory.createAttribute(POS, it.getPos().getAttrValue()));
if (it.getX() != ItTag.NO_VALUE) {
attrs.add(eventFactory.createAttribute(X, Integer.toString(it.getX())));
}
attr(attrs, TYPE, it.getType());
writeTag(IT, attrs, it.getContents());
}
private void writeHi(HiTag hi) throws XMLStreamException {
ArrayList<Attribute> attrs = new ArrayList<Attribute>();
if (hi.getX() != ItTag.NO_VALUE) {
attrs.add(eventFactory.createAttribute(X, Integer.toString(hi.getX())));
}
attr(attrs, TYPE, hi.getType());
writeTag(HI, attrs, hi.getContents());
}
private void writeSubflow(Subflow sub) throws XMLStreamException {
ArrayList<Attribute> attrs = new ArrayList<Attribute>();
attr(attrs, TYPE, sub.getType());
attr(attrs, DATATYPE, sub.getDatatype());
writeTag(SUB, attrs, sub.getContents());
}
private void attr(List<Attribute> attrs, QName name, String value) {
if (value != null) {
attrs.add(eventFactory.createAttribute(name, value));
}
}
private void dateAttr(List<Attribute> attrs, QName name, Date value) {
if (value != null) {
attrs.add(eventFactory.createAttribute(name, Util.writeTMXDate(value)));
}
}
}
| true | true | public void writeEvent(TMXEvent event) throws XMLStreamException {
switch (event.getEventType()) {
case START_TMX:
startTMX();
break;
case END_TMX:
endTMX();
break;
case START_HEADER:
startHeader(event.getHeader());
break;
case END_HEADER:
endHeader();
break;
case START_BODY:
startBody();
break;
case END_BODY:
endBody();
break;
case HEADER_PROPERTY:
Property p = event.getProperty();
writeProperty(p.type, p.value);
break;
case HEADER_NOTE:
Note n = event.getNote();
writeNote(n.getContent());
break;
case TU:
writeTu(event.getTU());
break;
default:
TODO();
break;
}
}
| public void writeEvent(TMXEvent event) throws XMLStreamException {
switch (event.getEventType()) {
case START_TMX:
startTMX();
break;
case END_TMX:
endTMX();
break;
case START_HEADER:
startHeader(event.getHeader());
break;
case END_HEADER:
endHeader();
break;
case START_BODY:
startBody();
break;
case END_BODY:
endBody();
break;
case HEADER_PROPERTY:
Property p = event.getProperty();
writeProperty(p.type, p.value);
break;
case HEADER_NOTE:
Note n = event.getNote();
writeNote(n.getContent());
break;
case TU:
writeTu(event.getTU());
break;
default:
throw new UnsupportedOperationException();
}
}
|
diff --git a/src/main/org/openscience/jchempaint/application/JChemPaint.java b/src/main/org/openscience/jchempaint/application/JChemPaint.java
index 6a88942..b8baa73 100644
--- a/src/main/org/openscience/jchempaint/application/JChemPaint.java
+++ b/src/main/org/openscience/jchempaint/application/JChemPaint.java
@@ -1,374 +1,378 @@
/*
* $RCSfile$
* $Author: egonw $
* $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $
* $Revision: 7634 $
*
* Copyright (C) 1997-2008 Stefan Kuhn
*
* Contact: [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
* All we ask is that proper credit is given for our work, which includes
* - but is not limited to - adding the above copyright notice to the beginning
* of your source code files, and to any copyright notice that you may distribute
* with programs based on this work.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.openscience.jchempaint.application;
import java.awt.Dimension;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.cli.UnrecognizedOptionException;
import org.openscience.cdk.ChemModel;
import org.openscience.cdk.DefaultChemObjectBuilder;
import org.openscience.cdk.interfaces.IAtomContainer;
import org.openscience.cdk.interfaces.IChemFile;
import org.openscience.cdk.interfaces.IChemModel;
import org.openscience.cdk.interfaces.IChemObject;
import org.openscience.cdk.interfaces.IReaction;
import org.openscience.cdk.io.CMLReader;
import org.openscience.cdk.io.INChIReader;
import org.openscience.cdk.io.ISimpleChemObjectReader;
import org.openscience.cdk.io.MDLRXNV2000Reader;
import org.openscience.cdk.io.MDLV2000Reader;
import org.openscience.cdk.io.ReaderFactory;
import org.openscience.cdk.io.SMILESReader;
import org.openscience.cdk.tools.manipulator.ChemModelManipulator;
import org.openscience.cdk.tools.manipulator.ReactionSetManipulator;
import org.openscience.jchempaint.GT;
import org.openscience.jchempaint.JChemPaintPanel;
import org.openscience.jchempaint.io.JCPFileFilter;
public class JChemPaint {
public static int instancecounter=1;
@SuppressWarnings("static-access")
public static void main(String[] args) {
try
{
String vers = System.getProperty("java.version");
String requiredJVM = "1.5.0";
Package self = Package.getPackage("org.openscience.cdk.applications.jchempaint");
String version = "Could not determine JCP version";
if(self!=null)
version=self.getImplementationVersion();
if (vers.compareTo(requiredJVM) < 0)
{
System.err.println("WARNING: JChemPaint "+version+" must be run with a Java VM version " +
requiredJVM + " or higher.");
System.err.println("Your JVM version: " + vers);
System.exit(1);
}
Options options = new Options();
options.addOption("h", "help", false, "give this help page");
options.addOption("v", "version", false, "gives JChemPaints version number");
options.addOption(
OptionBuilder.withArgName("property=value").
hasArg().
withValueSeparator().
withDescription("supported options are given below").
create("D")
);
CommandLine line = null;
try
{
CommandLineParser parser = new PosixParser();
line = parser.parse(options, args);
} catch (UnrecognizedOptionException exception)
{
System.err.println(exception.getMessage());
System.exit(-1);
} catch (ParseException exception)
{
System.err.println("Unexpected exception: " + exception.toString());
}
if (line.hasOption("v"))
{
System.out.println("JChemPaint v." + version + "\n");
System.exit(0);
}
if (line.hasOption("h"))
{
System.out.println("JChemPaint v." + version + "\n");
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("JChemPaint", options);
// now report on the -D options
System.out.println();
System.out.println("The -D options are as follows (defaults in parathesis):");
System.out.println(" cdk.debugging [true|false] (false)");
System.out.println(" cdk.debug.stdout [true|false] (false)");
System.out.println(" devel.gui [true|false] (false)");
System.out.println(" gui [stable|experimental] (stable)");
System.out.println(" user.language [DE|EN|NL|PL] (EN)");
System.exit(0);
}
// Process command line arguments
String modelFilename = "";
args = line.getArgs();
if (args.length > 0)
{
modelFilename = args[0];
File file = new File(modelFilename);
if (!file.exists())
{
System.err.println("File does not exist: " + modelFilename);
System.exit(-1);
}
showInstance(file,null,null);
}else{
showEmptyInstance();
}
} catch (Throwable t)
{
System.err.println("uncaught exception: " + t);
t.printStackTrace(System.err);
}
}
public static void showEmptyInstance() {
IChemModel chemModel=DefaultChemObjectBuilder.getInstance().newChemModel();
showInstance(chemModel, GT._("Untitled-")+(instancecounter++));
}
public static void showInstance(File inFile, String type, JChemPaintPanel jcpPanel){
if (!inFile.exists()) {
JOptionPane.showMessageDialog(jcpPanel, "File " + inFile.getPath()
+ " does not exist.");
return;
}
if (type == null) {
type = "unknown";
}
ISimpleChemObjectReader cor = null;
/*
* Have the ReaderFactory determine the file format
*/
try {
ReaderFactory factory = new ReaderFactory();
cor = factory.createReader(new FileReader(inFile));
+ if(cor instanceof CMLReader)
+ cor = new CMLReader(inFile.toURI().toString());
} catch (IOException ioExc) {
// we do nothing right now and hoe it still works
} catch (Exception exc) {
// we do nothing right now and hoe it still works
}
if (cor == null) {
// try to determine from user's guess
try {
FileInputStream reader = new FileInputStream(inFile);
if (type.equals(JCPFileFilter.cml)
|| type.equals(JCPFileFilter.xml)) {
- cor = new CMLReader(reader);
+ cor = new CMLReader(inFile.toURI().toString());
} else if (type.equals(JCPFileFilter.sdf)) {
cor = new MDLV2000Reader(reader);//TODO once merged, egons new reader needs to be used here
} else if (type.equals(JCPFileFilter.mol)) {
cor = new MDLV2000Reader(reader);
} else if (type.equals(JCPFileFilter.inchi)) {
cor = new INChIReader(reader);
} else if (type.equals(JCPFileFilter.rxn)) {
cor = new MDLRXNV2000Reader(reader);
} else if (type.equals(JCPFileFilter.smi)) {
cor = new SMILESReader(reader);
}
} catch (FileNotFoundException exception) {
// we do nothing right now and hoe it still works
}
}
if (cor == null) {
JOptionPane.showMessageDialog(jcpPanel,
"Could not determine file format.");
return;
}
// this takes care of files called .mol, but having several, sdf-style
// entries
if (cor instanceof MDLV2000Reader) {
try {
BufferedReader in = new BufferedReader(new FileReader(inFile));
String line;
while ((line = in.readLine()) != null) {
if (line.equals("$$$$")) {
String message = "It seems you opened a mol or sdf"
+ " file containing several molecules. "
+ "Only the first one will be shown";
JOptionPane.showMessageDialog(jcpPanel, message,
"sdf-like file",
JOptionPane.INFORMATION_MESSAGE);
break;
}
}
} catch (IOException ex) {
// we do nothing - firstly if IO does not work, we should not
// get here, secondly, if only this does not work, don't worry
}
}
String error = null;
ChemModel chemModel = null;
IChemFile chemFile = null;
if (cor.accepts(IChemFile.class)) {
// try to read a ChemFile
try {
chemFile = (IChemFile) cor
.read((IChemObject) new org.openscience.cdk.ChemFile());
if (chemFile == null) {
error = "The object chemFile was empty unexpectedly!";
}
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
if (error != null) {
JOptionPane.showMessageDialog(jcpPanel, error);
return;
}
if (cor.accepts(ChemModel.class)) {
// try to read a ChemModel
try {
chemModel = (ChemModel) cor.read((IChemObject) new ChemModel());
if (chemModel == null) {
error = "The object chemModel was empty unexpectedly!";
}
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
if (error != null) {
JOptionPane.showMessageDialog(jcpPanel, error);
}
if (chemModel == null && chemFile != null) {
chemModel = (ChemModel) chemFile.getChemSequence(0).getChemModel(0);
}
//we remove molecules which are in MoleculeSet as well as in a reaction
- List<IAtomContainer> aclist = ReactionSetManipulator.getAllAtomContainers(chemModel.getReactionSet());
- for(int i=chemModel.getMoleculeSet().getAtomContainerCount()-1;i>=0;i--){
- for(int k=0;k<aclist.size();k++){
- if(aclist.get(k)==chemModel.getMoleculeSet().getAtomContainer(i)){
- chemModel.getMoleculeSet().removeAtomContainer(i);
- break;
- }
- }
+ if(chemModel.getReactionSet()!=null){
+ List<IAtomContainer> aclist = ReactionSetManipulator.getAllAtomContainers(chemModel.getReactionSet());
+ for(int i=chemModel.getMoleculeSet().getAtomContainerCount()-1;i>=0;i--){
+ for(int k=0;k<aclist.size();k++){
+ if(aclist.get(k)==chemModel.getMoleculeSet().getAtomContainer(i)){
+ chemModel.getMoleculeSet().removeAtomContainer(i);
+ break;
+ }
+ }
+ }
}
// check for bonds
if (ChemModelManipulator.getBondCount(chemModel) == 0) {
error = "Model does not have bonds. Cannot depict contents.";
}
// check for coordinates
JChemPaint.checkCoordinates(chemModel);
//we give all reactions an ID, in case they have none
//IDs are needed for handling in JCP
if(chemModel.getReactionSet()!=null){
int i=0;
for(IReaction reaction : chemModel.getReactionSet().reactions()){
if(reaction.getID()==null)
reaction.setID("Reaction "+(++i));
}
}
JChemPaintPanel p = showInstance(chemModel, inFile.getName());
p.setCurrentWorkDirectory(inFile.getParentFile());
p.setLastOpenedFile(inFile);
p.setIsAlreadyAFile(inFile);
}
// TODO
private static void checkCoordinates(IChemModel chemModel) {
// if ((GeometryTools.has2DCoordinates(chemModel)==0)) {
// String error = "Model does not have 2D coordinates. Cannot open file.";
// logger.warn(error);
// JOptionPane.showMessageDialog(this, error);
// CreateCoordinatesForFileDialog frame = new CreateCoordinatesForFileDialog(chemModel, jchemPaintModel.getRendererModel().getRenderingCoordinates());
// frame.pack();
// frame.show();
// return;
// } else if ((GeometryTools.has2DCoordinatesNew(chemModel)==1)) {
// int result=JOptionPane.showConfirmDialog(this,"Model has some 2d coordinates. Do you want to show only the atoms with 2d coordiantes?","Only some 2d cooridantes",JOptionPane.YES_NO_OPTION);
// if(result>1){
// CreateCoordinatesForFileDialog frame = new CreateCoordinatesForFileDialog(chemModel, jchemPaintModel.getRendererModel().getRenderingCoordinates());
// frame.pack();
// frame.show();
// return;
// }else{
// for(int i=0;i<chemModel.getMoleculeSet().getAtomContainerCount();i++){
// for(int k=0;i<chemModel.getMoleculeSet().getAtomContainer(i).getAtomCount();k++){
// if(chemModel.getMoleculeSet().getAtomContainer(i).getAtom(k).getPoint2d()==null)
// chemModel.getMoleculeSet().getAtomContainer(i).removeAtomAndConnectedElectronContainers(chemModel.getMoleculeSet().getAtomContainer(i).getAtom(k));
// }
// }
// }
// }
// if(jcpPanel.getJChemPaintModel().getControllerModel().getAutoUpdateImplicitHydrogens()){
// HydrogenAdder hydrogenAdder = new HydrogenAdder("org.openscience.cdk.tools.ValencyChecker");
// java.util.Iterator mols = chemFile.getChemSequence(0).getChemModel(0).getMoleculeSet().molecules();
// while (mols.hasNext())
// {
// org.openscience.cdk.interfaces.IMolecule molecule = (IMolecule)mols.next();
// if (molecule != null)
// {
// try{
// hydrogenAdder.addImplicitHydrogensToSatisfyValency(molecule);
// }catch(Exception ex){
// //do nothing
// }
// }
// }
// }
}
public static JChemPaintPanel showInstance(IChemModel chemModel, String title){
JFrame f = new JFrame(title);
chemModel.setID(title);
f.addWindowListener(new JChemPaintPanel.AppCloser());
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
JChemPaintPanel p = new JChemPaintPanel(chemModel,"stable");
f.setPreferredSize(new Dimension(1000,500));
f.add(p);
f.pack();
f.setVisible(true);
return p;
}
}
| false | true | public static void showInstance(File inFile, String type, JChemPaintPanel jcpPanel){
if (!inFile.exists()) {
JOptionPane.showMessageDialog(jcpPanel, "File " + inFile.getPath()
+ " does not exist.");
return;
}
if (type == null) {
type = "unknown";
}
ISimpleChemObjectReader cor = null;
/*
* Have the ReaderFactory determine the file format
*/
try {
ReaderFactory factory = new ReaderFactory();
cor = factory.createReader(new FileReader(inFile));
} catch (IOException ioExc) {
// we do nothing right now and hoe it still works
} catch (Exception exc) {
// we do nothing right now and hoe it still works
}
if (cor == null) {
// try to determine from user's guess
try {
FileInputStream reader = new FileInputStream(inFile);
if (type.equals(JCPFileFilter.cml)
|| type.equals(JCPFileFilter.xml)) {
cor = new CMLReader(reader);
} else if (type.equals(JCPFileFilter.sdf)) {
cor = new MDLV2000Reader(reader);//TODO once merged, egons new reader needs to be used here
} else if (type.equals(JCPFileFilter.mol)) {
cor = new MDLV2000Reader(reader);
} else if (type.equals(JCPFileFilter.inchi)) {
cor = new INChIReader(reader);
} else if (type.equals(JCPFileFilter.rxn)) {
cor = new MDLRXNV2000Reader(reader);
} else if (type.equals(JCPFileFilter.smi)) {
cor = new SMILESReader(reader);
}
} catch (FileNotFoundException exception) {
// we do nothing right now and hoe it still works
}
}
if (cor == null) {
JOptionPane.showMessageDialog(jcpPanel,
"Could not determine file format.");
return;
}
// this takes care of files called .mol, but having several, sdf-style
// entries
if (cor instanceof MDLV2000Reader) {
try {
BufferedReader in = new BufferedReader(new FileReader(inFile));
String line;
while ((line = in.readLine()) != null) {
if (line.equals("$$$$")) {
String message = "It seems you opened a mol or sdf"
+ " file containing several molecules. "
+ "Only the first one will be shown";
JOptionPane.showMessageDialog(jcpPanel, message,
"sdf-like file",
JOptionPane.INFORMATION_MESSAGE);
break;
}
}
} catch (IOException ex) {
// we do nothing - firstly if IO does not work, we should not
// get here, secondly, if only this does not work, don't worry
}
}
String error = null;
ChemModel chemModel = null;
IChemFile chemFile = null;
if (cor.accepts(IChemFile.class)) {
// try to read a ChemFile
try {
chemFile = (IChemFile) cor
.read((IChemObject) new org.openscience.cdk.ChemFile());
if (chemFile == null) {
error = "The object chemFile was empty unexpectedly!";
}
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
if (error != null) {
JOptionPane.showMessageDialog(jcpPanel, error);
return;
}
if (cor.accepts(ChemModel.class)) {
// try to read a ChemModel
try {
chemModel = (ChemModel) cor.read((IChemObject) new ChemModel());
if (chemModel == null) {
error = "The object chemModel was empty unexpectedly!";
}
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
if (error != null) {
JOptionPane.showMessageDialog(jcpPanel, error);
}
if (chemModel == null && chemFile != null) {
chemModel = (ChemModel) chemFile.getChemSequence(0).getChemModel(0);
}
//we remove molecules which are in MoleculeSet as well as in a reaction
List<IAtomContainer> aclist = ReactionSetManipulator.getAllAtomContainers(chemModel.getReactionSet());
for(int i=chemModel.getMoleculeSet().getAtomContainerCount()-1;i>=0;i--){
for(int k=0;k<aclist.size();k++){
if(aclist.get(k)==chemModel.getMoleculeSet().getAtomContainer(i)){
chemModel.getMoleculeSet().removeAtomContainer(i);
break;
}
}
}
// check for bonds
if (ChemModelManipulator.getBondCount(chemModel) == 0) {
error = "Model does not have bonds. Cannot depict contents.";
}
// check for coordinates
JChemPaint.checkCoordinates(chemModel);
//we give all reactions an ID, in case they have none
//IDs are needed for handling in JCP
if(chemModel.getReactionSet()!=null){
int i=0;
for(IReaction reaction : chemModel.getReactionSet().reactions()){
if(reaction.getID()==null)
reaction.setID("Reaction "+(++i));
}
}
JChemPaintPanel p = showInstance(chemModel, inFile.getName());
p.setCurrentWorkDirectory(inFile.getParentFile());
p.setLastOpenedFile(inFile);
p.setIsAlreadyAFile(inFile);
}
| public static void showInstance(File inFile, String type, JChemPaintPanel jcpPanel){
if (!inFile.exists()) {
JOptionPane.showMessageDialog(jcpPanel, "File " + inFile.getPath()
+ " does not exist.");
return;
}
if (type == null) {
type = "unknown";
}
ISimpleChemObjectReader cor = null;
/*
* Have the ReaderFactory determine the file format
*/
try {
ReaderFactory factory = new ReaderFactory();
cor = factory.createReader(new FileReader(inFile));
if(cor instanceof CMLReader)
cor = new CMLReader(inFile.toURI().toString());
} catch (IOException ioExc) {
// we do nothing right now and hoe it still works
} catch (Exception exc) {
// we do nothing right now and hoe it still works
}
if (cor == null) {
// try to determine from user's guess
try {
FileInputStream reader = new FileInputStream(inFile);
if (type.equals(JCPFileFilter.cml)
|| type.equals(JCPFileFilter.xml)) {
cor = new CMLReader(inFile.toURI().toString());
} else if (type.equals(JCPFileFilter.sdf)) {
cor = new MDLV2000Reader(reader);//TODO once merged, egons new reader needs to be used here
} else if (type.equals(JCPFileFilter.mol)) {
cor = new MDLV2000Reader(reader);
} else if (type.equals(JCPFileFilter.inchi)) {
cor = new INChIReader(reader);
} else if (type.equals(JCPFileFilter.rxn)) {
cor = new MDLRXNV2000Reader(reader);
} else if (type.equals(JCPFileFilter.smi)) {
cor = new SMILESReader(reader);
}
} catch (FileNotFoundException exception) {
// we do nothing right now and hoe it still works
}
}
if (cor == null) {
JOptionPane.showMessageDialog(jcpPanel,
"Could not determine file format.");
return;
}
// this takes care of files called .mol, but having several, sdf-style
// entries
if (cor instanceof MDLV2000Reader) {
try {
BufferedReader in = new BufferedReader(new FileReader(inFile));
String line;
while ((line = in.readLine()) != null) {
if (line.equals("$$$$")) {
String message = "It seems you opened a mol or sdf"
+ " file containing several molecules. "
+ "Only the first one will be shown";
JOptionPane.showMessageDialog(jcpPanel, message,
"sdf-like file",
JOptionPane.INFORMATION_MESSAGE);
break;
}
}
} catch (IOException ex) {
// we do nothing - firstly if IO does not work, we should not
// get here, secondly, if only this does not work, don't worry
}
}
String error = null;
ChemModel chemModel = null;
IChemFile chemFile = null;
if (cor.accepts(IChemFile.class)) {
// try to read a ChemFile
try {
chemFile = (IChemFile) cor
.read((IChemObject) new org.openscience.cdk.ChemFile());
if (chemFile == null) {
error = "The object chemFile was empty unexpectedly!";
}
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
if (error != null) {
JOptionPane.showMessageDialog(jcpPanel, error);
return;
}
if (cor.accepts(ChemModel.class)) {
// try to read a ChemModel
try {
chemModel = (ChemModel) cor.read((IChemObject) new ChemModel());
if (chemModel == null) {
error = "The object chemModel was empty unexpectedly!";
}
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
if (error != null) {
JOptionPane.showMessageDialog(jcpPanel, error);
}
if (chemModel == null && chemFile != null) {
chemModel = (ChemModel) chemFile.getChemSequence(0).getChemModel(0);
}
//we remove molecules which are in MoleculeSet as well as in a reaction
if(chemModel.getReactionSet()!=null){
List<IAtomContainer> aclist = ReactionSetManipulator.getAllAtomContainers(chemModel.getReactionSet());
for(int i=chemModel.getMoleculeSet().getAtomContainerCount()-1;i>=0;i--){
for(int k=0;k<aclist.size();k++){
if(aclist.get(k)==chemModel.getMoleculeSet().getAtomContainer(i)){
chemModel.getMoleculeSet().removeAtomContainer(i);
break;
}
}
}
}
// check for bonds
if (ChemModelManipulator.getBondCount(chemModel) == 0) {
error = "Model does not have bonds. Cannot depict contents.";
}
// check for coordinates
JChemPaint.checkCoordinates(chemModel);
//we give all reactions an ID, in case they have none
//IDs are needed for handling in JCP
if(chemModel.getReactionSet()!=null){
int i=0;
for(IReaction reaction : chemModel.getReactionSet().reactions()){
if(reaction.getID()==null)
reaction.setID("Reaction "+(++i));
}
}
JChemPaintPanel p = showInstance(chemModel, inFile.getName());
p.setCurrentWorkDirectory(inFile.getParentFile());
p.setLastOpenedFile(inFile);
p.setIsAlreadyAFile(inFile);
}
|
diff --git a/tool/src/java/org/sakaiproject/evaluation/tool/producers/ModifyTemplateItemsProducer.java b/tool/src/java/org/sakaiproject/evaluation/tool/producers/ModifyTemplateItemsProducer.java
index 5d5f9028..6e90289b 100644
--- a/tool/src/java/org/sakaiproject/evaluation/tool/producers/ModifyTemplateItemsProducer.java
+++ b/tool/src/java/org/sakaiproject/evaluation/tool/producers/ModifyTemplateItemsProducer.java
@@ -1,518 +1,518 @@
/******************************************************************************
* TemplateModifyProducer.java - created on Aug 21, 2006
*
* Copyright (c) 2007 Virginia Polytechnic Institute and State University
* Licensed under the Educational Community License version 1.0
*
* A copy of the Educational Community License has been included in this
* distribution and is available at: http://www.opensource.org/licenses/ecl1.php
*
* Contributors:
* Aaron Zeckoski ([email protected])
* Antranig Basman ([email protected])
* Rui Feng ([email protected])
* Kapil Ahuja ([email protected])
*****************************************************************************/
package org.sakaiproject.evaluation.tool.producers;
import java.util.ArrayList;
import java.util.List;
import org.sakaiproject.evaluation.constant.EvalConstants;
import org.sakaiproject.evaluation.logic.EvalAuthoringService;
import org.sakaiproject.evaluation.logic.EvalCommonLogic;
import org.sakaiproject.evaluation.logic.EvalEvaluationService;
import org.sakaiproject.evaluation.logic.EvalSettings;
import org.sakaiproject.evaluation.logic.externals.ExternalHierarchyLogic;
import org.sakaiproject.evaluation.logic.model.EvalHierarchyNode;
import org.sakaiproject.evaluation.logic.model.EvalUser;
import org.sakaiproject.evaluation.model.EvalTemplate;
import org.sakaiproject.evaluation.model.EvalTemplateItem;
import org.sakaiproject.evaluation.tool.EvalToolConstants;
import org.sakaiproject.evaluation.tool.LocalTemplateLogic;
import org.sakaiproject.evaluation.tool.renderers.AddItemControlRenderer;
import org.sakaiproject.evaluation.tool.utils.RenderingUtils;
import org.sakaiproject.evaluation.tool.viewparams.BlockIdsParameters;
import org.sakaiproject.evaluation.tool.viewparams.EvalViewParameters;
import org.sakaiproject.evaluation.tool.viewparams.ItemViewParameters;
import org.sakaiproject.evaluation.tool.viewparams.TemplateItemViewParameters;
import org.sakaiproject.evaluation.tool.viewparams.TemplateViewParameters;
import org.sakaiproject.evaluation.utils.TemplateItemUtils;
import org.sakaiproject.util.FormattedText;
import uk.org.ponder.messageutil.MessageLocator;
import uk.org.ponder.rsf.components.UIBoundBoolean;
import uk.org.ponder.rsf.components.UIBranchContainer;
import uk.org.ponder.rsf.components.UICommand;
import uk.org.ponder.rsf.components.UIContainer;
import uk.org.ponder.rsf.components.UIELBinding;
import uk.org.ponder.rsf.components.UIForm;
import uk.org.ponder.rsf.components.UIInput;
import uk.org.ponder.rsf.components.UIInternalLink;
import uk.org.ponder.rsf.components.UILink;
import uk.org.ponder.rsf.components.UIMessage;
import uk.org.ponder.rsf.components.UIOutput;
import uk.org.ponder.rsf.components.UISelect;
import uk.org.ponder.rsf.components.UIVerbatim;
import uk.org.ponder.rsf.components.decorators.DecoratorList;
import uk.org.ponder.rsf.components.decorators.UIFreeAttributeDecorator;
import uk.org.ponder.rsf.components.decorators.UIIDStrategyDecorator;
import uk.org.ponder.rsf.components.decorators.UILabelTargetDecorator;
import uk.org.ponder.rsf.components.decorators.UIStyleDecorator;
import uk.org.ponder.rsf.components.decorators.UITooltipDecorator;
import uk.org.ponder.rsf.view.ComponentChecker;
import uk.org.ponder.rsf.view.ViewComponentProducer;
import uk.org.ponder.rsf.viewstate.SimpleViewParameters;
import uk.org.ponder.rsf.viewstate.ViewParameters;
import uk.org.ponder.rsf.viewstate.ViewParamsReporter;
/**
* This is the main page for handling various operations to template, items,
*
* @author Aaron Zeckoski ([email protected])
* @author Antranig Basman ([email protected])
*/
public class ModifyTemplateItemsProducer implements ViewComponentProducer, ViewParamsReporter {
public static final String VIEW_ID = "modify_template_items"; //$NON-NLS-1$
public String getViewID() {
return VIEW_ID;
}
private LocalTemplateLogic localTemplateLogic;
public void setLocalTemplateLogic(LocalTemplateLogic localTemplateLogic) {
this.localTemplateLogic = localTemplateLogic;
}
private EvalCommonLogic commonLogic;
public void setCommonLogic(EvalCommonLogic commonLogic) {
this.commonLogic = commonLogic;
}
private EvalEvaluationService evaluationService;
public void setEvaluationService(EvalEvaluationService evaluationService) {
this.evaluationService = evaluationService;
}
private EvalAuthoringService authoringService;
public void setAuthoringService(EvalAuthoringService authoringService) {
this.authoringService = authoringService;
}
private AddItemControlRenderer addItemControlRenderer;
public void setAddItemControlRenderer(AddItemControlRenderer addItemControlRenderer) {
this.addItemControlRenderer = addItemControlRenderer;
}
private EvalSettings evalSettings;
public void setEvalSettings(EvalSettings settings) {
this.evalSettings = settings;
}
private ExternalHierarchyLogic hierarchyLogic;
public void setExternalHierarchyLogic(ExternalHierarchyLogic logic) {
this.hierarchyLogic = logic;
}
private MessageLocator messageLocator;
public void setMessageLocator(MessageLocator messageLocator) {
this.messageLocator = messageLocator;
}
/*
* 1) access this page through "Continue and Add Questions" button on Template
* page 2) access this page through links on Control Panel or other 3) access
* this page through "Save" button on Template page
*/
public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
// local variables used in the render logic
String currentUserId = commonLogic.getCurrentUserId();
boolean userAdmin = commonLogic.isUserAdmin(currentUserId);
boolean createTemplate = authoringService.canCreateTemplate(currentUserId);
boolean beginEvaluation = evaluationService.canBeginEvaluation(currentUserId);
TemplateViewParameters evalViewParams = (TemplateViewParameters) viewparams;
Long templateId = evalViewParams.templateId;
EvalTemplate template = localTemplateLogic.fetchTemplate(templateId);
/*
* top links here
*/
UIInternalLink.make(tofill, "summary-link",
UIMessage.make("summary.page.title"),
new SimpleViewParameters(SummaryProducer.VIEW_ID));
if (userAdmin) {
UIInternalLink.make(tofill, "administrate-link",
UIMessage.make("administrate.page.title"),
new SimpleViewParameters(AdministrateProducer.VIEW_ID));
}
if (createTemplate
|| authoringService.canModifyTemplate(currentUserId, templateId)) {
UIInternalLink.make(tofill, "control-templates-link",
UIMessage.make("controltemplates.page.title"),
new SimpleViewParameters(ControlTemplatesProducer.VIEW_ID));
UIInternalLink.make(tofill, "control-items-link",
UIMessage.make("controlitems.page.title"),
new SimpleViewParameters(ControlItemsProducer.VIEW_ID));
} else {
throw new SecurityException("User attempted to access " +
VIEW_ID + " when they are not allowed");
}
if (beginEvaluation) {
UIInternalLink.make(tofill, "control-evaluations-link",
UIMessage.make("controlevaluations.page.title"),
new SimpleViewParameters(ControlEvaluationsProducer.VIEW_ID));
}
if (userAdmin) {
UIInternalLink.make(tofill, "control-scales-link",
UIMessage.make("controlscales.page.title"),
new SimpleViewParameters(ControlScalesProducer.VIEW_ID));
}
// begin page rendering
UIOutput.make(tofill, "site-id", commonLogic.getContentCollectionId(commonLogic.getCurrentEvalGroup()));
UIMessage.make(tofill, "modify-template-title", "modifytemplate.page.title");
UIInternalLink.make(tofill, "preview_eval_link", UIMessage.make("modifytemplate.preview.eval.link"),
new EvalViewParameters(PreviewEvalProducer.VIEW_ID, null, templateId))
.decorate( new UITooltipDecorator( UIMessage.make("modifytemplate.preview.eval.link.title") ) );
UIMessage.make(tofill, "preview-eval-desc", "modifytemplate.preview.eval.desc");
UILink.make(tofill, "preview-template-direct-link", UIMessage.make("general.direct.link"),
commonLogic.getEntityURL(template) )
.decorate( new UITooltipDecorator( UIMessage.make("general.direct.link.title") ) );
// get form to submit the type of item to create to the correct view
UIMessage.make(tofill, "add-item-note", "modifytemplate.add.item.note");
// create the choices for the pulldown
ArrayList<ViewParameters> templateItemVPList = new ArrayList<ViewParameters>();
ArrayList<String> templateItemLabelList = new ArrayList<String>();
for (int i = 0; i < EvalToolConstants.ITEM_SELECT_CLASSIFICATION_VALUES.length; i++) {
templateItemVPList.add( new ItemViewParameters(ModifyItemProducer.VIEW_ID,
EvalToolConstants.ITEM_SELECT_CLASSIFICATION_VALUES[i], templateId) );
templateItemLabelList.add(EvalToolConstants.ITEM_SELECT_CLASSIFICATION_LABELS[i]);
}
// add in existing items selection
templateItemVPList.add( new TemplateItemViewParameters(ExistingItemsProducer.VIEW_ID, templateId, null) );
templateItemLabelList.add("item.classification.existing");
// add in expert items choice if enabled
Boolean useExpertItems = (Boolean) evalSettings.get(EvalSettings.USE_EXPERT_ITEMS);
if (useExpertItems) {
templateItemVPList.add( new TemplateItemViewParameters(ExpertCategoryProducer.VIEW_ID, templateId, null) );
templateItemLabelList.add("item.classification.expert");
}
EvalUser TempOwner = commonLogic.getEvalUserById( template.getOwner() );
UIOutput.make(tofill, "template-owner", TempOwner.displayName );
addItemControlRenderer.renderControl(tofill, "add-item-control:",
templateItemVPList.toArray(new ViewParameters[templateItemVPList.size()]),
templateItemLabelList.toArray(new String[templateItemLabelList.size()]),
UIMessage.make("modifytemplate.add.item.button"), templateId);
List<EvalTemplateItem> itemList = localTemplateLogic.fetchTemplateItems(templateId);
List<EvalTemplateItem> templateItemsList = TemplateItemUtils.getNonChildItems(itemList);
if (templateItemsList.isEmpty()) {
UIMessage.make(tofill, "begin-eval-dummylink", "modifytemplate.begin.eval.link");
} else {
UIInternalLink evalLink = UIInternalLink.make(tofill, "begin_eval_link", UIMessage.make("modifytemplate.begin.eval.link"),
new EvalViewParameters(EvaluationCreateProducer.VIEW_ID, null, templateId));
evalLink.decorators = new DecoratorList( new UITooltipDecorator(UIMessage.make("modifytemplate.begin.eval.link.title")));
}
// TODO - this should be the actual level and not some made up string
String currentLevel = "Current";
UIMessage.make(tofill, "level-header-level", "modifytemplate.level.header.level",
new String[] {currentLevel});
UIOutput.make(tofill, "level-header-number", new Integer(templateItemsList.size()).toString() );
UIMessage.make(tofill, "level-header-items", "modifytemplate.level.header.items");
UIMessage.make(tofill, "template-title-header", "modifytemplate.template.title.header");
UIOutput.make(tofill, "title", template.getTitle());
UIInternalLink.make(tofill, "modify_title_desc_link", UIMessage.make("modifytemplate.modify.title.desc.link"),
new TemplateViewParameters(ModifyTemplateProducer.VIEW_ID, templateId)).decorators =
new DecoratorList(new UITooltipDecorator(UIMessage.make("modifytemplate.modify.title.desc.link.title")));
if (template.getDescription() != null && !template.getDescription().trim().equals("")) {
UIBranchContainer descbranch = UIBranchContainer.make(tofill, "description-switch:");
UIMessage.make(descbranch, "description-header", "modifytemplate.description.header");
UIOutput.make(descbranch, "description", template.getDescription());
}
UIForm form2 = UIForm.make(tofill, "modifyFormRows");
UICommand.make(form2, "hiddenBtn");
form2.parameters.add(new UIELBinding("#{templateBBean.templateId}", templateId));
UIMessage revertOrderButton = UIMessage.make(form2, "revertOrderButton", "modifytemplate.button.revert.order");
revertOrderButton.decorators = new DecoratorList( new UITooltipDecorator( UIMessage.make("modifytemplate.button.revert.order.title") ) );
UICommand saveReorderButton = UICommand.make(form2, "saveReorderButton",
UIMessage.make("modifytemplate.button.save.order"), "#{templateBBean.saveReorder}");
saveReorderButton.parameters.add(new UIELBinding("#{templateBBean.templateId}", templateId));
saveReorderButton.decorators = new DecoratorList( new UITooltipDecorator( UIMessage.make("modifytemplate.button.save.order.title") ) );
UIMessage.make(form2, "orderingInstructions", "modifytemplate.instructions.reorder");
String sCurItemNum = null;
int blockChildNum = 0;
if ((templateItemsList != null) && (templateItemsList.size() > 0)) {
String templateItemOTPBinding = null;
String templateItemOTP = null;
String[] itemNumArr = new String[templateItemsList.size()];
for (int h = 0; h < templateItemsList.size(); h++) {
itemNumArr[h] = Integer.toString(h + 1);
}
for (int i = 0; i < templateItemsList.size(); i++) {
EvalTemplateItem templateItem = (EvalTemplateItem) templateItemsList.get(i);
sCurItemNum = Integer.toString(i);
templateItemOTPBinding = "templateItemWBL." + templateItem.getId();
templateItemOTP = templateItemOTPBinding + ".";
UIBranchContainer itemBranch = UIBranchContainer.make(form2, "item-row:", sCurItemNum);
// Add item type and id to item tag only if this is a block item
if ( templateItem.getItem().getClassification().equals(EvalConstants.ITEM_TYPE_BLOCK_PARENT) ){
itemBranch.decorate( new UIFreeAttributeDecorator("name", EvalConstants.ITEM_TYPE_BLOCK_PARENT.toLowerCase() + "-" +templateItem.getId() ) );
}
// hidden item num
UIInput.make(itemBranch, "hidden-item-num", templateItemOTP + "displayOrder", sCurItemNum);
UIOutput.make(itemBranch, "template-item-id", templateItem.getId() + "");
// only show Block Check box for scaled and block parents
if ( templateItem.getItem().getClassification().equals(EvalConstants.ITEM_TYPE_SCALED) ||
templateItem.getItem().getClassification().equals(EvalConstants.ITEM_TYPE_BLOCK_PARENT) ) {
UIOutput checkBranch = UIOutput.make(itemBranch, "block-check-branch");
UIBoundBoolean blockCB = UIBoundBoolean.make(itemBranch, "block-checkbox", Boolean.FALSE);
// we have to force the id so the JS block checking can work
String name = "block-" + templateItem.getItem().getScale().getId() + "-" + templateItem.getId();
blockCB.decorators = new DecoratorList( new UIIDStrategyDecorator(name) );
// have to force the target id so that the label for works
UILabelTargetDecorator uild = new UILabelTargetDecorator(blockCB);
uild.targetFullID = name;
checkBranch.decorators = new DecoratorList( uild );
// tooltip
blockCB.decorators.add( new UITooltipDecorator( UIMessage.make("modifytemplate.item.checkbox.title") ) );
UIMessage.make(itemBranch, "check-input-label", "modifytemplate.check.label.title");
} else {
UIMessage.make(itemBranch, "check-placeholder", "modifytemplate.check.placeholder");
}
String itemLabelKey = EvalToolConstants.UNKNOWN_KEY;
for (int j = 0; j < EvalToolConstants.ITEM_CLASSIFICATION_VALUES.length; j++) {
if (templateItem.getItem().getClassification().equals(EvalToolConstants.ITEM_CLASSIFICATION_VALUES[j])) {
itemLabelKey = EvalToolConstants.ITEM_CLASSIFICATION_LABELS_PROPS[j];
break;
}
}
UIMessage.make(itemBranch, "item-classification", itemLabelKey);
if (templateItem.getScaleDisplaySetting() != null) {
String scaleDisplaySettingLabel = " - " + templateItem.getScaleDisplaySetting();
UIOutput.make(itemBranch, "scale-display", scaleDisplaySettingLabel);
}
if (templateItem.getCategory() != null && ! EvalConstants.ITEM_CATEGORY_COURSE.equals(templateItem.getCategory())){
String[] category = new String[] { messageLocator.getMessage( RenderingUtils.getCategoryLabelKey(templateItem.getCategory()) ) };
UIMessage.make(itemBranch, "item-category", "modifytemplate.item.category.title", category)
.decorate(new UITooltipDecorator(UIMessage.make("modifytemplate.item.category.tooltip", category)));
}
UIInternalLink.make(itemBranch, "preview-row-item",
new ItemViewParameters(PreviewItemProducer.VIEW_ID, (Long) null, templateItem.getId()) )
.decorate(new UITooltipDecorator(UIMessage.make("modifytemplate.item.preview")));
if ((templateItem.getBlockParent() != null) && (templateItem.getBlockParent().booleanValue() == true)) {
// if it is a block item
BlockIdsParameters target = new BlockIdsParameters(ModifyBlockProducer.VIEW_ID, templateId, templateItem.getId().toString());
UIInternalLink.make(itemBranch, "modify-row-item", target)
.decorate(new UITooltipDecorator(UIMessage.make("modifytemplate.item.edit")));
} else {
//it is a non-block item
ViewParameters target = new ItemViewParameters(ModifyItemProducer.VIEW_ID,
templateItem.getItem().getClassification(), templateId, templateItem.getId());
UIInternalLink.make(itemBranch, "modify-row-item", target)
.decorate(new UITooltipDecorator(UIMessage.make("modifytemplate.item.edit")));
}
if(TemplateItemUtils.isBlockParent(templateItem)){
- UIInternalLink unblockItem = UIInternalLink.make(itemBranch, "remove-row-item-unblock", UIMessage.make("modifytemplate.group.upgroup"),
+ UIInternalLink unblockItem = UIInternalLink.make(itemBranch, "remove-row-item-unblock", UIMessage.make("modifytemplate.group.ungroup"),
new ItemViewParameters(RemoveItemProducer.VIEW_ID, (Long)null, templateItem.getId(), templateId) );
unblockItem.decorate(new UIFreeAttributeDecorator("templateItemId", templateItem.getId().toString()));
unblockItem.decorate(new UIFreeAttributeDecorator("templateId", templateId.toString()));
unblockItem.decorate(new UIFreeAttributeDecorator("OTP", templateItemOTPBinding));
}
else{
UIInternalLink removeItem = UIInternalLink.make(itemBranch, "remove-row-item",
new ItemViewParameters(RemoveItemProducer.VIEW_ID, (Long)null, templateItem.getId(), templateId) );
removeItem.decorate(new UIFreeAttributeDecorator("templateItemId", templateItem.getId().toString()));
removeItem.decorate(new UIFreeAttributeDecorator("templateId", templateId.toString()));
removeItem.decorate(new UIFreeAttributeDecorator("OTP", templateItemOTPBinding));
removeItem.decorate(new UITooltipDecorator(UIMessage.make("modifytemplate.item.delete")));
}
// SECOND LINE
UISelect orderPulldown = UISelect.make(itemBranch, "item-select", itemNumArr, templateItemOTP + "displayOrder", null);
orderPulldown.decorators = new DecoratorList( new UITooltipDecorator( UIMessage.make("modifytemplate.select.order.title") ) );
String formattedText = FormattedText.convertFormattedTextToPlaintext(templateItem.getItem().getItemText());
UIBranchContainer branchText = UIBranchContainer.make(itemBranch, "item-text:");
UIBranchContainer branchTextHidden = UIBranchContainer.make(itemBranch, "item-text-hidden:");
UIVerbatim itemText = null;
if(formattedText.length() < 150){
itemText = UIVerbatim.make(branchText, "item-text-short", formattedText);
}else{
itemText = UIVerbatim.make(branchText, "item-text-short", formattedText.substring(0, 150));
UIOutput.make(branchText, "item-text-control");
UIVerbatim.make(branchTextHidden, "item-text-long", formattedText);
UIOutput.make(branchTextHidden, "item-text-hidden-control");
}
if(TemplateItemUtils.isBlockParent(templateItem)){
itemText.decorators = new DecoratorList(new UIStyleDecorator("itemBlockRow"));
UIOutput.make(branchText, "item-text-block");
}
/* Hierarchy Messages
* Only Display these if they are enabled in the preferences.
*/
Boolean showHierarchy = (Boolean) evalSettings.get(EvalSettings.DISPLAY_HIERARCHY_OPTIONS);
if ( showHierarchy ) {
/* Don't show the Node Id icon if it's a top level item */
if (!templateItem.getHierarchyLevel().equals(EvalConstants.HIERARCHY_LEVEL_TOP)) {
EvalHierarchyNode curnode = hierarchyLogic.getNodeById(templateItem.getHierarchyNodeId());
UILink.make(itemBranch, "item-hierarchy")
.decorate( new UITooltipDecorator( messageLocator.getMessage("modifytemplate.item.hierarchy.nodeid.title") + curnode.title ));
}
}
Boolean useResultsSharing = (Boolean) evalSettings.get(EvalSettings.ITEM_USE_RESULTS_SHARING);
if ( useResultsSharing ) {
// only show results sharing if it is being used
String resultsSharingMessage = "unknown.caps";
if ( EvalConstants.SHARING_PUBLIC.equals(templateItem.getResultsSharing()) ) {
resultsSharingMessage = "general.public";
} else if ( EvalConstants.SHARING_PRIVATE.equals(templateItem.getResultsSharing()) ) {
resultsSharingMessage = "general.private";
}
UIMessage.make(itemBranch, "item-results-sharing", resultsSharingMessage);
}
if ( EvalConstants.ITEM_TYPE_SCALED.equals(templateItem.getItem().getClassification()) &&
templateItem.getItem().getScale() != null ) {
// only show the scale type of this is a scaled item
UIMessage.make(itemBranch, "item-scale-type-title", "modifytemplate.item.scale.type.title");
UIOutput.make(itemBranch, "scale-type", templateItem.getItem().getScale().getTitle());
}
// display item options
boolean showOptions = false;
if ( templateItem.getUsesNA() != null
&& templateItem.getUsesNA() ) {
UIMessage.make(itemBranch, "item-na-enabled", "modifytemplate.item.na.note");
showOptions = true;
}
if ( templateItem.getUsesComment() != null
&& templateItem.getUsesComment() ) {
UIMessage.make(itemBranch, "item-comment-enabled", "modifytemplate.item.comment.note");
showOptions = true;
}
if (showOptions) {
UIMessage.make(itemBranch, "item-options", "modifytemplate.item.options");
}
// block child items
if ( TemplateItemUtils.isBlockParent(templateItem) ) {
List<EvalTemplateItem> childList = TemplateItemUtils.getChildItems(itemList, templateItem.getId());
if (childList.size() > 0) {
UIBranchContainer blockChildren = UIBranchContainer.make(itemBranch, "block-children:", Integer.toString(blockChildNum));
UIMessage.make(itemBranch, "modifyblock-items-list-instructions",
"modifyblock.page.instructions");
blockChildNum++;
int orderNo = 0;
// iterate through block children for the current block parent and emit each child item
for (int j = 0; j < childList.size(); j++) {
EvalTemplateItem child = (EvalTemplateItem) childList.get(j);
emitItem(itemBranch, child, orderNo + 1, templateId, templateItemOTPBinding);
orderNo++;
}
for (int k = 0; k < childList.size(); k++) {
EvalTemplateItem child = childList.get(k);
UIBranchContainer childRow = UIBranchContainer.make(blockChildren, "child-item:", k+"");
UIOutput.make(childRow, "child-item-num", child.getDisplayOrder().toString());
UIVerbatim.make(childRow, "child-item-text", child.getItem().getItemText());
}
} else {
throw new IllegalStateException("Block parent with no items in it, id=" + templateItem.getId());
}
}
}
}
//this outputs the total number of rows
UIVerbatim.make(tofill, "total-rows", (sCurItemNum + 1));
// the create block form
UIForm blockForm = UIForm.make(tofill, "createBlockForm",
new BlockIdsParameters(ModifyBlockProducer.VIEW_ID, templateId, null));
UICommand createBlock = UICommand.make(blockForm, "createBlockBtn", UIMessage.make("modifytemplate.button.createblock") );
createBlock.decorators = new DecoratorList( new UITooltipDecorator( UIMessage.make("modifytemplate.button.createblock.title") ) );
UIMessage.make(form2, "blockInstructions", "modifytemplate.instructions.block");
}
/**
* @param tofill
* @param templateItem
* @param index
* @param templateItemOTPBinding
* @param templateId
*/
private void emitItem(UIContainer tofill, EvalTemplateItem templateItem, int index, Long templateId, String templateItemOTPBinding ) {
UIBranchContainer radiobranch = UIBranchContainer.make(tofill,
"itemRowBlock:", templateItem.getId().toString()); //$NON-NLS-1$
UIOutput.make(radiobranch, "hidden-item-id", templateItem.getId().toString());
UIOutput.make(radiobranch, "item-block-num", Integer.toString(index));
UIVerbatim.make(radiobranch, "item-block-text", FormattedText.convertFormattedTextToPlaintext(templateItem.getItem().getItemText()));
UIInternalLink removeChildItem = UIInternalLink.make(radiobranch, "child-remove-item",
new ItemViewParameters(RemoveItemProducer.VIEW_ID, (Long)null, templateItem.getId(), templateId) );
removeChildItem.decorate(new UIFreeAttributeDecorator("templateItemId", templateItem.getId().toString()));
removeChildItem.decorate(new UIFreeAttributeDecorator("templateId", templateId.toString()));
removeChildItem.decorate(new UIFreeAttributeDecorator("OTP", templateItemOTPBinding));
removeChildItem.decorate(new UITooltipDecorator(UIMessage.make("modifytemplate.item.delete")));
}
/* (non-Javadoc)
* @see uk.org.ponder.rsf.viewstate.ViewParamsReporter#getViewParameters()
*/
public ViewParameters getViewParameters() {
return new TemplateViewParameters();
}
}
| true | true | public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
// local variables used in the render logic
String currentUserId = commonLogic.getCurrentUserId();
boolean userAdmin = commonLogic.isUserAdmin(currentUserId);
boolean createTemplate = authoringService.canCreateTemplate(currentUserId);
boolean beginEvaluation = evaluationService.canBeginEvaluation(currentUserId);
TemplateViewParameters evalViewParams = (TemplateViewParameters) viewparams;
Long templateId = evalViewParams.templateId;
EvalTemplate template = localTemplateLogic.fetchTemplate(templateId);
/*
* top links here
*/
UIInternalLink.make(tofill, "summary-link",
UIMessage.make("summary.page.title"),
new SimpleViewParameters(SummaryProducer.VIEW_ID));
if (userAdmin) {
UIInternalLink.make(tofill, "administrate-link",
UIMessage.make("administrate.page.title"),
new SimpleViewParameters(AdministrateProducer.VIEW_ID));
}
if (createTemplate
|| authoringService.canModifyTemplate(currentUserId, templateId)) {
UIInternalLink.make(tofill, "control-templates-link",
UIMessage.make("controltemplates.page.title"),
new SimpleViewParameters(ControlTemplatesProducer.VIEW_ID));
UIInternalLink.make(tofill, "control-items-link",
UIMessage.make("controlitems.page.title"),
new SimpleViewParameters(ControlItemsProducer.VIEW_ID));
} else {
throw new SecurityException("User attempted to access " +
VIEW_ID + " when they are not allowed");
}
if (beginEvaluation) {
UIInternalLink.make(tofill, "control-evaluations-link",
UIMessage.make("controlevaluations.page.title"),
new SimpleViewParameters(ControlEvaluationsProducer.VIEW_ID));
}
if (userAdmin) {
UIInternalLink.make(tofill, "control-scales-link",
UIMessage.make("controlscales.page.title"),
new SimpleViewParameters(ControlScalesProducer.VIEW_ID));
}
// begin page rendering
UIOutput.make(tofill, "site-id", commonLogic.getContentCollectionId(commonLogic.getCurrentEvalGroup()));
UIMessage.make(tofill, "modify-template-title", "modifytemplate.page.title");
UIInternalLink.make(tofill, "preview_eval_link", UIMessage.make("modifytemplate.preview.eval.link"),
new EvalViewParameters(PreviewEvalProducer.VIEW_ID, null, templateId))
.decorate( new UITooltipDecorator( UIMessage.make("modifytemplate.preview.eval.link.title") ) );
UIMessage.make(tofill, "preview-eval-desc", "modifytemplate.preview.eval.desc");
UILink.make(tofill, "preview-template-direct-link", UIMessage.make("general.direct.link"),
commonLogic.getEntityURL(template) )
.decorate( new UITooltipDecorator( UIMessage.make("general.direct.link.title") ) );
// get form to submit the type of item to create to the correct view
UIMessage.make(tofill, "add-item-note", "modifytemplate.add.item.note");
// create the choices for the pulldown
ArrayList<ViewParameters> templateItemVPList = new ArrayList<ViewParameters>();
ArrayList<String> templateItemLabelList = new ArrayList<String>();
for (int i = 0; i < EvalToolConstants.ITEM_SELECT_CLASSIFICATION_VALUES.length; i++) {
templateItemVPList.add( new ItemViewParameters(ModifyItemProducer.VIEW_ID,
EvalToolConstants.ITEM_SELECT_CLASSIFICATION_VALUES[i], templateId) );
templateItemLabelList.add(EvalToolConstants.ITEM_SELECT_CLASSIFICATION_LABELS[i]);
}
// add in existing items selection
templateItemVPList.add( new TemplateItemViewParameters(ExistingItemsProducer.VIEW_ID, templateId, null) );
templateItemLabelList.add("item.classification.existing");
// add in expert items choice if enabled
Boolean useExpertItems = (Boolean) evalSettings.get(EvalSettings.USE_EXPERT_ITEMS);
if (useExpertItems) {
templateItemVPList.add( new TemplateItemViewParameters(ExpertCategoryProducer.VIEW_ID, templateId, null) );
templateItemLabelList.add("item.classification.expert");
}
EvalUser TempOwner = commonLogic.getEvalUserById( template.getOwner() );
UIOutput.make(tofill, "template-owner", TempOwner.displayName );
addItemControlRenderer.renderControl(tofill, "add-item-control:",
templateItemVPList.toArray(new ViewParameters[templateItemVPList.size()]),
templateItemLabelList.toArray(new String[templateItemLabelList.size()]),
UIMessage.make("modifytemplate.add.item.button"), templateId);
List<EvalTemplateItem> itemList = localTemplateLogic.fetchTemplateItems(templateId);
List<EvalTemplateItem> templateItemsList = TemplateItemUtils.getNonChildItems(itemList);
if (templateItemsList.isEmpty()) {
UIMessage.make(tofill, "begin-eval-dummylink", "modifytemplate.begin.eval.link");
} else {
UIInternalLink evalLink = UIInternalLink.make(tofill, "begin_eval_link", UIMessage.make("modifytemplate.begin.eval.link"),
new EvalViewParameters(EvaluationCreateProducer.VIEW_ID, null, templateId));
evalLink.decorators = new DecoratorList( new UITooltipDecorator(UIMessage.make("modifytemplate.begin.eval.link.title")));
}
// TODO - this should be the actual level and not some made up string
String currentLevel = "Current";
UIMessage.make(tofill, "level-header-level", "modifytemplate.level.header.level",
new String[] {currentLevel});
UIOutput.make(tofill, "level-header-number", new Integer(templateItemsList.size()).toString() );
UIMessage.make(tofill, "level-header-items", "modifytemplate.level.header.items");
UIMessage.make(tofill, "template-title-header", "modifytemplate.template.title.header");
UIOutput.make(tofill, "title", template.getTitle());
UIInternalLink.make(tofill, "modify_title_desc_link", UIMessage.make("modifytemplate.modify.title.desc.link"),
new TemplateViewParameters(ModifyTemplateProducer.VIEW_ID, templateId)).decorators =
new DecoratorList(new UITooltipDecorator(UIMessage.make("modifytemplate.modify.title.desc.link.title")));
if (template.getDescription() != null && !template.getDescription().trim().equals("")) {
UIBranchContainer descbranch = UIBranchContainer.make(tofill, "description-switch:");
UIMessage.make(descbranch, "description-header", "modifytemplate.description.header");
UIOutput.make(descbranch, "description", template.getDescription());
}
UIForm form2 = UIForm.make(tofill, "modifyFormRows");
UICommand.make(form2, "hiddenBtn");
form2.parameters.add(new UIELBinding("#{templateBBean.templateId}", templateId));
UIMessage revertOrderButton = UIMessage.make(form2, "revertOrderButton", "modifytemplate.button.revert.order");
revertOrderButton.decorators = new DecoratorList( new UITooltipDecorator( UIMessage.make("modifytemplate.button.revert.order.title") ) );
UICommand saveReorderButton = UICommand.make(form2, "saveReorderButton",
UIMessage.make("modifytemplate.button.save.order"), "#{templateBBean.saveReorder}");
saveReorderButton.parameters.add(new UIELBinding("#{templateBBean.templateId}", templateId));
saveReorderButton.decorators = new DecoratorList( new UITooltipDecorator( UIMessage.make("modifytemplate.button.save.order.title") ) );
UIMessage.make(form2, "orderingInstructions", "modifytemplate.instructions.reorder");
String sCurItemNum = null;
int blockChildNum = 0;
if ((templateItemsList != null) && (templateItemsList.size() > 0)) {
String templateItemOTPBinding = null;
String templateItemOTP = null;
String[] itemNumArr = new String[templateItemsList.size()];
for (int h = 0; h < templateItemsList.size(); h++) {
itemNumArr[h] = Integer.toString(h + 1);
}
for (int i = 0; i < templateItemsList.size(); i++) {
EvalTemplateItem templateItem = (EvalTemplateItem) templateItemsList.get(i);
sCurItemNum = Integer.toString(i);
templateItemOTPBinding = "templateItemWBL." + templateItem.getId();
templateItemOTP = templateItemOTPBinding + ".";
UIBranchContainer itemBranch = UIBranchContainer.make(form2, "item-row:", sCurItemNum);
// Add item type and id to item tag only if this is a block item
if ( templateItem.getItem().getClassification().equals(EvalConstants.ITEM_TYPE_BLOCK_PARENT) ){
itemBranch.decorate( new UIFreeAttributeDecorator("name", EvalConstants.ITEM_TYPE_BLOCK_PARENT.toLowerCase() + "-" +templateItem.getId() ) );
}
// hidden item num
UIInput.make(itemBranch, "hidden-item-num", templateItemOTP + "displayOrder", sCurItemNum);
UIOutput.make(itemBranch, "template-item-id", templateItem.getId() + "");
// only show Block Check box for scaled and block parents
if ( templateItem.getItem().getClassification().equals(EvalConstants.ITEM_TYPE_SCALED) ||
templateItem.getItem().getClassification().equals(EvalConstants.ITEM_TYPE_BLOCK_PARENT) ) {
UIOutput checkBranch = UIOutput.make(itemBranch, "block-check-branch");
UIBoundBoolean blockCB = UIBoundBoolean.make(itemBranch, "block-checkbox", Boolean.FALSE);
// we have to force the id so the JS block checking can work
String name = "block-" + templateItem.getItem().getScale().getId() + "-" + templateItem.getId();
blockCB.decorators = new DecoratorList( new UIIDStrategyDecorator(name) );
// have to force the target id so that the label for works
UILabelTargetDecorator uild = new UILabelTargetDecorator(blockCB);
uild.targetFullID = name;
checkBranch.decorators = new DecoratorList( uild );
// tooltip
blockCB.decorators.add( new UITooltipDecorator( UIMessage.make("modifytemplate.item.checkbox.title") ) );
UIMessage.make(itemBranch, "check-input-label", "modifytemplate.check.label.title");
} else {
UIMessage.make(itemBranch, "check-placeholder", "modifytemplate.check.placeholder");
}
String itemLabelKey = EvalToolConstants.UNKNOWN_KEY;
for (int j = 0; j < EvalToolConstants.ITEM_CLASSIFICATION_VALUES.length; j++) {
if (templateItem.getItem().getClassification().equals(EvalToolConstants.ITEM_CLASSIFICATION_VALUES[j])) {
itemLabelKey = EvalToolConstants.ITEM_CLASSIFICATION_LABELS_PROPS[j];
break;
}
}
UIMessage.make(itemBranch, "item-classification", itemLabelKey);
if (templateItem.getScaleDisplaySetting() != null) {
String scaleDisplaySettingLabel = " - " + templateItem.getScaleDisplaySetting();
UIOutput.make(itemBranch, "scale-display", scaleDisplaySettingLabel);
}
if (templateItem.getCategory() != null && ! EvalConstants.ITEM_CATEGORY_COURSE.equals(templateItem.getCategory())){
String[] category = new String[] { messageLocator.getMessage( RenderingUtils.getCategoryLabelKey(templateItem.getCategory()) ) };
UIMessage.make(itemBranch, "item-category", "modifytemplate.item.category.title", category)
.decorate(new UITooltipDecorator(UIMessage.make("modifytemplate.item.category.tooltip", category)));
}
UIInternalLink.make(itemBranch, "preview-row-item",
new ItemViewParameters(PreviewItemProducer.VIEW_ID, (Long) null, templateItem.getId()) )
.decorate(new UITooltipDecorator(UIMessage.make("modifytemplate.item.preview")));
if ((templateItem.getBlockParent() != null) && (templateItem.getBlockParent().booleanValue() == true)) {
// if it is a block item
BlockIdsParameters target = new BlockIdsParameters(ModifyBlockProducer.VIEW_ID, templateId, templateItem.getId().toString());
UIInternalLink.make(itemBranch, "modify-row-item", target)
.decorate(new UITooltipDecorator(UIMessage.make("modifytemplate.item.edit")));
} else {
//it is a non-block item
ViewParameters target = new ItemViewParameters(ModifyItemProducer.VIEW_ID,
templateItem.getItem().getClassification(), templateId, templateItem.getId());
UIInternalLink.make(itemBranch, "modify-row-item", target)
.decorate(new UITooltipDecorator(UIMessage.make("modifytemplate.item.edit")));
}
if(TemplateItemUtils.isBlockParent(templateItem)){
UIInternalLink unblockItem = UIInternalLink.make(itemBranch, "remove-row-item-unblock", UIMessage.make("modifytemplate.group.upgroup"),
new ItemViewParameters(RemoveItemProducer.VIEW_ID, (Long)null, templateItem.getId(), templateId) );
unblockItem.decorate(new UIFreeAttributeDecorator("templateItemId", templateItem.getId().toString()));
unblockItem.decorate(new UIFreeAttributeDecorator("templateId", templateId.toString()));
unblockItem.decorate(new UIFreeAttributeDecorator("OTP", templateItemOTPBinding));
}
else{
UIInternalLink removeItem = UIInternalLink.make(itemBranch, "remove-row-item",
new ItemViewParameters(RemoveItemProducer.VIEW_ID, (Long)null, templateItem.getId(), templateId) );
removeItem.decorate(new UIFreeAttributeDecorator("templateItemId", templateItem.getId().toString()));
removeItem.decorate(new UIFreeAttributeDecorator("templateId", templateId.toString()));
removeItem.decorate(new UIFreeAttributeDecorator("OTP", templateItemOTPBinding));
removeItem.decorate(new UITooltipDecorator(UIMessage.make("modifytemplate.item.delete")));
}
// SECOND LINE
UISelect orderPulldown = UISelect.make(itemBranch, "item-select", itemNumArr, templateItemOTP + "displayOrder", null);
orderPulldown.decorators = new DecoratorList( new UITooltipDecorator( UIMessage.make("modifytemplate.select.order.title") ) );
String formattedText = FormattedText.convertFormattedTextToPlaintext(templateItem.getItem().getItemText());
UIBranchContainer branchText = UIBranchContainer.make(itemBranch, "item-text:");
UIBranchContainer branchTextHidden = UIBranchContainer.make(itemBranch, "item-text-hidden:");
UIVerbatim itemText = null;
if(formattedText.length() < 150){
itemText = UIVerbatim.make(branchText, "item-text-short", formattedText);
}else{
itemText = UIVerbatim.make(branchText, "item-text-short", formattedText.substring(0, 150));
UIOutput.make(branchText, "item-text-control");
UIVerbatim.make(branchTextHidden, "item-text-long", formattedText);
UIOutput.make(branchTextHidden, "item-text-hidden-control");
}
if(TemplateItemUtils.isBlockParent(templateItem)){
itemText.decorators = new DecoratorList(new UIStyleDecorator("itemBlockRow"));
UIOutput.make(branchText, "item-text-block");
}
/* Hierarchy Messages
* Only Display these if they are enabled in the preferences.
*/
Boolean showHierarchy = (Boolean) evalSettings.get(EvalSettings.DISPLAY_HIERARCHY_OPTIONS);
if ( showHierarchy ) {
/* Don't show the Node Id icon if it's a top level item */
if (!templateItem.getHierarchyLevel().equals(EvalConstants.HIERARCHY_LEVEL_TOP)) {
EvalHierarchyNode curnode = hierarchyLogic.getNodeById(templateItem.getHierarchyNodeId());
UILink.make(itemBranch, "item-hierarchy")
.decorate( new UITooltipDecorator( messageLocator.getMessage("modifytemplate.item.hierarchy.nodeid.title") + curnode.title ));
}
}
Boolean useResultsSharing = (Boolean) evalSettings.get(EvalSettings.ITEM_USE_RESULTS_SHARING);
if ( useResultsSharing ) {
// only show results sharing if it is being used
String resultsSharingMessage = "unknown.caps";
if ( EvalConstants.SHARING_PUBLIC.equals(templateItem.getResultsSharing()) ) {
resultsSharingMessage = "general.public";
} else if ( EvalConstants.SHARING_PRIVATE.equals(templateItem.getResultsSharing()) ) {
resultsSharingMessage = "general.private";
}
UIMessage.make(itemBranch, "item-results-sharing", resultsSharingMessage);
}
if ( EvalConstants.ITEM_TYPE_SCALED.equals(templateItem.getItem().getClassification()) &&
templateItem.getItem().getScale() != null ) {
// only show the scale type of this is a scaled item
UIMessage.make(itemBranch, "item-scale-type-title", "modifytemplate.item.scale.type.title");
UIOutput.make(itemBranch, "scale-type", templateItem.getItem().getScale().getTitle());
}
// display item options
boolean showOptions = false;
if ( templateItem.getUsesNA() != null
&& templateItem.getUsesNA() ) {
UIMessage.make(itemBranch, "item-na-enabled", "modifytemplate.item.na.note");
showOptions = true;
}
if ( templateItem.getUsesComment() != null
&& templateItem.getUsesComment() ) {
UIMessage.make(itemBranch, "item-comment-enabled", "modifytemplate.item.comment.note");
showOptions = true;
}
if (showOptions) {
UIMessage.make(itemBranch, "item-options", "modifytemplate.item.options");
}
// block child items
if ( TemplateItemUtils.isBlockParent(templateItem) ) {
List<EvalTemplateItem> childList = TemplateItemUtils.getChildItems(itemList, templateItem.getId());
if (childList.size() > 0) {
UIBranchContainer blockChildren = UIBranchContainer.make(itemBranch, "block-children:", Integer.toString(blockChildNum));
UIMessage.make(itemBranch, "modifyblock-items-list-instructions",
"modifyblock.page.instructions");
blockChildNum++;
int orderNo = 0;
// iterate through block children for the current block parent and emit each child item
for (int j = 0; j < childList.size(); j++) {
EvalTemplateItem child = (EvalTemplateItem) childList.get(j);
emitItem(itemBranch, child, orderNo + 1, templateId, templateItemOTPBinding);
orderNo++;
}
for (int k = 0; k < childList.size(); k++) {
EvalTemplateItem child = childList.get(k);
UIBranchContainer childRow = UIBranchContainer.make(blockChildren, "child-item:", k+"");
UIOutput.make(childRow, "child-item-num", child.getDisplayOrder().toString());
UIVerbatim.make(childRow, "child-item-text", child.getItem().getItemText());
}
} else {
throw new IllegalStateException("Block parent with no items in it, id=" + templateItem.getId());
}
}
}
}
//this outputs the total number of rows
UIVerbatim.make(tofill, "total-rows", (sCurItemNum + 1));
// the create block form
UIForm blockForm = UIForm.make(tofill, "createBlockForm",
new BlockIdsParameters(ModifyBlockProducer.VIEW_ID, templateId, null));
UICommand createBlock = UICommand.make(blockForm, "createBlockBtn", UIMessage.make("modifytemplate.button.createblock") );
createBlock.decorators = new DecoratorList( new UITooltipDecorator( UIMessage.make("modifytemplate.button.createblock.title") ) );
UIMessage.make(form2, "blockInstructions", "modifytemplate.instructions.block");
}
| public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
// local variables used in the render logic
String currentUserId = commonLogic.getCurrentUserId();
boolean userAdmin = commonLogic.isUserAdmin(currentUserId);
boolean createTemplate = authoringService.canCreateTemplate(currentUserId);
boolean beginEvaluation = evaluationService.canBeginEvaluation(currentUserId);
TemplateViewParameters evalViewParams = (TemplateViewParameters) viewparams;
Long templateId = evalViewParams.templateId;
EvalTemplate template = localTemplateLogic.fetchTemplate(templateId);
/*
* top links here
*/
UIInternalLink.make(tofill, "summary-link",
UIMessage.make("summary.page.title"),
new SimpleViewParameters(SummaryProducer.VIEW_ID));
if (userAdmin) {
UIInternalLink.make(tofill, "administrate-link",
UIMessage.make("administrate.page.title"),
new SimpleViewParameters(AdministrateProducer.VIEW_ID));
}
if (createTemplate
|| authoringService.canModifyTemplate(currentUserId, templateId)) {
UIInternalLink.make(tofill, "control-templates-link",
UIMessage.make("controltemplates.page.title"),
new SimpleViewParameters(ControlTemplatesProducer.VIEW_ID));
UIInternalLink.make(tofill, "control-items-link",
UIMessage.make("controlitems.page.title"),
new SimpleViewParameters(ControlItemsProducer.VIEW_ID));
} else {
throw new SecurityException("User attempted to access " +
VIEW_ID + " when they are not allowed");
}
if (beginEvaluation) {
UIInternalLink.make(tofill, "control-evaluations-link",
UIMessage.make("controlevaluations.page.title"),
new SimpleViewParameters(ControlEvaluationsProducer.VIEW_ID));
}
if (userAdmin) {
UIInternalLink.make(tofill, "control-scales-link",
UIMessage.make("controlscales.page.title"),
new SimpleViewParameters(ControlScalesProducer.VIEW_ID));
}
// begin page rendering
UIOutput.make(tofill, "site-id", commonLogic.getContentCollectionId(commonLogic.getCurrentEvalGroup()));
UIMessage.make(tofill, "modify-template-title", "modifytemplate.page.title");
UIInternalLink.make(tofill, "preview_eval_link", UIMessage.make("modifytemplate.preview.eval.link"),
new EvalViewParameters(PreviewEvalProducer.VIEW_ID, null, templateId))
.decorate( new UITooltipDecorator( UIMessage.make("modifytemplate.preview.eval.link.title") ) );
UIMessage.make(tofill, "preview-eval-desc", "modifytemplate.preview.eval.desc");
UILink.make(tofill, "preview-template-direct-link", UIMessage.make("general.direct.link"),
commonLogic.getEntityURL(template) )
.decorate( new UITooltipDecorator( UIMessage.make("general.direct.link.title") ) );
// get form to submit the type of item to create to the correct view
UIMessage.make(tofill, "add-item-note", "modifytemplate.add.item.note");
// create the choices for the pulldown
ArrayList<ViewParameters> templateItemVPList = new ArrayList<ViewParameters>();
ArrayList<String> templateItemLabelList = new ArrayList<String>();
for (int i = 0; i < EvalToolConstants.ITEM_SELECT_CLASSIFICATION_VALUES.length; i++) {
templateItemVPList.add( new ItemViewParameters(ModifyItemProducer.VIEW_ID,
EvalToolConstants.ITEM_SELECT_CLASSIFICATION_VALUES[i], templateId) );
templateItemLabelList.add(EvalToolConstants.ITEM_SELECT_CLASSIFICATION_LABELS[i]);
}
// add in existing items selection
templateItemVPList.add( new TemplateItemViewParameters(ExistingItemsProducer.VIEW_ID, templateId, null) );
templateItemLabelList.add("item.classification.existing");
// add in expert items choice if enabled
Boolean useExpertItems = (Boolean) evalSettings.get(EvalSettings.USE_EXPERT_ITEMS);
if (useExpertItems) {
templateItemVPList.add( new TemplateItemViewParameters(ExpertCategoryProducer.VIEW_ID, templateId, null) );
templateItemLabelList.add("item.classification.expert");
}
EvalUser TempOwner = commonLogic.getEvalUserById( template.getOwner() );
UIOutput.make(tofill, "template-owner", TempOwner.displayName );
addItemControlRenderer.renderControl(tofill, "add-item-control:",
templateItemVPList.toArray(new ViewParameters[templateItemVPList.size()]),
templateItemLabelList.toArray(new String[templateItemLabelList.size()]),
UIMessage.make("modifytemplate.add.item.button"), templateId);
List<EvalTemplateItem> itemList = localTemplateLogic.fetchTemplateItems(templateId);
List<EvalTemplateItem> templateItemsList = TemplateItemUtils.getNonChildItems(itemList);
if (templateItemsList.isEmpty()) {
UIMessage.make(tofill, "begin-eval-dummylink", "modifytemplate.begin.eval.link");
} else {
UIInternalLink evalLink = UIInternalLink.make(tofill, "begin_eval_link", UIMessage.make("modifytemplate.begin.eval.link"),
new EvalViewParameters(EvaluationCreateProducer.VIEW_ID, null, templateId));
evalLink.decorators = new DecoratorList( new UITooltipDecorator(UIMessage.make("modifytemplate.begin.eval.link.title")));
}
// TODO - this should be the actual level and not some made up string
String currentLevel = "Current";
UIMessage.make(tofill, "level-header-level", "modifytemplate.level.header.level",
new String[] {currentLevel});
UIOutput.make(tofill, "level-header-number", new Integer(templateItemsList.size()).toString() );
UIMessage.make(tofill, "level-header-items", "modifytemplate.level.header.items");
UIMessage.make(tofill, "template-title-header", "modifytemplate.template.title.header");
UIOutput.make(tofill, "title", template.getTitle());
UIInternalLink.make(tofill, "modify_title_desc_link", UIMessage.make("modifytemplate.modify.title.desc.link"),
new TemplateViewParameters(ModifyTemplateProducer.VIEW_ID, templateId)).decorators =
new DecoratorList(new UITooltipDecorator(UIMessage.make("modifytemplate.modify.title.desc.link.title")));
if (template.getDescription() != null && !template.getDescription().trim().equals("")) {
UIBranchContainer descbranch = UIBranchContainer.make(tofill, "description-switch:");
UIMessage.make(descbranch, "description-header", "modifytemplate.description.header");
UIOutput.make(descbranch, "description", template.getDescription());
}
UIForm form2 = UIForm.make(tofill, "modifyFormRows");
UICommand.make(form2, "hiddenBtn");
form2.parameters.add(new UIELBinding("#{templateBBean.templateId}", templateId));
UIMessage revertOrderButton = UIMessage.make(form2, "revertOrderButton", "modifytemplate.button.revert.order");
revertOrderButton.decorators = new DecoratorList( new UITooltipDecorator( UIMessage.make("modifytemplate.button.revert.order.title") ) );
UICommand saveReorderButton = UICommand.make(form2, "saveReorderButton",
UIMessage.make("modifytemplate.button.save.order"), "#{templateBBean.saveReorder}");
saveReorderButton.parameters.add(new UIELBinding("#{templateBBean.templateId}", templateId));
saveReorderButton.decorators = new DecoratorList( new UITooltipDecorator( UIMessage.make("modifytemplate.button.save.order.title") ) );
UIMessage.make(form2, "orderingInstructions", "modifytemplate.instructions.reorder");
String sCurItemNum = null;
int blockChildNum = 0;
if ((templateItemsList != null) && (templateItemsList.size() > 0)) {
String templateItemOTPBinding = null;
String templateItemOTP = null;
String[] itemNumArr = new String[templateItemsList.size()];
for (int h = 0; h < templateItemsList.size(); h++) {
itemNumArr[h] = Integer.toString(h + 1);
}
for (int i = 0; i < templateItemsList.size(); i++) {
EvalTemplateItem templateItem = (EvalTemplateItem) templateItemsList.get(i);
sCurItemNum = Integer.toString(i);
templateItemOTPBinding = "templateItemWBL." + templateItem.getId();
templateItemOTP = templateItemOTPBinding + ".";
UIBranchContainer itemBranch = UIBranchContainer.make(form2, "item-row:", sCurItemNum);
// Add item type and id to item tag only if this is a block item
if ( templateItem.getItem().getClassification().equals(EvalConstants.ITEM_TYPE_BLOCK_PARENT) ){
itemBranch.decorate( new UIFreeAttributeDecorator("name", EvalConstants.ITEM_TYPE_BLOCK_PARENT.toLowerCase() + "-" +templateItem.getId() ) );
}
// hidden item num
UIInput.make(itemBranch, "hidden-item-num", templateItemOTP + "displayOrder", sCurItemNum);
UIOutput.make(itemBranch, "template-item-id", templateItem.getId() + "");
// only show Block Check box for scaled and block parents
if ( templateItem.getItem().getClassification().equals(EvalConstants.ITEM_TYPE_SCALED) ||
templateItem.getItem().getClassification().equals(EvalConstants.ITEM_TYPE_BLOCK_PARENT) ) {
UIOutput checkBranch = UIOutput.make(itemBranch, "block-check-branch");
UIBoundBoolean blockCB = UIBoundBoolean.make(itemBranch, "block-checkbox", Boolean.FALSE);
// we have to force the id so the JS block checking can work
String name = "block-" + templateItem.getItem().getScale().getId() + "-" + templateItem.getId();
blockCB.decorators = new DecoratorList( new UIIDStrategyDecorator(name) );
// have to force the target id so that the label for works
UILabelTargetDecorator uild = new UILabelTargetDecorator(blockCB);
uild.targetFullID = name;
checkBranch.decorators = new DecoratorList( uild );
// tooltip
blockCB.decorators.add( new UITooltipDecorator( UIMessage.make("modifytemplate.item.checkbox.title") ) );
UIMessage.make(itemBranch, "check-input-label", "modifytemplate.check.label.title");
} else {
UIMessage.make(itemBranch, "check-placeholder", "modifytemplate.check.placeholder");
}
String itemLabelKey = EvalToolConstants.UNKNOWN_KEY;
for (int j = 0; j < EvalToolConstants.ITEM_CLASSIFICATION_VALUES.length; j++) {
if (templateItem.getItem().getClassification().equals(EvalToolConstants.ITEM_CLASSIFICATION_VALUES[j])) {
itemLabelKey = EvalToolConstants.ITEM_CLASSIFICATION_LABELS_PROPS[j];
break;
}
}
UIMessage.make(itemBranch, "item-classification", itemLabelKey);
if (templateItem.getScaleDisplaySetting() != null) {
String scaleDisplaySettingLabel = " - " + templateItem.getScaleDisplaySetting();
UIOutput.make(itemBranch, "scale-display", scaleDisplaySettingLabel);
}
if (templateItem.getCategory() != null && ! EvalConstants.ITEM_CATEGORY_COURSE.equals(templateItem.getCategory())){
String[] category = new String[] { messageLocator.getMessage( RenderingUtils.getCategoryLabelKey(templateItem.getCategory()) ) };
UIMessage.make(itemBranch, "item-category", "modifytemplate.item.category.title", category)
.decorate(new UITooltipDecorator(UIMessage.make("modifytemplate.item.category.tooltip", category)));
}
UIInternalLink.make(itemBranch, "preview-row-item",
new ItemViewParameters(PreviewItemProducer.VIEW_ID, (Long) null, templateItem.getId()) )
.decorate(new UITooltipDecorator(UIMessage.make("modifytemplate.item.preview")));
if ((templateItem.getBlockParent() != null) && (templateItem.getBlockParent().booleanValue() == true)) {
// if it is a block item
BlockIdsParameters target = new BlockIdsParameters(ModifyBlockProducer.VIEW_ID, templateId, templateItem.getId().toString());
UIInternalLink.make(itemBranch, "modify-row-item", target)
.decorate(new UITooltipDecorator(UIMessage.make("modifytemplate.item.edit")));
} else {
//it is a non-block item
ViewParameters target = new ItemViewParameters(ModifyItemProducer.VIEW_ID,
templateItem.getItem().getClassification(), templateId, templateItem.getId());
UIInternalLink.make(itemBranch, "modify-row-item", target)
.decorate(new UITooltipDecorator(UIMessage.make("modifytemplate.item.edit")));
}
if(TemplateItemUtils.isBlockParent(templateItem)){
UIInternalLink unblockItem = UIInternalLink.make(itemBranch, "remove-row-item-unblock", UIMessage.make("modifytemplate.group.ungroup"),
new ItemViewParameters(RemoveItemProducer.VIEW_ID, (Long)null, templateItem.getId(), templateId) );
unblockItem.decorate(new UIFreeAttributeDecorator("templateItemId", templateItem.getId().toString()));
unblockItem.decorate(new UIFreeAttributeDecorator("templateId", templateId.toString()));
unblockItem.decorate(new UIFreeAttributeDecorator("OTP", templateItemOTPBinding));
}
else{
UIInternalLink removeItem = UIInternalLink.make(itemBranch, "remove-row-item",
new ItemViewParameters(RemoveItemProducer.VIEW_ID, (Long)null, templateItem.getId(), templateId) );
removeItem.decorate(new UIFreeAttributeDecorator("templateItemId", templateItem.getId().toString()));
removeItem.decorate(new UIFreeAttributeDecorator("templateId", templateId.toString()));
removeItem.decorate(new UIFreeAttributeDecorator("OTP", templateItemOTPBinding));
removeItem.decorate(new UITooltipDecorator(UIMessage.make("modifytemplate.item.delete")));
}
// SECOND LINE
UISelect orderPulldown = UISelect.make(itemBranch, "item-select", itemNumArr, templateItemOTP + "displayOrder", null);
orderPulldown.decorators = new DecoratorList( new UITooltipDecorator( UIMessage.make("modifytemplate.select.order.title") ) );
String formattedText = FormattedText.convertFormattedTextToPlaintext(templateItem.getItem().getItemText());
UIBranchContainer branchText = UIBranchContainer.make(itemBranch, "item-text:");
UIBranchContainer branchTextHidden = UIBranchContainer.make(itemBranch, "item-text-hidden:");
UIVerbatim itemText = null;
if(formattedText.length() < 150){
itemText = UIVerbatim.make(branchText, "item-text-short", formattedText);
}else{
itemText = UIVerbatim.make(branchText, "item-text-short", formattedText.substring(0, 150));
UIOutput.make(branchText, "item-text-control");
UIVerbatim.make(branchTextHidden, "item-text-long", formattedText);
UIOutput.make(branchTextHidden, "item-text-hidden-control");
}
if(TemplateItemUtils.isBlockParent(templateItem)){
itemText.decorators = new DecoratorList(new UIStyleDecorator("itemBlockRow"));
UIOutput.make(branchText, "item-text-block");
}
/* Hierarchy Messages
* Only Display these if they are enabled in the preferences.
*/
Boolean showHierarchy = (Boolean) evalSettings.get(EvalSettings.DISPLAY_HIERARCHY_OPTIONS);
if ( showHierarchy ) {
/* Don't show the Node Id icon if it's a top level item */
if (!templateItem.getHierarchyLevel().equals(EvalConstants.HIERARCHY_LEVEL_TOP)) {
EvalHierarchyNode curnode = hierarchyLogic.getNodeById(templateItem.getHierarchyNodeId());
UILink.make(itemBranch, "item-hierarchy")
.decorate( new UITooltipDecorator( messageLocator.getMessage("modifytemplate.item.hierarchy.nodeid.title") + curnode.title ));
}
}
Boolean useResultsSharing = (Boolean) evalSettings.get(EvalSettings.ITEM_USE_RESULTS_SHARING);
if ( useResultsSharing ) {
// only show results sharing if it is being used
String resultsSharingMessage = "unknown.caps";
if ( EvalConstants.SHARING_PUBLIC.equals(templateItem.getResultsSharing()) ) {
resultsSharingMessage = "general.public";
} else if ( EvalConstants.SHARING_PRIVATE.equals(templateItem.getResultsSharing()) ) {
resultsSharingMessage = "general.private";
}
UIMessage.make(itemBranch, "item-results-sharing", resultsSharingMessage);
}
if ( EvalConstants.ITEM_TYPE_SCALED.equals(templateItem.getItem().getClassification()) &&
templateItem.getItem().getScale() != null ) {
// only show the scale type of this is a scaled item
UIMessage.make(itemBranch, "item-scale-type-title", "modifytemplate.item.scale.type.title");
UIOutput.make(itemBranch, "scale-type", templateItem.getItem().getScale().getTitle());
}
// display item options
boolean showOptions = false;
if ( templateItem.getUsesNA() != null
&& templateItem.getUsesNA() ) {
UIMessage.make(itemBranch, "item-na-enabled", "modifytemplate.item.na.note");
showOptions = true;
}
if ( templateItem.getUsesComment() != null
&& templateItem.getUsesComment() ) {
UIMessage.make(itemBranch, "item-comment-enabled", "modifytemplate.item.comment.note");
showOptions = true;
}
if (showOptions) {
UIMessage.make(itemBranch, "item-options", "modifytemplate.item.options");
}
// block child items
if ( TemplateItemUtils.isBlockParent(templateItem) ) {
List<EvalTemplateItem> childList = TemplateItemUtils.getChildItems(itemList, templateItem.getId());
if (childList.size() > 0) {
UIBranchContainer blockChildren = UIBranchContainer.make(itemBranch, "block-children:", Integer.toString(blockChildNum));
UIMessage.make(itemBranch, "modifyblock-items-list-instructions",
"modifyblock.page.instructions");
blockChildNum++;
int orderNo = 0;
// iterate through block children for the current block parent and emit each child item
for (int j = 0; j < childList.size(); j++) {
EvalTemplateItem child = (EvalTemplateItem) childList.get(j);
emitItem(itemBranch, child, orderNo + 1, templateId, templateItemOTPBinding);
orderNo++;
}
for (int k = 0; k < childList.size(); k++) {
EvalTemplateItem child = childList.get(k);
UIBranchContainer childRow = UIBranchContainer.make(blockChildren, "child-item:", k+"");
UIOutput.make(childRow, "child-item-num", child.getDisplayOrder().toString());
UIVerbatim.make(childRow, "child-item-text", child.getItem().getItemText());
}
} else {
throw new IllegalStateException("Block parent with no items in it, id=" + templateItem.getId());
}
}
}
}
//this outputs the total number of rows
UIVerbatim.make(tofill, "total-rows", (sCurItemNum + 1));
// the create block form
UIForm blockForm = UIForm.make(tofill, "createBlockForm",
new BlockIdsParameters(ModifyBlockProducer.VIEW_ID, templateId, null));
UICommand createBlock = UICommand.make(blockForm, "createBlockBtn", UIMessage.make("modifytemplate.button.createblock") );
createBlock.decorators = new DecoratorList( new UITooltipDecorator( UIMessage.make("modifytemplate.button.createblock.title") ) );
UIMessage.make(form2, "blockInstructions", "modifytemplate.instructions.block");
}
|
diff --git a/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/CategoryTypeLookup.java b/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/CategoryTypeLookup.java
index 4ff287d10..abfd2ab0c 100644
--- a/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/CategoryTypeLookup.java
+++ b/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/CategoryTypeLookup.java
@@ -1,180 +1,181 @@
/*
* Copyright 2003-2009 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.eclipse.jdt.groovy.search;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.codehaus.groovy.ast.AnnotationNode;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.FieldNode;
import org.codehaus.groovy.ast.ImportNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.jdt.groovy.model.GroovyCompilationUnit;
import org.eclipse.jdt.groovy.search.TypeLookupResult.TypeConfidence;
/**
* @author Andrew Eisenberg
* @created Oct 25, 2009
*
* Looks up the type of an expression in the currently applicable categories. Note that DefaultGroovyMethods are always
* considered to be an applicable category. This lookup is not being used yet
*/
public class CategoryTypeLookup implements ITypeLookup {
/**
* Looks up method calls to see if they are declared in any current categories
*/
public TypeLookupResult lookupType(Expression node, VariableScope scope, ClassNode objectExpressionType) {
if (node instanceof ConstantExpression) {
ConstantExpression constExpr = (ConstantExpression) node;
Set<ClassNode> categories = scope.getCategoryNames();
ClassNode currentType = objectExpressionType != null ? objectExpressionType : scope.getEnclosingTypeDeclaration();
Set<MethodNode> possibleMethods = new HashSet<MethodNode>();
// go through all categories and look for and look for a method with the given name
String text = constExpr.getText();
if (text.startsWith("${") && text.endsWith("}")) {
text = text.substring(2, text.length() - 1);
} else if (text.startsWith("$")) {
text = text.substring(1);
}
String getterName = createGetterName(text);
for (ClassNode category : categories) {
List<?> methods = category.getMethods(text); // use List<?> because groovy 1.6.5 does not
// have type parameters on this method
possibleMethods.addAll((Collection<? extends MethodNode>) methods);
// also check to see if the getter variant of any name is available
if (getterName != null) {
methods = category.getMethods(getterName);
possibleMethods.addAll((Collection<? extends MethodNode>) methods);
}
}
for (MethodNode methodNode : possibleMethods) {
Parameter[] params = methodNode.getParameters();
- if (params != null && isAssignableFrom(VariableScope.maybeConvertFromPrimitive(currentType), params[0].getType())) {
+ if (params != null && params.length > 0
+ && isAssignableFrom(VariableScope.maybeConvertFromPrimitive(currentType), params[0].getType())) {
// found it! There may be more, but this is good enough
ClassNode declaringClass = methodNode.getDeclaringClass();
return new TypeLookupResult(methodNode.getReturnType(), declaringClass, methodNode,
getConfidence(declaringClass), scope);
}
}
}
return null;
}
/**
* Convert name into a getter
*
* @param text
* @return name with get prefixed in front of it and first char capitalized or null if this name already looks like a getter or
* setter
*/
private String createGetterName(String name) {
if (!name.startsWith("get") && !name.startsWith("set") && name.length() > 0) {
return "get" + Character.toUpperCase(name.charAt(0)) + (name.length() > 1 ? name.substring(1) : "");
}
return null;
}
/**
* DGM and DGSM classes are loosely inferred so that other lookups can provide better solutions
*
* @param declaringClass
* @return
*/
private TypeConfidence getConfidence(ClassNode declaringClass) {
return declaringClass.getName().equals(VariableScope.DGM_CLASS_NODE.getName())
|| declaringClass.getName().equals(VariableScope.DGSM_CLASS_NODE.getName()) ? TypeConfidence.LOOSELY_INFERRED
: TypeConfidence.INFERRED;
}
/**
* @param interf
* @param allInterfaces
*/
private void findAllSupers(ClassNode clazz, Set<String> allSupers) {
if (!allSupers.contains(clazz.getName())) {
allSupers.add(clazz.getName());
if (clazz.getSuperClass() != null) {
findAllSupers(clazz.getSuperClass(), allSupers);
}
if (clazz.getInterfaces() != null) {
for (ClassNode superInterface : clazz.getInterfaces()) {
findAllSupers(superInterface, allSupers);
}
}
}
}
/**
* can from be assigned to to?
*
* @param from
* @param to
* @return
*/
private boolean isAssignableFrom(ClassNode from, ClassNode to) {
if (from == null || to == null) {
return false;
}
Set<String> allSupers = new HashSet<String>();
allSupers.add("java.lang.Object");
findAllSupers(from, allSupers);
for (String supr : allSupers) {
if (to.getName().equals(supr)) {
return true;
}
}
return false;
}
public TypeLookupResult lookupType(FieldNode node, VariableScope scope) {
return null;
}
public TypeLookupResult lookupType(MethodNode node, VariableScope scope) {
return null;
}
public TypeLookupResult lookupType(AnnotationNode node, VariableScope scope) {
return null;
}
public TypeLookupResult lookupType(ImportNode node, VariableScope scope) {
return null;
}
public TypeLookupResult lookupType(ClassNode node, VariableScope scope) {
return null;
}
public TypeLookupResult lookupType(Parameter node, VariableScope scope) {
return null;
}
public void initialize(GroovyCompilationUnit unit, VariableScope topLevelScope) {
// do nothing
}
}
| true | true | public TypeLookupResult lookupType(Expression node, VariableScope scope, ClassNode objectExpressionType) {
if (node instanceof ConstantExpression) {
ConstantExpression constExpr = (ConstantExpression) node;
Set<ClassNode> categories = scope.getCategoryNames();
ClassNode currentType = objectExpressionType != null ? objectExpressionType : scope.getEnclosingTypeDeclaration();
Set<MethodNode> possibleMethods = new HashSet<MethodNode>();
// go through all categories and look for and look for a method with the given name
String text = constExpr.getText();
if (text.startsWith("${") && text.endsWith("}")) {
text = text.substring(2, text.length() - 1);
} else if (text.startsWith("$")) {
text = text.substring(1);
}
String getterName = createGetterName(text);
for (ClassNode category : categories) {
List<?> methods = category.getMethods(text); // use List<?> because groovy 1.6.5 does not
// have type parameters on this method
possibleMethods.addAll((Collection<? extends MethodNode>) methods);
// also check to see if the getter variant of any name is available
if (getterName != null) {
methods = category.getMethods(getterName);
possibleMethods.addAll((Collection<? extends MethodNode>) methods);
}
}
for (MethodNode methodNode : possibleMethods) {
Parameter[] params = methodNode.getParameters();
if (params != null && isAssignableFrom(VariableScope.maybeConvertFromPrimitive(currentType), params[0].getType())) {
// found it! There may be more, but this is good enough
ClassNode declaringClass = methodNode.getDeclaringClass();
return new TypeLookupResult(methodNode.getReturnType(), declaringClass, methodNode,
getConfidence(declaringClass), scope);
}
}
}
return null;
}
| public TypeLookupResult lookupType(Expression node, VariableScope scope, ClassNode objectExpressionType) {
if (node instanceof ConstantExpression) {
ConstantExpression constExpr = (ConstantExpression) node;
Set<ClassNode> categories = scope.getCategoryNames();
ClassNode currentType = objectExpressionType != null ? objectExpressionType : scope.getEnclosingTypeDeclaration();
Set<MethodNode> possibleMethods = new HashSet<MethodNode>();
// go through all categories and look for and look for a method with the given name
String text = constExpr.getText();
if (text.startsWith("${") && text.endsWith("}")) {
text = text.substring(2, text.length() - 1);
} else if (text.startsWith("$")) {
text = text.substring(1);
}
String getterName = createGetterName(text);
for (ClassNode category : categories) {
List<?> methods = category.getMethods(text); // use List<?> because groovy 1.6.5 does not
// have type parameters on this method
possibleMethods.addAll((Collection<? extends MethodNode>) methods);
// also check to see if the getter variant of any name is available
if (getterName != null) {
methods = category.getMethods(getterName);
possibleMethods.addAll((Collection<? extends MethodNode>) methods);
}
}
for (MethodNode methodNode : possibleMethods) {
Parameter[] params = methodNode.getParameters();
if (params != null && params.length > 0
&& isAssignableFrom(VariableScope.maybeConvertFromPrimitive(currentType), params[0].getType())) {
// found it! There may be more, but this is good enough
ClassNode declaringClass = methodNode.getDeclaringClass();
return new TypeLookupResult(methodNode.getReturnType(), declaringClass, methodNode,
getConfidence(declaringClass), scope);
}
}
}
return null;
}
|
diff --git a/src/uk/me/parabola/mkgmap/reader/osm/boundary/BoundaryUtil.java b/src/uk/me/parabola/mkgmap/reader/osm/boundary/BoundaryUtil.java
index 764e5449..5997e49c 100644
--- a/src/uk/me/parabola/mkgmap/reader/osm/boundary/BoundaryUtil.java
+++ b/src/uk/me/parabola/mkgmap/reader/osm/boundary/BoundaryUtil.java
@@ -1,331 +1,337 @@
/*
* Copyright (C) 2006, 2011.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 or
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
package uk.me.parabola.mkgmap.reader.osm.boundary;
import java.awt.geom.Area;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import uk.me.parabola.imgfmt.app.Coord;
import uk.me.parabola.log.Logger;
import uk.me.parabola.mkgmap.reader.osm.Tags;
import uk.me.parabola.mkgmap.reader.osm.Way;
import uk.me.parabola.util.Java2DConverter;
public class BoundaryUtil {
private static final Logger log = Logger.getLogger(BoundaryUtil.class);
public static class BoundaryFileFilter implements FileFilter {
public boolean accept(File pathname) {
return pathname.isFile() && pathname.getName().endsWith(".bnd");
}
}
public static List<BoundaryElement> splitToElements(Area area) {
if (area.isEmpty()) {
return Collections.emptyList();
}
List<List<Coord>> areaElements = Java2DConverter.areaToShapes(area);
if (areaElements.isEmpty()) {
// this may happen if a boundary overlaps a raster tile in a very small area
// so that it is has no dimension
log.debug("Area has no dimension. Area:",area.getBounds());
return Collections.emptyList();
}
List<BoundaryElement> bElements = new ArrayList<BoundaryElement>();
for (List<Coord> singleElement : areaElements) {
if (singleElement.size() <= 3) {
// need at least 4 items to describe a polygon
continue;
}
Way w = new Way(0, singleElement);
boolean outer = w.clockwise();
bElements.add(new BoundaryElement(outer, singleElement));
}
if (bElements.isEmpty()) {
// should not happen because empty polygons should be removed by
// the Java2DConverter
log.error("Empty boundary elements list after conversion. Area: "+area.getBounds());
return Collections.emptyList();
}
// reverse the list because it starts with the inner elements first and
// we need the other way round
Collections.reverse(bElements);
assert bElements.get(0).isOuter() : log.threadTag()+" first element is not outer. "+ bElements;
return bElements;
}
public static Area convertToArea(List<BoundaryElement> list) {
Area area = new Area();
for (BoundaryElement elem : list) {
if (elem.isOuter()) {
area.add(elem.getArea());
} else {
area.subtract(elem.getArea());
}
}
return area;
}
public static List<Boundary> loadBoundaryFile(File boundaryFile,
uk.me.parabola.imgfmt.app.Area bbox) throws IOException
{
log.debug("Load boundary file",boundaryFile,"within",bbox);
List<Boundary> boundaryList = new ArrayList<Boundary>();
FileInputStream stream = new FileInputStream(boundaryFile);
try {
DataInputStream inpStream = new DataInputStream(
new BufferedInputStream(stream, 1024 * 1024));
try {
// 1st read the mkgmap release the boundary file is created by
String mkgmapRel = inpStream.readUTF();
long createTime = inpStream.readLong();
if (log.isDebugEnabled()) {
log.debug("File created by mkgmap release",mkgmapRel,"at",new Date(createTime));
}
while (true) {
int minLat = inpStream.readInt();
int minLong = inpStream.readInt();
int maxLat = inpStream.readInt();
int maxLong = inpStream.readInt();
log.debug("Next boundary. Lat min:",minLat,"max:",maxLat,"Long min:",minLong,"max:",maxLong);
uk.me.parabola.imgfmt.app.Area rBbox = new uk.me.parabola.imgfmt.app.Area(
minLat, minLong, maxLat, maxLong);
int bSize = inpStream.readInt();
log.debug("Size:",bSize);
if (bbox == null || bbox.intersects(rBbox)) {
log.debug("Bbox intersects. Load the boundary");
Tags tags = new Tags();
int noOfTags = inpStream.readInt();
for (int i = 0; i < noOfTags; i++) {
String name = inpStream.readUTF();
String value = inpStream.readUTF();
tags.put(name, value);
}
int noBElems = inpStream.readInt();
assert noBElems > 0;
// the first area is always an outer area and will be assigned to the variable
Area area = null;
for (int i = 0; i < noBElems; i++) {
boolean outer = inpStream.readBoolean();
int noCoords = inpStream.readInt();
log.debug("No of coords",noCoords);
List<Coord> points = new ArrayList<Coord>(noCoords);
for (int c = 0; c < noCoords; c++) {
int lat = inpStream.readInt();
int lon = inpStream.readInt();
points.add(new Coord(lat, lon));
}
Area elemArea = Java2DConverter.createArea(points);
if (outer) {
if (area == null) {
area = elemArea;
} else {
area.add(elemArea);
}
} else {
- area.subtract(elemArea);
+ if (area == null) {
+ log.warn("Boundary: "+tags);
+ log.warn("Outer way is tagged incosistently as inner way. Ignoring it.");
+ log.warn("Points: "+points);
+ } else {
+ area.subtract(elemArea);
+ }
}
}
Boundary boundary = new Boundary(area, tags);
boundaryList.add(boundary);
} else {
log.debug("Bbox does not intersect. Skip",bSize);
inpStream.skipBytes(bSize);
}
}
} catch (EOFException exp) {
// it's always thrown at the end of the file
// log.error("Got EOF at the end of the file");
}
inpStream.close();
} finally {
if (stream != null)
stream.close();
}
return boundaryList;
}
public static List<File> getBoundaryFiles(File boundaryDir,
uk.me.parabola.imgfmt.app.Area bbox) {
List<File> boundaryFiles = new ArrayList<File>();
for (int latSplit = BoundaryUtil.getSplitBegin(bbox.getMinLat()); latSplit <= BoundaryUtil
.getSplitBegin(bbox.getMaxLat()); latSplit += BoundaryUtil.RASTER) {
for (int lonSplit = BoundaryUtil.getSplitBegin(bbox.getMinLong()); lonSplit <= BoundaryUtil
.getSplitBegin(bbox.getMaxLong()); lonSplit += BoundaryUtil.RASTER) {
File bndFile = new File(boundaryDir, "bounds_"
+ getKey(latSplit, lonSplit) + ".bnd");
if (bndFile.exists())
boundaryFiles.add(bndFile);
}
}
return boundaryFiles;
}
public static List<Boundary> loadBoundaries(File boundaryDir,
uk.me.parabola.imgfmt.app.Area bbox) {
List<File> boundaryFiles = getBoundaryFiles(boundaryDir, bbox);
List<Boundary> boundaries = new ArrayList<Boundary>();
for (File boundaryFile : boundaryFiles) {
try {
boundaries.addAll(loadBoundaryFile(boundaryFile, bbox));
} catch (IOException exp) {
log.warn("Cannot load boundary file", boundaryFile + ".",exp);
// String basename = "missingbounds/";
// String[] bParts = boundaryFile.getName().substring(0,boundaryFile.getName().length()-4).split("_");
// int minLat = Integer.valueOf(bParts[1]);
// int minLong = Integer.valueOf(bParts[2]);
// uk.me.parabola.imgfmt.app.Area bBbox = new uk.me.parabola.imgfmt.app.Area(minLat, minLong, minLat+RASTER, minLong+RASTER);
// GpxCreator.createAreaGpx(basename+boundaryFile.getName(), bBbox);
// log.error("GPX created "+basename+boundaryFile.getName());
}
}
if (boundaryFiles.size() > 1) {
boundaries = mergeBoundaries(boundaries);
}
return boundaries;
}
private static List<Boundary> mergeBoundaries(List<Boundary> boundaryList) {
int noIdBoundaries = 0;
Map<String, Boundary> mergeMap = new HashMap<String, Boundary>();
for (Boundary toMerge : boundaryList) {
String bId = toMerge.getTags().get("mkgmap:boundaryid");
if (bId == null) {
noIdBoundaries++;
mergeMap.put("n" + noIdBoundaries, toMerge);
} else {
Boundary existingBoundary = mergeMap.get(bId);
if (existingBoundary == null) {
mergeMap.put(bId, toMerge);
} else {
if (log.isInfoEnabled())
log.info("Merge boundaries", existingBoundary.getTags(), "with", toMerge.getTags());
existingBoundary.getArea().add(toMerge.getArea());
// Merge the mkgmap:lies_in tag
// They should be the same but better to check that...
String liesInTagExist = existingBoundary.getTags().get("mkgmap:lies_in");
String liesInTagMerge = toMerge.getTags().get("mkgmap:lies_in");
if (liesInTagExist != null && liesInTagExist.equals(liesInTagMerge)==false) {
if (liesInTagMerge == null) {
existingBoundary.getTags().remove("mkgmap:lies_in");
} else {
// there is a difference in the lies_in tag => keep the equal ids
Set<String> existIds = new HashSet<String>(Arrays.asList(liesInTagExist.split(";")));
Set<String> mergeIds = new HashSet<String>(Arrays.asList(liesInTagMerge.split(";")));
existIds.retainAll(mergeIds);
if (existIds.isEmpty()) {
existingBoundary.getTags().remove("mkgmap:lies_in");
} else {
StringBuilder newLiesIn = new StringBuilder();
for (String liesInEntry : existIds) {
if (newLiesIn.length() > 0) {
newLiesIn.append(";");
}
newLiesIn.append(liesInEntry);
}
existingBoundary.getTags().put("mkgmap:lies_in", newLiesIn.toString());
}
}
}
}
}
}
if (noIdBoundaries > 0) {
log.error(noIdBoundaries
+ " without boundary id. Could not merge them.");
}
return new ArrayList<Boundary>(mergeMap.values());
}
public static final int RASTER = 50000;
public static int getSplitBegin(int value) {
int rem = value % RASTER;
if (rem == 0) {
return value;
} else if (value >= 0) {
return value - rem;
} else {
return value - RASTER - rem;
}
}
public static int getSplitEnd(int value) {
int rem = value % RASTER;
if (rem == 0) {
return value;
} else if (value >= 0) {
return value + RASTER - rem;
} else {
return value - rem;
}
}
public static String getKey(int lat, int lon) {
return lat + "_" + lon;
}
/**
* Retrieve the bounding box of the given boundary file.
* @param boundaryFile the boundary file
* @return the bounding box
*/
public static uk.me.parabola.imgfmt.app.Area getBbox(File boundaryFile) {
String filename = boundaryFile.getName();
// cut off the extension
filename = filename.substring(0,filename.length()-4);
String[] fParts = filename.split(Pattern.quote("_"));
int lat = Integer.valueOf(fParts[1]);
int lon = Integer.valueOf(fParts[2]);
return new uk.me.parabola.imgfmt.app.Area(lat, lon, lat+RASTER, lon+RASTER);
}
}
| true | true | public static List<Boundary> loadBoundaryFile(File boundaryFile,
uk.me.parabola.imgfmt.app.Area bbox) throws IOException
{
log.debug("Load boundary file",boundaryFile,"within",bbox);
List<Boundary> boundaryList = new ArrayList<Boundary>();
FileInputStream stream = new FileInputStream(boundaryFile);
try {
DataInputStream inpStream = new DataInputStream(
new BufferedInputStream(stream, 1024 * 1024));
try {
// 1st read the mkgmap release the boundary file is created by
String mkgmapRel = inpStream.readUTF();
long createTime = inpStream.readLong();
if (log.isDebugEnabled()) {
log.debug("File created by mkgmap release",mkgmapRel,"at",new Date(createTime));
}
while (true) {
int minLat = inpStream.readInt();
int minLong = inpStream.readInt();
int maxLat = inpStream.readInt();
int maxLong = inpStream.readInt();
log.debug("Next boundary. Lat min:",minLat,"max:",maxLat,"Long min:",minLong,"max:",maxLong);
uk.me.parabola.imgfmt.app.Area rBbox = new uk.me.parabola.imgfmt.app.Area(
minLat, minLong, maxLat, maxLong);
int bSize = inpStream.readInt();
log.debug("Size:",bSize);
if (bbox == null || bbox.intersects(rBbox)) {
log.debug("Bbox intersects. Load the boundary");
Tags tags = new Tags();
int noOfTags = inpStream.readInt();
for (int i = 0; i < noOfTags; i++) {
String name = inpStream.readUTF();
String value = inpStream.readUTF();
tags.put(name, value);
}
int noBElems = inpStream.readInt();
assert noBElems > 0;
// the first area is always an outer area and will be assigned to the variable
Area area = null;
for (int i = 0; i < noBElems; i++) {
boolean outer = inpStream.readBoolean();
int noCoords = inpStream.readInt();
log.debug("No of coords",noCoords);
List<Coord> points = new ArrayList<Coord>(noCoords);
for (int c = 0; c < noCoords; c++) {
int lat = inpStream.readInt();
int lon = inpStream.readInt();
points.add(new Coord(lat, lon));
}
Area elemArea = Java2DConverter.createArea(points);
if (outer) {
if (area == null) {
area = elemArea;
} else {
area.add(elemArea);
}
} else {
area.subtract(elemArea);
}
}
Boundary boundary = new Boundary(area, tags);
boundaryList.add(boundary);
} else {
log.debug("Bbox does not intersect. Skip",bSize);
inpStream.skipBytes(bSize);
}
}
} catch (EOFException exp) {
// it's always thrown at the end of the file
// log.error("Got EOF at the end of the file");
}
inpStream.close();
} finally {
if (stream != null)
stream.close();
}
return boundaryList;
}
| public static List<Boundary> loadBoundaryFile(File boundaryFile,
uk.me.parabola.imgfmt.app.Area bbox) throws IOException
{
log.debug("Load boundary file",boundaryFile,"within",bbox);
List<Boundary> boundaryList = new ArrayList<Boundary>();
FileInputStream stream = new FileInputStream(boundaryFile);
try {
DataInputStream inpStream = new DataInputStream(
new BufferedInputStream(stream, 1024 * 1024));
try {
// 1st read the mkgmap release the boundary file is created by
String mkgmapRel = inpStream.readUTF();
long createTime = inpStream.readLong();
if (log.isDebugEnabled()) {
log.debug("File created by mkgmap release",mkgmapRel,"at",new Date(createTime));
}
while (true) {
int minLat = inpStream.readInt();
int minLong = inpStream.readInt();
int maxLat = inpStream.readInt();
int maxLong = inpStream.readInt();
log.debug("Next boundary. Lat min:",minLat,"max:",maxLat,"Long min:",minLong,"max:",maxLong);
uk.me.parabola.imgfmt.app.Area rBbox = new uk.me.parabola.imgfmt.app.Area(
minLat, minLong, maxLat, maxLong);
int bSize = inpStream.readInt();
log.debug("Size:",bSize);
if (bbox == null || bbox.intersects(rBbox)) {
log.debug("Bbox intersects. Load the boundary");
Tags tags = new Tags();
int noOfTags = inpStream.readInt();
for (int i = 0; i < noOfTags; i++) {
String name = inpStream.readUTF();
String value = inpStream.readUTF();
tags.put(name, value);
}
int noBElems = inpStream.readInt();
assert noBElems > 0;
// the first area is always an outer area and will be assigned to the variable
Area area = null;
for (int i = 0; i < noBElems; i++) {
boolean outer = inpStream.readBoolean();
int noCoords = inpStream.readInt();
log.debug("No of coords",noCoords);
List<Coord> points = new ArrayList<Coord>(noCoords);
for (int c = 0; c < noCoords; c++) {
int lat = inpStream.readInt();
int lon = inpStream.readInt();
points.add(new Coord(lat, lon));
}
Area elemArea = Java2DConverter.createArea(points);
if (outer) {
if (area == null) {
area = elemArea;
} else {
area.add(elemArea);
}
} else {
if (area == null) {
log.warn("Boundary: "+tags);
log.warn("Outer way is tagged incosistently as inner way. Ignoring it.");
log.warn("Points: "+points);
} else {
area.subtract(elemArea);
}
}
}
Boundary boundary = new Boundary(area, tags);
boundaryList.add(boundary);
} else {
log.debug("Bbox does not intersect. Skip",bSize);
inpStream.skipBytes(bSize);
}
}
} catch (EOFException exp) {
// it's always thrown at the end of the file
// log.error("Got EOF at the end of the file");
}
inpStream.close();
} finally {
if (stream != null)
stream.close();
}
return boundaryList;
}
|
diff --git a/Demigods-Engine/src/main/java/com/censoredsoftware/demigods/engine/player/DCharacter.java b/Demigods-Engine/src/main/java/com/censoredsoftware/demigods/engine/player/DCharacter.java
index 0d6692ce..187c7d09 100644
--- a/Demigods-Engine/src/main/java/com/censoredsoftware/demigods/engine/player/DCharacter.java
+++ b/Demigods-Engine/src/main/java/com/censoredsoftware/demigods/engine/player/DCharacter.java
@@ -1,1420 +1,1421 @@
package com.censoredsoftware.demigods.engine.player;
import com.censoredsoftware.censoredlib.data.inventory.CEnderInventory;
import com.censoredsoftware.censoredlib.data.inventory.CInventory;
import com.censoredsoftware.censoredlib.data.inventory.CItemStack;
import com.censoredsoftware.censoredlib.data.player.Notification;
import com.censoredsoftware.censoredlib.language.Symbol;
import com.censoredsoftware.demigods.engine.Demigods;
import com.censoredsoftware.demigods.engine.ability.Ability;
import com.censoredsoftware.demigods.engine.battle.Participant;
import com.censoredsoftware.demigods.engine.data.DataManager;
import com.censoredsoftware.demigods.engine.data.util.CItemStacks;
import com.censoredsoftware.demigods.engine.data.util.CLocations;
import com.censoredsoftware.demigods.engine.deity.Alliance;
import com.censoredsoftware.demigods.engine.deity.Deity;
import com.censoredsoftware.demigods.engine.listener.DemigodsChatEvent;
import com.censoredsoftware.demigods.engine.structure.Structure;
import com.censoredsoftware.demigods.engine.structure.StructureData;
import com.censoredsoftware.demigods.engine.util.Configs;
import com.censoredsoftware.demigods.engine.util.Messages;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.*;
import org.bukkit.*;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.potion.PotionEffect;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.*;
public class DCharacter implements Participant, ConfigurationSerializable
{
private UUID id;
private String name;
private String mojangAccount;
private boolean alive;
private double health;
private Integer hunger;
private Float experience;
private Integer level;
private Integer killCount;
private UUID location;
private UUID bedSpawn;
private GameMode gameMode;
private String deity;
private Set<String> minorDeities;
private boolean active;
private boolean usable;
private UUID meta;
private UUID inventory, enderInventory;
private Set<String> potionEffects;
private Set<String> deaths;
private static boolean LEVEL_SEPERATE_SKILLS = Demigods.mythos().levelSeperateSkills();
public DCharacter()
{
deaths = Sets.newHashSet();
potionEffects = Sets.newHashSet();
minorDeities = Sets.newHashSet();
}
public DCharacter(UUID id, ConfigurationSection conf)
{
this.id = id;
name = conf.getString("name");
mojangAccount = conf.getString("mojangAccount");
if(conf.isBoolean("alive")) alive = conf.getBoolean("alive");
health = conf.getDouble("health");
hunger = conf.getInt("hunger");
experience = Float.valueOf(conf.getString("experience"));
level = conf.getInt("level");
killCount = conf.getInt("killCount");
if(conf.isString("location"))
{
location = UUID.fromString(conf.getString("location"));
try
{
CLocations.load(location);
}
catch(Throwable errored)
{
location = null;
}
}
if(conf.getString("bedSpawn") != null)
{
bedSpawn = UUID.fromString(conf.getString("bedSpawn"));
try
{
CLocations.load(bedSpawn);
}
catch(Throwable errored)
{
bedSpawn = null;
}
}
if(conf.getString("gameMode") != null) gameMode = GameMode.SURVIVAL;
deity = conf.getString("deity");
active = conf.getBoolean("active");
usable = conf.getBoolean("usable");
meta = UUID.fromString(conf.getString("meta"));
if(conf.isList("minorDeities")) minorDeities = Sets.newHashSet(conf.getStringList("minorDeities"));
if(conf.isString("inventory")) inventory = UUID.fromString(conf.getString("inventory"));
if(conf.isString("enderInventory")) enderInventory = UUID.fromString(conf.getString("enderInventory"));
if(conf.isList("deaths")) deaths = Sets.newHashSet(conf.getStringList("deaths"));
if(conf.isList("potionEffects")) potionEffects = Sets.newHashSet(conf.getStringList("potionEffects"));
}
@Override
public Map<String, Object> serialize()
{
Map<String, Object> map = Maps.newHashMap();
try
{
map.put("name", name);
map.put("mojangAccount", mojangAccount);
map.put("alive", alive);
map.put("health", health);
map.put("hunger", hunger);
map.put("experience", experience);
map.put("level", level);
map.put("killCount", killCount);
if(location != null) map.put("location", location.toString());
if(bedSpawn != null) map.put("bedSpawn", bedSpawn.toString());
if(gameMode != null) map.put("gameMode", gameMode.name());
map.put("deity", deity);
if(minorDeities != null) map.put("minorDeities", Lists.newArrayList(minorDeities));
map.put("active", active);
map.put("usable", usable);
map.put("meta", meta.toString());
if(inventory != null) map.put("inventory", inventory.toString());
if(enderInventory != null) map.put("enderInventory", enderInventory.toString());
if(deaths != null) map.put("deaths", Lists.newArrayList(deaths));
if(potionEffects != null) map.put("potionEffects", Lists.newArrayList(potionEffects));
}
catch(Throwable ignored)
{}
return map;
}
void generateId()
{
id = UUID.randomUUID();
}
void setName(String name)
{
this.name = name;
}
void setDeity(Deity deity)
{
this.deity = deity.getName();
}
public void setMinorDeities(Set<String> set)
{
this.minorDeities = set;
}
public void addMinorDeity(Deity deity)
{
this.minorDeities.add(deity.getName());
}
public void removeMinorDeity(Deity deity)
{
this.minorDeities.remove(deity.getName());
}
void setMojangAccount(DPlayer player)
{
this.mojangAccount = player.getMojangAccount();
}
public void setActive(boolean option)
{
this.active = option;
Util.save(this);
}
public void saveInventory()
{
this.inventory = Util.createInventory(this).getId();
this.enderInventory = Util.createEnderInventory(this).getId();
Util.save(this);
}
public void setAlive(boolean alive)
{
this.alive = alive;
Util.save(this);
}
public void setHealth(double health)
{
this.health = health;
}
public void setHunger(int hunger)
{
this.hunger = hunger;
}
public void setLevel(int level)
{
this.level = level;
}
public void setExperience(float exp)
{
this.experience = exp;
}
public void setLocation(Location location)
{
this.location = CLocations.create(location).getId();
}
public void setBedSpawn(Location location)
{
this.bedSpawn = CLocations.create(location).getId();
}
public void setGameMode(GameMode gameMode)
{
this.gameMode = gameMode;
}
public void setMeta(Meta meta)
{
this.meta = meta.getId();
}
public void setUsable(boolean usable)
{
this.usable = usable;
}
public void setPotionEffects(Collection<PotionEffect> potions)
{
if(potions != null)
{
if(potionEffects == null) potionEffects = Sets.newHashSet();
for(PotionEffect potion : potions)
potionEffects.add((new DSavedPotion(potion)).getId().toString());
}
}
public Set<PotionEffect> getPotionEffects()
{
if(potionEffects == null) potionEffects = Sets.newHashSet();
Set<PotionEffect> set = new HashSet<PotionEffect>();
for(String stringId : potionEffects)
{
try
{
PotionEffect potion = Util.getSavedPotion(UUID.fromString(stringId)).toPotionEffect();
if(potion != null)
{
DataManager.savedPotions.remove(UUID.fromString(stringId));
set.add(potion);
}
}
catch(Exception ignored)
{}
}
potionEffects.clear();
return set;
}
public Collection<DSavedPotion> getRawPotionEffects()
{
if(potionEffects == null) potionEffects = Sets.newHashSet();
return Collections2.transform(potionEffects, new Function<String, DSavedPotion>()
{
@Override
public DSavedPotion apply(String s)
{
try
{
return DataManager.savedPotions.get(UUID.fromString(s));
}
catch(Exception ignored)
{}
return null;
}
});
}
public CInventory getInventory()
{
if(Util.getInventory(inventory) == null) inventory = Util.createEmptyInventory().getId();
return Util.getInventory(inventory);
}
public CEnderInventory getEnderInventory()
{
if(Util.getEnderInventory(enderInventory) == null) enderInventory = Util.createEnderInventory(this).getId();
return Util.getEnderInventory(enderInventory);
}
public Meta getMeta()
{
return Util.loadMeta(meta);
}
public OfflinePlayer getOfflinePlayer()
{
return Bukkit.getOfflinePlayer(getPlayerName());
}
public String getName()
{
return name;
}
public boolean isActive()
{
return active;
}
public Location getLocation()
{
if(location == null) return null;
return CLocations.load(location).toLocation();
}
public Location getBedSpawn()
{
if(bedSpawn == null) return null;
return CLocations.load(bedSpawn).toLocation();
}
public GameMode getGameMode()
{
return gameMode;
}
public Location getCurrentLocation()
{
if(getOfflinePlayer().isOnline()) return getOfflinePlayer().getPlayer().getLocation();
return getLocation();
}
@Override
public DCharacter getRelatedCharacter()
{
return this;
}
@Override
public LivingEntity getEntity()
{
return getOfflinePlayer().getPlayer();
}
public String getMojangAccount()
{
return mojangAccount;
}
public String getPlayerName()
{
return DPlayer.Util.getPlayer(mojangAccount).getPlayerName();
}
public Integer getLevel()
{
return level;
}
public boolean isAlive()
{
return alive;
}
public Double getHealth()
{
return health;
}
public Double getMaxHealth()
{
return getDeity().getMaxHealth();
}
public Integer getHunger()
{
return hunger;
}
public Float getExperience()
{
return experience;
}
public boolean isDeity(String deityName)
{
return getDeity().getName().equalsIgnoreCase(deityName);
}
public Deity getDeity()
{
return Deity.Util.getDeity(this.deity);
}
public Collection<Deity> getMinorDeities()
{
return Collections2.transform(minorDeities, new Function<String, Deity>()
{
@Override
public Deity apply(String deity)
{
return Deity.Util.getDeity(deity);
}
});
}
public Alliance getAlliance()
{
return getDeity().getAlliance();
}
public int getKillCount()
{
return killCount;
}
public void setKillCount(int amount)
{
killCount = amount;
Util.save(this);
}
public void addKill()
{
killCount += 1;
Util.save(this);
}
public int getDeathCount()
{
return deaths.size();
}
public void addDeath()
{
if(deaths == null) deaths = Sets.newHashSet();
deaths.add(new DDeath(this).getId().toString());
Util.save(this);
}
public void addDeath(DCharacter attacker)
{
deaths.add(new DDeath(this, attacker).getId().toString());
Util.save(this);
}
public Collection<DDeath> getDeaths()
{
if(deaths == null) deaths = Sets.newHashSet();
return Collections2.transform(deaths, new Function<String, DDeath>()
{
@Override
public DDeath apply(String s)
{
try
{
return DDeath.Util.load(UUID.fromString(s));
}
catch(Exception ignored)
{}
return null;
}
});
}
public Collection<StructureData> getOwnedStructures()
{
return StructureData.Util.findAll(new Predicate<StructureData>()
{
@Override
public boolean apply(StructureData data)
{
return data.getOwner().equals(getId());
}
});
}
public Collection<StructureData> getOwnedStructures(final String type)
{
return StructureData.Util.findAll(new Predicate<StructureData>()
{
@Override
public boolean apply(StructureData data)
{
return data.getTypeName().equals(type) && data.getOwner().equals(getId());
}
});
}
public int getFavorRegen()
{
int favorRegenSkill = getMeta().getSkill(Skill.Type.FAVOR_REGEN) != null ? 4 * getMeta().getSkill(Skill.Type.FAVOR_REGEN).getLevel() : 0;
int regenRate = (int) Math.ceil(Configs.getSettingDouble("multipliers.favor") * (getDeity().getFavorRegen() + favorRegenSkill));
if(regenRate < 30) regenRate = 30;
return regenRate;
}
public void setCanPvp(boolean pvp)
{
DPlayer.Util.getPlayer(getOfflinePlayer()).setCanPvp(pvp);
}
@Override
public boolean canPvp()
{
return DPlayer.Util.getPlayer(getMojangAccount()).canPvp();
}
public boolean isUsable()
{
return usable;
}
public void updateUseable()
{
usable = Deity.Util.getDeity(this.deity) != null && Deity.Util.getDeity(this.deity).getFlags().contains(Deity.Flag.PLAYABLE);
}
public UUID getId()
{
return id;
}
public Collection<DPet> getPets()
{
return DPet.Util.findByOwner(id);
}
public void remove()
{
// Define the DPlayer
DPlayer dPlayer = DPlayer.Util.getPlayer(getOfflinePlayer());
// Switch the player to mortal
if(getOfflinePlayer().isOnline() && dPlayer.getCurrent().getName().equalsIgnoreCase(getName())) dPlayer.setToMortal();
// Remove the data
if(dPlayer.getCurrent().getName().equalsIgnoreCase(getName())) dPlayer.resetCurrent();
for(StructureData structureSave : Structure.Util.getStructureWithFlag(Structure.Flag.DELETE_WITH_OWNER))
if(structureSave.hasOwner() && structureSave.getOwner().equals(getId())) structureSave.remove();
for(DSavedPotion potion : getRawPotionEffects())
DataManager.savedPotions.remove(potion.getId());
Util.deleteInventory(getInventory().getId());
Util.deleteEnderInventory(getEnderInventory().getId());
Util.deleteMeta(getMeta().getId());
Util.delete(getId());
}
public void sendAllianceMessage(String message)
{
DemigodsChatEvent chatEvent = new DemigodsChatEvent(message, DCharacter.Util.getOnlineCharactersWithAlliance(getAlliance()));
Bukkit.getPluginManager().callEvent(chatEvent);
if(!chatEvent.isCancelled()) for(Player player : chatEvent.getRecipients())
player.sendMessage(message);
}
public void chatWithAlliance(String message)
{
sendAllianceMessage(" " + ChatColor.GRAY + getAlliance() + "s " + ChatColor.DARK_GRAY + "" + Symbol.BLACK_FLAG + " " + getDeity().getColor() + name + ChatColor.GRAY + ": " + ChatColor.RESET + message);
Messages.info("[" + getAlliance() + "]" + name + ": " + message);
}
public void applyToPlayer(final Player player)
{
// Define variables
DPlayer playerSave = DPlayer.Util.getPlayer(player);
// Set character to active
setActive(true);
if(playerSave.getMortalInventory() != null)
{
playerSave.setMortalName(player.getDisplayName());
playerSave.setMortalListName(player.getPlayerListName());
}
// Update their inventory
if(playerSave.getCharacters().size() == 1) saveInventory();
else player.getEnderChest().clear();
getInventory().setToPlayer(player);
getEnderInventory().setToPlayer(player);
// Update health, experience, and name
player.setDisplayName(getDeity().getColor() + getName());
player.setPlayerListName(getDeity().getColor() + getName());
player.setMaxHealth(getMaxHealth());
player.setHealth(getHealth() >= getMaxHealth() ? getMaxHealth() : getHealth());
player.setFoodLevel(getHunger());
player.setExp(getExperience());
player.setLevel(getLevel());
for(PotionEffect potion : player.getActivePotionEffects())
player.removePotionEffect(potion.getType());
- if(getPotionEffects() != null) player.addPotionEffects(getPotionEffects());
+ Set<PotionEffect> potionEffects = getPotionEffects();
+ if(!potionEffects.isEmpty()) player.addPotionEffects(potionEffects);
Bukkit.getScheduler().scheduleSyncDelayedTask(Demigods.PLUGIN, new BukkitRunnable()
{
@Override
public void run()
{
if(getBedSpawn() != null) player.setBedSpawnLocation(getBedSpawn());
}
}, 1);
if(gameMode != null) player.setGameMode(gameMode);
// Set player display name
player.setDisplayName(getDeity().getColor() + getName());
player.setPlayerListName(getDeity().getColor() + getName());
// Re-own pets
DPet.Util.reownPets(player, this);
// Add to their team
Demigods.BOARD.getTeam(getAlliance().getName()).removePlayer(getOfflinePlayer());
}
public static class Inventory extends CInventory
{
public Inventory()
{
super();
}
public Inventory(UUID id, ConfigurationSection conf)
{
super(id, conf);
}
protected CItemStack create(ItemStack itemStack)
{
return CItemStacks.create(itemStack);
}
protected CItemStack load(UUID itemStack)
{
return CItemStacks.load(itemStack);
}
protected void delete()
{
DataManager.inventories.remove(getId());
}
}
public static class EnderInventory extends CEnderInventory
{
public EnderInventory()
{
super();
}
public EnderInventory(UUID id, ConfigurationSection conf)
{
super(id, conf);
}
protected CItemStack create(ItemStack itemStack)
{
return CItemStacks.create(itemStack);
}
protected CItemStack load(UUID itemStack)
{
return CItemStacks.load(itemStack);
}
protected void delete()
{
DataManager.enderInventories.remove(this.getId());
}
}
public static class Meta implements ConfigurationSerializable
{
private UUID id;
private UUID character;
private int favor;
private int maxFavor;
private int skillPoints;
private Set<String> notifications;
private Map<String, Object> binds;
private Map<String, Object> skillData;
private Map<String, Object> warps;
private Map<String, Object> invites;
public Meta()
{}
public Meta(UUID id, ConfigurationSection conf)
{
this.id = id;
favor = conf.getInt("favor");
maxFavor = conf.getInt("maxFavor");
skillPoints = conf.getInt("skillPoints");
notifications = Sets.newHashSet(conf.getStringList("notifications"));
character = UUID.fromString(conf.getString("character"));
if(conf.getConfigurationSection("skillData") != null) skillData = conf.getConfigurationSection("skillData").getValues(false);
if(conf.getConfigurationSection("binds") != null) binds = conf.getConfigurationSection("binds").getValues(false);
if(conf.getConfigurationSection("warps") != null) warps = conf.getConfigurationSection("warps").getValues(false);
if(conf.getConfigurationSection("invites") != null) invites = conf.getConfigurationSection("invites").getValues(false);
}
@Override
public Map<String, Object> serialize()
{
Map<String, Object> map = Maps.newHashMap();
map.put("character", character.toString());
map.put("favor", favor);
map.put("maxFavor", maxFavor);
map.put("skillPoints", skillPoints);
map.put("notifications", Lists.newArrayList(notifications));
map.put("binds", binds);
map.put("skillData", skillData);
map.put("warps", warps);
map.put("invites", invites);
return map;
}
public void generateId()
{
id = UUID.randomUUID();
}
void setCharacter(DCharacter character)
{
this.character = character.getId();
}
void initialize()
{
notifications = Sets.newHashSet();
warps = Maps.newHashMap();
invites = Maps.newHashMap();
skillData = Maps.newHashMap();
binds = Maps.newHashMap();
}
public UUID getId()
{
return id;
}
public DCharacter getCharacter()
{
return DCharacter.Util.load(character);
}
public void setSkillPoints(int skillPoints)
{
this.skillPoints = skillPoints;
}
public int getSkillPoints()
{
return skillPoints;
}
public void addSkillPoints(int skillPoints)
{
setSkillPoints(getSkillPoints() + skillPoints);
}
public void subtractSkillPoints(int skillPoints)
{
setSkillPoints(getSkillPoints() - skillPoints);
}
public void addNotification(Notification notification)
{
getNotifications().add(notification.getId().toString());
Util.saveMeta(this);
}
public void removeNotification(Notification notification)
{
getNotifications().remove(notification.getId().toString());
Util.saveMeta(this);
}
public Set<String> getNotifications()
{
if(this.notifications == null) this.notifications = Sets.newHashSet();
return this.notifications;
}
public void clearNotifications()
{
notifications.clear();
}
public boolean hasNotifications()
{
return !notifications.isEmpty();
}
public void addWarp(String name, Location location)
{
warps.put(name.toLowerCase(), CLocations.create(location).getId().toString());
Util.saveMeta(this);
}
public void removeWarp(String name)
{
getWarps().remove(name.toLowerCase());
Util.saveMeta(this);
}
public Map<String, Object> getWarps()
{
if(this.warps == null) this.warps = Maps.newHashMap();
return this.warps;
}
public void clearWarps()
{
getWarps().clear();
}
public boolean hasWarps()
{
return !this.warps.isEmpty();
}
public void addInvite(String name, Location location)
{
getInvites().put(name.toLowerCase(), CLocations.create(location).getId().toString());
Util.saveMeta(this);
}
public void removeInvite(String name)
{
getInvites().remove(name.toLowerCase());
Util.saveMeta(this);
}
public Map<String, Object> getInvites()
{
if(this.invites == null) this.invites = Maps.newHashMap();
return this.invites;
}
public void clearInvites()
{
invites.clear();
}
public boolean hasInvites()
{
return !this.invites.isEmpty();
}
public void resetSkills()
{
getRawSkills().clear();
for(Skill.Type type : Skill.Type.values())
if(type.isDefault()) addSkill(Skill.Util.createSkill(getCharacter(), type));
}
public void cleanSkills()
{
List<String> toRemove = Lists.newArrayList();
// Locate obselete skills
for(String skillName : getRawSkills().keySet())
{
try
{
// Attempt to find the value of the skillname
Skill.Type.valueOf(skillName.toUpperCase());
}
catch(Exception ignored)
{
// There was an error. Catch it and remove the skill.
toRemove.add(skillName);
}
}
// Remove the obsolete skills
for(String skillName : toRemove)
getRawSkills().remove(skillName);
}
public void addSkill(Skill skill)
{
if(!getRawSkills().containsKey(skill.getType().toString())) getRawSkills().put(skill.getType().toString(), skill.getId().toString());
Util.saveMeta(this);
}
public Skill getSkill(Skill.Type type)
{
if(getRawSkills().containsKey(type.toString())) return Skill.Util.loadSkill(UUID.fromString(getRawSkills().get(type.toString()).toString()));
return null;
}
public Map<String, Object> getRawSkills()
{
if(skillData == null) skillData = Maps.newHashMap();
return skillData;
}
public Collection<Skill> getSkills()
{
return Collections2.transform(getRawSkills().values(), new Function<Object, Skill>()
{
@Override
public Skill apply(Object obj)
{
return Skill.Util.loadSkill(UUID.fromString(obj.toString()));
}
});
}
public boolean checkBound(String abilityName, Material material)
{
return getBinds().containsKey(abilityName) && binds.get(abilityName).equals(material.name());
}
public boolean isBound(Ability ability)
{
return getBinds().containsKey(ability.getName());
}
public boolean isBound(Material material)
{
return getBinds().containsValue(material.name());
}
public void setBind(Ability ability, Material material)
{
getBinds().put(ability.getName(), material.name());
}
public Map<String, Object> getBinds()
{
if(binds == null) binds = Maps.newHashMap();
return this.binds;
}
public void removeBind(Ability ability)
{
getBinds().remove(ability.getName());
}
public void removeBind(Material material)
{
if(getBinds().containsValue(material.name()))
{
String toRemove = null;
for(Map.Entry<String, Object> entry : getBinds().entrySet())
{
toRemove = entry.getValue().equals(material.name()) ? entry.getKey() : null;
}
getBinds().remove(toRemove);
}
}
public int getIndividualSkillCap()
{
int total = 0;
for(Skill skill : getSkills())
total += skill.getLevel();
return getOverallSkillCap() - total;
}
public int getOverallSkillCap()
{
// This is done this way so it can easily be manipulated later
return Configs.getSettingInt("caps.skills");
}
public int getAscensions()
{
if(LEVEL_SEPERATE_SKILLS)
{
double total = 0.0;
for(Skill skill : getSkills())
total += skill.getLevel();
return (int) Math.ceil(total / getSkills().size());
}
return (int) Math.ceil(getSkillPoints() / 500); // TODO Balance this.
}
public Integer getFavor()
{
return favor;
}
public void setFavor(int amount)
{
favor = amount;
Util.saveMeta(this);
}
public void addFavor(int amount)
{
if((favor + amount) > maxFavor) favor = maxFavor;
else favor += amount;
Util.saveMeta(this);
}
public void subtractFavor(int amount)
{
if((favor - amount) < 0) favor = 0;
else favor -= amount;
Util.saveMeta(this);
}
public Integer getMaxFavor()
{
return maxFavor;
}
public void addMaxFavor(int amount)
{
if((maxFavor + amount) > Configs.getSettingInt("caps.favor")) maxFavor = Configs.getSettingInt("caps.favor");
else maxFavor += amount;
Util.saveMeta(this);
}
public void setMaxFavor(int amount)
{
if(amount < 0) maxFavor = 0;
if(amount > Configs.getSettingInt("caps.favor")) maxFavor = Configs.getSettingInt("caps.favor");
else maxFavor = amount;
Util.saveMeta(this);
}
public void subtractMaxFavor(int amount)
{
setMaxFavor(getMaxFavor() - amount);
}
}
public static class Util
{
public static void save(DCharacter character)
{
DataManager.characters.put(character.getId(), character);
}
public static void saveMeta(Meta meta)
{
DataManager.characterMetas.put(meta.getId(), meta);
}
public static void saveInventory(Inventory inventory)
{
DataManager.inventories.put(inventory.getId(), inventory);
}
public static void saveInventory(EnderInventory inventory)
{
DataManager.enderInventories.put(inventory.getId(), inventory);
}
public static void delete(UUID id)
{
DataManager.characters.remove(id);
}
public static void deleteMeta(UUID id)
{
DataManager.characterMetas.remove(id);
}
public static void deleteInventory(UUID id)
{
DataManager.inventories.remove(id);
}
public static void deleteEnderInventory(UUID id)
{
DataManager.enderInventories.remove(id);
}
public static void create(DPlayer player, String chosenDeity, String chosenName, boolean switchCharacter)
{
// Switch to new character
if(switchCharacter) player.switchCharacter(create(player, chosenName, chosenDeity));
}
public static DCharacter create(DPlayer player, String charName, String charDeity)
{
if(getCharacterByName(charName) == null)
{
// Create the DCharacter
return create(player, charName, Deity.Util.getDeity(charDeity));
}
return null;
}
private static DCharacter create(final DPlayer player, final String charName, final Deity deity)
{
DCharacter character = new DCharacter();
character.generateId();
character.setAlive(true);
character.setMojangAccount(player);
character.setName(charName);
character.setDeity(deity);
character.setMinorDeities(new HashSet<String>(0));
character.setUsable(true);
character.setHealth(deity.getMaxHealth());
character.setHunger(20);
character.setExperience(0);
character.setLevel(0);
character.setKillCount(0);
character.setLocation(player.getOfflinePlayer().getPlayer().getLocation());
character.setMeta(Util.createMeta(character));
save(character);
return character;
}
public static CInventory createInventory(DCharacter character)
{
PlayerInventory inventory = character.getOfflinePlayer().getPlayer().getInventory();
Inventory charInventory = new Inventory();
charInventory.generateId();
if(inventory.getHelmet() != null) charInventory.setHelmet(inventory.getHelmet());
if(inventory.getChestplate() != null) charInventory.setChestplate(inventory.getChestplate());
if(inventory.getLeggings() != null) charInventory.setLeggings(inventory.getLeggings());
if(inventory.getBoots() != null) charInventory.setBoots(inventory.getBoots());
charInventory.setItems(inventory);
saveInventory(charInventory);
return charInventory;
}
public static CInventory createEmptyInventory()
{
Inventory charInventory = new Inventory();
charInventory.generateId();
charInventory.setHelmet(new ItemStack(Material.AIR));
charInventory.setChestplate(new ItemStack(Material.AIR));
charInventory.setLeggings(new ItemStack(Material.AIR));
charInventory.setBoots(new ItemStack(Material.AIR));
saveInventory(charInventory);
return charInventory;
}
public static CEnderInventory createEnderInventory(DCharacter character)
{
org.bukkit.inventory.Inventory inventory = character.getOfflinePlayer().getPlayer().getEnderChest();
EnderInventory enderInventory = new EnderInventory();
enderInventory.generateId();
enderInventory.setItems(inventory);
saveInventory(enderInventory);
return enderInventory;
}
public static CEnderInventory createEmptyEnderInventory()
{
EnderInventory enderInventory = new EnderInventory();
enderInventory.generateId();
saveInventory(enderInventory);
return enderInventory;
}
public static Meta createMeta(DCharacter character)
{
Meta charMeta = new Meta();
charMeta.initialize();
charMeta.setCharacter(character);
charMeta.generateId();
charMeta.setFavor(Configs.getSettingInt("character.defaults.favor"));
charMeta.setMaxFavor(Configs.getSettingInt("character.defaults.max_favor"));
charMeta.resetSkills();
saveMeta(charMeta);
return charMeta;
}
public static Set<DCharacter> loadAll()
{
return Sets.newHashSet(DataManager.characters.values());
}
public static DCharacter load(UUID id)
{
return DataManager.characters.get(id);
}
public static Meta loadMeta(UUID id)
{
return DataManager.characterMetas.get(id);
}
public static Inventory getInventory(UUID id)
{
try
{
return DataManager.inventories.get(id);
}
catch(Exception ignored)
{}
return null;
}
public static EnderInventory getEnderInventory(UUID id)
{
try
{
return DataManager.enderInventories.get(id);
}
catch(Exception ignored)
{}
return null;
}
public static DSavedPotion getSavedPotion(UUID id)
{
try
{
return DataManager.savedPotions.get(id);
}
catch(Exception ignored)
{}
return null;
}
public static void updateUsableCharacters()
{
for(DCharacter character : loadAll())
character.updateUseable();
}
public static DCharacter getCharacterByName(final String name)
{
try
{
return Iterators.find(loadAll().iterator(), new Predicate<DCharacter>()
{
@Override
public boolean apply(DCharacter loaded)
{
return loaded.getName().equalsIgnoreCase(name);
}
});
}
catch(Exception ignored)
{}
return null;
}
public static boolean charExists(String name)
{
return getCharacterByName(name) != null;
}
public static boolean isCooledDown(DCharacter player, String ability, boolean sendMsg)
{
if(DataManager.hasKeyTemp(player.getName(), ability + "_cooldown") && Long.parseLong(DataManager.getValueTemp(player.getName(), ability + "_cooldown").toString()) > System.currentTimeMillis())
{
if(sendMsg) player.getOfflinePlayer().getPlayer().sendMessage(ChatColor.RED + ability + " has not cooled down!");
return false;
}
else return true;
}
public static void setCoolDown(DCharacter player, String ability, long cooldown)
{
DataManager.saveTemp(player.getName(), ability + "_cooldown", cooldown);
}
public static long getCoolDown(DCharacter player, String ability)
{
return Long.parseLong(DataManager.getValueTemp(player.getName(), ability + "_cooldown").toString());
}
public static Set<DCharacter> getAllActive()
{
return Sets.filter(loadAll(), new Predicate<DCharacter>()
{
@Override
public boolean apply(DCharacter character)
{
return character.isUsable() && character.isActive();
}
});
}
public static Set<DCharacter> getAllUsable()
{
return Sets.filter(loadAll(), new Predicate<DCharacter>()
{
@Override
public boolean apply(DCharacter character)
{
return character.isUsable();
}
});
}
/**
* Returns true if <code>char1</code> is allied with <code>char2</code> based
* on their current alliances.
*
* @param char1 the first character to check.
* @param char2 the second character to check.
* @return boolean
*/
public static boolean areAllied(DCharacter char1, DCharacter char2)
{
return char1.getAlliance().getName().equalsIgnoreCase(char2.getAlliance().getName());
}
public static Collection<DCharacter> getOnlineCharactersWithDeity(final String deity)
{
return getCharactersWithPredicate(new Predicate<DCharacter>()
{
@Override
public boolean apply(DCharacter character)
{
return character.isActive() && character.getOfflinePlayer().isOnline() && character.getDeity().getName().equalsIgnoreCase(deity);
}
});
}
public static Collection<DCharacter> getOnlineCharactersWithAbility(final String abilityName)
{
return getCharactersWithPredicate(new Predicate<DCharacter>()
{
@Override
public boolean apply(DCharacter character)
{
if(character.isActive() && character.getOfflinePlayer().isOnline())
{
for(Ability abilityToCheck : character.getDeity().getAbilities())
if(abilityToCheck.getName().equalsIgnoreCase(abilityName)) return true;
}
return false;
}
});
}
public static Collection<DCharacter> getOnlineCharactersWithAlliance(final Alliance alliance)
{
return getCharactersWithPredicate(new Predicate<DCharacter>()
{
@Override
public boolean apply(DCharacter character)
{
return character.isActive() && character.getOfflinePlayer().isOnline() && character.getAlliance().equals(alliance);
}
});
}
public static Collection<DCharacter> getOnlineCharactersWithoutAlliance(final Alliance alliance)
{
return getCharactersWithPredicate(new Predicate<DCharacter>()
{
@Override
public boolean apply(DCharacter character)
{
return character.isActive() && character.getOfflinePlayer().isOnline() && !character.getAlliance().equals(alliance);
}
});
}
public static Collection<DCharacter> getOnlineCharactersBelowAscension(final int ascension)
{
return getCharactersWithPredicate(new Predicate<DCharacter>()
{
@Override
public boolean apply(DCharacter character)
{
return character.isActive() && character.getOfflinePlayer().isOnline() && character.getMeta().getAscensions() < ascension;
}
});
}
public static Collection<DCharacter> getOnlineCharacters()
{
return getCharactersWithPredicate(new Predicate<DCharacter>()
{
@Override
public boolean apply(DCharacter character)
{
return character.isActive() && character.getOfflinePlayer().isOnline();
}
});
}
public static Collection<DCharacter> getCharactersWithPredicate(Predicate<DCharacter> predicate)
{
return Collections2.filter(getAllUsable(), predicate);
}
/**
* Updates favor for all online characters.
*/
public static void updateFavor()
{
for(Player player : Bukkit.getOnlinePlayers())
{
DCharacter character = DPlayer.Util.getPlayer(player).getCurrent();
if(character != null) character.getMeta().addFavor(character.getFavorRegen());
}
}
}
}
| true | true | public void applyToPlayer(final Player player)
{
// Define variables
DPlayer playerSave = DPlayer.Util.getPlayer(player);
// Set character to active
setActive(true);
if(playerSave.getMortalInventory() != null)
{
playerSave.setMortalName(player.getDisplayName());
playerSave.setMortalListName(player.getPlayerListName());
}
// Update their inventory
if(playerSave.getCharacters().size() == 1) saveInventory();
else player.getEnderChest().clear();
getInventory().setToPlayer(player);
getEnderInventory().setToPlayer(player);
// Update health, experience, and name
player.setDisplayName(getDeity().getColor() + getName());
player.setPlayerListName(getDeity().getColor() + getName());
player.setMaxHealth(getMaxHealth());
player.setHealth(getHealth() >= getMaxHealth() ? getMaxHealth() : getHealth());
player.setFoodLevel(getHunger());
player.setExp(getExperience());
player.setLevel(getLevel());
for(PotionEffect potion : player.getActivePotionEffects())
player.removePotionEffect(potion.getType());
if(getPotionEffects() != null) player.addPotionEffects(getPotionEffects());
Bukkit.getScheduler().scheduleSyncDelayedTask(Demigods.PLUGIN, new BukkitRunnable()
{
@Override
public void run()
{
if(getBedSpawn() != null) player.setBedSpawnLocation(getBedSpawn());
}
}, 1);
if(gameMode != null) player.setGameMode(gameMode);
// Set player display name
player.setDisplayName(getDeity().getColor() + getName());
player.setPlayerListName(getDeity().getColor() + getName());
// Re-own pets
DPet.Util.reownPets(player, this);
// Add to their team
Demigods.BOARD.getTeam(getAlliance().getName()).removePlayer(getOfflinePlayer());
}
| public void applyToPlayer(final Player player)
{
// Define variables
DPlayer playerSave = DPlayer.Util.getPlayer(player);
// Set character to active
setActive(true);
if(playerSave.getMortalInventory() != null)
{
playerSave.setMortalName(player.getDisplayName());
playerSave.setMortalListName(player.getPlayerListName());
}
// Update their inventory
if(playerSave.getCharacters().size() == 1) saveInventory();
else player.getEnderChest().clear();
getInventory().setToPlayer(player);
getEnderInventory().setToPlayer(player);
// Update health, experience, and name
player.setDisplayName(getDeity().getColor() + getName());
player.setPlayerListName(getDeity().getColor() + getName());
player.setMaxHealth(getMaxHealth());
player.setHealth(getHealth() >= getMaxHealth() ? getMaxHealth() : getHealth());
player.setFoodLevel(getHunger());
player.setExp(getExperience());
player.setLevel(getLevel());
for(PotionEffect potion : player.getActivePotionEffects())
player.removePotionEffect(potion.getType());
Set<PotionEffect> potionEffects = getPotionEffects();
if(!potionEffects.isEmpty()) player.addPotionEffects(potionEffects);
Bukkit.getScheduler().scheduleSyncDelayedTask(Demigods.PLUGIN, new BukkitRunnable()
{
@Override
public void run()
{
if(getBedSpawn() != null) player.setBedSpawnLocation(getBedSpawn());
}
}, 1);
if(gameMode != null) player.setGameMode(gameMode);
// Set player display name
player.setDisplayName(getDeity().getColor() + getName());
player.setPlayerListName(getDeity().getColor() + getName());
// Re-own pets
DPet.Util.reownPets(player, this);
// Add to their team
Demigods.BOARD.getTeam(getAlliance().getName()).removePlayer(getOfflinePlayer());
}
|
diff --git a/core/plugins/org.eclipse.dltk.core/model/org/eclipse/dltk/internal/core/ModelElement.java b/core/plugins/org.eclipse.dltk.core/model/org/eclipse/dltk/internal/core/ModelElement.java
index 1d568e018..04ba952c9 100644
--- a/core/plugins/org.eclipse.dltk.core/model/org/eclipse/dltk/internal/core/ModelElement.java
+++ b/core/plugins/org.eclipse.dltk.core/model/org/eclipse/dltk/internal/core/ModelElement.java
@@ -1,748 +1,748 @@
/*******************************************************************************
* Copyright (c) 2005, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package org.eclipse.dltk.internal.core;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.PlatformObject;
import org.eclipse.dltk.core.DLTKCore;
import org.eclipse.dltk.core.IField;
import org.eclipse.dltk.core.IModelElement;
import org.eclipse.dltk.core.IModelElementMemento;
import org.eclipse.dltk.core.IModelElementVisitor;
import org.eclipse.dltk.core.IModelElementVisitorExtension;
import org.eclipse.dltk.core.IModelStatus;
import org.eclipse.dltk.core.IModelStatusConstants;
import org.eclipse.dltk.core.IOpenable;
import org.eclipse.dltk.core.IParent;
import org.eclipse.dltk.core.IScriptModel;
import org.eclipse.dltk.core.IScriptProject;
import org.eclipse.dltk.core.ISourceModule;
import org.eclipse.dltk.core.ISourceRange;
import org.eclipse.dltk.core.ISourceReference;
import org.eclipse.dltk.core.ModelException;
import org.eclipse.dltk.core.ScriptModelUtil;
import org.eclipse.dltk.core.WorkingCopyOwner;
import org.eclipse.dltk.internal.core.util.MementoTokenizer;
import org.eclipse.dltk.internal.core.util.Util;
import org.eclipse.dltk.utils.CorePrinter;
/**
* Root of model element handle hierarchy.
*
* @see IModelElement
*/
public abstract class ModelElement extends PlatformObject implements
IModelElement, IModelElementMemento {
public static final char JEM_ESCAPE = '\\';
public static final char JEM_SCRIPTPROJECT = '=';
public static final char JEM_PROJECTFRAGMENT = '/';
public static final char JEM_SCRIPTFOLDER = '<';
public static final char JEM_FIELD = '^';
public static final char JEM_METHOD = '~';
public static final char JEM_SOURCEMODULE = '{';
public static final char JEM_TYPE = '[';
public static final char JEM_IMPORTDECLARATION = '&';
public static final char JEM_COUNT = '!';
public static final char JEM_LOCALVARIABLE = '@';
public static final char JEM_TYPE_PARAMETER = ']';
public static final char JEM_PACKAGEDECLARATION = '%';
/**
* This Item is for direct user element handle. Resolving of elements with
* such delimiter requires building of the model.
*/
public static final char JEM_USER_ELEMENT = '}';
public static final String JEM_USER_ELEMENT_ENDING = "=/<^~{[&!@]%}";
// Used to replace path / or \\ symbols in external package names and
// archives.
public static final char JEM_SKIP_DELIMETER = '>';
/**
* This element's parent, or <code>null</code> if this element does not have
* a parent.
*/
protected final ModelElement parent;
protected static final ModelElement[] NO_ELEMENTS = new ModelElement[0];
protected static final Object NO_INFO = new Object();
/**
* Constructs a handle for a model element with the given parent element.
*
* @param parent
* The parent of model element
*
* @exception IllegalArgumentException
* if the type is not one of the valid model element type
* constants
*
*/
protected ModelElement(ModelElement parent) throws IllegalArgumentException {
this.parent = parent;
}
/**
* @see IModelElement
*/
public boolean exists() {
try {
getElementInfo();
return true;
} catch (ModelException e) {
// element doesn't exist: return false
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
}
return false;
}
/**
* @see IModelElement
*/
public IModelElement getAncestor(int ancestorType) {
IModelElement element = this;
while (element != null) {
if (element.getElementType() == ancestorType)
return element;
element = element.getParent();
}
return null;
}
@SuppressWarnings("unchecked")
public <E extends IModelElement> E getAncestor(Class<E> elementClass) {
IModelElement element = this;
do {
if (elementClass.isInstance(element)) {
return (E) element;
}
element = element.getParent();
} while (element != null);
return null;
}
/**
* @see IOpenable
*/
public void close() throws ModelException {
ModelManager.getModelManager().removeInfoAndChildren(this);
}
/**
* This element is being closed. Do any necessary cleanup.
*/
protected abstract void closing(Object info) throws ModelException;
/**
* Returns the info for this handle. If this element is not already open, it
* and all of its parents are opened. Does not return null. NOTE: BinaryType
* infos are NOT rooted under ModelElementInfo.
*
* @exception ModelException
* if the element is not present or not accessible
*/
public Object getElementInfo() throws ModelException {
return getElementInfo(null);
}
/**
* Returns the info for this handle. If this element is not already open, it
* and all of its parents are opened. Does not return null. NOTE: BinaryType
* infos are NOT rooted under ModelElementInfo.
*
* @exception ModelException
* if the element is not present or not accessible
*/
public Object getElementInfo(IProgressMonitor monitor)
throws ModelException {
ModelManager manager = ModelManager.getModelManager();
Object info = manager.getInfo(this);
if (info != null)
return info;
return openWhenClosed(createElementInfo(), monitor);
}
/*
* Opens an <code>Openable</code> that is known to be closed (no check for
* <code>isOpen()</code>). Returns the created element info.
*/
protected Object openWhenClosed(Object info, IProgressMonitor monitor)
throws ModelException {
ModelManager manager = ModelManager.getModelManager();
boolean hadTemporaryCache = manager.hasTemporaryCache();
try {
HashMap newElements = manager.getTemporaryCache();
generateInfos(info, newElements, monitor);
if (info == null) {
info = newElements.get(this);
}
if (info == null) { // a source ref element could not be opened
// close the buffer that was opened for the openable parent
// close only the openable's buffer (see
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=62854)
Openable openable = (Openable) getOpenable();
if (newElements.containsKey(openable)) {
openable.closeBuffer();
}
throw newNotPresentException();
}
if (!hadTemporaryCache) {
manager.putInfos(this, newElements);
}
} finally {
if (!hadTemporaryCache) {
manager.resetTemporaryCache();
}
}
return info;
}
/*
* @see IModelElement
*/
public IOpenable getOpenable() {
return this.getOpenableParent();
}
/**
* Return the first instance of IOpenable in the parent hierarchy of this
* element.
*
* <p>
* Subclasses that are not IOpenable's must override this method.
*/
public IOpenable getOpenableParent() {
return (IOpenable) this.parent;
}
/**
* @see IModelElement
*/
public IModelElement getParent() {
return this.parent;
}
/*
* Returns a new element info for this element.
*/
protected abstract Object createElementInfo();
/**
* Generates the element infos for this element, its ancestors (if they are
* not opened) and its children (if it is an Openable). Puts the newly
* created element info in the given map.
*/
protected abstract void generateInfos(Object info, HashMap newElements,
IProgressMonitor pm) throws ModelException;
/**
* @see IAdaptable
*/
public String getElementName() {
return ""; //$NON-NLS-1$
}
/**
* Creates and returns a new not present exception for this element.
*/
public ModelException newNotPresentException() {
return new ModelException(new ModelStatus(
IModelStatusConstants.ELEMENT_DOES_NOT_EXIST, this));
}
/**
* Returns true if this handle represents the same model element as the
* given handle. By default, two handles represent the same element if they
* are identical or if they represent the same type of element, have equal
* names, parents, and occurrence counts.
*
* <p>
* If a subclass has other requirements for equality, this method must be
* overridden.
*
* @see Object#equals
*/
public boolean equals(Object o) {
if (this == o)
return true;
// model parent is null
if (this.parent == null) {
return super.equals(o);
}
if (o == null) {
return false;
}
// assume instanceof check is done in subclass
final ModelElement other = (ModelElement) o;
return getElementName().equals(other.getElementName())
&& this.parent.equals(other.parent);
}
/**
* Returns the hash code for this model element. By default, the hash code
* for an element is a combination of its name and parent's hash code.
* Elements with other requirements must override this method.
*/
public int hashCode() {
if (this.parent == null)
return super.hashCode();
return Util.combineHashCodes(getElementName().hashCode(), this.parent
.hashCode());
}
/**
* Returns true if this element is an ancestor of the given element,
* otherwise false.
*/
public boolean isAncestorOf(IModelElement e) {
IModelElement parentElement = e.getParent();
while (parentElement != null && !parentElement.equals(this)) {
parentElement = parentElement.getParent();
}
return parentElement != null;
}
/**
* @see IModelElement
*/
public boolean isReadOnly() {
return false;
}
/**
* Returns a collection of (immediate) children of this node of the
* specified type.
*
* @param type
* - one of the EM_* constants defined by ModelElement
*/
protected List<IModelElement> getChildrenOfType(int type)
throws ModelException {
return getChildrenOfType(type, null);
}
protected List<IModelElement> getChildrenOfType(int type,
IProgressMonitor monitor) throws ModelException {
IModelElement[] children = getChildren(monitor);
int size = children.length;
List<IModelElement> list = new ArrayList<IModelElement>(size);
for (int i = 0; i < size; ++i) {
IModelElement elt = children[i];
if (elt.getElementType() == type) {
list.add(elt);
}
}
return list;
}
/**
* @see IParent
*/
public IModelElement[] getChildren() throws ModelException {
return getChildren(null);
}
public IModelElement[] getChildren(IProgressMonitor monitor)
throws ModelException {
Object elementInfo = getElementInfo(monitor);
if (elementInfo instanceof ModelElementInfo) {
return ((ModelElementInfo) elementInfo).getChildren();
} else {
return NO_ELEMENTS;
}
}
/**
* @see IModelElement
*/
public IScriptModel getModel() {
IModelElement current = this;
do {
if (current instanceof IScriptModel)
return (IScriptModel) current;
} while ((current = current.getParent()) != null);
return null;
}
/**
* Creates and returns a new model exception for this element with the given
* status.
*/
public ModelException newModelException(IStatus status) {
if (status instanceof IModelStatus)
return new ModelException((IModelStatus) status);
else
return new ModelException(new ModelStatus(status.getSeverity(),
status.getCode(), status.getMessage()));
}
/**
* @see IModelElement
*/
public IScriptProject getScriptProject() {
IModelElement current = this;
do {
if (current instanceof IScriptProject)
return (IScriptProject) current;
} while ((current = current.getParent()) != null);
return null;
}
public boolean hasChildren() throws ModelException {
// if I am not open, return true to avoid opening (case of a project, a
// source module or a binary file).
Object elementInfo = ModelManager.getModelManager().getInfo(this);
if (elementInfo instanceof ModelElementInfo) {
return ((ModelElementInfo) elementInfo).getChildren().length > 0;
} else {
return true;
}
}
/**
* Debugging purposes
*/
protected String tabString(int tab) {
StringBuffer buffer = new StringBuffer();
for (int i = tab; i > 0; i--)
buffer.append(" "); //$NON-NLS-1$
return buffer.toString();
}
/**
* Debugging purposes
*/
public String toDebugString() {
StringBuffer buffer = new StringBuffer();
this.toStringInfo(0, buffer, NO_INFO, true/* show resolved info */);
return buffer.toString();
}
/**
* Debugging purposes
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
toString(0, buffer);
return buffer.toString();
}
/**
* Debugging purposes
*/
protected void toString(int tab, StringBuffer buffer) {
Object info = this.toStringInfo(tab, buffer);
if (tab == 0) {
this.toStringAncestors(buffer);
}
this.toStringChildren(tab, buffer, info);
}
/**
* Debugging purposes
*/
public String toStringWithAncestors() {
return toStringWithAncestors(true/* show resolved info */);
}
/**
* Debugging purposes
*/
public String toStringWithAncestors(boolean showResolvedInfo) {
StringBuffer buffer = new StringBuffer();
this.toStringInfo(0, buffer, NO_INFO, showResolvedInfo);
this.toStringAncestors(buffer);
return buffer.toString();
}
/**
* Debugging purposes
*/
protected void toStringAncestors(StringBuffer buffer) {
ModelElement parentElement = (ModelElement) this.getParent();
if (parentElement != null && parentElement.getParent() != null) {
buffer.append(" [in "); //$NON-NLS-1$
parentElement.toStringInfo(0, buffer, NO_INFO, false); // don't show
// resolved
// info
parentElement.toStringAncestors(buffer);
buffer.append("]"); //$NON-NLS-1$
}
}
/**
* Debugging purposes
*/
protected void toStringChildren(int tab, StringBuffer buffer, Object info) {
if (info == null || !(info instanceof ModelElementInfo))
return;
IModelElement[] children = ((ModelElementInfo) info).getChildren();
for (int i = 0; i < children.length; i++) {
buffer.append("\n"); //$NON-NLS-1$
((ModelElement) children[i]).toString(tab + 1, buffer);
}
}
/**
* Debugging purposes
*/
public Object toStringInfo(int tab, StringBuffer buffer) {
Object info = ModelManager.getModelManager().peekAtInfo(this);
this.toStringInfo(tab, buffer, info, true/* show resolved info */);
return info;
}
/**
* Debugging purposes
*
* @param showResolvedInfo
* TODO
*/
protected void toStringInfo(int tab, StringBuffer buffer, Object info,
boolean showResolvedInfo) {
buffer.append(this.tabString(tab));
toStringName(buffer);
if (info == null) {
buffer.append(" (not open)"); //$NON-NLS-1$
}
}
/**
* Debugging purposes
*/
protected void toStringName(StringBuffer buffer) {
buffer.append(getElementName());
}
/**
* Returns the element that is located at the given source position in this
* element. This is a helper method for
* <code>ISourceModule#getElementAt</code>, and only works on compilation
* units and types. The position given is known to be within this element's
* source range already, and if no finer grained element is found at the
* position, this element is returned.
*/
protected IModelElement getSourceElementAt(int position)
throws ModelException {
IModelElement res = getSourceElementAtTop(position);
if (res != this)
return res;
if (this instanceof ISourceReference) {
IModelElement[] children = getChildren();
for (int i = children.length - 1; i >= 0; i--) {
IModelElement aChild = children[i];
if (aChild instanceof SourceRefElement) {
SourceRefElement child = (SourceRefElement) children[i];
if (child instanceof IParent) {
res = child.getSourceElementAt(position);
if (res != child)
return res;
}
}
}
} else {
// should not happen
Assert.isTrue(false);
}
return this;
}
/**
* Returns the element that is located at the given source position in this
* element. This is a helper method for
* <code>ISourceModule#getElementAt</code>, and only works on compilation
* units and types. The position given is known to be within this element's
* source range already, and if no finer grained element is found at the
* position, this element is returned.
*/
protected IModelElement getSourceElementAtTop(int position)
throws ModelException {
if (this instanceof ISourceReference) {
IModelElement[] children = getChildren();
for (int i = children.length - 1; i >= 0; i--) {
IModelElement aChild = children[i];
if (aChild instanceof SourceRefElement) {
SourceRefElement child = (SourceRefElement) children[i];
ISourceRange range = child.getSourceRange();
int start = range.getOffset();
int end = start + range.getLength();
if (start <= position && position <= end) {
if (child instanceof IField) {
// check muti-declaration case (see
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=39943
// )
int declarationStart = start;
SourceRefElement candidate = null;
do {
// check name range
range = ((IField) child).getNameRange();
if (position <= range.getOffset()
+ range.getLength()) {
candidate = child;
} else {
return candidate == null ? child
.getSourceElementAt(position)
: candidate
.getSourceElementAt(position);
}
child = --i >= 0 ? (SourceRefElement) children[i]
: null;
- } while (child != null
+ } while (child instanceof IField
&& child.getSourceRange().getOffset() == declarationStart);
// position in field's type: use first field
return candidate.getSourceElementAt(position);
} else if (child instanceof IParent) {
return child.getSourceElementAt(position);
} else {
return child;
}
}
}
}
} else {
// should not happen
Assert.isTrue(false);
}
return this;
}
/**
* Returns element type and name. called from
* {@link #printNode(CorePrinter)} only.
*
* @return
*/
protected String describeElement() {
return ScriptModelUtil.describeElementType(getElementType()) + ':'
+ getElementName();
}
/**
* Only for testing. Used to print this node with all sub childs.
*
* @param output
*/
public void printNode(CorePrinter output) {
output.formatPrint(describeElement());
output.indent();
try {
IModelElement modelElements[] = this.getChildren();
for (int i = 0; i < modelElements.length; ++i) {
IModelElement element = modelElements[i];
if (element instanceof ModelElement) {
((ModelElement) element).printNode(output);
} else {
output.print("Unknown element:" + element); //$NON-NLS-1$
}
}
} catch (ModelException ex) {
output.formatPrint(ex.getLocalizedMessage());
}
output.dedent();
}
/*
* @see IModelElement#getPrimaryElement()
*/
public IModelElement getPrimaryElement() {
return getPrimaryElement(true);
}
/*
* Returns the primary element. If checkOwner, and the cu owner is primary,
* return this element.
*/
public IModelElement getPrimaryElement(boolean checkOwner) {
return this;
}
public IModelElement getHandleFromMemento(MementoTokenizer memento,
WorkingCopyOwner owner) {
if (!memento.hasMoreTokens())
return this;
String token = memento.nextToken();
return getHandleFromMemento(token, memento, owner);
}
public abstract IModelElement getHandleFromMemento(String token,
MementoTokenizer memento, WorkingCopyOwner owner);
public String getHandleIdentifier() {
return getHandleMemento();
}
public String getHandleMemento() {
StringBuffer buff = new StringBuffer();
getHandleMemento(buff);
return buff.toString();
}
public void getHandleMemento(StringBuffer buff) {
((ModelElement) getParent()).getHandleMemento(buff);
buff.append(getHandleMementoDelimiter());
escapeMementoName(buff, getElementName());
}
protected abstract char getHandleMementoDelimiter();
protected void escapeMementoName(StringBuffer buffer, String mementoName) {
for (int i = 0, length = mementoName.length(); i < length; i++) {
char character = mementoName.charAt(i);
switch (character) {
case JEM_ESCAPE:
case JEM_COUNT:
case JEM_SCRIPTPROJECT:
case JEM_PROJECTFRAGMENT:
case JEM_SCRIPTFOLDER:
case JEM_FIELD:
case JEM_METHOD:
case JEM_SOURCEMODULE:
case JEM_TYPE:
case JEM_IMPORTDECLARATION:
case JEM_LOCALVARIABLE:
case JEM_TYPE_PARAMETER:
case JEM_USER_ELEMENT:
buffer.append(JEM_ESCAPE);
}
buffer.append(character);
}
}
public ISourceModule getSourceModule() {
return null;
}
public void accept(IModelElementVisitor visitor) throws ModelException {
if (visitor.visit(this)) {
IModelElement[] elements = getChildren();
for (int i = 0; i < elements.length; ++i) {
elements[i].accept(visitor);
}
if (visitor instanceof IModelElementVisitorExtension) {
((IModelElementVisitorExtension) visitor).endVisit(this);
}
}
}
}
| true | true | protected IModelElement getSourceElementAtTop(int position)
throws ModelException {
if (this instanceof ISourceReference) {
IModelElement[] children = getChildren();
for (int i = children.length - 1; i >= 0; i--) {
IModelElement aChild = children[i];
if (aChild instanceof SourceRefElement) {
SourceRefElement child = (SourceRefElement) children[i];
ISourceRange range = child.getSourceRange();
int start = range.getOffset();
int end = start + range.getLength();
if (start <= position && position <= end) {
if (child instanceof IField) {
// check muti-declaration case (see
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=39943
// )
int declarationStart = start;
SourceRefElement candidate = null;
do {
// check name range
range = ((IField) child).getNameRange();
if (position <= range.getOffset()
+ range.getLength()) {
candidate = child;
} else {
return candidate == null ? child
.getSourceElementAt(position)
: candidate
.getSourceElementAt(position);
}
child = --i >= 0 ? (SourceRefElement) children[i]
: null;
} while (child != null
&& child.getSourceRange().getOffset() == declarationStart);
// position in field's type: use first field
return candidate.getSourceElementAt(position);
} else if (child instanceof IParent) {
return child.getSourceElementAt(position);
} else {
return child;
}
}
}
}
} else {
// should not happen
Assert.isTrue(false);
}
return this;
}
| protected IModelElement getSourceElementAtTop(int position)
throws ModelException {
if (this instanceof ISourceReference) {
IModelElement[] children = getChildren();
for (int i = children.length - 1; i >= 0; i--) {
IModelElement aChild = children[i];
if (aChild instanceof SourceRefElement) {
SourceRefElement child = (SourceRefElement) children[i];
ISourceRange range = child.getSourceRange();
int start = range.getOffset();
int end = start + range.getLength();
if (start <= position && position <= end) {
if (child instanceof IField) {
// check muti-declaration case (see
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=39943
// )
int declarationStart = start;
SourceRefElement candidate = null;
do {
// check name range
range = ((IField) child).getNameRange();
if (position <= range.getOffset()
+ range.getLength()) {
candidate = child;
} else {
return candidate == null ? child
.getSourceElementAt(position)
: candidate
.getSourceElementAt(position);
}
child = --i >= 0 ? (SourceRefElement) children[i]
: null;
} while (child instanceof IField
&& child.getSourceRange().getOffset() == declarationStart);
// position in field's type: use first field
return candidate.getSourceElementAt(position);
} else if (child instanceof IParent) {
return child.getSourceElementAt(position);
} else {
return child;
}
}
}
}
} else {
// should not happen
Assert.isTrue(false);
}
return this;
}
|
diff --git a/org.eclipse.mylyn.resources.ui/src/org/eclipse/mylyn/internal/resources/ui/ContextEditorManager.java b/org.eclipse.mylyn.resources.ui/src/org/eclipse/mylyn/internal/resources/ui/ContextEditorManager.java
index 16f92f141..07ba74c4c 100644
--- a/org.eclipse.mylyn.resources.ui/src/org/eclipse/mylyn/internal/resources/ui/ContextEditorManager.java
+++ b/org.eclipse.mylyn.resources.ui/src/org/eclipse/mylyn/internal/resources/ui/ContextEditorManager.java
@@ -1,188 +1,189 @@
/*******************************************************************************
* Copyright (c) 2004 - 2006 University Of British Columbia and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.internal.resources.ui;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.eclipse.mylar.context.core.AbstractContextStructureBridge;
import org.eclipse.mylar.context.core.ContextCorePlugin;
import org.eclipse.mylar.context.core.IMylarContext;
import org.eclipse.mylar.context.core.IMylarContextListener;
import org.eclipse.mylar.context.core.IMylarElement;
import org.eclipse.mylar.context.ui.AbstractContextUiBridge;
import org.eclipse.mylar.context.ui.ContextUiPlugin;
import org.eclipse.mylar.core.MylarStatusHandler;
import org.eclipse.mylar.internal.context.ui.ContextUiPrefContstants;
import org.eclipse.mylar.tasks.core.ITask;
import org.eclipse.mylar.tasks.ui.TasksUiPlugin;
import org.eclipse.mylar.tasks.ui.editors.NewTaskEditorInput;
import org.eclipse.mylar.tasks.ui.editors.TaskEditor;
import org.eclipse.mylar.tasks.ui.editors.TaskEditorInput;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.IPreferenceConstants;
import org.eclipse.ui.internal.Workbench;
/**
* @author Mik Kersten
*/
public class ContextEditorManager implements IMylarContextListener {
private boolean previousCloseEditorsSetting = Workbench.getInstance().getPreferenceStore().getBoolean(IPreferenceConstants.REUSE_EDITORS_BOOLEAN);
public void contextActivated(IMylarContext context) {
if (!Workbench.getInstance().isStarting() && ContextUiPlugin.getDefault().getPreferenceStore().getBoolean(ContextUiPrefContstants.AUTO_MANAGE_EDITORS)) {
Workbench workbench = (Workbench) PlatformUI.getWorkbench();
previousCloseEditorsSetting = workbench.getPreferenceStore().getBoolean(IPreferenceConstants.REUSE_EDITORS_BOOLEAN);
workbench.getPreferenceStore().setValue(IPreferenceConstants.REUSE_EDITORS_BOOLEAN, false);
boolean wasPaused = ContextCorePlugin.getContextManager().isContextCapturePaused();
try {
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().setRedraw(false);
+ // do not setActive(false) due to bug 181923
+// PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().setRedraw(false);
// PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().setEnabled(false);
workbench.largeUpdateStart();
if (!wasPaused) {
ContextCorePlugin.getContextManager().setContextCapturePaused(true);
}
Collection<IMylarElement> documents = ContextCorePlugin.getContextManager().getInterestingDocuments();
int opened = 0;
int threshold = ContextUiPlugin.getDefault().getPreferenceStore().getInt(ContextUiPrefContstants.AUTO_MANAGE_EDITORS_OPEN_NUM);
for (Iterator<IMylarElement> iter = documents.iterator(); iter.hasNext() && opened < threshold - 1; opened++) {
IMylarElement document = iter.next();
AbstractContextUiBridge bridge = ContextUiPlugin.getDefault().getUiBridge(document.getContentType());
bridge.restoreEditor(document);
}
IMylarElement activeNode = context.getActiveNode();
if (activeNode != null) {
ContextUiPlugin.getDefault().getUiBridge(activeNode.getContentType()).open(activeNode);
}
} catch (Exception e) {
MylarStatusHandler.fail(e, "failed to open editors on activation", false);
} finally {
ContextCorePlugin.getContextManager().setContextCapturePaused(false);
workbench.largeUpdateEnd();
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().setRedraw(true);
+// PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().setRedraw(true);
// PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().setEnabled(true);
}
}
}
public void contextDeactivated(IMylarContext context) {
if (ContextUiPlugin.getDefault().getPreferenceStore().getBoolean(ContextUiPrefContstants.AUTO_MANAGE_EDITORS)) {
Workbench.getInstance().getPreferenceStore().setValue(IPreferenceConstants.REUSE_EDITORS_BOOLEAN, previousCloseEditorsSetting);
closeAllEditors();
}
}
public void closeAllEditors() {
try {
if (PlatformUI.getWorkbench().isClosing()) {
return;
}
for(IWorkbenchWindow window : PlatformUI.getWorkbench().getWorkbenchWindows()) {
IWorkbenchPage page = window.getActivePage();
if (page != null) {
IEditorReference[] references = page.getEditorReferences();
List<IEditorReference> toClose = new ArrayList<IEditorReference>();
for (int i = 0; i < references.length; i++) {
if (!isActiveTaskEditor(references[i]) && !isUnsubmittedTaskEditor(references[i])) {
toClose.add(references[i]);
}
}
page.closeEditors(toClose.toArray(new IEditorReference[toClose.size()]), true);
}
}
} catch (Throwable t) {
MylarStatusHandler.fail(t, "Could not auto close editor.", false);
}
}
private boolean isUnsubmittedTaskEditor(IEditorReference editorReference) {
IEditorPart part = editorReference.getEditor(false);
if (part instanceof TaskEditor) {
try {
IEditorInput input = editorReference.getEditorInput();
if (input instanceof NewTaskEditorInput) {
return true;
}
} catch (PartInitException e) {
// ignore
}
}
return false;
}
private boolean isActiveTaskEditor(IEditorReference editorReference) {
ITask activeTask = TasksUiPlugin.getTaskListManager().getTaskList().getActiveTask();
try {
IEditorInput input = editorReference.getEditorInput();
if (input instanceof TaskEditorInput) {
TaskEditorInput taskEditorInput = (TaskEditorInput)input;
if (activeTask != null && taskEditorInput.getTask() != null
&& taskEditorInput.getTask().getHandleIdentifier().equals(activeTask.getHandleIdentifier())) {
return true;
}
}
} catch (PartInitException e) {
// ignore
}
return false;
}
public void presentationSettingsChanging(UpdateKind kind) {
// ignore
}
public void presentationSettingsChanged(UpdateKind kind) {
// ignore
}
public void interestChanged(List<IMylarElement> elements) {
for (IMylarElement element : elements) {
if (ContextUiPlugin.getDefault().getPreferenceStore().getBoolean(ContextUiPrefContstants.AUTO_MANAGE_EDITORS)) {
if (!element.getInterest().isInteresting()) {
AbstractContextStructureBridge bridge = ContextCorePlugin.getDefault().getStructureBridge(element.getContentType());
if (bridge.isDocument(element.getHandleIdentifier())) {
AbstractContextUiBridge uiBridge = ContextUiPlugin.getDefault().getUiBridge(element.getContentType());
uiBridge.close(element);
}
}
}
}
}
public void elementDeleted(IMylarElement node) {
// ignore
}
public void landmarkAdded(IMylarElement node) {
// ignore
}
public void landmarkRemoved(IMylarElement node) {
// ignore
}
public void relationsChanged(IMylarElement node) {
// ignore
}
}
| false | true | public void contextActivated(IMylarContext context) {
if (!Workbench.getInstance().isStarting() && ContextUiPlugin.getDefault().getPreferenceStore().getBoolean(ContextUiPrefContstants.AUTO_MANAGE_EDITORS)) {
Workbench workbench = (Workbench) PlatformUI.getWorkbench();
previousCloseEditorsSetting = workbench.getPreferenceStore().getBoolean(IPreferenceConstants.REUSE_EDITORS_BOOLEAN);
workbench.getPreferenceStore().setValue(IPreferenceConstants.REUSE_EDITORS_BOOLEAN, false);
boolean wasPaused = ContextCorePlugin.getContextManager().isContextCapturePaused();
try {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().setRedraw(false);
// PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().setEnabled(false);
workbench.largeUpdateStart();
if (!wasPaused) {
ContextCorePlugin.getContextManager().setContextCapturePaused(true);
}
Collection<IMylarElement> documents = ContextCorePlugin.getContextManager().getInterestingDocuments();
int opened = 0;
int threshold = ContextUiPlugin.getDefault().getPreferenceStore().getInt(ContextUiPrefContstants.AUTO_MANAGE_EDITORS_OPEN_NUM);
for (Iterator<IMylarElement> iter = documents.iterator(); iter.hasNext() && opened < threshold - 1; opened++) {
IMylarElement document = iter.next();
AbstractContextUiBridge bridge = ContextUiPlugin.getDefault().getUiBridge(document.getContentType());
bridge.restoreEditor(document);
}
IMylarElement activeNode = context.getActiveNode();
if (activeNode != null) {
ContextUiPlugin.getDefault().getUiBridge(activeNode.getContentType()).open(activeNode);
}
} catch (Exception e) {
MylarStatusHandler.fail(e, "failed to open editors on activation", false);
} finally {
ContextCorePlugin.getContextManager().setContextCapturePaused(false);
workbench.largeUpdateEnd();
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().setRedraw(true);
// PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().setEnabled(true);
}
}
}
| public void contextActivated(IMylarContext context) {
if (!Workbench.getInstance().isStarting() && ContextUiPlugin.getDefault().getPreferenceStore().getBoolean(ContextUiPrefContstants.AUTO_MANAGE_EDITORS)) {
Workbench workbench = (Workbench) PlatformUI.getWorkbench();
previousCloseEditorsSetting = workbench.getPreferenceStore().getBoolean(IPreferenceConstants.REUSE_EDITORS_BOOLEAN);
workbench.getPreferenceStore().setValue(IPreferenceConstants.REUSE_EDITORS_BOOLEAN, false);
boolean wasPaused = ContextCorePlugin.getContextManager().isContextCapturePaused();
try {
// do not setActive(false) due to bug 181923
// PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().setRedraw(false);
// PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().setEnabled(false);
workbench.largeUpdateStart();
if (!wasPaused) {
ContextCorePlugin.getContextManager().setContextCapturePaused(true);
}
Collection<IMylarElement> documents = ContextCorePlugin.getContextManager().getInterestingDocuments();
int opened = 0;
int threshold = ContextUiPlugin.getDefault().getPreferenceStore().getInt(ContextUiPrefContstants.AUTO_MANAGE_EDITORS_OPEN_NUM);
for (Iterator<IMylarElement> iter = documents.iterator(); iter.hasNext() && opened < threshold - 1; opened++) {
IMylarElement document = iter.next();
AbstractContextUiBridge bridge = ContextUiPlugin.getDefault().getUiBridge(document.getContentType());
bridge.restoreEditor(document);
}
IMylarElement activeNode = context.getActiveNode();
if (activeNode != null) {
ContextUiPlugin.getDefault().getUiBridge(activeNode.getContentType()).open(activeNode);
}
} catch (Exception e) {
MylarStatusHandler.fail(e, "failed to open editors on activation", false);
} finally {
ContextCorePlugin.getContextManager().setContextCapturePaused(false);
workbench.largeUpdateEnd();
// PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().setRedraw(true);
// PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().setEnabled(true);
}
}
}
|
diff --git a/core/src/main/java/org/jvnet/sorcerer/frame/FrameSetGenerator.java b/core/src/main/java/org/jvnet/sorcerer/frame/FrameSetGenerator.java
index f818c05..e104a07 100644
--- a/core/src/main/java/org/jvnet/sorcerer/frame/FrameSetGenerator.java
+++ b/core/src/main/java/org/jvnet/sorcerer/frame/FrameSetGenerator.java
@@ -1,439 +1,441 @@
package org.jvnet.sorcerer.frame;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.TreePathScanner;
import org.jvnet.sorcerer.LinkResolver;
import org.jvnet.sorcerer.LinkResolverFactory;
import org.jvnet.sorcerer.ParsedSourceSet;
import org.jvnet.sorcerer.ParsedType;
import org.jvnet.sorcerer.ResourceResolver;
import org.jvnet.sorcerer.util.AbstractResourceResolver;
import org.jvnet.sorcerer.util.IOUtil;
import org.jvnet.sorcerer.util.JsonWriter;
import org.jvnet.sorcerer.util.TreeUtil;
import javax.lang.model.element.Element;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
/**
* HTML generator that produces sorcerer report in
* javadoc-like 3 frame layout.
*
* <p>
* This is the most simple way to use a sorcerer. Just
* call the {@link #generateAll(File)} method to generate
* the complete files into the output directory.
*
* <p>
* Most of the generated HTML files use hyphen in the file name,
* to make sure it doesn't collide with HTMLs generated from classes.
*
* @author Kohsuke Kawaguchi
*/
public class FrameSetGenerator extends AbstractWriter {
private String title = "Sorcerer report";
private final LinkResolverFactory linkResolverFactory;
/**
* Reference to the unnamed package.
*/
private final PackageElement unnamed;
public FrameSetGenerator(ParsedSourceSet pss) {
super(pss);
this.linkResolverFactory = pss.getLinkResolverFactory();
this.unnamed = pss.getElements().getPackageElement("");
}
/**
* Sets the window title.
*/
public void setTitle(String title) {
this.title = title;
}
private String getPackagePath(PackageElement pe) {
if(pe.equals(unnamed))
return ".";
else
return pe.getQualifiedName().toString().replace('.','/');
}
/**
* Generates all the HTML files into the given directory.
*/
public void generateAll(File outDir) throws IOException {
generateAll(outDir,null);
}
/**
* Generates all the HTML files into the given directory.
*
* @param css
* If specified, path to CSS will computed by using this resolver
*/
public void generateAll(File outDir, ResourceResolver css) throws IOException {
if(css==null) {
css = new AbstractResourceResolver() {
public String href(CompilationUnitTree compUnit) {
return getRelativePathToTop(compUnit)+"style.css";
}
};
}
pss.setLinkResolverFactories(linkResolverFactory);
for (CompilationUnitTree cu : pss.getCompilationUnits()) {
ExpressionTree packageName = cu.getPackageName();
String pkg = packageName==null?"":packageName.toString().replace('.','/')+'/';
String name = TreeUtil.getPrimaryTypeName(cu);
System.out.println(pkg+name);
File out = new File(outDir, pkg + name+".html");
- out.getParentFile().mkdirs();
+ File parent = out.getParentFile();
+ if(parent!=null) // null if outDir was "."
+ parent.mkdirs();
FrameHtmlGenerator gen = new FrameHtmlGenerator(pss,cu);
gen.setCss(css.href(cu));
gen.write(out);
File js = new File(outDir, pkg + name + "-outline.js");
generateClassOutlineJs(cu,new PrintWriter(js));
}
generateIndex(new PrintWriter(open(outDir,"index.html")));
generatePackageListJs(new PrintWriter(openDefault(outDir,"package-list.js")));
generatePackageList(new PrintWriter(openDefault(outDir,"package-list")));
for (PackageElement p : pss.getPackageElement()) {
File dir = new File(outDir,getPackagePath(p));
dir.mkdirs();
generateClassListJs(p,new PrintWriter(openDefault(dir,"class-list.js")));
}
System.out.println("Generating usage index");
{// "find usage" index
generateProjectUsageJs(new PrintWriter(openDefault(outDir,"project-usage.js")));
ClassUsageJsWriter cujw = new ClassUsageJsWriter(pss);
for( ParsedType pt : pss.getParsedTypes() ) {
if(pt.getReferers().length==0)
continue;
// local types can be only referenced from the same compilation unit.
if(pt.isLocal())
continue;
File out = new File(outDir, pt.element.getQualifiedName().toString().replace('.','/')+"-usage.js");
out.getParentFile().mkdirs();
cujw.write(pt,new PrintWriter(out));
}
}
// other resources from core
System.out.println("Generating static resource files");
copyResource(outDir, "behavior.js");
copyResource(outDir, "sorcerer.js");
copyResource(outDir, "style.css");
new File(outDir,"menu").mkdir();
copyResource(outDir, "menu/menu.css");
copyResource(outDir, "menu/rightarrow.gif");
copyResource(outDir, "menu/menu.js");
// frameset specific resources
for (String res : RESOURCES) {
File o = new File(outDir, res);
o.getParentFile().mkdirs();
InputStream in = getClass().getResourceAsStream(res);
if(in==null)
throw new Error("Resource "+res+" not found");
IOUtil.copy(in,o);
}
}
private void copyResource(File outDir, String resourceName) throws IOException {
IOUtil.copy(resourceName,new File(outDir,resourceName));
}
public void generateIndex(PrintWriter w) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("index.html")));
String line;
while((line=r.readLine())!=null) {
line = line.replaceAll("\\$\\{title\\}",title);
w.println(line);
}
r.close();
w.close();
}
public void generatePackageListJs(PrintWriter w) throws IOException {
class DefinedPkgInfo extends PkgInfo<DefinedPkgInfo> {
public DefinedPkgInfo(String name) {
super(name);
}
protected DefinedPkgInfo create(String name) {
return new DefinedPkgInfo(name);
}
/**
* False if this class doesn't have any classes in it (excluding descendants.)
*/
boolean hasClasses;
public void write(JsonWriter js) {
super.write(js);
if(hasClasses)
js.property("hasClasses",true);
}
}
// build package tree info
DefinedPkgInfo root = new DefinedPkgInfo("");
for (PackageElement pe : pss.getPackageElement()) {
root.add(pe.getQualifiedName().toString()).hasClasses=true;
}
try {
w.println("setPackageList(");
new JsonWriter(w).object(root);
w.println(");");
} finally {
w.close();
}
}
/**
* Generates javadoc compatible <tt>package-list</tt>
*/
public void generatePackageList(PrintWriter w) throws IOException {
try {
for (PackageElement pe : pss.getPackageElement()) {
w.println(pe.getQualifiedName());
}
} finally {
w.close();
}
}
public void generateClassListJs(PackageElement p, PrintWriter w) throws IOException {
LinkResolver linkResolver = linkResolverFactory.create(p, pss);
try {
w.printf("setClassList(\"%s\",",p.getQualifiedName());
JsonWriter jw = new JsonWriter(w);
jw.startArray();
for (TypeElement t : pss.getClassElements(p)) {
jw.startObject();
jw.property("name",t.getSimpleName());
jw.property("kind",getKindString(t.getKind()));
jw.property("href",linkResolver.href(t));
jw.property("access",getAccessLevel(t));
jw.endObject();
}
jw.endArray();
w.println(");");
} finally {
w.close();
}
}
public void generateClassOutlineJs(final CompilationUnitTree cu, PrintWriter w) throws IOException {
try {
w.printf("loadOutline(");
final JsonWriter jw = new JsonWriter(w);
jw.startObject();
jw.property("packageName", TreeUtil.getPackageName(cu));
jw.key("children").startArray();
new TreePathScanner<Void,Void>() {
private final SourcePositions sourcePositions = pss.getSourcePositions();
public Void visitClass(ClassTree ct, Void _) {
boolean r = pre(ct);
super.visitClass(ct,_);
if(r) post();
return _;
}
public Void visitMethod(MethodTree mt, Void _) {
boolean r = pre(mt);
super.visitMethod(mt,_);
if(r) post();
return _;
}
public Void visitVariable(VariableTree vt, Void _) {
boolean r = pre(vt);
super.visitVariable(vt,_);
if(r) post();
return _;
}
boolean pre(Tree t) {
Element e = pss.getTrees().getElement(getCurrentPath());
if(e==null) return false;
long endPos = sourcePositions.getEndPosition(cu,t);
if(endPos<0) return false; // synthetic
if(TreeUtil.OUTLINE_WORTHY_ELEMENT.contains(e.getKind())) {
jw.startObject();
writeOutlineNodeProperties(jw,e,cu,t);
jw.key("children").startArray();
return true;
}
return false;
}
private Void post() {
jw.endArray().endObject();
return null;
}
}.scan(cu,null);
jw.endArray().endObject();
w.println(");");
} finally {
w.close();
}
}
/**
* Writes out <tt>project-usage.js</tt> that lists all classes for which
* we have usage index.
*/
public void generateProjectUsageJs(PrintWriter w) throws IOException {
Map<PackageElement,Set<ParsedType>> pkgs =
new TreeMap<PackageElement,Set<ParsedType>>(ParsedSourceSet.PACKAGENAME_COMPARATOR);
for( ParsedType pt : pss.getParsedTypes() ) {
if(pt.getReferers().length==0)
continue;
PackageElement pkg = pss.getElements().getPackageOf(pt.element);
Set<ParsedType> types = pkgs.get(pkg);
if(types==null)
pkgs.put(pkg,types=new HashSet<ParsedType>());
if(!pt.isLocal())
types.add(pt);
}
w.println("setProjectUsage(");
JsonWriter js = new JsonWriter(w);
js.startArray();
for (Entry<PackageElement,Set<ParsedType>> pkg : pkgs.entrySet()) {
js.startObject();
js.property("package",pkg.getKey().getQualifiedName());
js.key("classes");
js.startArray();
String[] names = new String[pkg.getValue().size()];
int idx=0;
for (ParsedType pt : pkg.getValue()) {
names[idx++] = pt.getPackageLocalName();
}
Arrays.sort(names);
for (String n : names) {
js.object(n);
}
js.endArray();
js.endObject();
}
js.endArray();
w.println(")");
w.close();
}
private static final List<String> RESOURCES = new ArrayList<String>();
static {
RESOURCES.addAll(Arrays.asList( new String[]{
"package-tree.html",
"package-toolbar.html",
"package-container.html",
"outline-view.html",
"outline-toolbar.html",
"outline-container.html",
"search-pane.html",
"search-toolbar.html",
"search-container.html",
"eclipse-public-license.url",
"left-pane.js",
"left-pane.css",
"resource-files/yahoo.js",
"resource-files/dom.js",
"resource-files/event.js",
"resource-files/container_core.js",
"resource-files/close.gif",
"resource-files/layout-flat.gif",
"resource-files/layout-hierarchical.gif",
"resource-files/tree/folder.css",
"resource-files/tree/noicon.css",
"resource-files/tree/ln.gif",
"resource-files/tree/loading.gif",
"resource-files/tree/tn.gif",
"resource-files/tree/vline.gif",
"resource-files/tree/treeview.js",
"resource-files/tree/license.txt"
}));
for(String name : new String[]{"lm","lp","tm","tp"}) {
for( String folder : new String[]{"folder","noicon"}) {
RESOURCES.add("resource-files/tree/"+folder+"/"+name+".gif");
RESOURCES.add("resource-files/tree/"+folder+"/"+name+"h.gif");
}
}
for(String name : new String[]{"file","package","prj","type"}) {
RESOURCES.add("resource-files/search/"+name+"_mode.gif");
}
for(String name : new String[]{"alphab_sort_co.gif","fields_co.gif","localtypes_co.gif","public_co.gif","static_co.gif"}) {
RESOURCES.add("resource-files/outline-filter/"+name);
}
String[] modifiers = new String[]{"public", "protected", "private", "default"};
for( String kind : new String[]{"annotation","interface","enum","class","field","method"} )
for( String mod : modifiers)
RESOURCES.add("resource-files/"+kind+'_'+mod+".gif");
}
}
| true | true | public void generateAll(File outDir, ResourceResolver css) throws IOException {
if(css==null) {
css = new AbstractResourceResolver() {
public String href(CompilationUnitTree compUnit) {
return getRelativePathToTop(compUnit)+"style.css";
}
};
}
pss.setLinkResolverFactories(linkResolverFactory);
for (CompilationUnitTree cu : pss.getCompilationUnits()) {
ExpressionTree packageName = cu.getPackageName();
String pkg = packageName==null?"":packageName.toString().replace('.','/')+'/';
String name = TreeUtil.getPrimaryTypeName(cu);
System.out.println(pkg+name);
File out = new File(outDir, pkg + name+".html");
out.getParentFile().mkdirs();
FrameHtmlGenerator gen = new FrameHtmlGenerator(pss,cu);
gen.setCss(css.href(cu));
gen.write(out);
File js = new File(outDir, pkg + name + "-outline.js");
generateClassOutlineJs(cu,new PrintWriter(js));
}
generateIndex(new PrintWriter(open(outDir,"index.html")));
generatePackageListJs(new PrintWriter(openDefault(outDir,"package-list.js")));
generatePackageList(new PrintWriter(openDefault(outDir,"package-list")));
for (PackageElement p : pss.getPackageElement()) {
File dir = new File(outDir,getPackagePath(p));
dir.mkdirs();
generateClassListJs(p,new PrintWriter(openDefault(dir,"class-list.js")));
}
System.out.println("Generating usage index");
{// "find usage" index
generateProjectUsageJs(new PrintWriter(openDefault(outDir,"project-usage.js")));
ClassUsageJsWriter cujw = new ClassUsageJsWriter(pss);
for( ParsedType pt : pss.getParsedTypes() ) {
if(pt.getReferers().length==0)
continue;
// local types can be only referenced from the same compilation unit.
if(pt.isLocal())
continue;
File out = new File(outDir, pt.element.getQualifiedName().toString().replace('.','/')+"-usage.js");
out.getParentFile().mkdirs();
cujw.write(pt,new PrintWriter(out));
}
}
// other resources from core
System.out.println("Generating static resource files");
copyResource(outDir, "behavior.js");
copyResource(outDir, "sorcerer.js");
copyResource(outDir, "style.css");
new File(outDir,"menu").mkdir();
copyResource(outDir, "menu/menu.css");
copyResource(outDir, "menu/rightarrow.gif");
copyResource(outDir, "menu/menu.js");
// frameset specific resources
for (String res : RESOURCES) {
File o = new File(outDir, res);
o.getParentFile().mkdirs();
InputStream in = getClass().getResourceAsStream(res);
if(in==null)
throw new Error("Resource "+res+" not found");
IOUtil.copy(in,o);
}
}
| public void generateAll(File outDir, ResourceResolver css) throws IOException {
if(css==null) {
css = new AbstractResourceResolver() {
public String href(CompilationUnitTree compUnit) {
return getRelativePathToTop(compUnit)+"style.css";
}
};
}
pss.setLinkResolverFactories(linkResolverFactory);
for (CompilationUnitTree cu : pss.getCompilationUnits()) {
ExpressionTree packageName = cu.getPackageName();
String pkg = packageName==null?"":packageName.toString().replace('.','/')+'/';
String name = TreeUtil.getPrimaryTypeName(cu);
System.out.println(pkg+name);
File out = new File(outDir, pkg + name+".html");
File parent = out.getParentFile();
if(parent!=null) // null if outDir was "."
parent.mkdirs();
FrameHtmlGenerator gen = new FrameHtmlGenerator(pss,cu);
gen.setCss(css.href(cu));
gen.write(out);
File js = new File(outDir, pkg + name + "-outline.js");
generateClassOutlineJs(cu,new PrintWriter(js));
}
generateIndex(new PrintWriter(open(outDir,"index.html")));
generatePackageListJs(new PrintWriter(openDefault(outDir,"package-list.js")));
generatePackageList(new PrintWriter(openDefault(outDir,"package-list")));
for (PackageElement p : pss.getPackageElement()) {
File dir = new File(outDir,getPackagePath(p));
dir.mkdirs();
generateClassListJs(p,new PrintWriter(openDefault(dir,"class-list.js")));
}
System.out.println("Generating usage index");
{// "find usage" index
generateProjectUsageJs(new PrintWriter(openDefault(outDir,"project-usage.js")));
ClassUsageJsWriter cujw = new ClassUsageJsWriter(pss);
for( ParsedType pt : pss.getParsedTypes() ) {
if(pt.getReferers().length==0)
continue;
// local types can be only referenced from the same compilation unit.
if(pt.isLocal())
continue;
File out = new File(outDir, pt.element.getQualifiedName().toString().replace('.','/')+"-usage.js");
out.getParentFile().mkdirs();
cujw.write(pt,new PrintWriter(out));
}
}
// other resources from core
System.out.println("Generating static resource files");
copyResource(outDir, "behavior.js");
copyResource(outDir, "sorcerer.js");
copyResource(outDir, "style.css");
new File(outDir,"menu").mkdir();
copyResource(outDir, "menu/menu.css");
copyResource(outDir, "menu/rightarrow.gif");
copyResource(outDir, "menu/menu.js");
// frameset specific resources
for (String res : RESOURCES) {
File o = new File(outDir, res);
o.getParentFile().mkdirs();
InputStream in = getClass().getResourceAsStream(res);
if(in==null)
throw new Error("Resource "+res+" not found");
IOUtil.copy(in,o);
}
}
|
diff --git a/impl/src/main/java/org/jboss/cdi/tck/tests/event/observer/transactional/custom/CustomTransactionalObserverTest.java b/impl/src/main/java/org/jboss/cdi/tck/tests/event/observer/transactional/custom/CustomTransactionalObserverTest.java
index bf13c2870..c9de432bb 100644
--- a/impl/src/main/java/org/jboss/cdi/tck/tests/event/observer/transactional/custom/CustomTransactionalObserverTest.java
+++ b/impl/src/main/java/org/jboss/cdi/tck/tests/event/observer/transactional/custom/CustomTransactionalObserverTest.java
@@ -1,87 +1,87 @@
/*
* 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.event.observer.transactional.custom;
import static org.jboss.cdi.tck.TestGroups.INTEGRATION;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import javax.enterprise.event.TransactionPhase;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.cdi.tck.AbstractTest;
import org.jboss.cdi.tck.shrinkwrap.WebArchiveBuilder;
import org.jboss.cdi.tck.util.ActionSequence;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.test.audit.annotations.SpecAssertion;
import org.jboss.test.audit.annotations.SpecAssertions;
import org.jboss.test.audit.annotations.SpecVersion;
import org.testng.annotations.Test;
/**
* @author Martin Kouba
*/
@Test(groups = { INTEGRATION })
@SpecVersion(spec = "cdi", version = "20091101")
public class CustomTransactionalObserverTest extends AbstractTest {
@Deployment
public static WebArchive createTestArchive() {
return new WebArchiveBuilder().withTestClassPackage(CustomTransactionalObserverTest.class)
.withExtension(ObserverExtension.class).withDefaultPersistenceXml().build();
}
@Inject
private GiraffeService giraffeService;
@Inject
private ObserverExtension extension;
@Test
@SpecAssertions({ @SpecAssertion(section = "10.5", id = "fa"), @SpecAssertion(section = "10.5", id = "fb") })
public void testCustomTransactionalObserver() throws Exception {
ActionSequence.reset();
// GiraffeObserver 2x, GiraffeCustomObserver 1x
- assertEquals(getCurrentManager().resolveObserverMethods(Giraffe.class).size(), 3);
+ assertEquals(getCurrentManager().resolveObserverMethods(new Giraffe()).size(), 3);
// Transactional invocation
giraffeService.feed();
// Test ObserverMethod.notify() was called
assertNotNull(extension.getAnyGiraffeObserver().getReceivedPayload());
// Test ObserverMethod.getTransactionPhase() was called
assertTrue(extension.getAnyGiraffeObserver().isTransactionPhaseCalled());
// Test custom observer received notification during the after completion phase (after succesfull commit)
// BEFORE_COMPLETION must be fired at the beginning of the commit (after checkpoint)
// AFTER_SUCCESS must be fired after BEFORE_COMPLETION and before AFTER_COMPLETION
// AFTER_FAILURE is not fired
ActionSequence correctSequence = new ActionSequence();
correctSequence.add("checkpoint");
correctSequence.add(TransactionPhase.BEFORE_COMPLETION.toString());
correctSequence.add(TransactionPhase.AFTER_SUCCESS.toString());
correctSequence.add(TransactionPhase.AFTER_COMPLETION.toString());
assertEquals(ActionSequence.getSequence(), correctSequence);
}
}
| true | true | public void testCustomTransactionalObserver() throws Exception {
ActionSequence.reset();
// GiraffeObserver 2x, GiraffeCustomObserver 1x
assertEquals(getCurrentManager().resolveObserverMethods(Giraffe.class).size(), 3);
// Transactional invocation
giraffeService.feed();
// Test ObserverMethod.notify() was called
assertNotNull(extension.getAnyGiraffeObserver().getReceivedPayload());
// Test ObserverMethod.getTransactionPhase() was called
assertTrue(extension.getAnyGiraffeObserver().isTransactionPhaseCalled());
// Test custom observer received notification during the after completion phase (after succesfull commit)
// BEFORE_COMPLETION must be fired at the beginning of the commit (after checkpoint)
// AFTER_SUCCESS must be fired after BEFORE_COMPLETION and before AFTER_COMPLETION
// AFTER_FAILURE is not fired
ActionSequence correctSequence = new ActionSequence();
correctSequence.add("checkpoint");
correctSequence.add(TransactionPhase.BEFORE_COMPLETION.toString());
correctSequence.add(TransactionPhase.AFTER_SUCCESS.toString());
correctSequence.add(TransactionPhase.AFTER_COMPLETION.toString());
assertEquals(ActionSequence.getSequence(), correctSequence);
}
| public void testCustomTransactionalObserver() throws Exception {
ActionSequence.reset();
// GiraffeObserver 2x, GiraffeCustomObserver 1x
assertEquals(getCurrentManager().resolveObserverMethods(new Giraffe()).size(), 3);
// Transactional invocation
giraffeService.feed();
// Test ObserverMethod.notify() was called
assertNotNull(extension.getAnyGiraffeObserver().getReceivedPayload());
// Test ObserverMethod.getTransactionPhase() was called
assertTrue(extension.getAnyGiraffeObserver().isTransactionPhaseCalled());
// Test custom observer received notification during the after completion phase (after succesfull commit)
// BEFORE_COMPLETION must be fired at the beginning of the commit (after checkpoint)
// AFTER_SUCCESS must be fired after BEFORE_COMPLETION and before AFTER_COMPLETION
// AFTER_FAILURE is not fired
ActionSequence correctSequence = new ActionSequence();
correctSequence.add("checkpoint");
correctSequence.add(TransactionPhase.BEFORE_COMPLETION.toString());
correctSequence.add(TransactionPhase.AFTER_SUCCESS.toString());
correctSequence.add(TransactionPhase.AFTER_COMPLETION.toString());
assertEquals(ActionSequence.getSequence(), correctSequence);
}
|
diff --git a/src/org/me/tvhguide/ProgrammeListActivity.java b/src/org/me/tvhguide/ProgrammeListActivity.java
index cae2283..57435fc 100644
--- a/src/org/me/tvhguide/ProgrammeListActivity.java
+++ b/src/org/me/tvhguide/ProgrammeListActivity.java
@@ -1,316 +1,315 @@
/*
* Copyright (C) 2011 John Törnblom
*
* This file is part of TVHGuide.
*
* TVHGuide 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.
*
* TVHGuide 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 TVHGuide. If not, see <http://www.gnu.org/licenses/>.
*/
package org.me.tvhguide;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import org.me.tvhguide.htsp.HTSListener;
import org.me.tvhguide.htsp.HTSService;
import org.me.tvhguide.model.Channel;
import org.me.tvhguide.model.Programme;
/**
*
* @author john-tornblom
*/
public class ProgrammeListActivity extends ListActivity implements HTSListener {
private ProgrammeListAdapter prAdapter;
private Channel channel;
private String[] contentTypes;
private Pattern pattern;
private boolean hideIcons;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
List<Programme> prList = new ArrayList<Programme>();
Intent intent = getIntent();
if ("search".equals(intent.getAction())) {
pattern = Pattern.compile(intent.getStringExtra("query"),
Pattern.CASE_INSENSITIVE);
} else {
TVHGuideApplication app = (TVHGuideApplication) getApplication();
channel = app.getChannel(getIntent().getLongExtra("channelId", 0));
}
if (pattern == null && channel == null) {
finish();
return;
}
if (channel != null && !channel.epg.isEmpty()) {
setTitle(channel.name);
prList.addAll(channel.epg);
Button btn = new Button(this);
btn.setText(R.string.pr_get_more);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Programme p = null;
Iterator<Programme> it = channel.epg.iterator();
long nextId = 0;
while (it.hasNext()) {
p = it.next();
if (p.id != nextId && nextId != 0) {
break;
}
nextId = p.nextId;
}
if (nextId == 0) {
nextId = p.nextId;
}
if (nextId == 0) {
nextId = p.id;
- return;
}
Intent intent = new Intent(ProgrammeListActivity.this, HTSService.class);
intent.setAction(HTSService.ACTION_GET_EVENTS);
intent.putExtra("eventId", nextId);
intent.putExtra("channelId", channel.id);
intent.putExtra("count", 10);
startService(intent);
}
});
getListView().addFooterView(btn);
} else if (pattern != null) {
TVHGuideApplication app = (TVHGuideApplication) getApplication();
for (Channel ch : app.getChannels()) {
for (Programme p : ch.epg) {
if (pattern.matcher(p.title).find()) {
prList.add(p);
}
}
}
} else {
finish();
return;
}
contentTypes = getResources().getStringArray(R.array.pr_type);
prAdapter = new ProgrammeListAdapter(this, prList);
prAdapter.sort();
setListAdapter(prAdapter);
}
@Override
protected void onResume() {
super.onResume();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean b = !prefs.getBoolean("loadIcons", false);
if (b != hideIcons) {
prAdapter.notifyDataSetInvalidated();
}
hideIcons = b;
TVHGuideApplication app = (TVHGuideApplication) getApplication();
app.addListener(this);
}
@Override
protected void onPause() {
super.onPause();
TVHGuideApplication app = (TVHGuideApplication) getApplication();
app.removeListener(this);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Programme p = (Programme) prAdapter.getItem(position);
Intent intent = new Intent(this, ProgrammeActivity.class);
intent.putExtra("eventId", p.id);
intent.putExtra("channelId", p.channel.id);
startActivity(intent);
}
public void onMessage(String action, final Object obj) {
if (action.equals(TVHGuideApplication.ACTION_PROGRAMME_ADD)) {
runOnUiThread(new Runnable() {
public void run() {
Programme p = (Programme) obj;
if (channel != null && p.channel.id == channel.id) {
prAdapter.add(p);
prAdapter.notifyDataSetChanged();
prAdapter.sort();
} else if (pattern != null && pattern.matcher(p.title).find()) {
prAdapter.add(p);
prAdapter.notifyDataSetChanged();
prAdapter.sort();
}
}
});
} else if (action.equals(TVHGuideApplication.ACTION_PROGRAMME_DELETE)) {
runOnUiThread(new Runnable() {
public void run() {
Programme p = (Programme) obj;
prAdapter.remove(p);
prAdapter.notifyDataSetChanged();
}
});
}
}
private class ViewWarpper {
TextView title;
TextView channel;
TextView time;
TextView date;
TextView description;
ImageView icon;
public ViewWarpper(View base) {
title = (TextView) base.findViewById(R.id.pr_title);
channel = (TextView) base.findViewById(R.id.pr_channel);
description = (TextView) base.findViewById(R.id.pr_desc);
time = (TextView) base.findViewById(R.id.pr_time);
date = (TextView) base.findViewById(R.id.pr_date);
icon = (ImageView) base.findViewById(R.id.pr_icon);
}
public void repaint(Programme p) {
Channel ch = p.channel;
if (hideIcons || pattern == null) {
icon.setVisibility(ImageView.GONE);
} else {
icon.setBackgroundDrawable(ch.iconDrawable);
icon.setVisibility(ImageView.VISIBLE);
}
title.setText(p.title);
title.invalidate();
date.setText(DateFormat.getMediumDateFormat(date.getContext()).format(p.start));
date.invalidate();
description.setText(p.description);
description.invalidate();
if (p.type > 0 && p.type < 11) {
String str = contentTypes[p.type - 1];
channel.setText(ch.name + " (" + str + ")");
} else {
channel.setText(ch.name);
}
channel.invalidate();
date.setText(DateFormat.getMediumDateFormat(date.getContext()).format(p.start));
date.invalidate();
time.setText(
DateFormat.getTimeFormat(time.getContext()).format(p.start)
+ " - "
+ DateFormat.getTimeFormat(time.getContext()).format(p.stop));
time.invalidate();
}
}
class ProgrammeListAdapter extends ArrayAdapter<Programme> {
Activity context;
List<Programme> list;
ProgrammeListAdapter(Activity context, List<Programme> list) {
super(context, R.layout.pr_widget, list);
this.context = context;
this.list = list;
}
public void sort() {
sort(new Comparator<Programme>() {
public int compare(Programme x, Programme y) {
return x.compareTo(y);
}
});
}
public void updateView(ListView listView, Programme programme) {
for (int i = 0; i < listView.getChildCount(); i++) {
View view = listView.getChildAt(i);
int pos = listView.getPositionForView(view);
Programme pr = (Programme) listView.getItemAtPosition(pos);
if (view.getTag() == null || pr == null) {
continue;
}
if (programme.id != pr.id) {
continue;
}
ViewWarpper wrapper = (ViewWarpper) view.getTag();
wrapper.repaint(programme);
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewWarpper wrapper = null;
if (row == null) {
LayoutInflater inflater = context.getLayoutInflater();
row = inflater.inflate(R.layout.pr_widget, null, false);
wrapper = new ViewWarpper(row);
row.setTag(wrapper);
} else {
wrapper = (ViewWarpper) row.getTag();
}
Programme p = getItem(position);
wrapper.repaint(p);
return row;
}
}
}
| true | true | public void onCreate(Bundle icicle) {
super.onCreate(icicle);
List<Programme> prList = new ArrayList<Programme>();
Intent intent = getIntent();
if ("search".equals(intent.getAction())) {
pattern = Pattern.compile(intent.getStringExtra("query"),
Pattern.CASE_INSENSITIVE);
} else {
TVHGuideApplication app = (TVHGuideApplication) getApplication();
channel = app.getChannel(getIntent().getLongExtra("channelId", 0));
}
if (pattern == null && channel == null) {
finish();
return;
}
if (channel != null && !channel.epg.isEmpty()) {
setTitle(channel.name);
prList.addAll(channel.epg);
Button btn = new Button(this);
btn.setText(R.string.pr_get_more);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Programme p = null;
Iterator<Programme> it = channel.epg.iterator();
long nextId = 0;
while (it.hasNext()) {
p = it.next();
if (p.id != nextId && nextId != 0) {
break;
}
nextId = p.nextId;
}
if (nextId == 0) {
nextId = p.nextId;
}
if (nextId == 0) {
nextId = p.id;
return;
}
Intent intent = new Intent(ProgrammeListActivity.this, HTSService.class);
intent.setAction(HTSService.ACTION_GET_EVENTS);
intent.putExtra("eventId", nextId);
intent.putExtra("channelId", channel.id);
intent.putExtra("count", 10);
startService(intent);
}
});
getListView().addFooterView(btn);
} else if (pattern != null) {
TVHGuideApplication app = (TVHGuideApplication) getApplication();
for (Channel ch : app.getChannels()) {
for (Programme p : ch.epg) {
if (pattern.matcher(p.title).find()) {
prList.add(p);
}
}
}
} else {
finish();
return;
}
contentTypes = getResources().getStringArray(R.array.pr_type);
prAdapter = new ProgrammeListAdapter(this, prList);
prAdapter.sort();
setListAdapter(prAdapter);
}
| public void onCreate(Bundle icicle) {
super.onCreate(icicle);
List<Programme> prList = new ArrayList<Programme>();
Intent intent = getIntent();
if ("search".equals(intent.getAction())) {
pattern = Pattern.compile(intent.getStringExtra("query"),
Pattern.CASE_INSENSITIVE);
} else {
TVHGuideApplication app = (TVHGuideApplication) getApplication();
channel = app.getChannel(getIntent().getLongExtra("channelId", 0));
}
if (pattern == null && channel == null) {
finish();
return;
}
if (channel != null && !channel.epg.isEmpty()) {
setTitle(channel.name);
prList.addAll(channel.epg);
Button btn = new Button(this);
btn.setText(R.string.pr_get_more);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Programme p = null;
Iterator<Programme> it = channel.epg.iterator();
long nextId = 0;
while (it.hasNext()) {
p = it.next();
if (p.id != nextId && nextId != 0) {
break;
}
nextId = p.nextId;
}
if (nextId == 0) {
nextId = p.nextId;
}
if (nextId == 0) {
nextId = p.id;
}
Intent intent = new Intent(ProgrammeListActivity.this, HTSService.class);
intent.setAction(HTSService.ACTION_GET_EVENTS);
intent.putExtra("eventId", nextId);
intent.putExtra("channelId", channel.id);
intent.putExtra("count", 10);
startService(intent);
}
});
getListView().addFooterView(btn);
} else if (pattern != null) {
TVHGuideApplication app = (TVHGuideApplication) getApplication();
for (Channel ch : app.getChannels()) {
for (Programme p : ch.epg) {
if (pattern.matcher(p.title).find()) {
prList.add(p);
}
}
}
} else {
finish();
return;
}
contentTypes = getResources().getStringArray(R.array.pr_type);
prAdapter = new ProgrammeListAdapter(this, prList);
prAdapter.sort();
setListAdapter(prAdapter);
}
|
diff --git a/src/main/java/com/moviepilot/sheldon/compactor/handler/IndexWriter.java b/src/main/java/com/moviepilot/sheldon/compactor/handler/IndexWriter.java
index fd766cc..d9ba97e 100644
--- a/src/main/java/com/moviepilot/sheldon/compactor/handler/IndexWriter.java
+++ b/src/main/java/com/moviepilot/sheldon/compactor/handler/IndexWriter.java
@@ -1,83 +1,84 @@
package com.moviepilot.sheldon.compactor.handler;
import com.moviepilot.sheldon.compactor.config.Config;
import com.moviepilot.sheldon.compactor.event.IndexEntry;
import com.moviepilot.sheldon.compactor.event.PropertyContainerEvent;
import org.neo4j.unsafe.batchinsert.BatchInserterIndex;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import static com.moviepilot.sheldon.compactor.event.PropertyContainerEvent.Action.DELETE;
/**
* Handler for writing into the index
*
* @author stefanp
* @since 06.08.2012
*/
public final class IndexWriter<E extends PropertyContainerEvent> extends AbstractPropertyContainerEventHandler<E> {
private final Kind kind;
private final int indexId;
private final String tag;
private final ExecutorService executor;
private Future<?> flusher;
public IndexWriter(final Config config, final Kind kind, ExecutorService executorService, final int indexId) {
super(config.getModMap());
this.kind = kind;
this.indexId = indexId;
this.executor = executorService;
this.tag = "index_writer_" + indexId + "_flush";
}
public void onEvent_(final E event, final long sequence, final boolean endOfBatch) throws Exception {
if (event.isOk() && (event.action != DELETE)) {
for (final IndexEntry entry : event.indexEntries)
if (entry.numIndex == indexId) {
if (entry.write(event.id)) {
if (entry.flush) {
waitFlush();
submitNewFlush(entry.index);
getProgressor().tick(tag);
}
}
}
}
}
private void submitNewFlush(final BatchInserterIndex index) {
flusher = executor.submit(new Runnable() {
public void run() {
index.flush();
}
});
}
public void waitFlush() {
- try {
- while(true) {
- try {
- flusher.get();
- return;
- } catch (InterruptedException e) {
- // intentionally
+ if (flusher != null)
+ try {
+ while(true) {
+ try {
+ flusher.get();
+ return;
+ } catch (InterruptedException e) {
+ // intentionally
+ }
}
}
- }
- catch (ExecutionException e) {
- throw new RuntimeException(e);
- }
- finally {
- flusher = null;
- }
+ catch (ExecutionException e) {
+ throw new RuntimeException(e);
+ }
+ finally {
+ flusher = null;
+ }
}
public Kind getKind() {
return kind;
}
}
| false | true | public void waitFlush() {
try {
while(true) {
try {
flusher.get();
return;
} catch (InterruptedException e) {
// intentionally
}
}
}
catch (ExecutionException e) {
throw new RuntimeException(e);
}
finally {
flusher = null;
}
}
| public void waitFlush() {
if (flusher != null)
try {
while(true) {
try {
flusher.get();
return;
} catch (InterruptedException e) {
// intentionally
}
}
}
catch (ExecutionException e) {
throw new RuntimeException(e);
}
finally {
flusher = null;
}
}
|
diff --git a/src/actors/Enemy.java b/src/actors/Enemy.java
index bf6f7d8..8053ad3 100644
--- a/src/actors/Enemy.java
+++ b/src/actors/Enemy.java
@@ -1,140 +1,140 @@
package actors;
/**
* Enemy.java
* @author Nicholas Hydock
*
* Description: Computer controllable actors
*/
import graphics.Sprite;
import java.io.File;
import java.util.ArrayList;
import java.util.prefs.Preferences;
import org.ini4j.Ini;
import org.ini4j.IniPreferences;
public class Enemy extends Actor {
public static final String[] AVAILABLEENEMIES = new ArrayList<String>(){
{
for (String s : new File("data/actors/enemies/info").list())
if (s.endsWith(".ini"))
this.add(s.substring(0, s.length()-4));
}
}.toArray(new String[]{});
public static final int SMALL = 33;
public static final int MEDIUM = 49;
public static final int LARGE = 64;
public static final int FULL = 106;
int goldReward = 0; //amount of gold rewarded on killing the enemy
int size = MEDIUM; //enemy sprite size type
//spacing of enemy sprites in the gui are spaced by the type of sprite they are
// even though sprites have no limit dimensions, the spacing on screen is limited, so
// placing of sprites can't be 100% dynamic. Since there is no limit to actual picture
// dimensions, the sprite can be larger than the defined size to produce artistic overlap
String displayName; //name to show in battle for the enemy
String spriteName; //by having the sprite defined in the ini, it allows multiple enemies
//to use the same sprite without having to duplicate the file. This
//helps cut down on project file size as well as loading into memory
/**
* Creates an enemy instance
* @param n
*/
public Enemy(String n)
{
//load enemy data from ini
try
{
name = n;
Preferences p = new IniPreferences(new Ini(new File("data/actors/enemies/info/" + name + ".ini")));
Preferences dist = p.node("distribution");
Preferences elem = p.node("elemental");
Preferences main = p.node("enemy");
maxhp = dist.getInt("hp", 1);
hp = maxhp;
String[] m = dist.get("mp", "0/0/0/0/0/0/0/0").split("/");
for (int i = 0; i < m.length && i < mp.length; i++)
{
mp[i][0] = Integer.parseInt(m[i]);
mp[i][1] = Integer.parseInt(m[i]);
}
str = dist.getInt("str", 1);
def = dist.getInt("def", 1);
itl = dist.getInt("int", 1);
spd = dist.getInt("spd", 1);
evd = dist.getInt("evd", 1);
acc = dist.getInt("acc", 1);
vit = dist.getInt("vit", 1);
fire = elem.getInt("fire", 1);
frez = elem.getInt("frez", 1);
elec = elem.getInt("elec", 1);
lght = elem.getInt("lght", 1);
dark = elem.getInt("dark", 1);
exp = main.getInt("exp", 1);
- goldReward = main.getInt("g", 0);
+ goldReward = main.getInt("gold", 0);
spriteName = main.get("sprite", "");
String s = main.get("size", "medium");
if (s.equals("small"))
size = SMALL;
else if (s.equals("large"))
size = LARGE;
else if (s.equals("full"))
size = FULL;
else
size = MEDIUM;
}
catch (Exception e) {
e.printStackTrace();
}
commands = new String[]{"Attack"};
loadSprites();
}
@Override
protected void loadSprites() {
sprites = new Sprite[1];
sprites[0] = new Sprite("actors/enemies/sprites/" + spriteName + ".png");
}
@Override
public Sprite getSprite() {
return sprites[0];
}
/**
* Gold reward setter
* @param i
*/
public void setGold(int i) {
goldReward = i;
}
/**
* Gold reward getter
* @return
*/
public int getGold() {
return goldReward;
}
public int getSize()
{
return size;
}
}
| true | true | public Enemy(String n)
{
//load enemy data from ini
try
{
name = n;
Preferences p = new IniPreferences(new Ini(new File("data/actors/enemies/info/" + name + ".ini")));
Preferences dist = p.node("distribution");
Preferences elem = p.node("elemental");
Preferences main = p.node("enemy");
maxhp = dist.getInt("hp", 1);
hp = maxhp;
String[] m = dist.get("mp", "0/0/0/0/0/0/0/0").split("/");
for (int i = 0; i < m.length && i < mp.length; i++)
{
mp[i][0] = Integer.parseInt(m[i]);
mp[i][1] = Integer.parseInt(m[i]);
}
str = dist.getInt("str", 1);
def = dist.getInt("def", 1);
itl = dist.getInt("int", 1);
spd = dist.getInt("spd", 1);
evd = dist.getInt("evd", 1);
acc = dist.getInt("acc", 1);
vit = dist.getInt("vit", 1);
fire = elem.getInt("fire", 1);
frez = elem.getInt("frez", 1);
elec = elem.getInt("elec", 1);
lght = elem.getInt("lght", 1);
dark = elem.getInt("dark", 1);
exp = main.getInt("exp", 1);
goldReward = main.getInt("g", 0);
spriteName = main.get("sprite", "");
String s = main.get("size", "medium");
if (s.equals("small"))
size = SMALL;
else if (s.equals("large"))
size = LARGE;
else if (s.equals("full"))
size = FULL;
else
size = MEDIUM;
}
catch (Exception e) {
e.printStackTrace();
}
commands = new String[]{"Attack"};
loadSprites();
}
| public Enemy(String n)
{
//load enemy data from ini
try
{
name = n;
Preferences p = new IniPreferences(new Ini(new File("data/actors/enemies/info/" + name + ".ini")));
Preferences dist = p.node("distribution");
Preferences elem = p.node("elemental");
Preferences main = p.node("enemy");
maxhp = dist.getInt("hp", 1);
hp = maxhp;
String[] m = dist.get("mp", "0/0/0/0/0/0/0/0").split("/");
for (int i = 0; i < m.length && i < mp.length; i++)
{
mp[i][0] = Integer.parseInt(m[i]);
mp[i][1] = Integer.parseInt(m[i]);
}
str = dist.getInt("str", 1);
def = dist.getInt("def", 1);
itl = dist.getInt("int", 1);
spd = dist.getInt("spd", 1);
evd = dist.getInt("evd", 1);
acc = dist.getInt("acc", 1);
vit = dist.getInt("vit", 1);
fire = elem.getInt("fire", 1);
frez = elem.getInt("frez", 1);
elec = elem.getInt("elec", 1);
lght = elem.getInt("lght", 1);
dark = elem.getInt("dark", 1);
exp = main.getInt("exp", 1);
goldReward = main.getInt("gold", 0);
spriteName = main.get("sprite", "");
String s = main.get("size", "medium");
if (s.equals("small"))
size = SMALL;
else if (s.equals("large"))
size = LARGE;
else if (s.equals("full"))
size = FULL;
else
size = MEDIUM;
}
catch (Exception e) {
e.printStackTrace();
}
commands = new String[]{"Attack"};
loadSprites();
}
|
diff --git a/ttools/src/main/uk/ac/starlink/ttools/pipe/TableTask.java b/ttools/src/main/uk/ac/starlink/ttools/pipe/TableTask.java
index 63075c515..05aba13fe 100644
--- a/ttools/src/main/uk/ac/starlink/ttools/pipe/TableTask.java
+++ b/ttools/src/main/uk/ac/starlink/ttools/pipe/TableTask.java
@@ -1,223 +1,224 @@
package uk.ac.starlink.ttools.pipe;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import uk.ac.starlink.table.StarTable;
import uk.ac.starlink.table.StarTableFactory;
import uk.ac.starlink.table.StarTableOutput;
import uk.ac.starlink.table.StoragePolicy;
import uk.ac.starlink.table.TableBuilder;
import uk.ac.starlink.ttools.ArgException;
import uk.ac.starlink.util.Loader;
/**
* Generic superclass for table processing utilities.
*
* @author Mark Taylor (Starlink)
* @since 11 Feb 2005
*/
public abstract class TableTask {
private boolean noAction_;
private boolean debug_;
private boolean verbose_;
private StarTableFactory treader_;
public TableTask() {
/* Ensure that the properties are loaded; this may contain JDBC
* configuration which should be got before DriverManager might be
* initialised. */
Loader.loadProperties();
}
/**
* Returns the name by which this task would like to be known.
*/
public abstract String getCommandName();
/**
* Runs this task.
*
* @param args command line arguments
* @return true iff the task has executed successfully
*/
public boolean run( String[] args ) {
List argList = new ArrayList( Arrays.asList( args ) );
try {
setArgs( argList );
if ( ! argList.isEmpty() ) {
- String msg = "Undigested arguments:";
+ boolean plural = argList.size() > 1 ? "s" : "";
+ String msg = "Undigested argument" + plural + ":";
for ( Iterator it = argList.iterator(); it.hasNext(); ) {
msg += " " + it.next().toString();
}
System.err.println( msg );
System.err.println( getUsage() );
return false;
}
if ( ! isNoAction() ) {
execute();
}
return true;
}
catch ( ArgException e ) {
if ( debug_ ) {
e.printStackTrace( System.err );
}
else {
String msg = e.getMessage();
String usage = e.getUsageFragment();
System.err.println();
System.err.println( e.getMessage() );
if ( usage != null ) {
System.err.println( "\nUsage: " + usage );
}
System.err.println();
}
return false;
}
catch ( IOException e ) {
if ( debug_ ) {
e.printStackTrace( System.err );
}
else {
String msg = e.getMessage();
System.err.println( msg == null ? e.toString() : msg );
}
return false;
}
}
/**
* Consume a list of arguments.
* Any arguments which this task knows about should be noted and
* removed from the list. Any others should be ignored,
* and left in the list.
*
* @param argList an array of strings obtained from the command line
*/
public void setArgs( List argList ) throws ArgException {
for ( Iterator it = argList.iterator(); it.hasNext(); ) {
String arg = (String) it.next();
if ( arg.startsWith( "-" ) && arg.length() > 1 ) {
if ( arg.equals( "-disk" ) ) {
it.remove();
StoragePolicy.setDefaultPolicy( StoragePolicy.PREFER_DISK );
getTableFactory().setStoragePolicy( StoragePolicy
.PREFER_DISK );
}
else if ( arg.equals( "-debug" ) ) {
it.remove();
debug_ = true;
}
else if ( arg.equals( "-v" ) || arg.equals( "-verbose" ) ) {
it.remove();
verbose_ = true;
}
else if ( arg.equals( "-h" ) || arg.equals( "-help" ) ) {
it.remove();
System.out.println( getHelp() );
noAction_ = true;
}
}
}
/* Adjust logging level if necessary. */
if ( verbose_ ) {
Logger.getLogger( "uk.ac.starlink" ).setLevel( Level.INFO );
}
else {
Logger.getLogger( "uk.ac.starlink" ).setLevel( Level.WARNING );
}
}
public boolean isVerbose() {
return verbose_;
}
public boolean isNoAction() {
return noAction_;
}
/**
* Performs the work of this task;
*/
public abstract void execute() throws IOException;
/**
* Returns a table factory.
*
* @return factory
*/
public StarTableFactory getTableFactory() {
if ( treader_ == null ) {
treader_ = new StarTableFactory( false );
}
return treader_;
}
/**
* Returns a help message. May be more verbose than usage message.
*
* @return help string
*/
public String getHelp() {
return getUsage();
}
/**
* Returns a usage message.
* This is composed of both {@link #getGenericOptions} and
* {@link #getSpecificOptions}.
*
* @return usage string
*/
public String getUsage() {
StringBuffer line = new StringBuffer( "Usage: " + getCommandName() );
String pad = line.toString().replaceAll( ".", " " );
List uwords = new ArrayList();
uwords.addAll( Arrays.asList( getGenericOptions() ) );
uwords.addAll( Arrays.asList( getSpecificOptions() ) );
StringBuffer ubuf = new StringBuffer();
for ( Iterator it = uwords.iterator(); it.hasNext(); ) {
String word = (String) it.next();
if ( line.length() + word.length() > 75 ) {
ubuf.append( line )
.append( "\n" );
line = new StringBuffer( pad );
}
line.append( " " )
.append( word );
}
ubuf.append( line );
return "\n" + ubuf.toString() + "\n";
}
/**
* Returns a list of generic options understood by this class.
*
* @return generic options (one string per word)
*/
public String[] getGenericOptions() {
return new String[] {
"[-disk]",
"[-debug]",
"[-h[elp]]",
"[-v[erbose]]",
};
}
/**
* Returns a list of options specfic to this TableTask subclass.
*
* @return specific options (one string per word)
*/
public abstract String[] getSpecificOptions();
}
| true | true | public boolean run( String[] args ) {
List argList = new ArrayList( Arrays.asList( args ) );
try {
setArgs( argList );
if ( ! argList.isEmpty() ) {
String msg = "Undigested arguments:";
for ( Iterator it = argList.iterator(); it.hasNext(); ) {
msg += " " + it.next().toString();
}
System.err.println( msg );
System.err.println( getUsage() );
return false;
}
if ( ! isNoAction() ) {
execute();
}
return true;
}
catch ( ArgException e ) {
if ( debug_ ) {
e.printStackTrace( System.err );
}
else {
String msg = e.getMessage();
String usage = e.getUsageFragment();
System.err.println();
System.err.println( e.getMessage() );
if ( usage != null ) {
System.err.println( "\nUsage: " + usage );
}
System.err.println();
}
return false;
}
catch ( IOException e ) {
if ( debug_ ) {
e.printStackTrace( System.err );
}
else {
String msg = e.getMessage();
System.err.println( msg == null ? e.toString() : msg );
}
return false;
}
}
| public boolean run( String[] args ) {
List argList = new ArrayList( Arrays.asList( args ) );
try {
setArgs( argList );
if ( ! argList.isEmpty() ) {
boolean plural = argList.size() > 1 ? "s" : "";
String msg = "Undigested argument" + plural + ":";
for ( Iterator it = argList.iterator(); it.hasNext(); ) {
msg += " " + it.next().toString();
}
System.err.println( msg );
System.err.println( getUsage() );
return false;
}
if ( ! isNoAction() ) {
execute();
}
return true;
}
catch ( ArgException e ) {
if ( debug_ ) {
e.printStackTrace( System.err );
}
else {
String msg = e.getMessage();
String usage = e.getUsageFragment();
System.err.println();
System.err.println( e.getMessage() );
if ( usage != null ) {
System.err.println( "\nUsage: " + usage );
}
System.err.println();
}
return false;
}
catch ( IOException e ) {
if ( debug_ ) {
e.printStackTrace( System.err );
}
else {
String msg = e.getMessage();
System.err.println( msg == null ? e.toString() : msg );
}
return false;
}
}
|
diff --git a/src/org/jruby/RubyModule.java b/src/org/jruby/RubyModule.java
index 1b2cfaada..0104fa721 100644
--- a/src/org/jruby/RubyModule.java
+++ b/src/org/jruby/RubyModule.java
@@ -1,1591 +1,1592 @@
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Chad Fowler <[email protected]>
* Copyright (C) 2001 Alan Moore <[email protected]>
* Copyright (C) 2001-2002 Benoit Cerrina <[email protected]>
* Copyright (C) 2001-2004 Jan Arne Petersen <[email protected]>
* Copyright (C) 2002-2004 Anders Bengtsson <[email protected]>
* Copyright (C) 2004 Thomas E Enebo <[email protected]>
* Copyright (C) 2004-2005 Charles O Nutter <[email protected]>
* Copyright (C) 2004 Stefan Matthias Aust <[email protected]>
* Copyright (C) 2006 Miguel Covarrubias <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.jruby.internal.runtime.methods.AliasMethod;
import org.jruby.internal.runtime.methods.CallbackMethod;
import org.jruby.internal.runtime.methods.MethodMethod;
import org.jruby.internal.runtime.methods.ProcMethod;
import org.jruby.internal.runtime.methods.UndefinedMethod;
import org.jruby.internal.runtime.methods.WrapperCallable;
import org.jruby.runtime.Arity;
import org.jruby.runtime.ICallable;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.callback.Callback;
import org.jruby.runtime.marshal.MarshalStream;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.util.IdUtil;
import org.jruby.util.collections.SinglyLinkedList;
import org.jruby.exceptions.RaiseException;
/**
*
* @author jpetersen
*/
public class RubyModule extends RubyObject {
private static final String CVAR_TAINT_ERROR =
"Insecure: can't modify class variable";
private static final String CVAR_FREEZE_ERROR = "class/module";
// superClass may be null.
private RubyClass superClass;
// Containing class...The parent of Object is null. Object should always be last in chain.
//public RubyModule parentModule;
// CRef...to eventually replace parentModule
public SinglyLinkedList cref;
// ClassId is the name of the class/module sans where it is located.
// If it is null, then it an anonymous class.
private String classId;
// All methods and all CACHED methods for the module. The cached methods will be removed
// when appropriate (e.g. when method is removed by source class or a new method is added
// with same name by one of its subclasses).
private Map methods = new HashMap();
protected RubyModule(IRuby runtime, RubyClass metaClass, RubyClass superClass, SinglyLinkedList parentCRef, String name) {
super(runtime, metaClass);
this.superClass = superClass;
//this.parentModule = parentModule;
setBaseName(name);
// If no parent is passed in, it is safe to assume Object.
if (parentCRef == null) {
if (runtime.getObject() != null) {
parentCRef = runtime.getObject().getCRef();
}
}
this.cref = new SinglyLinkedList(this, parentCRef);
}
/** Getter for property superClass.
* @return Value of property superClass.
*/
public RubyClass getSuperClass() {
return superClass;
}
private void setSuperClass(RubyClass superClass) {
this.superClass = superClass;
}
public RubyModule getParent() {
if (cref.getNext() == null) {
return null;
}
return (RubyModule)cref.getNext().getValue();
}
public void setParent(RubyModule p) {
cref.setNext(p.getCRef());
}
public Map getMethods() {
return methods;
}
public boolean isModule() {
return true;
}
public boolean isClass() {
return false;
}
public boolean isSingleton() {
return false;
}
/**
* Is this module one that in an included one (e.g. an IncludedModuleWrapper).
*/
public boolean isIncluded() {
return false;
}
public RubyModule getNonIncludedClass() {
return this;
}
public String getBaseName() {
return classId;
}
public void setBaseName(String name) {
classId = name;
}
/**
* Generate a fully-qualified class name or a #-style name for anonymous and singleton classes.
*
* Ruby C equivalent = "classname"
*
* @return The generated class name
*/
public String getName() {
if (getBaseName() == null) {
if (isClass()) {
return "#<" + "Class" + ":01x" + Integer.toHexString(System.identityHashCode(this)) + ">";
} else {
return "#<" + "Module" + ":01x" + Integer.toHexString(System.identityHashCode(this)) + ">";
}
}
StringBuffer result = new StringBuffer(getBaseName());
RubyClass objectClass = getRuntime().getObject();
for (RubyModule p = this.getParent(); p != null && p != objectClass; p = p.getParent()) {
result.insert(0, "::").insert(0, p.getBaseName());
}
return result.toString();
}
/**
* Create a wrapper to use for including the specified module into this one.
*
* Ruby C equivalent = "include_class_new"
*
* @return The module wrapper
*/
public IncludedModuleWrapper newIncludeClass(RubyClass superClazz) {
IncludedModuleWrapper includedModule = new IncludedModuleWrapper(getRuntime(), superClazz, this);
// include its parent (and in turn that module's parents)
if (getSuperClass() != null) {
includedModule.includeModule(getSuperClass());
}
return includedModule;
}
/**
* Search this and parent modules for the named variable.
*
* @param name The variable to search for
* @return The module in which that variable is found, or null if not found
*/
private RubyModule getModuleWithInstanceVar(String name) {
for (RubyModule p = this; p != null; p = p.getSuperClass()) {
if (p.getInstanceVariable(name) != null) {
return p;
}
}
return null;
}
/**
* Set the named class variable to the given value, provided taint and freeze allow setting it.
*
* Ruby C equivalent = "rb_cvar_set"
*
* @param name The variable name to set
* @param value The value to set it to
*/
public IRubyObject setClassVar(String name, IRubyObject value) {
RubyModule module = getModuleWithInstanceVar(name);
if (module == null) {
module = this;
}
return module.setInstanceVariable(name, value, CVAR_TAINT_ERROR, CVAR_FREEZE_ERROR);
}
/**
* Retrieve the specified class variable, searching through this module, included modules, and supermodules.
*
* Ruby C equivalent = "rb_cvar_get"
*
* @param name The name of the variable to retrieve
* @return The variable's value, or throws NameError if not found
*/
public IRubyObject getClassVar(String name) {
RubyModule module = getModuleWithInstanceVar(name);
if (module != null) {
IRubyObject variable = module.getInstanceVariable(name);
return variable == null ? getRuntime().getNil() : variable;
}
throw getRuntime().newNameError("uninitialized class variable " + name + " in " + getName(), name);
}
/**
* Is class var defined?
*
* Ruby C equivalent = "rb_cvar_defined"
*
* @param name The class var to determine "is defined?"
* @return true if true, false if false
*/
public boolean isClassVarDefined(String name) {
return getModuleWithInstanceVar(name) != null;
}
/**
* Set the named constant on this module. Also, if the value provided is another Module and
* that module has not yet been named, assign it the specified name.
*
* @param name The name to assign
* @param value The value to assign to it; if an unnamed Module, also set its basename to name
* @return The result of setting the variable.
* @see RubyObject#setInstanceVariable(String, IRubyObject, String, String)
*/
public IRubyObject setConstant(String name, IRubyObject value) {
IRubyObject result = setInstanceVariable(name, value, "Insecure: can't set constant",
"class/module");
// if adding a module under a constant name, set that module's basename to the constant name
if (value instanceof RubyModule) {
RubyModule module = (RubyModule)value;
if (module.getBaseName() == null) {
module.setBaseName(name);
module.setParent(this);
}
/*
module.setParent(this);
*/
}
return result;
}
/**
* Finds a class that is within the current module (or class).
*
* @param name to be found in this module (or class)
* @return the class or null if no such class
*/
public RubyClass getClass(String name) {
IRubyObject module = getConstantAt(name);
return (module instanceof RubyClass) ? (RubyClass) module : null;
}
/**
* Base implementation of Module#const_missing, throws NameError for specific missing constant.
*
* @param name The constant name which was found to be missing
* @return Nothing! Absolutely nothing! (though subclasses might choose to return something)
*/
public IRubyObject const_missing(IRubyObject name) {
/* Uninitialized constant */
if (this != getRuntime().getObject()) {
throw getRuntime().newNameError("uninitialized constant " + getName() + "::" + name.asSymbol(), "" + getName() + "::" + name.asSymbol());
}
throw getRuntime().newNameError("uninitialized constant " + name.asSymbol(), name.asSymbol());
}
/**
* Include a new module in this module or class.
*
* @param arg The module to include
*/
public synchronized void includeModule(IRubyObject arg) {
assert arg != null;
testFrozen("module");
if (!isTaint()) {
getRuntime().secure(4);
}
if (!(arg instanceof RubyModule)) {
throw getRuntime().newTypeError("Wrong argument type " + arg.getMetaClass().getName() +
" (expected Module).");
}
RubyModule module = (RubyModule) arg;
// Make sure the module we include does not already exist
if (isSame(module)) {
return;
}
infectBy(module);
RubyModule p, c;
boolean changed = false;
boolean skip = false;
c = this;
while (module != null) {
if (getNonIncludedClass() == module.getNonIncludedClass()) {
throw getRuntime().newArgumentError("cyclic include detected");
}
boolean superclassSeen = false;
for (p = getSuperClass(); p != null; p = p.getSuperClass()) {
if (p instanceof IncludedModuleWrapper) {
if (p.getNonIncludedClass() == module.getNonIncludedClass()) {
if (!superclassSeen) {
c = p;
}
skip = true;
break;
}
} else {
superclassSeen = true;
}
}
if (!skip) {
// In the current logic, if we get here we know that module is not an
// IncludedModuleWrapper, so there's no need to fish out the delegate. But just
// in case the logic should change later, let's do it anyway:
c.setSuperClass(new IncludedModuleWrapper(getRuntime(), c.getSuperClass(),
module.getNonIncludedClass()));
c = c.getSuperClass();
changed = true;
}
module = module.getSuperClass();
skip = false;
}
if (changed) {
// MRI seems to blow away its cache completely after an include; is
// what we're doing here really safe?
- for (Iterator iter = ((RubyModule) arg).getMethods().keySet().iterator();
+ List methodNames = new ArrayList(((RubyModule) arg).getMethods().keySet());
+ for (Iterator iter = methodNames.iterator();
iter.hasNext();) {
String methodName = (String) iter.next();
getRuntime().getCacheMap().remove(methodName, searchMethod(methodName));
}
}
}
public void defineMethod(String name, Callback method) {
Visibility visibility = name.equals("initialize") ?
Visibility.PRIVATE : Visibility.PUBLIC;
addMethod(name, new CallbackMethod(this, method, visibility));
}
public void definePrivateMethod(String name, Callback method) {
addMethod(name, new CallbackMethod(this, method, Visibility.PRIVATE));
}
public void undefineMethod(String name) {
addMethod(name, UndefinedMethod.getInstance());
}
/** rb_undef
*
*/
public void undef(String name) {
IRuby runtime = getRuntime();
if (this == runtime.getObject()) {
runtime.secure(4);
}
if (runtime.getSafeLevel() >= 4 && !isTaint()) {
throw new SecurityException("Insecure: can't undef");
}
testFrozen("module");
if (name.equals("__id__") || name.equals("__send__")) {
getRuntime().getWarnings().warn("undefining `"+ name +"' may cause serious problem");
}
ICallable method = searchMethod(name);
if (method.isUndefined()) {
String s0 = " class";
RubyModule c = this;
if (c.isSingleton()) {
IRubyObject obj = getInstanceVariable("__attached__");
if (obj != null && obj instanceof RubyModule) {
c = (RubyModule) obj;
s0 = "";
}
} else if (c.isModule()) {
s0 = " module";
}
throw getRuntime().newNameError("Undefined method " + name + " for" + s0 + " '" + c.getName() + "'", name);
}
addMethod(name, UndefinedMethod.getInstance());
}
private void addCachedMethod(String name, ICallable method) {
// Included modules modify the original 'included' modules class. Since multiple
// classes can include the same module, we cannot cache in the original included module.
if (!isIncluded()) {
getMethods().put(name, method);
getRuntime().getCacheMap().add(method, this);
}
}
// TODO: Consider a better way of synchronizing
public void addMethod(String name, ICallable method) {
if (this == getRuntime().getObject()) {
getRuntime().secure(4);
}
if (getRuntime().getSafeLevel() >= 4 && !isTaint()) {
throw getRuntime().newSecurityError("Insecure: can't define method");
}
testFrozen("class/module");
// We can safely reference methods here instead of doing getMethods() since if we
// are adding we are not using a IncludedModuleWrapper.
synchronized(getMethods()) {
// If we add a method which already is cached in this class, then we should update the
// cachemap so it stays up to date.
ICallable existingMethod = (ICallable) getMethods().remove(name);
if (existingMethod != null) {
getRuntime().getCacheMap().remove(name, existingMethod);
}
getMethods().put(name, method);
}
}
public void removeCachedMethod(String name) {
getMethods().remove(name);
}
public void removeMethod(String name) {
if (this == getRuntime().getObject()) {
getRuntime().secure(4);
}
if (getRuntime().getSafeLevel() >= 4 && !isTaint()) {
throw getRuntime().newSecurityError("Insecure: can't remove method");
}
testFrozen("class/module");
// We can safely reference methods here instead of doing getMethods() since if we
// are adding we are not using a IncludedModuleWrapper.
synchronized(getMethods()) {
ICallable method = (ICallable) getMethods().remove(name);
if (method == null) {
throw getRuntime().newNameError("method '" + name + "' not defined in " + getName(), name);
}
getRuntime().getCacheMap().remove(name, method);
}
}
/**
* Search through this module and supermodules for method definitions. Cache superclass definitions in this class.
*
* @param name The name of the method to search for
* @return The method, or UndefinedMethod if not found
*/
public ICallable searchMethod(String name) {
for (RubyModule searchModule = this; searchModule != null; searchModule = searchModule.getSuperClass()) {
// included modules use delegates methods for we need to synchronize on result of getMethods
synchronized(searchModule.getMethods()) {
// See if current class has method or if it has been cached here already
ICallable method = (ICallable) searchModule.getMethods().get(name);
if (method != null) {
if (searchModule != this) {
addCachedMethod(name, method);
}
return method;
}
}
}
return UndefinedMethod.getInstance();
}
/**
* Search through this module and supermodules for method definitions. Cache superclass definitions in this class.
*
* @param name The name of the method to search for
* @return The method, or UndefinedMethod if not found
*/
public ICallable retrieveMethod(String name) {
return (ICallable)getMethods().get(name);
}
/**
* Search through this module and supermodules for method definitions. Cache superclass definitions in this class.
*
* @param name The name of the method to search for
* @return The method, or UndefinedMethod if not found
*/
public RubyModule findImplementer(RubyModule clazz) {
for (RubyModule searchModule = this; searchModule != null; searchModule = searchModule.getSuperClass()) {
if (searchModule.isSame(clazz)) {
return searchModule;
}
}
return null;
}
public void addModuleFunction(String name, ICallable method) {
addMethod(name, method);
addSingletonMethod(name, method);
}
/** rb_define_module_function
*
*/
public void defineModuleFunction(String name, Callback method) {
definePrivateMethod(name, method);
defineSingletonMethod(name, method);
}
/** rb_define_module_function
*
*/
public void definePublicModuleFunction(String name, Callback method) {
defineMethod(name, method);
defineSingletonMethod(name, method);
}
private IRubyObject getConstantInner(String name, boolean exclude) {
IRubyObject objectClass = getRuntime().getObject();
boolean retryForModule = false;
RubyModule p = this;
retry: while (true) {
while (p != null) {
IRubyObject constant = p.getConstantAt(name);
if (constant == null) {
if (getRuntime().getLoadService().autoload(p.getName() + "::" + name) != null) {
continue;
}
}
if (constant != null) {
if (exclude && p == objectClass && this != objectClass) {
getRuntime().getWarnings().warn("toplevel constant " + name +
" referenced by " + getName() + "::" + name);
}
return constant;
}
p = p.getSuperClass();
}
if (!exclude && !retryForModule && getClass().equals(RubyModule.class)) {
retryForModule = true;
p = getRuntime().getObject();
continue retry;
}
break;
}
return callMethod(getRuntime().getCurrentContext(), "const_missing", RubySymbol.newSymbol(getRuntime(), name));
}
/**
* Retrieve the named constant, invoking 'const_missing' should that be appropriate.
*
* @param name The constant to retrieve
* @return The value for the constant, or null if not found
*/
public IRubyObject getConstant(String name) {
return getConstantInner(name, false);
}
public IRubyObject getConstantFrom(String name) {
return getConstantInner(name, true);
}
public IRubyObject getConstantAt(String name) {
return getInstanceVariable(name);
}
/** rb_alias
*
*/
public synchronized void defineAlias(String name, String oldName) {
testFrozen("module");
if (oldName.equals(name)) {
return;
}
if (this == getRuntime().getObject()) {
getRuntime().secure(4);
}
ICallable method = searchMethod(oldName);
if (method.isUndefined()) {
if (isModule()) {
method = getRuntime().getObject().searchMethod(oldName);
}
if (method.isUndefined()) {
throw getRuntime().newNameError("undefined method `" + oldName + "' for " +
(isModule() ? "module" : "class") + " `" + getName() + "'", oldName);
}
}
getRuntime().getCacheMap().remove(name, searchMethod(name));
getMethods().put(name, new AliasMethod(method, oldName));
}
public RubyClass defineOrGetClassUnder(String name, RubyClass superClazz) {
IRubyObject type = getConstantAt(name);
if (type == null) {
return (RubyClass) setConstant(name,
getRuntime().defineClassUnder(name, superClazz, cref));
}
if (!(type instanceof RubyClass)) {
throw getRuntime().newTypeError(name + " is not a class.");
} else if (superClazz != null && ((RubyClass) type).getSuperClass().getRealClass() != superClazz) {
throw getRuntime().newTypeError("superclass mismatch for class " + name);
}
return (RubyClass) type;
}
/** rb_define_class_under
*
*/
public RubyClass defineClassUnder(String name, RubyClass superClazz) {
IRubyObject type = getConstantAt(name);
if (type == null) {
return (RubyClass) setConstant(name,
getRuntime().defineClassUnder(name, superClazz, cref));
}
if (!(type instanceof RubyClass)) {
throw getRuntime().newTypeError(name + " is not a class.");
} else if (((RubyClass) type).getSuperClass().getRealClass() != superClazz) {
throw getRuntime().newNameError(name + " is already defined.", name);
}
return (RubyClass) type;
}
public RubyModule defineModuleUnder(String name) {
IRubyObject type = getConstantAt(name);
if (type == null) {
return (RubyModule) setConstant(name,
getRuntime().defineModuleUnder(name, cref));
}
if (!(type instanceof RubyModule)) {
throw getRuntime().newTypeError(name + " is not a module.");
}
return (RubyModule) type;
}
/** rb_define_const
*
*/
public void defineConstant(String name, IRubyObject value) {
assert value != null;
if (this == getRuntime().getClass("Class")) {
getRuntime().secure(4);
}
if (!IdUtil.isConstant(name)) {
throw getRuntime().newNameError("bad constant name " + name, name);
}
setConstant(name, value);
}
/** rb_mod_remove_cvar
*
*/
public IRubyObject removeCvar(IRubyObject name) { // Wrong Parameter ?
if (!IdUtil.isClassVariable(name.asSymbol())) {
throw getRuntime().newNameError("wrong class variable name " + name.asSymbol(), name.asSymbol());
}
if (!isTaint() && getRuntime().getSafeLevel() >= 4) {
throw getRuntime().newSecurityError("Insecure: can't remove class variable");
}
testFrozen("class/module");
IRubyObject value = removeInstanceVariable(name.asSymbol());
if (value != null) {
return value;
}
if (isClassVarDefined(name.asSymbol())) {
throw cannotRemoveError(name.asSymbol());
}
throw getRuntime().newNameError("class variable " + name.asSymbol() + " not defined for " + getName(), name.asSymbol());
}
private void addAccessor(String name, boolean readable, boolean writeable) {
ThreadContext tc = getRuntime().getCurrentContext();
// Check the visibility of the previous frame, which will be the frame in which the class is being eval'ed
Visibility attributeScope = tc.getCurrentVisibility();
if (attributeScope.isPrivate()) {
//FIXME warning
} else if (attributeScope.isModuleFunction()) {
attributeScope = Visibility.PRIVATE;
// FIXME warning
}
final String variableName = "@" + name;
final IRuby runtime = getRuntime();
ThreadContext context = getRuntime().getCurrentContext();
if (readable) {
defineMethod(name, new Callback() {
public IRubyObject execute(IRubyObject self, IRubyObject[] args) {
checkArgumentCount(args, 0, 0);
IRubyObject variable = self.getInstanceVariable(variableName);
return variable == null ? runtime.getNil() : variable;
}
public Arity getArity() {
return Arity.noArguments();
}
});
callMethod(context, "method_added", RubySymbol.newSymbol(getRuntime(), name));
}
if (writeable) {
name = name + "=";
defineMethod(name, new Callback() {
public IRubyObject execute(IRubyObject self, IRubyObject[] args) {
IRubyObject[] fargs = runtime.getCurrentContext().getFrameArgs();
if (fargs.length != 1) {
throw runtime.newArgumentError("wrong # of arguments(" + fargs.length + "for 1)");
}
return self.setInstanceVariable(variableName, fargs[0]);
}
public Arity getArity() {
return Arity.singleArgument();
}
});
callMethod(context, "method_added", RubySymbol.newSymbol(getRuntime(), name));
}
}
/** set_method_visibility
*
*/
public void setMethodVisibility(IRubyObject[] methods, Visibility visibility) {
if (getRuntime().getSafeLevel() >= 4 && !isTaint()) {
throw getRuntime().newSecurityError("Insecure: can't change method visibility");
}
for (int i = 0; i < methods.length; i++) {
exportMethod(methods[i].asSymbol(), visibility);
}
}
/** rb_export_method
*
*/
public void exportMethod(String name, Visibility visibility) {
if (this == getRuntime().getObject()) {
getRuntime().secure(4);
}
ICallable method = searchMethod(name);
if (method.isUndefined()) {
throw getRuntime().newNameError("undefined method '" + name + "' for " +
(isModule() ? "module" : "class") + " '" + getName() + "'", name);
}
if (method.getVisibility() != visibility) {
if (this == method.getImplementationClass()) {
method.setVisibility(visibility);
} else {
final ThreadContext context = getRuntime().getCurrentContext();
addMethod(name, new CallbackMethod(this, new Callback() {
public IRubyObject execute(IRubyObject self, IRubyObject[] args) {
return context.callSuper(context.getFrameArgs());
}
public Arity getArity() {
return Arity.optional();
}
}, visibility));
}
}
}
/**
* MRI: rb_method_boundp
*
*/
public boolean isMethodBound(String name, boolean checkVisibility) {
ICallable method = searchMethod(name);
if (!method.isUndefined()) {
return !(checkVisibility && method.getVisibility().isPrivate());
}
return false;
}
public IRubyObject newMethod(IRubyObject receiver, String name, boolean bound) {
ICallable method = searchMethod(name);
if (method.isUndefined()) {
throw getRuntime().newNameError("undefined method `" + name +
"' for class `" + this.getName() + "'", name);
}
RubyMethod newMethod = null;
if (bound) {
newMethod = RubyMethod.newMethod(method.getImplementationClass(), name, this, name, method, receiver);
} else {
newMethod = RubyUnboundMethod.newUnboundMethod(method.getImplementationClass(), name, this, name, method);
}
newMethod.infectBy(this);
return newMethod;
}
// What is argument 1 for in this method?
public IRubyObject define_method(IRubyObject[] args) {
if (args.length < 1 || args.length > 2) {
throw getRuntime().newArgumentError("wrong # of arguments(" + args.length + " for 1)");
}
IRubyObject body;
String name = args[0].asSymbol();
ICallable newMethod = null;
ThreadContext tc = getRuntime().getCurrentContext();
Visibility visibility = tc.getCurrentVisibility();
if (visibility.isModuleFunction()) {
visibility = Visibility.PRIVATE;
}
if (args.length == 1 || args[1].isKindOf(getRuntime().getClass("Proc"))) {
// double-testing args.length here, but it avoids duplicating the proc-setup code in two places
RubyProc proc = (args.length == 1) ? getRuntime().newProc() : (RubyProc)args[1];
body = proc;
proc.getBlock().isLambda = true;
proc.getBlock().getFrame().setLastClass(this);
proc.getBlock().getFrame().setLastFunc(name);
newMethod = new ProcMethod(this, proc, visibility);
} else if (args[1].isKindOf(getRuntime().getClass("Method"))) {
RubyMethod method = (RubyMethod)args[1];
body = method;
newMethod = new MethodMethod(this, method.unbind(), visibility);
} else {
throw getRuntime().newTypeError("wrong argument type " + args[0].getType().getName() + " (expected Proc/Method)");
}
addMethod(name, newMethod);
RubySymbol symbol = RubySymbol.newSymbol(getRuntime(), name);
ThreadContext context = getRuntime().getCurrentContext();
if (tc.getPreviousVisibility().isModuleFunction()) {
getSingletonClass().addMethod(name, new WrapperCallable(getSingletonClass(), newMethod, Visibility.PUBLIC));
callMethod(context, "singleton_method_added", symbol);
}
callMethod(context, "method_added", symbol);
return body;
}
public IRubyObject executeUnder(Callback method, IRubyObject[] args) {
ThreadContext context = getRuntime().getCurrentContext();
context.preExecuteUnder(this);
try {
return method.execute(this, args);
} finally {
context.postExecuteUnder();
}
}
// Methods of the Module Class (rb_mod_*):
public static RubyModule newModule(IRuby runtime, String name) {
return newModule(runtime, name, null);
}
public static RubyModule newModule(IRuby runtime, String name, SinglyLinkedList parentCRef) {
// Modules do not directly define Object as their superClass even though in theory they
// should. The C version of Ruby may also do this (special checks in rb_alias for Module
// makes me think this).
// TODO cnutter: Shouldn't new modules have Module as their superclass?
RubyModule newModule = new RubyModule(runtime, runtime.getClass("Module"), null, parentCRef, name);
ThreadContext tc = runtime.getCurrentContext();
if (tc.isBlockGiven()) {
tc.yieldCurrentBlock(null, newModule, newModule, false);
}
return newModule;
}
public RubyString name() {
return getRuntime().newString(getBaseName() == null ? "" : getName());
}
/** rb_mod_class_variables
*
*/
public RubyArray class_variables() {
RubyArray ary = getRuntime().newArray();
for (RubyModule p = this; p != null; p = p.getSuperClass()) {
for (Iterator iter = p.instanceVariableNames(); iter.hasNext();) {
String id = (String) iter.next();
if (IdUtil.isClassVariable(id)) {
RubyString kval = getRuntime().newString(id);
if (!ary.includes(kval)) {
ary.append(kval);
}
}
}
}
return ary;
}
/** rb_mod_clone
*
*/
public IRubyObject rbClone() {
return cloneMethods((RubyModule) super.rbClone());
}
protected IRubyObject cloneMethods(RubyModule clone) {
RubyModule realType = this.getNonIncludedClass();
for (Iterator iter = getMethods().entrySet().iterator(); iter.hasNext(); ) {
Map.Entry entry = (Map.Entry) iter.next();
ICallable method = (ICallable) entry.getValue();
// Do not clone cached methods
if (method.getImplementationClass() == realType) {
// A cloned method now belongs to a new class. Set it.
// TODO: Make ICallable immutable
ICallable clonedMethod = method.dup();
clonedMethod.setImplementationClass(clone);
clone.getMethods().put(entry.getKey(), clonedMethod);
}
}
return clone;
}
protected IRubyObject doClone() {
return RubyModule.newModule(getRuntime(), getBaseName(), cref.getNext());
}
/** rb_mod_dup
*
*/
public IRubyObject dup() {
RubyModule dup = (RubyModule) rbClone();
dup.setMetaClass(getMetaClass());
dup.setFrozen(false);
// +++ jpetersen
// dup.setSingleton(isSingleton());
// --- jpetersen
return dup;
}
/** rb_mod_included_modules
*
*/
public RubyArray included_modules() {
RubyArray ary = getRuntime().newArray();
for (RubyModule p = getSuperClass(); p != null; p = p.getSuperClass()) {
if (p.isIncluded()) {
ary.append(p.getNonIncludedClass());
}
}
return ary;
}
/** rb_mod_ancestors
*
*/
public RubyArray ancestors() {
RubyArray ary = getRuntime().newArray(getAncestorList());
return ary;
}
public List getAncestorList() {
ArrayList list = new ArrayList();
for (RubyModule p = this; p != null; p = p.getSuperClass()) {
if(!p.isSingleton()) {
list.add(p.getNonIncludedClass());
}
}
return list;
}
public boolean hasModuleInHierarchy(RubyModule type) {
// XXX: This check previously used callMethod("==") to check for equality between classes
// when scanning the hierarchy. However the == check may be safe; we should only ever have
// one instance bound to a given type/constant. If it's found to be unsafe, examine ways
// to avoid the == call.
for (RubyModule p = this; p != null; p = p.getSuperClass()) {
if (p.getNonIncludedClass() == type) return true;
}
return false;
}
/** rb_mod_to_s
*
*/
public IRubyObject to_s() {
return getRuntime().newString(getName());
}
/** rb_mod_eqq
*
*/
public RubyBoolean op_eqq(IRubyObject obj) {
return getRuntime().newBoolean(obj.isKindOf(this));
}
/** rb_mod_le
*
*/
public IRubyObject op_le(IRubyObject obj) {
if (!(obj instanceof RubyModule)) {
throw getRuntime().newTypeError("compared with non class/module");
}
if (isKindOfModule((RubyModule)obj)) {
return getRuntime().getTrue();
} else if (((RubyModule)obj).isKindOfModule(this)) {
return getRuntime().getFalse();
}
return getRuntime().getNil();
}
/** rb_mod_lt
*
*/
public IRubyObject op_lt(IRubyObject obj) {
return obj == this ? getRuntime().getFalse() : op_le(obj);
}
/** rb_mod_ge
*
*/
public IRubyObject op_ge(IRubyObject obj) {
if (!(obj instanceof RubyModule)) {
throw getRuntime().newTypeError("compared with non class/module");
}
return ((RubyModule) obj).op_le(this);
}
/** rb_mod_gt
*
*/
public IRubyObject op_gt(IRubyObject obj) {
return this == obj ? getRuntime().getFalse() : op_ge(obj);
}
/** rb_mod_cmp
*
*/
public IRubyObject op_cmp(IRubyObject obj) {
if (this == obj) {
return getRuntime().newFixnum(0);
}
if (!(obj instanceof RubyModule)) {
throw getRuntime().newTypeError(
"<=> requires Class or Module (" + getMetaClass().getName() + " given)");
}
RubyModule module = (RubyModule)obj;
if (module.isKindOfModule(this)) {
return getRuntime().newFixnum(1);
} else if (this.isKindOfModule(module)) {
return getRuntime().newFixnum(-1);
}
return getRuntime().getNil();
}
public boolean isKindOfModule(RubyModule type) {
for (RubyModule p = this; p != null; p = p.getSuperClass()) {
if (p.isSame(type)) {
return true;
}
}
return false;
}
public boolean isSame(RubyModule module) {
return this == module;
}
/** rb_mod_initialize
*
*/
public IRubyObject initialize(IRubyObject[] args) {
return getRuntime().getNil();
}
/** rb_mod_attr
*
*/
public IRubyObject attr(IRubyObject[] args) {
checkArgumentCount(args, 1, 2);
boolean writeable = args.length > 1 ? args[1].isTrue() : false;
addAccessor(args[0].asSymbol(), true, writeable);
return getRuntime().getNil();
}
/** rb_mod_attr_reader
*
*/
public IRubyObject attr_reader(IRubyObject[] args) {
for (int i = 0; i < args.length; i++) {
addAccessor(args[i].asSymbol(), true, false);
}
return getRuntime().getNil();
}
/** rb_mod_attr_writer
*
*/
public IRubyObject attr_writer(IRubyObject[] args) {
for (int i = 0; i < args.length; i++) {
addAccessor(args[i].asSymbol(), false, true);
}
return getRuntime().getNil();
}
/** rb_mod_attr_accessor
*
*/
public IRubyObject attr_accessor(IRubyObject[] args) {
for (int i = 0; i < args.length; i++) {
addAccessor(args[i].asSymbol(), true, true);
}
return getRuntime().getNil();
}
/** rb_mod_const_get
*
*/
public IRubyObject const_get(IRubyObject symbol) {
String name = symbol.asSymbol();
if (!IdUtil.isConstant(name)) {
throw wrongConstantNameError(name);
}
return getConstant(name);
}
/** rb_mod_const_set
*
*/
public IRubyObject const_set(IRubyObject symbol, IRubyObject value) {
String name = symbol.asSymbol();
if (!IdUtil.isConstant(name)) {
throw wrongConstantNameError(name);
}
return setConstant(name, value);
}
/** rb_mod_const_defined
*
*/
public RubyBoolean const_defined(IRubyObject symbol) {
String name = symbol.asSymbol();
if (!IdUtil.isConstant(name)) {
throw wrongConstantNameError(name);
}
return getRuntime().newBoolean(getConstantAt(name) != null);
}
private RaiseException wrongConstantNameError(String name) {
return getRuntime().newNameError("wrong constant name " + name, name);
}
private RubyArray instance_methods(IRubyObject[] args, final Visibility visibility) {
boolean includeSuper = args.length > 0 ? args[0].isTrue() : true;
RubyArray ary = getRuntime().newArray();
HashMap undefinedMethods = new HashMap();
for (RubyModule type = this; type != null; type = type.getSuperClass()) {
RubyModule realType = type.getNonIncludedClass();
for (Iterator iter = type.getMethods().entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
ICallable method = (ICallable) entry.getValue();
String methodName = (String) entry.getKey();
if (method.isUndefined()) {
undefinedMethods.put(methodName, Boolean.TRUE);
continue;
}
if (method.getImplementationClass() == realType &&
method.getVisibility().is(visibility) && undefinedMethods.get(methodName) == null) {
RubyString name = getRuntime().newString(methodName);
if (!ary.includes(name)) {
ary.append(name);
}
}
}
if (!includeSuper) {
break;
}
}
return ary;
}
public RubyArray instance_methods(IRubyObject[] args) {
return instance_methods(args, Visibility.PUBLIC_PROTECTED);
}
public RubyArray public_instance_methods(IRubyObject[] args) {
return instance_methods(args, Visibility.PUBLIC);
}
public IRubyObject instance_method(IRubyObject symbol) {
return newMethod(null, symbol.asSymbol(), false);
}
/** rb_class_protected_instance_methods
*
*/
public RubyArray protected_instance_methods(IRubyObject[] args) {
return instance_methods(args, Visibility.PROTECTED);
}
/** rb_class_private_instance_methods
*
*/
public RubyArray private_instance_methods(IRubyObject[] args) {
return instance_methods(args, Visibility.PRIVATE);
}
/** rb_mod_constants
*
*/
public RubyArray constants() {
ArrayList constantNames = new ArrayList();
RubyModule objectClass = getRuntime().getObject();
if (getRuntime().getClass("Module") == this) {
for (Iterator vars = objectClass.instanceVariableNames();
vars.hasNext();) {
String name = (String) vars.next();
if (IdUtil.isConstant(name)) {
constantNames.add(getRuntime().newString(name));
}
}
return getRuntime().newArray(constantNames);
} else if (getRuntime().getObject() == this) {
for (Iterator vars = instanceVariableNames(); vars.hasNext();) {
String name = (String) vars.next();
if (IdUtil.isConstant(name)) {
constantNames.add(getRuntime().newString(name));
}
}
return getRuntime().newArray(constantNames);
}
for (RubyModule p = this; p != null; p = p.getSuperClass()) {
if (objectClass == p) {
continue;
}
for (Iterator vars = p.instanceVariableNames(); vars.hasNext();) {
String name = (String) vars.next();
if (IdUtil.isConstant(name)) {
constantNames.add(getRuntime().newString(name));
}
}
}
return getRuntime().newArray(constantNames);
}
/** rb_mod_remove_cvar
*
*/
public IRubyObject remove_class_variable(IRubyObject name) {
String id = name.asSymbol();
if (!IdUtil.isClassVariable(id)) {
throw getRuntime().newNameError("wrong class variable name " + id, id);
}
if (!isTaint() && getRuntime().getSafeLevel() >= 4) {
throw getRuntime().newSecurityError("Insecure: can't remove class variable");
}
testFrozen("class/module");
IRubyObject variable = removeInstanceVariable(id);
if (variable != null) {
return variable;
}
if (isClassVarDefined(id)) {
throw cannotRemoveError(id);
}
throw getRuntime().newNameError("class variable " + id + " not defined for " + getName(), id);
}
private RaiseException cannotRemoveError(String id) {
return getRuntime().newNameError("cannot remove " + id + " for " + getName(), id);
}
public IRubyObject remove_const(IRubyObject name) {
String id = name.asSymbol();
if (!IdUtil.isConstant(id)) {
throw wrongConstantNameError(id);
}
if (!isTaint() && getRuntime().getSafeLevel() >= 4) {
throw getRuntime().newSecurityError("Insecure: can't remove class variable");
}
testFrozen("class/module");
IRubyObject variable = getInstanceVariable(id);
if (variable != null) {
return removeInstanceVariable(id);
}
if (isClassVarDefined(id)) {
throw cannotRemoveError(id);
}
throw getRuntime().newNameError("constant " + id + " not defined for " + getName(), id);
}
/** rb_mod_append_features
*
*/
// TODO: Proper argument check (conversion?)
public RubyModule append_features(IRubyObject module) {
((RubyModule) module).includeModule(this);
return this;
}
/** rb_mod_extend_object
*
*/
public IRubyObject extend_object(IRubyObject obj) {
obj.extendObject(this);
return obj;
}
/** rb_mod_include
*
*/
public RubyModule include(IRubyObject[] modules) {
ThreadContext context = getRuntime().getCurrentContext();
for (int i = modules.length - 1; i >= 0; i--) {
modules[i].callMethod(context, "append_features", this);
modules[i].callMethod(context, "included", this);
}
return this;
}
public IRubyObject included(IRubyObject other) {
return getRuntime().getNil();
}
public IRubyObject extended(IRubyObject other) {
return getRuntime().getNil();
}
private void setVisibility(IRubyObject[] args, Visibility visibility) {
if (getRuntime().getSafeLevel() >= 4 && !isTaint()) {
throw getRuntime().newSecurityError("Insecure: can't change method visibility");
}
if (args.length == 0) {
getRuntime().getCurrentContext().setCurrentVisibility(visibility);
} else {
setMethodVisibility(args, visibility);
}
}
/** rb_mod_public
*
*/
public RubyModule rbPublic(IRubyObject[] args) {
setVisibility(args, Visibility.PUBLIC);
return this;
}
/** rb_mod_protected
*
*/
public RubyModule rbProtected(IRubyObject[] args) {
setVisibility(args, Visibility.PROTECTED);
return this;
}
/** rb_mod_private
*
*/
public RubyModule rbPrivate(IRubyObject[] args) {
setVisibility(args, Visibility.PRIVATE);
return this;
}
/** rb_mod_modfunc
*
*/
public RubyModule module_function(IRubyObject[] args) {
if (getRuntime().getSafeLevel() >= 4 && !isTaint()) {
throw getRuntime().newSecurityError("Insecure: can't change method visibility");
}
ThreadContext context = getRuntime().getCurrentContext();
if (args.length == 0) {
context.setCurrentVisibility(Visibility.MODULE_FUNCTION);
} else {
setMethodVisibility(args, Visibility.PRIVATE);
for (int i = 0; i < args.length; i++) {
String name = args[i].asSymbol();
ICallable method = searchMethod(name);
assert !method.isUndefined() : "undefined method '" + name + "'";
getSingletonClass().addMethod(name, new WrapperCallable(getSingletonClass(), method, Visibility.PUBLIC));
callMethod(context, "singleton_method_added", RubySymbol.newSymbol(getRuntime(), name));
}
}
return this;
}
public IRubyObject method_added(IRubyObject nothing) {
return getRuntime().getNil();
}
public RubyBoolean method_defined(IRubyObject symbol) {
return isMethodBound(symbol.asSymbol(), true) ? getRuntime().getTrue() : getRuntime().getFalse();
}
public RubyModule public_class_method(IRubyObject[] args) {
getMetaClass().setMethodVisibility(args, Visibility.PUBLIC);
return this;
}
public RubyModule private_class_method(IRubyObject[] args) {
getMetaClass().setMethodVisibility(args, Visibility.PRIVATE);
return this;
}
public RubyModule alias_method(IRubyObject newId, IRubyObject oldId) {
defineAlias(newId.asSymbol(), oldId.asSymbol());
return this;
}
public RubyModule undef_method(IRubyObject name) {
undef(name.asSymbol());
return this;
}
public IRubyObject module_eval(IRubyObject[] args) {
return specificEval(this, args);
}
public RubyModule remove_method(IRubyObject name) {
removeMethod(name.asSymbol());
return this;
}
public void marshalTo(MarshalStream output) throws java.io.IOException {
output.write('m');
output.dumpString(name().toString());
}
public static RubyModule unmarshalFrom(UnmarshalStream input) throws java.io.IOException {
String name = input.unmarshalString();
IRuby runtime = input.getRuntime();
RubyModule result = runtime.getClassFromPath(name);
if (result == null) {
throw runtime.newNameError("uninitialized constant " + name, name);
}
input.registerLinkTarget(result);
return result;
}
public SinglyLinkedList getCRef() {
return cref;
}
public IRubyObject inspect() {
return callMethod(getRuntime().getCurrentContext(), "to_s");
}
}
| true | true | public synchronized void includeModule(IRubyObject arg) {
assert arg != null;
testFrozen("module");
if (!isTaint()) {
getRuntime().secure(4);
}
if (!(arg instanceof RubyModule)) {
throw getRuntime().newTypeError("Wrong argument type " + arg.getMetaClass().getName() +
" (expected Module).");
}
RubyModule module = (RubyModule) arg;
// Make sure the module we include does not already exist
if (isSame(module)) {
return;
}
infectBy(module);
RubyModule p, c;
boolean changed = false;
boolean skip = false;
c = this;
while (module != null) {
if (getNonIncludedClass() == module.getNonIncludedClass()) {
throw getRuntime().newArgumentError("cyclic include detected");
}
boolean superclassSeen = false;
for (p = getSuperClass(); p != null; p = p.getSuperClass()) {
if (p instanceof IncludedModuleWrapper) {
if (p.getNonIncludedClass() == module.getNonIncludedClass()) {
if (!superclassSeen) {
c = p;
}
skip = true;
break;
}
} else {
superclassSeen = true;
}
}
if (!skip) {
// In the current logic, if we get here we know that module is not an
// IncludedModuleWrapper, so there's no need to fish out the delegate. But just
// in case the logic should change later, let's do it anyway:
c.setSuperClass(new IncludedModuleWrapper(getRuntime(), c.getSuperClass(),
module.getNonIncludedClass()));
c = c.getSuperClass();
changed = true;
}
module = module.getSuperClass();
skip = false;
}
if (changed) {
// MRI seems to blow away its cache completely after an include; is
// what we're doing here really safe?
for (Iterator iter = ((RubyModule) arg).getMethods().keySet().iterator();
iter.hasNext();) {
String methodName = (String) iter.next();
getRuntime().getCacheMap().remove(methodName, searchMethod(methodName));
}
}
}
| public synchronized void includeModule(IRubyObject arg) {
assert arg != null;
testFrozen("module");
if (!isTaint()) {
getRuntime().secure(4);
}
if (!(arg instanceof RubyModule)) {
throw getRuntime().newTypeError("Wrong argument type " + arg.getMetaClass().getName() +
" (expected Module).");
}
RubyModule module = (RubyModule) arg;
// Make sure the module we include does not already exist
if (isSame(module)) {
return;
}
infectBy(module);
RubyModule p, c;
boolean changed = false;
boolean skip = false;
c = this;
while (module != null) {
if (getNonIncludedClass() == module.getNonIncludedClass()) {
throw getRuntime().newArgumentError("cyclic include detected");
}
boolean superclassSeen = false;
for (p = getSuperClass(); p != null; p = p.getSuperClass()) {
if (p instanceof IncludedModuleWrapper) {
if (p.getNonIncludedClass() == module.getNonIncludedClass()) {
if (!superclassSeen) {
c = p;
}
skip = true;
break;
}
} else {
superclassSeen = true;
}
}
if (!skip) {
// In the current logic, if we get here we know that module is not an
// IncludedModuleWrapper, so there's no need to fish out the delegate. But just
// in case the logic should change later, let's do it anyway:
c.setSuperClass(new IncludedModuleWrapper(getRuntime(), c.getSuperClass(),
module.getNonIncludedClass()));
c = c.getSuperClass();
changed = true;
}
module = module.getSuperClass();
skip = false;
}
if (changed) {
// MRI seems to blow away its cache completely after an include; is
// what we're doing here really safe?
List methodNames = new ArrayList(((RubyModule) arg).getMethods().keySet());
for (Iterator iter = methodNames.iterator();
iter.hasNext();) {
String methodName = (String) iter.next();
getRuntime().getCacheMap().remove(methodName, searchMethod(methodName));
}
}
}
|
diff --git a/app/controllers/ImportApp.java b/app/controllers/ImportApp.java
index 1f3a9f5a..af3b6c10 100644
--- a/app/controllers/ImportApp.java
+++ b/app/controllers/ImportApp.java
@@ -1,98 +1,98 @@
package controllers;
import models.Project;
import models.ProjectUser;
import models.enumeration.ResourceType;
import models.enumeration.RoleType;
import play.data.Form;
import play.db.ebean.Transactional;
import play.mvc.Controller;
import play.mvc.Result;
import playRepository.GitRepository;
import utils.AccessControl;
import utils.Constants;
import utils.FileUtil;
import views.html.project.importing;
import org.eclipse.jgit.api.errors.*;
import java.io.IOException;
import java.io.File;
import static play.data.Form.form;
public class ImportApp extends Controller {
/**
* Git repository에서 코드를 가져와서 프로젝트를 만드는 폼을 보여준다.
*
* @return
*/
public static Result importForm() {
if (UserApp.currentUser().isAnonymous()) {
flash(Constants.WARNING, "user.login.alert");
return redirect(routes.UserApp.loginForm());
} else {
return ok(importing.render("title.newProject", form(Project.class)));
}
}
/**
* 새 프로젝트 시작 폼에 추가로 Git 저장소 URL을 추가로 입력받고
* 해당 저장소를 clone하여 프로젝트의 Git 저장소를 생성한다.
*
* @return
*/
@Transactional
public static Result newProject() throws GitAPIException, IOException {
if( !AccessControl.isCreatable(UserApp.currentUser(), ResourceType.PROJECT) ){
return forbidden("'" + UserApp.currentUser().name + "' has no permission");
}
Form<Project> filledNewProjectForm = form(Project.class).bindFromRequest();
String gitUrl = filledNewProjectForm.data().get("url");
if(gitUrl == null || gitUrl.trim().isEmpty()) {
- flash(Constants.WARNING, "import.error.empty.url");
+ flash(Constants.WARNING, "project.import.error.empty.url");
return badRequest(importing.render("title.newProject", filledNewProjectForm));
}
if (Project.exists(UserApp.currentUser().loginId, filledNewProjectForm.field("name").value())) {
flash(Constants.WARNING, "project.name.duplicate");
filledNewProjectForm.reject("name");
return badRequest(importing.render("title.newProject", filledNewProjectForm));
}
if (filledNewProjectForm.hasErrors()) {
filledNewProjectForm.reject("name");
flash(Constants.WARNING, "project.name.alert");
return badRequest(importing.render("title.newProject", filledNewProjectForm));
}
Project project = filledNewProjectForm.get();
project.owner = UserApp.currentUser().loginId;
String errorMessageKey = null;
try {
GitRepository.cloneRepository(gitUrl, project);
Long projectId = Project.create(project);
ProjectUser.assignRole(UserApp.currentUser().id, projectId, RoleType.MANAGER);
} catch (InvalidRemoteException e) {
// It is not an url.
- errorMessageKey = "import.error.wrong.url";
+ errorMessageKey = "project.import.error.wrong.url";
} catch (JGitInternalException e) {
// The url seems that does not locate a git repository.
- errorMessageKey = "import.error.wrong.url";
+ errorMessageKey = "project.import.error.wrong.url";
} catch (TransportException e) {
- errorMessageKey = "import.error.transport";
+ errorMessageKey = "project.import.error.transport";
}
if (errorMessageKey != null) {
flash(Constants.WARNING, errorMessageKey);
FileUtil.rm_rf(new File(GitRepository.getGitDirectory(project)));
return badRequest(importing.render("title.newProject", filledNewProjectForm));
} else {
return redirect(routes.ProjectApp.project(project.owner, project.name));
}
}
}
| false | true | public static Result newProject() throws GitAPIException, IOException {
if( !AccessControl.isCreatable(UserApp.currentUser(), ResourceType.PROJECT) ){
return forbidden("'" + UserApp.currentUser().name + "' has no permission");
}
Form<Project> filledNewProjectForm = form(Project.class).bindFromRequest();
String gitUrl = filledNewProjectForm.data().get("url");
if(gitUrl == null || gitUrl.trim().isEmpty()) {
flash(Constants.WARNING, "import.error.empty.url");
return badRequest(importing.render("title.newProject", filledNewProjectForm));
}
if (Project.exists(UserApp.currentUser().loginId, filledNewProjectForm.field("name").value())) {
flash(Constants.WARNING, "project.name.duplicate");
filledNewProjectForm.reject("name");
return badRequest(importing.render("title.newProject", filledNewProjectForm));
}
if (filledNewProjectForm.hasErrors()) {
filledNewProjectForm.reject("name");
flash(Constants.WARNING, "project.name.alert");
return badRequest(importing.render("title.newProject", filledNewProjectForm));
}
Project project = filledNewProjectForm.get();
project.owner = UserApp.currentUser().loginId;
String errorMessageKey = null;
try {
GitRepository.cloneRepository(gitUrl, project);
Long projectId = Project.create(project);
ProjectUser.assignRole(UserApp.currentUser().id, projectId, RoleType.MANAGER);
} catch (InvalidRemoteException e) {
// It is not an url.
errorMessageKey = "import.error.wrong.url";
} catch (JGitInternalException e) {
// The url seems that does not locate a git repository.
errorMessageKey = "import.error.wrong.url";
} catch (TransportException e) {
errorMessageKey = "import.error.transport";
}
if (errorMessageKey != null) {
flash(Constants.WARNING, errorMessageKey);
FileUtil.rm_rf(new File(GitRepository.getGitDirectory(project)));
return badRequest(importing.render("title.newProject", filledNewProjectForm));
} else {
return redirect(routes.ProjectApp.project(project.owner, project.name));
}
}
| public static Result newProject() throws GitAPIException, IOException {
if( !AccessControl.isCreatable(UserApp.currentUser(), ResourceType.PROJECT) ){
return forbidden("'" + UserApp.currentUser().name + "' has no permission");
}
Form<Project> filledNewProjectForm = form(Project.class).bindFromRequest();
String gitUrl = filledNewProjectForm.data().get("url");
if(gitUrl == null || gitUrl.trim().isEmpty()) {
flash(Constants.WARNING, "project.import.error.empty.url");
return badRequest(importing.render("title.newProject", filledNewProjectForm));
}
if (Project.exists(UserApp.currentUser().loginId, filledNewProjectForm.field("name").value())) {
flash(Constants.WARNING, "project.name.duplicate");
filledNewProjectForm.reject("name");
return badRequest(importing.render("title.newProject", filledNewProjectForm));
}
if (filledNewProjectForm.hasErrors()) {
filledNewProjectForm.reject("name");
flash(Constants.WARNING, "project.name.alert");
return badRequest(importing.render("title.newProject", filledNewProjectForm));
}
Project project = filledNewProjectForm.get();
project.owner = UserApp.currentUser().loginId;
String errorMessageKey = null;
try {
GitRepository.cloneRepository(gitUrl, project);
Long projectId = Project.create(project);
ProjectUser.assignRole(UserApp.currentUser().id, projectId, RoleType.MANAGER);
} catch (InvalidRemoteException e) {
// It is not an url.
errorMessageKey = "project.import.error.wrong.url";
} catch (JGitInternalException e) {
// The url seems that does not locate a git repository.
errorMessageKey = "project.import.error.wrong.url";
} catch (TransportException e) {
errorMessageKey = "project.import.error.transport";
}
if (errorMessageKey != null) {
flash(Constants.WARNING, errorMessageKey);
FileUtil.rm_rf(new File(GitRepository.getGitDirectory(project)));
return badRequest(importing.render("title.newProject", filledNewProjectForm));
} else {
return redirect(routes.ProjectApp.project(project.owner, project.name));
}
}
|
diff --git a/org.maven.ide.eclipse/src/org/maven/ide/eclipse/ui/internal/preferences/RemoteArchetypeCatalogDialog.java b/org.maven.ide.eclipse/src/org/maven/ide/eclipse/ui/internal/preferences/RemoteArchetypeCatalogDialog.java
index 8c08ec82..e2b28a66 100644
--- a/org.maven.ide.eclipse/src/org/maven/ide/eclipse/ui/internal/preferences/RemoteArchetypeCatalogDialog.java
+++ b/org.maven.ide.eclipse/src/org/maven/ide/eclipse/ui/internal/preferences/RemoteArchetypeCatalogDialog.java
@@ -1,279 +1,279 @@
/*******************************************************************************
* Copyright (c) 2008 Sonatype, 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
*******************************************************************************/
package org.maven.ide.eclipse.ui.internal.preferences;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.dialogs.DialogSettings;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.apache.maven.archetype.catalog.Archetype;
import org.apache.maven.archetype.catalog.ArchetypeCatalog;
import org.maven.ide.eclipse.MavenPlugin;
import org.maven.ide.eclipse.archetype.ArchetypeCatalogFactory;
import org.maven.ide.eclipse.archetype.ArchetypeCatalogFactory.RemoteCatalogFactory;
/**
* Remote Archetype catalog dialog
*
* @author Eugene Kuleshov
*/
public class RemoteArchetypeCatalogDialog extends TitleAreaDialog {
/**
*
*/
private static final int VERIFY_ID = IDialogConstants.CLIENT_ID + 1;
private static final String DIALOG_SETTINGS = RemoteArchetypeCatalogDialog.class.getName();
private static final String KEY_LOCATIONS = "catalogUrl";
private static final int MAX_HISTORY = 15;
private String title;
private String message;
Combo catalogUrlCombo;
private Text catalogDescriptionText;
private IDialogSettings dialogSettings;
private ArchetypeCatalogFactory archetypeCatalogFactory;
Button verifyButton;
protected RemoteArchetypeCatalogDialog(Shell shell, ArchetypeCatalogFactory factory) {
super(shell);
this.archetypeCatalogFactory = factory;
this.title = "Remote Archetype Catalog";
this.message = "Specify catalog url and description";
setShellStyle(SWT.DIALOG_TRIM);
IDialogSettings pluginSettings = MavenPlugin.getDefault().getDialogSettings();
dialogSettings = pluginSettings.getSection(DIALOG_SETTINGS);
if(dialogSettings == null) {
dialogSettings = new DialogSettings(DIALOG_SETTINGS);
pluginSettings.addSection(dialogSettings);
}
}
protected Control createContents(Composite parent) {
Control control = super.createContents(parent);
setTitle(title);
setMessage(message);
return control;
}
protected Control createDialogArea(Composite parent) {
Composite composite1 = (Composite) super.createDialogArea(parent);
Composite composite = new Composite(composite1, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
GridLayout gridLayout = new GridLayout();
gridLayout.marginTop = 7;
gridLayout.marginWidth = 12;
gridLayout.numColumns = 2;
composite.setLayout(gridLayout);
Label catalogLocationLabel = new Label(composite, SWT.NONE);
catalogLocationLabel.setText("&Catalog File:");
catalogUrlCombo = new Combo(composite, SWT.NONE);
GridData gd_catalogLocationCombo = new GridData(SWT.FILL, SWT.CENTER, true, false);
gd_catalogLocationCombo.widthHint = 250;
catalogUrlCombo.setLayoutData(gd_catalogLocationCombo);
catalogUrlCombo.setItems(getSavedValues(KEY_LOCATIONS));
Label catalogDescriptionLabel = new Label(composite, SWT.NONE);
catalogDescriptionLabel.setText("Description:");
catalogDescriptionText = new Text(composite, SWT.BORDER);
catalogDescriptionText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
if(archetypeCatalogFactory!=null) {
catalogUrlCombo.setText(archetypeCatalogFactory.getId());
catalogDescriptionText.setText(archetypeCatalogFactory.getDescription());
}
ModifyListener modifyListener = new ModifyListener() {
public void modifyText(final ModifyEvent e) {
update();
}
};
catalogUrlCombo.addModifyListener(modifyListener);
catalogDescriptionText.addModifyListener(modifyListener);
return composite;
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.TrayDialog#createButtonBar(org.eclipse.swt.widgets.Composite)
*/
protected Control createButtonBar(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
composite.setLayout(layout);
composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
composite.setFont(parent.getFont());
// create help control if needed
if(isHelpAvailable()) {
createHelpControl(composite);
}
verifyButton = createButton(composite, VERIFY_ID, "&Verify...", false);
verifyButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
verifyButton.setEnabled(false);
String url = catalogUrlCombo.getText();
final RemoteCatalogFactory factory = new RemoteCatalogFactory(url, null, true);
- new Job("Downloading remore catalog") {
+ new Job("Downloading remote catalog") {
protected IStatus run(IProgressMonitor monitor) {
IStatus status = Status.OK_STATUS;
ArchetypeCatalog catalog = null;
try {
catalog = factory.getArchetypeCatalog();
} finally {
final IStatus s = status;
@SuppressWarnings("unchecked")
final List<Archetype> archetypes = catalog==null ? Collections.emptyList() : catalog.getArchetypes();
getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
verifyButton.setEnabled(true);
if(!s.isOK()) {
setErrorMessage("Unable to read remote catalog;\n"+s.getMessage());
getButton(IDialogConstants.OK_ID).setEnabled(false);
} else if(archetypes.size()==0) {
setMessage("Remote catalog is empty", IStatus.WARNING);
} else {
setMessage("Found " + archetypes.size() + " archetype(s)", IStatus.INFO);
}
}
});
}
return Status.OK_STATUS;
}
}.schedule();
}
});
Label filler= new Label(composite, SWT.NONE);
filler.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));
layout.numColumns++;
super.createButtonsForButtonBar(composite); // cancel button
return composite;
}
protected Button getButton(int id) {
return super.getButton(id);
}
private String[] getSavedValues(String key) {
String[] array = dialogSettings.getArray(key);
return array == null ? new String[0] : array;
}
protected void configureShell(Shell shell) {
super.configureShell(shell);
shell.setText(title);
}
public void create() {
super.create();
getButton(IDialogConstants.OK_ID).setEnabled(false);
getButton(VERIFY_ID).setEnabled(false);
}
protected void okPressed() {
String description = catalogDescriptionText.getText().trim();
String location = catalogUrlCombo.getText().trim();
archetypeCatalogFactory = new RemoteCatalogFactory(location, description, true);
saveValue(KEY_LOCATIONS, location);
super.okPressed();
}
public ArchetypeCatalogFactory getArchetypeCatalogFactory() {
return archetypeCatalogFactory;
}
private void saveValue(String key, String value) {
List<String> dirs = new ArrayList<String>();
dirs.addAll(Arrays.asList(getSavedValues(key)));
dirs.remove(value);
dirs.add(0, value);
if(dirs.size() > MAX_HISTORY) {
dirs = dirs.subList(0, MAX_HISTORY);
}
dialogSettings.put(key, dirs.toArray(new String[dirs.size()]));
}
void update() {
boolean isValid = isValid();
getButton(IDialogConstants.OK_ID).setEnabled(isValid);
getButton(VERIFY_ID).setEnabled(isValid);
}
private boolean isValid() {
setErrorMessage(null);
setMessage(null, IStatus.WARNING);
String url = catalogUrlCombo.getText().trim();
if(url.length()==0) {
setErrorMessage("Archetype catalog url is required");
verifyButton.setEnabled(false);
return false;
}
verifyButton.setEnabled(true);
return true;
}
}
| true | true | protected Control createButtonBar(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
composite.setLayout(layout);
composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
composite.setFont(parent.getFont());
// create help control if needed
if(isHelpAvailable()) {
createHelpControl(composite);
}
verifyButton = createButton(composite, VERIFY_ID, "&Verify...", false);
verifyButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
verifyButton.setEnabled(false);
String url = catalogUrlCombo.getText();
final RemoteCatalogFactory factory = new RemoteCatalogFactory(url, null, true);
new Job("Downloading remore catalog") {
protected IStatus run(IProgressMonitor monitor) {
IStatus status = Status.OK_STATUS;
ArchetypeCatalog catalog = null;
try {
catalog = factory.getArchetypeCatalog();
} finally {
final IStatus s = status;
@SuppressWarnings("unchecked")
final List<Archetype> archetypes = catalog==null ? Collections.emptyList() : catalog.getArchetypes();
getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
verifyButton.setEnabled(true);
if(!s.isOK()) {
setErrorMessage("Unable to read remote catalog;\n"+s.getMessage());
getButton(IDialogConstants.OK_ID).setEnabled(false);
} else if(archetypes.size()==0) {
setMessage("Remote catalog is empty", IStatus.WARNING);
} else {
setMessage("Found " + archetypes.size() + " archetype(s)", IStatus.INFO);
}
}
});
}
return Status.OK_STATUS;
}
}.schedule();
}
});
Label filler= new Label(composite, SWT.NONE);
filler.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));
layout.numColumns++;
super.createButtonsForButtonBar(composite); // cancel button
return composite;
}
| protected Control createButtonBar(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
composite.setLayout(layout);
composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
composite.setFont(parent.getFont());
// create help control if needed
if(isHelpAvailable()) {
createHelpControl(composite);
}
verifyButton = createButton(composite, VERIFY_ID, "&Verify...", false);
verifyButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
verifyButton.setEnabled(false);
String url = catalogUrlCombo.getText();
final RemoteCatalogFactory factory = new RemoteCatalogFactory(url, null, true);
new Job("Downloading remote catalog") {
protected IStatus run(IProgressMonitor monitor) {
IStatus status = Status.OK_STATUS;
ArchetypeCatalog catalog = null;
try {
catalog = factory.getArchetypeCatalog();
} finally {
final IStatus s = status;
@SuppressWarnings("unchecked")
final List<Archetype> archetypes = catalog==null ? Collections.emptyList() : catalog.getArchetypes();
getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
verifyButton.setEnabled(true);
if(!s.isOK()) {
setErrorMessage("Unable to read remote catalog;\n"+s.getMessage());
getButton(IDialogConstants.OK_ID).setEnabled(false);
} else if(archetypes.size()==0) {
setMessage("Remote catalog is empty", IStatus.WARNING);
} else {
setMessage("Found " + archetypes.size() + " archetype(s)", IStatus.INFO);
}
}
});
}
return Status.OK_STATUS;
}
}.schedule();
}
});
Label filler= new Label(composite, SWT.NONE);
filler.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));
layout.numColumns++;
super.createButtonsForButtonBar(composite); // cancel button
return composite;
}
|
diff --git a/src/java-server-framework/org/xins/server/StandardCallingConvention.java b/src/java-server-framework/org/xins/server/StandardCallingConvention.java
index 309844809..9d10b50e6 100644
--- a/src/java-server-framework/org/xins/server/StandardCallingConvention.java
+++ b/src/java-server-framework/org/xins/server/StandardCallingConvention.java
@@ -1,188 +1,191 @@
/*
* $Id$
*
* Copyright 2004 Wanadoo Nederland B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.server;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.Utils;
import org.xins.common.collections.ProtectedPropertyReader;
import org.xins.common.text.ParseException;
import org.xins.common.text.TextUtils;
import org.xins.common.xml.Element;
import org.xins.common.xml.ElementParser;
/**
* Standard calling convention.
*
* @version $Revision$ $Date$
* @author Anthony Goubard (<a href="mailto:[email protected]">[email protected]</a>)
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*/
final class StandardCallingConvention
extends CallingConvention {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* The fully-qualified name of this class.
*/
static final String CLASSNAME = StandardCallingConvention.class.getName();
/**
* The enconding for the data section
*/
static final String DATA_ENCODING = "UTF-8";
/**
* The response encoding format.
*/
static final String RESPONSE_ENCODING = "UTF-8";
/**
* The content type of the HTTP response.
*/
static final String RESPONSE_CONTENT_TYPE = "text/xml;charset=" + RESPONSE_ENCODING;
/**
* Secret key used when accessing <code>ProtectedPropertyReader</code>
* objects.
*/
private static final Object SECRET_KEY = new Object();
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Constructs a new <code>StandardCallingConvention</code> object.
*/
StandardCallingConvention() {
// empty
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
/**
* Converts an HTTP request to a XINS request (implementation method). This
* method should only be called from class {@link CallingConvention}. Only
* then it is guaranteed that the <code>httpRequest</code> argument is not
* <code>null</code>.
*
* @param httpRequest
* the HTTP request, will not be <code>null</code>.
*
* @return
* the XINS request object, never <code>null</code>.
*
* @throws InvalidRequestException
* if the request is considerd to be invalid.
*
* @throws FunctionNotSpecifiedException
* if the request does not indicate the name of the function to execute.
*/
protected FunctionRequest convertRequestImpl(HttpServletRequest httpRequest)
throws InvalidRequestException,
FunctionNotSpecifiedException {
final String THIS_METHOD = "convertRequestImpl("
+ HttpServletRequest.class.getName()
+ ')';
// XXX: What if invalid URL, e.g. query string ends with percent sign?
// Determine function name
String functionName = httpRequest.getParameter("_function");
+ if (TextUtils.isEmpty(functionName)) {
+ throw new FunctionNotSpecifiedException();
+ }
// Determine function parameters
ProtectedPropertyReader functionParams = new ProtectedPropertyReader(SECRET_KEY);
Enumeration params = httpRequest.getParameterNames();
while (params.hasMoreElements()) {
String name = (String) params.nextElement();
String value = httpRequest.getParameter(name);
functionParams.set(SECRET_KEY, name, value);
}
// Remove all invalid parameters
cleanUpParameters(functionParams, SECRET_KEY);
// Get data section
String dataSectionValue = httpRequest.getParameter("_data");
Element dataElement;
if (dataSectionValue != null && dataSectionValue.length() > 0) {
try {
ElementParser parser = new ElementParser();
dataElement = parser.parse(dataSectionValue.getBytes(DATA_ENCODING));
} catch (UnsupportedEncodingException ex) {
final String SUBJECT_CLASS = "java.lang.String";
final String SUBJECT_METHOD = "getBytes(java.lang.String)";
final String DETAIL = "Encoding \"" + DATA_ENCODING + "\" is not supported.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD,
SUBJECT_CLASS, SUBJECT_METHOD,
DETAIL, ex);
} catch (ParseException ex) {
throw new InvalidRequestException("Cannot parse the data section.", ex);
}
} else {
dataElement = null;
}
// Construct and return the request object
return new FunctionRequest(functionName, functionParams, dataElement);
}
/**
* Converts a XINS result to an HTTP response (implementation method).
*
* @param xinsResult
* the XINS result object that should be converted to an HTTP response,
* will not be <code>null</code>.
*
* @param httpResponse
* the HTTP response object to configure, will not be <code>null</code>.
*
* @throws IOException
* if calling any of the methods in <code>httpResponse</code> causes an
* I/O error.
*/
protected void convertResultImpl(FunctionResult xinsResult,
HttpServletResponse httpResponse)
throws IOException {
// Send the XML output to the stream and flush
PrintWriter out = httpResponse.getWriter();
// TODO: OutputStream out = httpResponse.getOutputStream();
httpResponse.setContentType(RESPONSE_CONTENT_TYPE);
httpResponse.setStatus(HttpServletResponse.SC_OK);
CallResultOutputter.output(out, RESPONSE_ENCODING, xinsResult, false);
out.close();
}
}
| true | true | protected FunctionRequest convertRequestImpl(HttpServletRequest httpRequest)
throws InvalidRequestException,
FunctionNotSpecifiedException {
final String THIS_METHOD = "convertRequestImpl("
+ HttpServletRequest.class.getName()
+ ')';
// XXX: What if invalid URL, e.g. query string ends with percent sign?
// Determine function name
String functionName = httpRequest.getParameter("_function");
// Determine function parameters
ProtectedPropertyReader functionParams = new ProtectedPropertyReader(SECRET_KEY);
Enumeration params = httpRequest.getParameterNames();
while (params.hasMoreElements()) {
String name = (String) params.nextElement();
String value = httpRequest.getParameter(name);
functionParams.set(SECRET_KEY, name, value);
}
// Remove all invalid parameters
cleanUpParameters(functionParams, SECRET_KEY);
// Get data section
String dataSectionValue = httpRequest.getParameter("_data");
Element dataElement;
if (dataSectionValue != null && dataSectionValue.length() > 0) {
try {
ElementParser parser = new ElementParser();
dataElement = parser.parse(dataSectionValue.getBytes(DATA_ENCODING));
} catch (UnsupportedEncodingException ex) {
final String SUBJECT_CLASS = "java.lang.String";
final String SUBJECT_METHOD = "getBytes(java.lang.String)";
final String DETAIL = "Encoding \"" + DATA_ENCODING + "\" is not supported.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD,
SUBJECT_CLASS, SUBJECT_METHOD,
DETAIL, ex);
} catch (ParseException ex) {
throw new InvalidRequestException("Cannot parse the data section.", ex);
}
} else {
dataElement = null;
}
// Construct and return the request object
return new FunctionRequest(functionName, functionParams, dataElement);
}
| protected FunctionRequest convertRequestImpl(HttpServletRequest httpRequest)
throws InvalidRequestException,
FunctionNotSpecifiedException {
final String THIS_METHOD = "convertRequestImpl("
+ HttpServletRequest.class.getName()
+ ')';
// XXX: What if invalid URL, e.g. query string ends with percent sign?
// Determine function name
String functionName = httpRequest.getParameter("_function");
if (TextUtils.isEmpty(functionName)) {
throw new FunctionNotSpecifiedException();
}
// Determine function parameters
ProtectedPropertyReader functionParams = new ProtectedPropertyReader(SECRET_KEY);
Enumeration params = httpRequest.getParameterNames();
while (params.hasMoreElements()) {
String name = (String) params.nextElement();
String value = httpRequest.getParameter(name);
functionParams.set(SECRET_KEY, name, value);
}
// Remove all invalid parameters
cleanUpParameters(functionParams, SECRET_KEY);
// Get data section
String dataSectionValue = httpRequest.getParameter("_data");
Element dataElement;
if (dataSectionValue != null && dataSectionValue.length() > 0) {
try {
ElementParser parser = new ElementParser();
dataElement = parser.parse(dataSectionValue.getBytes(DATA_ENCODING));
} catch (UnsupportedEncodingException ex) {
final String SUBJECT_CLASS = "java.lang.String";
final String SUBJECT_METHOD = "getBytes(java.lang.String)";
final String DETAIL = "Encoding \"" + DATA_ENCODING + "\" is not supported.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD,
SUBJECT_CLASS, SUBJECT_METHOD,
DETAIL, ex);
} catch (ParseException ex) {
throw new InvalidRequestException("Cannot parse the data section.", ex);
}
} else {
dataElement = null;
}
// Construct and return the request object
return new FunctionRequest(functionName, functionParams, dataElement);
}
|
diff --git a/src/main/java/com/monits/commons/utils/HashingUtils.java b/src/main/java/com/monits/commons/utils/HashingUtils.java
index febac1c..81a2544 100644
--- a/src/main/java/com/monits/commons/utils/HashingUtils.java
+++ b/src/main/java/com/monits/commons/utils/HashingUtils.java
@@ -1,113 +1,112 @@
/*
Copyright 2011 Monits
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.monits.commons.utils;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.google.common.base.Charsets;
import com.monits.commons.model.HashingAlgorithm;
/**
* Hashing utilities.
*
* @author Franco Zeoli <[email protected]>
* @copyright 2011 Monits
* @license Apache 2.0 License
* @version Release: 1.0.0
* @link http://www.monits.com/
* @since 1.0.0
*/
public class HashingUtils {
/**
* Utility classes should not have a public or default constructor.
*/
private HashingUtils() {
throw new UnsupportedOperationException();
}
/**
* Retrieves the file hashed by the given hashing algorithm.
* @param filename The path to the file to hash.
* @param algorithm Which hashing algorithm to use.
* @return The resulting hash
* @throws FileNotFoundException
*/
public static String getFileHash(String filename, HashingAlgorithm algorithm) throws FileNotFoundException {
return getHash(new FileInputStream(filename), algorithm);
}
/**
* Retrieves the given input string hashed with the given hashing algorithm.
* @param input The string to hash.
* @param algorithm Which hashing algorithm to use.
* @return The resulting hash
*/
public static String getHash(String input, HashingAlgorithm algorithm) {
return getHash(new ByteArrayInputStream(input.getBytes(Charsets.UTF_8)), algorithm);
}
/**
* Retrieves the given input string hashed with the given hashing algorithm.
* @param input The source from which to read the input to hash.
* @param algorithm Which hashing algorithm to use.
* @return The resulting hash
*/
public static String getHash(InputStream input, HashingAlgorithm algorithm) {
byte[] buffer = new byte[1024];
try {
MessageDigest algo = MessageDigest.getInstance(algorithm.getName());
int readBytes;
- do {
- readBytes = input.read(buffer);
+ while ( (readBytes = input.read(buffer)) != -1) {
algo.update(buffer, 0, readBytes);
- } while (readBytes == buffer.length);
+ };
byte messageDigest[] = algo.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String token = Integer.toHexString(0xFF & messageDigest[i]);
// Make sure each is exactly 2 chars long
if (token.length() < 2) {
hexString.append("0");
}
hexString.append(token);
}
return hexString.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
| false | true | public static String getHash(InputStream input, HashingAlgorithm algorithm) {
byte[] buffer = new byte[1024];
try {
MessageDigest algo = MessageDigest.getInstance(algorithm.getName());
int readBytes;
do {
readBytes = input.read(buffer);
algo.update(buffer, 0, readBytes);
} while (readBytes == buffer.length);
byte messageDigest[] = algo.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String token = Integer.toHexString(0xFF & messageDigest[i]);
// Make sure each is exactly 2 chars long
if (token.length() < 2) {
hexString.append("0");
}
hexString.append(token);
}
return hexString.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
| public static String getHash(InputStream input, HashingAlgorithm algorithm) {
byte[] buffer = new byte[1024];
try {
MessageDigest algo = MessageDigest.getInstance(algorithm.getName());
int readBytes;
while ( (readBytes = input.read(buffer)) != -1) {
algo.update(buffer, 0, readBytes);
};
byte messageDigest[] = algo.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String token = Integer.toHexString(0xFF & messageDigest[i]);
// Make sure each is exactly 2 chars long
if (token.length() < 2) {
hexString.append("0");
}
hexString.append(token);
}
return hexString.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
|
diff --git a/src/com/android/settings/AccountSyncSettings.java b/src/com/android/settings/AccountSyncSettings.java
index 7c5dbf6..06f342d 100644
--- a/src/com/android/settings/AccountSyncSettings.java
+++ b/src/com/android/settings/AccountSyncSettings.java
@@ -1,367 +1,368 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings;
import com.android.providers.subscribedfeeds.R;
import com.google.android.collect.Maps;
import android.accounts.AccountManager;
import android.accounts.Account;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActiveSyncInfo;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.SyncStatusInfo;
import android.content.SyncAdapterType;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateFormat;
import android.preference.Preference;
import android.preference.PreferenceScreen;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
public class AccountSyncSettings extends AccountPreferenceBase implements OnClickListener {
private static final String TAG = "SyncSettings";
private static final String CHANGE_PASSWORD_KEY = "changePassword";
private static final int MENU_SYNC_NOW_ID = Menu.FIRST;
private static final int MENU_SYNC_CANCEL_ID = Menu.FIRST + 1;
private static final int REALLY_REMOVE_DIALOG = 100;
private static final int FAILED_REMOVAL_DIALOG = 101;
private TextView mUserId;
private TextView mProviderId;
private ImageView mProviderIcon;
private TextView mErrorInfoView;
protected View mRemoveAccountArea;
private java.text.DateFormat mDateFormat;
private java.text.DateFormat mTimeFormat;
private Preference mAuthenticatorPreferences;
private Account mAccount;
private Button mRemoveAccountButton;
public void onClick(View v) {
if (v == mRemoveAccountButton) {
showDialog(REALLY_REMOVE_DIALOG);
}
}
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
if (id == REALLY_REMOVE_DIALOG) {
dialog = new AlertDialog.Builder(this)
.setTitle(R.string.really_remove_account_title)
.setMessage(R.string.really_remove_account_message)
.setPositiveButton(R.string.remove_account_label,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
AccountManager.get(AccountSyncSettings.this).removeAccount(mAccount,
new AccountManagerCallback<Boolean>() {
public void run(AccountManagerFuture<Boolean> future) {
boolean failed = true;
try {
if (future.getResult() == true) {
failed = false;
}
} catch (OperationCanceledException e) {
// ignore it
} catch (IOException e) {
// TODO: retry?
} catch (AuthenticatorException e) {
// TODO: retry?
}
if (failed) {
showDialog(FAILED_REMOVAL_DIALOG);
} else {
finish();
}
}
}, null);
}
})
.create();
} else if (id == FAILED_REMOVAL_DIALOG) {
dialog = new AlertDialog.Builder(this)
.setTitle(R.string.really_remove_account_title)
.setMessage(R.string.remove_account_failed)
.create();
}
return dialog;
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.account_sync_screen);
addPreferencesFromResource(R.xml.account_sync_settings);
addAuthenticatorPreferences();
mErrorInfoView = (TextView) findViewById(R.id.sync_settings_error_info);
mErrorInfoView.setVisibility(View.GONE);
mErrorInfoView.setCompoundDrawablesWithIntrinsicBounds(
getResources().getDrawable(R.drawable.ic_list_syncerror), null, null, null);
mUserId = (TextView) findViewById(R.id.user_id);
mProviderId = (TextView) findViewById(R.id.provider_id);
mProviderIcon = (ImageView) findViewById(R.id.provider_icon);
mRemoveAccountArea = (View) findViewById(R.id.remove_account_area);
mRemoveAccountButton = (Button) findViewById(R.id.remove_account_button);
mRemoveAccountButton.setOnClickListener(this);
mDateFormat = DateFormat.getDateFormat(this);
mTimeFormat = DateFormat.getTimeFormat(this);
mAccount = (Account) getIntent().getParcelableExtra("account");
if (mAccount != null) {
Log.v(TAG, "Got account: " + mAccount);
mUserId.setText(mAccount.name);
mProviderId.setText(mAccount.type);
}
AccountManager.get(this).addOnAccountsUpdatedListener(this, null, true);
updateAuthDescriptions();
}
/*
* Get settings.xml from authenticator for this account.
* TODO: replace with authenticator-specific settings here when AuthenticatorDesc supports it.
*/
private void addAuthenticatorPreferences() {
mAuthenticatorPreferences = findPreference(CHANGE_PASSWORD_KEY);
}
ArrayList<SyncStateCheckBoxPreference> mCheckBoxes =
new ArrayList<SyncStateCheckBoxPreference>();
private void addSyncStateCheckBox(Account account, String authority) {
SyncStateCheckBoxPreference item =
new SyncStateCheckBoxPreference(this, account, authority);
item.setPersistent(false);
//final String name = authority + ", " + account.name + ", " + account.type;
final String name = authority;
item.setTitle(name);
item.setKey(name);
getPreferenceScreen().addPreference(item);
mCheckBoxes.add(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_SYNC_NOW_ID, 0, getString(R.string.sync_menu_sync_now))
.setIcon(com.android.internal.R.drawable.ic_menu_refresh);
menu.add(0, MENU_SYNC_CANCEL_ID, 0, getString(R.string.sync_menu_sync_cancel))
.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
boolean syncActive = ContentResolver.getActiveSync() != null;
menu.findItem(MENU_SYNC_NOW_ID).setVisible(!syncActive);
menu.findItem(MENU_SYNC_CANCEL_ID).setVisible(syncActive);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_SYNC_NOW_ID:
startSyncForEnabledProviders();
return true;
case MENU_SYNC_CANCEL_ID:
cancelSyncForEnabledProviders();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferences, Preference preference) {
if (preference instanceof SyncStateCheckBoxPreference) {
SyncStateCheckBoxPreference syncPref = (SyncStateCheckBoxPreference) preference;
String authority = syncPref.getAuthority();
Account account = syncPref.getAccount();
if (syncPref.isOneTimeSyncMode()) {
requestOrCancelSync(account, authority, true);
} else {
boolean syncOn = syncPref.isChecked();
boolean oldSyncState = ContentResolver.getSyncAutomatically(account, authority);
if (syncOn != oldSyncState) {
ContentResolver.setSyncAutomatically(account, authority, syncOn);
requestOrCancelSync(account, authority, syncOn);
}
}
} else {
return false;
}
return true;
}
private void startSyncForEnabledProviders() {
requestOrCancelSyncForEnabledProviders(true /* start them */);
}
private void cancelSyncForEnabledProviders() {
requestOrCancelSyncForEnabledProviders(false /* cancel them */);
}
private void requestOrCancelSyncForEnabledProviders(boolean startSync) {
int count = getPreferenceScreen().getPreferenceCount();
for (int i = 0; i < count; i++) {
Preference pref = getPreferenceScreen().getPreference(i);
if (! (pref instanceof SyncStateCheckBoxPreference)) {
continue;
}
SyncStateCheckBoxPreference syncPref = (SyncStateCheckBoxPreference) pref;
if (!syncPref.isChecked()) {
continue;
}
requestOrCancelSync(syncPref.getAccount(), syncPref.getAuthority(), startSync);
}
}
private void requestOrCancelSync(Account account, String authority, boolean flag) {
if (flag) {
Bundle extras = new Bundle();
extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
ContentResolver.requestSync(account, authority, extras);
} else {
ContentResolver.cancelSync(account, authority);
}
}
@Override
protected void onSyncStateUpdated() {
// iterate over all the preferences, setting the state properly for each
Date date = new Date();
ActiveSyncInfo activeSyncValues = ContentResolver.getActiveSync();
boolean syncIsFailing = false;
for (int i = 0, count = getPreferenceScreen().getPreferenceCount(); i < count; i++) {
Preference pref = getPreferenceScreen().getPreference(i);
if (! (pref instanceof SyncStateCheckBoxPreference)) {
continue;
}
SyncStateCheckBoxPreference syncPref = (SyncStateCheckBoxPreference) pref;
String authority = syncPref.getAuthority();
Account account = syncPref.getAccount();
SyncStatusInfo status = ContentResolver.getSyncStatus(account, authority);
boolean syncEnabled = ContentResolver.getSyncAutomatically(account, authority);
boolean authorityIsPending = ContentResolver.isSyncPending(account, authority);
boolean activelySyncing = activeSyncValues != null
- && activeSyncValues.account.equals(account);
+ && activeSyncValues.account.equals(account)
+ && activeSyncValues.authority.equals(authority);
boolean lastSyncFailed = status != null
&& status.lastFailureTime != 0
&& status.getLastFailureMesgAsInt(0)
!= ContentResolver.SYNC_ERROR_SYNC_ALREADY_IN_PROGRESS;
if (!syncEnabled) lastSyncFailed = false;
if (lastSyncFailed && !activelySyncing && !authorityIsPending) {
syncIsFailing = true;
}
final long successEndTime = (status == null) ? 0 : status.lastSuccessTime;
if (successEndTime != 0) {
date.setTime(successEndTime);
final String timeString = mDateFormat.format(date) + " "
+ mTimeFormat.format(date);
syncPref.setSummary(timeString);
} else {
syncPref.setSummary("");
}
syncPref.setActive(activelySyncing);
syncPref.setPending(authorityIsPending);
syncPref.setFailed(lastSyncFailed);
final boolean masterSyncAutomatically = ContentResolver.getMasterSyncAutomatically();
syncPref.setOneTimeSyncMode(!masterSyncAutomatically);
syncPref.setChecked(syncEnabled);
}
mErrorInfoView.setVisibility(syncIsFailing ? View.VISIBLE : View.GONE);
}
@Override
public void onAccountsUpdated(Account[] accounts) {
super.onAccountsUpdated(accounts);
SyncAdapterType[] syncAdapters = ContentResolver.getSyncAdapterTypes();
HashMap<String, ArrayList<String>> accountTypeToAuthorities = Maps.newHashMap();
for (int i = 0, n = syncAdapters.length; i < n; i++) {
final SyncAdapterType sa = syncAdapters[i];
if (sa.userVisible) {
ArrayList<String> authorities = accountTypeToAuthorities.get(sa.accountType);
if (authorities == null) {
authorities = new ArrayList<String>();
accountTypeToAuthorities.put(sa.accountType, authorities);
}
Log.d(TAG, "added authority " + sa.authority + " to accountType " + sa.accountType);
authorities.add(sa.authority);
}
}
for (int i = 0, n = mCheckBoxes.size(); i < n; i++) {
getPreferenceScreen().removePreference(mCheckBoxes.get(i));
}
mCheckBoxes.clear();
for (int i = 0, n = accounts.length; i < n; i++) {
final Account account = accounts[i];
Log.d(TAG, "looking for sync adapters that match account " + account);
final ArrayList<String> authorities = accountTypeToAuthorities.get(account.type);
if (authorities != null && (mAccount == null || mAccount.equals(account))) {
for (int j = 0, m = authorities.size(); j < m; j++) {
final String authority = authorities.get(j);
Log.d(TAG, " found authority " + authority);
if (ContentResolver.getIsSyncable(account, authority) > 0) {
addSyncStateCheckBox(account, authority);
}
}
}
}
onSyncStateUpdated();
}
/**
* Updates the titlebar with an icon for the provider type.
*/
@Override
protected void onAuthDescriptionsUpdated() {
super.onAuthDescriptionsUpdated();
mProviderIcon.setImageDrawable(getDrawableForType(mAccount.type));
mProviderId.setText(getLabelForType(mAccount.type));
// TODO: Enable Remove accounts when we can tell the account can be removed
}
}
| true | true | protected void onSyncStateUpdated() {
// iterate over all the preferences, setting the state properly for each
Date date = new Date();
ActiveSyncInfo activeSyncValues = ContentResolver.getActiveSync();
boolean syncIsFailing = false;
for (int i = 0, count = getPreferenceScreen().getPreferenceCount(); i < count; i++) {
Preference pref = getPreferenceScreen().getPreference(i);
if (! (pref instanceof SyncStateCheckBoxPreference)) {
continue;
}
SyncStateCheckBoxPreference syncPref = (SyncStateCheckBoxPreference) pref;
String authority = syncPref.getAuthority();
Account account = syncPref.getAccount();
SyncStatusInfo status = ContentResolver.getSyncStatus(account, authority);
boolean syncEnabled = ContentResolver.getSyncAutomatically(account, authority);
boolean authorityIsPending = ContentResolver.isSyncPending(account, authority);
boolean activelySyncing = activeSyncValues != null
&& activeSyncValues.account.equals(account);
boolean lastSyncFailed = status != null
&& status.lastFailureTime != 0
&& status.getLastFailureMesgAsInt(0)
!= ContentResolver.SYNC_ERROR_SYNC_ALREADY_IN_PROGRESS;
if (!syncEnabled) lastSyncFailed = false;
if (lastSyncFailed && !activelySyncing && !authorityIsPending) {
syncIsFailing = true;
}
final long successEndTime = (status == null) ? 0 : status.lastSuccessTime;
if (successEndTime != 0) {
date.setTime(successEndTime);
final String timeString = mDateFormat.format(date) + " "
+ mTimeFormat.format(date);
syncPref.setSummary(timeString);
} else {
syncPref.setSummary("");
}
syncPref.setActive(activelySyncing);
syncPref.setPending(authorityIsPending);
syncPref.setFailed(lastSyncFailed);
final boolean masterSyncAutomatically = ContentResolver.getMasterSyncAutomatically();
syncPref.setOneTimeSyncMode(!masterSyncAutomatically);
syncPref.setChecked(syncEnabled);
}
mErrorInfoView.setVisibility(syncIsFailing ? View.VISIBLE : View.GONE);
}
| protected void onSyncStateUpdated() {
// iterate over all the preferences, setting the state properly for each
Date date = new Date();
ActiveSyncInfo activeSyncValues = ContentResolver.getActiveSync();
boolean syncIsFailing = false;
for (int i = 0, count = getPreferenceScreen().getPreferenceCount(); i < count; i++) {
Preference pref = getPreferenceScreen().getPreference(i);
if (! (pref instanceof SyncStateCheckBoxPreference)) {
continue;
}
SyncStateCheckBoxPreference syncPref = (SyncStateCheckBoxPreference) pref;
String authority = syncPref.getAuthority();
Account account = syncPref.getAccount();
SyncStatusInfo status = ContentResolver.getSyncStatus(account, authority);
boolean syncEnabled = ContentResolver.getSyncAutomatically(account, authority);
boolean authorityIsPending = ContentResolver.isSyncPending(account, authority);
boolean activelySyncing = activeSyncValues != null
&& activeSyncValues.account.equals(account)
&& activeSyncValues.authority.equals(authority);
boolean lastSyncFailed = status != null
&& status.lastFailureTime != 0
&& status.getLastFailureMesgAsInt(0)
!= ContentResolver.SYNC_ERROR_SYNC_ALREADY_IN_PROGRESS;
if (!syncEnabled) lastSyncFailed = false;
if (lastSyncFailed && !activelySyncing && !authorityIsPending) {
syncIsFailing = true;
}
final long successEndTime = (status == null) ? 0 : status.lastSuccessTime;
if (successEndTime != 0) {
date.setTime(successEndTime);
final String timeString = mDateFormat.format(date) + " "
+ mTimeFormat.format(date);
syncPref.setSummary(timeString);
} else {
syncPref.setSummary("");
}
syncPref.setActive(activelySyncing);
syncPref.setPending(authorityIsPending);
syncPref.setFailed(lastSyncFailed);
final boolean masterSyncAutomatically = ContentResolver.getMasterSyncAutomatically();
syncPref.setOneTimeSyncMode(!masterSyncAutomatically);
syncPref.setChecked(syncEnabled);
}
mErrorInfoView.setVisibility(syncIsFailing ? View.VISIBLE : View.GONE);
}
|
diff --git a/src/client/src/org/obudget/client/Application.java b/src/client/src/org/obudget/client/Application.java
index 881ab93..42f7806 100644
--- a/src/client/src/org/obudget/client/Application.java
+++ b/src/client/src/org/obudget/client/Application.java
@@ -1,468 +1,469 @@
package org.obudget.client;
import java.util.List;
import java.util.Map;
import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.DecoratedPopupPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;
class Application implements ValueChangeHandler<String> {
private BudgetLines mChildrenBudgetLines = new BudgetLines();
private BudgetLines mHistoricBudgetLines = new BudgetLines();
private ResultGrid mResultsGrid = null;
private PieCharter mPieCharter = null;
private HTML mBreadcrumbs = null;
private TimeLineCharter mTimeLineCharter = null;
private String mCode = null;
private Integer mYear = null;
private ListBox mYearSelection = null;
private SuggestBox mSearchBox = null;
private Label mSummary1 = null;
private Label mSummary2 = null;
private Label mSummary2_1 = null;
private HTML mSummary3 = null;
private HTML mSummary3_1 = null;
private BudgetNews mBudgetNews = null;
private HTML mCheatSheet = null;
static private Application mInstance = null;
private static boolean mEmbedded = false;
static public Application getInstance() {
if ( mInstance == null ) {
mInstance = new Application();
mInstance.init();
}
return mInstance;
}
public void init() {
TotalBudget.getInstance();
Integer height = null;
Integer width = null;
Map<String,List<String>> parameters = Window.Location.getParameterMap();
if ( parameters.containsKey("w") &&
parameters.containsKey("h") ) {
height= Integer.parseInt( parameters.get("h").get(0) );
width = Integer.parseInt( parameters.get("w").get(0) );
}
mResultsGrid = new ResultGrid();
mResultsGrid.setWidth("100%");
Integer pieWidth = width == null ? 485 : width;
Integer pieHeight = height == null ? 400 : height;
mPieCharter = new PieCharter(this, mEmbedded, pieWidth, pieHeight);
mPieCharter.setWidth(pieWidth+"px");
mPieCharter.setHeight(pieHeight+"px");
Integer timeWidth = width == null ? 686 : width;
Integer timeHeight = height == null ? 400 : height;
mTimeLineCharter = new TimeLineCharter(this, mEmbedded, timeWidth, timeHeight);
mTimeLineCharter.setWidth(timeWidth+"px");
mTimeLineCharter.setHeight(timeHeight+"px");
mBreadcrumbs = new HTML("");
mBreadcrumbs.setHeight("20px");
mBreadcrumbs.setWidth("100%");
mYearSelection = new ListBox();
mYearSelection.addChangeHandler( new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
Integer index = mYearSelection.getSelectedIndex();
String yearStr = mYearSelection.getItemText(index);
Integer year;
try {
year = Integer.parseInt(yearStr);
} catch (Exception e) {
yearStr = yearStr.split(" ")[0];
year = Integer.parseInt(yearStr);
}
selectYear(year);
}
});
mSearchBox = new SuggestBox(new BudgetSuggestionOracle());
mSearchBox.setWidth("300px");
mSearchBox.addSelectionHandler( new SelectionHandler<Suggestion>() {
@Override
public void onSelection(SelectionEvent<Suggestion> event) {
final BudgetSuggestion bs = (BudgetSuggestion) event.getSelectedItem();
BudgetAPICaller api = new BudgetAPICaller();
api.setCode(bs.getCode());
api.setParameter("depth", "0");
api.setParameter("text", bs.getTitle());
api.go( new BudgetAPICallback() {
@Override
public void onSuccess(JSONArray data) {
if ( data.size() > 0 ) {
Integer year = (int) data.get(0).isObject().get("year").isNumber().doubleValue();
newCodeAndYear(bs.getCode(),year);
}
}
});
}
});
mSummary1 = new Label();
mSummary2 = new Label();
mSummary2_1 = new Label();
mSummary3 = new HTML();
mSummary3_1 = new HTML();
mBudgetNews = new BudgetNews();
mCheatSheet = new HTML("(הסברים)");
final DecoratedPopupPanel simplePopup = new DecoratedPopupPanel(true);
simplePopup.setWidth("400px");
HTML simplePopupContents = new HTML( "<h4>מונחון מקוצר</h4>"+
"<lu>"+
"<li><b>נטו</b>: <u>תקציב הוצאה נטו</u> – הסכום המותר להוצאה בשנה כלשהי כפי שמפורט בחוק התקציב. תקציב זה מכונה גם \"תקציב המזומנים\".</li>"+
"<li><b>ברוטו</b>: <u>תקציב ההוצאה נטו</u> בתוספת <u>תקציב ההוצאה המותנית בהכנסה</u> – תקציב נוסף המותר בהוצאה, ובלבד שיתקבלו תקבולים למימון ההוצאה מגורמים חוץ-ממשלתיים. תקבולים אלו אינם כוללים אגרה המשולמת לאוצר המדינה שהוטלה על-פי חיקוק שנחקק אחרי תחילת שנת הכספים 1992, ואינה כוללת הכנסה שמקורה במלווה (חוץ מתקציבי פיתוח וחשבון הון).</li>"+
"<li><b>הקצאה</b>: <u>תקציב מקורי</u> – התקציב שאושר בכנסת במסגרת חוק התקציב. ייתכנו הבדלים בין הצעת התקציב לבין התקציב שיאושר בכנסת בסופו של דבר.</li>"+
"<li><b>הקצאה מעודכנת</b>: <u>תקציב על שינוייו</u> – תקציב המדינה עשוי להשתנות במהלך השנה. שינויים אלו כוללים תוספות, הפחתות והעברות תקציביות בין סעיפי תקציב (באישור ועדת הכספים של הכנסת). נוסף על כך, פעמים רבות מועברים עודפים מחויבים משנה קודמת הנכללים בתקציב זה. רוב השינויים בתקציב דורשים את אישורה של ועדת הכספים של הכנסת. התקציב בסוף השנה הכולל את השינויים שנעשו בו במהלך השנה נקרא התקציב על שינוייו או התקציב המאושר.</li>"+
"<li><b>שימוש</b>: <u>ביצוע</u> – התקציב שכבר נוצל ושולם בפועל על-ידי החשב.</li>"+
"<li><b>ערך ריאלי ונומינלי</b>: ראו הסבר ב<a href='http://he.wikipedia.org/wiki/%D7%A2%D7%A8%D7%9A_%D7%A8%D7%99%D7%90%D7%9C%D7%99_%D7%95%D7%A2%D7%A8%D7%9A_%D7%A0%D7%95%D7%9E%D7%99%D7%A0%D7%9C%D7%99' target ='_blank'>ויקיפדיה</a>.</li>"+
"<li><b>ערך יחסי</b>: האחוז היחסי של סעיף זה מכלל תקציב המדינה</li>"+
"</lu>"+
"<br/>"+
"<i>לחץ מחוץ לחלונית זו לסגירתה</i>"+
"<br/>"+
"מקור: <a href='http://www.knesset.gov.il/mmm/data/docs/m02217.doc' target='_blank'>מסמך Word ממחלקת המחקר של הכנסת</a>");
simplePopupContents.setStyleName("obudget-cheatsheet-popup");
simplePopup.setWidget( simplePopupContents );
mCheatSheet.addClickHandler( new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
Widget source = (Widget) event.getSource();
int left = source.getAbsoluteLeft() + 10;
int top = source.getAbsoluteTop() + 10;
simplePopup.setPopupPosition(left, top);
simplePopup.show();
}
});
History.addValueChangeHandler( this );
}
public ResultGrid getResultsGrid() {
return mResultsGrid;
}
public PieCharter getPieCharter() {
return mPieCharter;
}
public void selectYear( Integer year ) {
if ( mCode != null ) {
selectBudgetCode(mCode, year);
}
}
public void selectBudgetCode( String code, Integer year ) {
mCode = code;
mYear = year;
BudgetAPICaller generalInfo = new BudgetAPICaller();
// Load single record
generalInfo.setCode(code);
generalInfo.setParameter("year", year.toString() );
generalInfo.setParameter("depth", "0");
generalInfo.go( new BudgetAPICallback() {
@Override
public void onSuccess(JSONArray data) {
if ( data.size() < 1 ) {
return;
}
JSONObject firstResult = data.get(0).isObject();
String title = firstResult.get("title").isString().stringValue();
String code = firstResult.get("budget_id").isString().stringValue();
mSearchBox.setValue(title);
//mYearSelection.setSelectedIndex( mYear - 1992 );
mBudgetNews.update("\""+title+"\"");
Window.setTitle("תקציב המדינה - "+title+" ("+mYear+")");
mSummary1.setText( title );
final Integer revisedSum;
final String revisedSumType;
if ( (firstResult.get("gross_amount_revised") != null) &&
(firstResult.get("gross_amount_revised").isNumber() != null) ) {
revisedSumType = "gross_amount_revised";
} else if ( (firstResult.get("gross_amount_allocated") != null) &&
(firstResult.get("gross_amount_allocated").isNumber() != null) ) {
revisedSumType = "gross_amount_allocated";
} else if ( (firstResult.get("net_amount_revised") != null) &&
(firstResult.get("net_amount_revised").isNumber() != null) ) {
revisedSumType = "net_amount_revised";
} else if ( (firstResult.get("net_amount_allocated") != null) &&
(firstResult.get("net_amount_allocated").isNumber() != null) ) {
revisedSumType = "net_amount_allocated";
} else {
revisedSumType = null;
}
if ( revisedSumType != null ) {
if ( ( firstResult.get(revisedSumType) != null ) &&
firstResult.get(revisedSumType).isNumber() != null ) {
revisedSum = (int) firstResult.get(revisedSumType).isNumber().doubleValue();
if ( revisedSum != 0 ) {
mSummary2.setText( NumberFormat.getDecimalFormat().format(revisedSum)+",000" );
} else {
mSummary2.setText( "0" );
}
mSummary2_1.setText( (revisedSumType.startsWith("net") ? " (נטו)" : "") );
} else {
revisedSum = null;
}
} else {
revisedSum = null;
mSummary2.setText("");
mSummary2_1.setText("");
}
mSummary3.setHTML("");
mSummary3_1.setHTML("");
if ( firstResult.get("parent") != null ) {
JSONArray parents = firstResult.get("parent").isArray();
if ( parents.size() > 0 ) {
final String parentCode = parents.get(0).isObject().get("budget_id").isString().stringValue();
final String parentTitle = parents.get(0).isObject().get("title").isString().stringValue();
BudgetAPICaller percent = new BudgetAPICaller();
percent.setCode(parentCode);
percent.setParameter("year", mYear.toString());
percent.setParameter("depth", "0");
percent.go( new BudgetAPICallback() {
@Override
public void onSuccess(JSONArray data) {
if ( (data.get(0).isObject().get(revisedSumType) != null) &&
- (data.get(0).isObject().get(revisedSumType).isNumber() != null) ) {
+ (data.get(0).isObject().get(revisedSumType).isNumber() != null) &&
+ (data.get(0).isObject().get(revisedSumType).isNumber().doubleValue() > 0) ) {
double percent = revisedSum / data.get(0).isObject().get(revisedSumType).isNumber().doubleValue();
mSummary3.setHTML( "שהם " + NumberFormat.getPercentFormat().format(percent) );
mSummary3_1.setHTML( "מתקציב <a href='#"+hashForCode(parentCode)+"'>"+parentTitle+"</a>");
}
}
});
}
String breadcrumbs = "";
for ( int i = 0 ; i < parents.size() ; i++ ) {
String ptitle = parents.get(i).isObject().get("title").isString().stringValue();
String pcode = parents.get(i).isObject().get("budget_id").isString().stringValue();
breadcrumbs = "<a href='#"+hashForCode(pcode)+"'>"+ptitle+"</a> ("+pcode+") "+" > " + breadcrumbs;
}
breadcrumbs += "<a href='#"+hashForCode(code)+"'>"+title+"</a> ("+code+")";
mBreadcrumbs.setHTML(breadcrumbs);
}
}
});
// Load all children
BudgetAPICaller childrenLines = new BudgetAPICaller();
childrenLines.setCode(code);
childrenLines.setParameter("year", year.toString());
childrenLines.setParameter("depth", "1");
childrenLines.go( new BudgetAPICallback() {
@Override
public void onSuccess(JSONArray data) {
mChildrenBudgetLines.parseJson(data);
mResultsGrid.handleData(mChildrenBudgetLines);
mPieCharter.handleData(mChildrenBudgetLines);
}
});
// Load same record, over the years
BudgetAPICaller historicLines = new BudgetAPICaller();
historicLines.setCode(code);
historicLines.setParameter("depth", "0");
historicLines.go( new BudgetAPICallback() {
@Override
public void onSuccess(JSONArray data) {
mHistoricBudgetLines.parseJson(data);
String lastLine = null;
boolean allEqual = true;
for ( BudgetLine bl : mHistoricBudgetLines ) {
if ( lastLine != null ) {
allEqual = allEqual && lastLine.equals(bl.getTitle());
}
lastLine = bl.getTitle();
}
mYearSelection.clear();
Integer selectedIndex = 0;
for ( BudgetLine bl : mHistoricBudgetLines ) {
String year = bl.getYear().toString();
if (year.equals( mYear.toString() )) {
mYearSelection.addItem( year );
selectedIndex = mYearSelection.getItemCount() - 1;
} else {
if ( allEqual ) {
mYearSelection.addItem( year );
} else {
mYearSelection.addItem( year + " - " + bl.getTitle() );
}
}
}
mYearSelection.setSelectedIndex( selectedIndex );
if ( !allEqual ) {
mYearSelection.setWidth("55px");
}
mTimeLineCharter.handleData(mHistoricBudgetLines);
}
});
}
public TimeLineCharter getTimeLineCharter() {
return mTimeLineCharter;
}
public String hash( String code, Integer year ) {
return code+","+year+","+mTimeLineCharter.getState()+","+mPieCharter.getState()+","+mResultsGrid.getState();
}
public String hashForCode( String code ) {
return hash( code, mYear );
}
public void newYear( Integer year ) {
newCodeAndYear( mCode, year);
}
public void newCodeAndYear( String code, Integer year ) {
mYear = year;
mCode = code;
History.newItem(hash(mCode, mYear));
}
public void stateChanged() {
History.newItem(hash(mCode, mYear),false);
}
public static native void recordAnalyticsHit(String pageName) /*-{
$wnd._gaq.push(['_trackPageview', pageName]);
}-*/;
@Override
public void onValueChange(ValueChangeEvent<String> event) {
String hash = event.getValue();
recordAnalyticsHit( Window.Location.getPath() + Window.Location.getHash() );
String[] parts = hash.split(",");
if ( parts.length == 12 ) {
String code = parts[0];
Integer year = Integer.decode(parts[1]);
try {
Integer timeLineDataType = Integer.decode(parts[2]);
Integer timeLineChartSelect0 = Integer.decode(parts[3]);
Integer timeLineChartSelect1 = Integer.decode(parts[4]);
Integer timeLineChartSelect2 = Integer.decode(parts[5]);
Integer timeLineChartSelect3 = Integer.decode(parts[6]);
Integer timeLineChartSelect4 = Integer.decode(parts[7]);
Integer timeLineChartSelect5 = Integer.decode(parts[8]);
Integer pieChartDataType = Integer.decode(parts[9]);
Integer pieChartNet= Integer.decode(parts[10]);
Integer resultsGridNet= Integer.decode(parts[11]);
selectBudgetCode(code, year);
mTimeLineCharter.setState( timeLineDataType,
timeLineChartSelect0,
timeLineChartSelect1,
timeLineChartSelect2,
timeLineChartSelect3,
timeLineChartSelect4,
timeLineChartSelect5 );
mPieCharter.setState( pieChartDataType,
pieChartNet );
mResultsGrid.setState( resultsGridNet );
} catch (Exception e){
Log.error("Application::onValueChange: Error while parsing url", e);
newCodeAndYear("00", 2010);
}
} else {
Log.error("Application::onValueChange: Error while parsing url");
newCodeAndYear("00", 2010);
}
}
public Widget getYearSelection() {
return mYearSelection;
}
public Widget getSearchBox() {
return mSearchBox;
}
public Widget getBreadcrumbs() {
return mBreadcrumbs;
}
public Widget getSummary1() {
return mSummary1;
}
public Widget getSummary2() {
return mSummary2;
}
public Widget getSummary3() {
return mSummary3;
}
public Widget getSummary2_1() {
return mSummary2_1;
}
public Widget getSummary3_1() {
return mSummary3_1;
}
public Widget getBudgetNews() {
return mBudgetNews;
}
public Widget getCheatSheet() {
return mCheatSheet;
}
public static void setEmbedded( boolean embedded ) {
mEmbedded = embedded;
}
}
| true | true | public void selectBudgetCode( String code, Integer year ) {
mCode = code;
mYear = year;
BudgetAPICaller generalInfo = new BudgetAPICaller();
// Load single record
generalInfo.setCode(code);
generalInfo.setParameter("year", year.toString() );
generalInfo.setParameter("depth", "0");
generalInfo.go( new BudgetAPICallback() {
@Override
public void onSuccess(JSONArray data) {
if ( data.size() < 1 ) {
return;
}
JSONObject firstResult = data.get(0).isObject();
String title = firstResult.get("title").isString().stringValue();
String code = firstResult.get("budget_id").isString().stringValue();
mSearchBox.setValue(title);
//mYearSelection.setSelectedIndex( mYear - 1992 );
mBudgetNews.update("\""+title+"\"");
Window.setTitle("תקציב המדינה - "+title+" ("+mYear+")");
mSummary1.setText( title );
final Integer revisedSum;
final String revisedSumType;
if ( (firstResult.get("gross_amount_revised") != null) &&
(firstResult.get("gross_amount_revised").isNumber() != null) ) {
revisedSumType = "gross_amount_revised";
} else if ( (firstResult.get("gross_amount_allocated") != null) &&
(firstResult.get("gross_amount_allocated").isNumber() != null) ) {
revisedSumType = "gross_amount_allocated";
} else if ( (firstResult.get("net_amount_revised") != null) &&
(firstResult.get("net_amount_revised").isNumber() != null) ) {
revisedSumType = "net_amount_revised";
} else if ( (firstResult.get("net_amount_allocated") != null) &&
(firstResult.get("net_amount_allocated").isNumber() != null) ) {
revisedSumType = "net_amount_allocated";
} else {
revisedSumType = null;
}
if ( revisedSumType != null ) {
if ( ( firstResult.get(revisedSumType) != null ) &&
firstResult.get(revisedSumType).isNumber() != null ) {
revisedSum = (int) firstResult.get(revisedSumType).isNumber().doubleValue();
if ( revisedSum != 0 ) {
mSummary2.setText( NumberFormat.getDecimalFormat().format(revisedSum)+",000" );
} else {
mSummary2.setText( "0" );
}
mSummary2_1.setText( (revisedSumType.startsWith("net") ? " (נטו)" : "") );
} else {
revisedSum = null;
}
} else {
revisedSum = null;
mSummary2.setText("");
mSummary2_1.setText("");
}
mSummary3.setHTML("");
mSummary3_1.setHTML("");
if ( firstResult.get("parent") != null ) {
JSONArray parents = firstResult.get("parent").isArray();
if ( parents.size() > 0 ) {
final String parentCode = parents.get(0).isObject().get("budget_id").isString().stringValue();
final String parentTitle = parents.get(0).isObject().get("title").isString().stringValue();
BudgetAPICaller percent = new BudgetAPICaller();
percent.setCode(parentCode);
percent.setParameter("year", mYear.toString());
percent.setParameter("depth", "0");
percent.go( new BudgetAPICallback() {
@Override
public void onSuccess(JSONArray data) {
if ( (data.get(0).isObject().get(revisedSumType) != null) &&
(data.get(0).isObject().get(revisedSumType).isNumber() != null) ) {
double percent = revisedSum / data.get(0).isObject().get(revisedSumType).isNumber().doubleValue();
mSummary3.setHTML( "שהם " + NumberFormat.getPercentFormat().format(percent) );
mSummary3_1.setHTML( "מתקציב <a href='#"+hashForCode(parentCode)+"'>"+parentTitle+"</a>");
}
}
});
}
String breadcrumbs = "";
for ( int i = 0 ; i < parents.size() ; i++ ) {
String ptitle = parents.get(i).isObject().get("title").isString().stringValue();
String pcode = parents.get(i).isObject().get("budget_id").isString().stringValue();
breadcrumbs = "<a href='#"+hashForCode(pcode)+"'>"+ptitle+"</a> ("+pcode+") "+" > " + breadcrumbs;
}
breadcrumbs += "<a href='#"+hashForCode(code)+"'>"+title+"</a> ("+code+")";
mBreadcrumbs.setHTML(breadcrumbs);
}
}
});
// Load all children
BudgetAPICaller childrenLines = new BudgetAPICaller();
childrenLines.setCode(code);
childrenLines.setParameter("year", year.toString());
childrenLines.setParameter("depth", "1");
childrenLines.go( new BudgetAPICallback() {
@Override
public void onSuccess(JSONArray data) {
mChildrenBudgetLines.parseJson(data);
mResultsGrid.handleData(mChildrenBudgetLines);
mPieCharter.handleData(mChildrenBudgetLines);
}
});
// Load same record, over the years
BudgetAPICaller historicLines = new BudgetAPICaller();
historicLines.setCode(code);
historicLines.setParameter("depth", "0");
historicLines.go( new BudgetAPICallback() {
@Override
public void onSuccess(JSONArray data) {
mHistoricBudgetLines.parseJson(data);
String lastLine = null;
boolean allEqual = true;
for ( BudgetLine bl : mHistoricBudgetLines ) {
if ( lastLine != null ) {
allEqual = allEqual && lastLine.equals(bl.getTitle());
}
lastLine = bl.getTitle();
}
mYearSelection.clear();
Integer selectedIndex = 0;
for ( BudgetLine bl : mHistoricBudgetLines ) {
String year = bl.getYear().toString();
if (year.equals( mYear.toString() )) {
mYearSelection.addItem( year );
selectedIndex = mYearSelection.getItemCount() - 1;
} else {
if ( allEqual ) {
mYearSelection.addItem( year );
} else {
mYearSelection.addItem( year + " - " + bl.getTitle() );
}
}
}
mYearSelection.setSelectedIndex( selectedIndex );
if ( !allEqual ) {
mYearSelection.setWidth("55px");
}
mTimeLineCharter.handleData(mHistoricBudgetLines);
}
});
}
| public void selectBudgetCode( String code, Integer year ) {
mCode = code;
mYear = year;
BudgetAPICaller generalInfo = new BudgetAPICaller();
// Load single record
generalInfo.setCode(code);
generalInfo.setParameter("year", year.toString() );
generalInfo.setParameter("depth", "0");
generalInfo.go( new BudgetAPICallback() {
@Override
public void onSuccess(JSONArray data) {
if ( data.size() < 1 ) {
return;
}
JSONObject firstResult = data.get(0).isObject();
String title = firstResult.get("title").isString().stringValue();
String code = firstResult.get("budget_id").isString().stringValue();
mSearchBox.setValue(title);
//mYearSelection.setSelectedIndex( mYear - 1992 );
mBudgetNews.update("\""+title+"\"");
Window.setTitle("תקציב המדינה - "+title+" ("+mYear+")");
mSummary1.setText( title );
final Integer revisedSum;
final String revisedSumType;
if ( (firstResult.get("gross_amount_revised") != null) &&
(firstResult.get("gross_amount_revised").isNumber() != null) ) {
revisedSumType = "gross_amount_revised";
} else if ( (firstResult.get("gross_amount_allocated") != null) &&
(firstResult.get("gross_amount_allocated").isNumber() != null) ) {
revisedSumType = "gross_amount_allocated";
} else if ( (firstResult.get("net_amount_revised") != null) &&
(firstResult.get("net_amount_revised").isNumber() != null) ) {
revisedSumType = "net_amount_revised";
} else if ( (firstResult.get("net_amount_allocated") != null) &&
(firstResult.get("net_amount_allocated").isNumber() != null) ) {
revisedSumType = "net_amount_allocated";
} else {
revisedSumType = null;
}
if ( revisedSumType != null ) {
if ( ( firstResult.get(revisedSumType) != null ) &&
firstResult.get(revisedSumType).isNumber() != null ) {
revisedSum = (int) firstResult.get(revisedSumType).isNumber().doubleValue();
if ( revisedSum != 0 ) {
mSummary2.setText( NumberFormat.getDecimalFormat().format(revisedSum)+",000" );
} else {
mSummary2.setText( "0" );
}
mSummary2_1.setText( (revisedSumType.startsWith("net") ? " (נטו)" : "") );
} else {
revisedSum = null;
}
} else {
revisedSum = null;
mSummary2.setText("");
mSummary2_1.setText("");
}
mSummary3.setHTML("");
mSummary3_1.setHTML("");
if ( firstResult.get("parent") != null ) {
JSONArray parents = firstResult.get("parent").isArray();
if ( parents.size() > 0 ) {
final String parentCode = parents.get(0).isObject().get("budget_id").isString().stringValue();
final String parentTitle = parents.get(0).isObject().get("title").isString().stringValue();
BudgetAPICaller percent = new BudgetAPICaller();
percent.setCode(parentCode);
percent.setParameter("year", mYear.toString());
percent.setParameter("depth", "0");
percent.go( new BudgetAPICallback() {
@Override
public void onSuccess(JSONArray data) {
if ( (data.get(0).isObject().get(revisedSumType) != null) &&
(data.get(0).isObject().get(revisedSumType).isNumber() != null) &&
(data.get(0).isObject().get(revisedSumType).isNumber().doubleValue() > 0) ) {
double percent = revisedSum / data.get(0).isObject().get(revisedSumType).isNumber().doubleValue();
mSummary3.setHTML( "שהם " + NumberFormat.getPercentFormat().format(percent) );
mSummary3_1.setHTML( "מתקציב <a href='#"+hashForCode(parentCode)+"'>"+parentTitle+"</a>");
}
}
});
}
String breadcrumbs = "";
for ( int i = 0 ; i < parents.size() ; i++ ) {
String ptitle = parents.get(i).isObject().get("title").isString().stringValue();
String pcode = parents.get(i).isObject().get("budget_id").isString().stringValue();
breadcrumbs = "<a href='#"+hashForCode(pcode)+"'>"+ptitle+"</a> ("+pcode+") "+" > " + breadcrumbs;
}
breadcrumbs += "<a href='#"+hashForCode(code)+"'>"+title+"</a> ("+code+")";
mBreadcrumbs.setHTML(breadcrumbs);
}
}
});
// Load all children
BudgetAPICaller childrenLines = new BudgetAPICaller();
childrenLines.setCode(code);
childrenLines.setParameter("year", year.toString());
childrenLines.setParameter("depth", "1");
childrenLines.go( new BudgetAPICallback() {
@Override
public void onSuccess(JSONArray data) {
mChildrenBudgetLines.parseJson(data);
mResultsGrid.handleData(mChildrenBudgetLines);
mPieCharter.handleData(mChildrenBudgetLines);
}
});
// Load same record, over the years
BudgetAPICaller historicLines = new BudgetAPICaller();
historicLines.setCode(code);
historicLines.setParameter("depth", "0");
historicLines.go( new BudgetAPICallback() {
@Override
public void onSuccess(JSONArray data) {
mHistoricBudgetLines.parseJson(data);
String lastLine = null;
boolean allEqual = true;
for ( BudgetLine bl : mHistoricBudgetLines ) {
if ( lastLine != null ) {
allEqual = allEqual && lastLine.equals(bl.getTitle());
}
lastLine = bl.getTitle();
}
mYearSelection.clear();
Integer selectedIndex = 0;
for ( BudgetLine bl : mHistoricBudgetLines ) {
String year = bl.getYear().toString();
if (year.equals( mYear.toString() )) {
mYearSelection.addItem( year );
selectedIndex = mYearSelection.getItemCount() - 1;
} else {
if ( allEqual ) {
mYearSelection.addItem( year );
} else {
mYearSelection.addItem( year + " - " + bl.getTitle() );
}
}
}
mYearSelection.setSelectedIndex( selectedIndex );
if ( !allEqual ) {
mYearSelection.setWidth("55px");
}
mTimeLineCharter.handleData(mHistoricBudgetLines);
}
});
}
|
diff --git a/src/tim/view/dialog/client/ClientDialog.java b/src/tim/view/dialog/client/ClientDialog.java
index 6373b8a..cc51608 100644
--- a/src/tim/view/dialog/client/ClientDialog.java
+++ b/src/tim/view/dialog/client/ClientDialog.java
@@ -1,100 +1,100 @@
package tim.view.dialog.client;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import javax.swing.JButton;
import javax.swing.JDialog;
import tim.application.Config;
import tim.application.GlobalRegistry;
import tim.application.exception.OperationNotPossibleException;
import tim.application.exception.PersistanceException;
import tim.application.exception.ResourceNotFoundException;
import tim.controller.AbstractController;
import tim.controller.ClientDialogController;
import tim.model.Element;
import tim.view.AbstractView;
public class ClientDialog extends JDialog implements AbstractView {
Form form;
ClientDialogController clientDialogController;
private JButton btnCancel;
private ClientDialogController controller;
public ClientDialog(ClientDialogController controller) {
this.controller = (ClientDialogController) controller;
try {
- form = new Form(controller.getAll("clients"), this);
+ form = new Form(controller.getAll("client"), this);
} catch (PersistanceException e) {
e.printStackTrace();
} catch (ResourceNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
btnCancel = new JButton(Config.RESSOURCE_BUNDLE.getString("dialogCancel"));
btnCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
close();
}
});
add(form, BorderLayout.NORTH);
add(btnCancel, BorderLayout.CENTER);
this.pack();
}
public void save(String action, Element element) {
try {
controller.save(action, element);
} catch (ClassCastException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (PersistanceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ResourceNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OperationNotPossibleException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void close() {
this.dispose();
}
@Override
public void update(Observable o, Object arg) {
try {
this.remove(form);
this.remove(btnCancel);
form = new Form(controller.getAll("clients"), this);
add(form, BorderLayout.NORTH);
add(btnCancel, BorderLayout.CENTER);
this.pack();
} catch (PersistanceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ResourceNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("reload");
}
}
| true | true | public ClientDialog(ClientDialogController controller) {
this.controller = (ClientDialogController) controller;
try {
form = new Form(controller.getAll("clients"), this);
} catch (PersistanceException e) {
e.printStackTrace();
} catch (ResourceNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
btnCancel = new JButton(Config.RESSOURCE_BUNDLE.getString("dialogCancel"));
btnCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
close();
}
});
add(form, BorderLayout.NORTH);
add(btnCancel, BorderLayout.CENTER);
this.pack();
}
| public ClientDialog(ClientDialogController controller) {
this.controller = (ClientDialogController) controller;
try {
form = new Form(controller.getAll("client"), this);
} catch (PersistanceException e) {
e.printStackTrace();
} catch (ResourceNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
btnCancel = new JButton(Config.RESSOURCE_BUNDLE.getString("dialogCancel"));
btnCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
close();
}
});
add(form, BorderLayout.NORTH);
add(btnCancel, BorderLayout.CENTER);
this.pack();
}
|
diff --git a/org.jacoco.agent.rt/src/org/jacoco/agent/rt/CoverageTransformer.java b/org.jacoco.agent.rt/src/org/jacoco/agent/rt/CoverageTransformer.java
index 0ac3994..b5b0561 100644
--- a/org.jacoco.agent.rt/src/org/jacoco/agent/rt/CoverageTransformer.java
+++ b/org.jacoco.agent.rt/src/org/jacoco/agent/rt/CoverageTransformer.java
@@ -1,88 +1,90 @@
/*******************************************************************************
* Copyright (c) 2009 Mountainminds GmbH & Co. KG 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:
* Marc R. Hoffmann - initial API and implementation
*
* $Id: $
*******************************************************************************/
package org.jacoco.agent.rt;
import static java.lang.String.format;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import org.jacoco.core.instr.CRC64;
import org.jacoco.core.instr.Instrumenter;
import org.jacoco.core.runtime.AgentOptions;
import org.jacoco.core.runtime.IRuntime;
import org.jacoco.core.runtime.WildcardMatcher;
/**
* Class file transformer to instrument classes for code coverage analysis.
*
* @author Marc R. Hoffmann
* @version $Revision: $
*/
public class CoverageTransformer implements ClassFileTransformer {
private final Instrumenter instrumenter;
private final WildcardMatcher includes;
private final WildcardMatcher excludes;
private final WildcardMatcher exclClassloader;
public CoverageTransformer(IRuntime runtime, AgentOptions options) {
this.instrumenter = new Instrumenter(runtime);
// Class names will be reported in VM notation:
includes = new WildcardMatcher(options.getIncludes().replace('.', '/'));
excludes = new WildcardMatcher(options.getExcludes().replace('.', '/'));
exclClassloader = new WildcardMatcher(options.getExclClassloader());
}
public byte[] transform(ClassLoader loader, String classname,
Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
byte[] classfileBuffer) throws IllegalClassFormatException {
if (!filter(loader, classname)) {
return null;
}
try {
return instrumenter.instrument(classfileBuffer);
} catch (Throwable t) {
final Long id = Long.valueOf(CRC64.checksum(classfileBuffer));
final String msg = "Error while instrumenting class %s (id=0x%x).";
final IllegalClassFormatException ex = new IllegalClassFormatException(
format(msg, classname, id));
ex.initCause(t);
+ // Force some output, as the exception is ignored by the JVM:
+ ex.printStackTrace();
throw ex;
}
}
/**
* Checks whether this class should be instrumented.
*
* @param loader
* loader for the class
* @return <code>true</code> if the class should be instrumented
*/
protected boolean filter(ClassLoader loader, String classname) {
// Don't instrument classes of the bootstrap loader:
return loader != null &&
!exclClassloader.matches(loader.getClass().getName()) &&
includes.matches(classname) &&
!excludes.matches(classname);
}
}
| true | true | public byte[] transform(ClassLoader loader, String classname,
Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
byte[] classfileBuffer) throws IllegalClassFormatException {
if (!filter(loader, classname)) {
return null;
}
try {
return instrumenter.instrument(classfileBuffer);
} catch (Throwable t) {
final Long id = Long.valueOf(CRC64.checksum(classfileBuffer));
final String msg = "Error while instrumenting class %s (id=0x%x).";
final IllegalClassFormatException ex = new IllegalClassFormatException(
format(msg, classname, id));
ex.initCause(t);
throw ex;
}
}
| public byte[] transform(ClassLoader loader, String classname,
Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
byte[] classfileBuffer) throws IllegalClassFormatException {
if (!filter(loader, classname)) {
return null;
}
try {
return instrumenter.instrument(classfileBuffer);
} catch (Throwable t) {
final Long id = Long.valueOf(CRC64.checksum(classfileBuffer));
final String msg = "Error while instrumenting class %s (id=0x%x).";
final IllegalClassFormatException ex = new IllegalClassFormatException(
format(msg, classname, id));
ex.initCause(t);
// Force some output, as the exception is ignored by the JVM:
ex.printStackTrace();
throw ex;
}
}
|
diff --git a/src/net/medsouz/miney/updater/RenderTick.java b/src/net/medsouz/miney/updater/RenderTick.java
index 43d95ae..64c74fe 100644
--- a/src/net/medsouz/miney/updater/RenderTick.java
+++ b/src/net/medsouz/miney/updater/RenderTick.java
@@ -1,37 +1,41 @@
package net.medsouz.miney.updater;
import java.util.EnumSet;
import net.minecraft.client.Minecraft;
import cpw.mods.fml.common.ITickHandler;
import cpw.mods.fml.common.TickType;
public class RenderTick implements ITickHandler{
@Override
public void tickStart(EnumSet<TickType> type, Object... tickData) {
}
@Override
public void tickEnd(EnumSet<TickType> type, Object... tickData) {
if(MineyUpdater.updater != null){
- Minecraft.getMinecraft().currentScreen.drawString(Minecraft.getMinecraft().fontRenderer, "Miney is updating!", 2, 2, 16777215);
+ if(Minecraft.getMinecraft().currentScreen != null){
+ Minecraft.getMinecraft().currentScreen.drawString(Minecraft.getMinecraft().fontRenderer, "Miney is updating!", 2, 2, 16777215);
+ }
}
if(MineyUpdater.updateFailed){
- Minecraft.getMinecraft().currentScreen.drawString(Minecraft.getMinecraft().fontRenderer, "Miney failed to update, please try again later!", 2, 2, 16777215);
+ if(Minecraft.getMinecraft().currentScreen != null){
+ Minecraft.getMinecraft().currentScreen.drawString(Minecraft.getMinecraft().fontRenderer, "Miney failed to update, please restart Minecraft to try again!", 2, 2, 16777215);
+ }
}
}
@Override
public EnumSet<TickType> ticks() {
return EnumSet.of(TickType.RENDER);
}
@Override
public String getLabel() {
return "Miney Updater Render Tick";
}
}
| false | true | public void tickEnd(EnumSet<TickType> type, Object... tickData) {
if(MineyUpdater.updater != null){
Minecraft.getMinecraft().currentScreen.drawString(Minecraft.getMinecraft().fontRenderer, "Miney is updating!", 2, 2, 16777215);
}
if(MineyUpdater.updateFailed){
Minecraft.getMinecraft().currentScreen.drawString(Minecraft.getMinecraft().fontRenderer, "Miney failed to update, please try again later!", 2, 2, 16777215);
}
}
| public void tickEnd(EnumSet<TickType> type, Object... tickData) {
if(MineyUpdater.updater != null){
if(Minecraft.getMinecraft().currentScreen != null){
Minecraft.getMinecraft().currentScreen.drawString(Minecraft.getMinecraft().fontRenderer, "Miney is updating!", 2, 2, 16777215);
}
}
if(MineyUpdater.updateFailed){
if(Minecraft.getMinecraft().currentScreen != null){
Minecraft.getMinecraft().currentScreen.drawString(Minecraft.getMinecraft().fontRenderer, "Miney failed to update, please restart Minecraft to try again!", 2, 2, 16777215);
}
}
}
|
diff --git a/test/call/oop/FieldsCall.java b/test/call/oop/FieldsCall.java
index 7082a88..3cd2af1 100755
--- a/test/call/oop/FieldsCall.java
+++ b/test/call/oop/FieldsCall.java
@@ -1,18 +1,19 @@
public class FieldsCall
{
public static void main(String[] args)
{
boolean pass = true;
pass &= Fields.getFive() == 5;
pass &= Fields.ten == 10;
- pass &= Fields.getObject() != null;
- pass &= Fields.getThing() == null;
- pass &= Fields.setThing("asdf");
- pass &= Fields.getThing() == "asdf";
- pass &= Fields.setThisThing("fdsa");
- pass &= Fields.getThisThing() == "fdsa";
+ Fields fields = new Fields();
+ pass &= fields.getObject() != null;
+ pass &= fields.getThing() == null;
+ fields.setThing("asdf");
+ pass &= fields.getThing() == "asdf";
+ fields.setThisThing("fdsa");
+ pass &= fields.getThisThing() == "fdsa";
if (!pass)
System.out.println("*** FAIL");
- System.out.println(Fields.pass());
+ System.out.println("+++ PASS");
}
}
| false | true | public static void main(String[] args)
{
boolean pass = true;
pass &= Fields.getFive() == 5;
pass &= Fields.ten == 10;
pass &= Fields.getObject() != null;
pass &= Fields.getThing() == null;
pass &= Fields.setThing("asdf");
pass &= Fields.getThing() == "asdf";
pass &= Fields.setThisThing("fdsa");
pass &= Fields.getThisThing() == "fdsa";
if (!pass)
System.out.println("*** FAIL");
System.out.println(Fields.pass());
}
| public static void main(String[] args)
{
boolean pass = true;
pass &= Fields.getFive() == 5;
pass &= Fields.ten == 10;
Fields fields = new Fields();
pass &= fields.getObject() != null;
pass &= fields.getThing() == null;
fields.setThing("asdf");
pass &= fields.getThing() == "asdf";
fields.setThisThing("fdsa");
pass &= fields.getThisThing() == "fdsa";
if (!pass)
System.out.println("*** FAIL");
System.out.println("+++ PASS");
}
|
diff --git a/src/main/java/br/com/caelum/vraptor/plugin/hibernate4/ConfigurationCreator.java b/src/main/java/br/com/caelum/vraptor/plugin/hibernate4/ConfigurationCreator.java
index f285f94..664b54b 100644
--- a/src/main/java/br/com/caelum/vraptor/plugin/hibernate4/ConfigurationCreator.java
+++ b/src/main/java/br/com/caelum/vraptor/plugin/hibernate4/ConfigurationCreator.java
@@ -1,67 +1,67 @@
/***
* Copyright (c) 2011 Caelum - www.caelum.com.br/opensource
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package br.com.caelum.vraptor.plugin.hibernate4;
import javax.annotation.PostConstruct;
import org.hibernate.cfg.Configuration;
import br.com.caelum.vraptor.environment.Environment;
import br.com.caelum.vraptor.ioc.ApplicationScoped;
import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.ioc.ComponentFactory;
/**
* Creates a Hibernate {@link Configuration}, once when application starts.
*
* @author Otávio Scherer Garcia
*/
@Component
@ApplicationScoped
public class ConfigurationCreator
implements ComponentFactory<Configuration> {
private Configuration cfg;
private Environment env;
public ConfigurationCreator(Environment env) {
this.env = env;
}
/**
* Create a new instance for {@link Configuration}, and after call the
* {@link ConfigurationCreator#configureExtras()} method, that you can override to configure extra guys.
* This method uses vraptor-environment that allow you to get different resources for each environment you
* needs.
*/
@PostConstruct
- protected void create() {
+ public void create() {
cfg = new Configuration().configure(env.getResource("/hibernate.cfg.xml"));
configureExtras();
}
/**
* This method can override if you want to configure more things.
*/
public void configureExtras() {
}
public Configuration getInstance() {
return cfg;
}
}
| true | true | protected void create() {
cfg = new Configuration().configure(env.getResource("/hibernate.cfg.xml"));
configureExtras();
}
| public void create() {
cfg = new Configuration().configure(env.getResource("/hibernate.cfg.xml"));
configureExtras();
}
|
diff --git a/src/web/org/openmrs/web/filter/OpenmrsFilter.java b/src/web/org/openmrs/web/filter/OpenmrsFilter.java
index 7dd256b1..eb1d5bc8 100644
--- a/src/web/org/openmrs/web/filter/OpenmrsFilter.java
+++ b/src/web/org/openmrs/web/filter/OpenmrsFilter.java
@@ -1,127 +1,134 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.filter;
import java.io.IOException;
import java.util.Date;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.User;
import org.openmrs.api.context.Context;
import org.openmrs.api.context.UserContext;
import org.openmrs.util.OpenmrsClassLoader;
import org.openmrs.web.WebConstants;
import org.springframework.web.filter.OncePerRequestFilter;
/**
* This is the custom OpenMRS filter. It is defined as the filter of choice in the web.xml file. All
* page/object calls run through the doFilter method so we can wrap every session with the user's
* userContext (which holds the user's authenticated info). This is needed because the OpenMRS API
* keeps authentication information on the current Thread. Web applications use a different thread
* per request, so before each request this filter will make sure that the UserContext (the
* authentication information) is on the Thread.
*/
public class OpenmrsFilter extends OncePerRequestFilter {
protected final Log log = LogFactory.getLog(getClass());
/**
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
log.debug("Destroying filter");
}
/**
* This method is called for every request for a page/image/javascript file/etc The main point
* of this is to make sure the user's current userContext is on the session and on the current
* thread
*
* @see org.springframework.web.filter.OncePerRequestFilter#doFilterInternal(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse, javax.servlet.FilterChain)
*/
@Override
protected void doFilterInternal(HttpServletRequest httpRequest, HttpServletResponse httpResponse, FilterChain chain)
throws ServletException,
IOException {
HttpSession httpSession = httpRequest.getSession();
// used by htmlInclude tag
httpRequest.setAttribute(WebConstants.INIT_REQ_UNIQUE_ID, String.valueOf(new Date().getTime()));
if (log.isDebugEnabled()) {
log.debug("requestURI " + httpRequest.getRequestURI());
log.debug("requestURL " + httpRequest.getRequestURL());
log.debug("request path info " + httpRequest.getPathInfo());
}
// User context is created if it doesn't already exist and added to the session
// note: this usercontext storage logic is copied to webinf/view/uncaughtexception.jsp to
// prevent stack traces being shown to non-authenticated users
UserContext userContext = (UserContext) httpSession.getAttribute(WebConstants.OPENMRS_USER_CONTEXT_HTTPSESSION_ATTR);
// default the session username attribute to anonymous
httpSession.setAttribute("username", "-anonymous user-");
// if there isn't a userContext on the session yet, create one
// and set it onto the session
if (userContext == null) {
userContext = new UserContext();
httpSession.setAttribute(WebConstants.OPENMRS_USER_CONTEXT_HTTPSESSION_ATTR, userContext);
if (log.isDebugEnabled())
log.debug("Just set user context " + userContext + " as attribute on session");
} else {
// set username as attribute on session so parent servlet container
// can identify sessions easier
User user;
if ((user = userContext.getAuthenticatedUser()) != null)
httpSession.setAttribute("username", user.getUsername());
}
// set the locale on the session (for the servlet container as well)
httpSession.setAttribute("locale", userContext.getLocale());
// Add the user context to the current thread
Context.setUserContext(userContext);
Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());
// Refresh the authenticated user to prevent LazyInitializationException.
// #1588 - LazyInitializationException: issue with User when serializing some objects
- if (Context.isAuthenticated())
+ if (Context.isAuthenticated()) {
Context.refreshAuthenticatedUser();
+ // greedy fetch of all collections on the authenticated user
+ User tmp = Context.getAuthenticatedUser();
+ tmp.getUserProperties().size();
+ tmp.getNames().size();
+ tmp.getAttributes().size();
+ tmp.getAddresses().size();
+ }
log.debug("before chain.Filter");
// continue the filter chain (going on to spring, authorization, etc)
try {
chain.doFilter(httpRequest, httpResponse);
}
finally {
Context.clearUserContext();
}
log.debug("after chain.doFilter");
}
}
| false | true | protected void doFilterInternal(HttpServletRequest httpRequest, HttpServletResponse httpResponse, FilterChain chain)
throws ServletException,
IOException {
HttpSession httpSession = httpRequest.getSession();
// used by htmlInclude tag
httpRequest.setAttribute(WebConstants.INIT_REQ_UNIQUE_ID, String.valueOf(new Date().getTime()));
if (log.isDebugEnabled()) {
log.debug("requestURI " + httpRequest.getRequestURI());
log.debug("requestURL " + httpRequest.getRequestURL());
log.debug("request path info " + httpRequest.getPathInfo());
}
// User context is created if it doesn't already exist and added to the session
// note: this usercontext storage logic is copied to webinf/view/uncaughtexception.jsp to
// prevent stack traces being shown to non-authenticated users
UserContext userContext = (UserContext) httpSession.getAttribute(WebConstants.OPENMRS_USER_CONTEXT_HTTPSESSION_ATTR);
// default the session username attribute to anonymous
httpSession.setAttribute("username", "-anonymous user-");
// if there isn't a userContext on the session yet, create one
// and set it onto the session
if (userContext == null) {
userContext = new UserContext();
httpSession.setAttribute(WebConstants.OPENMRS_USER_CONTEXT_HTTPSESSION_ATTR, userContext);
if (log.isDebugEnabled())
log.debug("Just set user context " + userContext + " as attribute on session");
} else {
// set username as attribute on session so parent servlet container
// can identify sessions easier
User user;
if ((user = userContext.getAuthenticatedUser()) != null)
httpSession.setAttribute("username", user.getUsername());
}
// set the locale on the session (for the servlet container as well)
httpSession.setAttribute("locale", userContext.getLocale());
// Add the user context to the current thread
Context.setUserContext(userContext);
Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());
// Refresh the authenticated user to prevent LazyInitializationException.
// #1588 - LazyInitializationException: issue with User when serializing some objects
if (Context.isAuthenticated())
Context.refreshAuthenticatedUser();
log.debug("before chain.Filter");
// continue the filter chain (going on to spring, authorization, etc)
try {
chain.doFilter(httpRequest, httpResponse);
}
finally {
Context.clearUserContext();
}
log.debug("after chain.doFilter");
}
| protected void doFilterInternal(HttpServletRequest httpRequest, HttpServletResponse httpResponse, FilterChain chain)
throws ServletException,
IOException {
HttpSession httpSession = httpRequest.getSession();
// used by htmlInclude tag
httpRequest.setAttribute(WebConstants.INIT_REQ_UNIQUE_ID, String.valueOf(new Date().getTime()));
if (log.isDebugEnabled()) {
log.debug("requestURI " + httpRequest.getRequestURI());
log.debug("requestURL " + httpRequest.getRequestURL());
log.debug("request path info " + httpRequest.getPathInfo());
}
// User context is created if it doesn't already exist and added to the session
// note: this usercontext storage logic is copied to webinf/view/uncaughtexception.jsp to
// prevent stack traces being shown to non-authenticated users
UserContext userContext = (UserContext) httpSession.getAttribute(WebConstants.OPENMRS_USER_CONTEXT_HTTPSESSION_ATTR);
// default the session username attribute to anonymous
httpSession.setAttribute("username", "-anonymous user-");
// if there isn't a userContext on the session yet, create one
// and set it onto the session
if (userContext == null) {
userContext = new UserContext();
httpSession.setAttribute(WebConstants.OPENMRS_USER_CONTEXT_HTTPSESSION_ATTR, userContext);
if (log.isDebugEnabled())
log.debug("Just set user context " + userContext + " as attribute on session");
} else {
// set username as attribute on session so parent servlet container
// can identify sessions easier
User user;
if ((user = userContext.getAuthenticatedUser()) != null)
httpSession.setAttribute("username", user.getUsername());
}
// set the locale on the session (for the servlet container as well)
httpSession.setAttribute("locale", userContext.getLocale());
// Add the user context to the current thread
Context.setUserContext(userContext);
Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());
// Refresh the authenticated user to prevent LazyInitializationException.
// #1588 - LazyInitializationException: issue with User when serializing some objects
if (Context.isAuthenticated()) {
Context.refreshAuthenticatedUser();
// greedy fetch of all collections on the authenticated user
User tmp = Context.getAuthenticatedUser();
tmp.getUserProperties().size();
tmp.getNames().size();
tmp.getAttributes().size();
tmp.getAddresses().size();
}
log.debug("before chain.Filter");
// continue the filter chain (going on to spring, authorization, etc)
try {
chain.doFilter(httpRequest, httpResponse);
}
finally {
Context.clearUserContext();
}
log.debug("after chain.doFilter");
}
|
diff --git a/src/main/java/net/gtaun/shoebill/dependency/ShoebillDependencyManager.java b/src/main/java/net/gtaun/shoebill/dependency/ShoebillDependencyManager.java
index 368a1b7..0e151c3 100644
--- a/src/main/java/net/gtaun/shoebill/dependency/ShoebillDependencyManager.java
+++ b/src/main/java/net/gtaun/shoebill/dependency/ShoebillDependencyManager.java
@@ -1,183 +1,183 @@
/**
* Copyright (C) 2012 JoJLlmAn
* Copyright (C) 2012 MK124
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.gtaun.shoebill.dependency;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.gtaun.shoebill.ResourceConfig;
import net.gtaun.shoebill.ResourceConfig.RepositoryEntry;
import net.gtaun.shoebill.ShoebillArtifactLocator;
import net.gtaun.shoebill.ShoebillConfig;
import org.sonatype.aether.RepositorySystem;
import org.sonatype.aether.artifact.Artifact;
import org.sonatype.aether.collection.CollectRequest;
import org.sonatype.aether.collection.DependencyCollectionException;
import org.sonatype.aether.graph.Dependency;
import org.sonatype.aether.graph.DependencyNode;
import org.sonatype.aether.repository.RemoteRepository;
import org.sonatype.aether.resolution.DependencyRequest;
import org.sonatype.aether.resolution.DependencyResolutionException;
import org.sonatype.aether.util.DefaultRepositorySystemSession;
import org.sonatype.aether.util.artifact.DefaultArtifact;
import org.sonatype.aether.util.graph.PreorderNodeListGenerator;
/**
*
*
* @author JoJLlmAn, MK124
*/
public class ShoebillDependencyManager
{
private static final String SHOEBILL_CONFIG_PATH = "./shoebill/shoebill.yml";
private static final String PROPERTY_JAR_FILES = "jarFiles";
private static final String SCOPE_RUNTIME = "runtime";
private static final FilenameFilter JAR_FILENAME_FILTER = new FilenameFilter()
{
@Override
public boolean accept(File dir, String name)
{
return name.endsWith(".jar");
}
};
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Throwable
{
Map<String, Object> properties = resolveDependencies();
List<File> files = List.class.cast(properties.get(PROPERTY_JAR_FILES));
for (File file : files) System.out.println(file);
}
public static Map<String, Object> resolveDependencies() throws Throwable
{
ShoebillConfig shoebillConfig = new ShoebillConfig(new FileInputStream(SHOEBILL_CONFIG_PATH));
ResourceConfig resourceConfig = new ResourceConfig(new FileInputStream(new File(shoebillConfig.getShoebillDir(), "resources.yml")));
ShoebillArtifactLocator artifactLocator = new ShoebillArtifactLocator(shoebillConfig, resourceConfig);
final File repoDir = shoebillConfig.getRepositoryDir();
final File libDir = shoebillConfig.getLibrariesDir();
final File pluginsDir = shoebillConfig.getPluginsDir();
final File gamemodesDir = shoebillConfig.getGamemodesDir();
File[] libJarFiles = libDir.listFiles(JAR_FILENAME_FILTER);
File[] pluginsJarFiles = pluginsDir.listFiles(JAR_FILENAME_FILTER);
File[] gamemodesJarFiles = gamemodesDir.listFiles(JAR_FILENAME_FILTER);
List<File> files = new ArrayList<>();
if(libJarFiles != null) files.addAll(Arrays.asList(libJarFiles));
if(pluginsJarFiles != null) files.addAll(Arrays.asList(pluginsJarFiles));
if(gamemodesJarFiles != null) files.addAll(Arrays.asList(gamemodesJarFiles));
if (shoebillConfig.isResolveDependencies())
{
RepositorySystem repoSystem = AetherUtil.newRepositorySystem();
DefaultRepositorySystemSession session = AetherUtil.newRepositorySystemSession(repoSystem, repoDir);
CollectRequest collectRequest = new CollectRequest();
session.setRepositoryListener(new ShoebillRepositoryListener());
session.setUpdatePolicy(resourceConfig.getCacheUpdatePolicy());
for (RepositoryEntry repo : resourceConfig.getRepositories())
{
collectRequest.addRepository(new RemoteRepository(repo.getId(), repo.getType(), repo.getUrl()));
}
// Runtime
String runtimeCoord = resourceConfig.getRuntime();
if (runtimeCoord.contains(":"))
{
Artifact runtimeArtifact = new DefaultArtifact(resourceConfig.getRuntime());
collectRequest.addDependency(new Dependency(runtimeArtifact, SCOPE_RUNTIME));
}
else
{
System.out.println("Skipped artifact " + runtimeCoord + " (Runtime)");
}
// Plugins
for (String coord : resourceConfig.getPlugins())
{
if (coord.contains(":") == false)
{
- System.out.println("Skipped artifact " + runtimeCoord + " (Plugin)");
+ System.out.println("Skipped artifact " + coord + " (Plugin)");
continue;
}
Artifact artifact = new DefaultArtifact(coord);
collectRequest.addDependency(new Dependency(artifact, SCOPE_RUNTIME));
}
// Gamemode
String gamemodeCoord = resourceConfig.getGamemode();
if (gamemodeCoord.contains(":"))
{
Artifact gamemodeArtifact = new DefaultArtifact(resourceConfig.getGamemode());
collectRequest.addDependency(new Dependency(gamemodeArtifact, SCOPE_RUNTIME));
}
else
{
- System.out.println("Skipped artifact " + runtimeCoord + " (Gamemode)");
+ System.out.println("Skipped artifact " + gamemodeCoord + " (Gamemode)");
}
DependencyNode node = null;
try
{
node = repoSystem.collectDependencies(session, collectRequest).getRoot();
}
catch (DependencyCollectionException e)
{
e.printStackTrace();
}
DependencyRequest dependencyRequest = new DependencyRequest(node, null);
dependencyRequest.setFilter(new ShoebillDependencyFilter(artifactLocator));
try
{
repoSystem.resolveDependencies(session, dependencyRequest);
}
catch (DependencyResolutionException e)
{
e.printStackTrace();
}
PreorderNodeListGenerator nlg = new PreorderNodeListGenerator();
node.accept(nlg);
files.addAll(nlg.getFiles());
}
else
{
System.out.println("Skip resolve dependencies." );
}
Map<String, Object> properties = new HashMap<>();
properties.put(PROPERTY_JAR_FILES, files);
return properties;
}
}
| false | true | public static Map<String, Object> resolveDependencies() throws Throwable
{
ShoebillConfig shoebillConfig = new ShoebillConfig(new FileInputStream(SHOEBILL_CONFIG_PATH));
ResourceConfig resourceConfig = new ResourceConfig(new FileInputStream(new File(shoebillConfig.getShoebillDir(), "resources.yml")));
ShoebillArtifactLocator artifactLocator = new ShoebillArtifactLocator(shoebillConfig, resourceConfig);
final File repoDir = shoebillConfig.getRepositoryDir();
final File libDir = shoebillConfig.getLibrariesDir();
final File pluginsDir = shoebillConfig.getPluginsDir();
final File gamemodesDir = shoebillConfig.getGamemodesDir();
File[] libJarFiles = libDir.listFiles(JAR_FILENAME_FILTER);
File[] pluginsJarFiles = pluginsDir.listFiles(JAR_FILENAME_FILTER);
File[] gamemodesJarFiles = gamemodesDir.listFiles(JAR_FILENAME_FILTER);
List<File> files = new ArrayList<>();
if(libJarFiles != null) files.addAll(Arrays.asList(libJarFiles));
if(pluginsJarFiles != null) files.addAll(Arrays.asList(pluginsJarFiles));
if(gamemodesJarFiles != null) files.addAll(Arrays.asList(gamemodesJarFiles));
if (shoebillConfig.isResolveDependencies())
{
RepositorySystem repoSystem = AetherUtil.newRepositorySystem();
DefaultRepositorySystemSession session = AetherUtil.newRepositorySystemSession(repoSystem, repoDir);
CollectRequest collectRequest = new CollectRequest();
session.setRepositoryListener(new ShoebillRepositoryListener());
session.setUpdatePolicy(resourceConfig.getCacheUpdatePolicy());
for (RepositoryEntry repo : resourceConfig.getRepositories())
{
collectRequest.addRepository(new RemoteRepository(repo.getId(), repo.getType(), repo.getUrl()));
}
// Runtime
String runtimeCoord = resourceConfig.getRuntime();
if (runtimeCoord.contains(":"))
{
Artifact runtimeArtifact = new DefaultArtifact(resourceConfig.getRuntime());
collectRequest.addDependency(new Dependency(runtimeArtifact, SCOPE_RUNTIME));
}
else
{
System.out.println("Skipped artifact " + runtimeCoord + " (Runtime)");
}
// Plugins
for (String coord : resourceConfig.getPlugins())
{
if (coord.contains(":") == false)
{
System.out.println("Skipped artifact " + runtimeCoord + " (Plugin)");
continue;
}
Artifact artifact = new DefaultArtifact(coord);
collectRequest.addDependency(new Dependency(artifact, SCOPE_RUNTIME));
}
// Gamemode
String gamemodeCoord = resourceConfig.getGamemode();
if (gamemodeCoord.contains(":"))
{
Artifact gamemodeArtifact = new DefaultArtifact(resourceConfig.getGamemode());
collectRequest.addDependency(new Dependency(gamemodeArtifact, SCOPE_RUNTIME));
}
else
{
System.out.println("Skipped artifact " + runtimeCoord + " (Gamemode)");
}
DependencyNode node = null;
try
{
node = repoSystem.collectDependencies(session, collectRequest).getRoot();
}
catch (DependencyCollectionException e)
{
e.printStackTrace();
}
DependencyRequest dependencyRequest = new DependencyRequest(node, null);
dependencyRequest.setFilter(new ShoebillDependencyFilter(artifactLocator));
try
{
repoSystem.resolveDependencies(session, dependencyRequest);
}
catch (DependencyResolutionException e)
{
e.printStackTrace();
}
PreorderNodeListGenerator nlg = new PreorderNodeListGenerator();
node.accept(nlg);
files.addAll(nlg.getFiles());
}
else
{
System.out.println("Skip resolve dependencies." );
}
Map<String, Object> properties = new HashMap<>();
properties.put(PROPERTY_JAR_FILES, files);
return properties;
}
| public static Map<String, Object> resolveDependencies() throws Throwable
{
ShoebillConfig shoebillConfig = new ShoebillConfig(new FileInputStream(SHOEBILL_CONFIG_PATH));
ResourceConfig resourceConfig = new ResourceConfig(new FileInputStream(new File(shoebillConfig.getShoebillDir(), "resources.yml")));
ShoebillArtifactLocator artifactLocator = new ShoebillArtifactLocator(shoebillConfig, resourceConfig);
final File repoDir = shoebillConfig.getRepositoryDir();
final File libDir = shoebillConfig.getLibrariesDir();
final File pluginsDir = shoebillConfig.getPluginsDir();
final File gamemodesDir = shoebillConfig.getGamemodesDir();
File[] libJarFiles = libDir.listFiles(JAR_FILENAME_FILTER);
File[] pluginsJarFiles = pluginsDir.listFiles(JAR_FILENAME_FILTER);
File[] gamemodesJarFiles = gamemodesDir.listFiles(JAR_FILENAME_FILTER);
List<File> files = new ArrayList<>();
if(libJarFiles != null) files.addAll(Arrays.asList(libJarFiles));
if(pluginsJarFiles != null) files.addAll(Arrays.asList(pluginsJarFiles));
if(gamemodesJarFiles != null) files.addAll(Arrays.asList(gamemodesJarFiles));
if (shoebillConfig.isResolveDependencies())
{
RepositorySystem repoSystem = AetherUtil.newRepositorySystem();
DefaultRepositorySystemSession session = AetherUtil.newRepositorySystemSession(repoSystem, repoDir);
CollectRequest collectRequest = new CollectRequest();
session.setRepositoryListener(new ShoebillRepositoryListener());
session.setUpdatePolicy(resourceConfig.getCacheUpdatePolicy());
for (RepositoryEntry repo : resourceConfig.getRepositories())
{
collectRequest.addRepository(new RemoteRepository(repo.getId(), repo.getType(), repo.getUrl()));
}
// Runtime
String runtimeCoord = resourceConfig.getRuntime();
if (runtimeCoord.contains(":"))
{
Artifact runtimeArtifact = new DefaultArtifact(resourceConfig.getRuntime());
collectRequest.addDependency(new Dependency(runtimeArtifact, SCOPE_RUNTIME));
}
else
{
System.out.println("Skipped artifact " + runtimeCoord + " (Runtime)");
}
// Plugins
for (String coord : resourceConfig.getPlugins())
{
if (coord.contains(":") == false)
{
System.out.println("Skipped artifact " + coord + " (Plugin)");
continue;
}
Artifact artifact = new DefaultArtifact(coord);
collectRequest.addDependency(new Dependency(artifact, SCOPE_RUNTIME));
}
// Gamemode
String gamemodeCoord = resourceConfig.getGamemode();
if (gamemodeCoord.contains(":"))
{
Artifact gamemodeArtifact = new DefaultArtifact(resourceConfig.getGamemode());
collectRequest.addDependency(new Dependency(gamemodeArtifact, SCOPE_RUNTIME));
}
else
{
System.out.println("Skipped artifact " + gamemodeCoord + " (Gamemode)");
}
DependencyNode node = null;
try
{
node = repoSystem.collectDependencies(session, collectRequest).getRoot();
}
catch (DependencyCollectionException e)
{
e.printStackTrace();
}
DependencyRequest dependencyRequest = new DependencyRequest(node, null);
dependencyRequest.setFilter(new ShoebillDependencyFilter(artifactLocator));
try
{
repoSystem.resolveDependencies(session, dependencyRequest);
}
catch (DependencyResolutionException e)
{
e.printStackTrace();
}
PreorderNodeListGenerator nlg = new PreorderNodeListGenerator();
node.accept(nlg);
files.addAll(nlg.getFiles());
}
else
{
System.out.println("Skip resolve dependencies." );
}
Map<String, Object> properties = new HashMap<>();
properties.put(PROPERTY_JAR_FILES, files);
return properties;
}
|
diff --git a/src/functions/Function.java b/src/functions/Function.java
index 66bef34..5c65cce 100644
--- a/src/functions/Function.java
+++ b/src/functions/Function.java
@@ -1,82 +1,82 @@
package functions;
import backEnd.Model;
public abstract class Function {
private Model myModel;
private int inputNum;
public Function (int num, Model model) {
myModel = model;
inputNum = num;
}
public abstract double execute (String[] input);
public double getValue (String[] input) {
if(!myModel.getMap().containsKey(input[1])) {
return Double.parseDouble(input[1]);
}
return myModel.getMap().get(input[1]).execute(newArray(input, 1));
}
public double[] getValue (String[] input, int numVals) {
double[] values = new double[numVals];
String[] intermediate = input;
for(int i = 0; i < numVals; i++) {
values[i] = getValue(intermediate);
intermediate = getIntermediate(intermediate);
}
return values;
}
public String[] getIntermediate (String[] input) {
String[] intArray = null;
for (int i = 0; i < input.length; i++) {
if(!myModel.getMap().containsKey(input[i])) {
intArray = newArray(input, i + 1);
break;
}
}
String[] result = new String[intArray.length + 1];
result[0] = input[0];
for(int j = 1; j < result.length; j++) {
result[j] = intArray[j-1];
}
return result;
}
public String[] getOutput (String[] args) {
String[] result = null;
int count = 0;
if(inputNum == 0) {
return newArray(args, 1);
}
for(int i = 0; i < args.length; i++) {
- if(myModel.getMap().containsKey(args[i])) {
+ if(myModel.getMap().containsKey(args[i]) && inputNum == 1) {
count -= myModel.getMap().get(args[i]).getArgs() - 1;
}
if(!myModel.getMap().containsKey(args[i])) {
count++;
if(count == inputNum) {
result = newArray(args, i + 1);
break;
}
}
}
return result;
}
private String[] newArray (String[] array, int overlap) {
String[] output = new String[array.length - overlap];
for(int i = overlap; i < array.length; i++) {
output[i-overlap] = array[i];
}
return output;
}
public int getArgs () {
return inputNum;
}
}
| true | true | public String[] getOutput (String[] args) {
String[] result = null;
int count = 0;
if(inputNum == 0) {
return newArray(args, 1);
}
for(int i = 0; i < args.length; i++) {
if(myModel.getMap().containsKey(args[i])) {
count -= myModel.getMap().get(args[i]).getArgs() - 1;
}
if(!myModel.getMap().containsKey(args[i])) {
count++;
if(count == inputNum) {
result = newArray(args, i + 1);
break;
}
}
}
return result;
}
| public String[] getOutput (String[] args) {
String[] result = null;
int count = 0;
if(inputNum == 0) {
return newArray(args, 1);
}
for(int i = 0; i < args.length; i++) {
if(myModel.getMap().containsKey(args[i]) && inputNum == 1) {
count -= myModel.getMap().get(args[i]).getArgs() - 1;
}
if(!myModel.getMap().containsKey(args[i])) {
count++;
if(count == inputNum) {
result = newArray(args, i + 1);
break;
}
}
}
return result;
}
|
diff --git a/test/src/org/bouncycastle/math/ec/test/ECPointTest.java b/test/src/org/bouncycastle/math/ec/test/ECPointTest.java
index e0e2daf0..0e12c55b 100644
--- a/test/src/org/bouncycastle/math/ec/test/ECPointTest.java
+++ b/test/src/org/bouncycastle/math/ec/test/ECPointTest.java
@@ -1,441 +1,441 @@
package org.bouncycastle.math.ec.test;
import java.math.BigInteger;
import java.security.SecureRandom;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.bouncycastle.asn1.sec.SECNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECFieldElement;
import org.bouncycastle.math.ec.ECPoint;
/**
* Test class for {@link org.bouncycastle.math.ec.ECPoint ECPoint}. All
* literature values are taken from "Guide to elliptic curve cryptography",
* Darrel Hankerson, Alfred J. Menezes, Scott Vanstone, 2004, Springer-Verlag
* New York, Inc.
*/
public class ECPointTest extends TestCase
{
/**
* The standard curves on which the tests are done
*/
public static final String[] CURVES = { "sect163r2", "sect233r1",
"sect283r1", "sect409r1", "sect571r1", "secp224r1", "secp256r1",
"secp521r1" };
/**
* Random source used to generate random points
*/
private SecureRandom secRand = new SecureRandom();
private ECPointTest.Fp fp = null;
private ECPointTest.F2m f2m = null;
/**
* Nested class containing sample literature values for <code>Fp</code>.
*/
public static class Fp
{
private final BigInteger q = new BigInteger("29");
private final BigInteger a = new BigInteger("4");
private final BigInteger b = new BigInteger("20");
private final ECCurve.Fp curve = new ECCurve.Fp(q, a, b);
private final ECPoint.Fp infinity = new ECPoint.Fp(curve, null, null);
private final int[] pointSource = { 5, 22, 16, 27, 13, 6, 14, 6 };
private ECPoint.Fp[] p = new ECPoint.Fp[pointSource.length / 2];
/**
* Creates the points on the curve with literature values.
*/
private void createPoints()
{
for (int i = 0; i < pointSource.length / 2; i++)
{
ECFieldElement.Fp x = new ECFieldElement.Fp(q, new BigInteger(
Integer.toString(pointSource[2 * i])));
ECFieldElement.Fp y = new ECFieldElement.Fp(q, new BigInteger(
Integer.toString(pointSource[2 * i + 1])));
p[i] = new ECPoint.Fp(curve, x, y);
}
}
}
/**
* Nested class containing sample literature values for <code>F2m</code>.
*/
public static class F2m
{
// Irreducible polynomial for TPB z^4 + z + 1
private final int m = 4;
private final int k1 = 1;
// a = z^3
private final ECFieldElement.F2m aTpb = new ECFieldElement.F2m(m, k1,
new BigInteger("1000", 2));
// b = z^3 + 1
private final ECFieldElement.F2m bTpb = new ECFieldElement.F2m(m, k1,
new BigInteger("1001", 2));
private final ECCurve.F2m curve = new ECCurve.F2m(m, k1, aTpb
.toBigInteger(), bTpb.toBigInteger());
private final ECPoint.F2m infinity = new ECPoint.F2m(curve);
private final String[] pointSource = { "0010", "1111", "1100", "1100",
"0001", "0001", "1011", "0010" };
private ECPoint.F2m[] p = new ECPoint.F2m[pointSource.length / 2];
/**
* Creates the points on the curve with literature values.
*/
private void createPoints()
{
for (int i = 0; i < pointSource.length / 2; i++)
{
ECFieldElement.F2m x = new ECFieldElement.F2m(m, k1,
new BigInteger(pointSource[2 * i], 2));
ECFieldElement.F2m y = new ECFieldElement.F2m(m, k1,
new BigInteger(pointSource[2 * i + 1], 2));
p[i] = new ECPoint.F2m(curve, x, y);
}
}
}
public void setUp()
{
fp = new ECPointTest.Fp();
fp.createPoints();
f2m = new ECPointTest.F2m();
f2m.createPoints();
}
/**
* Tests, if inconsistent points can be created, i.e. points with exactly
* one null coordinate (not permitted).
*/
public void testPointCreationConsistency()
{
try
{
ECPoint.Fp bad = new ECPoint.Fp(fp.curve, new ECFieldElement.Fp(
fp.q, new BigInteger("12")), null);
fail();
}
catch (IllegalArgumentException expected)
{
}
try
{
ECPoint.Fp bad = new ECPoint.Fp(fp.curve, null,
new ECFieldElement.Fp(fp.q, new BigInteger("12")));
fail();
}
catch (IllegalArgumentException expected)
{
}
try
{
- ECPoint.F2m bad = new ECPoint.F2m(fp.curve, new ECFieldElement.F2m(
+ ECPoint.F2m bad = new ECPoint.F2m(f2m.curve, new ECFieldElement.F2m(
f2m.m, f2m.k1, new BigInteger("1011")), null);
fail();
}
catch (IllegalArgumentException expected)
{
}
try
{
- ECPoint.F2m bad = new ECPoint.F2m(fp.curve, null,
+ ECPoint.F2m bad = new ECPoint.F2m(f2m.curve, null,
new ECFieldElement.F2m(f2m.m, f2m.k1,
new BigInteger("1011")));
fail();
}
catch (IllegalArgumentException expected)
{
}
}
/**
* Tests <code>ECPoint.add()</code> against literature values.
*
* @param p
* The array of literature values.
* @param infinity
* The point at infinity on the respective curve.
*/
private void implTestAdd(ECPoint[] p, ECPoint infinity)
{
assertEquals("p0 plus p1 does not equal p2", p[2], p[0].add(p[1]));
assertEquals("p1 plus p0 does not equal p2", p[2], p[1].add(p[0]));
for (int i = 0; i < p.length; i++)
{
assertEquals("Adding infinity failed", p[i], p[i].add(infinity));
assertEquals("Adding to infinity failed", p[i], infinity.add(p[i]));
}
}
/**
* Calls <code>implTestAdd()</code> for <code>Fp</code> and
* <code>F2m</code>.
*/
public void testAdd()
{
implTestAdd(fp.p, fp.infinity);
implTestAdd(f2m.p, f2m.infinity);
}
/**
* Tests <code>ECPoint.twice()</code> against literature values.
*
* @param p
* The array of literature values.
*/
private void implTestTwice(ECPoint[] p)
{
assertEquals("Twice incorrect", p[3], p[0].twice());
assertEquals("Add same point incorrect", p[3], p[0].add(p[0]));
}
/**
* Calls <code>implTestTwice()</code> for <code>Fp</code> and
* <code>F2m</code>.
*/
public void testTwice()
{
implTestTwice(fp.p);
implTestTwice(f2m.p);
}
/**
* Goes through all points on an elliptic curve and checks, if adding a
* point <code>k</code>-times is the same as multiplying the point by
* <code>k</code>, for all <code>k</code>. Should be called for points
* on very small elliptic curves only.
*
* @param p
* The base point on the elliptic curve.
* @param infinity
* The point at infinity on the elliptic curve.
*/
private void implTestAllPoints(ECPoint p, ECPoint infinity)
{
ECPoint adder = infinity;
ECPoint multiplier = infinity;
int i = 1;
do
{
adder = adder.add(p);
multiplier = p.multiply(new BigInteger(Integer.toString(i)));
assertEquals("Results of add() and multiply() are inconsistent "
+ i, adder, multiplier);
i++;
}
while (!(adder.equals(infinity)));
}
/**
* Calls <code>implTestAllPoints()</code> for the small literature curves,
* both for <code>Fp</code> and <code>F2m</code>.
*/
public void testAllPoints()
{
for (int i = 0; i < fp.p.length; i++)
{
implTestAllPoints(fp.p[0], fp.infinity);
}
for (int i = 0; i < f2m.p.length; i++)
{
implTestAllPoints(f2m.p[0], f2m.infinity);
}
}
/**
* Simple shift-and-add multiplication. Serves as reference implementation
* to verify (possibly faster) implementations in
* {@link org.bouncycastle.math.ec.ECPoint ECPoint}.
*
* @param p
* The point to multiply.
* @param k
* The multiplier.
* @return The result of the point multiplication <code>kP</code>.
*/
private ECPoint multiply(ECPoint p, BigInteger k)
{
ECPoint q;
if (p instanceof ECPoint.Fp)
{
q = new ECPoint.Fp(p.getCurve(), null, null);
}
else
{
q = new ECPoint.F2m(p.getCurve(), null, null);
}
int t = k.bitLength();
for (int i = 0; i < t; i++)
{
if (k.testBit(i))
{
q = q.add(p);
}
p = p.twice();
}
return q;
}
/**
* Checks, if the point multiplication algorithm of the given point yields
* the same result as point multiplication done by the reference
* implementation given in <code>multiply()</code>. This method chooses a
* random number by which the given point <code>p</code> is multiplied.
*
* @param p
* The point to be multiplied.
* @param numBits
* The bitlength of the random number by which <code>p</code>
* is multiplied.
*/
private void implTestMultiply(ECPoint p, int numBits)
{
BigInteger k = new BigInteger(numBits, secRand);
ECPoint ref = multiply(p, k);
ECPoint q = p.multiply(k);
assertEquals("ECPoint.multiply is incorrect", ref, q);
}
/**
* Tests <code>ECPoint.add()</code> and <code>ECPoint.subtract()</code>
* for the given point and the given point at infinity.
*
* @param p
* The point on which the tests are performed.
* @param infinity
* The point at infinity on the same curve as <code>p</code>.
*/
private void implTestAddSubtract(ECPoint p, ECPoint infinity)
{
assertEquals("Twice and Add inconsistent", p.twice(), p.add(p));
assertEquals("Twice p - p is not p", p, p.twice().subtract(p));
assertEquals("p - p is not infinity", infinity, p.subtract(p));
assertEquals("p plus infinity is not p", p, p.add(infinity));
assertEquals("infinity plus p is not p", p, infinity.add(p));
assertEquals("infinity plus infinity is not infinity ", infinity,
infinity.add(infinity));
}
/**
* Calls <code>implTestAddSubtract()</code> for literature values, both
* for <code>Fp</code> and <code>F2m</code>.
*/
public void testAddSubtractMultiplySimple()
{
for (int i = 0; i < 4; i++)
{
implTestAddSubtract(fp.p[i], fp.infinity);
implTestAddSubtract(f2m.p[i], f2m.infinity);
// Could be any numBits, 6 is chosen at will
implTestMultiply(fp.p[i], 6);
implTestMultiply(fp.infinity, 6);
implTestMultiply(f2m.p[i], 6);
implTestMultiply(f2m.infinity, 6);
}
}
/**
* Test encoding with and without point compression.
*
* @param p
* The point to be encoded and decoded.
*/
private void implTestEncoding(ECPoint p)
{
// Not Point Compression
ECPoint unCompP;
// Point compression
ECPoint compP;
if (p instanceof ECPoint.Fp)
{
unCompP = new ECPoint.Fp(p.getCurve(), p.getX(), p.getY(), false);
compP = new ECPoint.Fp(p.getCurve(), p.getX(), p.getY(), true);
}
else
{
unCompP = new ECPoint.F2m(p.getCurve(), p.getX(), p.getY(), false);
compP = new ECPoint.F2m(p.getCurve(), p.getX(), p.getY(), true);
}
byte[] unCompBarr = unCompP.getEncoded();
ECPoint decUnComp = p.getCurve().decodePoint(unCompBarr);
assertEquals("Error decoding uncompressed point", p, decUnComp);
byte[] compBarr = compP.getEncoded();
ECPoint decComp = p.getCurve().decodePoint(compBarr);
assertEquals("Error decoding compressed point", p, decComp);
}
/**
* Calls <code>implTestAddSubtract()</code>,
* <code>implTestMultiply</code> and <code>implTestEncoding</code> for
* the standard elliptic curves as given in <code>CURVES</code>.
*/
public void testAddSubtractMultiplyTwiceEncoding()
{
for (int i = 0; i < CURVES.length; i++)
{
X9ECParameters x9ECParameters = SECNamedCurves.getByName(CURVES[i]);
BigInteger n = x9ECParameters.getN();
// The generator is multiplied by random b to get random q
BigInteger b = new BigInteger(n.bitLength(), secRand);
ECPoint g = x9ECParameters.getG();
ECPoint q = g.multiply(b);
// Get point at infinity on the curve
ECPoint infinity;
if (g instanceof ECPoint.Fp)
{
infinity = new ECPoint.Fp(x9ECParameters.getCurve(), null, null);
}
else
{
infinity = new ECPoint.F2m(x9ECParameters.getCurve(), null,
null);
}
implTestAddSubtract(q, infinity);
implTestMultiply(q, n.bitLength());
implTestMultiply(infinity, n.bitLength());
implTestEncoding(q);
}
}
public static Test suite()
{
return new TestSuite(ECPointTest.class);
}
}
| false | true | public void testPointCreationConsistency()
{
try
{
ECPoint.Fp bad = new ECPoint.Fp(fp.curve, new ECFieldElement.Fp(
fp.q, new BigInteger("12")), null);
fail();
}
catch (IllegalArgumentException expected)
{
}
try
{
ECPoint.Fp bad = new ECPoint.Fp(fp.curve, null,
new ECFieldElement.Fp(fp.q, new BigInteger("12")));
fail();
}
catch (IllegalArgumentException expected)
{
}
try
{
ECPoint.F2m bad = new ECPoint.F2m(fp.curve, new ECFieldElement.F2m(
f2m.m, f2m.k1, new BigInteger("1011")), null);
fail();
}
catch (IllegalArgumentException expected)
{
}
try
{
ECPoint.F2m bad = new ECPoint.F2m(fp.curve, null,
new ECFieldElement.F2m(f2m.m, f2m.k1,
new BigInteger("1011")));
fail();
}
catch (IllegalArgumentException expected)
{
}
}
| public void testPointCreationConsistency()
{
try
{
ECPoint.Fp bad = new ECPoint.Fp(fp.curve, new ECFieldElement.Fp(
fp.q, new BigInteger("12")), null);
fail();
}
catch (IllegalArgumentException expected)
{
}
try
{
ECPoint.Fp bad = new ECPoint.Fp(fp.curve, null,
new ECFieldElement.Fp(fp.q, new BigInteger("12")));
fail();
}
catch (IllegalArgumentException expected)
{
}
try
{
ECPoint.F2m bad = new ECPoint.F2m(f2m.curve, new ECFieldElement.F2m(
f2m.m, f2m.k1, new BigInteger("1011")), null);
fail();
}
catch (IllegalArgumentException expected)
{
}
try
{
ECPoint.F2m bad = new ECPoint.F2m(f2m.curve, null,
new ECFieldElement.F2m(f2m.m, f2m.k1,
new BigInteger("1011")));
fail();
}
catch (IllegalArgumentException expected)
{
}
}
|
diff --git a/blocks/sublima-app/src/main/java/com/computas/sublima/app/service/LoginService.java b/blocks/sublima-app/src/main/java/com/computas/sublima/app/service/LoginService.java
index cc1f60d2..8e7d5793 100755
--- a/blocks/sublima-app/src/main/java/com/computas/sublima/app/service/LoginService.java
+++ b/blocks/sublima-app/src/main/java/com/computas/sublima/app/service/LoginService.java
@@ -1,76 +1,76 @@
package com.computas.sublima.app.service;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.cocoon.auth.AuthenticationException;
import com.computas.sublima.query.service.DatabaseService;
/**
* Class for handling of user validation
* @author ewinge
*
*/
public class LoginService {
private DatabaseService dbService = new DatabaseService();
private AdminService adminService = new AdminService();
/**
* Checks if a given username and password are valid
* @param name The username
* @param password The Password
* @return true if the log on information is valid, otherwise false
* @throws AuthenticationException
*/
public boolean validateUser(String name, String password) throws AuthenticationException {
boolean validUser = true;
if (name == null) {
return false;
} else {
if (!name.equalsIgnoreCase("administrator")) {
if (adminService.isInactiveUser(name)) {
validUser = false;
}
}
String sql = "SELECT * FROM DB.DBA.users WHERE username = '" + name + "'";
Statement statement = null;
try {
Connection connection = dbService.getJavaSQLConnection();
if (connection == null) {
throw new AuthenticationException("Could not connect to user database for authentication.");
}
statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
if (!rs.next()) { //empty
validUser = false;
}
if (!adminService.generateSHA1(password).equals(rs.getString("password"))) {
validUser = false;
}
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
- throw new AuthenticationException("An error occured when trying to validate password.");
+ return false;
}
return validUser;
}
}
}
| true | true | public boolean validateUser(String name, String password) throws AuthenticationException {
boolean validUser = true;
if (name == null) {
return false;
} else {
if (!name.equalsIgnoreCase("administrator")) {
if (adminService.isInactiveUser(name)) {
validUser = false;
}
}
String sql = "SELECT * FROM DB.DBA.users WHERE username = '" + name + "'";
Statement statement = null;
try {
Connection connection = dbService.getJavaSQLConnection();
if (connection == null) {
throw new AuthenticationException("Could not connect to user database for authentication.");
}
statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
if (!rs.next()) { //empty
validUser = false;
}
if (!adminService.generateSHA1(password).equals(rs.getString("password"))) {
validUser = false;
}
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
throw new AuthenticationException("An error occured when trying to validate password.");
}
return validUser;
}
}
| public boolean validateUser(String name, String password) throws AuthenticationException {
boolean validUser = true;
if (name == null) {
return false;
} else {
if (!name.equalsIgnoreCase("administrator")) {
if (adminService.isInactiveUser(name)) {
validUser = false;
}
}
String sql = "SELECT * FROM DB.DBA.users WHERE username = '" + name + "'";
Statement statement = null;
try {
Connection connection = dbService.getJavaSQLConnection();
if (connection == null) {
throw new AuthenticationException("Could not connect to user database for authentication.");
}
statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
if (!rs.next()) { //empty
validUser = false;
}
if (!adminService.generateSHA1(password).equals(rs.getString("password"))) {
validUser = false;
}
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return validUser;
}
}
|
diff --git a/Essentials/src/com/earth2me/essentials/EssentialsEcoPlayerListener.java b/Essentials/src/com/earth2me/essentials/EssentialsEcoPlayerListener.java
index afd3f40..528b27d 100644
--- a/Essentials/src/com/earth2me/essentials/EssentialsEcoPlayerListener.java
+++ b/Essentials/src/com/earth2me/essentials/EssentialsEcoPlayerListener.java
@@ -1,147 +1,154 @@
package com.earth2me.essentials;
import java.util.Map;
import org.bukkit.Material;
import org.bukkit.block.Sign;
import org.bukkit.craftbukkit.block.CraftSign;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.inventory.ItemStack;
public class EssentialsEcoPlayerListener extends PlayerListener
{
@Override
public void onPlayerInteract(PlayerInteractEvent event)
{
if (Essentials.getSettings().areSignsDisabled()) return;
if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return;
User user = User.get(event.getPlayer());
String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length());
if (event.getClickedBlock().getType() != Material.WALL_SIGN && event.getClickedBlock().getType() != Material.SIGN_POST)
return;
Sign sign = new CraftSign(event.getClickedBlock());
if (sign.getLine(0).equals("§1[Buy]") && user.isAuthorized("essentials.signs.buy.use"))
{
try
{
int amount = Integer.parseInt(sign.getLine(1));
ItemStack item = ItemDb.get(sign.getLine(2), amount);
int cost = Integer.parseInt(sign.getLine(3).substring(1));
if (user.getMoney() < cost) throw new Exception("You do not have sufficient funds.");
user.takeMoney(cost);
Map<Integer, ItemStack> leftOver = user.getInventory().addItem(item);
for (ItemStack itemStack : leftOver.values()) {
user.getWorld().dropItem(user.getLocation(), itemStack);
}
user.updateInventory();
}
catch (Throwable ex)
{
user.sendMessage("§cError: " + ex.getMessage());
}
return;
}
if (sign.getLine(0).equals("§1[Sell]") && user.isAuthorized("essentials.signs.sell.use"))
{
try
{
int amount = Integer.parseInt(sign.getLine(1));
ItemStack item = ItemDb.get(sign.getLine(2), amount);
int cost = Integer.parseInt(sign.getLine(3).substring(1));
if (!InventoryWorkaround.containsItem(user.getInventory(), true, item)) throw new Exception("You do not have enough items to sell.");
user.giveMoney(cost);
InventoryWorkaround.removeItem(user.getInventory(), true, item);
user.updateInventory();
}
catch (Throwable ex)
{
user.sendMessage("§cError: " + ex.getMessage());
}
return;
}
if (sign.getLine(0).equals("§1[Trade]") && user.isAuthorized("essentials.signs.trade.use"))
{
try
{
String[] l1 = sign.getLines()[1].split("[ :-]+");
String[] l2 = sign.getLines()[2].split("[ :-]+");
boolean m1 = l1[0].matches("\\$[0-9]+");
boolean m2 = l2[0].matches("\\$[0-9]+");
int q1 = Integer.parseInt(m1 ? l1[0].substring(1) : l1[0]);
int q2 = Integer.parseInt(m2 ? l2[0].substring(1) : l2[0]);
int r1 = Integer.parseInt(l1[m1 ? 1 : 2]);
int r2 = Integer.parseInt(l2[m2 ? 1 : 2]);
r1 = r1 - r1 % q1;
r2 = r2 - r2 % q2;
if (q1 < 1 || q2 < 1) throw new Exception("Quantities must be greater than 0.");
ItemStack i1 = m1 || r1 <= 0? null : ItemDb.get(l1[1], r1);
ItemStack qi1 = m1 ? null : ItemDb.get(l1[1], q1);
ItemStack qi2 = m2 ? null : ItemDb.get(l2[1], q2);
if (username.equals(sign.getLines()[3].substring(2)))
{
if (m1)
{
user.giveMoney(r1);
}
else if (i1 != null)
{
- user.getInventory().addItem(i1);
+ Map<Integer, ItemStack> leftOver = user.getInventory().addItem(i1);
+ for (ItemStack itemStack : leftOver.values()) {
+ user.getWorld().dropItem(user.getLocation(), itemStack);
+ }
user.updateInventory();
}
r1 = 0;
sign.setLine(1, (m1 ? "$" + q1 : q1 + " " + l1[1]) + ":" + r1);
}
else
{
if (m1)
{
if (user.getMoney() < q1)
throw new Exception("You do not have sufficient funds.");
}
else
{
if (!InventoryWorkaround.containsItem(user.getInventory(), true, qi1))
throw new Exception("You do not have " + q1 + "x " + l1[1] + ".");
}
if (r2 < q2) throw new Exception("The trade sign does not have enough supply left.");
if (m1)
user.takeMoney(q1);
else
InventoryWorkaround.removeItem(user.getInventory(), true, qi1);
if (m2)
user.giveMoney(q2);
- else
- user.getInventory().addItem(qi2);
+ else {
+ Map<Integer, ItemStack> leftOver = user.getInventory().addItem(qi2);
+ for (ItemStack itemStack : leftOver.values()) {
+ user.getWorld().dropItem(user.getLocation(), itemStack);
+ }
+ }
user.updateInventory();
r1 += q1;
r2 -= q2;
sign.setLine(0, "§1[Trade]");
sign.setLine(1, (m1 ? "$" + q1 : q1 + " " + l1[1]) + ":" + r1);
sign.setLine(2, (m2 ? "$" + q2 : q2 + " " + l2[1]) + ":" + r2);
user.sendMessage("§7Trade completed.");
}
}
catch (Throwable ex)
{
user.sendMessage("§cError: " + ex.getMessage());
}
return;
}
}
}
| false | true | public void onPlayerInteract(PlayerInteractEvent event)
{
if (Essentials.getSettings().areSignsDisabled()) return;
if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return;
User user = User.get(event.getPlayer());
String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length());
if (event.getClickedBlock().getType() != Material.WALL_SIGN && event.getClickedBlock().getType() != Material.SIGN_POST)
return;
Sign sign = new CraftSign(event.getClickedBlock());
if (sign.getLine(0).equals("§1[Buy]") && user.isAuthorized("essentials.signs.buy.use"))
{
try
{
int amount = Integer.parseInt(sign.getLine(1));
ItemStack item = ItemDb.get(sign.getLine(2), amount);
int cost = Integer.parseInt(sign.getLine(3).substring(1));
if (user.getMoney() < cost) throw new Exception("You do not have sufficient funds.");
user.takeMoney(cost);
Map<Integer, ItemStack> leftOver = user.getInventory().addItem(item);
for (ItemStack itemStack : leftOver.values()) {
user.getWorld().dropItem(user.getLocation(), itemStack);
}
user.updateInventory();
}
catch (Throwable ex)
{
user.sendMessage("§cError: " + ex.getMessage());
}
return;
}
if (sign.getLine(0).equals("§1[Sell]") && user.isAuthorized("essentials.signs.sell.use"))
{
try
{
int amount = Integer.parseInt(sign.getLine(1));
ItemStack item = ItemDb.get(sign.getLine(2), amount);
int cost = Integer.parseInt(sign.getLine(3).substring(1));
if (!InventoryWorkaround.containsItem(user.getInventory(), true, item)) throw new Exception("You do not have enough items to sell.");
user.giveMoney(cost);
InventoryWorkaround.removeItem(user.getInventory(), true, item);
user.updateInventory();
}
catch (Throwable ex)
{
user.sendMessage("§cError: " + ex.getMessage());
}
return;
}
if (sign.getLine(0).equals("§1[Trade]") && user.isAuthorized("essentials.signs.trade.use"))
{
try
{
String[] l1 = sign.getLines()[1].split("[ :-]+");
String[] l2 = sign.getLines()[2].split("[ :-]+");
boolean m1 = l1[0].matches("\\$[0-9]+");
boolean m2 = l2[0].matches("\\$[0-9]+");
int q1 = Integer.parseInt(m1 ? l1[0].substring(1) : l1[0]);
int q2 = Integer.parseInt(m2 ? l2[0].substring(1) : l2[0]);
int r1 = Integer.parseInt(l1[m1 ? 1 : 2]);
int r2 = Integer.parseInt(l2[m2 ? 1 : 2]);
r1 = r1 - r1 % q1;
r2 = r2 - r2 % q2;
if (q1 < 1 || q2 < 1) throw new Exception("Quantities must be greater than 0.");
ItemStack i1 = m1 || r1 <= 0? null : ItemDb.get(l1[1], r1);
ItemStack qi1 = m1 ? null : ItemDb.get(l1[1], q1);
ItemStack qi2 = m2 ? null : ItemDb.get(l2[1], q2);
if (username.equals(sign.getLines()[3].substring(2)))
{
if (m1)
{
user.giveMoney(r1);
}
else if (i1 != null)
{
user.getInventory().addItem(i1);
user.updateInventory();
}
r1 = 0;
sign.setLine(1, (m1 ? "$" + q1 : q1 + " " + l1[1]) + ":" + r1);
}
else
{
if (m1)
{
if (user.getMoney() < q1)
throw new Exception("You do not have sufficient funds.");
}
else
{
if (!InventoryWorkaround.containsItem(user.getInventory(), true, qi1))
throw new Exception("You do not have " + q1 + "x " + l1[1] + ".");
}
if (r2 < q2) throw new Exception("The trade sign does not have enough supply left.");
if (m1)
user.takeMoney(q1);
else
InventoryWorkaround.removeItem(user.getInventory(), true, qi1);
if (m2)
user.giveMoney(q2);
else
user.getInventory().addItem(qi2);
user.updateInventory();
r1 += q1;
r2 -= q2;
sign.setLine(0, "§1[Trade]");
sign.setLine(1, (m1 ? "$" + q1 : q1 + " " + l1[1]) + ":" + r1);
sign.setLine(2, (m2 ? "$" + q2 : q2 + " " + l2[1]) + ":" + r2);
user.sendMessage("§7Trade completed.");
}
}
catch (Throwable ex)
{
user.sendMessage("§cError: " + ex.getMessage());
}
return;
}
}
| public void onPlayerInteract(PlayerInteractEvent event)
{
if (Essentials.getSettings().areSignsDisabled()) return;
if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return;
User user = User.get(event.getPlayer());
String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length());
if (event.getClickedBlock().getType() != Material.WALL_SIGN && event.getClickedBlock().getType() != Material.SIGN_POST)
return;
Sign sign = new CraftSign(event.getClickedBlock());
if (sign.getLine(0).equals("§1[Buy]") && user.isAuthorized("essentials.signs.buy.use"))
{
try
{
int amount = Integer.parseInt(sign.getLine(1));
ItemStack item = ItemDb.get(sign.getLine(2), amount);
int cost = Integer.parseInt(sign.getLine(3).substring(1));
if (user.getMoney() < cost) throw new Exception("You do not have sufficient funds.");
user.takeMoney(cost);
Map<Integer, ItemStack> leftOver = user.getInventory().addItem(item);
for (ItemStack itemStack : leftOver.values()) {
user.getWorld().dropItem(user.getLocation(), itemStack);
}
user.updateInventory();
}
catch (Throwable ex)
{
user.sendMessage("§cError: " + ex.getMessage());
}
return;
}
if (sign.getLine(0).equals("§1[Sell]") && user.isAuthorized("essentials.signs.sell.use"))
{
try
{
int amount = Integer.parseInt(sign.getLine(1));
ItemStack item = ItemDb.get(sign.getLine(2), amount);
int cost = Integer.parseInt(sign.getLine(3).substring(1));
if (!InventoryWorkaround.containsItem(user.getInventory(), true, item)) throw new Exception("You do not have enough items to sell.");
user.giveMoney(cost);
InventoryWorkaround.removeItem(user.getInventory(), true, item);
user.updateInventory();
}
catch (Throwable ex)
{
user.sendMessage("§cError: " + ex.getMessage());
}
return;
}
if (sign.getLine(0).equals("§1[Trade]") && user.isAuthorized("essentials.signs.trade.use"))
{
try
{
String[] l1 = sign.getLines()[1].split("[ :-]+");
String[] l2 = sign.getLines()[2].split("[ :-]+");
boolean m1 = l1[0].matches("\\$[0-9]+");
boolean m2 = l2[0].matches("\\$[0-9]+");
int q1 = Integer.parseInt(m1 ? l1[0].substring(1) : l1[0]);
int q2 = Integer.parseInt(m2 ? l2[0].substring(1) : l2[0]);
int r1 = Integer.parseInt(l1[m1 ? 1 : 2]);
int r2 = Integer.parseInt(l2[m2 ? 1 : 2]);
r1 = r1 - r1 % q1;
r2 = r2 - r2 % q2;
if (q1 < 1 || q2 < 1) throw new Exception("Quantities must be greater than 0.");
ItemStack i1 = m1 || r1 <= 0? null : ItemDb.get(l1[1], r1);
ItemStack qi1 = m1 ? null : ItemDb.get(l1[1], q1);
ItemStack qi2 = m2 ? null : ItemDb.get(l2[1], q2);
if (username.equals(sign.getLines()[3].substring(2)))
{
if (m1)
{
user.giveMoney(r1);
}
else if (i1 != null)
{
Map<Integer, ItemStack> leftOver = user.getInventory().addItem(i1);
for (ItemStack itemStack : leftOver.values()) {
user.getWorld().dropItem(user.getLocation(), itemStack);
}
user.updateInventory();
}
r1 = 0;
sign.setLine(1, (m1 ? "$" + q1 : q1 + " " + l1[1]) + ":" + r1);
}
else
{
if (m1)
{
if (user.getMoney() < q1)
throw new Exception("You do not have sufficient funds.");
}
else
{
if (!InventoryWorkaround.containsItem(user.getInventory(), true, qi1))
throw new Exception("You do not have " + q1 + "x " + l1[1] + ".");
}
if (r2 < q2) throw new Exception("The trade sign does not have enough supply left.");
if (m1)
user.takeMoney(q1);
else
InventoryWorkaround.removeItem(user.getInventory(), true, qi1);
if (m2)
user.giveMoney(q2);
else {
Map<Integer, ItemStack> leftOver = user.getInventory().addItem(qi2);
for (ItemStack itemStack : leftOver.values()) {
user.getWorld().dropItem(user.getLocation(), itemStack);
}
}
user.updateInventory();
r1 += q1;
r2 -= q2;
sign.setLine(0, "§1[Trade]");
sign.setLine(1, (m1 ? "$" + q1 : q1 + " " + l1[1]) + ":" + r1);
sign.setLine(2, (m2 ? "$" + q2 : q2 + " " + l2[1]) + ":" + r2);
user.sendMessage("§7Trade completed.");
}
}
catch (Throwable ex)
{
user.sendMessage("§cError: " + ex.getMessage());
}
return;
}
}
|
diff --git a/java/src/com/android/inputmethod/latin/BinaryDictionary.java b/java/src/com/android/inputmethod/latin/BinaryDictionary.java
index cdaffa655..726c44cc1 100644
--- a/java/src/com/android/inputmethod/latin/BinaryDictionary.java
+++ b/java/src/com/android/inputmethod/latin/BinaryDictionary.java
@@ -1,238 +1,238 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.latin;
import android.content.Context;
import android.text.TextUtils;
import android.util.SparseArray;
import com.android.inputmethod.keyboard.ProximityInfo;
import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
/**
* Implements a static, compacted, binary dictionary of standard words.
*/
public class BinaryDictionary extends Dictionary {
public static final String DICTIONARY_PACK_AUTHORITY =
"com.android.inputmethod.latin.dictionarypack";
/**
* There is a difference between what java and native code can handle.
* This value should only be used in BinaryDictionary.java
* It is necessary to keep it at this value because some languages e.g. German have
* really long words.
*/
public static final int MAX_WORD_LENGTH = 48;
public static final int MAX_WORDS = 18;
public static final int MAX_SPACES = 16;
private static final String TAG = "BinaryDictionary";
private static final int MAX_PREDICTIONS = 60;
private static final int MAX_RESULTS = Math.max(MAX_PREDICTIONS, MAX_WORDS);
private static final int TYPED_LETTER_MULTIPLIER = 2;
private long mNativeDict;
private final Locale mLocale;
private final int[] mInputCodePoints = new int[MAX_WORD_LENGTH];
// TODO: The below should be int[] mOutputCodePoints
private final char[] mOutputChars = new char[MAX_WORD_LENGTH * MAX_RESULTS];
private final int[] mSpaceIndices = new int[MAX_SPACES];
private final int[] mOutputScores = new int[MAX_RESULTS];
private final int[] mOutputTypes = new int[MAX_RESULTS];
private final boolean mUseFullEditDistance;
private final SparseArray<DicTraverseSession> mDicTraverseSessions =
new SparseArray<DicTraverseSession>();
private DicTraverseSession getTraverseSession(int traverseSessionId) {
DicTraverseSession traverseSession = mDicTraverseSessions.get(traverseSessionId);
if (traverseSession == null) {
synchronized(mDicTraverseSessions) {
traverseSession = mDicTraverseSessions.get(traverseSessionId);
if (traverseSession == null) {
traverseSession = new DicTraverseSession(mLocale, mNativeDict);
mDicTraverseSessions.put(traverseSessionId, traverseSession);
}
}
}
return traverseSession;
}
/**
* Constructor for the binary dictionary. This is supposed to be called from the
* dictionary factory.
* All implementations should pass null into flagArray, except for testing purposes.
* @param context the context to access the environment from.
* @param filename the name of the file to read through native code.
* @param offset the offset of the dictionary data within the file.
* @param length the length of the binary data.
* @param useFullEditDistance whether to use the full edit distance in suggestions
* @param dictType the dictionary type, as a human-readable string
*/
public BinaryDictionary(final Context context,
final String filename, final long offset, final long length,
final boolean useFullEditDistance, final Locale locale, final String dictType) {
super(dictType);
mLocale = locale;
mUseFullEditDistance = useFullEditDistance;
loadDictionary(filename, offset, length);
}
static {
JniUtils.loadNativeLibrary();
}
private native long openNative(String sourceDir, long dictOffset, long dictSize,
int typedLetterMultiplier, int fullWordMultiplier, int maxWordLength, int maxWords,
int maxPredictions);
private native void closeNative(long dict);
private native int getFrequencyNative(long dict, int[] word);
private native boolean isValidBigramNative(long dict, int[] word1, int[] word2);
private native int getSuggestionsNative(long dict, long proximityInfo, long traverseSession,
int[] xCoordinates, int[] yCoordinates, int[] times, int[] pointerIds,
int[] inputCodePoints, int codesSize, int commitPoint, boolean isGesture,
int[] prevWordCodePointArray, boolean useFullEditDistance, char[] outputChars,
int[] outputScores, int[] outputIndices, int[] outputTypes);
private static native float calcNormalizedScoreNative(char[] before, char[] after, int score);
private static native int editDistanceNative(char[] before, char[] after);
// TODO: Move native dict into session
private final void loadDictionary(String path, long startOffset, long length) {
mNativeDict = openNative(path, startOffset, length, TYPED_LETTER_MULTIPLIER,
FULL_WORD_SCORE_MULTIPLIER, MAX_WORD_LENGTH, MAX_WORDS, MAX_PREDICTIONS);
}
@Override
public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer,
final CharSequence prevWord, final ProximityInfo proximityInfo) {
return getSuggestionsWithSessionId(composer, prevWord, proximityInfo, 0);
}
@Override
public ArrayList<SuggestedWordInfo> getSuggestionsWithSessionId(final WordComposer composer,
final CharSequence prevWord, final ProximityInfo proximityInfo, int sessionId) {
if (!isValidDictionary()) return null;
Arrays.fill(mInputCodePoints, WordComposer.NOT_A_CODE);
// TODO: toLowerCase in the native code
final int[] prevWordCodePointArray = (null == prevWord)
? null : StringUtils.toCodePointArray(prevWord.toString());
final int composerSize = composer.size();
final boolean isGesture = composer.isBatchMode();
if (composerSize <= 1 || !isGesture) {
if (composerSize > MAX_WORD_LENGTH - 1) return null;
for (int i = 0; i < composerSize; i++) {
mInputCodePoints[i] = composer.getCodeAt(i);
}
}
final InputPointers ips = composer.getInputPointers();
final int codesSize = isGesture ? ips.getPointerSize() : composerSize;
// proximityInfo and/or prevWordForBigrams may not be null.
final int tmpCount = getSuggestionsNative(mNativeDict,
proximityInfo.getNativeProximityInfo(), getTraverseSession(sessionId).getSession(),
ips.getXCoordinates(), ips.getYCoordinates(), ips.getTimes(), ips.getPointerIds(),
mInputCodePoints, codesSize, 0 /* commitPoint */, isGesture, prevWordCodePointArray,
mUseFullEditDistance, mOutputChars, mOutputScores, mSpaceIndices, mOutputTypes);
final int count = Math.min(tmpCount, MAX_PREDICTIONS);
final ArrayList<SuggestedWordInfo> suggestions = new ArrayList<SuggestedWordInfo>();
for (int j = 0; j < count; ++j) {
if (composerSize > 0 && mOutputScores[j] < 1) break;
final int start = j * MAX_WORD_LENGTH;
int len = 0;
- while (len < MAX_WORD_LENGTH && mOutputChars[start + len] != 0) {
+ while (len < MAX_WORD_LENGTH && mOutputChars[start + len] != 0) {
++len;
}
if (len > 0) {
final int score = SuggestedWordInfo.KIND_WHITELIST == mOutputTypes[j]
? SuggestedWordInfo.MAX_SCORE : mOutputScores[j];
suggestions.add(new SuggestedWordInfo(
new String(mOutputChars, start, len), score, mOutputTypes[j], mDictType));
}
}
return suggestions;
}
/* package for test */ boolean isValidDictionary() {
return mNativeDict != 0;
}
public static float calcNormalizedScore(String before, String after, int score) {
return calcNormalizedScoreNative(before.toCharArray(), after.toCharArray(), score);
}
public static int editDistance(String before, String after) {
return editDistanceNative(before.toCharArray(), after.toCharArray());
}
@Override
public boolean isValidWord(CharSequence word) {
return getFrequency(word) >= 0;
}
@Override
public int getFrequency(CharSequence word) {
if (word == null) return -1;
int[] codePoints = StringUtils.toCodePointArray(word.toString());
return getFrequencyNative(mNativeDict, codePoints);
}
// TODO: Add a batch process version (isValidBigramMultiple?) to avoid excessive numbers of jni
// calls when checking for changes in an entire dictionary.
public boolean isValidBigram(CharSequence word1, CharSequence word2) {
if (TextUtils.isEmpty(word1) || TextUtils.isEmpty(word2)) return false;
int[] chars1 = StringUtils.toCodePointArray(word1.toString());
int[] chars2 = StringUtils.toCodePointArray(word2.toString());
return isValidBigramNative(mNativeDict, chars1, chars2);
}
@Override
public synchronized void close() {
for (int i = 0; i < mDicTraverseSessions.size(); ++i) {
final int key = mDicTraverseSessions.keyAt(i);
final DicTraverseSession traverseSession = mDicTraverseSessions.get(key);
if (traverseSession != null) {
traverseSession.close();
}
}
closeInternal();
}
private void closeInternal() {
if (mNativeDict != 0) {
closeNative(mNativeDict);
mNativeDict = 0;
}
}
@Override
protected void finalize() throws Throwable {
try {
closeInternal();
} finally {
super.finalize();
}
}
}
| true | true | public ArrayList<SuggestedWordInfo> getSuggestionsWithSessionId(final WordComposer composer,
final CharSequence prevWord, final ProximityInfo proximityInfo, int sessionId) {
if (!isValidDictionary()) return null;
Arrays.fill(mInputCodePoints, WordComposer.NOT_A_CODE);
// TODO: toLowerCase in the native code
final int[] prevWordCodePointArray = (null == prevWord)
? null : StringUtils.toCodePointArray(prevWord.toString());
final int composerSize = composer.size();
final boolean isGesture = composer.isBatchMode();
if (composerSize <= 1 || !isGesture) {
if (composerSize > MAX_WORD_LENGTH - 1) return null;
for (int i = 0; i < composerSize; i++) {
mInputCodePoints[i] = composer.getCodeAt(i);
}
}
final InputPointers ips = composer.getInputPointers();
final int codesSize = isGesture ? ips.getPointerSize() : composerSize;
// proximityInfo and/or prevWordForBigrams may not be null.
final int tmpCount = getSuggestionsNative(mNativeDict,
proximityInfo.getNativeProximityInfo(), getTraverseSession(sessionId).getSession(),
ips.getXCoordinates(), ips.getYCoordinates(), ips.getTimes(), ips.getPointerIds(),
mInputCodePoints, codesSize, 0 /* commitPoint */, isGesture, prevWordCodePointArray,
mUseFullEditDistance, mOutputChars, mOutputScores, mSpaceIndices, mOutputTypes);
final int count = Math.min(tmpCount, MAX_PREDICTIONS);
final ArrayList<SuggestedWordInfo> suggestions = new ArrayList<SuggestedWordInfo>();
for (int j = 0; j < count; ++j) {
if (composerSize > 0 && mOutputScores[j] < 1) break;
final int start = j * MAX_WORD_LENGTH;
int len = 0;
while (len < MAX_WORD_LENGTH && mOutputChars[start + len] != 0) {
++len;
}
if (len > 0) {
final int score = SuggestedWordInfo.KIND_WHITELIST == mOutputTypes[j]
? SuggestedWordInfo.MAX_SCORE : mOutputScores[j];
suggestions.add(new SuggestedWordInfo(
new String(mOutputChars, start, len), score, mOutputTypes[j], mDictType));
}
}
return suggestions;
}
| public ArrayList<SuggestedWordInfo> getSuggestionsWithSessionId(final WordComposer composer,
final CharSequence prevWord, final ProximityInfo proximityInfo, int sessionId) {
if (!isValidDictionary()) return null;
Arrays.fill(mInputCodePoints, WordComposer.NOT_A_CODE);
// TODO: toLowerCase in the native code
final int[] prevWordCodePointArray = (null == prevWord)
? null : StringUtils.toCodePointArray(prevWord.toString());
final int composerSize = composer.size();
final boolean isGesture = composer.isBatchMode();
if (composerSize <= 1 || !isGesture) {
if (composerSize > MAX_WORD_LENGTH - 1) return null;
for (int i = 0; i < composerSize; i++) {
mInputCodePoints[i] = composer.getCodeAt(i);
}
}
final InputPointers ips = composer.getInputPointers();
final int codesSize = isGesture ? ips.getPointerSize() : composerSize;
// proximityInfo and/or prevWordForBigrams may not be null.
final int tmpCount = getSuggestionsNative(mNativeDict,
proximityInfo.getNativeProximityInfo(), getTraverseSession(sessionId).getSession(),
ips.getXCoordinates(), ips.getYCoordinates(), ips.getTimes(), ips.getPointerIds(),
mInputCodePoints, codesSize, 0 /* commitPoint */, isGesture, prevWordCodePointArray,
mUseFullEditDistance, mOutputChars, mOutputScores, mSpaceIndices, mOutputTypes);
final int count = Math.min(tmpCount, MAX_PREDICTIONS);
final ArrayList<SuggestedWordInfo> suggestions = new ArrayList<SuggestedWordInfo>();
for (int j = 0; j < count; ++j) {
if (composerSize > 0 && mOutputScores[j] < 1) break;
final int start = j * MAX_WORD_LENGTH;
int len = 0;
while (len < MAX_WORD_LENGTH && mOutputChars[start + len] != 0) {
++len;
}
if (len > 0) {
final int score = SuggestedWordInfo.KIND_WHITELIST == mOutputTypes[j]
? SuggestedWordInfo.MAX_SCORE : mOutputScores[j];
suggestions.add(new SuggestedWordInfo(
new String(mOutputChars, start, len), score, mOutputTypes[j], mDictType));
}
}
return suggestions;
}
|
diff --git a/src/java/org/jivesoftware/spark/ui/SparkTabHandler.java b/src/java/org/jivesoftware/spark/ui/SparkTabHandler.java
index 595a4521..7f294d6b 100644
--- a/src/java/org/jivesoftware/spark/ui/SparkTabHandler.java
+++ b/src/java/org/jivesoftware/spark/ui/SparkTabHandler.java
@@ -1,67 +1,67 @@
/**
* $Revision: $
* $Date: $
*
* Copyright (C) 2006 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Lesser Public License (LGPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.spark.ui;
import org.jivesoftware.spark.component.tabbedPane.SparkTab;
import org.jivesoftware.spark.ui.rooms.ChatRoomImpl;
import org.jivesoftware.spark.PresenceManager;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.resource.SparkRes;
import java.awt.Component;
import java.awt.Color;
/**
* Allows users to control the decoration of a <code>SparkTab</code> component within the <code>ChatContainer</code>.
*/
public abstract class SparkTabHandler {
public abstract boolean isTabHandled(SparkTab tab, Component component, boolean isSelectedTab, boolean chatFrameFocused);
/**
* Updates the SparkTab to show it is in a stale state.
*
* @param tab the SparkTab.
* @param chatRoom the ChatRoom of the SparkTab.
*/
protected void decorateStaleTab(SparkTab tab, ChatRoom chatRoom) {
tab.setTitleColor(Color.gray);
tab.setTabFont(tab.getDefaultFont());
String jid = ((ChatRoomImpl)chatRoom).getParticipantJID();
Presence presence = PresenceManager.getPresence(jid);
if (!presence.isAvailable()) {
tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_UNAVAILABLE_STALE_IMAGE));
}
else {
Presence.Mode mode = presence.getMode();
- if (mode == Presence.Mode.available) {
+ if (mode == Presence.Mode.available || mode == null) {
tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_AVAILABLE_STALE_IMAGE));
}
else if (mode == Presence.Mode.away) {
tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_AWAY_STALE_IMAGE));
}
else if (mode == Presence.Mode.chat) {
tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_FREE_CHAT_STALE_IMAGE));
}
else if (mode == Presence.Mode.dnd) {
tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_DND_STALE_IMAGE));
}
else if (mode == Presence.Mode.xa) {
tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_DND_STALE_IMAGE));
}
}
tab.validateTab();
}
}
| true | true | protected void decorateStaleTab(SparkTab tab, ChatRoom chatRoom) {
tab.setTitleColor(Color.gray);
tab.setTabFont(tab.getDefaultFont());
String jid = ((ChatRoomImpl)chatRoom).getParticipantJID();
Presence presence = PresenceManager.getPresence(jid);
if (!presence.isAvailable()) {
tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_UNAVAILABLE_STALE_IMAGE));
}
else {
Presence.Mode mode = presence.getMode();
if (mode == Presence.Mode.available) {
tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_AVAILABLE_STALE_IMAGE));
}
else if (mode == Presence.Mode.away) {
tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_AWAY_STALE_IMAGE));
}
else if (mode == Presence.Mode.chat) {
tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_FREE_CHAT_STALE_IMAGE));
}
else if (mode == Presence.Mode.dnd) {
tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_DND_STALE_IMAGE));
}
else if (mode == Presence.Mode.xa) {
tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_DND_STALE_IMAGE));
}
}
tab.validateTab();
}
| protected void decorateStaleTab(SparkTab tab, ChatRoom chatRoom) {
tab.setTitleColor(Color.gray);
tab.setTabFont(tab.getDefaultFont());
String jid = ((ChatRoomImpl)chatRoom).getParticipantJID();
Presence presence = PresenceManager.getPresence(jid);
if (!presence.isAvailable()) {
tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_UNAVAILABLE_STALE_IMAGE));
}
else {
Presence.Mode mode = presence.getMode();
if (mode == Presence.Mode.available || mode == null) {
tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_AVAILABLE_STALE_IMAGE));
}
else if (mode == Presence.Mode.away) {
tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_AWAY_STALE_IMAGE));
}
else if (mode == Presence.Mode.chat) {
tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_FREE_CHAT_STALE_IMAGE));
}
else if (mode == Presence.Mode.dnd) {
tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_DND_STALE_IMAGE));
}
else if (mode == Presence.Mode.xa) {
tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_DND_STALE_IMAGE));
}
}
tab.validateTab();
}
|
diff --git a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/DefaultMessageHandler.java b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/DefaultMessageHandler.java
index cb450f1..2c4929b 100644
--- a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/DefaultMessageHandler.java
+++ b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/DefaultMessageHandler.java
@@ -1,198 +1,198 @@
/**
* 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.camel.component.sjms.consumer;
import static org.apache.camel.util.ObjectHelper.wrapRuntimeCamelException;
import java.util.concurrent.ExecutorService;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import org.apache.camel.AsyncProcessor;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.component.sjms.jms.JmsMessageHelper;
import org.apache.camel.component.sjms.jms.SessionAcknowledgementType;
import org.apache.camel.impl.DefaultExchange;
import org.apache.camel.spi.Synchronization;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* TODO Add Class documentation for DefaultMessageHandler
*
* @author sully6768
*/
public abstract class DefaultMessageHandler implements MessageListener {
protected final Logger log = LoggerFactory.getLogger(getClass());
private final ExecutorService executor;
private Endpoint endpoint;
private AsyncProcessor processor;
private Session session;
private boolean transacted = false;
private SessionAcknowledgementType acknowledgementType = SessionAcknowledgementType.AUTO_ACKNOWLEDGE;
private boolean synchronous = true;
private Destination namedReplyTo;
private Synchronization synchronization;
private boolean topic = false;
public DefaultMessageHandler(Endpoint endpoint, ExecutorService executor) {
this(endpoint, executor, null);
}
public DefaultMessageHandler(Endpoint endpoint, ExecutorService executor, Synchronization synchronization) {
super();
this.synchronization = synchronization;
this.endpoint = endpoint;
this.executor = executor;
}
@Override
public void onMessage(Message message) {
handleMessage(message);
}
/**
* @param message
*/
private void handleMessage(Message message) {
RuntimeCamelException rce = null;
try {
final DefaultExchange exchange = (DefaultExchange) JmsMessageHelper
.createExchange(message, getEndpoint());
if (log.isDebugEnabled()) {
log.debug("Processing Exchange.id:{}", exchange.getExchangeId());
}
if (isTransacted() && synchronization != null) {
exchange.addOnCompletion(synchronization);
}
try {
if (isTransacted() || isSynchronous()) {
if (log.isDebugEnabled()) {
log.debug(
- " Sending message asynchronously: {}", exchange.getIn().getBody());
+ " Handling synchronous message: {}", exchange.getIn().getBody());
}
doHandleMessage(exchange);
} else {
if (log.isDebugEnabled()) {
log.debug(
- " Sending message asynchronously: {}", exchange.getIn().getBody());
+ " Handling asynchronous message: {}", exchange.getIn().getBody());
}
executor.execute(new Runnable() {
@Override
public void run() {
try {
doHandleMessage(exchange);
} catch (Exception e) {
ObjectHelper.wrapRuntimeCamelException(e);
}
}
});
}
} catch (Exception e) {
if (exchange != null) {
if (exchange.getException() == null) {
exchange.setException(e);
} else {
throw e;
}
}
}
} catch (Exception e) {
rce = wrapRuntimeCamelException(e);
} finally {
if (rce != null) {
throw rce;
}
}
}
public abstract void doHandleMessage(final Exchange exchange);
public abstract void close();
public void setTransacted(boolean transacted) {
this.transacted = transacted;
}
public boolean isTransacted() {
return transacted;
}
public Endpoint getEndpoint() {
return endpoint;
}
public AsyncProcessor getProcessor() {
return processor;
}
public void setProcessor(AsyncProcessor processor) {
this.processor = processor;
}
public SessionAcknowledgementType getAcknowledgementType() {
return acknowledgementType;
}
public void setAcknowledgementType(
SessionAcknowledgementType acknowledgementType) {
this.acknowledgementType = acknowledgementType;
}
public void setSession(Session session) {
this.session = session;
}
public Session getSession() {
return session;
}
public void setSynchronous(boolean async) {
this.synchronous = async;
}
public boolean isSynchronous() {
return synchronous;
}
public void setNamedReplyTo(Destination namedReplyToDestination) {
this.namedReplyTo = namedReplyToDestination;
}
public Destination getNamedReplyTo() {
return namedReplyTo;
}
public void setTopic(boolean topic) {
this.topic = topic;
}
public boolean isTopic() {
return topic;
}
}
| false | true | private void handleMessage(Message message) {
RuntimeCamelException rce = null;
try {
final DefaultExchange exchange = (DefaultExchange) JmsMessageHelper
.createExchange(message, getEndpoint());
if (log.isDebugEnabled()) {
log.debug("Processing Exchange.id:{}", exchange.getExchangeId());
}
if (isTransacted() && synchronization != null) {
exchange.addOnCompletion(synchronization);
}
try {
if (isTransacted() || isSynchronous()) {
if (log.isDebugEnabled()) {
log.debug(
" Sending message asynchronously: {}", exchange.getIn().getBody());
}
doHandleMessage(exchange);
} else {
if (log.isDebugEnabled()) {
log.debug(
" Sending message asynchronously: {}", exchange.getIn().getBody());
}
executor.execute(new Runnable() {
@Override
public void run() {
try {
doHandleMessage(exchange);
} catch (Exception e) {
ObjectHelper.wrapRuntimeCamelException(e);
}
}
});
}
} catch (Exception e) {
if (exchange != null) {
if (exchange.getException() == null) {
exchange.setException(e);
} else {
throw e;
}
}
}
} catch (Exception e) {
rce = wrapRuntimeCamelException(e);
} finally {
if (rce != null) {
throw rce;
}
}
}
| private void handleMessage(Message message) {
RuntimeCamelException rce = null;
try {
final DefaultExchange exchange = (DefaultExchange) JmsMessageHelper
.createExchange(message, getEndpoint());
if (log.isDebugEnabled()) {
log.debug("Processing Exchange.id:{}", exchange.getExchangeId());
}
if (isTransacted() && synchronization != null) {
exchange.addOnCompletion(synchronization);
}
try {
if (isTransacted() || isSynchronous()) {
if (log.isDebugEnabled()) {
log.debug(
" Handling synchronous message: {}", exchange.getIn().getBody());
}
doHandleMessage(exchange);
} else {
if (log.isDebugEnabled()) {
log.debug(
" Handling asynchronous message: {}", exchange.getIn().getBody());
}
executor.execute(new Runnable() {
@Override
public void run() {
try {
doHandleMessage(exchange);
} catch (Exception e) {
ObjectHelper.wrapRuntimeCamelException(e);
}
}
});
}
} catch (Exception e) {
if (exchange != null) {
if (exchange.getException() == null) {
exchange.setException(e);
} else {
throw e;
}
}
}
} catch (Exception e) {
rce = wrapRuntimeCamelException(e);
} finally {
if (rce != null) {
throw rce;
}
}
}
|
diff --git a/backend/src/com/mymed/controller/core/manager/AbstractManager.java b/backend/src/com/mymed/controller/core/manager/AbstractManager.java
index 48dce4071..83e503d07 100644
--- a/backend/src/com/mymed/controller/core/manager/AbstractManager.java
+++ b/backend/src/com/mymed/controller/core/manager/AbstractManager.java
@@ -1,113 +1,112 @@
package com.mymed.controller.core.manager;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Map.Entry;
import javassist.Modifier;
import com.mymed.controller.core.exception.InternalBackEndException;
import com.mymed.controller.core.manager.storage.IStorageManager;
import com.mymed.model.data.AbstractMBean;
import com.mymed.utils.ClassType;
/**
*
* @author lvanni
*
*/
public abstract class AbstractManager extends ManagerValues {
private static final int PRIV_FIN = Modifier.PRIVATE + Modifier.FINAL;
private static final int PRIV_STAT_FIN = Modifier.PRIVATE + Modifier.STATIC + Modifier.FINAL;
protected IStorageManager storageManager;
public AbstractManager(final IStorageManager storageManager) {
this.storageManager = storageManager;
}
/**
* Introspection
*
* @param mbean
* @param args
* @return
* @throws InternalBackEndException
*/
public AbstractMBean introspection(final AbstractMBean mbean, final Map<byte[], byte[]> args)
throws InternalBackEndException {
try {
for (final Entry<byte[], byte[]> arg : args.entrySet()) {
try {
final Field field = mbean.getClass().getDeclaredField(new String(arg.getKey(), "UTF8"));
/*
* We check the value of the modifiers of the field: if the
* field is private and final, or private static and final,
* we skip it.
*/
final int modifiers = field.getModifiers();
if (modifiers == PRIV_FIN || modifiers == PRIV_STAT_FIN) {
continue;
}
final ClassType classType = ClassType.inferType(field.getGenericType());
final String setterName = createSetterName(field, classType);
final Method method = mbean.getClass().getMethod(setterName, classType.getPrimitiveType());
final Object argument = ClassType.objectFromClassType(classType, arg.getValue());
method.invoke(mbean, argument);
} catch (final NoSuchFieldException e) {
- System.out
- .println("\nWARNING: " + new String(arg.getKey(), "UTF8") + " is not PRIV_FIN bean field");
+ System.out.println("\nWARNING: " + new String(arg.getKey(), "UTF8") + " is not a bean field");
}
}
} catch (final Exception ex) {
throw new InternalBackEndException(ex);
}
return mbean;
}
/**
* Create the name of the setter method based on the field name and its
* class.
* <p>
* This is particularly useful due to the fact that boolean fields does not
* have a normal setter name.
*
* @param field
* the filed we want the setter method of
* @param classType
* the class type of the field
* @return the name of the setter method
*/
private String createSetterName(final Field field, final ClassType classType) {
final StringBuilder setterName = new StringBuilder(20);
final String fieldName = field.getName();
setterName.append("set");
String subName = fieldName;
/*
* Check that the boolean field we are on does start with 'is'. This
* should be the default prefix for boolean fields. In this case the
* setter method will be based on the field name, but without the 'is'
* prefix.
*/
if (classType.equals(ClassType.BOOL)) {
if (fieldName.startsWith("is")) {
subName = fieldName.substring(2, fieldName.length());
}
}
setterName.append(subName.substring(0, 1).toUpperCase());
setterName.append(subName.substring(1));
setterName.trimToSize();
return setterName.toString();
}
}
| true | true | public AbstractMBean introspection(final AbstractMBean mbean, final Map<byte[], byte[]> args)
throws InternalBackEndException {
try {
for (final Entry<byte[], byte[]> arg : args.entrySet()) {
try {
final Field field = mbean.getClass().getDeclaredField(new String(arg.getKey(), "UTF8"));
/*
* We check the value of the modifiers of the field: if the
* field is private and final, or private static and final,
* we skip it.
*/
final int modifiers = field.getModifiers();
if (modifiers == PRIV_FIN || modifiers == PRIV_STAT_FIN) {
continue;
}
final ClassType classType = ClassType.inferType(field.getGenericType());
final String setterName = createSetterName(field, classType);
final Method method = mbean.getClass().getMethod(setterName, classType.getPrimitiveType());
final Object argument = ClassType.objectFromClassType(classType, arg.getValue());
method.invoke(mbean, argument);
} catch (final NoSuchFieldException e) {
System.out
.println("\nWARNING: " + new String(arg.getKey(), "UTF8") + " is not PRIV_FIN bean field");
}
}
} catch (final Exception ex) {
throw new InternalBackEndException(ex);
}
return mbean;
}
| public AbstractMBean introspection(final AbstractMBean mbean, final Map<byte[], byte[]> args)
throws InternalBackEndException {
try {
for (final Entry<byte[], byte[]> arg : args.entrySet()) {
try {
final Field field = mbean.getClass().getDeclaredField(new String(arg.getKey(), "UTF8"));
/*
* We check the value of the modifiers of the field: if the
* field is private and final, or private static and final,
* we skip it.
*/
final int modifiers = field.getModifiers();
if (modifiers == PRIV_FIN || modifiers == PRIV_STAT_FIN) {
continue;
}
final ClassType classType = ClassType.inferType(field.getGenericType());
final String setterName = createSetterName(field, classType);
final Method method = mbean.getClass().getMethod(setterName, classType.getPrimitiveType());
final Object argument = ClassType.objectFromClassType(classType, arg.getValue());
method.invoke(mbean, argument);
} catch (final NoSuchFieldException e) {
System.out.println("\nWARNING: " + new String(arg.getKey(), "UTF8") + " is not a bean field");
}
}
} catch (final Exception ex) {
throw new InternalBackEndException(ex);
}
return mbean;
}
|
diff --git a/src/main/java/com/mike724/email/EmailCommands.java b/src/main/java/com/mike724/email/EmailCommands.java
index 9891177..012bd58 100644
--- a/src/main/java/com/mike724/email/EmailCommands.java
+++ b/src/main/java/com/mike724/email/EmailCommands.java
@@ -1,234 +1,235 @@
/*
This file is part of Email.
Email 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.
Email 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 Email. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mike724.email;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.plugin.PluginDescriptionFile;
public class EmailCommands implements CommandExecutor {
private Email plugin;
public EmailCommands(Email plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(cmd.getName().equalsIgnoreCase("email")) {
if(args.length == 0) {
sender.sendMessage(ChatColor.AQUA+"Use '/email help' for help");
return true;
}
boolean isPlayer = sender instanceof Player;
String msgUseHelp = ChatColor.RED+"Invalid command usage or no permission, use '/email help' for help.";
String opt = args[0];
if(opt.equalsIgnoreCase("help")) {
sender.sendMessage(ChatColor.GREEN+"~~~ Start Email help ~~~");
sender.sendMessage(ChatColor.AQUA+"To view plugin information: ");
sender.sendMessage(ChatColor.YELLOW+"/email info");
if(sender.hasPermission("Email.set")) {
sender.sendMessage(ChatColor.AQUA+"To set your email (players only): ");
sender.sendMessage(ChatColor.YELLOW+"/email set [email protected]");
}
if(sender.hasPermission("Email.set.others")) {
sender.sendMessage(ChatColor.AQUA+"To set a player's email: ");
sender.sendMessage(ChatColor.YELLOW+"/email set <player name> [email protected]");
}
if(sender.hasPermission("Email.remove")) {
sender.sendMessage(ChatColor.AQUA+"To remove your email (players only): ");
sender.sendMessage(ChatColor.YELLOW+"/email remove");
}
if(sender.hasPermission("Email.remove.others")) {
sender.sendMessage(ChatColor.AQUA+"To remove a player's email: ");
sender.sendMessage(ChatColor.YELLOW+"/email remove <player name>");
}
if(sender.hasPermission("Email.view")) {
sender.sendMessage(ChatColor.AQUA+"To view your email (players only): ");
sender.sendMessage(ChatColor.YELLOW+"/email view");
}
if(sender.hasPermission("Email.view.others")) {
sender.sendMessage(ChatColor.AQUA+"To view a player's email: ");
sender.sendMessage(ChatColor.YELLOW+"/email view <player name>");
}
if(sender.hasPermission("Email.send")) {
sender.sendMessage(ChatColor.AQUA+"To send an email to a specific player: ");
sender.sendMessage(ChatColor.YELLOW+"/email send <player name>");
sender.sendMessage(ChatColor.YELLOW+"(must be holding a written book)");
}
if(sender.hasPermission("Email.send.all")) {
sender.sendMessage(ChatColor.AQUA+"To send an email to a ALL players: ");
sender.sendMessage(ChatColor.YELLOW+"/email send");
sender.sendMessage(ChatColor.YELLOW+"(must be holding a written book)");
}
if(sender.hasPermission("Email.export")) {
sender.sendMessage(ChatColor.AQUA+"To export emails to a text file: ");
sender.sendMessage(ChatColor.YELLOW+"/email export <type, either 1 or 2>");
sender.sendMessage(ChatColor.YELLOW+"Type 1 will output names and emails, type 2 will only export emails.");
}
sender.sendMessage(ChatColor.GREEN+"~~~ End Email help ~~~");
return true;
} else if(opt.equalsIgnoreCase("set")) {
if(args.length == 2 && isPlayer && sender.hasPermission("Email.set")) {
boolean result = plugin.emails.setPlayerEmail(sender.getName(), args[1]);
sender.sendMessage((result) ? ChatColor.GREEN+"Email set" : ChatColor.RED+"Invalid email");
return true;
} else if(args.length == 3 && sender.hasPermission("Email.set.others")) {
boolean result = plugin.emails.setPlayerEmail(args[1], args[2]);
sender.sendMessage((result) ? ChatColor.GREEN+"Email set" : ChatColor.RED+"Invalid email");
return true;
} else {
sender.sendMessage(msgUseHelp);
return true;
}
} else if(opt.equalsIgnoreCase("remove")) {
if(args.length == 1 && isPlayer && sender.hasPermission("Email.remove")) {
plugin.emails.removePlayerEmail(sender.getName());
sender.sendMessage(ChatColor.GREEN+"Email removed");
return true;
} else if(args.length == 2 && sender.hasPermission("Email.remove.others")) {
plugin.emails.removePlayerEmail(args[1]);
sender.sendMessage(ChatColor.GREEN+"Email removed");
return true;
} else {
sender.sendMessage(msgUseHelp);
return true;
}
} else if(opt.equalsIgnoreCase("view")) {
if(args.length == 1 && isPlayer && sender.hasPermission("Email.view")) {
String email = plugin.emails.getPlayerEmail(sender.getName());
if(email != null) {
sender.sendMessage(ChatColor.GREEN+"The email is: "+ChatColor.YELLOW+email);
} else {
sender.sendMessage(ChatColor.RED+"You don't have an email set");
}
return true;
} else if(args.length == 2 && sender.hasPermission("Email.view.others")) {
String email = plugin.emails.getPlayerEmail(args[1]);
if(email != null) {
sender.sendMessage(ChatColor.GREEN+"The email is: "+ChatColor.YELLOW+email);
} else {
sender.sendMessage(ChatColor.RED+"That player does not have an email set");
}
return true;
} else {
sender.sendMessage(msgUseHelp);
return true;
}
} else if(opt.equalsIgnoreCase("send")) {
if(plugin.mailman == null) {
sender.sendMessage(ChatColor.RED+"Email sending is disabled on this server!");
return true;
}
if(!isPlayer) {
sender.sendMessage(ChatColor.RED+"Sorry, only players can do that.");
return true;
}
- if(args.length != 1 || args.length != 2) {
+ if(!(args.length == 1 || args.length == 2)) {
sender.sendMessage(msgUseHelp);
return true;
}
boolean allPlayers = args.length == 1;
if((allPlayers && sender.hasPermission("Email.send.all")) || (!allPlayers && sender.hasPermission("Email.send"))) {
//Get itemstack in hand, quit if it's not a written book
Player p = (Player)sender;
ItemStack hand = p.getItemInHand();
if(hand.getType() != Material.WRITTEN_BOOK) {
sender.sendMessage(ChatColor.RED+"You must be holding a written book to do that!");
return true;
}
//Set appropriate recipient string
//If all players, then toEmail will be a CSV string (ex. [email protected],[email protected])
String toEmail = "";
if(allPlayers) {
String[] emailArray = plugin.emails.getAllPlayerEmails();
for(String email : emailArray) {
toEmail += ","+email;
}
toEmail = toEmail.substring(1);
} else {
toEmail = plugin.emails.getPlayerEmail(args[1]);
}
//Can't have that!
if(toEmail.isEmpty()) {
sender.sendMessage(ChatColor.RED+"That player has not set their email!");
return true;
}
//Get the book's metadata
BookMeta data = (BookMeta)hand.getItemMeta();
//The email's subject
String emailSubject = data.getTitle();
//The email's body
String emailContent = "";
for(String page : data.getPages()) {
emailContent += " "+page;
}
//Remove the extra space
emailContent = emailContent.substring(1);
//Send the email! :)
Bukkit.getScheduler().runTaskAsynchronously(plugin, new EmailTask(plugin.mailman, toEmail, emailSubject, emailContent));
+ sender.sendMessage(ChatColor.GREEN+"Email is being sent! It should be received soon.");
} else {
sender.sendMessage(msgUseHelp);
return true;
}
} else if(opt.equalsIgnoreCase("export")) {
if(args.length == 2 && sender.hasPermission("Email.export")) {
if(args[1].equalsIgnoreCase("1")) {
plugin.emails.export(1);
sender.sendMessage(ChatColor.GREEN+"Emails and names exported");
return true;
} else if(args[1].equalsIgnoreCase("2")) {
plugin.emails.export(2);
sender.sendMessage(ChatColor.GREEN+"Emails exported");
return true;
} else {
sender.sendMessage(ChatColor.RED+"Incorrect type, must be 1 or 2.");
}
} else {
sender.sendMessage(msgUseHelp);
return true;
}
} else if(opt.equalsIgnoreCase("info")) {
PluginDescriptionFile pdf = plugin.getDescription();
String name = ChatColor.YELLOW+pdf.getName()+ChatColor.AQUA;
String version = ChatColor.YELLOW+pdf.getVersion()+ChatColor.AQUA;
String author = ChatColor.YELLOW+pdf.getAuthors().get(0)+ChatColor.AQUA;
sender.sendMessage(name+" version "+version+" by "+author+" is "+ChatColor.GREEN+"running.");
return true;
}
sender.sendMessage(msgUseHelp);
return true;
}
return false;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(cmd.getName().equalsIgnoreCase("email")) {
if(args.length == 0) {
sender.sendMessage(ChatColor.AQUA+"Use '/email help' for help");
return true;
}
boolean isPlayer = sender instanceof Player;
String msgUseHelp = ChatColor.RED+"Invalid command usage or no permission, use '/email help' for help.";
String opt = args[0];
if(opt.equalsIgnoreCase("help")) {
sender.sendMessage(ChatColor.GREEN+"~~~ Start Email help ~~~");
sender.sendMessage(ChatColor.AQUA+"To view plugin information: ");
sender.sendMessage(ChatColor.YELLOW+"/email info");
if(sender.hasPermission("Email.set")) {
sender.sendMessage(ChatColor.AQUA+"To set your email (players only): ");
sender.sendMessage(ChatColor.YELLOW+"/email set [email protected]");
}
if(sender.hasPermission("Email.set.others")) {
sender.sendMessage(ChatColor.AQUA+"To set a player's email: ");
sender.sendMessage(ChatColor.YELLOW+"/email set <player name> [email protected]");
}
if(sender.hasPermission("Email.remove")) {
sender.sendMessage(ChatColor.AQUA+"To remove your email (players only): ");
sender.sendMessage(ChatColor.YELLOW+"/email remove");
}
if(sender.hasPermission("Email.remove.others")) {
sender.sendMessage(ChatColor.AQUA+"To remove a player's email: ");
sender.sendMessage(ChatColor.YELLOW+"/email remove <player name>");
}
if(sender.hasPermission("Email.view")) {
sender.sendMessage(ChatColor.AQUA+"To view your email (players only): ");
sender.sendMessage(ChatColor.YELLOW+"/email view");
}
if(sender.hasPermission("Email.view.others")) {
sender.sendMessage(ChatColor.AQUA+"To view a player's email: ");
sender.sendMessage(ChatColor.YELLOW+"/email view <player name>");
}
if(sender.hasPermission("Email.send")) {
sender.sendMessage(ChatColor.AQUA+"To send an email to a specific player: ");
sender.sendMessage(ChatColor.YELLOW+"/email send <player name>");
sender.sendMessage(ChatColor.YELLOW+"(must be holding a written book)");
}
if(sender.hasPermission("Email.send.all")) {
sender.sendMessage(ChatColor.AQUA+"To send an email to a ALL players: ");
sender.sendMessage(ChatColor.YELLOW+"/email send");
sender.sendMessage(ChatColor.YELLOW+"(must be holding a written book)");
}
if(sender.hasPermission("Email.export")) {
sender.sendMessage(ChatColor.AQUA+"To export emails to a text file: ");
sender.sendMessage(ChatColor.YELLOW+"/email export <type, either 1 or 2>");
sender.sendMessage(ChatColor.YELLOW+"Type 1 will output names and emails, type 2 will only export emails.");
}
sender.sendMessage(ChatColor.GREEN+"~~~ End Email help ~~~");
return true;
} else if(opt.equalsIgnoreCase("set")) {
if(args.length == 2 && isPlayer && sender.hasPermission("Email.set")) {
boolean result = plugin.emails.setPlayerEmail(sender.getName(), args[1]);
sender.sendMessage((result) ? ChatColor.GREEN+"Email set" : ChatColor.RED+"Invalid email");
return true;
} else if(args.length == 3 && sender.hasPermission("Email.set.others")) {
boolean result = plugin.emails.setPlayerEmail(args[1], args[2]);
sender.sendMessage((result) ? ChatColor.GREEN+"Email set" : ChatColor.RED+"Invalid email");
return true;
} else {
sender.sendMessage(msgUseHelp);
return true;
}
} else if(opt.equalsIgnoreCase("remove")) {
if(args.length == 1 && isPlayer && sender.hasPermission("Email.remove")) {
plugin.emails.removePlayerEmail(sender.getName());
sender.sendMessage(ChatColor.GREEN+"Email removed");
return true;
} else if(args.length == 2 && sender.hasPermission("Email.remove.others")) {
plugin.emails.removePlayerEmail(args[1]);
sender.sendMessage(ChatColor.GREEN+"Email removed");
return true;
} else {
sender.sendMessage(msgUseHelp);
return true;
}
} else if(opt.equalsIgnoreCase("view")) {
if(args.length == 1 && isPlayer && sender.hasPermission("Email.view")) {
String email = plugin.emails.getPlayerEmail(sender.getName());
if(email != null) {
sender.sendMessage(ChatColor.GREEN+"The email is: "+ChatColor.YELLOW+email);
} else {
sender.sendMessage(ChatColor.RED+"You don't have an email set");
}
return true;
} else if(args.length == 2 && sender.hasPermission("Email.view.others")) {
String email = plugin.emails.getPlayerEmail(args[1]);
if(email != null) {
sender.sendMessage(ChatColor.GREEN+"The email is: "+ChatColor.YELLOW+email);
} else {
sender.sendMessage(ChatColor.RED+"That player does not have an email set");
}
return true;
} else {
sender.sendMessage(msgUseHelp);
return true;
}
} else if(opt.equalsIgnoreCase("send")) {
if(plugin.mailman == null) {
sender.sendMessage(ChatColor.RED+"Email sending is disabled on this server!");
return true;
}
if(!isPlayer) {
sender.sendMessage(ChatColor.RED+"Sorry, only players can do that.");
return true;
}
if(args.length != 1 || args.length != 2) {
sender.sendMessage(msgUseHelp);
return true;
}
boolean allPlayers = args.length == 1;
if((allPlayers && sender.hasPermission("Email.send.all")) || (!allPlayers && sender.hasPermission("Email.send"))) {
//Get itemstack in hand, quit if it's not a written book
Player p = (Player)sender;
ItemStack hand = p.getItemInHand();
if(hand.getType() != Material.WRITTEN_BOOK) {
sender.sendMessage(ChatColor.RED+"You must be holding a written book to do that!");
return true;
}
//Set appropriate recipient string
//If all players, then toEmail will be a CSV string (ex. [email protected],[email protected])
String toEmail = "";
if(allPlayers) {
String[] emailArray = plugin.emails.getAllPlayerEmails();
for(String email : emailArray) {
toEmail += ","+email;
}
toEmail = toEmail.substring(1);
} else {
toEmail = plugin.emails.getPlayerEmail(args[1]);
}
//Can't have that!
if(toEmail.isEmpty()) {
sender.sendMessage(ChatColor.RED+"That player has not set their email!");
return true;
}
//Get the book's metadata
BookMeta data = (BookMeta)hand.getItemMeta();
//The email's subject
String emailSubject = data.getTitle();
//The email's body
String emailContent = "";
for(String page : data.getPages()) {
emailContent += " "+page;
}
//Remove the extra space
emailContent = emailContent.substring(1);
//Send the email! :)
Bukkit.getScheduler().runTaskAsynchronously(plugin, new EmailTask(plugin.mailman, toEmail, emailSubject, emailContent));
} else {
sender.sendMessage(msgUseHelp);
return true;
}
} else if(opt.equalsIgnoreCase("export")) {
if(args.length == 2 && sender.hasPermission("Email.export")) {
if(args[1].equalsIgnoreCase("1")) {
plugin.emails.export(1);
sender.sendMessage(ChatColor.GREEN+"Emails and names exported");
return true;
} else if(args[1].equalsIgnoreCase("2")) {
plugin.emails.export(2);
sender.sendMessage(ChatColor.GREEN+"Emails exported");
return true;
} else {
sender.sendMessage(ChatColor.RED+"Incorrect type, must be 1 or 2.");
}
} else {
sender.sendMessage(msgUseHelp);
return true;
}
} else if(opt.equalsIgnoreCase("info")) {
PluginDescriptionFile pdf = plugin.getDescription();
String name = ChatColor.YELLOW+pdf.getName()+ChatColor.AQUA;
String version = ChatColor.YELLOW+pdf.getVersion()+ChatColor.AQUA;
String author = ChatColor.YELLOW+pdf.getAuthors().get(0)+ChatColor.AQUA;
sender.sendMessage(name+" version "+version+" by "+author+" is "+ChatColor.GREEN+"running.");
return true;
}
sender.sendMessage(msgUseHelp);
return true;
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(cmd.getName().equalsIgnoreCase("email")) {
if(args.length == 0) {
sender.sendMessage(ChatColor.AQUA+"Use '/email help' for help");
return true;
}
boolean isPlayer = sender instanceof Player;
String msgUseHelp = ChatColor.RED+"Invalid command usage or no permission, use '/email help' for help.";
String opt = args[0];
if(opt.equalsIgnoreCase("help")) {
sender.sendMessage(ChatColor.GREEN+"~~~ Start Email help ~~~");
sender.sendMessage(ChatColor.AQUA+"To view plugin information: ");
sender.sendMessage(ChatColor.YELLOW+"/email info");
if(sender.hasPermission("Email.set")) {
sender.sendMessage(ChatColor.AQUA+"To set your email (players only): ");
sender.sendMessage(ChatColor.YELLOW+"/email set [email protected]");
}
if(sender.hasPermission("Email.set.others")) {
sender.sendMessage(ChatColor.AQUA+"To set a player's email: ");
sender.sendMessage(ChatColor.YELLOW+"/email set <player name> [email protected]");
}
if(sender.hasPermission("Email.remove")) {
sender.sendMessage(ChatColor.AQUA+"To remove your email (players only): ");
sender.sendMessage(ChatColor.YELLOW+"/email remove");
}
if(sender.hasPermission("Email.remove.others")) {
sender.sendMessage(ChatColor.AQUA+"To remove a player's email: ");
sender.sendMessage(ChatColor.YELLOW+"/email remove <player name>");
}
if(sender.hasPermission("Email.view")) {
sender.sendMessage(ChatColor.AQUA+"To view your email (players only): ");
sender.sendMessage(ChatColor.YELLOW+"/email view");
}
if(sender.hasPermission("Email.view.others")) {
sender.sendMessage(ChatColor.AQUA+"To view a player's email: ");
sender.sendMessage(ChatColor.YELLOW+"/email view <player name>");
}
if(sender.hasPermission("Email.send")) {
sender.sendMessage(ChatColor.AQUA+"To send an email to a specific player: ");
sender.sendMessage(ChatColor.YELLOW+"/email send <player name>");
sender.sendMessage(ChatColor.YELLOW+"(must be holding a written book)");
}
if(sender.hasPermission("Email.send.all")) {
sender.sendMessage(ChatColor.AQUA+"To send an email to a ALL players: ");
sender.sendMessage(ChatColor.YELLOW+"/email send");
sender.sendMessage(ChatColor.YELLOW+"(must be holding a written book)");
}
if(sender.hasPermission("Email.export")) {
sender.sendMessage(ChatColor.AQUA+"To export emails to a text file: ");
sender.sendMessage(ChatColor.YELLOW+"/email export <type, either 1 or 2>");
sender.sendMessage(ChatColor.YELLOW+"Type 1 will output names and emails, type 2 will only export emails.");
}
sender.sendMessage(ChatColor.GREEN+"~~~ End Email help ~~~");
return true;
} else if(opt.equalsIgnoreCase("set")) {
if(args.length == 2 && isPlayer && sender.hasPermission("Email.set")) {
boolean result = plugin.emails.setPlayerEmail(sender.getName(), args[1]);
sender.sendMessage((result) ? ChatColor.GREEN+"Email set" : ChatColor.RED+"Invalid email");
return true;
} else if(args.length == 3 && sender.hasPermission("Email.set.others")) {
boolean result = plugin.emails.setPlayerEmail(args[1], args[2]);
sender.sendMessage((result) ? ChatColor.GREEN+"Email set" : ChatColor.RED+"Invalid email");
return true;
} else {
sender.sendMessage(msgUseHelp);
return true;
}
} else if(opt.equalsIgnoreCase("remove")) {
if(args.length == 1 && isPlayer && sender.hasPermission("Email.remove")) {
plugin.emails.removePlayerEmail(sender.getName());
sender.sendMessage(ChatColor.GREEN+"Email removed");
return true;
} else if(args.length == 2 && sender.hasPermission("Email.remove.others")) {
plugin.emails.removePlayerEmail(args[1]);
sender.sendMessage(ChatColor.GREEN+"Email removed");
return true;
} else {
sender.sendMessage(msgUseHelp);
return true;
}
} else if(opt.equalsIgnoreCase("view")) {
if(args.length == 1 && isPlayer && sender.hasPermission("Email.view")) {
String email = plugin.emails.getPlayerEmail(sender.getName());
if(email != null) {
sender.sendMessage(ChatColor.GREEN+"The email is: "+ChatColor.YELLOW+email);
} else {
sender.sendMessage(ChatColor.RED+"You don't have an email set");
}
return true;
} else if(args.length == 2 && sender.hasPermission("Email.view.others")) {
String email = plugin.emails.getPlayerEmail(args[1]);
if(email != null) {
sender.sendMessage(ChatColor.GREEN+"The email is: "+ChatColor.YELLOW+email);
} else {
sender.sendMessage(ChatColor.RED+"That player does not have an email set");
}
return true;
} else {
sender.sendMessage(msgUseHelp);
return true;
}
} else if(opt.equalsIgnoreCase("send")) {
if(plugin.mailman == null) {
sender.sendMessage(ChatColor.RED+"Email sending is disabled on this server!");
return true;
}
if(!isPlayer) {
sender.sendMessage(ChatColor.RED+"Sorry, only players can do that.");
return true;
}
if(!(args.length == 1 || args.length == 2)) {
sender.sendMessage(msgUseHelp);
return true;
}
boolean allPlayers = args.length == 1;
if((allPlayers && sender.hasPermission("Email.send.all")) || (!allPlayers && sender.hasPermission("Email.send"))) {
//Get itemstack in hand, quit if it's not a written book
Player p = (Player)sender;
ItemStack hand = p.getItemInHand();
if(hand.getType() != Material.WRITTEN_BOOK) {
sender.sendMessage(ChatColor.RED+"You must be holding a written book to do that!");
return true;
}
//Set appropriate recipient string
//If all players, then toEmail will be a CSV string (ex. [email protected],[email protected])
String toEmail = "";
if(allPlayers) {
String[] emailArray = plugin.emails.getAllPlayerEmails();
for(String email : emailArray) {
toEmail += ","+email;
}
toEmail = toEmail.substring(1);
} else {
toEmail = plugin.emails.getPlayerEmail(args[1]);
}
//Can't have that!
if(toEmail.isEmpty()) {
sender.sendMessage(ChatColor.RED+"That player has not set their email!");
return true;
}
//Get the book's metadata
BookMeta data = (BookMeta)hand.getItemMeta();
//The email's subject
String emailSubject = data.getTitle();
//The email's body
String emailContent = "";
for(String page : data.getPages()) {
emailContent += " "+page;
}
//Remove the extra space
emailContent = emailContent.substring(1);
//Send the email! :)
Bukkit.getScheduler().runTaskAsynchronously(plugin, new EmailTask(plugin.mailman, toEmail, emailSubject, emailContent));
sender.sendMessage(ChatColor.GREEN+"Email is being sent! It should be received soon.");
} else {
sender.sendMessage(msgUseHelp);
return true;
}
} else if(opt.equalsIgnoreCase("export")) {
if(args.length == 2 && sender.hasPermission("Email.export")) {
if(args[1].equalsIgnoreCase("1")) {
plugin.emails.export(1);
sender.sendMessage(ChatColor.GREEN+"Emails and names exported");
return true;
} else if(args[1].equalsIgnoreCase("2")) {
plugin.emails.export(2);
sender.sendMessage(ChatColor.GREEN+"Emails exported");
return true;
} else {
sender.sendMessage(ChatColor.RED+"Incorrect type, must be 1 or 2.");
}
} else {
sender.sendMessage(msgUseHelp);
return true;
}
} else if(opt.equalsIgnoreCase("info")) {
PluginDescriptionFile pdf = plugin.getDescription();
String name = ChatColor.YELLOW+pdf.getName()+ChatColor.AQUA;
String version = ChatColor.YELLOW+pdf.getVersion()+ChatColor.AQUA;
String author = ChatColor.YELLOW+pdf.getAuthors().get(0)+ChatColor.AQUA;
sender.sendMessage(name+" version "+version+" by "+author+" is "+ChatColor.GREEN+"running.");
return true;
}
sender.sendMessage(msgUseHelp);
return true;
}
return false;
}
|
diff --git a/src/jrds/probe/HttpProbe.java b/src/jrds/probe/HttpProbe.java
index a199e06c..c851ddc2 100644
--- a/src/jrds/probe/HttpProbe.java
+++ b/src/jrds/probe/HttpProbe.java
@@ -1,261 +1,262 @@
package jrds.probe;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IllegalFormatConversionException;
import java.util.List;
import java.util.Map;
import jrds.Probe;
import jrds.RdsHost;
import jrds.starter.Resolver;
import jrds.starter.Starter;
import org.apache.log4j.Level;
/**
* A generic probe to collect an HTTP service
* default generic :
* port to provide a default port to collect
* file to provide a specific file to collect
*
* Implemention should implement the parseStream method
*
* @author Fabrice Bacchella
* @version $Revision$, $Date$
*/
public abstract class HttpProbe extends Probe<String, Number> implements UrlProbe {
private URL url = null;
private String host = null;
private int port = 0;
private String file = null;
private String label;
private List<Object> argslist = null;
Starter resolver = null;
public void configure(URL url) {
this.url = url;
finishConfigure();
}
public void configure(Integer port, String file) {
this.port = port;
this.file = file;
finishConfigure();
}
public void configure(Integer port) {
this.port = port;
finishConfigure();
}
public void configure(String file) {
this.file = file;
finishConfigure();
}
public void configure(List<Object> argslist) {
this.argslist = argslist;
finishConfigure();
}
public void configure(URL url, List<Object> argslist) {
this.url = url;
this.argslist = argslist;
finishConfigure();
}
public void configure(Integer port, String file, List<Object> argslist) {
this.port = port;
this.file = file;
this.argslist = argslist;
finishConfigure();
}
public void configure() {
finishConfigure();
}
private void finishConfigure() {
RdsHost monitoredHost = getHost();
log(Level.TRACE, "Set host to %s", monitoredHost);
host = monitoredHost.getDnsName();
try {
if(url != null)
setUrl(new URL(getUrl().getProtocol(), host, getUrl().getPort(), getUrl().getFile()));
} catch (MalformedURLException e) {
log(Level.ERROR, e, "URL " + "http://%d:%s%s is invalid", host, getUrl().getPort(), getUrl().getFile());
}
URL tempurl = getUrl();
if("http".equals(tempurl.getProtocol())) {
resolver = new Resolver(url.getHost()).register(getHost());
}
log(Level.DEBUG, "Url to collect is %s", getUrl());
}
/* (non-Javadoc)
* @see jrds.Probe#isCollectRunning()
*/
@Override
public boolean isCollectRunning() {
if (resolver != null && ! resolver.isStarted())
return false;
return super.isCollectRunning();
}
/**
* @param A stream collected from the http source
* @return a map of collected value
*/
protected abstract Map<String, Number> parseStream(InputStream stream);
/**
* A utility method that transform the input stream to a List of lines
* @param stream
* @return
*/
public List<String> parseStreamToLines(InputStream stream) {
List<String> lines = java.util.Collections.emptyList();
log(Level.DEBUG, "Getting %s", getUrl());
try {
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
lines = new ArrayList<String>();
String lastLine;
while((lastLine = in.readLine()) != null)
lines.add(lastLine);
in.close();
} catch (IOException e) {
log(Level.ERROR, e, "Unable to read url %s because; %s", getUrl(), e.getMessage());
}
return lines;
}
/* (non-Javadoc)
* @see com.aol.jrds.Probe#getNewSampleValues()
*/
public Map<String, Number> getNewSampleValues() {
String hostName = getUrl().getHost();
if(hostName != null) {
Starter resolver = getStarters().find(Resolver.makeKey(hostName));
if(resolver != null && ! resolver.isStarted()) {
log(Level.TRACE, "Resolver not started for %s", hostName);
return Collections.emptyMap();
}
}
- Map<String, Number> vars = java.util.Collections.emptyMap();
log(Level.DEBUG, "Getting %s", getUrl());
URLConnection cnx = null;
try {
cnx = getUrl().openConnection();
cnx.setConnectTimeout(getTimeout() * 1000);
cnx.setReadTimeout(getTimeout() * 1000);
cnx.connect();
} catch (IOException e) {
- log(Level.ERROR, e, "Unable to read url %s because; %s", getUrl(), e.getMessage());
+ log(Level.ERROR, e, "Connection to %s failed: %s", getUrl(), e.getMessage());
+ return Collections.emptyMap();
}
try {
InputStream is = cnx.getInputStream();
- vars = parseStream(is);
+ Map<String, Number> vars = parseStream(is);
is.close();
+ return vars;
} catch(ConnectException e) {
- log(Level.ERROR, e, "Connection refused to %", getUrl());
+ log(Level.ERROR, e, "Connection refused to %s", getUrl());
} catch (IOException e) {
//Clean http connection error management
//see http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
try {
byte[] buffer = new byte[4096];
int respCode = ((HttpURLConnection)cnx).getResponseCode();
- log(Level.ERROR, e, "Unable to read url %s because : %s, htt error code: %d", getUrl(), e.getMessage(),respCode);
+ log(Level.ERROR, e, "Unable to read url %s because: %s, http error code: %d", getUrl(), e.getMessage(), respCode);
InputStream es = ((HttpURLConnection)cnx).getErrorStream();
// read the response body
while (es.read(buffer) > 0) {}
// close the error stream
es.close();
} catch(IOException ex) {
log(Level.ERROR, ex, "Unable to recover from error in url %s because %s", getUrl(), ex.getMessage());
}
}
- return vars;
+ return Collections.emptyMap();
}
/**
* @return Returns the url.
*/
public String getUrlAsString() {
return getUrl().toString();
}
public int getPort() {
return getUrl().getPort();
}
/**
* @return Returns the url.
*/
public URL getUrl() {
if(url == null) {
try {
String portStr = null;
if(port == 0) {
portStr = getPd().getSpecific("port");
if(portStr == null || "".equals(portStr)) {
portStr = "80";
}
}
if(file == null) {
file = getPd().getSpecific("file");
if(file == null || "".equals(file)) {
file = "/";
}
}
if(argslist != null) {
try {
String urlString = String.format("http://" + host + ":" + portStr + file, argslist.toArray());
url = new URL(urlString);
} catch (IllegalFormatConversionException e) {
log(Level.ERROR, "Illegal format string: http://%s:%s%s, args %d", host, portStr, file, argslist.size());
return null;
}
}
else {
if(port == 0)
port = jrds.Util.parseStringNumber(portStr, Integer.class, 80).intValue();
url = new URL("http", host, port, file);
}
} catch (MalformedURLException e) {
log(Level.ERROR, e, "URL http://%s:%s%s is invalid",host , port, file);
}
}
return url;
}
/**
* @param url The url to set.
*/
public void setUrl(URL url) {
this.url = url;
}
@Override
public String getSourceType() {
return "HTTP";
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
}
| false | true | public Map<String, Number> getNewSampleValues() {
String hostName = getUrl().getHost();
if(hostName != null) {
Starter resolver = getStarters().find(Resolver.makeKey(hostName));
if(resolver != null && ! resolver.isStarted()) {
log(Level.TRACE, "Resolver not started for %s", hostName);
return Collections.emptyMap();
}
}
Map<String, Number> vars = java.util.Collections.emptyMap();
log(Level.DEBUG, "Getting %s", getUrl());
URLConnection cnx = null;
try {
cnx = getUrl().openConnection();
cnx.setConnectTimeout(getTimeout() * 1000);
cnx.setReadTimeout(getTimeout() * 1000);
cnx.connect();
} catch (IOException e) {
log(Level.ERROR, e, "Unable to read url %s because; %s", getUrl(), e.getMessage());
}
try {
InputStream is = cnx.getInputStream();
vars = parseStream(is);
is.close();
} catch(ConnectException e) {
log(Level.ERROR, e, "Connection refused to %", getUrl());
} catch (IOException e) {
//Clean http connection error management
//see http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
try {
byte[] buffer = new byte[4096];
int respCode = ((HttpURLConnection)cnx).getResponseCode();
log(Level.ERROR, e, "Unable to read url %s because : %s, htt error code: %d", getUrl(), e.getMessage(),respCode);
InputStream es = ((HttpURLConnection)cnx).getErrorStream();
// read the response body
while (es.read(buffer) > 0) {}
// close the error stream
es.close();
} catch(IOException ex) {
log(Level.ERROR, ex, "Unable to recover from error in url %s because %s", getUrl(), ex.getMessage());
}
}
return vars;
}
| public Map<String, Number> getNewSampleValues() {
String hostName = getUrl().getHost();
if(hostName != null) {
Starter resolver = getStarters().find(Resolver.makeKey(hostName));
if(resolver != null && ! resolver.isStarted()) {
log(Level.TRACE, "Resolver not started for %s", hostName);
return Collections.emptyMap();
}
}
log(Level.DEBUG, "Getting %s", getUrl());
URLConnection cnx = null;
try {
cnx = getUrl().openConnection();
cnx.setConnectTimeout(getTimeout() * 1000);
cnx.setReadTimeout(getTimeout() * 1000);
cnx.connect();
} catch (IOException e) {
log(Level.ERROR, e, "Connection to %s failed: %s", getUrl(), e.getMessage());
return Collections.emptyMap();
}
try {
InputStream is = cnx.getInputStream();
Map<String, Number> vars = parseStream(is);
is.close();
return vars;
} catch(ConnectException e) {
log(Level.ERROR, e, "Connection refused to %s", getUrl());
} catch (IOException e) {
//Clean http connection error management
//see http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
try {
byte[] buffer = new byte[4096];
int respCode = ((HttpURLConnection)cnx).getResponseCode();
log(Level.ERROR, e, "Unable to read url %s because: %s, http error code: %d", getUrl(), e.getMessage(), respCode);
InputStream es = ((HttpURLConnection)cnx).getErrorStream();
// read the response body
while (es.read(buffer) > 0) {}
// close the error stream
es.close();
} catch(IOException ex) {
log(Level.ERROR, ex, "Unable to recover from error in url %s because %s", getUrl(), ex.getMessage());
}
}
return Collections.emptyMap();
}
|
diff --git a/src/main/java/com/bsg/pcms/provision/content/svc/ContentServiceImpl.java b/src/main/java/com/bsg/pcms/provision/content/svc/ContentServiceImpl.java
index a866d09..5965bb7 100644
--- a/src/main/java/com/bsg/pcms/provision/content/svc/ContentServiceImpl.java
+++ b/src/main/java/com/bsg/pcms/provision/content/svc/ContentServiceImpl.java
@@ -1,139 +1,139 @@
package com.bsg.pcms.provision.content.svc;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.bsg.pcms.dto.SeriesDTO;
import com.bsg.pcms.provision.category.svc.CategoryService;
import com.bsg.pcms.provision.content.ContentDTOEx;
import com.bsg.pcms.provision.content.ContentDao;
import com.bsg.pcms.provision.series.SeriesDao;
@Service
public class ContentServiceImpl implements ContentService {
private Logger logger = LoggerFactory.getLogger(CategoryService.class);
@Autowired
private ContentDao contentDao;
@Autowired
private SeriesDao seriesDao;
public ContentDTOEx getContent(ContentDTOEx content) {
return contentDao.getContent(content);
}
public int getContentCount(ContentDTOEx content) {
return contentDao.getContentCount(content);
}
public int getContentCountBySeriesMgmtno(int seriesMgmtno) {
return contentDao.getContentCountBySeriesMgmtno(seriesMgmtno);
}
public List<ContentDTOEx> getContentList(ContentDTOEx content) {
return contentDao.getContentList(content);
}
public List<ContentDTOEx> getContentCodeListBySeriesMgmtno(ContentDTOEx cde) {
return contentDao.getContentCodeListBySeriesMgmtno(cde);
}
public List<ContentDTOEx> getContentCodeListByCateId(ContentDTOEx cde) {
return contentDao.getContentCodeListByCateId(cde);
}
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.SERIALIZABLE, readOnly = false, rollbackFor = { SQLException.class })
public int createContent(ContentDTOEx cde) throws SQLException {
int seriesUpdateResult = this.updateContentForSeries(cde);
logger.debug("seriesUpdateResult : {}", seriesUpdateResult);
//컨텐츠 코드 생성
cde.setContents_cd(this.makeContentCode(cde));
return contentDao.createContent(cde);
}
public int createContentBySeries(ContentDTOEx content) {
return contentDao.createContent(content);
}
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.SERIALIZABLE, readOnly = false, rollbackFor = { SQLException.class })
public int updateContent(ContentDTOEx cde) throws SQLException {
int seriesUpdateResult = this.updateContentForSeries(cde);
logger.debug("seriesUpdateResult : {}", seriesUpdateResult);
return contentDao.updateContent(cde);
}
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.SERIALIZABLE, readOnly = false, rollbackFor = { SQLException.class })
public int deleteContent(ContentDTOEx content) throws SQLException {
String[] contentList = content.getStrList().split(",");
List<String> list = Arrays.asList(contentList);
int result = 0;
for (String contents_cd : list) {
content.setContents_cd(contents_cd);
result = contentDao.deleteContent(content);
}
return result;
}
private String makeContentCode(ContentDTOEx contentDTO) {
ContentDTOEx resultDTO = contentDao.getContentCodeBy(contentDTO);
// 컨텐츠 시퀀스 생성
int seq = 1;
if (resultDTO != null) {
String contentsCode = resultDTO.getContents_cd();
int i = Integer.valueOf(contentsCode.substring(contentsCode.length() - 7, contentsCode.length() - 3));
seq = ++i;
}
// 컨텐츠 접미사 생성
String suffix = "";
String contentType = contentDTO.getContents_type();
- if (contentType.equalsIgnoreCase("pb")) {
+ if (contentType.equalsIgnoreCase("PD001001")) {
suffix = "PB";
- } else if (contentType.equalsIgnoreCase("ebook")) {
+ } else if (contentType.equalsIgnoreCase("PD001002")) {
suffix = "EB";
- } else if (contentType.equalsIgnoreCase("2d")) {
+ } else if (contentType.equalsIgnoreCase("PD001003")) {
suffix = "2D";
- } else if (contentType.equalsIgnoreCase("3d")) {
+ } else if (contentType.equalsIgnoreCase("PD001004")) {
suffix = "3D"; // 3d
} else {
suffix = "GA"; // game
}
// 컨텐츠 코드 CP[cpId(2자리)]_SE[seriesId(2자리)P[콘텐츠시퀀스(4자리)_접미사]]
String contentCode = String.format("CP%02d_SE%02dP%04d_%s", contentDTO.getCompany_mgmtno(), contentDTO.getSeries_mgmtno(), seq, suffix);
return contentCode.toString();
}
/** 컨텐츠 생성시 company_mgmtno가 없는 series들 update
* @param cde
* @return
*/
private int updateContentForSeries(ContentDTOEx cde) {
ContentDTOEx seriesParam = new ContentDTOEx();
seriesParam.setCompany_mgmtno(cde.getCompany_mgmtno());
seriesParam.setSeries_mgmtno(cde.getSeries_mgmtno());
seriesParam.setSeries_name(String.valueOf(cde.getSeries_mgmtno()));
int seriesUpdateResult = contentDao.updateContentForSeries(seriesParam);
return seriesUpdateResult;
}
}
| false | true | private String makeContentCode(ContentDTOEx contentDTO) {
ContentDTOEx resultDTO = contentDao.getContentCodeBy(contentDTO);
// 컨텐츠 시퀀스 생성
int seq = 1;
if (resultDTO != null) {
String contentsCode = resultDTO.getContents_cd();
int i = Integer.valueOf(contentsCode.substring(contentsCode.length() - 7, contentsCode.length() - 3));
seq = ++i;
}
// 컨텐츠 접미사 생성
String suffix = "";
String contentType = contentDTO.getContents_type();
if (contentType.equalsIgnoreCase("pb")) {
suffix = "PB";
} else if (contentType.equalsIgnoreCase("ebook")) {
suffix = "EB";
} else if (contentType.equalsIgnoreCase("2d")) {
suffix = "2D";
} else if (contentType.equalsIgnoreCase("3d")) {
suffix = "3D"; // 3d
} else {
suffix = "GA"; // game
}
// 컨텐츠 코드 CP[cpId(2자리)]_SE[seriesId(2자리)P[콘텐츠시퀀스(4자리)_접미사]]
String contentCode = String.format("CP%02d_SE%02dP%04d_%s", contentDTO.getCompany_mgmtno(), contentDTO.getSeries_mgmtno(), seq, suffix);
return contentCode.toString();
}
| private String makeContentCode(ContentDTOEx contentDTO) {
ContentDTOEx resultDTO = contentDao.getContentCodeBy(contentDTO);
// 컨텐츠 시퀀스 생성
int seq = 1;
if (resultDTO != null) {
String contentsCode = resultDTO.getContents_cd();
int i = Integer.valueOf(contentsCode.substring(contentsCode.length() - 7, contentsCode.length() - 3));
seq = ++i;
}
// 컨텐츠 접미사 생성
String suffix = "";
String contentType = contentDTO.getContents_type();
if (contentType.equalsIgnoreCase("PD001001")) {
suffix = "PB";
} else if (contentType.equalsIgnoreCase("PD001002")) {
suffix = "EB";
} else if (contentType.equalsIgnoreCase("PD001003")) {
suffix = "2D";
} else if (contentType.equalsIgnoreCase("PD001004")) {
suffix = "3D"; // 3d
} else {
suffix = "GA"; // game
}
// 컨텐츠 코드 CP[cpId(2자리)]_SE[seriesId(2자리)P[콘텐츠시퀀스(4자리)_접미사]]
String contentCode = String.format("CP%02d_SE%02dP%04d_%s", contentDTO.getCompany_mgmtno(), contentDTO.getSeries_mgmtno(), seq, suffix);
return contentCode.toString();
}
|
diff --git a/kdcloud-webservice/src/test/java/com/kdcloud/server/rest/resource/ServerResourceTest.java b/kdcloud-webservice/src/test/java/com/kdcloud/server/rest/resource/ServerResourceTest.java
index 15cd187..e0379fc 100644
--- a/kdcloud-webservice/src/test/java/com/kdcloud/server/rest/resource/ServerResourceTest.java
+++ b/kdcloud-webservice/src/test/java/com/kdcloud/server/rest/resource/ServerResourceTest.java
@@ -1,158 +1,158 @@
package com.kdcloud.server.rest.resource;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.restlet.Application;
import org.restlet.Context;
import org.restlet.data.Form;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.kdcloud.server.engine.embedded.EmbeddedEngine;
import com.kdcloud.server.entity.DataTable;
import com.kdcloud.server.entity.Modality;
import com.kdcloud.server.entity.Report;
import com.kdcloud.server.entity.ServerAction;
import com.kdcloud.server.entity.ServerMethod;
import com.kdcloud.server.entity.ServerParameter;
import com.kdcloud.server.entity.User;
import com.kdcloud.server.entity.Workflow;
import com.kdcloud.server.rest.api.DatasetResource;
import com.kdcloud.server.rest.api.GlobalAnalysisResource;
import com.kdcloud.server.rest.api.ModalitiesResource;
import com.kdcloud.server.rest.api.UserDataResource;
import com.kdcloud.server.rest.api.WorkflowResource;
import com.kdcloud.server.rest.application.Utils;
import com.kdcloud.weka.core.DenseInstance;
import com.kdcloud.weka.core.Instances;
public class ServerResourceTest {
private final LocalServiceTestHelper helper = new LocalServiceTestHelper(
new LocalDatastoreServiceTestConfig()
/* .setDefaultHighRepJobPolicyUnappliedJobPercentage(100) */);
public static final String USER_ID = TestContext.USER_ID;
private Context context = new TestContext();
private Application application = new Application(context);
UserDataServerResource userDataResource = new UserDataServerResource(application);
@Before
public void setUp() throws Exception {
helper.setUp();
}
@After
public void tearDown() throws Exception {
helper.tearDown();
}
@Test
public void testUserData() {
Long id = userDataResource.createDataset();
assertNotNull(id);
User u = userDataResource.userDao.findById(USER_ID);
assertNotNull(u);
assertNotNull(u.getTable());
DataTable dataset = userDataResource.dataTableDao.findById(id);
assertNotNull(dataset.getId());
}
@Test
public void testDataset() {
Long id = userDataResource.createDataset();
DataTable dataset = userDataResource.dataTableDao.findById(id);
DatasetServerResource datasetResource = new DatasetServerResource(application, dataset);
double[] cells = { 1, 2 };
Instances data = new Instances(dataset.getInstances());
data.add(new DenseInstance(0, cells));
datasetResource.uploadData(data);
assertEquals(1, datasetResource.getData().size());
// datasetResource.deleteDataset();
// assertNull(datasetResource.dataTableDao.findById(id));
}
@Test
public void testModalities() {
Utils.initDatabase(context);
ModalitiesServerResource modalitiesResource = new ModalitiesServerResource(application);
List<Modality> list = modalitiesResource.listModalities();
assertEquals(3, list.size());
Modality modality = list.get(0);
modality.setName("test");
ChoosenModalityServerResource choosenModalityResource = new ChoosenModalityServerResource(application, modality);
choosenModalityResource.editModality(modality);
modality = choosenModalityResource.modalityDao.findById(modality.getId());
assertEquals("test", modality.getName());
choosenModalityResource.deleteModality();
modality = choosenModalityResource.modalityDao.findById(modality.getId());
assertNull(modality);
}
@Test
public void testWorkflow() {
Workflow workflow = EmbeddedEngine.getQRSWorkflow();
Instances instances = new Instances("test", workflow.getInputSpec(), 0);
userDataResource.createDataset(instances);
WorkflowServerResource workflowResource = new WorkflowServerResource(application, workflow);
Form form = new Form();
form.add(ServerParameter.USER_ID.getName(), USER_ID);
Report r = workflowResource.execute(form);
assertNotNull(r);
}
@Test
public void testGlobalData() {
+ Workflow workflow = EmbeddedEngine.getQRSWorkflow();
+ Instances instances = new Instances("test", workflow.getInputSpec(), 0);
String[] ids = { "a", "b", "c" };
for (String s : ids) {
User user = new User();
user.setId(s);
userDataResource.user = user;
- userDataResource.createDataset();
+ userDataResource.createDataset(instances);
}
GlobalDataServerResource globalDataResource = new GlobalDataServerResource(application);
assertTrue(globalDataResource.getAllUsersWithData().contains(ids[0]));
assertEquals(ids.length, globalDataResource.getAllUsersWithData()
.size());
- Workflow workflow = EmbeddedEngine.getQRSWorkflow();
GlobalAnalysisServerResource globalAnalysisResource = new GlobalAnalysisServerResource(application, workflow);
Form form = new Form();
- form.add(ServerParameter.USER_ID.getName(), USER_ID);
assertEquals(ids.length, globalAnalysisResource.execute(form).size());
}
@Test
public void testDevices() {
DeviceServerResource deviceResource = new DeviceServerResource(application);
deviceResource.register("test");
deviceResource.unregister("test");
}
// @Test
// public void testScheduling() {
// userDataResource.createDataset();
// userDataResource.getPersistenceContext().close();
// scheduler.requestProcess();
// scheduler.getPersistenceContext().close();
// worker.pullTask(null);
// }
}
| false | true | public void testGlobalData() {
String[] ids = { "a", "b", "c" };
for (String s : ids) {
User user = new User();
user.setId(s);
userDataResource.user = user;
userDataResource.createDataset();
}
GlobalDataServerResource globalDataResource = new GlobalDataServerResource(application);
assertTrue(globalDataResource.getAllUsersWithData().contains(ids[0]));
assertEquals(ids.length, globalDataResource.getAllUsersWithData()
.size());
Workflow workflow = EmbeddedEngine.getQRSWorkflow();
GlobalAnalysisServerResource globalAnalysisResource = new GlobalAnalysisServerResource(application, workflow);
Form form = new Form();
form.add(ServerParameter.USER_ID.getName(), USER_ID);
assertEquals(ids.length, globalAnalysisResource.execute(form).size());
}
| public void testGlobalData() {
Workflow workflow = EmbeddedEngine.getQRSWorkflow();
Instances instances = new Instances("test", workflow.getInputSpec(), 0);
String[] ids = { "a", "b", "c" };
for (String s : ids) {
User user = new User();
user.setId(s);
userDataResource.user = user;
userDataResource.createDataset(instances);
}
GlobalDataServerResource globalDataResource = new GlobalDataServerResource(application);
assertTrue(globalDataResource.getAllUsersWithData().contains(ids[0]));
assertEquals(ids.length, globalDataResource.getAllUsersWithData()
.size());
GlobalAnalysisServerResource globalAnalysisResource = new GlobalAnalysisServerResource(application, workflow);
Form form = new Form();
assertEquals(ids.length, globalAnalysisResource.execute(form).size());
}
|
diff --git a/srcj/com/sun/electric/tool/io/output/Spice.java b/srcj/com/sun/electric/tool/io/output/Spice.java
index 12b48092d..c2e34f4c2 100755
--- a/srcj/com/sun/electric/tool/io/output/Spice.java
+++ b/srcj/com/sun/electric/tool/io/output/Spice.java
@@ -1,3271 +1,3271 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: Spice.java
* Original C Code written by Steven M. Rubin and Sid Penstone
* Translated to Java by Steven M. Rubin, Sun Microsystems.
*
* Copyright (c) 2004 Sun Microsystems and Static Free Software
*
* Electric(tm) is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Electric(tm) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.io.output;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.geometry.PolyBase;
import com.sun.electric.database.geometry.PolyMerge;
import com.sun.electric.database.geometry.GeometryHandler;
import com.sun.electric.database.hierarchy.*;
import com.sun.electric.database.network.Global;
import com.sun.electric.database.network.Netlist;
import com.sun.electric.database.network.Network;
import com.sun.electric.database.prototype.NodeProto;
import com.sun.electric.database.prototype.PortProto;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.text.Version;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.variable.TextDescriptor;
import com.sun.electric.database.variable.VarContext;
import com.sun.electric.database.variable.Variable;
import com.sun.electric.technology.*;
import com.sun.electric.technology.technologies.Generic;
import com.sun.electric.technology.technologies.Schematics;
import com.sun.electric.tool.io.FileType;
import com.sun.electric.tool.io.input.Simulate;
import com.sun.electric.tool.io.input.spicenetlist.SpiceNetlistReader;
import com.sun.electric.tool.io.input.spicenetlist.SpiceSubckt;
import com.sun.electric.tool.simulation.Simulation;
import com.sun.electric.tool.user.Exec;
import com.sun.electric.tool.user.User;
import com.sun.electric.tool.user.dialogs.ExecDialog;
import com.sun.electric.tool.user.ui.TopLevel;
import com.sun.electric.tool.user.waveform.WaveformWindow;
import com.sun.electric.tool.Job;
import com.sun.electric.tool.JobException;
import com.sun.electric.tool.generator.sclibrary.SCLibraryGen;
import com.sun.electric.tool.ncc.basic.NccCellAnnotations;
import com.sun.electric.tool.ncc.basic.NccCellAnnotations.NamePattern;
import com.sun.electric.tool.logicaleffort.LENetlister;
import java.awt.geom.AffineTransform;
import java.io.*;
import java.net.URL;
import java.util.*;
/**
* This is the Simulation Interface tool.
*/
public class Spice extends Topology
{
/** key of Variable holding generic Spice templates. */ public static final Variable.Key SPICE_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template");
/** key of Variable holding Spice 2 templates. */ public static final Variable.Key SPICE_2_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_spice2");
/** key of Variable holding Spice 3 templates. */ public static final Variable.Key SPICE_3_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_spice3");
/** key of Variable holding HSpice templates. */ public static final Variable.Key SPICE_H_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_hspice");
/** key of Variable holding PSpice templates. */ public static final Variable.Key SPICE_P_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_pspice");
/** key of Variable holding GnuCap templates. */ public static final Variable.Key SPICE_GC_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_gnucap");
/** key of Variable holding Smart Spice templates. */ public static final Variable.Key SPICE_SM_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_smartspice");
/** key of Variable holding Smart Spice templates. */ public static final Variable.Key SPICE_A_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_assura");
/** key of Variable holding Smart Spice templates. */ public static final Variable.Key SPICE_C_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_calibre");
/** key of Variable holding SPICE code. */ public static final Variable.Key SPICE_CARD_KEY = Variable.newKey("SIM_spice_card");
/** key of Variable holding SPICE declaration. */ public static final Variable.Key SPICE_DECLARATION_KEY = Variable.newKey("SIM_spice_declaration");
/** key of Variable holding SPICE model. */ public static final Variable.Key SPICE_MODEL_KEY = Variable.newKey("SIM_spice_model");
/** key of Variable holding SPICE flat code. */ public static final Variable.Key SPICE_CODE_FLAT_KEY = Variable.newKey("SIM_spice_code_flat");
/** key of wire capacitance. */ public static final Variable.Key ATTR_C = Variable.newKey("ATTR_C");
/** key of wire resistance. */ public static final Variable.Key ATTR_R = Variable.newKey("ATTR_R");
/** Prefix for spice extension. */ public static final String SPICE_EXTENSION_PREFIX = "Extension ";
/** key of Variable holding generic CDL templates. */ public static final Variable.Key CDL_TEMPLATE_KEY = Variable.newKey("ATTR_CDL_template");
/** maximum subcircuit name length */ private static final int SPICEMAXLENSUBCKTNAME = 70;
/** maximum subcircuit name length */ private static final int CDLMAXLENSUBCKTNAME = 40;
/** maximum subcircuit name length */ private static final int SPICEMAXLENLINE = 78;
/** legal characters in a spice deck */ private static final String SPICELEGALCHARS = "!#$%*+-/<>[]_@";
/** legal characters in a spice deck */ private static final String PSPICELEGALCHARS = "!#$%*+-/<>[]_";
/** legal characters in a CDL deck */ private static final String CDLNOBRACKETLEGALCHARS = "!#$%*+-/<>_";
/** if CDL writes out empty subckt definitions */ private static final boolean CDLWRITESEMPTYSUBCKTS = false;
/** if use spice globals */ private static final boolean USE_GLOBALS = true;
/** default Technology to use. */ private Technology layoutTechnology;
/** Mask shrink factor (default =1) */ private double maskScale;
/** True to write CDL format */ private boolean useCDL;
/** Legal characters */ private String legalSpiceChars;
/** Template Key for current spice engine */ private Variable.Key preferedEngineTemplateKey;
/** Special case for HSpice for Assura */ private boolean assuraHSpice = false;
/** Spice type: 2, 3, H, P, etc */ private Simulation.SpiceEngine spiceEngine;
/** those cells that have overridden models */ private HashMap<Cell,String> modelOverrides = new HashMap<Cell,String>();
/** List of segmented nets and parasitics */ private List<SegmentedNets> segmentedParasiticInfo = new ArrayList<SegmentedNets>();
/** Networks exempted during parasitic ext */ private ExemptedNets exemptedNets;
/** Whether or not to write empty subckts */ private boolean writeEmptySubckts = true;
/** max length per line */ private int spiceMaxLenLine = SPICEMAXLENLINE;
/** Flat measurements file */ private FlatSpiceCodeVisitor spiceCodeFlat = null;
/** map of "parameterized" cells that are not covered by Topology */ private Map<Cell,Cell> uniquifyCells;
/** uniqueID */ private int uniqueID;
/** map of shortened instance names */ private Map<String,Integer> uniqueNames;
private static final boolean useNewParasitics = true;
private static class SpiceNet
{
/** network object associated with this */ Network network;
/** merged geometry for this network */ PolyMerge merge;
/** area of diffusion */ double diffArea;
/** perimeter of diffusion */ double diffPerim;
/** amount of capacitance in non-diff */ float nonDiffCapacitance;
/** number of transistors on the net */ int transistorCount;
}
private static class SpiceFinishedListener implements Exec.FinishedListener {
private Cell cell;
private FileType type;
private String file;
private SpiceFinishedListener(Cell cell, FileType type, String file) {
this.cell = cell;
this.type = type;
this.file = file;
}
public void processFinished(Exec.FinishedEvent e) {
URL fileURL = TextUtils.makeURLToFile(file);
// create a new waveform window
WaveformWindow ww = WaveformWindow.findWaveformWindow(cell);
Simulate.plotSimulationResults(type, cell, fileURL, ww);
}
}
/**
* The main entry point for Spice deck writing.
* @param cell the top-level cell to write.
* @param context the hierarchical context to the cell.
* @param filePath the disk file to create.
* @param cdl true if this is CDL output (false for Spice).
*/
public static void writeSpiceFile(Cell cell, VarContext context, String filePath, boolean cdl)
{
Spice out = new Spice();
out.useCDL = cdl;
if (out.openTextOutputStream(filePath)) return;
if (out.writeCell(cell, context)) return;
if (out.closeTextOutputStream()) return;
System.out.println(filePath + " written");
// write CDL support file if requested
if (out.useCDL)
{
// write the control files
String deckFile = filePath;
String deckPath = "";
int lastDirSep = deckFile.lastIndexOf(File.separatorChar);
if (lastDirSep > 0)
{
deckPath = deckFile.substring(0, lastDirSep);
deckFile = deckFile.substring(lastDirSep+1);
}
String templateFile = deckPath + File.separator + cell.getName() + ".cdltemplate";
if (out.openTextOutputStream(templateFile)) return;
String libName = Simulation.getCDLLibName();
String libPath = Simulation.getCDLLibPath();
out.printWriter.print("cdlInKeys = list(nil\n");
out.printWriter.print(" 'searchPath \"" + deckFile + "");
if (libPath.length() > 0)
out.printWriter.print("\n " + libPath);
out.printWriter.print("\"\n");
out.printWriter.print(" 'cdlFile \"" + deckPath + File.separator + deckFile + "\"\n");
out.printWriter.print(" 'userSkillFile \"\"\n");
out.printWriter.print(" 'opusLib \"" + libName + "\"\n");
out.printWriter.print(" 'primaryCell \"" + cell.getName() + "\"\n");
out.printWriter.print(" 'caseSensitivity \"lower\"\n");
out.printWriter.print(" 'hierarchy \"flatten\"\n");
out.printWriter.print(" 'cellTable \"\"\n");
out.printWriter.print(" 'viewName \"netlist\"\n");
out.printWriter.print(" 'viewType \"\"\n");
out.printWriter.print(" 'pr nil\n");
out.printWriter.print(" 'skipDevice nil\n");
out.printWriter.print(" 'schemaLib \"sample\"\n");
out.printWriter.print(" 'refLib \"\"\n");
out.printWriter.print(" 'globalNodeExpand \"full\"\n");
out.printWriter.print(")\n");
if (out.closeTextOutputStream()) return;
System.out.println(templateFile + " written");
// ttyputmsg(x_("Now type: exec nino CDLIN %s &"), templatefile);
}
String runSpice = Simulation.getSpiceRunChoice();
if (!runSpice.equals(Simulation.spiceRunChoiceDontRun)) {
String command = Simulation.getSpiceRunProgram() + " " + Simulation.getSpiceRunProgramArgs();
// see if user specified custom dir to run process in
String workdir = User.getWorkingDirectory();
String rundir = workdir;
if (Simulation.getSpiceUseRunDir()) {
rundir = Simulation.getSpiceRunDir();
}
File dir = new File(rundir);
int start = filePath.lastIndexOf(File.separator);
if (start == -1) start = 0; else {
start++;
if (start > filePath.length()) start = filePath.length();
}
int end = filePath.lastIndexOf(".");
if (end == -1) end = filePath.length();
String filename_noext = filePath.substring(start, end);
String filename = filePath.substring(start, filePath.length());
// replace vars in command and args
command = command.replaceAll("\\$\\{WORKING_DIR}", workdir);
command = command.replaceAll("\\$\\{USE_DIR}", rundir);
command = command.replaceAll("\\$\\{FILENAME}", filename);
command = command.replaceAll("\\$\\{FILENAME_NO_EXT}", filename_noext);
// set up run probe
FileType type = Simulate.getCurrentSpiceOutputType();
String [] extensions = type.getExtensions();
String outFile = rundir + File.separator + filename_noext + "." + extensions[0];
Exec.FinishedListener l = new SpiceFinishedListener(cell, type, outFile);
if (runSpice.equals(Simulation.spiceRunChoiceRunIgnoreOutput)) {
Exec e = new Exec(command, null, dir, null, null);
if (Simulation.getSpiceRunProbe()) e.addFinishedListener(l);
e.start();
}
if (runSpice.equals(Simulation.spiceRunChoiceRunReportOutput)) {
ExecDialog dialog = new ExecDialog(TopLevel.getCurrentJFrame(), false);
if (Simulation.getSpiceRunProbe()) dialog.addFinishedListener(l);
dialog.startProcess(command, null, dir);
}
System.out.println("Running spice command: "+command);
}
if (Simulation.isParasiticsBackAnnotateLayout() && Simulation.isSpiceUseParasitics()) {
out.backAnnotateLayout();
}
// // run spice (if requested)
// var = getvalkey((INTBIG)sim_tool, VTOOL, VINTEGER, sim_dontrunkey);
// if (var != NOVARIABLE && var->addr != SIMRUNNO)
// {
// ttyputmsg(_("Running SPICE..."));
// var = getvalkey((INTBIG)sim_tool, VTOOL, VSTRING, sim_spice_listingfilekey);
// if (var == NOVARIABLE) sim_spice_execute(deckfile, x_(""), np); else
// sim_spice_execute(deckfile, (CHAR *)var->addr, np);
// }
}
/**
* Creates a new instance of Spice
*/
Spice()
{
}
protected void start()
{
// find the proper technology to use if this is schematics
if (topCell.getTechnology().isLayout())
layoutTechnology = topCell.getTechnology();
else
layoutTechnology = Schematics.getDefaultSchematicTechnology();
// make sure key is cached
spiceEngine = Simulation.getSpiceEngine();
preferedEngineTemplateKey = SPICE_TEMPLATE_KEY;
assuraHSpice = false;
switch (spiceEngine)
{
case SPICE_ENGINE_2: preferedEngineTemplateKey = SPICE_2_TEMPLATE_KEY; break;
case SPICE_ENGINE_3: preferedEngineTemplateKey = SPICE_3_TEMPLATE_KEY; break;
case SPICE_ENGINE_H: preferedEngineTemplateKey = SPICE_H_TEMPLATE_KEY; break;
case SPICE_ENGINE_P: preferedEngineTemplateKey = SPICE_P_TEMPLATE_KEY; break;
case SPICE_ENGINE_G: preferedEngineTemplateKey = SPICE_GC_TEMPLATE_KEY; break;
case SPICE_ENGINE_S: preferedEngineTemplateKey = SPICE_SM_TEMPLATE_KEY; break;
case SPICE_ENGINE_H_ASSURA: preferedEngineTemplateKey = SPICE_A_TEMPLATE_KEY; assuraHSpice = true; break;
case SPICE_ENGINE_H_CALIBRE: preferedEngineTemplateKey = SPICE_C_TEMPLATE_KEY; assuraHSpice = true; break;
}
if (assuraHSpice || (useCDL && !CDLWRITESEMPTYSUBCKTS) ||
(!useCDL && !Simulation.isSpiceWriteEmtpySubckts())) {
writeEmptySubckts = false;
}
// get the mask scale
maskScale = 1.0;
// Variable scaleVar = layoutTechnology.getVar("SIM_spice_mask_scale");
// if (scaleVar != null) maskScale = TextUtils.atof(scaleVar.getObject().toString());
// set up the parameterized cells
uniquifyCells = new HashMap<Cell,Cell>();
uniqueID = 0;
uniqueNames = new HashMap<String,Integer>();
checkIfParameterized(topCell);
// setup the legal characters
legalSpiceChars = SPICELEGALCHARS;
if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_P ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_G) legalSpiceChars = PSPICELEGALCHARS;
// start writing the spice deck
if (useCDL)
{
// setup bracket conversion for CDL
if (Simulation.isCDLConvertBrackets())
legalSpiceChars = CDLNOBRACKETLEGALCHARS;
multiLinePrint(true, "* First line is ignored\n");
// see if include file specified
String headerPath = TextUtils.getFilePath(topCell.getLibrary().getLibFile());
String filePart = Simulation.getCDLIncludeFile();
if (!filePart.equals("")) {
String fileName = headerPath + filePart;
File test = new File(fileName);
if (test.exists())
{
multiLinePrint(true, "* Primitives described in this file:\n");
addIncludeFile(filePart);
} else {
System.out.println("Warning: CDL Include file not found: "+fileName);
}
}
} else
{
writeHeader(topCell);
spiceCodeFlat = new FlatSpiceCodeVisitor(filePath+".flatcode", this);
HierarchyEnumerator.enumerateCell(topCell, VarContext.globalContext, spiceCodeFlat, true);
spiceCodeFlat.close();
}
if (Simulation.isParasiticsUseExemptedNetsFile()) {
String headerPath = TextUtils.getFilePath(topCell.getLibrary().getLibFile());
exemptedNets = new ExemptedNets(new File(headerPath + File.separator + "exemptedNets.txt"));
}
// gather all global signal names
/*
if (USE_GLOBALS)
{
Netlist netList = getNetlistForCell(topCell);
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (!Simulation.isSpiceUseNodeNames() || spiceEngine != Simulation.SPICE_ENGINE_3)
{
if (globalSize > 0)
{
StringBuffer infstr = new StringBuffer();
infstr.append("\n.global");
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
String name = global.getName();
if (global == Global.power) { if (getPowerName(null) != null) name = getPowerName(null); }
if (global == Global.ground) { if (getGroundName(null) != null) name = getGroundName(null); }
infstr.append(" " + name);
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
}
}
*/
}
protected void done()
{
if (!useCDL)
{
writeTrailer(topCell);
if (Simulation.isSpiceWriteFinalDotEnd())
multiLinePrint(false, ".END\n");
}
}
/**
* To write M factor information into given string buffer
* @param no Nodable representing the node
* @param infstr Buffer where to write to
*/
private void writeMFactor(VarContext context, Nodable no, StringBuffer infstr)
{
Variable mVar = no.getVar(Simulation.M_FACTOR_KEY);
if (mVar == null) return;
Object value = context.evalVar(mVar);
// check for M=@M, and warn user that this is a bad idea, and we will not write it out
if (mVar.getObject().toString().equals("@M") || (mVar.getObject().toString().equals("P(\"M\")"))) {
System.out.println("Warning: M=@M [eval="+value+"] on "+no.getName()+" is a bad idea, not writing it out: "+context.push(no).getInstPath("."));
return;
}
infstr.append(" M=" + formatParam(value.toString()));
}
/** Called at the end of the enter cell phase of hierarchy enumeration */
protected void enterCell(HierarchyEnumerator.CellInfo info) {
if (exemptedNets != null)
exemptedNets.setExemptedNets(info);
}
private Variable getEngineTemplate(Cell cell)
{
Variable varTemplate = null;
varTemplate = cell.getVar(preferedEngineTemplateKey);
if (!assuraHSpice) // null in case of NO_TEMPLATE_KEY
{
if (varTemplate == null)
varTemplate = cell.getVar(SPICE_TEMPLATE_KEY);
}
return varTemplate;
}
/**
* Method to write cellGeom
*/
protected void writeCellTopology(Cell cell, CellNetInfo cni, VarContext context, Topology.MyCellInfo info)
{
if (cell == topCell && USE_GLOBALS) {
Netlist netList = cni.getNetList();
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (!Simulation.isSpiceUseNodeNames() || spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_3)
{
if (globalSize > 0)
{
StringBuffer infstr = new StringBuffer();
infstr.append("\n.global");
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
String name = global.getName();
if (global == Global.power) { if (getPowerName(null) != null) name = getPowerName(null); }
if (global == Global.ground) { if (getGroundName(null) != null) name = getGroundName(null); }
infstr.append(" " + name);
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
}
}
// gather networks in the cell
Netlist netList = cni.getNetList();
// make sure power and ground appear at the top level
if (cell == topCell && !Simulation.isSpiceForceGlobalPwrGnd())
{
if (cni.getPowerNet() == null)
System.out.println("WARNING: cannot find power at top level of circuit");
if (cni.getGroundNet() == null)
System.out.println("WARNING: cannot find ground at top level of circuit");
}
// create list of electrical nets in this cell
HashMap<Network,SpiceNet> spiceNetMap = new HashMap<Network,SpiceNet>();
// create SpiceNet objects for all networks in the cell
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
// create a "SpiceNet" for the network
SpiceNet spNet = new SpiceNet();
spNet.network = net;
spNet.transistorCount = 0;
spNet.diffArea = 0;
spNet.diffPerim = 0;
spNet.nonDiffCapacitance = 0;
spNet.merge = new PolyMerge();
spiceNetMap.put(net, spNet);
}
// create list of segemented networks for parasitic extraction
boolean verboseSegmentedNames = Simulation.isParasiticsUseVerboseNaming();
boolean useParasitics = useNewParasitics && (!useCDL) &&
Simulation.isSpiceUseParasitics() && (cell.getView() == View.LAYOUT);
SegmentedNets segmentedNets = new SegmentedNets(cell, verboseSegmentedNames, cni, useParasitics);
segmentedParasiticInfo.add(segmentedNets);
if (useParasitics) {
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
//System.out.println("\n Finding parasitics for cell "+cell.describe(false));
HashMap<Network,Network> exemptedNetsFound = new HashMap<Network,Network>();
for (Iterator<ArcInst> ait = cell.getArcs(); ait.hasNext(); ) {
ArcInst ai = ait.next();
boolean ignoreArc = false;
// figure out res and cap, see if we should ignore it
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC)
ignoreArc = true;
double length = ai.getLambdaLength() * scale / 1000; // length in microns
double width = ai.getLambdaFullWidth() * scale / 1000; // width in microns
double area = length * width;
double fringe = length*2;
double cap = 0;
double res = 0;
Technology tech = ai.getProto().getTechnology();
Poly [] arcInstPolyList = tech.getShapeOfArc(ai);
int tot = arcInstPolyList.length;
for(int j=0; j<tot; j++)
{
Poly poly = arcInstPolyList[j];
if (poly.getStyle().isText()) continue;
Layer layer = poly.getLayer();
if (layer.getTechnology() != layoutTechnology) continue;
if ((layer.getFunctionExtras() & Layer.Function.PSEUDO) != 0) continue;
if (!layer.isDiffusionLayer() && layer.getCapacitance() > 0.0) {
double areacap = area * layer.getCapacitance();
double fringecap = fringe * layer.getEdgeCapacitance();
cap = areacap + fringecap;
res = length/width * layer.getResistance();
}
}
// add res if big enough
if (res <= cell.getTechnology().getMinResistance()) {
ignoreArc = true;
}
if (Simulation.isParasiticsUseExemptedNetsFile()) {
Network net = netList.getNetwork(ai, 0);
// ignore nets in exempted nets file
if (Simulation.isParasiticsIgnoreExemptedNets()) {
// check if this net is exempted
if (exemptedNets.isExempted(info.getNetID(net))) {
ignoreArc = true;
cap = 0;
if (!exemptedNetsFound.containsKey(net)) {
System.out.println("Not extracting net "+cell.describe(false)+" "+net.getName());
exemptedNetsFound.put(net, net);
cap = exemptedNets.getReplacementCap(cell, net);
}
}
// extract only nets in exempted nets file
} else {
if (exemptedNets.isExempted(info.getNetID(net)) && ignoreArc == false) {
if (!exemptedNetsFound.containsKey(net)) {
System.out.println("Extracting net "+cell.describe(false)+" "+net.getName());
exemptedNetsFound.put(net, net);
}
} else {
ignoreArc = true;
}
}
}
int arcPImodels = SegmentedNets.getNumPISegments(res, layoutTechnology.getMaxSeriesResistance());
if (ignoreArc)
arcPImodels = 1; // split cap to two pins if ignoring arc
// add caps
segmentedNets.putSegment(ai.getHeadPortInst(), cap/(arcPImodels+1));
segmentedNets.putSegment(ai.getTailPortInst(), cap/(arcPImodels+1));
if (ignoreArc) {
// short arc
segmentedNets.shortSegments(ai.getHeadPortInst(), ai.getTailPortInst());
} else {
segmentedNets.addArcRes(ai, res);
if (arcPImodels > 1)
segmentedNets.addArcCap(ai, cap); // need to store cap later to break it up
}
}
// Don't take into account gate resistance: so we need to short two PortInsts
// of gate together if this is layout
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
if (!ni.isCellInstance()) {
if (((PrimitiveNode)ni.getProto()).getGroupFunction() == PrimitiveNode.Function.TRANS) {
PortInst gate0 = ni.getTransistorGatePort();
PortInst gate1 = null;
for (Iterator<PortInst> pit = ni.getPortInsts(); pit.hasNext();) {
PortInst p2 = pit.next();
if (p2 != gate0 && netList.getNetwork(gate0) == netList.getNetwork(p2))
gate1 = p2;
}
if (gate1 != null) {
segmentedNets.shortSegments(gate0, gate1);
}
}
} else {
//System.out.println("Shorting shorted exports");
// short together pins if shorted by subcell
Cell subCell = (Cell)ni.getProto();
SegmentedNets subNets = getSegmentedNets(subCell);
// list of lists of shorted exports
if (subNets != null) { // subnets may be null if mixing schematics with layout technologies
for (Iterator<List<String>> it = subNets.getShortedExports(); it.hasNext(); ) {
List<String> exports = it.next();
PortInst pi1 = null;
// list of exports shorted together
for (String exportName : exports) {
// get portinst on node
PortInst pi = ni.findPortInst(exportName);
if (pi1 == null) {
pi1 = pi; continue;
}
segmentedNets.shortSegments(pi1, pi);
}
}
}
}
} // for (cell.getNodes())
}
// count the number of different transistor types
int bipolarTrans = 0, nmosTrans = 0, pmosTrans = 0;
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
addNodeInformation(netList, spiceNetMap, ni);
PrimitiveNode.Function fun = ni.getFunction();
if (fun == PrimitiveNode.Function.TRANPN || fun == PrimitiveNode.Function.TRA4NPN ||
fun == PrimitiveNode.Function.TRAPNP || fun == PrimitiveNode.Function.TRA4PNP ||
fun == PrimitiveNode.Function.TRANS) bipolarTrans++; else
if (fun == PrimitiveNode.Function.TRAEMES || fun == PrimitiveNode.Function.TRA4EMES ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRA4DMES ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS) nmosTrans++; else
if (fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS) pmosTrans++;
}
// accumulate geometry of all arcs
for(Iterator<ArcInst> aIt = cell.getArcs(); aIt.hasNext(); )
{
ArcInst ai = aIt.next();
// don't count non-electrical arcs
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC) continue;
// ignore busses
// if (ai->network->buswidth > 1) continue;
Network net = netList.getNetwork(ai, 0);
SpiceNet spNet = spiceNetMap.get(net);
if (spNet == null) continue;
addArcInformation(spNet.merge, ai);
}
// get merged polygons so far
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = spiceNetMap.get(net);
for (Layer layer : spNet.merge.getKeySet())
{
List<PolyBase> polyList = spNet.merge.getMergedPoints(layer, true);
if (polyList == null) continue;
if (polyList.size() > 1)
Collections.sort(polyList, GeometryHandler.shapeSort);
for(PolyBase poly : polyList)
{
// compute perimeter and area
double perim = poly.getPerimeter();
double area = poly.getArea();
// accumulate this information
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
if (layer.isDiffusionLayer()) {
spNet.diffArea += area * maskScale * maskScale;
spNet.diffPerim += perim * maskScale;
} else {
area = area * scale * scale / 1000000; // area in square microns
perim = perim * scale / 1000; // perim in microns
spNet.nonDiffCapacitance += layer.getCapacitance() * area * maskScale * maskScale;
spNet.nonDiffCapacitance += layer.getEdgeCapacitance() * perim * maskScale;
}
}
}
}
// make sure the ground net is number zero
Network groundNet = cni.getGroundNet();
Network powerNet = cni.getPowerNet();
if (pmosTrans != 0 && powerNet == null)
{
String message = "WARNING: no power connection for P-transistor wells in " + cell;
dumpErrorMessage(message);
}
if (nmosTrans != 0 && groundNet == null)
{
String message = "WARNING: no ground connection for N-transistor wells in " + cell;
dumpErrorMessage(message);
}
// // use ground net for substrate
// if (subnet == NOSPNET && sim_spice_gnd != NONETWORK)
// subnet = (SPNET *)sim_spice_gnd->temp1;
// if (bipolarTrans != 0 && subnet == NOSPNET)
// {
// infstr = initinfstr();
// formatinfstr(infstr, _("WARNING: no explicit connection to the substrate in cell %s"),
// describenodeproto(np));
// dumpErrorMessage(infstr);
// if (sim_spice_gnd != NONETWORK)
// {
// ttyputmsg(_(" A connection to ground will be used if necessary."));
// subnet = (SPNET *)sim_spice_gnd->temp1;
// }
// }
// generate header for subckt or top-level cell
String topLevelInstance = "";
if (cell == topCell && !useCDL && !Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(true, "\n*** TOP LEVEL CELL: " + cell.describe(false) + "\n");
} else
{
if (!writeEmptySubckts) {
if (cellIsEmpty(cell))
return;
}
String cellName = cni.getParameterizedName();
multiLinePrint(true, "\n*** CELL: " + cell.describe(false) + "\n");
StringBuffer infstr = new StringBuffer();
infstr.append(".SUBCKT " + cellName);
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
if (ignoreSubcktPort(cs)) continue;
if (cs.isGlobal()) {
System.out.println("Warning: Explicit Global signal "+cs.getName()+" exported in "+cell.describe(false));
}
// special case for parasitic extraction
if (useParasitics && !cs.isGlobal() && cs.getExport() != null) {
Network net = cs.getNetwork();
HashMap<String,List<String>> shortedExportsMap = new HashMap<String,List<String>>();
// For a single logical network, we need to:
// 1) treat certain exports as separate so as not to short resistors on arcs between the exports
// 2) join certain exports that do not have resistors on arcs between them, and record this information
// so that the next level up knows to short networks connection to those exports.
for (Iterator<Export> it = net.getExports(); it.hasNext(); ) {
Export e = it.next();
PortInst pi = e.getOriginalPort();
String name = segmentedNets.getNetName(pi);
// exports are shorted if their segmented net names are the same (case (2))
List<String> shortedExports = shortedExportsMap.get(name);
if (shortedExports == null) {
shortedExports = new ArrayList<String>();
shortedExportsMap.put(name, shortedExports);
// this is the first occurance of this segmented network,
// use the name as the export (1)
infstr.append(" " + name);
}
shortedExports.add(e.getName());
}
// record shorted exports
for (List<String> shortedExports : shortedExportsMap.values()) {
if (shortedExports.size() > 1) {
segmentedNets.addShortedExports(shortedExports);
}
}
} else {
infstr.append(" " + cs.getName());
}
}
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (USE_GLOBALS)
{
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
infstr.append(" " + cs.getName());
}
}
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
// create top level instantiation
if (Simulation.isSpiceWriteTopCellInstance())
topLevelInstance = infstr.toString().replaceFirst("\\.SUBCKT ", "X") + " " + cellName;
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this cell
for(Iterator<Variable> it = cell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (paramVar.getCode() != TextDescriptor.Code.SPICE) continue;
infstr.append(" " + paramVar.getTrueName() + "=" + paramVar.getPureValue(-1));
}
// for(Iterator it = cell.getVariables(); it.hasNext(); )
// {
// Variable paramVar = it.next();
// if (!paramVar.isParam()) continue;
// infstr.append(" " + paramVar.getTrueName() + "=" + paramVar.getPureValue(-1));
// }
}
// Writing M factor
//writeMFactor(cell, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
// generate pin descriptions for reference (when not using node names)
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
multiLinePrint(true, "** GLOBAL " + cs.getName() + "\n");
}
// write exports to this cell
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
// ignore networks that aren't exported
PortProto pp = cs.getExport();
if (pp == null) continue;
if (cs.isGlobal()) continue;
//multiLinePrint(true, "** PORT " + cs.getName() + "\n");
}
}
// write out any directly-typed SPICE declaratons for the cell
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech.invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_DECLARATION_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Declaration nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false);
}
}
// third pass through the node list, print it this time
for(Iterator<Nodable> nIt = netList.getNodables(); nIt.hasNext(); )
{
Nodable no = nIt.next();
NodeProto niProto = no.getProto();
// handle sub-cell calls
if (no.isCellInstance())
{
Cell subCell = (Cell)niProto;
// look for a SPICE template on the prototype
Variable varTemplate = null;
if (useCDL)
{
varTemplate = subCell.getVar(CDL_TEMPLATE_KEY);
} else
{
varTemplate = getEngineTemplate(subCell);
// varTemplate = subCell.getVar(preferedEngineTemplateKey);
// if (varTemplate == null)
// varTemplate = subCell.getVar(SPICE_TEMPLATE_KEY);
}
// handle templates
if (varTemplate != null)
{
if (varTemplate.getObject() instanceof Object[])
{
Object [] manyLines = (Object [])varTemplate.getObject();
for(int i=0; i<manyLines.length; i++)
{
String line = manyLines[i].toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
if (i == 0) writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
} else
{
String line = varTemplate.getObject().toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
continue;
}
// get the ports on this node (in proper order)
CellNetInfo subCni = getCellNetInfo(parameterizedName(no, context));
if (subCni == null) continue;
if (!writeEmptySubckts) {
// do not instantiate if empty
if (cellIsEmpty((Cell)niProto))
continue;
}
String modelChar = "X";
if (no.getName() != null) modelChar += getSafeNetName(no.getName(), false);
StringBuffer infstr = new StringBuffer();
infstr.append(modelChar);
for(Iterator<CellSignal> sIt = subCni.getCellSignals(); sIt.hasNext(); )
{
CellSignal subCS = sIt.next();
// ignore networks that aren't exported
PortProto pp = subCS.getExport();
Network net;
int exportIndex = subCS.getExportIndex();
// This checks if we are netlisting a schematic top level with
// swapped-in layout subcells
if (pp != null && (cell.getView() == View.SCHEMATIC) && (subCni.getCell().getView() == View.LAYOUT)) {
// find equivalent pp from layout to schematic
Network subNet = subCS.getNetwork(); // layout network name
boolean found = false;
for (Iterator<Export> eIt = subCell.getExports(); eIt.hasNext(); ) {
Export ex = eIt.next();
for (int i=0; i<ex.getNameKey().busWidth(); i++) {
String exName = ex.getNameKey().subname(i).toString();
if (exName.equals(subNet.getName())) {
pp = ex;
exportIndex = i;
found = true;
break;
}
}
if (found) break;
}
if (!found) {
if (pp.isGround() && pp.getName().startsWith("gnd")) {
infstr.append(" gnd");
} else if (pp.isPower() && pp.getName().startsWith("vdd")) {
infstr.append(" vdd");
} else {
System.out.println("No matching export on schematic/icon found for export "+
subNet.getName()+" in cell "+subCni.getCell().describe(false));
infstr.append(" unknown");
}
continue;
}
}
if (USE_GLOBALS)
{
if (pp == null) continue;
if (subCS.isGlobal() && subCS.getNetwork().isExported()) {
// only add to port list if exported with global name
if (!isGlobalExport(subCS)) continue;
}
net = netList.getNetwork(no, pp, exportIndex);
} else
{
if (pp == null && !subCS.isGlobal()) continue;
if (subCS.isGlobal())
net = netList.getNetwork(no, subCS.getGlobal());
else
net = netList.getNetwork(no, pp, exportIndex);
}
CellSignal cs = cni.getCellSignal(net);
// special case for parasitic extraction
if (useParasitics && !cs.isGlobal()) {
// connect to all exports (except power and ground of subcell net)
SegmentedNets subSegmentedNets = getSegmentedNets((Cell)no.getProto());
Network subNet = subCS.getNetwork();
List<String> exportNames = new ArrayList<String>();
for (Iterator<Export> it = subNet.getExports(); it.hasNext(); ) {
// get subcell export, unless collapsed due to less than min R
Export e = it.next();
PortInst pi = e.getOriginalPort();
String name = subSegmentedNets.getNetName(pi);
if (exportNames.contains(name)) continue;
exportNames.add(name);
// ok, there is a port on the subckt on this subcell for this export,
// now get the appropriate network in this cell
pi = no.getNodeInst().findPortInstFromProto(no.getProto().findPortProto(e.getNameKey()));
name = segmentedNets.getNetName(pi);
infstr.append(" " + name);
}
} else {
String name = cs.getName();
if (segmentedNets.getUseParasitics()) {
name = segmentedNets.getNetName(no.getNodeInst().findPortInstFromProto(pp));
}
infstr.append(" " + name);
}
}
if (USE_GLOBALS)
{
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
Global.Set globals = subCni.getNetList().getGlobals();
int globalSize = globals.size();
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
infstr.append(" " + global.getName());
}
}
}
if (useCDL) {
infstr.append(" /" + subCni.getParameterizedName());
} else {
infstr.append(" " + subCni.getParameterizedName());
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this instance
for(Iterator<Variable> it = subCell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
Variable instVar = no.getVar(paramVar.getKey());
String paramStr = "??";
if (instVar != null) {
if (paramVar.getCode() != TextDescriptor.Code.SPICE) continue;
Object obj = context.evalSpice(instVar, false);
if (obj != null)
paramStr = formatParam(String.valueOf(obj));
}
infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
}
// for(Iterator it = subCell.getVariables(); it.hasNext(); )
// {
// Variable paramVar = it.next();
// if (!paramVar.isParam()) continue;
// Variable instVar = no.getVar(paramVar.getKey());
// String paramStr = "??";
// if (instVar != null) paramStr = formatParam(trimSingleQuotes(String.valueOf(context.evalVar(instVar))));
// infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
// }
}
// Writing MFactor if available.
writeMFactor(context, no, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
continue;
}
// get the type of this node
NodeInst ni = (NodeInst)no;
PrimitiveNode.Function fun = ni.getFunction();
// handle resistors, inductors, capacitors, and diodes
if (fun.isResistor() || // == PrimitiveNode.Function.RESIST ||
fun == PrimitiveNode.Function.INDUCT ||
fun.isCapacitor() || // == PrimitiveNode.Function.CAPAC || fun == PrimitiveNode.Function.ECAPAC ||
fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
if (fun.isResistor()) // == PrimitiveNode.Function.RESIST)
{
if ((fun == PrimitiveNode.Function.PRESIST && isShortExplicitResistors()) ||
(fun == PrimitiveNode.Function.RESIST && isShortResistors()))
continue;
Variable resistVar = ni.getVar(Schematics.SCHEM_RESISTANCE);
String extra = "";
String partName = "R";
if (resistVar != null)
{
if (resistVar.getCode() == TextDescriptor.Code.SPICE) {
Object obj = context.evalSpice(resistVar, false);
extra = String.valueOf(obj);
}
- if (extra == null)
+ if (extra == "")
extra = resistVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); //displayedUnits(pureValue, TextDescriptor.Unit.RESISTANCE, TextUtils.UnitScale.NONE);
} else {
extra = "'"+extra+"'";
}
} else {
if (fun == PrimitiveNode.Function.PRESIST) {
partName = "XR";
double width = ni.getYSize();
double length = ni.getXSize();
SizeOffset offset = ni.getSizeOffset();
width = width - offset.getHighYOffset() - offset.getLowYOffset();
length = length - offset.getHighXOffset() - offset.getLowXOffset();
extra = " L='"+length+"*LAMBDA' W='"+width+"*LAMBDA'";
if (layoutTechnology == Technology.getCMOS90Technology() ||
(cell.getView() == View.LAYOUT && cell.getTechnology() == Technology.getCMOS90Technology())) {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "GND rpporpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "GND rnporpo"+extra;
}
} else {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "rppo1rpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "rnpo1rpo"+extra;
}
}
}
}
writeTwoPort(ni, partName, extra, cni, netList, context, segmentedNets);
} else if (fun.isCapacitor()) // == PrimitiveNode.Function.CAPAC || fun == PrimitiveNode.Function.ECAPAC)
{
Variable capacVar = ni.getVar(Schematics.SCHEM_CAPACITANCE);
String extra = "";
if (capacVar != null)
{
if (capacVar.getCode() == TextDescriptor.Code.SPICE) {
Object obj = context.evalSpice(capacVar, false);
extra = String.valueOf(obj);
}
- if (extra == null)
+ if (extra == "")
extra = capacVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.CAPACITANCE, TextUtils.UnitScale.NONE);
} else {
extra = "'"+extra+"'";
}
}
writeTwoPort(ni, "C", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.INDUCT)
{
Variable inductVar = ni.getVar(Schematics.SCHEM_INDUCTANCE);
String extra = "";
if (inductVar != null)
{
if (inductVar.getCode() == TextDescriptor.Code.SPICE) {
Object obj = context.evalSpice(inductVar, false);
extra = String.valueOf(obj);
}
- if (extra == null)
+ if (extra == "")
extra = inductVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.INDUCTANCE, TextUtils.UnitScale.NONE);
} else {
extra = "'"+extra+"'";
}
}
writeTwoPort(ni, "L", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
Variable diodeVar = ni.getVar(Schematics.SCHEM_DIODE);
String extra = "";
if (diodeVar != null)
extra = diodeVar.describe(context, ni);
if (extra.length() == 0) extra = "DIODE";
writeTwoPort(ni, "D", extra, cni, netList, context, segmentedNets);
}
continue;
}
// the default is to handle everything else as a transistor
if (((PrimitiveNode)niProto).getGroupFunction() != PrimitiveNode.Function.TRANS)
continue;
Network gateNet = netList.getNetwork(ni.getTransistorGatePort());
CellSignal gateCs = cni.getCellSignal(gateNet);
Network sourceNet = netList.getNetwork(ni.getTransistorSourcePort());
CellSignal sourceCs = cni.getCellSignal(sourceNet);
Network drainNet = netList.getNetwork(ni.getTransistorDrainPort());
CellSignal drainCs = cni.getCellSignal(drainNet);
CellSignal biasCs = null;
PortInst biasPort = ni.getTransistorBiasPort();
if (biasPort != null)
{
biasCs = cni.getCellSignal(netList.getNetwork(biasPort));
}
// make sure transistor is connected to nets
if (gateCs == null || sourceCs == null || drainCs == null)
{
String message = "WARNING: " + ni + " not fully connected in " + cell;
dumpErrorMessage(message);
}
// get model information
String modelName = null;
String defaultBulkName = null;
Variable modelVar = ni.getVar(SPICE_MODEL_KEY);
if (modelVar != null) modelName = modelVar.getObject().toString();
// special case for ST090 technology which has stupid non-standard transistor
// models which are subcircuits
boolean st090laytrans = false;
boolean tsmc090laytrans = false;
if (cell.getView() == View.LAYOUT && layoutTechnology == Technology.getCMOS90Technology()) {
if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.TSMC)
tsmc090laytrans = true;
else if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.ST)
st090laytrans = true;
}
String modelChar = "";
if (fun == PrimitiveNode.Function.TRANSREF) // self-referential transistor
{
modelChar = "X";
biasCs = cni.getCellSignal(groundNet);
modelName = niProto.getName();
} else if (fun == PrimitiveNode.Function.TRANMOS) // NMOS (Enhancement) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
defaultBulkName = "gnd";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRA4NMOS) // NMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRADMOS) // DMOS (Depletion) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRA4DMOS) // DMOS (Depletion) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRAPMOS) // PMOS (Complementary) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(powerNet);
defaultBulkName = "vdd";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRA4PMOS) // PMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRANPN) // NPN (Junction) transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRA4NPN) // NPN (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRAPNP) // PNP (Junction) transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRA4PNP) // PNP (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRANJFET) // NJFET (N Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRA4NJFET) // NJFET (N Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRAPJFET) // PJFET (P Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRA4PJFET) // PJFET (P Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRADMES || // DMES (Depletion) transistor
fun == PrimitiveNode.Function.TRA4DMES) // DMES (Depletion) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "DMES";
} else if (fun == PrimitiveNode.Function.TRAEMES || // EMES (Enhancement) transistor
fun == PrimitiveNode.Function.TRA4EMES) // EMES (Enhancement) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "EMES";
} else if (fun == PrimitiveNode.Function.TRANS) // special transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
}
if (ni.getName() != null) modelChar += getSafeNetName(ni.getName(), false);
StringBuffer infstr = new StringBuffer();
String drainName = drainCs.getName();
String gateName = gateCs.getName();
String sourceName = sourceCs.getName();
if (segmentedNets.getUseParasitics()) {
drainName = segmentedNets.getNetName(ni.getTransistorDrainPort());
gateName = segmentedNets.getNetName(ni.getTransistorGatePort());
sourceName = segmentedNets.getNetName(ni.getTransistorSourcePort());
}
infstr.append(modelChar + " " + drainName + " " + gateName + " " + sourceName);
if (biasCs != null) {
String biasName = biasCs.getName();
if (segmentedNets.getUseParasitics()) {
if (ni.getTransistorBiasPort() != null)
biasName = segmentedNets.getNetName(ni.getTransistorBiasPort());
}
infstr.append(" " + biasName);
} else {
if (cell.getView() == View.LAYOUT && defaultBulkName != null)
infstr.append(" " + defaultBulkName);
}
if (modelName != null) infstr.append(" " + modelName);
// compute length and width (or area for nonMOS transistors)
TransistorSize size = ni.getTransistorSize(context);
if (size == null)
System.out.println("Warning: transistor with null size " + ni.getName());
else
{
if (size.getDoubleWidth() > 0 || size.getDoubleLength() > 0)
{
double w = maskScale * size.getDoubleWidth();
double l = maskScale * size.getDoubleLength();
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
l -= lengthSubtraction;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
// make into microns (convert to nanometers then divide by 1000)
l *= layoutTechnology.getScale() / 1000.0;
w *= layoutTechnology.getScale() / 1000.0;
}
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
((fun == PrimitiveNode.Function.TRANJFET || fun == PrimitiveNode.Function.TRAPJFET ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRAEMES) &&
(spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_ASSURA)))
{
// schematic transistors may be text
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength()) + " - "+ lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength()));
} else {
infstr.append(" L=" + TextUtils.formatDouble(l, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String)) {
infstr.append(" W="+formatParam((String)size.getWidth()));
} else {
infstr.append(" W=" + TextUtils.formatDouble(w, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
if (fun != PrimitiveNode.Function.TRANMOS && fun != PrimitiveNode.Function.TRA4NMOS &&
fun != PrimitiveNode.Function.TRAPMOS && fun != PrimitiveNode.Function.TRA4PMOS &&
fun != PrimitiveNode.Function.TRADMOS && fun != PrimitiveNode.Function.TRA4DMOS)
{
infstr.append(" AREA=" + TextUtils.formatDouble(l*w, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda()) infstr.append("P");
}
} else {
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength()) + " - "+lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength()));
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String))
infstr.append(" W="+formatParam((String)size.getWidth()));
}
}
// make sure transistor is connected to nets
SpiceNet spNetGate = spiceNetMap.get(gateNet);
SpiceNet spNetSource = spiceNetMap.get(sourceNet);
SpiceNet spNetDrain = spiceNetMap.get(drainNet);
if (spNetGate == null || spNetSource == null || spNetDrain == null) continue;
// compute area of source and drain
if (!useCDL)
{
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS)
{
double as = 0, ad = 0, ps = 0, pd = 0;
if (spNetSource.transistorCount != 0)
{
as = spNetSource.diffArea / spNetSource.transistorCount;
ps = spNetSource.diffPerim / spNetSource.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
as *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
ps *= layoutTechnology.getScale() / 1000.0;
}
}
if (spNetDrain.transistorCount != 0)
{
ad = spNetDrain.diffArea / spNetDrain.transistorCount;
pd = spNetDrain.diffPerim / spNetDrain.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
ad *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
pd *= layoutTechnology.getScale() / 1000.0;
}
}
if (as > 0.0)
{
infstr.append(" AS=" + TextUtils.formatDouble(as, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ad > 0.0)
{
infstr.append(" AD=" + TextUtils.formatDouble(ad, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ps > 0.0)
{
infstr.append(" PS=" + TextUtils.formatDouble(ps, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if (pd > 0.0)
{
infstr.append(" PD=" + TextUtils.formatDouble(pd, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
}
// Writing MFactor if available.
writeMFactor(context, ni, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
// print resistances and capacitances
if (!useCDL)
{
if (Simulation.isSpiceUseParasitics() && cell.getView() == View.LAYOUT)
{
if (useNewParasitics) {
int capCount = 0;
int resCount = 0;
// write caps
multiLinePrint(true, "** Extracted Parasitic Capacitors ***\n");
for (SegmentedNets.NetInfo netInfo : segmentedNets.getUniqueSegments()) {
if (netInfo.cap > cell.getTechnology().getMinCapacitance()) {
if (netInfo.netName.equals("gnd")) continue; // don't write out caps from gnd to gnd
multiLinePrint(false, "C" + capCount + " " + netInfo.netName + " 0 " + TextUtils.formatDouble(netInfo.cap, 2) + "fF\n");
capCount++;
}
}
// write resistors
multiLinePrint(true, "** Extracted Parasitic Resistors ***\n");
for (Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) {
ArcInst ai = it.next();
Double res = segmentedNets.arcRes.get(ai);
if (res == null) continue;
String n0 = segmentedNets.getNetName(ai.getHeadPortInst());
String n1 = segmentedNets.getNetName(ai.getTailPortInst());
int arcPImodels = SegmentedNets.getNumPISegments(res.doubleValue(), layoutTechnology.getMaxSeriesResistance());
if (arcPImodels > 1) {
// have to break it up into smaller pieces
double segCap = segmentedNets.getArcCap(ai)/((double)(arcPImodels+1));
double segRes = res.doubleValue()/((double)arcPImodels);
String segn0 = n0;
String segn1 = n0;
for (int i=0; i<arcPImodels; i++) {
segn1 = n0 + "##" + i;
// print cap on intermediate node
if (i == (arcPImodels-1))
segn1 = n1;
multiLinePrint(false, "R"+resCount+" "+segn0+" "+segn1+" "+TextUtils.formatDouble(segRes)+"\n");
resCount++;
if (i < (arcPImodels-1)) {
if (!segn1.equals("gnd")) {
multiLinePrint(false, "C"+capCount+" "+segn1+" 0 "+TextUtils.formatDouble(segCap)+"fF\n");
capCount++;
}
}
segn0 = segn1;
}
} else {
multiLinePrint(false, "R" + resCount + " " + n0 + " " + n1 + " " + TextUtils.formatDouble(res.doubleValue(), 2) + "\n");
resCount++;
}
}
} else {
// print parasitic capacitances
boolean first = true;
int capacNum = 1;
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
Network net = cs.getNetwork();
if (net == cni.getGroundNet()) continue;
SpiceNet spNet = spiceNetMap.get(net);
if (spNet.nonDiffCapacitance > layoutTechnology.getMinCapacitance())
{
if (first)
{
first = false;
multiLinePrint(true, "** Extracted Parasitic Elements:\n");
}
multiLinePrint(false, "C" + capacNum + " " + cs.getName() + " 0 " + TextUtils.formatDouble(spNet.nonDiffCapacitance, 2) + "fF\n");
capacNum++;
}
}
}
}
}
// write out any directly-typed SPICE cards
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech.invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_CARD_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Code nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false);
}
}
// finally, if this is the top level,
// write out some very small resistors between any networks
// that are asserted will be connected by the NCC annotation "exportsConnectedByParent"
// this should really be done internally in the network tool with a switch, but
// this hack works here for now
NccCellAnnotations anna = NccCellAnnotations.getAnnotations(cell);
if (cell == topCell && anna != null) {
// each list contains all name patterns that are be shorted together
if (anna.getExportsConnected().hasNext()) {
multiLinePrint(true, "\n*** Exports shorted due to NCC annotation 'exportsConnectedByParent':\n");
}
for (Iterator<List<NamePattern>> it = anna.getExportsConnected(); it.hasNext(); ) {
List<NamePattern> list = it.next();
List<Network> netsToConnect = new ArrayList<Network>();
// each name pattern can match any number of exports in the cell
for (NccCellAnnotations.NamePattern pat : list) {
for (Iterator<PortProto> it3 = cell.getPorts(); it3.hasNext(); ) {
Export e = (Export)it3.next();
String name = e.getName();
// keep track of networks to short together
if (pat.matches(name)) {
Network net = netList.getNetwork(e, 0);
if (!netsToConnect.contains(net))
netsToConnect.add(net);
}
}
}
// connect all nets in list of nets to connect
String name = null;
// int i=0;
for (Network net : netsToConnect) {
if (name != null) {
multiLinePrint(false, "R"+name+" "+name+" "+net.getName()+" 0.001\n");
}
name = net.getName();
// i++;
}
}
}
// now we're finished writing the subcircuit.
if (cell != topCell || useCDL || Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(false, ".ENDS " + cni.getParameterizedName() + "\n");
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
multiLinePrint(false, "\n\n"+topLevelInstance+"\n\n");
}
}
private void emitEmbeddedSpice(Variable cardVar, VarContext context, SegmentedNets segmentedNets, HierarchyEnumerator.CellInfo info, boolean flatNetNames)
{
Object obj = cardVar.getObject();
if (!(obj instanceof String) && !(obj instanceof String[])) return;
if (!cardVar.isDisplay()) return;
if (obj instanceof String)
{
StringBuffer buf = replacePortsAndVars((String)obj, context.getNodable(), context.pop(), null, segmentedNets, info, flatNetNames);
buf.append('\n');
String msg = buf.toString();
boolean isComment = false;
if (msg.startsWith("*")) isComment = true;
multiLinePrint(isComment, msg);
} else
{
String [] strings = (String [])obj;
for(int i=0; i<strings.length; i++)
{
StringBuffer buf = replacePortsAndVars(strings[i], context.getNodable(), context.pop(), null, segmentedNets, info, flatNetNames);
buf.append('\n');
String msg = buf.toString();
boolean isComment = false;
if (msg.startsWith("*")) isComment = true;
multiLinePrint(isComment, msg);
}
}
}
/**
* Check if the specified cell is parameterized. Note that this
* recursively checks all cells below this cell as well, and marks
* all cells that contain LE gates, or whose subcells contain LE gates,
* as parameterized.
* @return true if cell has been marked as parameterized
*/
private boolean checkIfParameterized(Cell cell) {
//System.out.println("Checking Cell "+cell.describe());
boolean mark = false;
for (Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); ) {
NodeInst ni = it.next();
if (!ni.isCellInstance()) continue;
if (ni.isIconOfParent()) continue;
if (ni.getVar(LENetlister.ATTR_LEGATE) != null) {
// make sure cell also has that var
Cell np = (Cell)ni.getProto();
if (np.contentsView() != null) np = np.contentsView();
if (np.getVar(LENetlister.ATTR_LEGATE) != null)
mark = true; continue;
}
if (ni.getVar(LENetlister.ATTR_LEKEEPER) != null) {
// make sure cell also has that var
Cell np = (Cell)ni.getProto();
if (np.contentsView() != null) np = np.contentsView();
if (np.getVar(LENetlister.ATTR_LEKEEPER) != null)
mark = true; continue;
}
Cell proto = ((Cell)ni.getProto()).contentsView();
if (proto == null) proto = (Cell)ni.getProto();
if (checkIfParameterized(proto)) { mark = true; }
}
if (mark)
uniquifyCells.put(cell, cell);
//System.out.println("---> "+cell.describe()+" is marked "+mark);
return mark;
}
/*
* Method to create a parameterized name for node instance "ni".
* If the node is not parameterized, returns zero.
* If it returns a name, that name must be deallocated when done.
*/
protected String parameterizedName(Nodable no, VarContext context)
{
Cell cell = (Cell)no.getProto();
StringBuffer uniqueCellName = new StringBuffer(getUniqueCellName(cell));
if (uniquifyCells.get(cell) != null) {
// if this cell is marked to be make unique, make a unique name out of the var context
VarContext vc = context.push(no);
uniqueCellName.append("_"+vc.getInstPath("."));
} else {
boolean useCellParams = !useCDL && Simulation.isSpiceUseCellParameters();
if (canParameterizeNames() && no.isCellInstance() && !SCLibraryGen.isStandardCell(cell))
{
// if there are parameters, append them to this name
List<Variable> paramValues = new ArrayList<Variable>();
for(Iterator<Variable> it = no.getVariables(); it.hasNext(); )
{
Variable var = it.next();
if (!no.getNodeInst().isParam(var.getKey())) continue;
// if (!var.isParam()) continue;
Variable cellvar = cell.getVar(var.getKey());
if (useCellParams && (cellvar.getCode() == TextDescriptor.Code.SPICE)) {
continue;
}
paramValues.add(var);
}
for(Variable var : paramValues)
{
String eval = var.describe(context, no);
//Object eval = context.evalVar(var, no);
if (eval == null) continue;
//uniqueCellName += "-" + var.getTrueName() + "-" + eval.toString();
uniqueCellName.append("-" + eval.toString());
}
}
}
// if it is over the length limit, truncate it
int limit = maxNameLength();
if (limit > 0 && uniqueCellName.length() > limit)
{
Integer i = uniqueNames.get(uniqueCellName.toString());
if (i == null) {
i = new Integer(uniqueID);
uniqueID++;
uniqueNames.put(uniqueCellName.toString(), i);
}
uniqueCellName = uniqueCellName.delete(limit-10, uniqueCellName.length());
uniqueCellName.append("-ID"+i);
}
// make it safe
return getSafeCellName(uniqueCellName.toString());
}
/**
* Replace ports and vars in 'line'. Ports and Vars should be
* referenced via $(name)
* @param line the string to search and replace within
* @param no the nodable up the hierarchy that has the parameters on it
* @param context the context of the nodable
* @param cni the cell net info of cell in which the nodable exists (if cni is
* null, no port name replacement will be done)
* @return the modified line
*/
private StringBuffer replacePortsAndVars(String line, Nodable no, VarContext context,
CellNetInfo cni, SegmentedNets segmentedNets,
HierarchyEnumerator.CellInfo info, boolean flatNetNames) {
StringBuffer infstr = new StringBuffer();
Cell subCell = null;
if (no != null)
{
subCell = (Cell)no.getProto();
}
for(int pt = 0; pt < line.length(); pt++)
{
char chr = line.charAt(pt);
if (chr != '$' || pt+1 >= line.length() || line.charAt(pt+1) != '(')
{
infstr.append(chr);
continue;
}
int start = pt + 2;
for(pt = start; pt < line.length(); pt++)
if (line.charAt(pt) == ')') break;
// do the parameter substitution
String paramName = line.substring(start, pt);
PortProto pp = null;
if (subCell != null) {
pp = subCell.findPortProto(paramName);
}
Variable.Key varKey;
if (paramName.equalsIgnoreCase("node_name") && no != null)
{
String nodeName = getSafeNetName(no.getName(), false);
// nodeName = nodeName.replaceAll("[\\[\\]]", "_");
infstr.append(nodeName);
} else if (cni != null && pp != null)
{
// port name found: use its spice node
Network net = cni.getNetList().getNetwork(no, pp, 0);
CellSignal cs = cni.getCellSignal(net);
String portName = cs.getName();
if (segmentedNets.getUseParasitics()) {
PortInst pi = no.getNodeInst().findPortInstFromProto(pp);
portName = segmentedNets.getNetName(pi);
}
if (flatNetNames) {
portName = info.getUniqueNetName(net, ".");
}
infstr.append(portName);
} else if (no != null && (varKey = Variable.findKey("ATTR_" + paramName)) != null)
{
// no port name found, look for variable name
Variable attrVar = null;
//Variable.Key varKey = Variable.findKey("ATTR_" + paramName);
if (varKey != null) {
attrVar = no.getVar(varKey);
if (attrVar == null) attrVar = no.getParameter(varKey);
}
if (attrVar == null) infstr.append("??"); else
{
String pVal = "?";
Variable parentVar = attrVar;
if (subCell != null)
parentVar = subCell.getVar(attrVar.getKey());
if (!useCDL && Simulation.isSpiceUseCellParameters() &&
parentVar.getCode() == TextDescriptor.Code.SPICE) {
Object obj = context.evalSpice(attrVar, false);
if (obj != null)
pVal = obj.toString();
} else {
pVal = String.valueOf(context.evalVar(attrVar, no));
}
if (attrVar.getCode() != TextDescriptor.Code.NONE) pVal = trimSingleQuotes(pVal);
infstr.append(pVal);
//else
// infstr.append(trimSingleQuotes(attrVar.getPureValue(-1, -1)));
}
} else {
// look for the network name
boolean found = false;
String hierName = null;
String [] names = paramName.split("\\.");
if (names.length > 1 && flatNetNames) {
// hierarchical name, down hierarchy
Cell thisCell = info.getCell();
Netlist thisNetlist = info.getNetlist();
VarContext thisContext = context;
if (no != null) {
// push it back on, it got popped off in "embedSpice..."
thisContext = thisContext.push(no);
}
for (int i=0; i<names.length-1; i++) {
boolean foundno = false;
for (Iterator<Nodable> it = thisNetlist.getNodables(); it.hasNext(); ) {
Nodable subno = it.next();
if (subno.getName().equals(names[i])) {
if (subno.getProto() instanceof Cell) {
thisCell = (Cell)subno.getProto();
thisNetlist = thisNetlist.getNetlist(subno);
thisContext = thisContext.push(subno);
}
foundno = true;
continue;
}
}
if (!foundno) {
System.out.println("Unable to find "+names[i]+" in "+paramName);
break;
}
}
Network net = findNet(thisNetlist, names[names.length-1]);
if (net != null) {
HierarchyEnumerator.NetNameProxy proxy = new HierarchyEnumerator.NetNameProxy(
thisContext, ".x", net);
Global g = getGlobal(proxy.getNet());
if (g != null)
hierName = g.getName();
else
hierName = proxy.toString();
}
} else {
// net may be exported and named at higher level, use getUniqueName
Network net = findNet(info.getNetlist(), paramName);
if (net != null) {
if (flatNetNames) {
HierarchyEnumerator.NetNameProxy proxy = info.getUniqueNetNameProxy(net, ".x");
Global g = getGlobal(proxy.getNet());
if (g != null)
hierName = g.getName();
else
hierName = proxy.toString();
} else {
hierName = cni.getCellSignal(net).getName();
}
}
}
// convert to spice format
if (hierName != null) {
if (flatNetNames) {
if (hierName.indexOf(".x") > 0) {
hierName = "x"+hierName;
}
// remove x in front of net name
int i = hierName.lastIndexOf(".x");
if (i > 0)
hierName = hierName.substring(0, i+1) + hierName.substring(i+2);
else {
i = hierName.lastIndexOf("."+paramName);
if (i > 0) {
hierName = hierName.substring(0, i) + "_" + hierName.substring(i+1);
}
}
}
infstr.append(hierName);
found = true;
}
if (!found) {
System.out.println("Unable to lookup key $("+paramName+") in cell "+context.getInstPath("."));
}
}
}
return infstr;
}
private Network findNet(Netlist netlist, String netName) {
Network foundnet = null;
for (Iterator<Network> it = netlist.getNetworks(); it.hasNext(); ) {
Network net = it.next();
if (net.hasName(netName)) {
foundnet = net;
break;
}
}
return foundnet;
}
/**
* Get the global associated with this net. Returns null if net is
* not a global.
* @param net
* @return global associated with this net, or null if not global
*/
private Global getGlobal(Network net) {
Netlist netlist = net.getNetlist();
for (int i=0; i<netlist.getGlobals().size(); i++) {
Global g = netlist.getGlobals().get(i);
if (netlist.getNetwork(g) == net)
return g;
}
return null;
}
/**
* Check if the global cell signal is exported as with a global name,
* rather than just being a global tied to some other export.
* I.e., returns true if global "gnd" has been exported using name "gnd".
* @param cs
* @return true if global signal exported with global name
*/
private boolean isGlobalExport(CellSignal cs) {
if (!cs.isGlobal() || !cs.isExported()) return false;
for (Iterator<Export> it = cs.getNetwork().getExports(); it.hasNext(); ) {
Export ex = it.next();
for (int i=0; i<ex.getNameKey().busWidth(); i++) {
String name = ex.getNameKey().subname(i).canonicString();
if (cs.getName().equals(name)) {
return true;
}
}
}
return false;
}
private boolean ignoreSubcktPort(CellSignal cs) {
// ignore networks that aren't exported
PortProto pp = cs.getExport();
if (USE_GLOBALS)
{
if (pp == null) return true;
if (cs.isGlobal() && !cs.getNetwork().isExported()) return true;
if (cs.isGlobal() && cs.getNetwork().isExported()) {
// only add to port list if exported with global name
if (!isGlobalExport(cs)) return true;
}
} else
{
if (pp == null && !cs.isGlobal()) return true;
}
if (useCDL)
{
// // if this is output and the last was input (or visa-versa), insert "/"
// if (i > 0 && netlist[i-1]->temp2 != net->temp2)
// infstr.append(" /");
}
return false;
}
/**
* Class to take care of added networks in cell due to
* extracting resistance of arcs. Takes care of naming,
* addings caps at portinst locations (due to PI model end caps),
* and storing resistance of arcs.
* <P>
* A network is broken into segments at all PortInsts along the network.
* Each PortInst is given a new net segment name. These names are used
* to write out caps and resistors. Each Arc writes out a PI model
* (a cap on each end and a resistor in the middle). Sometimes, an arc
* has very little or zero resistance, or we want to ignore it. Then
* we must short two portinsts together into the same net segment.
* However, we do not discard the capacitance, but continue to add it up.
*/
private static class SegmentedNets {
private static Comparator<PortInst> PORT_INST_COMPARATOR = new Comparator<PortInst>() {
public int compare(PortInst p1, PortInst p2) {
if (p1 == p2) return 0;
int cmp = p1.getNodeInst().compareTo(p2.getNodeInst());
if (cmp != 0) return cmp;
if (p1.getPortIndex() < p2.getPortIndex()) return -1;
return 1;
}
};
private static class NetInfo implements Comparable {
private String netName = "unassigned";
private double cap = 0;
private TreeSet<PortInst> joinedPorts = new TreeSet<PortInst>(PORT_INST_COMPARATOR); // list of portInsts on this new net
/**
* Compares NetInfos by thier first PortInst.
* @param obj the other NetInfo.
* @return a comparison between the NetInfos.
*/
public int compareTo(Object obj) {
NetInfo that = (NetInfo)obj;
if (this.joinedPorts.isEmpty()) return that.joinedPorts.isEmpty() ? 0 : -1;
if (that.joinedPorts.isEmpty()) return 1;
return PORT_INST_COMPARATOR.compare(this.joinedPorts.first(), that.joinedPorts.first());
}
}
private HashMap<PortInst,NetInfo> segmentedNets; // key: portinst, obj: PortInstInfo
private HashMap<ArcInst,Double> arcRes; // key: arcinst, obj: Double (arc resistance)
boolean verboseNames = false; // true to give renamed nets verbose names
private CellNetInfo cni; // the Cell's net info
boolean useParasitics = false; // disable or enable netname remapping
private HashMap<Network,Integer> netCounters; // key: net, obj: Integer - for naming segments
private Cell cell;
private List<List<String>> shortedExports; // list of lists of export names shorted together
private HashMap<ArcInst,Double> longArcCaps; // for arcs to be broken up into multiple PI models, need to record cap
private SegmentedNets(Cell cell, boolean verboseNames, CellNetInfo cni, boolean useParasitics) {
segmentedNets = new HashMap<PortInst,NetInfo>();
arcRes = new HashMap<ArcInst,Double>();
this.verboseNames = verboseNames;
this.cni = cni;
this.useParasitics = useParasitics;
netCounters = new HashMap<Network,Integer>();
this.cell = cell;
shortedExports = new ArrayList<List<String>>();
longArcCaps = new HashMap<ArcInst,Double>();
}
// don't call this method outside of SegmentedNets
// Add a new PortInst net segment
private NetInfo putSegment(PortInst pi, double cap) {
// create new info for PortInst
NetInfo info = segmentedNets.get(pi);
if (info == null) {
info = new NetInfo();
info.netName = getNewName(pi, info);
info.cap += cap;
if (isPowerGround(pi)) info.cap = 0; // note if you remove this line,
// you have to explicity short all
// power portinsts together, or you can get duplicate caps
info.joinedPorts.add(pi);
segmentedNets.put(pi, info);
} else {
info.cap += cap;
//assert(info.joinedPorts.contains(pi)); // should already contain pi if info already exists
}
return info;
}
// don't call this method outside of SegmentedNets
// Get a new name for the net segment associated with the portinst
private String getNewName(PortInst pi, NetInfo info) {
Network net = cni.getNetList().getNetwork(pi);
CellSignal cs = cni.getCellSignal(net);
if (!useParasitics || (!Simulation.isParasiticsExtractPowerGround() &&
isPowerGround(pi))) return cs.getName();
Integer i = netCounters.get(net);
if (i == null) {
i = new Integer(0);
netCounters.put(net, i);
}
// get new name
String name = info.netName;
Export ex = pi.getExports().hasNext() ? pi.getExports().next() : null;
//if (ex != null && ex.getName().equals(cs.getName())) {
if (ex != null) {
name = ex.getName();
} else {
if (i.intValue() == 0 && !cs.isExported()) // get rid of #0 if net not exported
name = cs.getName();
else {
if (verboseNames)
name = cs.getName() + "#" + i.intValue() + pi.getNodeInst().getName() + "_" + pi.getPortProto().getName();
else
name = cs.getName() + "#" + i.intValue();
}
i = new Integer(i.intValue() + 1);
netCounters.put(net, i);
}
return name;
}
// short two net segments together by their portinsts
private void shortSegments(PortInst p1, PortInst p2) {
if (!segmentedNets.containsKey(p1))
putSegment(p1, 0);
if (!segmentedNets.containsKey(p2));
putSegment(p2, 0);
NetInfo info1 = segmentedNets.get(p1);
NetInfo info2 = segmentedNets.get(p2);
if (info1 == info2) return; // already joined
// short
//System.out.println("Shorted together "+info1.netName+ " and "+info2.netName);
info1.joinedPorts.addAll(info2.joinedPorts);
info1.cap += info2.cap;
if (TextUtils.STRING_NUMBER_ORDER.compare(info2.netName, info1.netName) < 0) {
// if (info2.netName.compareTo(info1.netName) < 0) {
info1.netName = info2.netName;
}
//info1.netName += info2.netName;
// replace info2 with info1, info2 is no longer used
// need to do for every portinst in merged segment
for (PortInst pi : info1.joinedPorts)
segmentedNets.put(pi, info1);
}
// get the segment name for the portinst.
// if no parasitics, this is just the CellSignal name.
private String getNetName(PortInst pi) {
if (!useParasitics || (isPowerGround(pi) &&
!Simulation.isParasiticsExtractPowerGround())) {
CellSignal cs = cni.getCellSignal(cni.getNetList().getNetwork(pi));
//System.out.println("CellSignal name for "+pi.getNodeInst().getName()+"."+pi.getPortProto().getName()+" is "+cs.getName());
//System.out.println("NETWORK NAMED "+cs.getName());
return cs.getName();
}
NetInfo info = segmentedNets.get(pi);
if (info == null) {
info = putSegment(pi, 0);
}
//System.out.println("NETWORK INAMED "+info.netName);
return info.netName;
}
private void addArcRes(ArcInst ai, double res) {
// short out if both conns are power/ground
if (isPowerGround(ai.getHeadPortInst()) && isPowerGround(ai.getTailPortInst()) &&
!Simulation.isParasiticsExtractPowerGround()) {
shortSegments(ai.getHeadPortInst(), ai.getTailPortInst());
return;
}
arcRes.put(ai, new Double(res));
}
private boolean isPowerGround(PortInst pi) {
Network net = cni.getNetList().getNetwork(pi);
CellSignal cs = cni.getCellSignal(net);
if (cs.isPower() || cs.isGround()) return true;
if (cs.getName().startsWith("vdd")) return true;
if (cs.getName().startsWith("gnd")) return true;
return false;
}
/**
* Return list of NetInfos for unique segments
* @return a list of al NetInfos
*/
private TreeSet<NetInfo> getUniqueSegments() {
return new TreeSet<NetInfo>(segmentedNets.values());
}
private boolean getUseParasitics() {
return useParasitics;
}
// list of export names (Strings)
private void addShortedExports(List<String> exports) {
shortedExports.add(exports);
}
// list of lists of export names (Strings)
private Iterator<List<String>> getShortedExports() { return shortedExports.iterator(); }
public static int getNumPISegments(double res, double maxSeriesResistance) {
int arcPImodels = 1;
arcPImodels = (int)(res/maxSeriesResistance); // need preference here
if ((res % maxSeriesResistance) != 0) arcPImodels++;
return arcPImodels;
}
// for arcs of larger than max series resistance, we need to break it up into
// multiple PI models. So, we need to store the cap associated with the arc
private void addArcCap(ArcInst ai, double cap) {
longArcCaps.put(ai, new Double(cap));
}
private double getArcCap(ArcInst ai) {
Double d = longArcCaps.get(ai);
return d.doubleValue();
}
}
private SegmentedNets getSegmentedNets(Cell cell) {
for (SegmentedNets seg : segmentedParasiticInfo) {
if (seg.cell == cell) return seg;
}
return null;
}
private void backAnnotateLayout()
{
Set<Cell> cellsToClear = new HashSet<Cell>();
List<PortInst> capsOnPorts = new ArrayList<PortInst>();
List<String> valsOnPorts = new ArrayList<String>();
List<ArcInst> resOnArcs = new ArrayList<ArcInst>();
List<Double> valsOnArcs = new ArrayList<Double>();
for (SegmentedNets segmentedNets : segmentedParasiticInfo)
{
Cell cell = segmentedNets.cell;
if (cell.getView() != View.LAYOUT) continue;
// gather cells to clear capacitor values
cellsToClear.add(cell);
// gather capacitor updates
for (SegmentedNets.NetInfo info : segmentedNets.getUniqueSegments())
{
PortInst pi = info.joinedPorts.iterator().next();
if (info.cap > cell.getTechnology().getMinCapacitance())
{
capsOnPorts.add(pi);
valsOnPorts.add(TextUtils.formatDouble(info.cap, 2) + "fF");
}
}
// gather resistor updates
for (Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); )
{
ArcInst ai = it.next();
Double res = segmentedNets.arcRes.get(ai);
Variable var = ai.getVar(ATTR_R);
resOnArcs.add(ai);
valsOnArcs.add(res);
}
}
new BackAnnotateJob(cellsToClear, capsOnPorts, valsOnPorts, resOnArcs, valsOnArcs);
}
private static class BackAnnotateJob extends Job
{
private Set<Cell> cellsToClear;
private List<PortInst> capsOnPorts;
private List<String> valsOnPorts;
private List<ArcInst> resOnArcs;
private List<Double> valsOnArcs;
private BackAnnotateJob(Set<Cell> cellsToClear, List<PortInst> capsOnPorts, List<String> valsOnPorts,
List<ArcInst> resOnArcs, List<Double> valsOnArcs)
{
super("Spice Layout Back Annotate", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.capsOnPorts = capsOnPorts;
this.valsOnPorts = valsOnPorts;
this.resOnArcs = resOnArcs;
this.valsOnArcs = valsOnArcs;
this.cellsToClear = cellsToClear;
startJob();
}
public boolean doIt() throws JobException
{
TextDescriptor ctd = TextDescriptor.getPortInstTextDescriptor().withDispPart(TextDescriptor.DispPos.NAMEVALUE);
TextDescriptor rtd = TextDescriptor.getArcTextDescriptor().withDispPart(TextDescriptor.DispPos.NAMEVALUE);
int capCount = 0;
int resCount = 0;
// clear caps on layout
for(Cell cell : cellsToClear)
{
// delete all C's already on layout
for (Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
for (Iterator<PortInst> pit = ni.getPortInsts(); pit.hasNext(); )
{
PortInst pi = pit.next();
Variable var = pi.getVar(ATTR_C);
if (var != null) pi.delVar(var.getKey());
}
}
}
// add new C's
for(int i=0; i<capsOnPorts.size(); i++)
{
PortInst pi = capsOnPorts.get(i);
String str = valsOnPorts.get(i);
pi.newVar(ATTR_C, str, ctd);
resCount++;
}
// add new R's
for(int i=0; i<resOnArcs.size(); i++)
{
ArcInst ai = resOnArcs.get(i);
Double res = valsOnArcs.get(i);
// delete R if no new one
Variable var = ai.getVar(ATTR_R);
if (res == null && var != null)
ai.delVar(ATTR_R);
// change R if new one
if (res != null)
{
ai.newVar(ATTR_R, res, rtd);
resCount++;
}
}
System.out.println("Back-annotated "+resCount+" Resistors and "+capCount+" Capacitors");
return true;
}
}
/**
* These are nets that are either extracted when nothing else is extracted,
* or not extracted during extraction. They are specified via the top level
* net cell + name, any traversal of that net down the hierarchy is also not extracted.
*/
private static class ExemptedNets {
private HashMap<Cell,List<Net>> netsByCell; // key: cell, value: List of ExemptedNets.Net objects
private Set<Integer> exemptedNetIDs;
private static class Net {
private String name;
private double replacementCap;
}
private ExemptedNets(File file) {
netsByCell = new HashMap<Cell,List<Net>>();
exemptedNetIDs = new TreeSet<Integer>();
try {
FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader);
String line;
int lineno = 1;
System.out.println("Using exempted nets file "+file.getAbsolutePath());
while ((line = br.readLine()) != null) {
processLine(line, lineno);
lineno++;
}
} catch (IOException e) {
System.out.println(e.getMessage());
return;
}
}
private void processLine(String line, int lineno) {
if (line == null) return;
if (line.trim().equals("")) return;
String parts[] = line.trim().split("\\s+");
if (parts.length < 3) {
System.out.println("Error on line "+lineno+": Expected 'LibraryName CellName NetName', but was "+line);
return;
}
Cell cell = getCell(parts[0], parts[1]);
if (cell == null) return;
double cap = 0;
if (parts.length > 3) {
try {
cap = Double.parseDouble(parts[3]);
} catch (NumberFormatException e) {
System.out.println("Error on line "+lineno+" "+e.getMessage());
}
}
List<Net> list = netsByCell.get(cell);
if (list == null) {
list = new ArrayList<Net>();
netsByCell.put(cell, list);
}
Net n = new Net();
n.name = parts[2];
n.replacementCap = cap;
list.add(n);
}
private Cell getCell(String library, String cell) {
Library lib = Library.findLibrary(library);
if (lib == null) {
System.out.println("Could not find library "+library);
return null;
}
Cell c = lib.findNodeProto(cell);
if (c == null) {
System.out.println("Could not find cell "+cell+" in library "+library);
return null;
}
return c;
}
/**
* Get the netIDs for all exempted nets in the cell specified by the CellInfo
* @param info
*/
private void setExemptedNets(HierarchyEnumerator.CellInfo info) {
Cell cell = info.getCell();
List<Net> netNames = netsByCell.get(cell);
if (netNames == null) return; // nothing for this cell
for (Net n : netNames) {
String netName = n.name;
Network net = findNetwork(info, netName);
if (net == null) {
System.out.println("Cannot find network "+netName+" in cell "+cell.describe(true));
continue;
}
// get the global ID
System.out.println("Specified exemption of net "+cell.describe(false)+" "+netName);
int netID = info.getNetID(net);
exemptedNetIDs.add(new Integer(netID));
}
}
private Network findNetwork(HierarchyEnumerator.CellInfo info, String name) {
for (Iterator<Network> it = info.getNetlist().getNetworks(); it.hasNext(); ) {
Network net = it.next();
if (net.hasName(name)) return net;
}
return null;
}
private boolean isExempted(int netID) {
return exemptedNetIDs.contains(new Integer(netID));
}
private double getReplacementCap(Cell cell, Network net) {
List<Net> netNames = netsByCell.get(cell);
if (netNames == null) return 0; // nothing for this cell
for (Net n : netNames) {
if (net.hasName(n.name)) {
return n.replacementCap;
}
}
return 0;
}
}
/****************************** SUBCLASSED METHODS FOR THE TOPOLOGY ANALYZER ******************************/
/**
* Method to adjust a cell name to be safe for Spice output.
* @param name the cell name.
* @return the name, adjusted for Spice output.
*/
protected String getSafeCellName(String name)
{
return getSafeNetName(name, false);
}
/** Method to return the proper name of Power */
protected String getPowerName(Network net)
{
if (net != null)
{
// favor "vdd" if it is present
for(Iterator<String> it = net.getNames(); it.hasNext(); )
{
String netName = it.next();
if (netName.equalsIgnoreCase("vdd")) return "vdd";
}
}
return null;
}
/** Method to return the proper name of Ground */
protected String getGroundName(Network net)
{
if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_2 ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_P ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_G) return "0";
if (net != null)
{
// favor "gnd" if it is present
for(Iterator<String> it = net.getNames(); it.hasNext(); )
{
String netName = it.next();
if (netName.equalsIgnoreCase("gnd")) return "gnd";
}
}
return null;
}
/** Method to return the proper name of a Global signal */
protected String getGlobalName(Global glob) { return glob.getName(); }
/** Method to report that export names do NOT take precedence over
* arc names when determining the name of the network. */
protected boolean isNetworksUseExportedNames() { return false; }
/** Method to report that library names are NOT always prepended to cell names. */
protected boolean isLibraryNameAlwaysAddedToCellName() { return false; }
/** Method to report that aggregate names (busses) are not used. */
protected boolean isAggregateNamesSupported() { return false; }
/** Method to report that not to choose best export name among exports connected to signal. */
protected boolean isChooseBestExportName() { return false; }
/** Method to report whether input and output names are separated. */
protected boolean isSeparateInputAndOutput() { return false; }
/** If the netlister has requirments not to netlist certain cells and their
* subcells, override this method.
* If this cell has a spice template, skip it
*/
protected boolean skipCellAndSubcells(Cell cell)
{
if (useCDL) {
// check for CDL template: if exists, skip
Variable cdlTemplate = cell.getVar(CDL_TEMPLATE_KEY);
if (cdlTemplate != null) return true;
// no template, return false
return false;
}
// skip if there is a template
Variable varTemplate = null;
varTemplate = cell.getVar(preferedEngineTemplateKey);
if (varTemplate != null) return true;
if (!assuraHSpice)
{
varTemplate = cell.getVar(SPICE_TEMPLATE_KEY);
}
if (varTemplate != null) return true;
// look for a model file on the current cell
if (CellModelPrefs.spiceModelPrefs.isUseModelFromFile(cell)) {
String fileName = CellModelPrefs.spiceModelPrefs.getModelFile(cell);
if (!modelOverrides.containsKey(cell))
{
multiLinePrint(true, "\n* " + cell + " is described in this file:\n");
addIncludeFile(fileName);
if (!fileName.startsWith("/") && !fileName.startsWith("\\")) {
File spiceFile = new File(filePath);
fileName = (new File(spiceFile.getParent(), fileName)).getPath();
}
modelOverrides.put(cell, fileName);
}
return true;
}
return false;
}
protected void validateSkippedCell(HierarchyEnumerator.CellInfo info) {
String fileName = modelOverrides.get(info.getCell());
if (fileName != null) {
// validate included file
SpiceNetlistReader reader = new SpiceNetlistReader();
try {
reader.readFile(fileName, false);
HierarchyEnumerator.CellInfo parentInfo = info.getParentInfo();
Nodable no = info.getParentInst();
String parameterizedName = parameterizedName(no, parentInfo.getContext());
CellNetInfo cni = getCellNetInfo(parameterizedName);
SpiceSubckt subckt = reader.getSubckt(parameterizedName);
if (subckt == null) {
System.out.println("Error: No subckt for "+parameterizedName+" found in included file: "+fileName);
} else {
List<String> signals = new ArrayList<String>();
for (Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); ) {
CellSignal cs = sIt.next();
if (ignoreSubcktPort(cs)) continue;
signals.add(cs.getName());
}
List<String> subcktSignals = subckt.getPorts();
if (signals.size() != subcktSignals.size()) {
System.out.println("Warning: wrong number of ports for subckt "+
parameterizedName+": expected "+signals.size()+", but found "+
subcktSignals.size()+", in included file "+fileName);
}
int len = Math.min(signals.size(), subcktSignals.size());
for (int i=0; i<len; i++) {
String s1 = signals.get(i);
String s2 = subcktSignals.get(i);
if (!s1.equalsIgnoreCase(s2)) {
System.out.println("Warning: port "+i+" of subckt "+parameterizedName+
" is named "+s1+" in Electric, but "+s2+" in included file "+fileName);
}
}
}
} catch (FileNotFoundException e) {
System.out.println("Error validating included file: "+e.getMessage());
}
}
}
/**
* Method to adjust a network name to be safe for Spice output.
* Spice has a list of legal punctuation characters that it allows.
*/
protected String getSafeNetName(String name, boolean bus)
{
return getSafeNetName(name, bus, legalSpiceChars, spiceEngine);
}
/**
* Method to adjust a network name to be safe for Spice output.
* Spice has a list of legal punctuation characters that it allows.
*/
public static String getSafeNetName(String name)
{
String legalSpiceChars = SPICELEGALCHARS;
if (Simulation.getSpiceEngine() == Simulation.SpiceEngine.SPICE_ENGINE_P)
legalSpiceChars = PSPICELEGALCHARS;
return getSafeNetName(name, false, legalSpiceChars, Simulation.getSpiceEngine());
}
/**
* Method to adjust a network name to be safe for Spice output.
* Spice has a list of legal punctuation characters that it allows.
*/
private static String getSafeNetName(String name, boolean bus, String legalSpiceChars, Simulation.SpiceEngine spiceEngine)
{
// simple names are trivially accepted as is
boolean allAlNum = true;
int len = name.length();
if (len <= 0) return name;
for(int i=0; i<len; i++)
{
boolean valid = TextUtils.isLetterOrDigit(name.charAt(i));
if (i == 0) valid = Character.isLetter(name.charAt(i));
if (!valid)
{
allAlNum = false;
break;
}
}
if (allAlNum) return name;
StringBuffer sb = new StringBuffer();
if (TextUtils.isDigit(name.charAt(0)) &&
spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_G &&
spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_P &&
spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_2) sb.append('_');
for(int t=0; t<name.length(); t++)
{
char chr = name.charAt(t);
boolean legalChar = TextUtils.isLetterOrDigit(chr);
if (!legalChar)
{
for(int j=0; j<legalSpiceChars.length(); j++)
{
char legalChr = legalSpiceChars.charAt(j);
if (chr == legalChr) { legalChar = true; break; }
}
}
if (!legalChar) chr = '_';
sb.append(chr);
}
return sb.toString();
}
/** Tell the Hierarchy enumerator whether or not to short parasitic resistors */
protected boolean isShortResistors() {
if (useCDL && Simulation.getCDLIgnoreResistors())
return true;
return false;
}
/** Tell the Hierarchy enumerator whether or not to short explicit (poly) resistors */
protected boolean isShortExplicitResistors() {
// until netlister is changed
if (useCDL && Simulation.getCDLIgnoreResistors())
return false;
return false;
}
/**
* Method to tell whether the topological analysis should mangle cell names that are parameterized.
*/
protected boolean canParameterizeNames() { return true; } //return !useCDL; }
/**
* Method to tell set a limit on the number of characters in a name.
* @return the limit to name size (SPICE limits to 32 character names?????).
*/
protected int maxNameLength() { if (useCDL) return CDLMAXLENSUBCKTNAME; return SPICEMAXLENSUBCKTNAME; }
protected boolean enumerateLayoutView(Cell cell) {
return (CellModelPrefs.spiceModelPrefs.isUseLayoutView(cell));
}
/******************** DECK GENERATION SUPPORT ********************/
/**
* write a header for "cell" to spice deck "sim_spice_file"
* The model cards come from a file specified by tech:~.SIM_spice_model_file
* or else tech:~.SIM_spice_header_level%ld
* The spice model file can be located in el_libdir
*/
private void writeHeader(Cell cell)
{
// Print the header line for SPICE
multiLinePrint(true, "*** SPICE deck for cell " + cell.noLibDescribe() +
" from library " + cell.getLibrary().getName() + "\n");
emitCopyright("*** ", "");
if (User.isIncludeDateAndVersionInOutput())
{
multiLinePrint(true, "*** Created on " + TextUtils.formatDate(topCell.getCreationDate()) + "\n");
multiLinePrint(true, "*** Last revised on " + TextUtils.formatDate(topCell.getRevisionDate()) + "\n");
multiLinePrint(true, "*** Written on " + TextUtils.formatDate(new Date()) +
" by Electric VLSI Design System, version " + Version.getVersion() + "\n");
} else
{
multiLinePrint(true, "*** Written by Electric VLSI Design System\n");
}
String foundry = layoutTechnology.getSelectedFoundry() == null ? "" : (", foundry "+layoutTechnology.getSelectedFoundry().toString());
multiLinePrint(true, "*** Layout tech: "+layoutTechnology.getTechName()+foundry+"\n");
multiLinePrint(true, "*** UC SPICE *** , MIN_RESIST " + layoutTechnology.getMinResistance() +
", MIN_CAPAC " + layoutTechnology.getMinCapacitance() + "FF\n");
boolean useParasitics = useNewParasitics && (!useCDL) &&
Simulation.isSpiceUseParasitics() && (cell.getView() == View.LAYOUT);
if (useParasitics) {
for (Layer layer : layoutTechnology.getLayersSortedByHeight()) {
double edgecap = layer.getEdgeCapacitance();
double areacap = layer.getCapacitance();
double res = layer.getResistance();
if (edgecap != 0 || areacap != 0 || res != 0) {
multiLinePrint(true, "*** "+layer.getName()+":\tareacap="+areacap+"FF/um^2,\tedgecap="+edgecap+"FF/um,\tres="+res+"ohms/sq\n");
}
}
}
multiLinePrint(false, ".OPTIONS NOMOD NOPAGE\n");
// if sizes to be written in lambda, tell spice conversion factor
if (Simulation.isSpiceWriteTransSizeInLambda())
{
double scale = layoutTechnology.getScale();
multiLinePrint(true, "*** Lambda Conversion ***\n");
multiLinePrint(false, ".opt scale=" + TextUtils.formatDouble(scale / 1000.0, 3) + "U\n\n");
}
// see if spice model/option cards from file if specified
String headerFile = Simulation.getSpiceHeaderCardInfo();
if (headerFile.length() > 0)
{
if (headerFile.startsWith(SPICE_EXTENSION_PREFIX))
{
// extension specified: look for a file with the cell name and that extension
String headerPath = TextUtils.getFilePath(TextUtils.makeURLToFile(filePath));
String ext = headerFile.substring(SPICE_EXTENSION_PREFIX.length());
if (ext.startsWith(".")) ext = ext.substring(1);
String filePart = cell.getName() + "." + ext;
String fileName = headerPath + filePart;
File test = new File(fileName);
if (test.exists())
{
multiLinePrint(true, "* Model cards are described in this file:\n");
addIncludeFile(filePart);
System.out.println("Spice Header Card '" + fileName + "' is included");
return;
}
else
System.out.println("Spice Header Card '" + fileName + "' cannot be loaded");
} else
{
// normal header file specified
File test = new File(headerFile);
if (!test.exists())
System.out.println("Warning: cannot find model file '" + headerFile + "'");
multiLinePrint(true, "* Model cards are described in this file:\n");
addIncludeFile(headerFile);
return;
}
}
// no header files: write predefined header for this level and technology
int level = TextUtils.atoi(Simulation.getSpiceLevel());
String [] header = null;
switch (level)
{
case 1: header = layoutTechnology.getSpiceHeaderLevel1(); break;
case 2: header = layoutTechnology.getSpiceHeaderLevel2(); break;
case 3: header = layoutTechnology.getSpiceHeaderLevel3(); break;
}
if (header != null)
{
for(int i=0; i<header.length; i++)
multiLinePrint(false, header[i] + "\n");
return;
}
System.out.println("WARNING: no model cards for SPICE level " + level +
" in " + layoutTechnology.getTechName() + " technology");
}
/**
* Write a trailer from an external file, defined as a variable on
* the current technology in this library: tech:~.SIM_spice_trailer_file
* if it is available.
*/
private void writeTrailer(Cell cell)
{
// get spice trailer cards from file if specified
String trailerFile = Simulation.getSpiceTrailerCardInfo();
if (trailerFile.length() > 0)
{
if (trailerFile.startsWith(SPICE_EXTENSION_PREFIX))
{
// extension specified: look for a file with the cell name and that extension
String trailerpath = TextUtils.getFilePath(TextUtils.makeURLToFile(filePath));
String ext = trailerFile.substring(SPICE_EXTENSION_PREFIX.length());
if (ext.startsWith(".")) ext = ext.substring(1);
String filePart = cell.getName() + "." + ext;
String fileName = trailerpath + filePart;
File test = new File(fileName);
if (test.exists())
{
multiLinePrint(true, "* Trailer cards are described in this file:\n");
addIncludeFile(filePart);
System.out.println("Spice Trailer Card '" + fileName + "' is included");
}
else
System.out.println("Spice Trailer Card '" + fileName + "' cannot be loaded");
} else
{
// normal trailer file specified
multiLinePrint(true, "* Trailer cards are described in this file:\n");
addIncludeFile(trailerFile);
System.out.println("Spice Trailer Card '" + trailerFile + "' is included");
}
}
}
/**
* Function to write a two port device to the file. Complain about any missing connections.
* Determine the port connections from the portprotos in the instance
* prototype. Get the part number from the 'part' number value;
* increment it. The type of device is declared in type; extra is the string
* data acquired before calling here.
* If the device is connected to the same net at both ends, do not
* write it. Is this OK?
*/
private void writeTwoPort(NodeInst ni, String partName, String extra, CellNetInfo cni, Netlist netList, VarContext context, SegmentedNets segmentedNets)
{
PortInst port0 = ni.getPortInst(0);
PortInst port1 = ni.getPortInst(1);
Network net0 = netList.getNetwork(port0);
Network net1 = netList.getNetwork(port1);
CellSignal cs0 = cni.getCellSignal(net0);
CellSignal cs1 = cni.getCellSignal(net1);
// make sure the component is connected to nets
if (cs0 == null || cs1 == null)
{
String message = "WARNING: " + ni + " component not fully connected in " + ni.getParent();
dumpErrorMessage(message);
}
if (cs0 != null && cs1 != null && cs0 == cs1)
{
String message = "WARNING: " + ni + " component appears to be shorted on net " + net0.toString() +
" in " + ni.getParent();
dumpErrorMessage(message);
return;
}
if (ni.getName() != null) partName += getSafeNetName(ni.getName(), false);
// add Mfactor if there
StringBuffer sbExtra = new StringBuffer(extra);
writeMFactor(context, ni, sbExtra);
String name0 = cs0.getName();
String name1 = cs1.getName();
if (segmentedNets.getUseParasitics()) {
name0 = segmentedNets.getNetName(port0);
name1 = segmentedNets.getNetName(port1);
}
multiLinePrint(false, partName + " " + name1 + " " + name0 + " " + sbExtra.toString() + "\n");
}
/**
* This adds formatting to a Spice parameter value. It adds single quotes
* around the param string if they do not already exist.
* @param param the string param value (without the name= part).
* @return a param string with single quotes around it
*/
private static String formatParam(String param) {
String value = trimSingleQuotes(param);
try {
Double.valueOf(value);
return value;
} catch (NumberFormatException e) {
return ("'"+value+"'");
}
}
private static String trimSingleQuotes(String param) {
if (param.startsWith("'") && param.endsWith("'")) {
return param.substring(1, param.length()-1);
}
return param;
}
/******************** PARASITIC CALCULATIONS ********************/
/**
* Method to recursively determine the area of diffusion and capacitance
* associated with port "pp" of nodeinst "ni". If the node is mult_layer, then
* determine the dominant capacitance layer, and add its area; all other
* layers will be added as well to the extra_area total.
* Continue out of the ports on a complex cell
*/
private void addNodeInformation(Netlist netList, HashMap<Network,SpiceNet> spiceNets, NodeInst ni)
{
// cells have no area or capacitance (for now)
if (ni.isCellInstance()) return; // No area for complex nodes
PrimitiveNode.Function function = ni.getFunction();
// initialize to examine the polygons on this node
Technology tech = ni.getProto().getTechnology();
AffineTransform trans = ni.rotateOut();
// make linked list of polygons
Poly [] polyList = tech.getShapeOfNode(ni, true, true, null);
int tot = polyList.length;
for(int i=0; i<tot; i++)
{
Poly poly = polyList[i];
// make sure this layer connects electrically to the desired port
PortProto pp = poly.getPort();
if (pp == null) continue;
Network net = netList.getNetwork(ni, pp, 0);
// don't bother with layers without capacity
Layer layer = poly.getLayer();
if (!layer.isDiffusionLayer() && layer.getCapacitance() == 0.0) continue;
if (layer.getTechnology() != Technology.getCurrent()) continue;
// leave out the gate capacitance of transistors
if (layer.getFunction() == Layer.Function.GATE) continue;
SpiceNet spNet = spiceNets.get(net);
if (spNet == null) continue;
// get the area of this polygon
poly.transform(trans);
spNet.merge.addPolygon(layer, poly);
// count the number of transistors on this net
if (layer.isDiffusionLayer() && function.isTransistor()) spNet.transistorCount++;
}
}
/**
* Method to recursively determine the area of diffusion, capacitance, (NOT
* resistance) on arc "ai". If the arc contains active device diffusion, then
* it will contribute to the area of sources and drains, and the other layers
* will be ignored. This is not quite the same as the rule used for
* contact (node) structures. Note: the earlier version of this
* function assumed that diffusion arcs would always have zero capacitance
* values for the other layers; this produces an error if any of these layers
* have non-zero values assigned for other reasons. So we will check for the
* function of the arc, and if it contains active device, we will ignore any
* other layers
*/
private void addArcInformation(PolyMerge merge, ArcInst ai)
{
boolean isDiffArc = ai.isDiffusionArc(); // check arc function
Technology tech = ai.getProto().getTechnology();
Poly [] arcInstPolyList = tech.getShapeOfArc(ai);
int tot = arcInstPolyList.length;
for(int j=0; j<tot; j++)
{
Poly poly = arcInstPolyList[j];
if (poly.getStyle().isText()) continue;
Layer layer = poly.getLayer();
if (layer.getTechnology() != Technology.getCurrent()) continue;
if ((layer.getFunctionExtras() & Layer.Function.PSEUDO) != 0) continue;
if (layer.isDiffusionLayer()||
(!isDiffArc && layer.getCapacitance() > 0.0))
merge.addPolygon(layer, poly);
}
}
/******************** TEXT METHODS ********************/
/**
* Method to insert an "include" of file "filename" into the stream "io".
*/
private void addIncludeFile(String fileName)
{
if (useCDL) {
multiLinePrint(false, ".include "+ fileName + "\n");
return;
}
if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_2 || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3 ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_G || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_S)
{
multiLinePrint(false, ".include " + fileName + "\n");
} else if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_ASSURA ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_CALIBRE)
{
multiLinePrint(false, ".include '" + fileName + "'\n");
} else if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_P)
{
multiLinePrint(false, ".INC " + fileName + "\n");
}
}
private void validateIncludeFile(String fileName, String subcktName) {
}
/******************** SUPPORT ********************/
/**
* Method to return value if arc contains device active diffusion
*/
// private boolean arcIsDiff(ArcInst ai)
// {
// ArcProto.Function fun = ai.getProto().getFunction();
// boolean newV = ai.isDiffusionArc();
// boolean oldV = (fun == ArcProto.Function.DIFFP || fun == ArcProto.Function.DIFFN ||
// fun == ArcProto.Function.DIFF || fun == ArcProto.Function.DIFFS || fun == ArcProto.Function.DIFFW);
// if (newV != oldV)
// System.out.println("Difference in arcIsDiff");
// return oldV;
//// if (fun == ArcProto.Function.DIFFP || fun == ArcProto.Function.DIFFN || fun == ArcProto.Function.DIFF) return true;
//// if (fun == ArcProto.Function.DIFFS || fun == ArcProto.Function.DIFFW) return true;
//// return false;
// }
private static final boolean CELLISEMPTYDEBUG = false;
private HashMap<Cell,Boolean> checkedCells = new HashMap<Cell,Boolean>();
private boolean cellIsEmpty(Cell cell)
{
Boolean b = checkedCells.get(cell);
if (b != null) return b.booleanValue();
boolean empty = true;
List<Cell> emptyCells = new ArrayList<Cell>();
for (Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); ) {
NodeInst ni = it.next();
// if node is a cell, check if subcell is empty
if (ni.isCellInstance()) {
// ignore own icon
if (ni.isIconOfParent()) {
continue;
}
Cell iconCell = (Cell)ni.getProto();
Cell schCell = iconCell.contentsView();
if (schCell == null) schCell = iconCell;
if (cellIsEmpty(schCell)) {
if (CELLISEMPTYDEBUG) emptyCells.add(schCell);
continue;
} else {
empty = false;
break;
}
}
// otherwise, this is a primitive
PrimitiveNode.Function fun = ni.getFunction();
// Passive devices used by spice/CDL
if (fun.isResistor() || // == PrimitiveNode.Function.RESIST ||
fun == PrimitiveNode.Function.INDUCT ||
fun.isCapacitor() || // == PrimitiveNode.Function.CAPAC || fun == PrimitiveNode.Function.ECAPAC ||
fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
empty = false;
break;
}
// active devices used by Spice/CDL
if (((PrimitiveNode)ni.getProto()).getGroupFunction() == PrimitiveNode.Function.TRANS) {
empty = false;
break;
}
// check for spice code on pins
if (ni.getVar(SPICE_CARD_KEY) != null) {
empty = false;
break;
}
}
// look for a model file on the current cell
if (CellModelPrefs.spiceModelPrefs.isUseModelFromFile(cell)) {
empty = false;
}
// check for spice template
if (getEngineTemplate(cell) != null) {
empty = false;
}
// empty
if (CELLISEMPTYDEBUG && empty) {
System.out.println(cell+" is empty and contains the following empty cells:");
for (Cell c : emptyCells)
System.out.println(" "+c.describe(true));
}
checkedCells.put(cell, new Boolean(empty));
return empty;
}
/******************** LOW-LEVEL OUTPUT METHODS ********************/
/**
* Method to report an error that is built in the infinite string.
* The error is sent to the messages window and also to the SPICE deck "f".
*/
private void dumpErrorMessage(String message)
{
multiLinePrint(true, "*** " + message + "\n");
System.out.println(message);
}
/**
* Formatted output to file "stream". All spice output is in upper case.
* The buffer can contain no more than 1024 chars including the newlinelastMoveTo
* and null characters.
* Doesn't return anything.
*/
private void multiLinePrint(boolean isComment, String str)
{
// put in line continuations, if over 78 chars long
char contChar = '+';
if (isComment) contChar = '*';
int lastSpace = -1;
int count = 0;
boolean insideQuotes = false;
int lineStart = 0;
for (int pt = 0; pt < str.length(); pt++)
{
char chr = str.charAt(pt);
// if (sim_spice_machine == SPICE2)
// {
// if (islower(*pt)) *pt = toupper(*pt);
// }
if (chr == '\n')
{
printWriter.print(str.substring(lineStart, pt+1));
count = 0;
lastSpace = -1;
lineStart = pt+1;
} else
{
if (chr == ' ' && !insideQuotes) lastSpace = pt;
if (chr == '\'') insideQuotes = !insideQuotes;
count++;
if (count >= spiceMaxLenLine && !insideQuotes && lastSpace > -1)
{
String partial = str.substring(lineStart, lastSpace+1);
printWriter.print(partial + "\n" + contChar);
count = count - partial.length();
lineStart = lastSpace+1;
lastSpace = -1;
}
}
}
if (lineStart < str.length())
{
String partial = str.substring(lineStart);
printWriter.print(partial);
}
}
public static class FlatSpiceCodeVisitor extends HierarchyEnumerator.Visitor {
private PrintWriter printWriter;
private PrintWriter spicePrintWriter;
private String filePath;
Spice spice; // just used for file writing and formatting
SegmentedNets segNets;
public FlatSpiceCodeVisitor(String filePath, Spice spice) {
this.spice = spice;
this.spicePrintWriter = spice.printWriter;
this.filePath = filePath;
spice.spiceMaxLenLine = 1000;
segNets = null;
}
public boolean enterCell(HierarchyEnumerator.CellInfo info) {
return true;
}
public void exitCell(HierarchyEnumerator.CellInfo info) {
Cell cell = info.getCell();
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech.invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_CODE_FLAT_KEY);
if (cardVar != null) {
if (printWriter == null) {
try {
printWriter = new PrintWriter(new BufferedWriter(new FileWriter(filePath)));
} catch (IOException e) {
System.out.println("Unable to open "+filePath+" for write.");
return;
}
spice.printWriter = printWriter;
segNets = new SegmentedNets(null, false, null, false);
}
spice.emitEmbeddedSpice(cardVar, info.getContext(), segNets, info, true);
}
}
}
public boolean visitNodeInst(Nodable ni, HierarchyEnumerator.CellInfo info) {
return true;
}
public void close() {
if (printWriter != null) {
System.out.println(filePath+" written");
spice.printWriter = spicePrintWriter;
printWriter.close();
}
spice.spiceMaxLenLine = SPICEMAXLENLINE;
}
}
}
| false | true | protected void writeCellTopology(Cell cell, CellNetInfo cni, VarContext context, Topology.MyCellInfo info)
{
if (cell == topCell && USE_GLOBALS) {
Netlist netList = cni.getNetList();
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (!Simulation.isSpiceUseNodeNames() || spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_3)
{
if (globalSize > 0)
{
StringBuffer infstr = new StringBuffer();
infstr.append("\n.global");
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
String name = global.getName();
if (global == Global.power) { if (getPowerName(null) != null) name = getPowerName(null); }
if (global == Global.ground) { if (getGroundName(null) != null) name = getGroundName(null); }
infstr.append(" " + name);
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
}
}
// gather networks in the cell
Netlist netList = cni.getNetList();
// make sure power and ground appear at the top level
if (cell == topCell && !Simulation.isSpiceForceGlobalPwrGnd())
{
if (cni.getPowerNet() == null)
System.out.println("WARNING: cannot find power at top level of circuit");
if (cni.getGroundNet() == null)
System.out.println("WARNING: cannot find ground at top level of circuit");
}
// create list of electrical nets in this cell
HashMap<Network,SpiceNet> spiceNetMap = new HashMap<Network,SpiceNet>();
// create SpiceNet objects for all networks in the cell
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
// create a "SpiceNet" for the network
SpiceNet spNet = new SpiceNet();
spNet.network = net;
spNet.transistorCount = 0;
spNet.diffArea = 0;
spNet.diffPerim = 0;
spNet.nonDiffCapacitance = 0;
spNet.merge = new PolyMerge();
spiceNetMap.put(net, spNet);
}
// create list of segemented networks for parasitic extraction
boolean verboseSegmentedNames = Simulation.isParasiticsUseVerboseNaming();
boolean useParasitics = useNewParasitics && (!useCDL) &&
Simulation.isSpiceUseParasitics() && (cell.getView() == View.LAYOUT);
SegmentedNets segmentedNets = new SegmentedNets(cell, verboseSegmentedNames, cni, useParasitics);
segmentedParasiticInfo.add(segmentedNets);
if (useParasitics) {
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
//System.out.println("\n Finding parasitics for cell "+cell.describe(false));
HashMap<Network,Network> exemptedNetsFound = new HashMap<Network,Network>();
for (Iterator<ArcInst> ait = cell.getArcs(); ait.hasNext(); ) {
ArcInst ai = ait.next();
boolean ignoreArc = false;
// figure out res and cap, see if we should ignore it
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC)
ignoreArc = true;
double length = ai.getLambdaLength() * scale / 1000; // length in microns
double width = ai.getLambdaFullWidth() * scale / 1000; // width in microns
double area = length * width;
double fringe = length*2;
double cap = 0;
double res = 0;
Technology tech = ai.getProto().getTechnology();
Poly [] arcInstPolyList = tech.getShapeOfArc(ai);
int tot = arcInstPolyList.length;
for(int j=0; j<tot; j++)
{
Poly poly = arcInstPolyList[j];
if (poly.getStyle().isText()) continue;
Layer layer = poly.getLayer();
if (layer.getTechnology() != layoutTechnology) continue;
if ((layer.getFunctionExtras() & Layer.Function.PSEUDO) != 0) continue;
if (!layer.isDiffusionLayer() && layer.getCapacitance() > 0.0) {
double areacap = area * layer.getCapacitance();
double fringecap = fringe * layer.getEdgeCapacitance();
cap = areacap + fringecap;
res = length/width * layer.getResistance();
}
}
// add res if big enough
if (res <= cell.getTechnology().getMinResistance()) {
ignoreArc = true;
}
if (Simulation.isParasiticsUseExemptedNetsFile()) {
Network net = netList.getNetwork(ai, 0);
// ignore nets in exempted nets file
if (Simulation.isParasiticsIgnoreExemptedNets()) {
// check if this net is exempted
if (exemptedNets.isExempted(info.getNetID(net))) {
ignoreArc = true;
cap = 0;
if (!exemptedNetsFound.containsKey(net)) {
System.out.println("Not extracting net "+cell.describe(false)+" "+net.getName());
exemptedNetsFound.put(net, net);
cap = exemptedNets.getReplacementCap(cell, net);
}
}
// extract only nets in exempted nets file
} else {
if (exemptedNets.isExempted(info.getNetID(net)) && ignoreArc == false) {
if (!exemptedNetsFound.containsKey(net)) {
System.out.println("Extracting net "+cell.describe(false)+" "+net.getName());
exemptedNetsFound.put(net, net);
}
} else {
ignoreArc = true;
}
}
}
int arcPImodels = SegmentedNets.getNumPISegments(res, layoutTechnology.getMaxSeriesResistance());
if (ignoreArc)
arcPImodels = 1; // split cap to two pins if ignoring arc
// add caps
segmentedNets.putSegment(ai.getHeadPortInst(), cap/(arcPImodels+1));
segmentedNets.putSegment(ai.getTailPortInst(), cap/(arcPImodels+1));
if (ignoreArc) {
// short arc
segmentedNets.shortSegments(ai.getHeadPortInst(), ai.getTailPortInst());
} else {
segmentedNets.addArcRes(ai, res);
if (arcPImodels > 1)
segmentedNets.addArcCap(ai, cap); // need to store cap later to break it up
}
}
// Don't take into account gate resistance: so we need to short two PortInsts
// of gate together if this is layout
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
if (!ni.isCellInstance()) {
if (((PrimitiveNode)ni.getProto()).getGroupFunction() == PrimitiveNode.Function.TRANS) {
PortInst gate0 = ni.getTransistorGatePort();
PortInst gate1 = null;
for (Iterator<PortInst> pit = ni.getPortInsts(); pit.hasNext();) {
PortInst p2 = pit.next();
if (p2 != gate0 && netList.getNetwork(gate0) == netList.getNetwork(p2))
gate1 = p2;
}
if (gate1 != null) {
segmentedNets.shortSegments(gate0, gate1);
}
}
} else {
//System.out.println("Shorting shorted exports");
// short together pins if shorted by subcell
Cell subCell = (Cell)ni.getProto();
SegmentedNets subNets = getSegmentedNets(subCell);
// list of lists of shorted exports
if (subNets != null) { // subnets may be null if mixing schematics with layout technologies
for (Iterator<List<String>> it = subNets.getShortedExports(); it.hasNext(); ) {
List<String> exports = it.next();
PortInst pi1 = null;
// list of exports shorted together
for (String exportName : exports) {
// get portinst on node
PortInst pi = ni.findPortInst(exportName);
if (pi1 == null) {
pi1 = pi; continue;
}
segmentedNets.shortSegments(pi1, pi);
}
}
}
}
} // for (cell.getNodes())
}
// count the number of different transistor types
int bipolarTrans = 0, nmosTrans = 0, pmosTrans = 0;
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
addNodeInformation(netList, spiceNetMap, ni);
PrimitiveNode.Function fun = ni.getFunction();
if (fun == PrimitiveNode.Function.TRANPN || fun == PrimitiveNode.Function.TRA4NPN ||
fun == PrimitiveNode.Function.TRAPNP || fun == PrimitiveNode.Function.TRA4PNP ||
fun == PrimitiveNode.Function.TRANS) bipolarTrans++; else
if (fun == PrimitiveNode.Function.TRAEMES || fun == PrimitiveNode.Function.TRA4EMES ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRA4DMES ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS) nmosTrans++; else
if (fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS) pmosTrans++;
}
// accumulate geometry of all arcs
for(Iterator<ArcInst> aIt = cell.getArcs(); aIt.hasNext(); )
{
ArcInst ai = aIt.next();
// don't count non-electrical arcs
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC) continue;
// ignore busses
// if (ai->network->buswidth > 1) continue;
Network net = netList.getNetwork(ai, 0);
SpiceNet spNet = spiceNetMap.get(net);
if (spNet == null) continue;
addArcInformation(spNet.merge, ai);
}
// get merged polygons so far
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = spiceNetMap.get(net);
for (Layer layer : spNet.merge.getKeySet())
{
List<PolyBase> polyList = spNet.merge.getMergedPoints(layer, true);
if (polyList == null) continue;
if (polyList.size() > 1)
Collections.sort(polyList, GeometryHandler.shapeSort);
for(PolyBase poly : polyList)
{
// compute perimeter and area
double perim = poly.getPerimeter();
double area = poly.getArea();
// accumulate this information
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
if (layer.isDiffusionLayer()) {
spNet.diffArea += area * maskScale * maskScale;
spNet.diffPerim += perim * maskScale;
} else {
area = area * scale * scale / 1000000; // area in square microns
perim = perim * scale / 1000; // perim in microns
spNet.nonDiffCapacitance += layer.getCapacitance() * area * maskScale * maskScale;
spNet.nonDiffCapacitance += layer.getEdgeCapacitance() * perim * maskScale;
}
}
}
}
// make sure the ground net is number zero
Network groundNet = cni.getGroundNet();
Network powerNet = cni.getPowerNet();
if (pmosTrans != 0 && powerNet == null)
{
String message = "WARNING: no power connection for P-transistor wells in " + cell;
dumpErrorMessage(message);
}
if (nmosTrans != 0 && groundNet == null)
{
String message = "WARNING: no ground connection for N-transistor wells in " + cell;
dumpErrorMessage(message);
}
// // use ground net for substrate
// if (subnet == NOSPNET && sim_spice_gnd != NONETWORK)
// subnet = (SPNET *)sim_spice_gnd->temp1;
// if (bipolarTrans != 0 && subnet == NOSPNET)
// {
// infstr = initinfstr();
// formatinfstr(infstr, _("WARNING: no explicit connection to the substrate in cell %s"),
// describenodeproto(np));
// dumpErrorMessage(infstr);
// if (sim_spice_gnd != NONETWORK)
// {
// ttyputmsg(_(" A connection to ground will be used if necessary."));
// subnet = (SPNET *)sim_spice_gnd->temp1;
// }
// }
// generate header for subckt or top-level cell
String topLevelInstance = "";
if (cell == topCell && !useCDL && !Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(true, "\n*** TOP LEVEL CELL: " + cell.describe(false) + "\n");
} else
{
if (!writeEmptySubckts) {
if (cellIsEmpty(cell))
return;
}
String cellName = cni.getParameterizedName();
multiLinePrint(true, "\n*** CELL: " + cell.describe(false) + "\n");
StringBuffer infstr = new StringBuffer();
infstr.append(".SUBCKT " + cellName);
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
if (ignoreSubcktPort(cs)) continue;
if (cs.isGlobal()) {
System.out.println("Warning: Explicit Global signal "+cs.getName()+" exported in "+cell.describe(false));
}
// special case for parasitic extraction
if (useParasitics && !cs.isGlobal() && cs.getExport() != null) {
Network net = cs.getNetwork();
HashMap<String,List<String>> shortedExportsMap = new HashMap<String,List<String>>();
// For a single logical network, we need to:
// 1) treat certain exports as separate so as not to short resistors on arcs between the exports
// 2) join certain exports that do not have resistors on arcs between them, and record this information
// so that the next level up knows to short networks connection to those exports.
for (Iterator<Export> it = net.getExports(); it.hasNext(); ) {
Export e = it.next();
PortInst pi = e.getOriginalPort();
String name = segmentedNets.getNetName(pi);
// exports are shorted if their segmented net names are the same (case (2))
List<String> shortedExports = shortedExportsMap.get(name);
if (shortedExports == null) {
shortedExports = new ArrayList<String>();
shortedExportsMap.put(name, shortedExports);
// this is the first occurance of this segmented network,
// use the name as the export (1)
infstr.append(" " + name);
}
shortedExports.add(e.getName());
}
// record shorted exports
for (List<String> shortedExports : shortedExportsMap.values()) {
if (shortedExports.size() > 1) {
segmentedNets.addShortedExports(shortedExports);
}
}
} else {
infstr.append(" " + cs.getName());
}
}
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (USE_GLOBALS)
{
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
infstr.append(" " + cs.getName());
}
}
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
// create top level instantiation
if (Simulation.isSpiceWriteTopCellInstance())
topLevelInstance = infstr.toString().replaceFirst("\\.SUBCKT ", "X") + " " + cellName;
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this cell
for(Iterator<Variable> it = cell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (paramVar.getCode() != TextDescriptor.Code.SPICE) continue;
infstr.append(" " + paramVar.getTrueName() + "=" + paramVar.getPureValue(-1));
}
// for(Iterator it = cell.getVariables(); it.hasNext(); )
// {
// Variable paramVar = it.next();
// if (!paramVar.isParam()) continue;
// infstr.append(" " + paramVar.getTrueName() + "=" + paramVar.getPureValue(-1));
// }
}
// Writing M factor
//writeMFactor(cell, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
// generate pin descriptions for reference (when not using node names)
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
multiLinePrint(true, "** GLOBAL " + cs.getName() + "\n");
}
// write exports to this cell
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
// ignore networks that aren't exported
PortProto pp = cs.getExport();
if (pp == null) continue;
if (cs.isGlobal()) continue;
//multiLinePrint(true, "** PORT " + cs.getName() + "\n");
}
}
// write out any directly-typed SPICE declaratons for the cell
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech.invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_DECLARATION_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Declaration nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false);
}
}
// third pass through the node list, print it this time
for(Iterator<Nodable> nIt = netList.getNodables(); nIt.hasNext(); )
{
Nodable no = nIt.next();
NodeProto niProto = no.getProto();
// handle sub-cell calls
if (no.isCellInstance())
{
Cell subCell = (Cell)niProto;
// look for a SPICE template on the prototype
Variable varTemplate = null;
if (useCDL)
{
varTemplate = subCell.getVar(CDL_TEMPLATE_KEY);
} else
{
varTemplate = getEngineTemplate(subCell);
// varTemplate = subCell.getVar(preferedEngineTemplateKey);
// if (varTemplate == null)
// varTemplate = subCell.getVar(SPICE_TEMPLATE_KEY);
}
// handle templates
if (varTemplate != null)
{
if (varTemplate.getObject() instanceof Object[])
{
Object [] manyLines = (Object [])varTemplate.getObject();
for(int i=0; i<manyLines.length; i++)
{
String line = manyLines[i].toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
if (i == 0) writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
} else
{
String line = varTemplate.getObject().toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
continue;
}
// get the ports on this node (in proper order)
CellNetInfo subCni = getCellNetInfo(parameterizedName(no, context));
if (subCni == null) continue;
if (!writeEmptySubckts) {
// do not instantiate if empty
if (cellIsEmpty((Cell)niProto))
continue;
}
String modelChar = "X";
if (no.getName() != null) modelChar += getSafeNetName(no.getName(), false);
StringBuffer infstr = new StringBuffer();
infstr.append(modelChar);
for(Iterator<CellSignal> sIt = subCni.getCellSignals(); sIt.hasNext(); )
{
CellSignal subCS = sIt.next();
// ignore networks that aren't exported
PortProto pp = subCS.getExport();
Network net;
int exportIndex = subCS.getExportIndex();
// This checks if we are netlisting a schematic top level with
// swapped-in layout subcells
if (pp != null && (cell.getView() == View.SCHEMATIC) && (subCni.getCell().getView() == View.LAYOUT)) {
// find equivalent pp from layout to schematic
Network subNet = subCS.getNetwork(); // layout network name
boolean found = false;
for (Iterator<Export> eIt = subCell.getExports(); eIt.hasNext(); ) {
Export ex = eIt.next();
for (int i=0; i<ex.getNameKey().busWidth(); i++) {
String exName = ex.getNameKey().subname(i).toString();
if (exName.equals(subNet.getName())) {
pp = ex;
exportIndex = i;
found = true;
break;
}
}
if (found) break;
}
if (!found) {
if (pp.isGround() && pp.getName().startsWith("gnd")) {
infstr.append(" gnd");
} else if (pp.isPower() && pp.getName().startsWith("vdd")) {
infstr.append(" vdd");
} else {
System.out.println("No matching export on schematic/icon found for export "+
subNet.getName()+" in cell "+subCni.getCell().describe(false));
infstr.append(" unknown");
}
continue;
}
}
if (USE_GLOBALS)
{
if (pp == null) continue;
if (subCS.isGlobal() && subCS.getNetwork().isExported()) {
// only add to port list if exported with global name
if (!isGlobalExport(subCS)) continue;
}
net = netList.getNetwork(no, pp, exportIndex);
} else
{
if (pp == null && !subCS.isGlobal()) continue;
if (subCS.isGlobal())
net = netList.getNetwork(no, subCS.getGlobal());
else
net = netList.getNetwork(no, pp, exportIndex);
}
CellSignal cs = cni.getCellSignal(net);
// special case for parasitic extraction
if (useParasitics && !cs.isGlobal()) {
// connect to all exports (except power and ground of subcell net)
SegmentedNets subSegmentedNets = getSegmentedNets((Cell)no.getProto());
Network subNet = subCS.getNetwork();
List<String> exportNames = new ArrayList<String>();
for (Iterator<Export> it = subNet.getExports(); it.hasNext(); ) {
// get subcell export, unless collapsed due to less than min R
Export e = it.next();
PortInst pi = e.getOriginalPort();
String name = subSegmentedNets.getNetName(pi);
if (exportNames.contains(name)) continue;
exportNames.add(name);
// ok, there is a port on the subckt on this subcell for this export,
// now get the appropriate network in this cell
pi = no.getNodeInst().findPortInstFromProto(no.getProto().findPortProto(e.getNameKey()));
name = segmentedNets.getNetName(pi);
infstr.append(" " + name);
}
} else {
String name = cs.getName();
if (segmentedNets.getUseParasitics()) {
name = segmentedNets.getNetName(no.getNodeInst().findPortInstFromProto(pp));
}
infstr.append(" " + name);
}
}
if (USE_GLOBALS)
{
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
Global.Set globals = subCni.getNetList().getGlobals();
int globalSize = globals.size();
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
infstr.append(" " + global.getName());
}
}
}
if (useCDL) {
infstr.append(" /" + subCni.getParameterizedName());
} else {
infstr.append(" " + subCni.getParameterizedName());
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this instance
for(Iterator<Variable> it = subCell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
Variable instVar = no.getVar(paramVar.getKey());
String paramStr = "??";
if (instVar != null) {
if (paramVar.getCode() != TextDescriptor.Code.SPICE) continue;
Object obj = context.evalSpice(instVar, false);
if (obj != null)
paramStr = formatParam(String.valueOf(obj));
}
infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
}
// for(Iterator it = subCell.getVariables(); it.hasNext(); )
// {
// Variable paramVar = it.next();
// if (!paramVar.isParam()) continue;
// Variable instVar = no.getVar(paramVar.getKey());
// String paramStr = "??";
// if (instVar != null) paramStr = formatParam(trimSingleQuotes(String.valueOf(context.evalVar(instVar))));
// infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
// }
}
// Writing MFactor if available.
writeMFactor(context, no, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
continue;
}
// get the type of this node
NodeInst ni = (NodeInst)no;
PrimitiveNode.Function fun = ni.getFunction();
// handle resistors, inductors, capacitors, and diodes
if (fun.isResistor() || // == PrimitiveNode.Function.RESIST ||
fun == PrimitiveNode.Function.INDUCT ||
fun.isCapacitor() || // == PrimitiveNode.Function.CAPAC || fun == PrimitiveNode.Function.ECAPAC ||
fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
if (fun.isResistor()) // == PrimitiveNode.Function.RESIST)
{
if ((fun == PrimitiveNode.Function.PRESIST && isShortExplicitResistors()) ||
(fun == PrimitiveNode.Function.RESIST && isShortResistors()))
continue;
Variable resistVar = ni.getVar(Schematics.SCHEM_RESISTANCE);
String extra = "";
String partName = "R";
if (resistVar != null)
{
if (resistVar.getCode() == TextDescriptor.Code.SPICE) {
Object obj = context.evalSpice(resistVar, false);
extra = String.valueOf(obj);
}
if (extra == null)
extra = resistVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); //displayedUnits(pureValue, TextDescriptor.Unit.RESISTANCE, TextUtils.UnitScale.NONE);
} else {
extra = "'"+extra+"'";
}
} else {
if (fun == PrimitiveNode.Function.PRESIST) {
partName = "XR";
double width = ni.getYSize();
double length = ni.getXSize();
SizeOffset offset = ni.getSizeOffset();
width = width - offset.getHighYOffset() - offset.getLowYOffset();
length = length - offset.getHighXOffset() - offset.getLowXOffset();
extra = " L='"+length+"*LAMBDA' W='"+width+"*LAMBDA'";
if (layoutTechnology == Technology.getCMOS90Technology() ||
(cell.getView() == View.LAYOUT && cell.getTechnology() == Technology.getCMOS90Technology())) {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "GND rpporpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "GND rnporpo"+extra;
}
} else {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "rppo1rpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "rnpo1rpo"+extra;
}
}
}
}
writeTwoPort(ni, partName, extra, cni, netList, context, segmentedNets);
} else if (fun.isCapacitor()) // == PrimitiveNode.Function.CAPAC || fun == PrimitiveNode.Function.ECAPAC)
{
Variable capacVar = ni.getVar(Schematics.SCHEM_CAPACITANCE);
String extra = "";
if (capacVar != null)
{
if (capacVar.getCode() == TextDescriptor.Code.SPICE) {
Object obj = context.evalSpice(capacVar, false);
extra = String.valueOf(obj);
}
if (extra == null)
extra = capacVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.CAPACITANCE, TextUtils.UnitScale.NONE);
} else {
extra = "'"+extra+"'";
}
}
writeTwoPort(ni, "C", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.INDUCT)
{
Variable inductVar = ni.getVar(Schematics.SCHEM_INDUCTANCE);
String extra = "";
if (inductVar != null)
{
if (inductVar.getCode() == TextDescriptor.Code.SPICE) {
Object obj = context.evalSpice(inductVar, false);
extra = String.valueOf(obj);
}
if (extra == null)
extra = inductVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.INDUCTANCE, TextUtils.UnitScale.NONE);
} else {
extra = "'"+extra+"'";
}
}
writeTwoPort(ni, "L", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
Variable diodeVar = ni.getVar(Schematics.SCHEM_DIODE);
String extra = "";
if (diodeVar != null)
extra = diodeVar.describe(context, ni);
if (extra.length() == 0) extra = "DIODE";
writeTwoPort(ni, "D", extra, cni, netList, context, segmentedNets);
}
continue;
}
// the default is to handle everything else as a transistor
if (((PrimitiveNode)niProto).getGroupFunction() != PrimitiveNode.Function.TRANS)
continue;
Network gateNet = netList.getNetwork(ni.getTransistorGatePort());
CellSignal gateCs = cni.getCellSignal(gateNet);
Network sourceNet = netList.getNetwork(ni.getTransistorSourcePort());
CellSignal sourceCs = cni.getCellSignal(sourceNet);
Network drainNet = netList.getNetwork(ni.getTransistorDrainPort());
CellSignal drainCs = cni.getCellSignal(drainNet);
CellSignal biasCs = null;
PortInst biasPort = ni.getTransistorBiasPort();
if (biasPort != null)
{
biasCs = cni.getCellSignal(netList.getNetwork(biasPort));
}
// make sure transistor is connected to nets
if (gateCs == null || sourceCs == null || drainCs == null)
{
String message = "WARNING: " + ni + " not fully connected in " + cell;
dumpErrorMessage(message);
}
// get model information
String modelName = null;
String defaultBulkName = null;
Variable modelVar = ni.getVar(SPICE_MODEL_KEY);
if (modelVar != null) modelName = modelVar.getObject().toString();
// special case for ST090 technology which has stupid non-standard transistor
// models which are subcircuits
boolean st090laytrans = false;
boolean tsmc090laytrans = false;
if (cell.getView() == View.LAYOUT && layoutTechnology == Technology.getCMOS90Technology()) {
if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.TSMC)
tsmc090laytrans = true;
else if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.ST)
st090laytrans = true;
}
String modelChar = "";
if (fun == PrimitiveNode.Function.TRANSREF) // self-referential transistor
{
modelChar = "X";
biasCs = cni.getCellSignal(groundNet);
modelName = niProto.getName();
} else if (fun == PrimitiveNode.Function.TRANMOS) // NMOS (Enhancement) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
defaultBulkName = "gnd";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRA4NMOS) // NMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRADMOS) // DMOS (Depletion) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRA4DMOS) // DMOS (Depletion) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRAPMOS) // PMOS (Complementary) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(powerNet);
defaultBulkName = "vdd";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRA4PMOS) // PMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRANPN) // NPN (Junction) transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRA4NPN) // NPN (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRAPNP) // PNP (Junction) transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRA4PNP) // PNP (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRANJFET) // NJFET (N Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRA4NJFET) // NJFET (N Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRAPJFET) // PJFET (P Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRA4PJFET) // PJFET (P Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRADMES || // DMES (Depletion) transistor
fun == PrimitiveNode.Function.TRA4DMES) // DMES (Depletion) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "DMES";
} else if (fun == PrimitiveNode.Function.TRAEMES || // EMES (Enhancement) transistor
fun == PrimitiveNode.Function.TRA4EMES) // EMES (Enhancement) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "EMES";
} else if (fun == PrimitiveNode.Function.TRANS) // special transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
}
if (ni.getName() != null) modelChar += getSafeNetName(ni.getName(), false);
StringBuffer infstr = new StringBuffer();
String drainName = drainCs.getName();
String gateName = gateCs.getName();
String sourceName = sourceCs.getName();
if (segmentedNets.getUseParasitics()) {
drainName = segmentedNets.getNetName(ni.getTransistorDrainPort());
gateName = segmentedNets.getNetName(ni.getTransistorGatePort());
sourceName = segmentedNets.getNetName(ni.getTransistorSourcePort());
}
infstr.append(modelChar + " " + drainName + " " + gateName + " " + sourceName);
if (biasCs != null) {
String biasName = biasCs.getName();
if (segmentedNets.getUseParasitics()) {
if (ni.getTransistorBiasPort() != null)
biasName = segmentedNets.getNetName(ni.getTransistorBiasPort());
}
infstr.append(" " + biasName);
} else {
if (cell.getView() == View.LAYOUT && defaultBulkName != null)
infstr.append(" " + defaultBulkName);
}
if (modelName != null) infstr.append(" " + modelName);
// compute length and width (or area for nonMOS transistors)
TransistorSize size = ni.getTransistorSize(context);
if (size == null)
System.out.println("Warning: transistor with null size " + ni.getName());
else
{
if (size.getDoubleWidth() > 0 || size.getDoubleLength() > 0)
{
double w = maskScale * size.getDoubleWidth();
double l = maskScale * size.getDoubleLength();
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
l -= lengthSubtraction;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
// make into microns (convert to nanometers then divide by 1000)
l *= layoutTechnology.getScale() / 1000.0;
w *= layoutTechnology.getScale() / 1000.0;
}
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
((fun == PrimitiveNode.Function.TRANJFET || fun == PrimitiveNode.Function.TRAPJFET ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRAEMES) &&
(spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_ASSURA)))
{
// schematic transistors may be text
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength()) + " - "+ lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength()));
} else {
infstr.append(" L=" + TextUtils.formatDouble(l, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String)) {
infstr.append(" W="+formatParam((String)size.getWidth()));
} else {
infstr.append(" W=" + TextUtils.formatDouble(w, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
if (fun != PrimitiveNode.Function.TRANMOS && fun != PrimitiveNode.Function.TRA4NMOS &&
fun != PrimitiveNode.Function.TRAPMOS && fun != PrimitiveNode.Function.TRA4PMOS &&
fun != PrimitiveNode.Function.TRADMOS && fun != PrimitiveNode.Function.TRA4DMOS)
{
infstr.append(" AREA=" + TextUtils.formatDouble(l*w, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda()) infstr.append("P");
}
} else {
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength()) + " - "+lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength()));
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String))
infstr.append(" W="+formatParam((String)size.getWidth()));
}
}
// make sure transistor is connected to nets
SpiceNet spNetGate = spiceNetMap.get(gateNet);
SpiceNet spNetSource = spiceNetMap.get(sourceNet);
SpiceNet spNetDrain = spiceNetMap.get(drainNet);
if (spNetGate == null || spNetSource == null || spNetDrain == null) continue;
// compute area of source and drain
if (!useCDL)
{
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS)
{
double as = 0, ad = 0, ps = 0, pd = 0;
if (spNetSource.transistorCount != 0)
{
as = spNetSource.diffArea / spNetSource.transistorCount;
ps = spNetSource.diffPerim / spNetSource.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
as *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
ps *= layoutTechnology.getScale() / 1000.0;
}
}
if (spNetDrain.transistorCount != 0)
{
ad = spNetDrain.diffArea / spNetDrain.transistorCount;
pd = spNetDrain.diffPerim / spNetDrain.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
ad *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
pd *= layoutTechnology.getScale() / 1000.0;
}
}
if (as > 0.0)
{
infstr.append(" AS=" + TextUtils.formatDouble(as, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ad > 0.0)
{
infstr.append(" AD=" + TextUtils.formatDouble(ad, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ps > 0.0)
{
infstr.append(" PS=" + TextUtils.formatDouble(ps, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if (pd > 0.0)
{
infstr.append(" PD=" + TextUtils.formatDouble(pd, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
}
// Writing MFactor if available.
writeMFactor(context, ni, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
// print resistances and capacitances
if (!useCDL)
{
if (Simulation.isSpiceUseParasitics() && cell.getView() == View.LAYOUT)
{
if (useNewParasitics) {
int capCount = 0;
int resCount = 0;
// write caps
multiLinePrint(true, "** Extracted Parasitic Capacitors ***\n");
for (SegmentedNets.NetInfo netInfo : segmentedNets.getUniqueSegments()) {
if (netInfo.cap > cell.getTechnology().getMinCapacitance()) {
if (netInfo.netName.equals("gnd")) continue; // don't write out caps from gnd to gnd
multiLinePrint(false, "C" + capCount + " " + netInfo.netName + " 0 " + TextUtils.formatDouble(netInfo.cap, 2) + "fF\n");
capCount++;
}
}
// write resistors
multiLinePrint(true, "** Extracted Parasitic Resistors ***\n");
for (Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) {
ArcInst ai = it.next();
Double res = segmentedNets.arcRes.get(ai);
if (res == null) continue;
String n0 = segmentedNets.getNetName(ai.getHeadPortInst());
String n1 = segmentedNets.getNetName(ai.getTailPortInst());
int arcPImodels = SegmentedNets.getNumPISegments(res.doubleValue(), layoutTechnology.getMaxSeriesResistance());
if (arcPImodels > 1) {
// have to break it up into smaller pieces
double segCap = segmentedNets.getArcCap(ai)/((double)(arcPImodels+1));
double segRes = res.doubleValue()/((double)arcPImodels);
String segn0 = n0;
String segn1 = n0;
for (int i=0; i<arcPImodels; i++) {
segn1 = n0 + "##" + i;
// print cap on intermediate node
if (i == (arcPImodels-1))
segn1 = n1;
multiLinePrint(false, "R"+resCount+" "+segn0+" "+segn1+" "+TextUtils.formatDouble(segRes)+"\n");
resCount++;
if (i < (arcPImodels-1)) {
if (!segn1.equals("gnd")) {
multiLinePrint(false, "C"+capCount+" "+segn1+" 0 "+TextUtils.formatDouble(segCap)+"fF\n");
capCount++;
}
}
segn0 = segn1;
}
} else {
multiLinePrint(false, "R" + resCount + " " + n0 + " " + n1 + " " + TextUtils.formatDouble(res.doubleValue(), 2) + "\n");
resCount++;
}
}
} else {
// print parasitic capacitances
boolean first = true;
int capacNum = 1;
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
Network net = cs.getNetwork();
if (net == cni.getGroundNet()) continue;
SpiceNet spNet = spiceNetMap.get(net);
if (spNet.nonDiffCapacitance > layoutTechnology.getMinCapacitance())
{
if (first)
{
first = false;
multiLinePrint(true, "** Extracted Parasitic Elements:\n");
}
multiLinePrint(false, "C" + capacNum + " " + cs.getName() + " 0 " + TextUtils.formatDouble(spNet.nonDiffCapacitance, 2) + "fF\n");
capacNum++;
}
}
}
}
}
// write out any directly-typed SPICE cards
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech.invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_CARD_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Code nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false);
}
}
// finally, if this is the top level,
// write out some very small resistors between any networks
// that are asserted will be connected by the NCC annotation "exportsConnectedByParent"
// this should really be done internally in the network tool with a switch, but
// this hack works here for now
NccCellAnnotations anna = NccCellAnnotations.getAnnotations(cell);
if (cell == topCell && anna != null) {
// each list contains all name patterns that are be shorted together
if (anna.getExportsConnected().hasNext()) {
multiLinePrint(true, "\n*** Exports shorted due to NCC annotation 'exportsConnectedByParent':\n");
}
for (Iterator<List<NamePattern>> it = anna.getExportsConnected(); it.hasNext(); ) {
List<NamePattern> list = it.next();
List<Network> netsToConnect = new ArrayList<Network>();
// each name pattern can match any number of exports in the cell
for (NccCellAnnotations.NamePattern pat : list) {
for (Iterator<PortProto> it3 = cell.getPorts(); it3.hasNext(); ) {
Export e = (Export)it3.next();
String name = e.getName();
// keep track of networks to short together
if (pat.matches(name)) {
Network net = netList.getNetwork(e, 0);
if (!netsToConnect.contains(net))
netsToConnect.add(net);
}
}
}
// connect all nets in list of nets to connect
String name = null;
// int i=0;
for (Network net : netsToConnect) {
if (name != null) {
multiLinePrint(false, "R"+name+" "+name+" "+net.getName()+" 0.001\n");
}
name = net.getName();
// i++;
}
}
}
// now we're finished writing the subcircuit.
if (cell != topCell || useCDL || Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(false, ".ENDS " + cni.getParameterizedName() + "\n");
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
multiLinePrint(false, "\n\n"+topLevelInstance+"\n\n");
}
}
| protected void writeCellTopology(Cell cell, CellNetInfo cni, VarContext context, Topology.MyCellInfo info)
{
if (cell == topCell && USE_GLOBALS) {
Netlist netList = cni.getNetList();
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (!Simulation.isSpiceUseNodeNames() || spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_3)
{
if (globalSize > 0)
{
StringBuffer infstr = new StringBuffer();
infstr.append("\n.global");
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
String name = global.getName();
if (global == Global.power) { if (getPowerName(null) != null) name = getPowerName(null); }
if (global == Global.ground) { if (getGroundName(null) != null) name = getGroundName(null); }
infstr.append(" " + name);
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
}
}
// gather networks in the cell
Netlist netList = cni.getNetList();
// make sure power and ground appear at the top level
if (cell == topCell && !Simulation.isSpiceForceGlobalPwrGnd())
{
if (cni.getPowerNet() == null)
System.out.println("WARNING: cannot find power at top level of circuit");
if (cni.getGroundNet() == null)
System.out.println("WARNING: cannot find ground at top level of circuit");
}
// create list of electrical nets in this cell
HashMap<Network,SpiceNet> spiceNetMap = new HashMap<Network,SpiceNet>();
// create SpiceNet objects for all networks in the cell
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
// create a "SpiceNet" for the network
SpiceNet spNet = new SpiceNet();
spNet.network = net;
spNet.transistorCount = 0;
spNet.diffArea = 0;
spNet.diffPerim = 0;
spNet.nonDiffCapacitance = 0;
spNet.merge = new PolyMerge();
spiceNetMap.put(net, spNet);
}
// create list of segemented networks for parasitic extraction
boolean verboseSegmentedNames = Simulation.isParasiticsUseVerboseNaming();
boolean useParasitics = useNewParasitics && (!useCDL) &&
Simulation.isSpiceUseParasitics() && (cell.getView() == View.LAYOUT);
SegmentedNets segmentedNets = new SegmentedNets(cell, verboseSegmentedNames, cni, useParasitics);
segmentedParasiticInfo.add(segmentedNets);
if (useParasitics) {
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
//System.out.println("\n Finding parasitics for cell "+cell.describe(false));
HashMap<Network,Network> exemptedNetsFound = new HashMap<Network,Network>();
for (Iterator<ArcInst> ait = cell.getArcs(); ait.hasNext(); ) {
ArcInst ai = ait.next();
boolean ignoreArc = false;
// figure out res and cap, see if we should ignore it
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC)
ignoreArc = true;
double length = ai.getLambdaLength() * scale / 1000; // length in microns
double width = ai.getLambdaFullWidth() * scale / 1000; // width in microns
double area = length * width;
double fringe = length*2;
double cap = 0;
double res = 0;
Technology tech = ai.getProto().getTechnology();
Poly [] arcInstPolyList = tech.getShapeOfArc(ai);
int tot = arcInstPolyList.length;
for(int j=0; j<tot; j++)
{
Poly poly = arcInstPolyList[j];
if (poly.getStyle().isText()) continue;
Layer layer = poly.getLayer();
if (layer.getTechnology() != layoutTechnology) continue;
if ((layer.getFunctionExtras() & Layer.Function.PSEUDO) != 0) continue;
if (!layer.isDiffusionLayer() && layer.getCapacitance() > 0.0) {
double areacap = area * layer.getCapacitance();
double fringecap = fringe * layer.getEdgeCapacitance();
cap = areacap + fringecap;
res = length/width * layer.getResistance();
}
}
// add res if big enough
if (res <= cell.getTechnology().getMinResistance()) {
ignoreArc = true;
}
if (Simulation.isParasiticsUseExemptedNetsFile()) {
Network net = netList.getNetwork(ai, 0);
// ignore nets in exempted nets file
if (Simulation.isParasiticsIgnoreExemptedNets()) {
// check if this net is exempted
if (exemptedNets.isExempted(info.getNetID(net))) {
ignoreArc = true;
cap = 0;
if (!exemptedNetsFound.containsKey(net)) {
System.out.println("Not extracting net "+cell.describe(false)+" "+net.getName());
exemptedNetsFound.put(net, net);
cap = exemptedNets.getReplacementCap(cell, net);
}
}
// extract only nets in exempted nets file
} else {
if (exemptedNets.isExempted(info.getNetID(net)) && ignoreArc == false) {
if (!exemptedNetsFound.containsKey(net)) {
System.out.println("Extracting net "+cell.describe(false)+" "+net.getName());
exemptedNetsFound.put(net, net);
}
} else {
ignoreArc = true;
}
}
}
int arcPImodels = SegmentedNets.getNumPISegments(res, layoutTechnology.getMaxSeriesResistance());
if (ignoreArc)
arcPImodels = 1; // split cap to two pins if ignoring arc
// add caps
segmentedNets.putSegment(ai.getHeadPortInst(), cap/(arcPImodels+1));
segmentedNets.putSegment(ai.getTailPortInst(), cap/(arcPImodels+1));
if (ignoreArc) {
// short arc
segmentedNets.shortSegments(ai.getHeadPortInst(), ai.getTailPortInst());
} else {
segmentedNets.addArcRes(ai, res);
if (arcPImodels > 1)
segmentedNets.addArcCap(ai, cap); // need to store cap later to break it up
}
}
// Don't take into account gate resistance: so we need to short two PortInsts
// of gate together if this is layout
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
if (!ni.isCellInstance()) {
if (((PrimitiveNode)ni.getProto()).getGroupFunction() == PrimitiveNode.Function.TRANS) {
PortInst gate0 = ni.getTransistorGatePort();
PortInst gate1 = null;
for (Iterator<PortInst> pit = ni.getPortInsts(); pit.hasNext();) {
PortInst p2 = pit.next();
if (p2 != gate0 && netList.getNetwork(gate0) == netList.getNetwork(p2))
gate1 = p2;
}
if (gate1 != null) {
segmentedNets.shortSegments(gate0, gate1);
}
}
} else {
//System.out.println("Shorting shorted exports");
// short together pins if shorted by subcell
Cell subCell = (Cell)ni.getProto();
SegmentedNets subNets = getSegmentedNets(subCell);
// list of lists of shorted exports
if (subNets != null) { // subnets may be null if mixing schematics with layout technologies
for (Iterator<List<String>> it = subNets.getShortedExports(); it.hasNext(); ) {
List<String> exports = it.next();
PortInst pi1 = null;
// list of exports shorted together
for (String exportName : exports) {
// get portinst on node
PortInst pi = ni.findPortInst(exportName);
if (pi1 == null) {
pi1 = pi; continue;
}
segmentedNets.shortSegments(pi1, pi);
}
}
}
}
} // for (cell.getNodes())
}
// count the number of different transistor types
int bipolarTrans = 0, nmosTrans = 0, pmosTrans = 0;
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
addNodeInformation(netList, spiceNetMap, ni);
PrimitiveNode.Function fun = ni.getFunction();
if (fun == PrimitiveNode.Function.TRANPN || fun == PrimitiveNode.Function.TRA4NPN ||
fun == PrimitiveNode.Function.TRAPNP || fun == PrimitiveNode.Function.TRA4PNP ||
fun == PrimitiveNode.Function.TRANS) bipolarTrans++; else
if (fun == PrimitiveNode.Function.TRAEMES || fun == PrimitiveNode.Function.TRA4EMES ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRA4DMES ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS) nmosTrans++; else
if (fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS) pmosTrans++;
}
// accumulate geometry of all arcs
for(Iterator<ArcInst> aIt = cell.getArcs(); aIt.hasNext(); )
{
ArcInst ai = aIt.next();
// don't count non-electrical arcs
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC) continue;
// ignore busses
// if (ai->network->buswidth > 1) continue;
Network net = netList.getNetwork(ai, 0);
SpiceNet spNet = spiceNetMap.get(net);
if (spNet == null) continue;
addArcInformation(spNet.merge, ai);
}
// get merged polygons so far
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = spiceNetMap.get(net);
for (Layer layer : spNet.merge.getKeySet())
{
List<PolyBase> polyList = spNet.merge.getMergedPoints(layer, true);
if (polyList == null) continue;
if (polyList.size() > 1)
Collections.sort(polyList, GeometryHandler.shapeSort);
for(PolyBase poly : polyList)
{
// compute perimeter and area
double perim = poly.getPerimeter();
double area = poly.getArea();
// accumulate this information
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
if (layer.isDiffusionLayer()) {
spNet.diffArea += area * maskScale * maskScale;
spNet.diffPerim += perim * maskScale;
} else {
area = area * scale * scale / 1000000; // area in square microns
perim = perim * scale / 1000; // perim in microns
spNet.nonDiffCapacitance += layer.getCapacitance() * area * maskScale * maskScale;
spNet.nonDiffCapacitance += layer.getEdgeCapacitance() * perim * maskScale;
}
}
}
}
// make sure the ground net is number zero
Network groundNet = cni.getGroundNet();
Network powerNet = cni.getPowerNet();
if (pmosTrans != 0 && powerNet == null)
{
String message = "WARNING: no power connection for P-transistor wells in " + cell;
dumpErrorMessage(message);
}
if (nmosTrans != 0 && groundNet == null)
{
String message = "WARNING: no ground connection for N-transistor wells in " + cell;
dumpErrorMessage(message);
}
// // use ground net for substrate
// if (subnet == NOSPNET && sim_spice_gnd != NONETWORK)
// subnet = (SPNET *)sim_spice_gnd->temp1;
// if (bipolarTrans != 0 && subnet == NOSPNET)
// {
// infstr = initinfstr();
// formatinfstr(infstr, _("WARNING: no explicit connection to the substrate in cell %s"),
// describenodeproto(np));
// dumpErrorMessage(infstr);
// if (sim_spice_gnd != NONETWORK)
// {
// ttyputmsg(_(" A connection to ground will be used if necessary."));
// subnet = (SPNET *)sim_spice_gnd->temp1;
// }
// }
// generate header for subckt or top-level cell
String topLevelInstance = "";
if (cell == topCell && !useCDL && !Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(true, "\n*** TOP LEVEL CELL: " + cell.describe(false) + "\n");
} else
{
if (!writeEmptySubckts) {
if (cellIsEmpty(cell))
return;
}
String cellName = cni.getParameterizedName();
multiLinePrint(true, "\n*** CELL: " + cell.describe(false) + "\n");
StringBuffer infstr = new StringBuffer();
infstr.append(".SUBCKT " + cellName);
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
if (ignoreSubcktPort(cs)) continue;
if (cs.isGlobal()) {
System.out.println("Warning: Explicit Global signal "+cs.getName()+" exported in "+cell.describe(false));
}
// special case for parasitic extraction
if (useParasitics && !cs.isGlobal() && cs.getExport() != null) {
Network net = cs.getNetwork();
HashMap<String,List<String>> shortedExportsMap = new HashMap<String,List<String>>();
// For a single logical network, we need to:
// 1) treat certain exports as separate so as not to short resistors on arcs between the exports
// 2) join certain exports that do not have resistors on arcs between them, and record this information
// so that the next level up knows to short networks connection to those exports.
for (Iterator<Export> it = net.getExports(); it.hasNext(); ) {
Export e = it.next();
PortInst pi = e.getOriginalPort();
String name = segmentedNets.getNetName(pi);
// exports are shorted if their segmented net names are the same (case (2))
List<String> shortedExports = shortedExportsMap.get(name);
if (shortedExports == null) {
shortedExports = new ArrayList<String>();
shortedExportsMap.put(name, shortedExports);
// this is the first occurance of this segmented network,
// use the name as the export (1)
infstr.append(" " + name);
}
shortedExports.add(e.getName());
}
// record shorted exports
for (List<String> shortedExports : shortedExportsMap.values()) {
if (shortedExports.size() > 1) {
segmentedNets.addShortedExports(shortedExports);
}
}
} else {
infstr.append(" " + cs.getName());
}
}
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (USE_GLOBALS)
{
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
infstr.append(" " + cs.getName());
}
}
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
// create top level instantiation
if (Simulation.isSpiceWriteTopCellInstance())
topLevelInstance = infstr.toString().replaceFirst("\\.SUBCKT ", "X") + " " + cellName;
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this cell
for(Iterator<Variable> it = cell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (paramVar.getCode() != TextDescriptor.Code.SPICE) continue;
infstr.append(" " + paramVar.getTrueName() + "=" + paramVar.getPureValue(-1));
}
// for(Iterator it = cell.getVariables(); it.hasNext(); )
// {
// Variable paramVar = it.next();
// if (!paramVar.isParam()) continue;
// infstr.append(" " + paramVar.getTrueName() + "=" + paramVar.getPureValue(-1));
// }
}
// Writing M factor
//writeMFactor(cell, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
// generate pin descriptions for reference (when not using node names)
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
multiLinePrint(true, "** GLOBAL " + cs.getName() + "\n");
}
// write exports to this cell
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
// ignore networks that aren't exported
PortProto pp = cs.getExport();
if (pp == null) continue;
if (cs.isGlobal()) continue;
//multiLinePrint(true, "** PORT " + cs.getName() + "\n");
}
}
// write out any directly-typed SPICE declaratons for the cell
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech.invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_DECLARATION_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Declaration nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false);
}
}
// third pass through the node list, print it this time
for(Iterator<Nodable> nIt = netList.getNodables(); nIt.hasNext(); )
{
Nodable no = nIt.next();
NodeProto niProto = no.getProto();
// handle sub-cell calls
if (no.isCellInstance())
{
Cell subCell = (Cell)niProto;
// look for a SPICE template on the prototype
Variable varTemplate = null;
if (useCDL)
{
varTemplate = subCell.getVar(CDL_TEMPLATE_KEY);
} else
{
varTemplate = getEngineTemplate(subCell);
// varTemplate = subCell.getVar(preferedEngineTemplateKey);
// if (varTemplate == null)
// varTemplate = subCell.getVar(SPICE_TEMPLATE_KEY);
}
// handle templates
if (varTemplate != null)
{
if (varTemplate.getObject() instanceof Object[])
{
Object [] manyLines = (Object [])varTemplate.getObject();
for(int i=0; i<manyLines.length; i++)
{
String line = manyLines[i].toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
if (i == 0) writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
} else
{
String line = varTemplate.getObject().toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
continue;
}
// get the ports on this node (in proper order)
CellNetInfo subCni = getCellNetInfo(parameterizedName(no, context));
if (subCni == null) continue;
if (!writeEmptySubckts) {
// do not instantiate if empty
if (cellIsEmpty((Cell)niProto))
continue;
}
String modelChar = "X";
if (no.getName() != null) modelChar += getSafeNetName(no.getName(), false);
StringBuffer infstr = new StringBuffer();
infstr.append(modelChar);
for(Iterator<CellSignal> sIt = subCni.getCellSignals(); sIt.hasNext(); )
{
CellSignal subCS = sIt.next();
// ignore networks that aren't exported
PortProto pp = subCS.getExport();
Network net;
int exportIndex = subCS.getExportIndex();
// This checks if we are netlisting a schematic top level with
// swapped-in layout subcells
if (pp != null && (cell.getView() == View.SCHEMATIC) && (subCni.getCell().getView() == View.LAYOUT)) {
// find equivalent pp from layout to schematic
Network subNet = subCS.getNetwork(); // layout network name
boolean found = false;
for (Iterator<Export> eIt = subCell.getExports(); eIt.hasNext(); ) {
Export ex = eIt.next();
for (int i=0; i<ex.getNameKey().busWidth(); i++) {
String exName = ex.getNameKey().subname(i).toString();
if (exName.equals(subNet.getName())) {
pp = ex;
exportIndex = i;
found = true;
break;
}
}
if (found) break;
}
if (!found) {
if (pp.isGround() && pp.getName().startsWith("gnd")) {
infstr.append(" gnd");
} else if (pp.isPower() && pp.getName().startsWith("vdd")) {
infstr.append(" vdd");
} else {
System.out.println("No matching export on schematic/icon found for export "+
subNet.getName()+" in cell "+subCni.getCell().describe(false));
infstr.append(" unknown");
}
continue;
}
}
if (USE_GLOBALS)
{
if (pp == null) continue;
if (subCS.isGlobal() && subCS.getNetwork().isExported()) {
// only add to port list if exported with global name
if (!isGlobalExport(subCS)) continue;
}
net = netList.getNetwork(no, pp, exportIndex);
} else
{
if (pp == null && !subCS.isGlobal()) continue;
if (subCS.isGlobal())
net = netList.getNetwork(no, subCS.getGlobal());
else
net = netList.getNetwork(no, pp, exportIndex);
}
CellSignal cs = cni.getCellSignal(net);
// special case for parasitic extraction
if (useParasitics && !cs.isGlobal()) {
// connect to all exports (except power and ground of subcell net)
SegmentedNets subSegmentedNets = getSegmentedNets((Cell)no.getProto());
Network subNet = subCS.getNetwork();
List<String> exportNames = new ArrayList<String>();
for (Iterator<Export> it = subNet.getExports(); it.hasNext(); ) {
// get subcell export, unless collapsed due to less than min R
Export e = it.next();
PortInst pi = e.getOriginalPort();
String name = subSegmentedNets.getNetName(pi);
if (exportNames.contains(name)) continue;
exportNames.add(name);
// ok, there is a port on the subckt on this subcell for this export,
// now get the appropriate network in this cell
pi = no.getNodeInst().findPortInstFromProto(no.getProto().findPortProto(e.getNameKey()));
name = segmentedNets.getNetName(pi);
infstr.append(" " + name);
}
} else {
String name = cs.getName();
if (segmentedNets.getUseParasitics()) {
name = segmentedNets.getNetName(no.getNodeInst().findPortInstFromProto(pp));
}
infstr.append(" " + name);
}
}
if (USE_GLOBALS)
{
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
Global.Set globals = subCni.getNetList().getGlobals();
int globalSize = globals.size();
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
infstr.append(" " + global.getName());
}
}
}
if (useCDL) {
infstr.append(" /" + subCni.getParameterizedName());
} else {
infstr.append(" " + subCni.getParameterizedName());
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this instance
for(Iterator<Variable> it = subCell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
Variable instVar = no.getVar(paramVar.getKey());
String paramStr = "??";
if (instVar != null) {
if (paramVar.getCode() != TextDescriptor.Code.SPICE) continue;
Object obj = context.evalSpice(instVar, false);
if (obj != null)
paramStr = formatParam(String.valueOf(obj));
}
infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
}
// for(Iterator it = subCell.getVariables(); it.hasNext(); )
// {
// Variable paramVar = it.next();
// if (!paramVar.isParam()) continue;
// Variable instVar = no.getVar(paramVar.getKey());
// String paramStr = "??";
// if (instVar != null) paramStr = formatParam(trimSingleQuotes(String.valueOf(context.evalVar(instVar))));
// infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
// }
}
// Writing MFactor if available.
writeMFactor(context, no, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
continue;
}
// get the type of this node
NodeInst ni = (NodeInst)no;
PrimitiveNode.Function fun = ni.getFunction();
// handle resistors, inductors, capacitors, and diodes
if (fun.isResistor() || // == PrimitiveNode.Function.RESIST ||
fun == PrimitiveNode.Function.INDUCT ||
fun.isCapacitor() || // == PrimitiveNode.Function.CAPAC || fun == PrimitiveNode.Function.ECAPAC ||
fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
if (fun.isResistor()) // == PrimitiveNode.Function.RESIST)
{
if ((fun == PrimitiveNode.Function.PRESIST && isShortExplicitResistors()) ||
(fun == PrimitiveNode.Function.RESIST && isShortResistors()))
continue;
Variable resistVar = ni.getVar(Schematics.SCHEM_RESISTANCE);
String extra = "";
String partName = "R";
if (resistVar != null)
{
if (resistVar.getCode() == TextDescriptor.Code.SPICE) {
Object obj = context.evalSpice(resistVar, false);
extra = String.valueOf(obj);
}
if (extra == "")
extra = resistVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); //displayedUnits(pureValue, TextDescriptor.Unit.RESISTANCE, TextUtils.UnitScale.NONE);
} else {
extra = "'"+extra+"'";
}
} else {
if (fun == PrimitiveNode.Function.PRESIST) {
partName = "XR";
double width = ni.getYSize();
double length = ni.getXSize();
SizeOffset offset = ni.getSizeOffset();
width = width - offset.getHighYOffset() - offset.getLowYOffset();
length = length - offset.getHighXOffset() - offset.getLowXOffset();
extra = " L='"+length+"*LAMBDA' W='"+width+"*LAMBDA'";
if (layoutTechnology == Technology.getCMOS90Technology() ||
(cell.getView() == View.LAYOUT && cell.getTechnology() == Technology.getCMOS90Technology())) {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "GND rpporpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "GND rnporpo"+extra;
}
} else {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "rppo1rpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "rnpo1rpo"+extra;
}
}
}
}
writeTwoPort(ni, partName, extra, cni, netList, context, segmentedNets);
} else if (fun.isCapacitor()) // == PrimitiveNode.Function.CAPAC || fun == PrimitiveNode.Function.ECAPAC)
{
Variable capacVar = ni.getVar(Schematics.SCHEM_CAPACITANCE);
String extra = "";
if (capacVar != null)
{
if (capacVar.getCode() == TextDescriptor.Code.SPICE) {
Object obj = context.evalSpice(capacVar, false);
extra = String.valueOf(obj);
}
if (extra == "")
extra = capacVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.CAPACITANCE, TextUtils.UnitScale.NONE);
} else {
extra = "'"+extra+"'";
}
}
writeTwoPort(ni, "C", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.INDUCT)
{
Variable inductVar = ni.getVar(Schematics.SCHEM_INDUCTANCE);
String extra = "";
if (inductVar != null)
{
if (inductVar.getCode() == TextDescriptor.Code.SPICE) {
Object obj = context.evalSpice(inductVar, false);
extra = String.valueOf(obj);
}
if (extra == "")
extra = inductVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.INDUCTANCE, TextUtils.UnitScale.NONE);
} else {
extra = "'"+extra+"'";
}
}
writeTwoPort(ni, "L", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
Variable diodeVar = ni.getVar(Schematics.SCHEM_DIODE);
String extra = "";
if (diodeVar != null)
extra = diodeVar.describe(context, ni);
if (extra.length() == 0) extra = "DIODE";
writeTwoPort(ni, "D", extra, cni, netList, context, segmentedNets);
}
continue;
}
// the default is to handle everything else as a transistor
if (((PrimitiveNode)niProto).getGroupFunction() != PrimitiveNode.Function.TRANS)
continue;
Network gateNet = netList.getNetwork(ni.getTransistorGatePort());
CellSignal gateCs = cni.getCellSignal(gateNet);
Network sourceNet = netList.getNetwork(ni.getTransistorSourcePort());
CellSignal sourceCs = cni.getCellSignal(sourceNet);
Network drainNet = netList.getNetwork(ni.getTransistorDrainPort());
CellSignal drainCs = cni.getCellSignal(drainNet);
CellSignal biasCs = null;
PortInst biasPort = ni.getTransistorBiasPort();
if (biasPort != null)
{
biasCs = cni.getCellSignal(netList.getNetwork(biasPort));
}
// make sure transistor is connected to nets
if (gateCs == null || sourceCs == null || drainCs == null)
{
String message = "WARNING: " + ni + " not fully connected in " + cell;
dumpErrorMessage(message);
}
// get model information
String modelName = null;
String defaultBulkName = null;
Variable modelVar = ni.getVar(SPICE_MODEL_KEY);
if (modelVar != null) modelName = modelVar.getObject().toString();
// special case for ST090 technology which has stupid non-standard transistor
// models which are subcircuits
boolean st090laytrans = false;
boolean tsmc090laytrans = false;
if (cell.getView() == View.LAYOUT && layoutTechnology == Technology.getCMOS90Technology()) {
if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.TSMC)
tsmc090laytrans = true;
else if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.ST)
st090laytrans = true;
}
String modelChar = "";
if (fun == PrimitiveNode.Function.TRANSREF) // self-referential transistor
{
modelChar = "X";
biasCs = cni.getCellSignal(groundNet);
modelName = niProto.getName();
} else if (fun == PrimitiveNode.Function.TRANMOS) // NMOS (Enhancement) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
defaultBulkName = "gnd";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRA4NMOS) // NMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRADMOS) // DMOS (Depletion) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRA4DMOS) // DMOS (Depletion) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRAPMOS) // PMOS (Complementary) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(powerNet);
defaultBulkName = "vdd";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRA4PMOS) // PMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRANPN) // NPN (Junction) transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRA4NPN) // NPN (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRAPNP) // PNP (Junction) transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRA4PNP) // PNP (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRANJFET) // NJFET (N Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRA4NJFET) // NJFET (N Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRAPJFET) // PJFET (P Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRA4PJFET) // PJFET (P Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRADMES || // DMES (Depletion) transistor
fun == PrimitiveNode.Function.TRA4DMES) // DMES (Depletion) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "DMES";
} else if (fun == PrimitiveNode.Function.TRAEMES || // EMES (Enhancement) transistor
fun == PrimitiveNode.Function.TRA4EMES) // EMES (Enhancement) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "EMES";
} else if (fun == PrimitiveNode.Function.TRANS) // special transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
}
if (ni.getName() != null) modelChar += getSafeNetName(ni.getName(), false);
StringBuffer infstr = new StringBuffer();
String drainName = drainCs.getName();
String gateName = gateCs.getName();
String sourceName = sourceCs.getName();
if (segmentedNets.getUseParasitics()) {
drainName = segmentedNets.getNetName(ni.getTransistorDrainPort());
gateName = segmentedNets.getNetName(ni.getTransistorGatePort());
sourceName = segmentedNets.getNetName(ni.getTransistorSourcePort());
}
infstr.append(modelChar + " " + drainName + " " + gateName + " " + sourceName);
if (biasCs != null) {
String biasName = biasCs.getName();
if (segmentedNets.getUseParasitics()) {
if (ni.getTransistorBiasPort() != null)
biasName = segmentedNets.getNetName(ni.getTransistorBiasPort());
}
infstr.append(" " + biasName);
} else {
if (cell.getView() == View.LAYOUT && defaultBulkName != null)
infstr.append(" " + defaultBulkName);
}
if (modelName != null) infstr.append(" " + modelName);
// compute length and width (or area for nonMOS transistors)
TransistorSize size = ni.getTransistorSize(context);
if (size == null)
System.out.println("Warning: transistor with null size " + ni.getName());
else
{
if (size.getDoubleWidth() > 0 || size.getDoubleLength() > 0)
{
double w = maskScale * size.getDoubleWidth();
double l = maskScale * size.getDoubleLength();
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
l -= lengthSubtraction;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
// make into microns (convert to nanometers then divide by 1000)
l *= layoutTechnology.getScale() / 1000.0;
w *= layoutTechnology.getScale() / 1000.0;
}
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
((fun == PrimitiveNode.Function.TRANJFET || fun == PrimitiveNode.Function.TRAPJFET ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRAEMES) &&
(spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_ASSURA)))
{
// schematic transistors may be text
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength()) + " - "+ lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength()));
} else {
infstr.append(" L=" + TextUtils.formatDouble(l, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String)) {
infstr.append(" W="+formatParam((String)size.getWidth()));
} else {
infstr.append(" W=" + TextUtils.formatDouble(w, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
if (fun != PrimitiveNode.Function.TRANMOS && fun != PrimitiveNode.Function.TRA4NMOS &&
fun != PrimitiveNode.Function.TRAPMOS && fun != PrimitiveNode.Function.TRA4PMOS &&
fun != PrimitiveNode.Function.TRADMOS && fun != PrimitiveNode.Function.TRA4DMOS)
{
infstr.append(" AREA=" + TextUtils.formatDouble(l*w, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda()) infstr.append("P");
}
} else {
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength()) + " - "+lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength()));
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String))
infstr.append(" W="+formatParam((String)size.getWidth()));
}
}
// make sure transistor is connected to nets
SpiceNet spNetGate = spiceNetMap.get(gateNet);
SpiceNet spNetSource = spiceNetMap.get(sourceNet);
SpiceNet spNetDrain = spiceNetMap.get(drainNet);
if (spNetGate == null || spNetSource == null || spNetDrain == null) continue;
// compute area of source and drain
if (!useCDL)
{
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS)
{
double as = 0, ad = 0, ps = 0, pd = 0;
if (spNetSource.transistorCount != 0)
{
as = spNetSource.diffArea / spNetSource.transistorCount;
ps = spNetSource.diffPerim / spNetSource.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
as *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
ps *= layoutTechnology.getScale() / 1000.0;
}
}
if (spNetDrain.transistorCount != 0)
{
ad = spNetDrain.diffArea / spNetDrain.transistorCount;
pd = spNetDrain.diffPerim / spNetDrain.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
ad *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
pd *= layoutTechnology.getScale() / 1000.0;
}
}
if (as > 0.0)
{
infstr.append(" AS=" + TextUtils.formatDouble(as, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ad > 0.0)
{
infstr.append(" AD=" + TextUtils.formatDouble(ad, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ps > 0.0)
{
infstr.append(" PS=" + TextUtils.formatDouble(ps, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if (pd > 0.0)
{
infstr.append(" PD=" + TextUtils.formatDouble(pd, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
}
// Writing MFactor if available.
writeMFactor(context, ni, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
// print resistances and capacitances
if (!useCDL)
{
if (Simulation.isSpiceUseParasitics() && cell.getView() == View.LAYOUT)
{
if (useNewParasitics) {
int capCount = 0;
int resCount = 0;
// write caps
multiLinePrint(true, "** Extracted Parasitic Capacitors ***\n");
for (SegmentedNets.NetInfo netInfo : segmentedNets.getUniqueSegments()) {
if (netInfo.cap > cell.getTechnology().getMinCapacitance()) {
if (netInfo.netName.equals("gnd")) continue; // don't write out caps from gnd to gnd
multiLinePrint(false, "C" + capCount + " " + netInfo.netName + " 0 " + TextUtils.formatDouble(netInfo.cap, 2) + "fF\n");
capCount++;
}
}
// write resistors
multiLinePrint(true, "** Extracted Parasitic Resistors ***\n");
for (Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) {
ArcInst ai = it.next();
Double res = segmentedNets.arcRes.get(ai);
if (res == null) continue;
String n0 = segmentedNets.getNetName(ai.getHeadPortInst());
String n1 = segmentedNets.getNetName(ai.getTailPortInst());
int arcPImodels = SegmentedNets.getNumPISegments(res.doubleValue(), layoutTechnology.getMaxSeriesResistance());
if (arcPImodels > 1) {
// have to break it up into smaller pieces
double segCap = segmentedNets.getArcCap(ai)/((double)(arcPImodels+1));
double segRes = res.doubleValue()/((double)arcPImodels);
String segn0 = n0;
String segn1 = n0;
for (int i=0; i<arcPImodels; i++) {
segn1 = n0 + "##" + i;
// print cap on intermediate node
if (i == (arcPImodels-1))
segn1 = n1;
multiLinePrint(false, "R"+resCount+" "+segn0+" "+segn1+" "+TextUtils.formatDouble(segRes)+"\n");
resCount++;
if (i < (arcPImodels-1)) {
if (!segn1.equals("gnd")) {
multiLinePrint(false, "C"+capCount+" "+segn1+" 0 "+TextUtils.formatDouble(segCap)+"fF\n");
capCount++;
}
}
segn0 = segn1;
}
} else {
multiLinePrint(false, "R" + resCount + " " + n0 + " " + n1 + " " + TextUtils.formatDouble(res.doubleValue(), 2) + "\n");
resCount++;
}
}
} else {
// print parasitic capacitances
boolean first = true;
int capacNum = 1;
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
Network net = cs.getNetwork();
if (net == cni.getGroundNet()) continue;
SpiceNet spNet = spiceNetMap.get(net);
if (spNet.nonDiffCapacitance > layoutTechnology.getMinCapacitance())
{
if (first)
{
first = false;
multiLinePrint(true, "** Extracted Parasitic Elements:\n");
}
multiLinePrint(false, "C" + capacNum + " " + cs.getName() + " 0 " + TextUtils.formatDouble(spNet.nonDiffCapacitance, 2) + "fF\n");
capacNum++;
}
}
}
}
}
// write out any directly-typed SPICE cards
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech.invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_CARD_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Code nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false);
}
}
// finally, if this is the top level,
// write out some very small resistors between any networks
// that are asserted will be connected by the NCC annotation "exportsConnectedByParent"
// this should really be done internally in the network tool with a switch, but
// this hack works here for now
NccCellAnnotations anna = NccCellAnnotations.getAnnotations(cell);
if (cell == topCell && anna != null) {
// each list contains all name patterns that are be shorted together
if (anna.getExportsConnected().hasNext()) {
multiLinePrint(true, "\n*** Exports shorted due to NCC annotation 'exportsConnectedByParent':\n");
}
for (Iterator<List<NamePattern>> it = anna.getExportsConnected(); it.hasNext(); ) {
List<NamePattern> list = it.next();
List<Network> netsToConnect = new ArrayList<Network>();
// each name pattern can match any number of exports in the cell
for (NccCellAnnotations.NamePattern pat : list) {
for (Iterator<PortProto> it3 = cell.getPorts(); it3.hasNext(); ) {
Export e = (Export)it3.next();
String name = e.getName();
// keep track of networks to short together
if (pat.matches(name)) {
Network net = netList.getNetwork(e, 0);
if (!netsToConnect.contains(net))
netsToConnect.add(net);
}
}
}
// connect all nets in list of nets to connect
String name = null;
// int i=0;
for (Network net : netsToConnect) {
if (name != null) {
multiLinePrint(false, "R"+name+" "+name+" "+net.getName()+" 0.001\n");
}
name = net.getName();
// i++;
}
}
}
// now we're finished writing the subcircuit.
if (cell != topCell || useCDL || Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(false, ".ENDS " + cni.getParameterizedName() + "\n");
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
multiLinePrint(false, "\n\n"+topLevelInstance+"\n\n");
}
}
|
diff --git a/src/main/java/signup.java b/src/main/java/signup.java
index f876882..70d4ffb 100644
--- a/src/main/java/signup.java
+++ b/src/main/java/signup.java
@@ -1,110 +1,111 @@
package edu.cst438.fourup;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.util.*;
import com.google.gson.Gson;
import java.net.URI;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.MongoURI;
import java.net.UnknownHostException;
import java.util.Set;
import com.mongodb.DB;
import com.mongodb.MongoException;
public class signup extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String email = request.getParameter("email");
String password = request.getParameter("password");
+ String verifypassword = request.getParameter("verifypassword");
Map<String, String> myResponse = new HashMap<String, String>();
myResponse.put("Status", "Success");
myResponse.put("message", "what happened here");
myResponse.put("Error", "there was an error");
String strResponse = new Gson().toJson(myResponse);
PrintWriter out = response.getWriter();
if (email.matches("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"))//make sure email is properly formatted
{
try
{
//URI mongoURI = new URI(System.getenv("mongodb://fsolis:[email protected]:10041/app15095098"));
MongoURI mongoURI = new MongoURI(System.getenv("MONGOHQ_URL"));
DB db = mongoURI.connectDB(); //instance of databse
//db.authenticate(mongoURI.getUsername(), mongoURI.getPassword());//authenticates d
//Set<string> accounts = db.getCollectionName("accounts");
//Mongo mongo = new Mongo("localhost", 27017); //creates new instance of mongo
//DB db = mongo.getDB("fourup"); //gets fourup database
DBCollection accounts = db.getCollection("accounts"); //creates collection for accounts
BasicDBObject query = new BasicDBObject(); //creates a basic object named query
query.put("email", email); //sets email to email
DBCursor cursor = accounts.find(query);
if (cursor.size() > 0) //check if email has already been registered
{
out.write(myResponse.get("Error")); //should output error
}
else //since email doesn't currently exist in DB, go ahead and register user
{
- if (password.equals(verifypassword))//check that both of the passwords entered match each other
+ if (password.equals(verifypassword)) //check that both of the passwords entered match each other
{
BasicDBObject document = new BasicDBObject();
int salt = getSalt();
String hpass = passwrdHash(password,salt);
document.put("email", email);
document.put("salt", salt);
- document.put("password", hpass);//this is where we need to hash the password
+ document.put("password", hpass); //this is where we need to hash the password
accounts.insert(document);
out.write(myResponse.get("Status"));
}
else
{
out.write(myResponse.get("Error")); //should output error
}
}
}
catch (MongoException e)
{
e.printStackTrace();
}
}
else
{
out.write(myResponse.get("Error")); //should output error
}
}
public String passwrdHash(String password,int salt)
{
char c;
int n;
String temp = "",temper2 = "";
for(int i = 0;i<password.length();i++)
{
c = password.charAt(i);
n = c * salt;
temper2 = Integer.toString(n);
temp = temp + temper2;
}
System.out.println(temp);
return temp;
}
public int getSalt()
{
Random generator = new Random();
int salt;
salt = generator.nextInt(1000);
return salt;
}
}
| false | true | public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String email = request.getParameter("email");
String password = request.getParameter("password");
Map<String, String> myResponse = new HashMap<String, String>();
myResponse.put("Status", "Success");
myResponse.put("message", "what happened here");
myResponse.put("Error", "there was an error");
String strResponse = new Gson().toJson(myResponse);
PrintWriter out = response.getWriter();
if (email.matches("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"))//make sure email is properly formatted
{
try
{
//URI mongoURI = new URI(System.getenv("mongodb://fsolis:[email protected]:10041/app15095098"));
MongoURI mongoURI = new MongoURI(System.getenv("MONGOHQ_URL"));
DB db = mongoURI.connectDB(); //instance of databse
//db.authenticate(mongoURI.getUsername(), mongoURI.getPassword());//authenticates d
//Set<string> accounts = db.getCollectionName("accounts");
//Mongo mongo = new Mongo("localhost", 27017); //creates new instance of mongo
//DB db = mongo.getDB("fourup"); //gets fourup database
DBCollection accounts = db.getCollection("accounts"); //creates collection for accounts
BasicDBObject query = new BasicDBObject(); //creates a basic object named query
query.put("email", email); //sets email to email
DBCursor cursor = accounts.find(query);
if (cursor.size() > 0) //check if email has already been registered
{
out.write(myResponse.get("Error")); //should output error
}
else //since email doesn't currently exist in DB, go ahead and register user
{
if (password.equals(verifypassword))//check that both of the passwords entered match each other
{
BasicDBObject document = new BasicDBObject();
int salt = getSalt();
String hpass = passwrdHash(password,salt);
document.put("email", email);
document.put("salt", salt);
document.put("password", hpass);//this is where we need to hash the password
accounts.insert(document);
out.write(myResponse.get("Status"));
}
else
{
out.write(myResponse.get("Error")); //should output error
}
}
}
catch (MongoException e)
{
e.printStackTrace();
}
}
else
{
out.write(myResponse.get("Error")); //should output error
}
}
| public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String email = request.getParameter("email");
String password = request.getParameter("password");
String verifypassword = request.getParameter("verifypassword");
Map<String, String> myResponse = new HashMap<String, String>();
myResponse.put("Status", "Success");
myResponse.put("message", "what happened here");
myResponse.put("Error", "there was an error");
String strResponse = new Gson().toJson(myResponse);
PrintWriter out = response.getWriter();
if (email.matches("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"))//make sure email is properly formatted
{
try
{
//URI mongoURI = new URI(System.getenv("mongodb://fsolis:[email protected]:10041/app15095098"));
MongoURI mongoURI = new MongoURI(System.getenv("MONGOHQ_URL"));
DB db = mongoURI.connectDB(); //instance of databse
//db.authenticate(mongoURI.getUsername(), mongoURI.getPassword());//authenticates d
//Set<string> accounts = db.getCollectionName("accounts");
//Mongo mongo = new Mongo("localhost", 27017); //creates new instance of mongo
//DB db = mongo.getDB("fourup"); //gets fourup database
DBCollection accounts = db.getCollection("accounts"); //creates collection for accounts
BasicDBObject query = new BasicDBObject(); //creates a basic object named query
query.put("email", email); //sets email to email
DBCursor cursor = accounts.find(query);
if (cursor.size() > 0) //check if email has already been registered
{
out.write(myResponse.get("Error")); //should output error
}
else //since email doesn't currently exist in DB, go ahead and register user
{
if (password.equals(verifypassword)) //check that both of the passwords entered match each other
{
BasicDBObject document = new BasicDBObject();
int salt = getSalt();
String hpass = passwrdHash(password,salt);
document.put("email", email);
document.put("salt", salt);
document.put("password", hpass); //this is where we need to hash the password
accounts.insert(document);
out.write(myResponse.get("Status"));
}
else
{
out.write(myResponse.get("Error")); //should output error
}
}
}
catch (MongoException e)
{
e.printStackTrace();
}
}
else
{
out.write(myResponse.get("Error")); //should output error
}
}
|
diff --git a/cat-core/src/main/java/com/dianping/cat/build/ComponentsConfigurator.java b/cat-core/src/main/java/com/dianping/cat/build/ComponentsConfigurator.java
index 92d7fe868..7604a8c3f 100644
--- a/cat-core/src/main/java/com/dianping/cat/build/ComponentsConfigurator.java
+++ b/cat-core/src/main/java/com/dianping/cat/build/ComponentsConfigurator.java
@@ -1,76 +1,76 @@
package com.dianping.cat.build;
import java.util.ArrayList;
import java.util.List;
import org.unidal.initialization.Module;
import org.unidal.lookup.configuration.AbstractResourceConfigurator;
import org.unidal.lookup.configuration.Component;
import com.dianping.cat.CatCoreModule;
import com.dianping.cat.DomainManager;
import com.dianping.cat.ServerConfigManager;
import com.dianping.cat.analysis.DefaultMessageAnalyzerManager;
import com.dianping.cat.analysis.MessageAnalyzerManager;
import com.dianping.cat.configuration.ClientConfigManager;
import com.dianping.cat.core.dal.HostinfoDao;
import com.dianping.cat.core.dal.ProjectDao;
import com.dianping.cat.core.dal.TaskDao;
import com.dianping.cat.message.spi.MessageCodec;
import com.dianping.cat.message.spi.codec.PlainTextMessageCodec;
import com.dianping.cat.message.spi.core.DefaultMessageHandler;
import com.dianping.cat.message.spi.core.DefaultMessagePathBuilder;
import com.dianping.cat.message.spi.core.MessageHandler;
import com.dianping.cat.message.spi.core.MessagePathBuilder;
import com.dianping.cat.message.spi.core.TcpSocketReceiver;
import com.dianping.cat.message.spi.core.TcpSocketReceiver.DecodeMessageTask;
import com.dianping.cat.statistic.ServerStatisticManager;
import com.dianping.cat.storage.dump.LocalMessageBucket;
import com.dianping.cat.storage.dump.LocalMessageBucketManager;
import com.dianping.cat.storage.dump.MessageBucket;
import com.dianping.cat.storage.dump.MessageBucketManager;
import com.dianping.cat.task.TaskManager;
public class ComponentsConfigurator extends AbstractResourceConfigurator {
@Override
public List<Component> defineComponents() {
List<Component> all = new ArrayList<Component>();
all.add(C(DomainManager.class)//
.req(ServerConfigManager.class, ProjectDao.class, HostinfoDao.class));
all.add(C(TaskManager.class).req(TaskDao.class));
all.add(C(ServerConfigManager.class));
all.add(C(ServerStatisticManager.class));
all.add(C(MessagePathBuilder.class, DefaultMessagePathBuilder.class) //
.req(ClientConfigManager.class));
all.add(C(MessageAnalyzerManager.class, DefaultMessageAnalyzerManager.class));
all.add(C(TcpSocketReceiver.class).req(ServerConfigManager.class).req(ServerStatisticManager.class)
- .req(MessageCodec.class, PlainTextMessageCodec.ID));
+ .req(MessageCodec.class, PlainTextMessageCodec.ID).req(MessageHandler.class));
all.add(C(MessageHandler.class, DefaultMessageHandler.class));
all.add(C(DecodeMessageTask.class));
all.add(C(MessageBucket.class, LocalMessageBucket.ID, LocalMessageBucket.class) //
.is(PER_LOOKUP) //
.req(MessageCodec.class, PlainTextMessageCodec.ID));
all.add(C(MessageBucketManager.class, LocalMessageBucketManager.ID, LocalMessageBucketManager.class) //
.req(ServerConfigManager.class, MessagePathBuilder.class, ServerStatisticManager.class));
all.add(C(Module.class, CatCoreModule.ID, CatCoreModule.class));
all.addAll(new CatCoreDatabaseConfigurator().defineComponents());
all.addAll(new CodecComponentConfigurator().defineComponents());
all.addAll(new StorageComponentConfigurator().defineComponents());
return all;
}
public static void main(String[] args) {
generatePlexusComponentsXmlFile(new ComponentsConfigurator());
}
}
| true | true | public List<Component> defineComponents() {
List<Component> all = new ArrayList<Component>();
all.add(C(DomainManager.class)//
.req(ServerConfigManager.class, ProjectDao.class, HostinfoDao.class));
all.add(C(TaskManager.class).req(TaskDao.class));
all.add(C(ServerConfigManager.class));
all.add(C(ServerStatisticManager.class));
all.add(C(MessagePathBuilder.class, DefaultMessagePathBuilder.class) //
.req(ClientConfigManager.class));
all.add(C(MessageAnalyzerManager.class, DefaultMessageAnalyzerManager.class));
all.add(C(TcpSocketReceiver.class).req(ServerConfigManager.class).req(ServerStatisticManager.class)
.req(MessageCodec.class, PlainTextMessageCodec.ID));
all.add(C(MessageHandler.class, DefaultMessageHandler.class));
all.add(C(DecodeMessageTask.class));
all.add(C(MessageBucket.class, LocalMessageBucket.ID, LocalMessageBucket.class) //
.is(PER_LOOKUP) //
.req(MessageCodec.class, PlainTextMessageCodec.ID));
all.add(C(MessageBucketManager.class, LocalMessageBucketManager.ID, LocalMessageBucketManager.class) //
.req(ServerConfigManager.class, MessagePathBuilder.class, ServerStatisticManager.class));
all.add(C(Module.class, CatCoreModule.ID, CatCoreModule.class));
all.addAll(new CatCoreDatabaseConfigurator().defineComponents());
all.addAll(new CodecComponentConfigurator().defineComponents());
all.addAll(new StorageComponentConfigurator().defineComponents());
return all;
}
| public List<Component> defineComponents() {
List<Component> all = new ArrayList<Component>();
all.add(C(DomainManager.class)//
.req(ServerConfigManager.class, ProjectDao.class, HostinfoDao.class));
all.add(C(TaskManager.class).req(TaskDao.class));
all.add(C(ServerConfigManager.class));
all.add(C(ServerStatisticManager.class));
all.add(C(MessagePathBuilder.class, DefaultMessagePathBuilder.class) //
.req(ClientConfigManager.class));
all.add(C(MessageAnalyzerManager.class, DefaultMessageAnalyzerManager.class));
all.add(C(TcpSocketReceiver.class).req(ServerConfigManager.class).req(ServerStatisticManager.class)
.req(MessageCodec.class, PlainTextMessageCodec.ID).req(MessageHandler.class));
all.add(C(MessageHandler.class, DefaultMessageHandler.class));
all.add(C(DecodeMessageTask.class));
all.add(C(MessageBucket.class, LocalMessageBucket.ID, LocalMessageBucket.class) //
.is(PER_LOOKUP) //
.req(MessageCodec.class, PlainTextMessageCodec.ID));
all.add(C(MessageBucketManager.class, LocalMessageBucketManager.ID, LocalMessageBucketManager.class) //
.req(ServerConfigManager.class, MessagePathBuilder.class, ServerStatisticManager.class));
all.add(C(Module.class, CatCoreModule.ID, CatCoreModule.class));
all.addAll(new CatCoreDatabaseConfigurator().defineComponents());
all.addAll(new CodecComponentConfigurator().defineComponents());
all.addAll(new StorageComponentConfigurator().defineComponents());
return all;
}
|
diff --git a/src/org/mozilla/javascript/Interpreter.java b/src/org/mozilla/javascript/Interpreter.java
index ffeb89c2..54c3cd9a 100644
--- a/src/org/mozilla/javascript/Interpreter.java
+++ b/src/org/mozilla/javascript/Interpreter.java
@@ -1,4736 +1,4736 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-2000
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Patrick Beard
* Norris Boyd
* Igor Bukanov
* Ethan Hugg
* Bob Jervis
* Terry Lucas
* Roger Lawrence
* Milen Nankov
* Hannes Wallnoefer
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript;
import java.io.PrintStream;
import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import org.mozilla.javascript.ScriptRuntime.NoSuchMethodShim;
import org.mozilla.javascript.debug.DebugFrame;
public class Interpreter implements Evaluator
{
// Additional interpreter-specific codes
private static final int
// Stack: ... value1 -> ... value1 value1
Icode_DUP = -1,
// Stack: ... value2 value1 -> ... value2 value1 value2 value1
Icode_DUP2 = -2,
// Stack: ... value2 value1 -> ... value1 value2
Icode_SWAP = -3,
// Stack: ... value1 -> ...
Icode_POP = -4,
// Store stack top into return register and then pop it
Icode_POP_RESULT = -5,
// To jump conditionally and pop additional stack value
Icode_IFEQ_POP = -6,
// various types of ++/--
Icode_VAR_INC_DEC = -7,
Icode_NAME_INC_DEC = -8,
Icode_PROP_INC_DEC = -9,
Icode_ELEM_INC_DEC = -10,
Icode_REF_INC_DEC = -11,
// load/save scope from/to local
Icode_SCOPE_LOAD = -12,
Icode_SCOPE_SAVE = -13,
Icode_TYPEOFNAME = -14,
// helper for function calls
Icode_NAME_AND_THIS = -15,
Icode_PROP_AND_THIS = -16,
Icode_ELEM_AND_THIS = -17,
Icode_VALUE_AND_THIS = -18,
// Create closure object for nested functions
Icode_CLOSURE_EXPR = -19,
Icode_CLOSURE_STMT = -20,
// Special calls
Icode_CALLSPECIAL = -21,
// To return undefined value
Icode_RETUNDEF = -22,
// Exception handling implementation
Icode_GOSUB = -23,
Icode_STARTSUB = -24,
Icode_RETSUB = -25,
// To indicating a line number change in icodes.
Icode_LINE = -26,
// To store shorts and ints inline
Icode_SHORTNUMBER = -27,
Icode_INTNUMBER = -28,
// To create and populate array to hold values for [] and {} literals
Icode_LITERAL_NEW = -29,
Icode_LITERAL_SET = -30,
// Array literal with skipped index like [1,,2]
Icode_SPARE_ARRAYLIT = -31,
// Load index register to prepare for the following index operation
Icode_REG_IND_C0 = -32,
Icode_REG_IND_C1 = -33,
Icode_REG_IND_C2 = -34,
Icode_REG_IND_C3 = -35,
Icode_REG_IND_C4 = -36,
Icode_REG_IND_C5 = -37,
Icode_REG_IND1 = -38,
Icode_REG_IND2 = -39,
Icode_REG_IND4 = -40,
// Load string register to prepare for the following string operation
Icode_REG_STR_C0 = -41,
Icode_REG_STR_C1 = -42,
Icode_REG_STR_C2 = -43,
Icode_REG_STR_C3 = -44,
Icode_REG_STR1 = -45,
Icode_REG_STR2 = -46,
Icode_REG_STR4 = -47,
// Version of getvar/setvar that read var index directly from bytecode
Icode_GETVAR1 = -48,
Icode_SETVAR1 = -49,
// Load unefined
Icode_UNDEF = -50,
Icode_ZERO = -51,
Icode_ONE = -52,
// entrance and exit from .()
Icode_ENTERDQ = -53,
Icode_LEAVEDQ = -54,
Icode_TAIL_CALL = -55,
// Clear local to allow GC its context
Icode_LOCAL_CLEAR = -56,
// Literal get/set
Icode_LITERAL_GETTER = -57,
Icode_LITERAL_SETTER = -58,
// const
Icode_SETCONST = -59,
Icode_SETCONSTVAR = -60,
Icode_SETCONSTVAR1 = -61,
// Generator opcodes (along with Token.YIELD)
Icode_GENERATOR = -62,
Icode_GENERATOR_END = -63,
Icode_DEBUGGER = -64,
// Last icode
MIN_ICODE = -64;
// data for parsing
private CompilerEnvirons compilerEnv;
private boolean itsInFunctionFlag;
private boolean itsInTryFlag;
private InterpreterData itsData;
private ScriptOrFnNode scriptOrFn;
private int itsICodeTop;
private int itsStackDepth;
private int itsLineNumber;
private int itsDoubleTableTop;
private ObjToIntMap itsStrings = new ObjToIntMap(20);
private int itsLocalTop;
private static final int MIN_LABEL_TABLE_SIZE = 32;
private static final int MIN_FIXUP_TABLE_SIZE = 40;
private int[] itsLabelTable;
private int itsLabelTableTop;
// itsFixupTable[i] = (label_index << 32) | fixup_site
private long[] itsFixupTable;
private int itsFixupTableTop;
private ObjArray itsLiteralIds = new ObjArray();
private int itsExceptionTableTop;
private static final int EXCEPTION_TRY_START_SLOT = 0;
private static final int EXCEPTION_TRY_END_SLOT = 1;
private static final int EXCEPTION_HANDLER_SLOT = 2;
private static final int EXCEPTION_TYPE_SLOT = 3;
private static final int EXCEPTION_LOCAL_SLOT = 4;
private static final int EXCEPTION_SCOPE_SLOT = 5;
// SLOT_SIZE: space for try start/end, handler, start, handler type,
// exception local and scope local
private static final int EXCEPTION_SLOT_SIZE = 6;
// ECF_ or Expression Context Flags constants: for now only TAIL is available
private static final int ECF_TAIL = 1 << 0;
/**
* Class to hold data corresponding to one interpreted call stack frame.
*/
private static class CallFrame implements Cloneable, Serializable
{
static final long serialVersionUID = -2843792508994958978L;
CallFrame parentFrame;
// amount of stack frames before this one on the interpretation stack
int frameIndex;
// If true indicates read-only frame that is a part of continuation
boolean frozen;
InterpretedFunction fnOrScript;
InterpreterData idata;
// Stack structure
// stack[0 <= i < localShift]: arguments and local variables
// stack[localShift <= i <= emptyStackTop]: used for local temporaries
// stack[emptyStackTop < i < stack.length]: stack data
// sDbl[i]: if stack[i] is UniqueTag.DOUBLE_MARK, sDbl[i] holds the number value
Object[] stack;
int[] stackAttributes;
double[] sDbl;
CallFrame varSource; // defaults to this unless continuation frame
int localShift;
int emptyStackTop;
DebugFrame debuggerFrame;
boolean useActivation;
boolean isContinuationsTopFrame;
Scriptable thisObj;
Scriptable[] scriptRegExps;
// The values that change during interpretation
Object result;
double resultDbl;
int pc;
int pcPrevBranch;
int pcSourceLineStart;
Scriptable scope;
int savedStackTop;
int savedCallOp;
Object throwable;
CallFrame cloneFrozen()
{
if (!frozen) Kit.codeBug();
CallFrame copy;
try {
copy = (CallFrame)clone();
} catch (CloneNotSupportedException ex) {
throw new IllegalStateException();
}
// clone stack but keep varSource to point to values
// from this frame to share variables.
copy.stack = stack.clone();
copy.stackAttributes = stackAttributes.clone();
copy.sDbl = sDbl.clone();
copy.frozen = false;
return copy;
}
}
private static final class ContinuationJump implements Serializable
{
static final long serialVersionUID = 7687739156004308247L;
CallFrame capturedFrame;
CallFrame branchFrame;
Object result;
double resultDbl;
ContinuationJump(NativeContinuation c, CallFrame current)
{
this.capturedFrame = (CallFrame)c.getImplementation();
if (this.capturedFrame == null || current == null) {
// Continuation and current execution does not share
// any frames if there is nothing to capture or
// if there is no currently executed frames
this.branchFrame = null;
} else {
// Search for branch frame where parent frame chains starting
// from captured and current meet.
CallFrame chain1 = this.capturedFrame;
CallFrame chain2 = current;
// First work parents of chain1 or chain2 until the same
// frame depth.
int diff = chain1.frameIndex - chain2.frameIndex;
if (diff != 0) {
if (diff < 0) {
// swap to make sure that
// chain1.frameIndex > chain2.frameIndex and diff > 0
chain1 = current;
chain2 = this.capturedFrame;
diff = -diff;
}
do {
chain1 = chain1.parentFrame;
} while (--diff != 0);
if (chain1.frameIndex != chain2.frameIndex) Kit.codeBug();
}
// Now walk parents in parallel until a shared frame is found
// or until the root is reached.
while (chain1 != chain2 && chain1 != null) {
chain1 = chain1.parentFrame;
chain2 = chain2.parentFrame;
}
this.branchFrame = chain1;
if (this.branchFrame != null && !this.branchFrame.frozen)
Kit.codeBug();
}
}
}
private static CallFrame captureFrameForGenerator(CallFrame frame) {
frame.frozen = true;
CallFrame result = frame.cloneFrozen();
frame.frozen = false;
// now isolate this frame from its previous context
result.parentFrame = null;
result.frameIndex = 0;
return result;
}
static {
// Checks for byte code consistencies, good compiler can eliminate them
if (Token.LAST_BYTECODE_TOKEN > 127) {
String str = "Violation of Token.LAST_BYTECODE_TOKEN <= 127";
System.err.println(str);
throw new IllegalStateException(str);
}
if (MIN_ICODE < -128) {
String str = "Violation of Interpreter.MIN_ICODE >= -128";
System.err.println(str);
throw new IllegalStateException(str);
}
}
private static String bytecodeName(int bytecode)
{
if (!validBytecode(bytecode)) {
throw new IllegalArgumentException(String.valueOf(bytecode));
}
if (!Token.printICode) {
return String.valueOf(bytecode);
}
if (validTokenCode(bytecode)) {
return Token.name(bytecode);
}
switch (bytecode) {
case Icode_DUP: return "DUP";
case Icode_DUP2: return "DUP2";
case Icode_SWAP: return "SWAP";
case Icode_POP: return "POP";
case Icode_POP_RESULT: return "POP_RESULT";
case Icode_IFEQ_POP: return "IFEQ_POP";
case Icode_VAR_INC_DEC: return "VAR_INC_DEC";
case Icode_NAME_INC_DEC: return "NAME_INC_DEC";
case Icode_PROP_INC_DEC: return "PROP_INC_DEC";
case Icode_ELEM_INC_DEC: return "ELEM_INC_DEC";
case Icode_REF_INC_DEC: return "REF_INC_DEC";
case Icode_SCOPE_LOAD: return "SCOPE_LOAD";
case Icode_SCOPE_SAVE: return "SCOPE_SAVE";
case Icode_TYPEOFNAME: return "TYPEOFNAME";
case Icode_NAME_AND_THIS: return "NAME_AND_THIS";
case Icode_PROP_AND_THIS: return "PROP_AND_THIS";
case Icode_ELEM_AND_THIS: return "ELEM_AND_THIS";
case Icode_VALUE_AND_THIS: return "VALUE_AND_THIS";
case Icode_CLOSURE_EXPR: return "CLOSURE_EXPR";
case Icode_CLOSURE_STMT: return "CLOSURE_STMT";
case Icode_CALLSPECIAL: return "CALLSPECIAL";
case Icode_RETUNDEF: return "RETUNDEF";
case Icode_GOSUB: return "GOSUB";
case Icode_STARTSUB: return "STARTSUB";
case Icode_RETSUB: return "RETSUB";
case Icode_LINE: return "LINE";
case Icode_SHORTNUMBER: return "SHORTNUMBER";
case Icode_INTNUMBER: return "INTNUMBER";
case Icode_LITERAL_NEW: return "LITERAL_NEW";
case Icode_LITERAL_SET: return "LITERAL_SET";
case Icode_SPARE_ARRAYLIT: return "SPARE_ARRAYLIT";
case Icode_REG_IND_C0: return "REG_IND_C0";
case Icode_REG_IND_C1: return "REG_IND_C1";
case Icode_REG_IND_C2: return "REG_IND_C2";
case Icode_REG_IND_C3: return "REG_IND_C3";
case Icode_REG_IND_C4: return "REG_IND_C4";
case Icode_REG_IND_C5: return "REG_IND_C5";
case Icode_REG_IND1: return "LOAD_IND1";
case Icode_REG_IND2: return "LOAD_IND2";
case Icode_REG_IND4: return "LOAD_IND4";
case Icode_REG_STR_C0: return "REG_STR_C0";
case Icode_REG_STR_C1: return "REG_STR_C1";
case Icode_REG_STR_C2: return "REG_STR_C2";
case Icode_REG_STR_C3: return "REG_STR_C3";
case Icode_REG_STR1: return "LOAD_STR1";
case Icode_REG_STR2: return "LOAD_STR2";
case Icode_REG_STR4: return "LOAD_STR4";
case Icode_GETVAR1: return "GETVAR1";
case Icode_SETVAR1: return "SETVAR1";
case Icode_UNDEF: return "UNDEF";
case Icode_ZERO: return "ZERO";
case Icode_ONE: return "ONE";
case Icode_ENTERDQ: return "ENTERDQ";
case Icode_LEAVEDQ: return "LEAVEDQ";
case Icode_TAIL_CALL: return "TAIL_CALL";
case Icode_LOCAL_CLEAR: return "LOCAL_CLEAR";
case Icode_LITERAL_GETTER: return "LITERAL_GETTER";
case Icode_LITERAL_SETTER: return "LITERAL_SETTER";
case Icode_SETCONST: return "SETCONST";
case Icode_SETCONSTVAR: return "SETCONSTVAR";
case Icode_SETCONSTVAR1: return "SETCONSTVAR1";
case Icode_GENERATOR: return "GENERATOR";
case Icode_GENERATOR_END: return "GENERATOR_END";
case Icode_DEBUGGER: return "DEBUGGER";
}
// icode without name
throw new IllegalStateException(String.valueOf(bytecode));
}
private static boolean validIcode(int icode)
{
return MIN_ICODE <= icode && icode <= -1;
}
private static boolean validTokenCode(int token)
{
return Token.FIRST_BYTECODE_TOKEN <= token
&& token <= Token.LAST_BYTECODE_TOKEN;
}
private static boolean validBytecode(int bytecode)
{
return validIcode(bytecode) || validTokenCode(bytecode);
}
public Object compile(CompilerEnvirons compilerEnv,
ScriptOrFnNode tree,
String encodedSource,
boolean returnFunction)
{
this.compilerEnv = compilerEnv;
new NodeTransformer().transform(tree);
if (Token.printTrees) {
System.out.println(tree.toStringTree(tree));
}
if (returnFunction) {
tree = tree.getFunctionNode(0);
}
scriptOrFn = tree;
itsData = new InterpreterData(compilerEnv.getLanguageVersion(),
scriptOrFn.getSourceName(),
encodedSource);
itsData.topLevel = true;
if (returnFunction) {
generateFunctionICode();
} else {
generateICodeFromTree(scriptOrFn);
}
return itsData;
}
public Script createScriptObject(Object bytecode, Object staticSecurityDomain)
{
if(bytecode != itsData)
{
Kit.codeBug();
}
return InterpretedFunction.createScript(itsData,
staticSecurityDomain);
}
public void setEvalScriptFlag(Script script) {
((InterpretedFunction)script).idata.evalScriptFlag = true;
}
public Function createFunctionObject(Context cx, Scriptable scope,
Object bytecode, Object staticSecurityDomain)
{
if(bytecode != itsData)
{
Kit.codeBug();
}
return InterpretedFunction.createFunction(cx, scope, itsData,
staticSecurityDomain);
}
private void generateFunctionICode()
{
itsInFunctionFlag = true;
FunctionNode theFunction = (FunctionNode)scriptOrFn;
itsData.itsFunctionType = theFunction.getFunctionType();
itsData.itsNeedsActivation = theFunction.requiresActivation();
itsData.itsName = theFunction.getFunctionName();
if (!theFunction.getIgnoreDynamicScope()) {
if (compilerEnv.isUseDynamicScope()) {
itsData.useDynamicScope = true;
}
}
if (theFunction.isGenerator()) {
addIcode(Icode_GENERATOR);
addUint16(theFunction.getBaseLineno() & 0xFFFF);
}
generateICodeFromTree(theFunction.getLastChild());
}
private void generateICodeFromTree(Node tree)
{
generateNestedFunctions();
generateRegExpLiterals();
visitStatement(tree, 0);
fixLabelGotos();
// add RETURN_RESULT only to scripts as function always ends with RETURN
if (itsData.itsFunctionType == 0) {
addToken(Token.RETURN_RESULT);
}
if (itsData.itsICode.length != itsICodeTop) {
// Make itsData.itsICode length exactly itsICodeTop to save memory
// and catch bugs with jumps beyond icode as early as possible
byte[] tmp = new byte[itsICodeTop];
System.arraycopy(itsData.itsICode, 0, tmp, 0, itsICodeTop);
itsData.itsICode = tmp;
}
if (itsStrings.size() == 0) {
itsData.itsStringTable = null;
} else {
itsData.itsStringTable = new String[itsStrings.size()];
ObjToIntMap.Iterator iter = itsStrings.newIterator();
for (iter.start(); !iter.done(); iter.next()) {
String str = (String)iter.getKey();
int index = iter.getValue();
if (itsData.itsStringTable[index] != null) Kit.codeBug();
itsData.itsStringTable[index] = str;
}
}
if (itsDoubleTableTop == 0) {
itsData.itsDoubleTable = null;
} else if (itsData.itsDoubleTable.length != itsDoubleTableTop) {
double[] tmp = new double[itsDoubleTableTop];
System.arraycopy(itsData.itsDoubleTable, 0, tmp, 0,
itsDoubleTableTop);
itsData.itsDoubleTable = tmp;
}
if (itsExceptionTableTop != 0
&& itsData.itsExceptionTable.length != itsExceptionTableTop)
{
int[] tmp = new int[itsExceptionTableTop];
System.arraycopy(itsData.itsExceptionTable, 0, tmp, 0,
itsExceptionTableTop);
itsData.itsExceptionTable = tmp;
}
itsData.itsMaxVars = scriptOrFn.getParamAndVarCount();
// itsMaxFrameArray: interpret method needs this amount for its
// stack and sDbl arrays
itsData.itsMaxFrameArray = itsData.itsMaxVars
+ itsData.itsMaxLocals
+ itsData.itsMaxStack;
itsData.argNames = scriptOrFn.getParamAndVarNames();
itsData.argIsConst = scriptOrFn.getParamAndVarConst();
itsData.argCount = scriptOrFn.getParamCount();
itsData.encodedSourceStart = scriptOrFn.getEncodedSourceStart();
itsData.encodedSourceEnd = scriptOrFn.getEncodedSourceEnd();
if (itsLiteralIds.size() != 0) {
itsData.literalIds = itsLiteralIds.toArray();
}
if (Token.printICode) dumpICode(itsData);
}
private void generateNestedFunctions()
{
int functionCount = scriptOrFn.getFunctionCount();
if (functionCount == 0) return;
InterpreterData[] array = new InterpreterData[functionCount];
for (int i = 0; i != functionCount; i++) {
FunctionNode def = scriptOrFn.getFunctionNode(i);
Interpreter jsi = new Interpreter();
jsi.compilerEnv = compilerEnv;
jsi.scriptOrFn = def;
jsi.itsData = new InterpreterData(itsData);
jsi.generateFunctionICode();
array[i] = jsi.itsData;
}
itsData.itsNestedFunctions = array;
}
private void generateRegExpLiterals()
{
int N = scriptOrFn.getRegexpCount();
if (N == 0) return;
Context cx = Context.getContext();
RegExpProxy rep = ScriptRuntime.checkRegExpProxy(cx);
Object[] array = new Object[N];
for (int i = 0; i != N; i++) {
String string = scriptOrFn.getRegexpString(i);
String flags = scriptOrFn.getRegexpFlags(i);
array[i] = rep.compileRegExp(cx, string, flags);
}
itsData.itsRegExpLiterals = array;
}
private void updateLineNumber(Node node)
{
int lineno = node.getLineno();
if (lineno != itsLineNumber && lineno >= 0) {
if (itsData.firstLinePC < 0) {
itsData.firstLinePC = lineno;
}
itsLineNumber = lineno;
addIcode(Icode_LINE);
addUint16(lineno & 0xFFFF);
}
}
private RuntimeException badTree(Node node)
{
throw new RuntimeException(node.toString());
}
private void visitStatement(Node node, int initialStackDepth)
{
int type = node.getType();
Node child = node.getFirstChild();
switch (type) {
case Token.FUNCTION:
{
int fnIndex = node.getExistingIntProp(Node.FUNCTION_PROP);
int fnType = scriptOrFn.getFunctionNode(fnIndex).
getFunctionType();
// Only function expressions or function expression
// statements need closure code creating new function
// object on stack as function statements are initialized
// at script/function start.
// In addition, function expressions can not be present here
// at statement level, they must only be present as expressions.
if (fnType == FunctionNode.FUNCTION_EXPRESSION_STATEMENT) {
addIndexOp(Icode_CLOSURE_STMT, fnIndex);
} else {
if (fnType != FunctionNode.FUNCTION_STATEMENT) {
throw Kit.codeBug();
}
}
// For function statements or function expression statements
// in scripts, we need to ensure that the result of the script
// is the function if it is the last statement in the script.
// For example, eval("function () {}") should return a
// function, not undefined.
if (!itsInFunctionFlag) {
addIndexOp(Icode_CLOSURE_EXPR, fnIndex);
stackChange(1);
addIcode(Icode_POP_RESULT);
stackChange(-1);
}
}
break;
case Token.LABEL:
case Token.LOOP:
case Token.BLOCK:
case Token.EMPTY:
case Token.WITH:
updateLineNumber(node);
case Token.SCRIPT:
// fall through
while (child != null) {
visitStatement(child, initialStackDepth);
child = child.getNext();
}
break;
case Token.ENTERWITH:
visitExpression(child, 0);
addToken(Token.ENTERWITH);
stackChange(-1);
break;
case Token.LEAVEWITH:
addToken(Token.LEAVEWITH);
break;
case Token.LOCAL_BLOCK:
{
int local = allocLocal();
node.putIntProp(Node.LOCAL_PROP, local);
updateLineNumber(node);
while (child != null) {
visitStatement(child, initialStackDepth);
child = child.getNext();
}
addIndexOp(Icode_LOCAL_CLEAR, local);
releaseLocal(local);
}
break;
case Token.DEBUGGER:
addIcode(Icode_DEBUGGER);
break;
case Token.SWITCH:
updateLineNumber(node);
// See comments in IRFactory.createSwitch() for description
// of SWITCH node
{
visitExpression(child, 0);
for (Node.Jump caseNode = (Node.Jump)child.getNext();
caseNode != null;
caseNode = (Node.Jump)caseNode.getNext())
{
if (caseNode.getType() != Token.CASE)
throw badTree(caseNode);
Node test = caseNode.getFirstChild();
addIcode(Icode_DUP);
stackChange(1);
visitExpression(test, 0);
addToken(Token.SHEQ);
stackChange(-1);
// If true, Icode_IFEQ_POP will jump and remove case
// value from stack
addGoto(caseNode.target, Icode_IFEQ_POP);
stackChange(-1);
}
addIcode(Icode_POP);
stackChange(-1);
}
break;
case Token.TARGET:
markTargetLabel(node);
break;
case Token.IFEQ :
case Token.IFNE :
{
Node target = ((Node.Jump)node).target;
visitExpression(child, 0);
addGoto(target, type);
stackChange(-1);
}
break;
case Token.GOTO:
{
Node target = ((Node.Jump)node).target;
addGoto(target, type);
}
break;
case Token.JSR:
{
Node target = ((Node.Jump)node).target;
addGoto(target, Icode_GOSUB);
}
break;
case Token.FINALLY:
{
// Account for incomming GOTOSUB address
stackChange(1);
int finallyRegister = getLocalBlockRef(node);
addIndexOp(Icode_STARTSUB, finallyRegister);
stackChange(-1);
while (child != null) {
visitStatement(child, initialStackDepth);
child = child.getNext();
}
addIndexOp(Icode_RETSUB, finallyRegister);
}
break;
case Token.EXPR_VOID:
case Token.EXPR_RESULT:
updateLineNumber(node);
visitExpression(child, 0);
addIcode((type == Token.EXPR_VOID) ? Icode_POP : Icode_POP_RESULT);
stackChange(-1);
break;
case Token.TRY:
{
Node.Jump tryNode = (Node.Jump)node;
int exceptionObjectLocal = getLocalBlockRef(tryNode);
int scopeLocal = allocLocal();
addIndexOp(Icode_SCOPE_SAVE, scopeLocal);
int tryStart = itsICodeTop;
boolean savedFlag = itsInTryFlag;
itsInTryFlag = true;
while (child != null) {
visitStatement(child, initialStackDepth);
child = child.getNext();
}
itsInTryFlag = savedFlag;
Node catchTarget = tryNode.target;
if (catchTarget != null) {
int catchStartPC
= itsLabelTable[getTargetLabel(catchTarget)];
addExceptionHandler(
tryStart, catchStartPC, catchStartPC,
false, exceptionObjectLocal, scopeLocal);
}
Node finallyTarget = tryNode.getFinally();
if (finallyTarget != null) {
int finallyStartPC
= itsLabelTable[getTargetLabel(finallyTarget)];
addExceptionHandler(
tryStart, finallyStartPC, finallyStartPC,
true, exceptionObjectLocal, scopeLocal);
}
addIndexOp(Icode_LOCAL_CLEAR, scopeLocal);
releaseLocal(scopeLocal);
}
break;
case Token.CATCH_SCOPE:
{
int localIndex = getLocalBlockRef(node);
int scopeIndex = node.getExistingIntProp(Node.CATCH_SCOPE_PROP);
String name = child.getString();
child = child.getNext();
visitExpression(child, 0); // load expression object
addStringPrefix(name);
addIndexPrefix(localIndex);
addToken(Token.CATCH_SCOPE);
addUint8(scopeIndex != 0 ? 1 : 0);
stackChange(-1);
}
break;
case Token.THROW:
updateLineNumber(node);
visitExpression(child, 0);
addToken(Token.THROW);
addUint16(itsLineNumber & 0xFFFF);
stackChange(-1);
break;
case Token.RETHROW:
updateLineNumber(node);
addIndexOp(Token.RETHROW, getLocalBlockRef(node));
break;
case Token.RETURN:
updateLineNumber(node);
if (node.getIntProp(Node.GENERATOR_END_PROP, 0) != 0) {
// We're in a generator, so change RETURN to GENERATOR_END
addIcode(Icode_GENERATOR_END);
addUint16(itsLineNumber & 0xFFFF);
} else if (child != null) {
visitExpression(child, ECF_TAIL);
addToken(Token.RETURN);
stackChange(-1);
} else {
addIcode(Icode_RETUNDEF);
}
break;
case Token.RETURN_RESULT:
updateLineNumber(node);
addToken(Token.RETURN_RESULT);
break;
case Token.ENUM_INIT_KEYS:
case Token.ENUM_INIT_VALUES:
case Token.ENUM_INIT_ARRAY:
visitExpression(child, 0);
addIndexOp(type, getLocalBlockRef(node));
stackChange(-1);
break;
case Icode_GENERATOR:
break;
default:
throw badTree(node);
}
if (itsStackDepth != initialStackDepth) {
throw Kit.codeBug();
}
}
private void visitExpression(Node node, int contextFlags)
{
int type = node.getType();
Node child = node.getFirstChild();
int savedStackDepth = itsStackDepth;
switch (type) {
case Token.FUNCTION:
{
int fnIndex = node.getExistingIntProp(Node.FUNCTION_PROP);
FunctionNode fn = scriptOrFn.getFunctionNode(fnIndex);
// See comments in visitStatement for Token.FUNCTION case
if (fn.getFunctionType() != FunctionNode.FUNCTION_EXPRESSION) {
throw Kit.codeBug();
}
addIndexOp(Icode_CLOSURE_EXPR, fnIndex);
stackChange(1);
}
break;
case Token.LOCAL_LOAD:
{
int localIndex = getLocalBlockRef(node);
addIndexOp(Token.LOCAL_LOAD, localIndex);
stackChange(1);
}
break;
case Token.COMMA:
{
Node lastChild = node.getLastChild();
while (child != lastChild) {
visitExpression(child, 0);
addIcode(Icode_POP);
stackChange(-1);
child = child.getNext();
}
// Preserve tail context flag if any
visitExpression(child, contextFlags & ECF_TAIL);
}
break;
case Token.USE_STACK:
// Indicates that stack was modified externally,
// like placed catch object
stackChange(1);
break;
case Token.REF_CALL:
case Token.CALL:
case Token.NEW:
{
if (type == Token.NEW) {
visitExpression(child, 0);
} else {
generateCallFunAndThis(child);
}
int argCount = 0;
while ((child = child.getNext()) != null) {
visitExpression(child, 0);
++argCount;
}
int callType = node.getIntProp(Node.SPECIALCALL_PROP,
Node.NON_SPECIALCALL);
if (callType != Node.NON_SPECIALCALL) {
// embed line number and source filename
addIndexOp(Icode_CALLSPECIAL, argCount);
addUint8(callType);
addUint8(type == Token.NEW ? 1 : 0);
addUint16(itsLineNumber & 0xFFFF);
} else {
// Only use the tail call optimization if we're not in a try
// or we're not generating debug info (since the
// optimization will confuse the debugger)
if (type == Token.CALL && (contextFlags & ECF_TAIL) != 0 &&
!compilerEnv.isGenerateDebugInfo() && !itsInTryFlag)
{
type = Icode_TAIL_CALL;
}
addIndexOp(type, argCount);
}
// adjust stack
if (type == Token.NEW) {
// new: f, args -> result
stackChange(-argCount);
} else {
// call: f, thisObj, args -> result
// ref_call: f, thisObj, args -> ref
stackChange(-1 - argCount);
}
if (argCount > itsData.itsMaxCalleeArgs) {
itsData.itsMaxCalleeArgs = argCount;
}
}
break;
case Token.AND:
case Token.OR:
{
visitExpression(child, 0);
addIcode(Icode_DUP);
stackChange(1);
int afterSecondJumpStart = itsICodeTop;
int jump = (type == Token.AND) ? Token.IFNE : Token.IFEQ;
addGotoOp(jump);
stackChange(-1);
addIcode(Icode_POP);
stackChange(-1);
child = child.getNext();
// Preserve tail context flag if any
visitExpression(child, contextFlags & ECF_TAIL);
resolveForwardGoto(afterSecondJumpStart);
}
break;
case Token.HOOK:
{
Node ifThen = child.getNext();
Node ifElse = ifThen.getNext();
visitExpression(child, 0);
int elseJumpStart = itsICodeTop;
addGotoOp(Token.IFNE);
stackChange(-1);
// Preserve tail context flag if any
visitExpression(ifThen, contextFlags & ECF_TAIL);
int afterElseJumpStart = itsICodeTop;
addGotoOp(Token.GOTO);
resolveForwardGoto(elseJumpStart);
itsStackDepth = savedStackDepth;
// Preserve tail context flag if any
visitExpression(ifElse, contextFlags & ECF_TAIL);
resolveForwardGoto(afterElseJumpStart);
}
break;
case Token.GETPROP:
case Token.GETPROPNOWARN:
visitExpression(child, 0);
child = child.getNext();
addStringOp(type, child.getString());
break;
case Token.GETELEM:
case Token.DELPROP:
case Token.BITAND:
case Token.BITOR:
case Token.BITXOR:
case Token.LSH:
case Token.RSH:
case Token.URSH:
case Token.ADD:
case Token.SUB:
case Token.MOD:
case Token.DIV:
case Token.MUL:
case Token.EQ:
case Token.NE:
case Token.SHEQ:
case Token.SHNE:
case Token.IN:
case Token.INSTANCEOF:
case Token.LE:
case Token.LT:
case Token.GE:
case Token.GT:
visitExpression(child, 0);
child = child.getNext();
visitExpression(child, 0);
addToken(type);
stackChange(-1);
break;
case Token.POS:
case Token.NEG:
case Token.NOT:
case Token.BITNOT:
case Token.TYPEOF:
case Token.VOID:
visitExpression(child, 0);
if (type == Token.VOID) {
addIcode(Icode_POP);
addIcode(Icode_UNDEF);
} else {
addToken(type);
}
break;
case Token.GET_REF:
case Token.DEL_REF:
visitExpression(child, 0);
addToken(type);
break;
case Token.SETPROP:
case Token.SETPROP_OP:
{
visitExpression(child, 0);
child = child.getNext();
String property = child.getString();
child = child.getNext();
if (type == Token.SETPROP_OP) {
addIcode(Icode_DUP);
stackChange(1);
addStringOp(Token.GETPROP, property);
// Compensate for the following USE_STACK
stackChange(-1);
}
visitExpression(child, 0);
addStringOp(Token.SETPROP, property);
stackChange(-1);
}
break;
case Token.SETELEM:
case Token.SETELEM_OP:
visitExpression(child, 0);
child = child.getNext();
visitExpression(child, 0);
child = child.getNext();
if (type == Token.SETELEM_OP) {
addIcode(Icode_DUP2);
stackChange(2);
addToken(Token.GETELEM);
stackChange(-1);
// Compensate for the following USE_STACK
stackChange(-1);
}
visitExpression(child, 0);
addToken(Token.SETELEM);
stackChange(-2);
break;
case Token.SET_REF:
case Token.SET_REF_OP:
visitExpression(child, 0);
child = child.getNext();
if (type == Token.SET_REF_OP) {
addIcode(Icode_DUP);
stackChange(1);
addToken(Token.GET_REF);
// Compensate for the following USE_STACK
stackChange(-1);
}
visitExpression(child, 0);
addToken(Token.SET_REF);
stackChange(-1);
break;
case Token.SETNAME:
{
String name = child.getString();
visitExpression(child, 0);
child = child.getNext();
visitExpression(child, 0);
addStringOp(Token.SETNAME, name);
stackChange(-1);
}
break;
case Token.SETCONST:
{
String name = child.getString();
visitExpression(child, 0);
child = child.getNext();
visitExpression(child, 0);
addStringOp(Icode_SETCONST, name);
stackChange(-1);
}
break;
case Token.TYPEOFNAME:
{
int index = -1;
// use typeofname if an activation frame exists
// since the vars all exist there instead of in jregs
if (itsInFunctionFlag && !itsData.itsNeedsActivation)
index = scriptOrFn.getIndexForNameNode(node);
if (index == -1) {
addStringOp(Icode_TYPEOFNAME, node.getString());
stackChange(1);
} else {
addVarOp(Token.GETVAR, index);
stackChange(1);
addToken(Token.TYPEOF);
}
}
break;
case Token.BINDNAME:
case Token.NAME:
case Token.STRING:
addStringOp(type, node.getString());
stackChange(1);
break;
case Token.INC:
case Token.DEC:
visitIncDec(node, child);
break;
case Token.NUMBER:
{
double num = node.getDouble();
int inum = (int)num;
if (inum == num) {
if (inum == 0) {
addIcode(Icode_ZERO);
// Check for negative zero
if (1.0 / num < 0.0) {
addToken(Token.NEG);
}
} else if (inum == 1) {
addIcode(Icode_ONE);
} else if ((short)inum == inum) {
addIcode(Icode_SHORTNUMBER);
// write short as uin16 bit pattern
addUint16(inum & 0xFFFF);
} else {
addIcode(Icode_INTNUMBER);
addInt(inum);
}
} else {
int index = getDoubleIndex(num);
addIndexOp(Token.NUMBER, index);
}
stackChange(1);
}
break;
case Token.GETVAR:
{
if (itsData.itsNeedsActivation) Kit.codeBug();
int index = scriptOrFn.getIndexForNameNode(node);
addVarOp(Token.GETVAR, index);
stackChange(1);
}
break;
case Token.SETVAR:
{
if (itsData.itsNeedsActivation) Kit.codeBug();
int index = scriptOrFn.getIndexForNameNode(child);
child = child.getNext();
visitExpression(child, 0);
addVarOp(Token.SETVAR, index);
}
break;
case Token.SETCONSTVAR:
{
if (itsData.itsNeedsActivation) Kit.codeBug();
int index = scriptOrFn.getIndexForNameNode(child);
child = child.getNext();
visitExpression(child, 0);
addVarOp(Token.SETCONSTVAR, index);
}
break;
case Token.NULL:
case Token.THIS:
case Token.THISFN:
case Token.FALSE:
case Token.TRUE:
addToken(type);
stackChange(1);
break;
case Token.ENUM_NEXT:
case Token.ENUM_ID:
addIndexOp(type, getLocalBlockRef(node));
stackChange(1);
break;
case Token.REGEXP:
{
int index = node.getExistingIntProp(Node.REGEXP_PROP);
addIndexOp(Token.REGEXP, index);
stackChange(1);
}
break;
case Token.ARRAYLIT:
case Token.OBJECTLIT:
visitLiteral(node, child);
break;
case Token.ARRAYCOMP:
visitArrayComprehension(node, child, child.getNext());
break;
case Token.REF_SPECIAL:
visitExpression(child, 0);
addStringOp(type, (String)node.getProp(Node.NAME_PROP));
break;
case Token.REF_MEMBER:
case Token.REF_NS_MEMBER:
case Token.REF_NAME:
case Token.REF_NS_NAME:
{
int memberTypeFlags = node.getIntProp(Node.MEMBER_TYPE_PROP, 0);
// generate possible target, possible namespace and member
int childCount = 0;
do {
visitExpression(child, 0);
++childCount;
child = child.getNext();
} while (child != null);
addIndexOp(type, memberTypeFlags);
stackChange(1 - childCount);
}
break;
case Token.DOTQUERY:
{
int queryPC;
updateLineNumber(node);
visitExpression(child, 0);
addIcode(Icode_ENTERDQ);
stackChange(-1);
queryPC = itsICodeTop;
visitExpression(child.getNext(), 0);
addBackwardGoto(Icode_LEAVEDQ, queryPC);
}
break;
case Token.DEFAULTNAMESPACE :
case Token.ESCXMLATTR :
case Token.ESCXMLTEXT :
visitExpression(child, 0);
addToken(type);
break;
case Token.YIELD:
if (child != null) {
visitExpression(child, 0);
} else {
addIcode(Icode_UNDEF);
stackChange(1);
}
addToken(Token.YIELD);
addUint16(node.getLineno() & 0xFFFF);
break;
case Token.WITHEXPR: {
Node enterWith = node.getFirstChild();
Node with = enterWith.getNext();
visitExpression(enterWith.getFirstChild(), 0);
addToken(Token.ENTERWITH);
stackChange(-1);
visitExpression(with.getFirstChild(), 0);
addToken(Token.LEAVEWITH);
break;
}
default:
throw badTree(node);
}
if (savedStackDepth + 1 != itsStackDepth) {
Kit.codeBug();
}
}
private void generateCallFunAndThis(Node left)
{
// Generate code to place on stack function and thisObj
int type = left.getType();
switch (type) {
case Token.NAME: {
String name = left.getString();
// stack: ... -> ... function thisObj
addStringOp(Icode_NAME_AND_THIS, name);
stackChange(2);
break;
}
case Token.GETPROP:
case Token.GETELEM: {
Node target = left.getFirstChild();
visitExpression(target, 0);
Node id = target.getNext();
if (type == Token.GETPROP) {
String property = id.getString();
// stack: ... target -> ... function thisObj
addStringOp(Icode_PROP_AND_THIS, property);
stackChange(1);
} else {
visitExpression(id, 0);
// stack: ... target id -> ... function thisObj
addIcode(Icode_ELEM_AND_THIS);
}
break;
}
default:
// Including Token.GETVAR
visitExpression(left, 0);
// stack: ... value -> ... function thisObj
addIcode(Icode_VALUE_AND_THIS);
stackChange(1);
break;
}
}
private void visitIncDec(Node node, Node child)
{
int incrDecrMask = node.getExistingIntProp(Node.INCRDECR_PROP);
int childType = child.getType();
switch (childType) {
case Token.GETVAR : {
if (itsData.itsNeedsActivation) Kit.codeBug();
int i = scriptOrFn.getIndexForNameNode(child);
addVarOp(Icode_VAR_INC_DEC, i);
addUint8(incrDecrMask);
stackChange(1);
break;
}
case Token.NAME : {
String name = child.getString();
addStringOp(Icode_NAME_INC_DEC, name);
addUint8(incrDecrMask);
stackChange(1);
break;
}
case Token.GETPROP : {
Node object = child.getFirstChild();
visitExpression(object, 0);
String property = object.getNext().getString();
addStringOp(Icode_PROP_INC_DEC, property);
addUint8(incrDecrMask);
break;
}
case Token.GETELEM : {
Node object = child.getFirstChild();
visitExpression(object, 0);
Node index = object.getNext();
visitExpression(index, 0);
addIcode(Icode_ELEM_INC_DEC);
addUint8(incrDecrMask);
stackChange(-1);
break;
}
case Token.GET_REF : {
Node ref = child.getFirstChild();
visitExpression(ref, 0);
addIcode(Icode_REF_INC_DEC);
addUint8(incrDecrMask);
break;
}
default : {
throw badTree(node);
}
}
}
private void visitLiteral(Node node, Node child)
{
int type = node.getType();
int count;
Object[] propertyIds = null;
if (type == Token.ARRAYLIT) {
count = 0;
for (Node n = child; n != null; n = n.getNext()) {
++count;
}
} else if (type == Token.OBJECTLIT) {
propertyIds = (Object[])node.getProp(Node.OBJECT_IDS_PROP);
count = propertyIds.length;
} else {
throw badTree(node);
}
addIndexOp(Icode_LITERAL_NEW, count);
stackChange(2);
while (child != null) {
int childType = child.getType();
if (childType == Token.GET) {
visitExpression(child.getFirstChild(), 0);
addIcode(Icode_LITERAL_GETTER);
} else if (childType == Token.SET) {
visitExpression(child.getFirstChild(), 0);
addIcode(Icode_LITERAL_SETTER);
} else {
visitExpression(child, 0);
addIcode(Icode_LITERAL_SET);
}
stackChange(-1);
child = child.getNext();
}
if (type == Token.ARRAYLIT) {
int[] skipIndexes = (int[])node.getProp(Node.SKIP_INDEXES_PROP);
if (skipIndexes == null) {
addToken(Token.ARRAYLIT);
} else {
int index = itsLiteralIds.size();
itsLiteralIds.add(skipIndexes);
addIndexOp(Icode_SPARE_ARRAYLIT, index);
}
} else {
int index = itsLiteralIds.size();
itsLiteralIds.add(propertyIds);
addIndexOp(Token.OBJECTLIT, index);
}
stackChange(-1);
}
private void visitArrayComprehension(Node node, Node initStmt, Node expr)
{
// A bit of a hack: array comprehensions are implemented using
// statement nodes for the iteration, yet they appear in an
// expression context. So we pass the current stack depth to
// visitStatement so it can check that the depth is not altered
// by statements.
visitStatement(initStmt, itsStackDepth);
visitExpression(expr, 0);
}
private int getLocalBlockRef(Node node)
{
Node localBlock = (Node)node.getProp(Node.LOCAL_BLOCK_PROP);
return localBlock.getExistingIntProp(Node.LOCAL_PROP);
}
private int getTargetLabel(Node target)
{
int label = target.labelId();
if (label != -1) {
return label;
}
label = itsLabelTableTop;
if (itsLabelTable == null || label == itsLabelTable.length) {
if (itsLabelTable == null) {
itsLabelTable = new int[MIN_LABEL_TABLE_SIZE];
}else {
int[] tmp = new int[itsLabelTable.length * 2];
System.arraycopy(itsLabelTable, 0, tmp, 0, label);
itsLabelTable = tmp;
}
}
itsLabelTableTop = label + 1;
itsLabelTable[label] = -1;
target.labelId(label);
return label;
}
private void markTargetLabel(Node target)
{
int label = getTargetLabel(target);
if (itsLabelTable[label] != -1) {
// Can mark label only once
Kit.codeBug();
}
itsLabelTable[label] = itsICodeTop;
}
private void addGoto(Node target, int gotoOp)
{
int label = getTargetLabel(target);
if (!(label < itsLabelTableTop)) Kit.codeBug();
int targetPC = itsLabelTable[label];
if (targetPC != -1) {
addBackwardGoto(gotoOp, targetPC);
} else {
int gotoPC = itsICodeTop;
addGotoOp(gotoOp);
int top = itsFixupTableTop;
if (itsFixupTable == null || top == itsFixupTable.length) {
if (itsFixupTable == null) {
itsFixupTable = new long[MIN_FIXUP_TABLE_SIZE];
} else {
long[] tmp = new long[itsFixupTable.length * 2];
System.arraycopy(itsFixupTable, 0, tmp, 0, top);
itsFixupTable = tmp;
}
}
itsFixupTableTop = top + 1;
itsFixupTable[top] = ((long)label << 32) | gotoPC;
}
}
private void fixLabelGotos()
{
for (int i = 0; i < itsFixupTableTop; i++) {
long fixup = itsFixupTable[i];
int label = (int)(fixup >> 32);
int jumpSource = (int)fixup;
int pc = itsLabelTable[label];
if (pc == -1) {
// Unlocated label
throw Kit.codeBug();
}
resolveGoto(jumpSource, pc);
}
itsFixupTableTop = 0;
}
private void addBackwardGoto(int gotoOp, int jumpPC)
{
int fromPC = itsICodeTop;
// Ensure that this is a jump backward
if (fromPC <= jumpPC) throw Kit.codeBug();
addGotoOp(gotoOp);
resolveGoto(fromPC, jumpPC);
}
private void resolveForwardGoto(int fromPC)
{
// Ensure that forward jump skips at least self bytecode
if (itsICodeTop < fromPC + 3) throw Kit.codeBug();
resolveGoto(fromPC, itsICodeTop);
}
private void resolveGoto(int fromPC, int jumpPC)
{
int offset = jumpPC - fromPC;
// Ensure that jumps do not overlap
if (0 <= offset && offset <= 2) throw Kit.codeBug();
int offsetSite = fromPC + 1;
if (offset != (short)offset) {
if (itsData.longJumps == null) {
itsData.longJumps = new UintMap();
}
itsData.longJumps.put(offsetSite, jumpPC);
offset = 0;
}
byte[] array = itsData.itsICode;
array[offsetSite] = (byte)(offset >> 8);
array[offsetSite + 1] = (byte)offset;
}
private void addToken(int token)
{
if (!validTokenCode(token)) throw Kit.codeBug();
addUint8(token);
}
private void addIcode(int icode)
{
if (!validIcode(icode)) throw Kit.codeBug();
// Write negative icode as uint8 bits
addUint8(icode & 0xFF);
}
private void addUint8(int value)
{
if ((value & ~0xFF) != 0) throw Kit.codeBug();
byte[] array = itsData.itsICode;
int top = itsICodeTop;
if (top == array.length) {
array = increaseICodeCapacity(1);
}
array[top] = (byte)value;
itsICodeTop = top + 1;
}
private void addUint16(int value)
{
if ((value & ~0xFFFF) != 0) throw Kit.codeBug();
byte[] array = itsData.itsICode;
int top = itsICodeTop;
if (top + 2 > array.length) {
array = increaseICodeCapacity(2);
}
array[top] = (byte)(value >>> 8);
array[top + 1] = (byte)value;
itsICodeTop = top + 2;
}
private void addInt(int i)
{
byte[] array = itsData.itsICode;
int top = itsICodeTop;
if (top + 4 > array.length) {
array = increaseICodeCapacity(4);
}
array[top] = (byte)(i >>> 24);
array[top + 1] = (byte)(i >>> 16);
array[top + 2] = (byte)(i >>> 8);
array[top + 3] = (byte)i;
itsICodeTop = top + 4;
}
private int getDoubleIndex(double num)
{
int index = itsDoubleTableTop;
if (index == 0) {
itsData.itsDoubleTable = new double[64];
} else if (itsData.itsDoubleTable.length == index) {
double[] na = new double[index * 2];
System.arraycopy(itsData.itsDoubleTable, 0, na, 0, index);
itsData.itsDoubleTable = na;
}
itsData.itsDoubleTable[index] = num;
itsDoubleTableTop = index + 1;
return index;
}
private void addGotoOp(int gotoOp)
{
byte[] array = itsData.itsICode;
int top = itsICodeTop;
if (top + 3 > array.length) {
array = increaseICodeCapacity(3);
}
array[top] = (byte)gotoOp;
// Offset would written later
itsICodeTop = top + 1 + 2;
}
private void addVarOp(int op, int varIndex)
{
switch (op) {
case Token.SETCONSTVAR:
if (varIndex < 128) {
addIcode(Icode_SETCONSTVAR1);
addUint8(varIndex);
return;
}
addIndexOp(Icode_SETCONSTVAR, varIndex);
return;
case Token.GETVAR:
case Token.SETVAR:
if (varIndex < 128) {
addIcode(op == Token.GETVAR ? Icode_GETVAR1 : Icode_SETVAR1);
addUint8(varIndex);
return;
}
// fallthrough
case Icode_VAR_INC_DEC:
addIndexOp(op, varIndex);
return;
}
throw Kit.codeBug();
}
private void addStringOp(int op, String str)
{
addStringPrefix(str);
if (validIcode(op)) {
addIcode(op);
} else {
addToken(op);
}
}
private void addIndexOp(int op, int index)
{
addIndexPrefix(index);
if (validIcode(op)) {
addIcode(op);
} else {
addToken(op);
}
}
private void addStringPrefix(String str)
{
int index = itsStrings.get(str, -1);
if (index == -1) {
index = itsStrings.size();
itsStrings.put(str, index);
}
if (index < 4) {
addIcode(Icode_REG_STR_C0 - index);
} else if (index <= 0xFF) {
addIcode(Icode_REG_STR1);
addUint8(index);
} else if (index <= 0xFFFF) {
addIcode(Icode_REG_STR2);
addUint16(index);
} else {
addIcode(Icode_REG_STR4);
addInt(index);
}
}
private void addIndexPrefix(int index)
{
if (index < 0) Kit.codeBug();
if (index < 6) {
addIcode(Icode_REG_IND_C0 - index);
} else if (index <= 0xFF) {
addIcode(Icode_REG_IND1);
addUint8(index);
} else if (index <= 0xFFFF) {
addIcode(Icode_REG_IND2);
addUint16(index);
} else {
addIcode(Icode_REG_IND4);
addInt(index);
}
}
private void addExceptionHandler(int icodeStart, int icodeEnd,
int handlerStart, boolean isFinally,
int exceptionObjectLocal, int scopeLocal)
{
int top = itsExceptionTableTop;
int[] table = itsData.itsExceptionTable;
if (table == null) {
if (top != 0) Kit.codeBug();
table = new int[EXCEPTION_SLOT_SIZE * 2];
itsData.itsExceptionTable = table;
} else if (table.length == top) {
table = new int[table.length * 2];
System.arraycopy(itsData.itsExceptionTable, 0, table, 0, top);
itsData.itsExceptionTable = table;
}
table[top + EXCEPTION_TRY_START_SLOT] = icodeStart;
table[top + EXCEPTION_TRY_END_SLOT] = icodeEnd;
table[top + EXCEPTION_HANDLER_SLOT] = handlerStart;
table[top + EXCEPTION_TYPE_SLOT] = isFinally ? 1 : 0;
table[top + EXCEPTION_LOCAL_SLOT] = exceptionObjectLocal;
table[top + EXCEPTION_SCOPE_SLOT] = scopeLocal;
itsExceptionTableTop = top + EXCEPTION_SLOT_SIZE;
}
private byte[] increaseICodeCapacity(int extraSize)
{
int capacity = itsData.itsICode.length;
int top = itsICodeTop;
if (top + extraSize <= capacity) throw Kit.codeBug();
capacity *= 2;
if (top + extraSize > capacity) {
capacity = top + extraSize;
}
byte[] array = new byte[capacity];
System.arraycopy(itsData.itsICode, 0, array, 0, top);
itsData.itsICode = array;
return array;
}
private void stackChange(int change)
{
if (change <= 0) {
itsStackDepth += change;
} else {
int newDepth = itsStackDepth + change;
if (newDepth > itsData.itsMaxStack) {
itsData.itsMaxStack = newDepth;
}
itsStackDepth = newDepth;
}
}
private int allocLocal()
{
int localSlot = itsLocalTop;
++itsLocalTop;
if (itsLocalTop > itsData.itsMaxLocals) {
itsData.itsMaxLocals = itsLocalTop;
}
return localSlot;
}
private void releaseLocal(int localSlot)
{
--itsLocalTop;
if (localSlot != itsLocalTop) Kit.codeBug();
}
private static int getShort(byte[] iCode, int pc) {
return (iCode[pc] << 8) | (iCode[pc + 1] & 0xFF);
}
private static int getIndex(byte[] iCode, int pc) {
return ((iCode[pc] & 0xFF) << 8) | (iCode[pc + 1] & 0xFF);
}
private static int getInt(byte[] iCode, int pc) {
return (iCode[pc] << 24) | ((iCode[pc + 1] & 0xFF) << 16)
| ((iCode[pc + 2] & 0xFF) << 8) | (iCode[pc + 3] & 0xFF);
}
private static int getExceptionHandler(CallFrame frame,
boolean onlyFinally)
{
int[] exceptionTable = frame.idata.itsExceptionTable;
if (exceptionTable == null) {
// No exception handlers
return -1;
}
// Icode switch in the interpreter increments PC immediately
// and it is necessary to subtract 1 from the saved PC
// to point it before the start of the next instruction.
int pc = frame.pc - 1;
// OPT: use binary search
int best = -1, bestStart = 0, bestEnd = 0;
for (int i = 0; i != exceptionTable.length; i += EXCEPTION_SLOT_SIZE) {
int start = exceptionTable[i + EXCEPTION_TRY_START_SLOT];
int end = exceptionTable[i + EXCEPTION_TRY_END_SLOT];
if (!(start <= pc && pc < end)) {
continue;
}
if (onlyFinally && exceptionTable[i + EXCEPTION_TYPE_SLOT] != 1) {
continue;
}
if (best >= 0) {
// Since handlers always nest and they never have shared end
// although they can share start it is sufficient to compare
// handlers ends
if (bestEnd < end) {
continue;
}
// Check the above assumption
if (bestStart > start) Kit.codeBug(); // should be nested
if (bestEnd == end) Kit.codeBug(); // no ens sharing
}
best = i;
bestStart = start;
bestEnd = end;
}
return best;
}
private static void dumpICode(InterpreterData idata)
{
if (!Token.printICode) {
return;
}
byte iCode[] = idata.itsICode;
int iCodeLength = iCode.length;
String[] strings = idata.itsStringTable;
PrintStream out = System.out;
out.println("ICode dump, for " + idata.itsName
+ ", length = " + iCodeLength);
out.println("MaxStack = " + idata.itsMaxStack);
int indexReg = 0;
for (int pc = 0; pc < iCodeLength; ) {
out.flush();
out.print(" [" + pc + "] ");
int token = iCode[pc];
int icodeLength = bytecodeSpan(token);
String tname = bytecodeName(token);
int old_pc = pc;
++pc;
switch (token) {
default:
if (icodeLength != 1) Kit.codeBug();
out.println(tname);
break;
case Icode_GOSUB :
case Token.GOTO :
case Token.IFEQ :
case Token.IFNE :
case Icode_IFEQ_POP :
case Icode_LEAVEDQ : {
int newPC = pc + getShort(iCode, pc) - 1;
out.println(tname + " " + newPC);
pc += 2;
break;
}
case Icode_VAR_INC_DEC :
case Icode_NAME_INC_DEC :
case Icode_PROP_INC_DEC :
case Icode_ELEM_INC_DEC :
case Icode_REF_INC_DEC: {
int incrDecrType = iCode[pc];
out.println(tname + " " + incrDecrType);
++pc;
break;
}
case Icode_CALLSPECIAL : {
int callType = iCode[pc] & 0xFF;
boolean isNew = (iCode[pc + 1] != 0);
int line = getIndex(iCode, pc+2);
out.println(tname+" "+callType+" "+isNew+" "+indexReg+" "+line);
pc += 4;
break;
}
case Token.CATCH_SCOPE:
{
boolean afterFisrtFlag = (iCode[pc] != 0);
out.println(tname+" "+afterFisrtFlag);
++pc;
}
break;
case Token.REGEXP :
out.println(tname+" "+idata.itsRegExpLiterals[indexReg]);
break;
case Token.OBJECTLIT :
case Icode_SPARE_ARRAYLIT :
out.println(tname+" "+idata.literalIds[indexReg]);
break;
case Icode_CLOSURE_EXPR :
case Icode_CLOSURE_STMT :
out.println(tname+" "+idata.itsNestedFunctions[indexReg]);
break;
case Token.CALL :
case Icode_TAIL_CALL :
case Token.REF_CALL :
case Token.NEW :
out.println(tname+' '+indexReg);
break;
case Token.THROW :
case Token.YIELD :
case Icode_GENERATOR :
case Icode_GENERATOR_END :
{
int line = getIndex(iCode, pc);
out.println(tname + " : " + line);
pc += 2;
break;
}
case Icode_SHORTNUMBER : {
int value = getShort(iCode, pc);
out.println(tname + " " + value);
pc += 2;
break;
}
case Icode_INTNUMBER : {
int value = getInt(iCode, pc);
out.println(tname + " " + value);
pc += 4;
break;
}
case Token.NUMBER : {
double value = idata.itsDoubleTable[indexReg];
out.println(tname + " " + value);
break;
}
case Icode_LINE : {
int line = getIndex(iCode, pc);
out.println(tname + " : " + line);
pc += 2;
break;
}
case Icode_REG_STR1: {
String str = strings[0xFF & iCode[pc]];
out.println(tname + " \"" + str + '"');
++pc;
break;
}
case Icode_REG_STR2: {
String str = strings[getIndex(iCode, pc)];
out.println(tname + " \"" + str + '"');
pc += 2;
break;
}
case Icode_REG_STR4: {
String str = strings[getInt(iCode, pc)];
out.println(tname + " \"" + str + '"');
pc += 4;
break;
}
case Icode_REG_IND_C0:
indexReg = 0;
out.println(tname);
break;
case Icode_REG_IND_C1:
indexReg = 1;
out.println(tname);
break;
case Icode_REG_IND_C2:
indexReg = 2;
out.println(tname);
break;
case Icode_REG_IND_C3:
indexReg = 3;
out.println(tname);
break;
case Icode_REG_IND_C4:
indexReg = 4;
out.println(tname);
break;
case Icode_REG_IND_C5:
indexReg = 5;
out.println(tname);
break;
case Icode_REG_IND1: {
indexReg = 0xFF & iCode[pc];
out.println(tname+" "+indexReg);
++pc;
break;
}
case Icode_REG_IND2: {
indexReg = getIndex(iCode, pc);
out.println(tname+" "+indexReg);
pc += 2;
break;
}
case Icode_REG_IND4: {
indexReg = getInt(iCode, pc);
out.println(tname+" "+indexReg);
pc += 4;
break;
}
case Icode_GETVAR1:
case Icode_SETVAR1:
case Icode_SETCONSTVAR1:
indexReg = iCode[pc];
out.println(tname+" "+indexReg);
++pc;
break;
}
if (old_pc + icodeLength != pc) Kit.codeBug();
}
int[] table = idata.itsExceptionTable;
if (table != null) {
out.println("Exception handlers: "
+table.length / EXCEPTION_SLOT_SIZE);
for (int i = 0; i != table.length;
i += EXCEPTION_SLOT_SIZE)
{
int tryStart = table[i + EXCEPTION_TRY_START_SLOT];
int tryEnd = table[i + EXCEPTION_TRY_END_SLOT];
int handlerStart = table[i + EXCEPTION_HANDLER_SLOT];
int type = table[i + EXCEPTION_TYPE_SLOT];
int exceptionLocal = table[i + EXCEPTION_LOCAL_SLOT];
int scopeLocal = table[i + EXCEPTION_SCOPE_SLOT];
out.println(" tryStart="+tryStart+" tryEnd="+tryEnd
+" handlerStart="+handlerStart
+" type="+(type == 0 ? "catch" : "finally")
+" exceptionLocal="+exceptionLocal);
}
}
out.flush();
}
private static int bytecodeSpan(int bytecode)
{
switch (bytecode) {
case Token.THROW :
case Token.YIELD:
case Icode_GENERATOR:
case Icode_GENERATOR_END:
// source line
return 1 + 2;
case Icode_GOSUB :
case Token.GOTO :
case Token.IFEQ :
case Token.IFNE :
case Icode_IFEQ_POP :
case Icode_LEAVEDQ :
// target pc offset
return 1 + 2;
case Icode_CALLSPECIAL :
// call type
// is new
// line number
return 1 + 1 + 1 + 2;
case Token.CATCH_SCOPE:
// scope flag
return 1 + 1;
case Icode_VAR_INC_DEC:
case Icode_NAME_INC_DEC:
case Icode_PROP_INC_DEC:
case Icode_ELEM_INC_DEC:
case Icode_REF_INC_DEC:
// type of ++/--
return 1 + 1;
case Icode_SHORTNUMBER :
// short number
return 1 + 2;
case Icode_INTNUMBER :
// int number
return 1 + 4;
case Icode_REG_IND1:
// ubyte index
return 1 + 1;
case Icode_REG_IND2:
// ushort index
return 1 + 2;
case Icode_REG_IND4:
// int index
return 1 + 4;
case Icode_REG_STR1:
// ubyte string index
return 1 + 1;
case Icode_REG_STR2:
// ushort string index
return 1 + 2;
case Icode_REG_STR4:
// int string index
return 1 + 4;
case Icode_GETVAR1:
case Icode_SETVAR1:
case Icode_SETCONSTVAR1:
// byte var index
return 1 + 1;
case Icode_LINE :
// line number
return 1 + 2;
}
if (!validBytecode(bytecode)) throw Kit.codeBug();
return 1;
}
static int[] getLineNumbers(InterpreterData data)
{
UintMap presentLines = new UintMap();
byte[] iCode = data.itsICode;
int iCodeLength = iCode.length;
for (int pc = 0; pc != iCodeLength;) {
int bytecode = iCode[pc];
int span = bytecodeSpan(bytecode);
if (bytecode == Icode_LINE) {
if (span != 3) Kit.codeBug();
int line = getIndex(iCode, pc + 1);
presentLines.put(line, 0);
}
pc += span;
}
return presentLines.getKeys();
}
public void captureStackInfo(RhinoException ex)
{
Context cx = Context.getCurrentContext();
if (cx == null || cx.lastInterpreterFrame == null) {
// No interpreter invocations
ex.interpreterStackInfo = null;
ex.interpreterLineData = null;
return;
}
// has interpreter frame on the stack
CallFrame[] array;
if (cx.previousInterpreterInvocations == null
|| cx.previousInterpreterInvocations.size() == 0)
{
array = new CallFrame[1];
} else {
int previousCount = cx.previousInterpreterInvocations.size();
if (cx.previousInterpreterInvocations.peek()
== cx.lastInterpreterFrame)
{
// It can happen if exception was generated after
// frame was pushed to cx.previousInterpreterInvocations
// but before assignment to cx.lastInterpreterFrame.
// In this case frames has to be ignored.
--previousCount;
}
array = new CallFrame[previousCount + 1];
cx.previousInterpreterInvocations.toArray(array);
}
array[array.length - 1] = (CallFrame)cx.lastInterpreterFrame;
int interpreterFrameCount = 0;
for (int i = 0; i != array.length; ++i) {
interpreterFrameCount += 1 + array[i].frameIndex;
}
int[] linePC = new int[interpreterFrameCount];
// Fill linePC with pc positions from all interpreter frames.
// Start from the most nested frame
int linePCIndex = interpreterFrameCount;
for (int i = array.length; i != 0;) {
--i;
CallFrame frame = array[i];
while (frame != null) {
--linePCIndex;
linePC[linePCIndex] = frame.pcSourceLineStart;
frame = frame.parentFrame;
}
}
if (linePCIndex != 0) Kit.codeBug();
ex.interpreterStackInfo = array;
ex.interpreterLineData = linePC;
}
public String getSourcePositionFromStack(Context cx, int[] linep)
{
CallFrame frame = (CallFrame)cx.lastInterpreterFrame;
InterpreterData idata = frame.idata;
if (frame.pcSourceLineStart >= 0) {
linep[0] = getIndex(idata.itsICode, frame.pcSourceLineStart);
} else {
linep[0] = 0;
}
return idata.itsSourceFile;
}
public String getPatchedStack(RhinoException ex,
String nativeStackTrace)
{
String tag = "org.mozilla.javascript.Interpreter.interpretLoop";
StringBuffer sb = new StringBuffer(nativeStackTrace.length() + 1000);
String lineSeparator = SecurityUtilities.getSystemProperty("line.separator");
CallFrame[] array = (CallFrame[])ex.interpreterStackInfo;
int[] linePC = ex.interpreterLineData;
int arrayIndex = array.length;
int linePCIndex = linePC.length;
int offset = 0;
while (arrayIndex != 0) {
--arrayIndex;
int pos = nativeStackTrace.indexOf(tag, offset);
if (pos < 0) {
break;
}
// Skip tag length
pos += tag.length();
// Skip until the end of line
for (; pos != nativeStackTrace.length(); ++pos) {
char c = nativeStackTrace.charAt(pos);
if (c == '\n' || c == '\r') {
break;
}
}
sb.append(nativeStackTrace.substring(offset, pos));
offset = pos;
CallFrame frame = array[arrayIndex];
while (frame != null) {
if (linePCIndex == 0) Kit.codeBug();
--linePCIndex;
InterpreterData idata = frame.idata;
sb.append(lineSeparator);
sb.append("\tat script");
if (idata.itsName != null && idata.itsName.length() != 0) {
sb.append('.');
sb.append(idata.itsName);
}
sb.append('(');
sb.append(idata.itsSourceFile);
int pc = linePC[linePCIndex];
if (pc >= 0) {
// Include line info only if available
sb.append(':');
sb.append(getIndex(idata.itsICode, pc));
}
sb.append(')');
frame = frame.parentFrame;
}
}
sb.append(nativeStackTrace.substring(offset));
return sb.toString();
}
public List<String> getScriptStack(RhinoException ex)
{
if (ex.interpreterStackInfo == null) {
return null;
}
List<String> list = new ArrayList<String>();
String lineSeparator =
SecurityUtilities.getSystemProperty("line.separator");
CallFrame[] array = (CallFrame[])ex.interpreterStackInfo;
int[] linePC = ex.interpreterLineData;
int arrayIndex = array.length;
int linePCIndex = linePC.length;
while (arrayIndex != 0) {
--arrayIndex;
StringBuilder sb = new StringBuilder();
CallFrame frame = array[arrayIndex];
while (frame != null) {
if (linePCIndex == 0) Kit.codeBug();
--linePCIndex;
InterpreterData idata = frame.idata;
sb.append("\tat ");
sb.append(idata.itsSourceFile);
int pc = linePC[linePCIndex];
if (pc >= 0) {
// Include line info only if available
sb.append(':');
sb.append(getIndex(idata.itsICode, pc));
}
if (idata.itsName != null && idata.itsName.length() != 0) {
sb.append(" (");
sb.append(idata.itsName);
sb.append(')');
}
sb.append(lineSeparator);
frame = frame.parentFrame;
}
list.add(sb.toString());
}
return list;
}
static String getEncodedSource(InterpreterData idata)
{
if (idata.encodedSource == null) {
return null;
}
return idata.encodedSource.substring(idata.encodedSourceStart,
idata.encodedSourceEnd);
}
private static void initFunction(Context cx, Scriptable scope,
InterpretedFunction parent, int index)
{
InterpretedFunction fn;
fn = InterpretedFunction.createFunction(cx, scope, parent, index);
ScriptRuntime.initFunction(cx, scope, fn, fn.idata.itsFunctionType,
parent.idata.evalScriptFlag);
}
static Object interpret(InterpretedFunction ifun,
Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
if (!ScriptRuntime.hasTopCall(cx)) Kit.codeBug();
if (cx.interpreterSecurityDomain != ifun.securityDomain) {
Object savedDomain = cx.interpreterSecurityDomain;
cx.interpreterSecurityDomain = ifun.securityDomain;
try {
return ifun.securityController.callWithDomain(
ifun.securityDomain, cx, ifun, scope, thisObj, args);
} finally {
cx.interpreterSecurityDomain = savedDomain;
}
}
CallFrame frame = new CallFrame();
initFrame(cx, scope, thisObj, args, null, 0, args.length,
ifun, null, frame);
frame.isContinuationsTopFrame = cx.isContinuationsTopCall;
cx.isContinuationsTopCall = false;
return interpretLoop(cx, frame, null);
}
static class GeneratorState {
GeneratorState(int operation, Object value) {
this.operation = operation;
this.value = value;
}
int operation;
Object value;
RuntimeException returnedException;
}
public static Object resumeGenerator(Context cx,
Scriptable scope,
int operation,
Object savedState,
Object value)
{
CallFrame frame = (CallFrame) savedState;
GeneratorState generatorState = new GeneratorState(operation, value);
if (operation == NativeGenerator.GENERATOR_CLOSE) {
try {
return interpretLoop(cx, frame, generatorState);
} catch (RuntimeException e) {
// Only propagate exceptions other than closingException
if (e != value)
throw e;
}
return Undefined.instance;
}
Object result = interpretLoop(cx, frame, generatorState);
if (generatorState.returnedException != null)
throw generatorState.returnedException;
return result;
}
public static Object restartContinuation(NativeContinuation c, Context cx,
Scriptable scope, Object[] args)
{
if (!ScriptRuntime.hasTopCall(cx)) {
return ScriptRuntime.doTopCall(c, cx, scope, null, args);
}
Object arg;
if (args.length == 0) {
arg = Undefined.instance;
} else {
arg = args[0];
}
CallFrame capturedFrame = (CallFrame)c.getImplementation();
if (capturedFrame == null) {
// No frames to restart
return arg;
}
ContinuationJump cjump = new ContinuationJump(c, null);
cjump.result = arg;
return interpretLoop(cx, null, cjump);
}
private static Object interpretLoop(Context cx, CallFrame frame,
Object throwable)
{
// throwable holds exception object to rethrow or catch
// It is also used for continuation restart in which case
// it holds ContinuationJump
final Object DBL_MRK = UniqueTag.DOUBLE_MARK;
final Object undefined = Undefined.instance;
final boolean instructionCounting = (cx.instructionThreshold != 0);
// arbitrary number to add to instructionCount when calling
// other functions
final int INVOCATION_COST = 100;
// arbitrary exception cost for instruction counting
final int EXCEPTION_COST = 100;
String stringReg = null;
int indexReg = -1;
if (cx.lastInterpreterFrame != null) {
// save the top frame from the previous interpretLoop
// invocation on the stack
if (cx.previousInterpreterInvocations == null) {
cx.previousInterpreterInvocations = new ObjArray();
}
cx.previousInterpreterInvocations.push(cx.lastInterpreterFrame);
}
// When restarting continuation throwable is not null and to jump
// to the code that rewind continuation state indexReg should be set
// to -1.
// With the normal call throwable == null and indexReg == -1 allows to
// catch bugs with using indeReg to access array elements before
// initializing indexReg.
GeneratorState generatorState = null;
if (throwable != null) {
if (throwable instanceof GeneratorState) {
generatorState = (GeneratorState) throwable;
// reestablish this call frame
enterFrame(cx, frame, ScriptRuntime.emptyArgs, true);
throwable = null;
} else if (!(throwable instanceof ContinuationJump)) {
// It should be continuation
Kit.codeBug();
}
}
Object interpreterResult = null;
double interpreterResultDbl = 0.0;
StateLoop: for (;;) {
withoutExceptions: try {
if (throwable != null) {
// Need to return both 'frame' and 'throwable' from
// 'processThrowable', so just added a 'throwable'
// member in 'frame'.
frame = processThrowable(cx, throwable, frame, indexReg,
instructionCounting);
throwable = frame.throwable;
frame.throwable = null;
} else {
if (generatorState == null && frame.frozen) Kit.codeBug();
}
// Use local variables for constant values in frame
// for faster access
Object[] stack = frame.stack;
double[] sDbl = frame.sDbl;
Object[] vars = frame.varSource.stack;
double[] varDbls = frame.varSource.sDbl;
int[] varAttributes = frame.varSource.stackAttributes;
byte[] iCode = frame.idata.itsICode;
String[] strings = frame.idata.itsStringTable;
// Use local for stackTop as well. Since execption handlers
// can only exist at statement level where stack is empty,
// it is necessary to save/restore stackTop only across
// function calls and normal returns.
int stackTop = frame.savedStackTop;
// Store new frame in cx which is used for error reporting etc.
cx.lastInterpreterFrame = frame;
Loop: for (;;) {
// Exception handler assumes that PC is already incremented
// pass the instruction start when it searches the
// exception handler
int op = iCode[frame.pc++];
jumplessRun: {
// Back indent to ease implementation reading
switch (op) {
case Icode_GENERATOR: {
if (!frame.frozen) {
// First time encountering this opcode: create new generator
// object and return
frame.pc--; // we want to come back here when we resume
CallFrame generatorFrame = captureFrameForGenerator(frame);
generatorFrame.frozen = true;
NativeGenerator generator = new NativeGenerator(frame.scope,
generatorFrame.fnOrScript, generatorFrame);
frame.result = generator;
break Loop;
} else {
// We are now resuming execution. Fall through to YIELD case.
}
}
// fall through...
case Token.YIELD: {
if (!frame.frozen) {
return freezeGenerator(cx, frame, stackTop, generatorState);
} else {
Object obj = thawGenerator(frame, stackTop, generatorState, op);
if (obj != Scriptable.NOT_FOUND) {
throwable = obj;
break withoutExceptions;
}
continue Loop;
}
}
case Icode_GENERATOR_END: {
// throw StopIteration
frame.frozen = true;
int sourceLine = getIndex(iCode, frame.pc);
generatorState.returnedException = new JavaScriptException(
NativeIterator.getStopIterationObject(frame.scope),
frame.idata.itsSourceFile, sourceLine);
break Loop;
}
case Token.THROW: {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
int sourceLine = getIndex(iCode, frame.pc);
throwable = new JavaScriptException(value,
frame.idata.itsSourceFile,
sourceLine);
break withoutExceptions;
}
case Token.RETHROW: {
indexReg += frame.localShift;
throwable = stack[indexReg];
break withoutExceptions;
}
case Token.GE :
case Token.LE :
case Token.GT :
case Token.LT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
object_compare:
{
number_compare:
{
double rDbl, lDbl;
if (rhs == DBL_MRK) {
rDbl = sDbl[stackTop + 1];
lDbl = stack_double(frame, stackTop);
} else if (lhs == DBL_MRK) {
rDbl = ScriptRuntime.toNumber(rhs);
lDbl = sDbl[stackTop];
} else {
break number_compare;
}
switch (op) {
case Token.GE:
valBln = (lDbl >= rDbl);
break object_compare;
case Token.LE:
valBln = (lDbl <= rDbl);
break object_compare;
case Token.GT:
valBln = (lDbl > rDbl);
break object_compare;
case Token.LT:
valBln = (lDbl < rDbl);
break object_compare;
default:
throw Kit.codeBug();
}
}
switch (op) {
case Token.GE:
valBln = ScriptRuntime.cmp_LE(rhs, lhs);
break;
case Token.LE:
valBln = ScriptRuntime.cmp_LE(lhs, rhs);
break;
case Token.GT:
valBln = ScriptRuntime.cmp_LT(rhs, lhs);
break;
case Token.LT:
valBln = ScriptRuntime.cmp_LT(lhs, rhs);
break;
default:
throw Kit.codeBug();
}
}
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.IN :
case Token.INSTANCEOF : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
boolean valBln;
if (op == Token.IN) {
valBln = ScriptRuntime.in(lhs, rhs, cx);
} else {
valBln = ScriptRuntime.instanceOf(lhs, rhs, cx);
}
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.EQ :
case Token.NE : {
--stackTop;
boolean valBln;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
if (rhs == DBL_MRK) {
if (lhs == DBL_MRK) {
valBln = (sDbl[stackTop] == sDbl[stackTop + 1]);
} else {
valBln = ScriptRuntime.eqNumber(sDbl[stackTop + 1], lhs);
}
} else {
if (lhs == DBL_MRK) {
valBln = ScriptRuntime.eqNumber(sDbl[stackTop], rhs);
} else {
valBln = ScriptRuntime.eq(lhs, rhs);
}
}
valBln ^= (op == Token.NE);
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.SHEQ :
case Token.SHNE : {
--stackTop;
boolean valBln = shallowEquals(stack, sDbl, stackTop);
valBln ^= (op == Token.SHNE);
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.IFNE :
if (stack_boolean(frame, stackTop--)) {
frame.pc += 2;
continue Loop;
}
break jumplessRun;
case Token.IFEQ :
if (!stack_boolean(frame, stackTop--)) {
frame.pc += 2;
continue Loop;
}
break jumplessRun;
case Icode_IFEQ_POP :
if (!stack_boolean(frame, stackTop--)) {
frame.pc += 2;
continue Loop;
}
stack[stackTop--] = null;
break jumplessRun;
case Token.GOTO :
break jumplessRun;
case Icode_GOSUB :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = frame.pc + 2;
break jumplessRun;
case Icode_STARTSUB :
if (stackTop == frame.emptyStackTop + 1) {
// Call from Icode_GOSUB: store return PC address in the local
indexReg += frame.localShift;
stack[indexReg] = stack[stackTop];
sDbl[indexReg] = sDbl[stackTop];
--stackTop;
} else {
// Call from exception handler: exception object is already stored
// in the local
if (stackTop != frame.emptyStackTop) Kit.codeBug();
}
continue Loop;
case Icode_RETSUB : {
// indexReg: local to store return address
if (instructionCounting) {
addInstructionCount(cx, frame, 0);
}
indexReg += frame.localShift;
Object value = stack[indexReg];
if (value != DBL_MRK) {
// Invocation from exception handler, restore object to rethrow
throwable = value;
break withoutExceptions;
}
// Normal return from GOSUB
frame.pc = (int)sDbl[indexReg];
if (instructionCounting) {
frame.pcPrevBranch = frame.pc;
}
continue Loop;
}
case Icode_POP :
stack[stackTop] = null;
stackTop--;
continue Loop;
case Icode_POP_RESULT :
frame.result = stack[stackTop];
frame.resultDbl = sDbl[stackTop];
stack[stackTop] = null;
--stackTop;
continue Loop;
case Icode_DUP :
stack[stackTop + 1] = stack[stackTop];
sDbl[stackTop + 1] = sDbl[stackTop];
stackTop++;
continue Loop;
case Icode_DUP2 :
stack[stackTop + 1] = stack[stackTop - 1];
sDbl[stackTop + 1] = sDbl[stackTop - 1];
stack[stackTop + 2] = stack[stackTop];
sDbl[stackTop + 2] = sDbl[stackTop];
stackTop += 2;
continue Loop;
case Icode_SWAP : {
Object o = stack[stackTop];
stack[stackTop] = stack[stackTop - 1];
stack[stackTop - 1] = o;
double d = sDbl[stackTop];
sDbl[stackTop] = sDbl[stackTop - 1];
sDbl[stackTop - 1] = d;
continue Loop;
}
case Token.RETURN :
frame.result = stack[stackTop];
frame.resultDbl = sDbl[stackTop];
--stackTop;
break Loop;
case Token.RETURN_RESULT :
break Loop;
case Icode_RETUNDEF :
frame.result = undefined;
break Loop;
case Token.BITNOT : {
int rIntValue = stack_int32(frame, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ~rIntValue;
continue Loop;
}
case Token.BITAND :
case Token.BITOR :
case Token.BITXOR :
case Token.LSH :
case Token.RSH : {
int lIntValue = stack_int32(frame, stackTop-1);
int rIntValue = stack_int32(frame, stackTop);
stack[--stackTop] = DBL_MRK;
switch (op) {
case Token.BITAND:
lIntValue &= rIntValue;
break;
case Token.BITOR:
lIntValue |= rIntValue;
break;
case Token.BITXOR:
lIntValue ^= rIntValue;
break;
case Token.LSH:
lIntValue <<= rIntValue;
break;
case Token.RSH:
lIntValue >>= rIntValue;
break;
}
sDbl[stackTop] = lIntValue;
continue Loop;
}
case Token.URSH : {
double lDbl = stack_double(frame, stackTop-1);
int rIntValue = stack_int32(frame, stackTop) & 0x1F;
stack[--stackTop] = DBL_MRK;
sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue;
continue Loop;
}
case Token.NEG :
case Token.POS : {
double rDbl = stack_double(frame, stackTop);
stack[stackTop] = DBL_MRK;
if (op == Token.NEG) {
rDbl = -rDbl;
}
sDbl[stackTop] = rDbl;
continue Loop;
}
case Token.ADD :
--stackTop;
do_add(stack, sDbl, stackTop, cx);
continue Loop;
case Token.SUB :
case Token.MUL :
case Token.DIV :
case Token.MOD : {
double rDbl = stack_double(frame, stackTop);
--stackTop;
double lDbl = stack_double(frame, stackTop);
stack[stackTop] = DBL_MRK;
switch (op) {
case Token.SUB:
lDbl -= rDbl;
break;
case Token.MUL:
lDbl *= rDbl;
break;
case Token.DIV:
lDbl /= rDbl;
break;
case Token.MOD:
lDbl %= rDbl;
break;
}
sDbl[stackTop] = lDbl;
continue Loop;
}
case Token.NOT :
stack[stackTop] = ScriptRuntime.wrapBoolean(
!stack_boolean(frame, stackTop));
continue Loop;
case Token.BINDNAME :
stack[++stackTop] = ScriptRuntime.bind(cx, frame.scope, stringReg);
continue Loop;
case Token.SETNAME : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setName(lhs, rhs, cx,
frame.scope, stringReg);
continue Loop;
}
case Icode_SETCONST: {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setConst(lhs, rhs, cx, stringReg);
continue Loop;
}
case Token.DELPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.delete(lhs, rhs, cx);
continue Loop;
}
case Token.GETPROPNOWARN : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getObjectPropNoWarn(lhs, stringReg, cx);
continue Loop;
}
case Token.GETPROP : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getObjectProp(lhs, stringReg, cx);
continue Loop;
}
case Token.SETPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setObjectProp(lhs, stringReg, rhs,
cx);
continue Loop;
}
case Icode_PROP_INC_DEC : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.propIncrDecr(lhs, stringReg,
cx, iCode[frame.pc]);
++frame.pc;
continue Loop;
}
case Token.GETELEM : {
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) {
lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
}
Object value;
Object id = stack[stackTop + 1];
if (id != DBL_MRK) {
value = ScriptRuntime.getObjectElem(lhs, id, cx);
} else {
double d = sDbl[stackTop + 1];
value = ScriptRuntime.getObjectIndex(lhs, d, cx);
}
stack[stackTop] = value;
continue Loop;
}
case Token.SETELEM : {
stackTop -= 2;
Object rhs = stack[stackTop + 2];
if (rhs == DBL_MRK) {
rhs = ScriptRuntime.wrapNumber(sDbl[stackTop + 2]);
}
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) {
lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
}
Object value;
Object id = stack[stackTop + 1];
if (id != DBL_MRK) {
value = ScriptRuntime.setObjectElem(lhs, id, rhs, cx);
} else {
double d = sDbl[stackTop + 1];
value = ScriptRuntime.setObjectIndex(lhs, d, rhs, cx);
}
stack[stackTop] = value;
continue Loop;
}
case Icode_ELEM_INC_DEC: {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.elemIncrDecr(lhs, rhs, cx,
iCode[frame.pc]);
++frame.pc;
continue Loop;
}
case Token.GET_REF : {
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refGet(ref, cx);
continue Loop;
}
case Token.SET_REF : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refSet(ref, value, cx);
continue Loop;
}
case Token.DEL_REF : {
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refDel(ref, cx);
continue Loop;
}
case Icode_REF_INC_DEC : {
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refIncrDecr(ref, cx, iCode[frame.pc]);
++frame.pc;
continue Loop;
}
case Token.LOCAL_LOAD :
++stackTop;
indexReg += frame.localShift;
stack[stackTop] = stack[indexReg];
sDbl[stackTop] = sDbl[indexReg];
continue Loop;
case Icode_LOCAL_CLEAR :
indexReg += frame.localShift;
stack[indexReg] = null;
continue Loop;
case Icode_NAME_AND_THIS :
// stringReg: name
++stackTop;
stack[stackTop] = ScriptRuntime.getNameFunctionAndThis(stringReg,
cx, frame.scope);
++stackTop;
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
case Icode_PROP_AND_THIS: {
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
// stringReg: property
stack[stackTop] = ScriptRuntime.getPropFunctionAndThis(obj, stringReg,
cx);
++stackTop;
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
}
case Icode_ELEM_AND_THIS: {
Object obj = stack[stackTop - 1];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop - 1]);
Object id = stack[stackTop];
if (id == DBL_MRK) id = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop - 1] = ScriptRuntime.getElemFunctionAndThis(obj, id, cx);
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
}
case Icode_VALUE_AND_THIS : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getValueFunctionAndThis(value, cx);
++stackTop;
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
}
case Icode_CALLSPECIAL : {
if (instructionCounting) {
cx.instructionCount += INVOCATION_COST;
}
int callType = iCode[frame.pc] & 0xFF;
boolean isNew = (iCode[frame.pc + 1] != 0);
int sourceLine = getIndex(iCode, frame.pc + 2);
// indexReg: number of arguments
if (isNew) {
// stack change: function arg0 .. argN -> newResult
stackTop -= indexReg;
Object function = stack[stackTop];
if (function == DBL_MRK)
function = ScriptRuntime.wrapNumber(sDbl[stackTop]);
Object[] outArgs = getArgsArray(
stack, sDbl, stackTop + 1, indexReg);
stack[stackTop] = ScriptRuntime.newSpecial(
cx, function, outArgs, frame.scope, callType);
} else {
// stack change: function thisObj arg0 .. argN -> result
stackTop -= 1 + indexReg;
// Call code generation ensure that stack here
// is ... Callable Scriptable
Scriptable functionThis = (Scriptable)stack[stackTop + 1];
Callable function = (Callable)stack[stackTop];
Object[] outArgs = getArgsArray(
stack, sDbl, stackTop + 2, indexReg);
stack[stackTop] = ScriptRuntime.callSpecial(
cx, function, functionThis, outArgs,
frame.scope, frame.thisObj, callType,
frame.idata.itsSourceFile, sourceLine);
}
frame.pc += 4;
continue Loop;
}
case Token.CALL :
case Icode_TAIL_CALL :
case Token.REF_CALL : {
if (instructionCounting) {
cx.instructionCount += INVOCATION_COST;
}
// stack change: function thisObj arg0 .. argN -> result
// indexReg: number of arguments
stackTop -= 1 + indexReg;
// CALL generation ensures that fun and funThisObj
// are already Scriptable and Callable objects respectively
Callable fun = (Callable)stack[stackTop];
Scriptable funThisObj = (Scriptable)stack[stackTop + 1];
if (op == Token.REF_CALL) {
Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 2,
indexReg);
stack[stackTop] = ScriptRuntime.callRef(fun, funThisObj,
outArgs, cx);
continue Loop;
}
Scriptable calleeScope = frame.scope;
if (frame.useActivation) {
calleeScope = ScriptableObject.getTopLevelScope(frame.scope);
}
if (fun instanceof InterpretedFunction) {
InterpretedFunction ifun = (InterpretedFunction)fun;
if (frame.fnOrScript.securityDomain == ifun.securityDomain) {
CallFrame callParentFrame = frame;
CallFrame calleeFrame = new CallFrame();
if (op == Icode_TAIL_CALL) {
// In principle tail call can re-use the current
// frame and its stack arrays but it is hard to
// do properly. Any exceptions that can legally
// happen during frame re-initialization including
// StackOverflowException during innocent looking
// System.arraycopy may leave the current frame
// data corrupted leading to undefined behaviour
// in the catch code bellow that unwinds JS stack
// on exceptions. Then there is issue about frame release
// end exceptions there.
// To avoid frame allocation a released frame
// can be cached for re-use which would also benefit
// non-tail calls but it is not clear that this caching
// would gain in performance due to potentially
// bad interaction with GC.
callParentFrame = frame.parentFrame;
// Release the current frame. See Bug #344501 to see why
// it is being done here.
exitFrame(cx, frame, null);
}
initFrame(cx, calleeScope, funThisObj, stack, sDbl,
stackTop + 2, indexReg, ifun, callParentFrame,
calleeFrame);
if (op != Icode_TAIL_CALL) {
frame.savedStackTop = stackTop;
frame.savedCallOp = op;
}
frame = calleeFrame;
continue StateLoop;
}
}
if (fun instanceof NativeContinuation) {
// Jump to the captured continuation
ContinuationJump cjump;
cjump = new ContinuationJump((NativeContinuation)fun, frame);
// continuation result is the first argument if any
// of continuation call
if (indexReg == 0) {
cjump.result = undefined;
} else {
cjump.result = stack[stackTop + 2];
cjump.resultDbl = sDbl[stackTop + 2];
}
// Start the real unwind job
throwable = cjump;
break withoutExceptions;
}
if (fun instanceof IdFunctionObject) {
IdFunctionObject ifun = (IdFunctionObject)fun;
if (NativeContinuation.isContinuationConstructor(ifun)) {
frame.stack[stackTop] = captureContinuation(cx,
frame.parentFrame, false);
continue Loop;
}
// Bug 405654 -- make best effort to keep Function.apply and
// Function.call within this interpreter loop invocation
if (BaseFunction.isApplyOrCall(ifun)) {
Callable applyCallable = ScriptRuntime.getCallable(funThisObj);
if (applyCallable instanceof InterpretedFunction) {
InterpretedFunction iApplyCallable = (InterpretedFunction)applyCallable;
if (frame.fnOrScript.securityDomain == iApplyCallable.securityDomain) {
frame = initFrameForApplyOrCall(cx, frame, indexReg,
stack, sDbl, stackTop, op, calleeScope, ifun,
iApplyCallable);
continue StateLoop;
}
}
}
}
// Bug 447697 -- make best effort to keep __noSuchMethod__ within this
// interpreter loop invocation
if (fun instanceof NoSuchMethodShim) {
// get the shim and the actual method
NoSuchMethodShim noSuchMethodShim = (NoSuchMethodShim) fun;
Callable noSuchMethodMethod = noSuchMethodShim.noSuchMethodMethod;
// if the method is in fact an InterpretedFunction
if (noSuchMethodMethod instanceof InterpretedFunction) {
InterpretedFunction ifun = (InterpretedFunction) noSuchMethodMethod;
if (frame.fnOrScript.securityDomain == ifun.securityDomain) {
frame = initFrameForNoSuchMethod(cx, frame, indexReg, stack, sDbl,
stackTop, op, funThisObj, calleeScope,
noSuchMethodShim, ifun);
continue StateLoop;
}
}
}
cx.lastInterpreterFrame = frame;
frame.savedCallOp = op;
frame.savedStackTop = stackTop;
stack[stackTop] = fun.call(cx, calleeScope, funThisObj,
getArgsArray(stack, sDbl, stackTop + 2, indexReg));
cx.lastInterpreterFrame = null;
continue Loop;
}
case Token.NEW : {
if (instructionCounting) {
cx.instructionCount += INVOCATION_COST;
}
// stack change: function arg0 .. argN -> newResult
// indexReg: number of arguments
stackTop -= indexReg;
Object lhs = stack[stackTop];
if (lhs instanceof InterpretedFunction) {
InterpretedFunction f = (InterpretedFunction)lhs;
if (frame.fnOrScript.securityDomain == f.securityDomain) {
Scriptable newInstance = f.createObject(cx, frame.scope);
CallFrame calleeFrame = new CallFrame();
initFrame(cx, frame.scope, newInstance, stack, sDbl,
stackTop + 1, indexReg, f, frame,
calleeFrame);
stack[stackTop] = newInstance;
frame.savedStackTop = stackTop;
frame.savedCallOp = op;
frame = calleeFrame;
continue StateLoop;
}
}
if (!(lhs instanceof Function)) {
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
throw ScriptRuntime.notFunctionError(lhs);
}
Function fun = (Function)lhs;
if (fun instanceof IdFunctionObject) {
IdFunctionObject ifun = (IdFunctionObject)fun;
if (NativeContinuation.isContinuationConstructor(ifun)) {
frame.stack[stackTop] =
captureContinuation(cx, frame.parentFrame, false);
continue Loop;
}
}
Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, indexReg);
stack[stackTop] = fun.construct(cx, frame.scope, outArgs);
continue Loop;
}
case Token.TYPEOF : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.typeof(lhs);
continue Loop;
}
case Icode_TYPEOFNAME :
stack[++stackTop] = ScriptRuntime.typeofName(frame.scope, stringReg);
continue Loop;
case Token.STRING :
stack[++stackTop] = stringReg;
continue Loop;
case Icode_SHORTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getShort(iCode, frame.pc);
frame.pc += 2;
continue Loop;
case Icode_INTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getInt(iCode, frame.pc);
frame.pc += 4;
continue Loop;
case Token.NUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = frame.idata.itsDoubleTable[indexReg];
continue Loop;
case Token.NAME :
stack[++stackTop] = ScriptRuntime.name(cx, frame.scope, stringReg);
continue Loop;
case Icode_NAME_INC_DEC :
stack[++stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, stringReg,
cx, iCode[frame.pc]);
++frame.pc;
continue Loop;
case Icode_SETCONSTVAR1:
indexReg = iCode[frame.pc++];
// fallthrough
case Token.SETCONSTVAR :
if (!frame.useActivation) {
if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) {
throw Context.reportRuntimeError1("msg.var.redecl",
frame.idata.argNames[indexReg]);
}
if ((varAttributes[indexReg] & ScriptableObject.UNINITIALIZED_CONST)
!= 0)
{
vars[indexReg] = stack[stackTop];
varAttributes[indexReg] &= ~ScriptableObject.UNINITIALIZED_CONST;
varDbls[indexReg] = sDbl[stackTop];
}
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stringReg = frame.idata.argNames[indexReg];
if (frame.scope instanceof ConstProperties) {
ConstProperties cp = (ConstProperties)frame.scope;
cp.putConst(stringReg, frame.scope, val);
} else
throw Kit.codeBug();
}
continue Loop;
case Icode_SETVAR1:
indexReg = iCode[frame.pc++];
// fallthrough
case Token.SETVAR :
if (!frame.useActivation) {
if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) {
vars[indexReg] = stack[stackTop];
varDbls[indexReg] = sDbl[stackTop];
}
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stringReg = frame.idata.argNames[indexReg];
frame.scope.put(stringReg, frame.scope, val);
}
continue Loop;
case Icode_GETVAR1:
indexReg = iCode[frame.pc++];
// fallthrough
case Token.GETVAR :
++stackTop;
if (!frame.useActivation) {
stack[stackTop] = vars[indexReg];
sDbl[stackTop] = varDbls[indexReg];
} else {
stringReg = frame.idata.argNames[indexReg];
stack[stackTop] = frame.scope.get(stringReg, frame.scope);
}
continue Loop;
case Icode_VAR_INC_DEC : {
// indexReg : varindex
++stackTop;
int incrDecrMask = iCode[frame.pc];
if (!frame.useActivation) {
stack[stackTop] = DBL_MRK;
Object varValue = vars[indexReg];
double d;
if (varValue == DBL_MRK) {
d = varDbls[indexReg];
} else {
d = ScriptRuntime.toNumber(varValue);
vars[indexReg] = DBL_MRK;
}
double d2 = ((incrDecrMask & Node.DECR_FLAG) == 0)
? d + 1.0 : d - 1.0;
varDbls[indexReg] = d2;
sDbl[stackTop] = ((incrDecrMask & Node.POST_FLAG) == 0) ? d2 : d;
} else {
String varName = frame.idata.argNames[indexReg];
stack[stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, varName,
cx, incrDecrMask);
}
++frame.pc;
continue Loop;
}
case Icode_ZERO :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 0;
continue Loop;
case Icode_ONE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 1;
continue Loop;
case Token.NULL :
stack[++stackTop] = null;
continue Loop;
case Token.THIS :
stack[++stackTop] = frame.thisObj;
continue Loop;
case Token.THISFN :
stack[++stackTop] = frame.fnOrScript;
continue Loop;
case Token.FALSE :
stack[++stackTop] = Boolean.FALSE;
continue Loop;
case Token.TRUE :
stack[++stackTop] = Boolean.TRUE;
continue Loop;
case Icode_UNDEF :
stack[++stackTop] = undefined;
continue Loop;
case Token.ENTERWITH : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
frame.scope = ScriptRuntime.enterWith(lhs, cx, frame.scope);
continue Loop;
}
case Token.LEAVEWITH :
frame.scope = ScriptRuntime.leaveWith(frame.scope);
continue Loop;
case Token.CATCH_SCOPE : {
// stack top: exception object
// stringReg: name of exception variable
// indexReg: local for exception scope
--stackTop;
indexReg += frame.localShift;
boolean afterFirstScope = (frame.idata.itsICode[frame.pc] != 0);
Throwable caughtException = (Throwable)stack[stackTop + 1];
Scriptable lastCatchScope;
if (!afterFirstScope) {
lastCatchScope = null;
} else {
lastCatchScope = (Scriptable)stack[indexReg];
}
stack[indexReg] = ScriptRuntime.newCatchScope(caughtException,
lastCatchScope, stringReg,
cx, frame.scope);
++frame.pc;
continue Loop;
}
case Token.ENUM_INIT_KEYS :
case Token.ENUM_INIT_VALUES :
case Token.ENUM_INIT_ARRAY : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
indexReg += frame.localShift;
int enumType = op == Token.ENUM_INIT_KEYS
? ScriptRuntime.ENUMERATE_KEYS :
op == Token.ENUM_INIT_VALUES
? ScriptRuntime.ENUMERATE_VALUES :
ScriptRuntime.ENUMERATE_ARRAY;
stack[indexReg] = ScriptRuntime.enumInit(lhs, cx, enumType);
continue Loop;
}
case Token.ENUM_NEXT :
case Token.ENUM_ID : {
indexReg += frame.localShift;
Object val = stack[indexReg];
++stackTop;
stack[stackTop] = (op == Token.ENUM_NEXT)
? (Object)ScriptRuntime.enumNext(val)
: (Object)ScriptRuntime.enumId(val, cx);
continue Loop;
}
case Token.REF_SPECIAL : {
//stringReg: name of special property
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.specialRef(obj, stringReg, cx);
continue Loop;
}
case Token.REF_MEMBER: {
//indexReg: flags
Object elem = stack[stackTop];
if (elem == DBL_MRK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.memberRef(obj, elem, cx, indexReg);
continue Loop;
}
case Token.REF_NS_MEMBER: {
//indexReg: flags
Object elem = stack[stackTop];
if (elem == DBL_MRK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object ns = stack[stackTop];
if (ns == DBL_MRK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.memberRef(obj, ns, elem, cx, indexReg);
continue Loop;
}
case Token.REF_NAME: {
//indexReg: flags
Object name = stack[stackTop];
if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.nameRef(name, cx, frame.scope,
indexReg);
continue Loop;
}
case Token.REF_NS_NAME: {
//indexReg: flags
Object name = stack[stackTop];
if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object ns = stack[stackTop];
if (ns == DBL_MRK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.nameRef(ns, name, cx, frame.scope,
indexReg);
continue Loop;
}
case Icode_SCOPE_LOAD :
indexReg += frame.localShift;
frame.scope = (Scriptable)stack[indexReg];
continue Loop;
case Icode_SCOPE_SAVE :
indexReg += frame.localShift;
stack[indexReg] = frame.scope;
continue Loop;
case Icode_CLOSURE_EXPR :
stack[++stackTop] = InterpretedFunction.createFunction(cx, frame.scope,
frame.fnOrScript,
indexReg);
continue Loop;
case Icode_CLOSURE_STMT :
initFunction(cx, frame.scope, frame.fnOrScript, indexReg);
continue Loop;
case Token.REGEXP :
stack[++stackTop] = frame.scriptRegExps[indexReg];
continue Loop;
case Icode_LITERAL_NEW :
// indexReg: number of values in the literal
++stackTop;
stack[stackTop] = new int[indexReg];
++stackTop;
stack[stackTop] = new Object[indexReg];
sDbl[stackTop] = 0;
continue Loop;
case Icode_LITERAL_SET : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
int i = (int)sDbl[stackTop];
((Object[])stack[stackTop])[i] = value;
sDbl[stackTop] = i + 1;
continue Loop;
}
case Icode_LITERAL_GETTER : {
Object value = stack[stackTop];
--stackTop;
int i = (int)sDbl[stackTop];
((Object[])stack[stackTop])[i] = value;
((int[])stack[stackTop - 1])[i] = -1;
sDbl[stackTop] = i + 1;
continue Loop;
}
case Icode_LITERAL_SETTER : {
Object value = stack[stackTop];
--stackTop;
int i = (int)sDbl[stackTop];
((Object[])stack[stackTop])[i] = value;
((int[])stack[stackTop - 1])[i] = +1;
sDbl[stackTop] = i + 1;
continue Loop;
}
case Token.ARRAYLIT :
case Icode_SPARE_ARRAYLIT :
case Token.OBJECTLIT : {
Object[] data = (Object[])stack[stackTop];
--stackTop;
int[] getterSetters = (int[])stack[stackTop];
Object val;
if (op == Token.OBJECTLIT) {
Object[] ids = (Object[])frame.idata.literalIds[indexReg];
val = ScriptRuntime.newObjectLiteral(ids, data, getterSetters, cx,
frame.scope);
} else {
int[] skipIndexces = null;
if (op == Icode_SPARE_ARRAYLIT) {
skipIndexces = (int[])frame.idata.literalIds[indexReg];
}
val = ScriptRuntime.newArrayLiteral(data, skipIndexces, cx,
frame.scope);
}
stack[stackTop] = val;
continue Loop;
}
case Icode_ENTERDQ : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
frame.scope = ScriptRuntime.enterDotQuery(lhs, frame.scope);
continue Loop;
}
case Icode_LEAVEDQ : {
boolean valBln = stack_boolean(frame, stackTop);
Object x = ScriptRuntime.updateDotQuery(valBln, frame.scope);
if (x != null) {
stack[stackTop] = x;
frame.scope = ScriptRuntime.leaveDotQuery(frame.scope);
frame.pc += 2;
continue Loop;
}
// reset stack and PC to code after ENTERDQ
--stackTop;
break jumplessRun;
}
case Token.DEFAULTNAMESPACE : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setDefaultNamespace(value, cx);
continue Loop;
}
case Token.ESCXMLATTR : {
Object value = stack[stackTop];
if (value != DBL_MRK) {
stack[stackTop] = ScriptRuntime.escapeAttributeValue(value, cx);
}
continue Loop;
}
case Token.ESCXMLTEXT : {
Object value = stack[stackTop];
if (value != DBL_MRK) {
stack[stackTop] = ScriptRuntime.escapeTextValue(value, cx);
}
continue Loop;
}
case Icode_DEBUGGER:
if (frame.debuggerFrame != null) {
frame.debuggerFrame.onDebuggerStatement(cx);
}
- break Loop;
+ continue Loop;
case Icode_LINE :
frame.pcSourceLineStart = frame.pc;
if (frame.debuggerFrame != null) {
int line = getIndex(iCode, frame.pc);
frame.debuggerFrame.onLineChange(cx, line);
}
frame.pc += 2;
continue Loop;
case Icode_REG_IND_C0:
indexReg = 0;
continue Loop;
case Icode_REG_IND_C1:
indexReg = 1;
continue Loop;
case Icode_REG_IND_C2:
indexReg = 2;
continue Loop;
case Icode_REG_IND_C3:
indexReg = 3;
continue Loop;
case Icode_REG_IND_C4:
indexReg = 4;
continue Loop;
case Icode_REG_IND_C5:
indexReg = 5;
continue Loop;
case Icode_REG_IND1:
indexReg = 0xFF & iCode[frame.pc];
++frame.pc;
continue Loop;
case Icode_REG_IND2:
indexReg = getIndex(iCode, frame.pc);
frame.pc += 2;
continue Loop;
case Icode_REG_IND4:
indexReg = getInt(iCode, frame.pc);
frame.pc += 4;
continue Loop;
case Icode_REG_STR_C0:
stringReg = strings[0];
continue Loop;
case Icode_REG_STR_C1:
stringReg = strings[1];
continue Loop;
case Icode_REG_STR_C2:
stringReg = strings[2];
continue Loop;
case Icode_REG_STR_C3:
stringReg = strings[3];
continue Loop;
case Icode_REG_STR1:
stringReg = strings[0xFF & iCode[frame.pc]];
++frame.pc;
continue Loop;
case Icode_REG_STR2:
stringReg = strings[getIndex(iCode, frame.pc)];
frame.pc += 2;
continue Loop;
case Icode_REG_STR4:
stringReg = strings[getInt(iCode, frame.pc)];
frame.pc += 4;
continue Loop;
default :
dumpICode(frame.idata);
throw new RuntimeException(
"Unknown icode : "+op+" @ pc : "+(frame.pc-1));
} // end of interpreter switch
} // end of jumplessRun label block
// This should be reachable only for jump implementation
// when pc points to encoded target offset
if (instructionCounting) {
addInstructionCount(cx, frame, 2);
}
int offset = getShort(iCode, frame.pc);
if (offset != 0) {
// -1 accounts for pc pointing to jump opcode + 1
frame.pc += offset - 1;
} else {
frame.pc = frame.idata.longJumps.
getExistingInt(frame.pc);
}
if (instructionCounting) {
frame.pcPrevBranch = frame.pc;
}
continue Loop;
} // end of Loop: for
exitFrame(cx, frame, null);
interpreterResult = frame.result;
interpreterResultDbl = frame.resultDbl;
if (frame.parentFrame != null) {
frame = frame.parentFrame;
if (frame.frozen) {
frame = frame.cloneFrozen();
}
setCallResult(
frame, interpreterResult, interpreterResultDbl);
interpreterResult = null; // Help GC
continue StateLoop;
}
break StateLoop;
} // end of interpreter withoutExceptions: try
catch (Throwable ex) {
if (throwable != null) {
// This is serious bug and it is better to track it ASAP
ex.printStackTrace(System.err);
throw new IllegalStateException();
}
throwable = ex;
}
// This should be reachable only after above catch or from
// finally when it needs to propagate exception or from
// explicit throw
if (throwable == null) Kit.codeBug();
// Exception type
final int EX_CATCH_STATE = 2; // Can execute JS catch
final int EX_FINALLY_STATE = 1; // Can execute JS finally
final int EX_NO_JS_STATE = 0; // Terminate JS execution
int exState;
ContinuationJump cjump = null;
if (generatorState != null &&
generatorState.operation == NativeGenerator.GENERATOR_CLOSE &&
throwable == generatorState.value)
{
exState = EX_FINALLY_STATE;
} else if (throwable instanceof JavaScriptException) {
exState = EX_CATCH_STATE;
} else if (throwable instanceof EcmaError) {
// an offical ECMA error object,
exState = EX_CATCH_STATE;
} else if (throwable instanceof EvaluatorException) {
exState = EX_CATCH_STATE;
} else if (throwable instanceof RuntimeException) {
exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
? EX_CATCH_STATE
: EX_FINALLY_STATE;
} else if (throwable instanceof Error) {
exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
? EX_CATCH_STATE
: EX_NO_JS_STATE;
} else if (throwable instanceof ContinuationJump) {
// It must be ContinuationJump
exState = EX_FINALLY_STATE;
cjump = (ContinuationJump)throwable;
} else {
exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
? EX_CATCH_STATE
: EX_FINALLY_STATE;
}
if (instructionCounting) {
try {
addInstructionCount(cx, frame, EXCEPTION_COST);
} catch (RuntimeException ex) {
throwable = ex;
exState = EX_FINALLY_STATE;
} catch (Error ex) {
// Error from instruction counting
// => unconditionally terminate JS
throwable = ex;
cjump = null;
exState = EX_NO_JS_STATE;
}
}
if (frame.debuggerFrame != null
&& throwable instanceof RuntimeException)
{
// Call debugger only for RuntimeException
RuntimeException rex = (RuntimeException)throwable;
try {
frame.debuggerFrame.onExceptionThrown(cx, rex);
} catch (Throwable ex) {
// Any exception from debugger
// => unconditionally terminate JS
throwable = ex;
cjump = null;
exState = EX_NO_JS_STATE;
}
}
for (;;) {
if (exState != EX_NO_JS_STATE) {
boolean onlyFinally = (exState != EX_CATCH_STATE);
indexReg = getExceptionHandler(frame, onlyFinally);
if (indexReg >= 0) {
// We caught an exception, restart the loop
// with exception pending the processing at the loop
// start
continue StateLoop;
}
}
// No allowed exception handlers in this frame, unwind
// to parent and try to look there
exitFrame(cx, frame, throwable);
frame = frame.parentFrame;
if (frame == null) { break; }
if (cjump != null && cjump.branchFrame == frame) {
// Continuation branch point was hit,
// restart the state loop to reenter continuation
indexReg = -1;
continue StateLoop;
}
}
// No more frames, rethrow the exception or deal with continuation
if (cjump != null) {
if (cjump.branchFrame != null) {
// The above loop should locate the top frame
Kit.codeBug();
}
if (cjump.capturedFrame != null) {
// Restarting detached continuation
indexReg = -1;
continue StateLoop;
}
// Return continuation result to the caller
interpreterResult = cjump.result;
interpreterResultDbl = cjump.resultDbl;
throwable = null;
}
break StateLoop;
} // end of StateLoop: for(;;)
// Do cleanups/restorations before the final return or throw
if (cx.previousInterpreterInvocations != null
&& cx.previousInterpreterInvocations.size() != 0)
{
cx.lastInterpreterFrame
= cx.previousInterpreterInvocations.pop();
} else {
// It was the last interpreter frame on the stack
cx.lastInterpreterFrame = null;
// Force GC of the value cx.previousInterpreterInvocations
cx.previousInterpreterInvocations = null;
}
if (throwable != null) {
if (throwable instanceof RuntimeException) {
throw (RuntimeException)throwable;
} else {
// Must be instance of Error or code bug
throw (Error)throwable;
}
}
return (interpreterResult != DBL_MRK)
? interpreterResult
: ScriptRuntime.wrapNumber(interpreterResultDbl);
}
/**
* Call __noSuchMethod__.
*/
private static CallFrame initFrameForNoSuchMethod(Context cx,
CallFrame frame, int indexReg, Object[] stack, double[] sDbl,
int stackTop, int op, Scriptable funThisObj, Scriptable calleeScope,
NoSuchMethodShim noSuchMethodShim, InterpretedFunction ifun)
{
// create an args array from the stack
Object[] argsArray = null;
// exactly like getArgsArray except that the first argument
// is the method name from the shim
int shift = stackTop + 2;
Object[] elements = new Object[indexReg];
for (int i=0; i < indexReg; ++i, ++shift) {
Object val = stack[shift];
if (val == UniqueTag.DOUBLE_MARK) {
val = ScriptRuntime.wrapNumber(sDbl[shift]);
}
elements[i] = val;
}
argsArray = new Object[2];
argsArray[0] = noSuchMethodShim.methodName;
argsArray[1] = cx.newArray(calleeScope, elements);
// exactly the same as if it's a regular InterpretedFunction
CallFrame callParentFrame = frame;
CallFrame calleeFrame = new CallFrame();
if (op == Icode_TAIL_CALL) {
callParentFrame = frame.parentFrame;
exitFrame(cx, frame, null);
}
// init the frame with the underlying method with the
// adjusted args array and shim's function
initFrame(cx, calleeScope, funThisObj, argsArray, null,
0, 2, ifun, callParentFrame, calleeFrame);
if (op != Icode_TAIL_CALL) {
frame.savedStackTop = stackTop;
frame.savedCallOp = op;
}
return calleeFrame;
}
private static boolean shallowEquals(Object[] stack, double[] sDbl,
int stackTop)
{
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
final Object DBL_MRK = UniqueTag.DOUBLE_MARK;
double rdbl, ldbl;
if (rhs == DBL_MRK) {
rdbl = sDbl[stackTop + 1];
if (lhs == DBL_MRK) {
ldbl = sDbl[stackTop];
} else if (lhs instanceof Number) {
ldbl = ((Number)lhs).doubleValue();
} else {
return false;
}
} else if (lhs == DBL_MRK) {
ldbl = sDbl[stackTop];
if (rhs == DBL_MRK) {
rdbl = sDbl[stackTop + 1];
} else if (rhs instanceof Number) {
rdbl = ((Number)rhs).doubleValue();
} else {
return false;
}
} else {
return ScriptRuntime.shallowEq(lhs, rhs);
}
return (ldbl == rdbl);
}
private static CallFrame processThrowable(Context cx, Object throwable,
CallFrame frame, int indexReg,
boolean instructionCounting)
{
// Recovering from exception, indexReg contains
// the index of handler
if (indexReg >= 0) {
// Normal exception handler, transfer
// control appropriately
if (frame.frozen) {
// XXX Deal with exceptios!!!
frame = frame.cloneFrozen();
}
int[] table = frame.idata.itsExceptionTable;
frame.pc = table[indexReg + EXCEPTION_HANDLER_SLOT];
if (instructionCounting) {
frame.pcPrevBranch = frame.pc;
}
frame.savedStackTop = frame.emptyStackTop;
int scopeLocal = frame.localShift
+ table[indexReg
+ EXCEPTION_SCOPE_SLOT];
int exLocal = frame.localShift
+ table[indexReg
+ EXCEPTION_LOCAL_SLOT];
frame.scope = (Scriptable)frame.stack[scopeLocal];
frame.stack[exLocal] = throwable;
throwable = null;
} else {
// Continuation restoration
ContinuationJump cjump = (ContinuationJump)throwable;
// Clear throwable to indicate that exceptions are OK
throwable = null;
if (cjump.branchFrame != frame) Kit.codeBug();
// Check that we have at least one frozen frame
// in the case of detached continuation restoration:
// unwind code ensure that
if (cjump.capturedFrame == null) Kit.codeBug();
// Need to rewind branchFrame, capturedFrame
// and all frames in between
int rewindCount = cjump.capturedFrame.frameIndex + 1;
if (cjump.branchFrame != null) {
rewindCount -= cjump.branchFrame.frameIndex;
}
int enterCount = 0;
CallFrame[] enterFrames = null;
CallFrame x = cjump.capturedFrame;
for (int i = 0; i != rewindCount; ++i) {
if (!x.frozen) Kit.codeBug();
if (isFrameEnterExitRequired(x)) {
if (enterFrames == null) {
// Allocate enough space to store the rest
// of rewind frames in case all of them
// would require to enter
enterFrames = new CallFrame[rewindCount
- i];
}
enterFrames[enterCount] = x;
++enterCount;
}
x = x.parentFrame;
}
while (enterCount != 0) {
// execute enter: walk enterFrames in the reverse
// order since they were stored starting from
// the capturedFrame, not branchFrame
--enterCount;
x = enterFrames[enterCount];
enterFrame(cx, x, ScriptRuntime.emptyArgs, true);
}
// Continuation jump is almost done: capturedFrame
// points to the call to the function that captured
// continuation, so clone capturedFrame and
// emulate return that function with the suplied result
frame = cjump.capturedFrame.cloneFrozen();
setCallResult(frame, cjump.result, cjump.resultDbl);
// restart the execution
}
frame.throwable = throwable;
return frame;
}
private static Object freezeGenerator(Context cx, CallFrame frame,
int stackTop,
GeneratorState generatorState)
{
if (generatorState.operation == NativeGenerator.GENERATOR_CLOSE) {
// Error: no yields when generator is closing
throw ScriptRuntime.typeError0("msg.yield.closing");
}
// return to our caller (which should be a method of NativeGenerator)
frame.frozen = true;
frame.result = frame.stack[stackTop];
frame.resultDbl = frame.sDbl[stackTop];
frame.savedStackTop = stackTop;
frame.pc--; // we want to come back here when we resume
ScriptRuntime.exitActivationFunction(cx);
return (frame.result != UniqueTag.DOUBLE_MARK)
? frame.result
: ScriptRuntime.wrapNumber(frame.resultDbl);
}
private static Object thawGenerator(CallFrame frame, int stackTop,
GeneratorState generatorState, int op)
{
// we are resuming execution
frame.frozen = false;
int sourceLine = getIndex(frame.idata.itsICode, frame.pc);
frame.pc += 2; // skip line number data
if (generatorState.operation == NativeGenerator.GENERATOR_THROW) {
// processing a call to <generator>.throw(exception): must
// act as if exception was thrown from resumption point
return new JavaScriptException(generatorState.value,
frame.idata.itsSourceFile,
sourceLine);
}
if (generatorState.operation == NativeGenerator.GENERATOR_CLOSE) {
return generatorState.value;
}
if (generatorState.operation != NativeGenerator.GENERATOR_SEND)
throw Kit.codeBug();
if (op == Token.YIELD)
frame.stack[stackTop] = generatorState.value;
return Scriptable.NOT_FOUND;
}
private static CallFrame initFrameForApplyOrCall(Context cx, CallFrame frame,
int indexReg, Object[] stack, double[] sDbl, int stackTop, int op,
Scriptable calleeScope, IdFunctionObject ifun,
InterpretedFunction iApplyCallable)
{
Scriptable applyThis;
if (indexReg != 0) {
applyThis = ScriptRuntime.toObjectOrNull(cx, stack[stackTop + 2]);
}
else {
applyThis = null;
}
if (applyThis == null) {
// This covers the case of args[0] == (null|undefined) as well.
applyThis = ScriptRuntime.getTopCallScope(cx);
}
if(op == Icode_TAIL_CALL) {
exitFrame(cx, frame, null);
frame = frame.parentFrame;
}
else {
frame.savedStackTop = stackTop;
frame.savedCallOp = op;
}
CallFrame calleeFrame = new CallFrame();
if(BaseFunction.isApply(ifun)) {
Object[] callArgs = indexReg < 2 ? ScriptRuntime.emptyArgs :
ScriptRuntime.getApplyArguments(cx, stack[stackTop + 3]);
initFrame(cx, calleeScope, applyThis, callArgs, null, 0,
callArgs.length, iApplyCallable, frame, calleeFrame);
}
else {
// Shift args left
for(int i = 1; i < indexReg; ++i) {
stack[stackTop + 1 + i] = stack[stackTop + 2 + i];
sDbl[stackTop + 1 + i] = sDbl[stackTop + 2 + i];
}
int argCount = indexReg < 2 ? 0 : indexReg - 1;
initFrame(cx, calleeScope, applyThis, stack, sDbl, stackTop + 2,
argCount, iApplyCallable, frame, calleeFrame);
}
frame = calleeFrame;
return frame;
}
private static void initFrame(Context cx, Scriptable callerScope,
Scriptable thisObj,
Object[] args, double[] argsDbl,
int argShift, int argCount,
InterpretedFunction fnOrScript,
CallFrame parentFrame, CallFrame frame)
{
InterpreterData idata = fnOrScript.idata;
boolean useActivation = idata.itsNeedsActivation;
DebugFrame debuggerFrame = null;
if (cx.debugger != null) {
debuggerFrame = cx.debugger.getFrame(cx, idata);
if (debuggerFrame != null) {
useActivation = true;
}
}
if (useActivation) {
// Copy args to new array to pass to enterActivationFunction
// or debuggerFrame.onEnter
if (argsDbl != null) {
args = getArgsArray(args, argsDbl, argShift, argCount);
}
argShift = 0;
argsDbl = null;
}
Scriptable scope;
if (idata.itsFunctionType != 0) {
if (!idata.useDynamicScope) {
scope = fnOrScript.getParentScope();
} else {
scope = callerScope;
}
if (useActivation) {
scope = ScriptRuntime.createFunctionActivation(
fnOrScript, scope, args);
}
} else {
scope = callerScope;
ScriptRuntime.initScript(fnOrScript, thisObj, cx, scope,
fnOrScript.idata.evalScriptFlag);
}
if (idata.itsNestedFunctions != null) {
if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation)
Kit.codeBug();
for (int i = 0; i < idata.itsNestedFunctions.length; i++) {
InterpreterData fdata = idata.itsNestedFunctions[i];
if (fdata.itsFunctionType == FunctionNode.FUNCTION_STATEMENT) {
initFunction(cx, scope, fnOrScript, i);
}
}
}
Scriptable[] scriptRegExps = null;
if (idata.itsRegExpLiterals != null) {
// Wrapped regexps for functions are stored in
// InterpretedFunction
// but for script which should not contain references to scope
// the regexps re-wrapped during each script execution
if (idata.itsFunctionType != 0) {
scriptRegExps = fnOrScript.functionRegExps;
} else {
scriptRegExps = fnOrScript.createRegExpWraps(cx, scope);
}
}
// Initialize args, vars, locals and stack
int emptyStackTop = idata.itsMaxVars + idata.itsMaxLocals - 1;
int maxFrameArray = idata.itsMaxFrameArray;
if (maxFrameArray != emptyStackTop + idata.itsMaxStack + 1)
Kit.codeBug();
Object[] stack;
int[] stackAttributes;
double[] sDbl;
boolean stackReuse;
if (frame.stack != null && maxFrameArray <= frame.stack.length) {
// Reuse stacks from old frame
stackReuse = true;
stack = frame.stack;
stackAttributes = frame.stackAttributes;
sDbl = frame.sDbl;
} else {
stackReuse = false;
stack = new Object[maxFrameArray];
stackAttributes = new int[maxFrameArray];
sDbl = new double[maxFrameArray];
}
int varCount = idata.getParamAndVarCount();
for (int i = 0; i < varCount; i++) {
if (idata.getParamOrVarConst(i))
stackAttributes[i] = ScriptableObject.CONST;
}
int definedArgs = idata.argCount;
if (definedArgs > argCount) { definedArgs = argCount; }
// Fill the frame structure
frame.parentFrame = parentFrame;
frame.frameIndex = (parentFrame == null)
? 0 : parentFrame.frameIndex + 1;
if(frame.frameIndex > cx.getMaximumInterpreterStackDepth())
{
throw Context.reportRuntimeError("Exceeded maximum stack depth");
}
frame.frozen = false;
frame.fnOrScript = fnOrScript;
frame.idata = idata;
frame.stack = stack;
frame.stackAttributes = stackAttributes;
frame.sDbl = sDbl;
frame.varSource = frame;
frame.localShift = idata.itsMaxVars;
frame.emptyStackTop = emptyStackTop;
frame.debuggerFrame = debuggerFrame;
frame.useActivation = useActivation;
frame.thisObj = thisObj;
frame.scriptRegExps = scriptRegExps;
// Initialize initial values of variables that change during
// interpretation.
frame.result = Undefined.instance;
frame.pc = 0;
frame.pcPrevBranch = 0;
frame.pcSourceLineStart = idata.firstLinePC;
frame.scope = scope;
frame.savedStackTop = emptyStackTop;
frame.savedCallOp = 0;
System.arraycopy(args, argShift, stack, 0, definedArgs);
if (argsDbl != null) {
System.arraycopy(argsDbl, argShift, sDbl, 0, definedArgs);
}
for (int i = definedArgs; i != idata.itsMaxVars; ++i) {
stack[i] = Undefined.instance;
}
if (stackReuse) {
// Clean the stack part and space beyond stack if any
// of the old array to allow to GC objects there
for (int i = emptyStackTop + 1; i != stack.length; ++i) {
stack[i] = null;
}
}
enterFrame(cx, frame, args, false);
}
private static boolean isFrameEnterExitRequired(CallFrame frame)
{
return frame.debuggerFrame != null || frame.idata.itsNeedsActivation;
}
private static void enterFrame(Context cx, CallFrame frame, Object[] args,
boolean continuationRestart)
{
boolean usesActivation = frame.idata.itsNeedsActivation;
boolean isDebugged = frame.debuggerFrame != null;
if(usesActivation || isDebugged) {
Scriptable scope = frame.scope;
if(scope == null) {
Kit.codeBug();
} else if (continuationRestart) {
// Walk the parent chain of frame.scope until a NativeCall is
// found. Normally, frame.scope is a NativeCall when called
// from initFrame() for a debugged or activatable function.
// However, when called from interpretLoop() as part of
// restarting a continuation, it can also be a NativeWith if
// the continuation was captured within a "with" or "catch"
// block ("catch" implicitly uses NativeWith to create a scope
// to expose the exception variable).
for(;;) {
if(scope instanceof NativeWith) {
scope = scope.getParentScope();
if (scope == null || (frame.parentFrame != null &&
frame.parentFrame.scope == scope))
{
// If we get here, we didn't find a NativeCall in
// the call chain before reaching parent frame's
// scope. This should not be possible.
Kit.codeBug();
break; // Never reached, but keeps the static analyzer happy about "scope" not being null 5 lines above.
}
}
else {
break;
}
}
}
if (isDebugged) {
frame.debuggerFrame.onEnter(cx, scope, frame.thisObj, args);
}
// Enter activation only when itsNeedsActivation true,
// since debugger should not interfere with activation
// chaining
if (usesActivation) {
ScriptRuntime.enterActivationFunction(cx, scope);
}
}
}
private static void exitFrame(Context cx, CallFrame frame,
Object throwable)
{
if (frame.idata.itsNeedsActivation) {
ScriptRuntime.exitActivationFunction(cx);
}
if (frame.debuggerFrame != null) {
try {
if (throwable instanceof Throwable) {
frame.debuggerFrame.onExit(cx, true, throwable);
} else {
Object result;
ContinuationJump cjump = (ContinuationJump)throwable;
if (cjump == null) {
result = frame.result;
} else {
result = cjump.result;
}
if (result == UniqueTag.DOUBLE_MARK) {
double resultDbl;
if (cjump == null) {
resultDbl = frame.resultDbl;
} else {
resultDbl = cjump.resultDbl;
}
result = ScriptRuntime.wrapNumber(resultDbl);
}
frame.debuggerFrame.onExit(cx, false, result);
}
} catch (Throwable ex) {
System.err.println(
"RHINO USAGE WARNING: onExit terminated with exception");
ex.printStackTrace(System.err);
}
}
}
private static void setCallResult(CallFrame frame,
Object callResult,
double callResultDbl)
{
if (frame.savedCallOp == Token.CALL) {
frame.stack[frame.savedStackTop] = callResult;
frame.sDbl[frame.savedStackTop] = callResultDbl;
} else if (frame.savedCallOp == Token.NEW) {
// If construct returns scriptable,
// then it replaces on stack top saved original instance
// of the object.
if (callResult instanceof Scriptable) {
frame.stack[frame.savedStackTop] = callResult;
}
} else {
Kit.codeBug();
}
frame.savedCallOp = 0;
}
public static NativeContinuation captureContinuation(Context cx) {
if (cx.lastInterpreterFrame == null ||
!(cx.lastInterpreterFrame instanceof CallFrame))
{
throw new IllegalStateException("Interpreter frames not found");
}
return captureContinuation(cx, (CallFrame)cx.lastInterpreterFrame, true);
}
private static NativeContinuation captureContinuation(Context cx, CallFrame frame,
boolean requireContinuationsTopFrame)
{
NativeContinuation c = new NativeContinuation();
ScriptRuntime.setObjectProtoAndParent(
c, ScriptRuntime.getTopCallScope(cx));
// Make sure that all frames are frozen
CallFrame x = frame;
CallFrame outermost = frame;
while (x != null && !x.frozen) {
x.frozen = true;
// Allow to GC unused stack space
for (int i = x.savedStackTop + 1; i != x.stack.length; ++i) {
// Allow to GC unused stack space
x.stack[i] = null;
x.stackAttributes[i] = ScriptableObject.EMPTY;
}
if (x.savedCallOp == Token.CALL) {
// the call will always overwrite the stack top with the result
x.stack[x.savedStackTop] = null;
} else {
if (x.savedCallOp != Token.NEW) Kit.codeBug();
// the new operator uses stack top to store the constructed
// object so it shall not be cleared: see comments in
// setCallResult
}
outermost = x;
x = x.parentFrame;
}
while (outermost.parentFrame != null)
outermost = outermost.parentFrame;
if (requireContinuationsTopFrame && !outermost.isContinuationsTopFrame)
{
throw new IllegalStateException("Cannot capture continuation " +
"from JavaScript code not called directly by " +
"executeScriptWithContinuations or " +
"callFunctionWithContinuations");
}
c.initImplementation(frame);
return c;
}
private static int stack_int32(CallFrame frame, int i)
{
Object x = frame.stack[i];
double value;
if (x == UniqueTag.DOUBLE_MARK) {
value = frame.sDbl[i];
} else {
value = ScriptRuntime.toNumber(x);
}
return ScriptRuntime.toInt32(value);
}
private static double stack_double(CallFrame frame, int i)
{
Object x = frame.stack[i];
if (x != UniqueTag.DOUBLE_MARK) {
return ScriptRuntime.toNumber(x);
} else {
return frame.sDbl[i];
}
}
private static boolean stack_boolean(CallFrame frame, int i)
{
Object x = frame.stack[i];
if (x == Boolean.TRUE) {
return true;
} else if (x == Boolean.FALSE) {
return false;
} else if (x == UniqueTag.DOUBLE_MARK) {
double d = frame.sDbl[i];
return d == d && d != 0.0;
} else if (x == null || x == Undefined.instance) {
return false;
} else if (x instanceof Number) {
double d = ((Number)x).doubleValue();
return (d == d && d != 0.0);
} else if (x instanceof Boolean) {
return ((Boolean)x).booleanValue();
} else {
return ScriptRuntime.toBoolean(x);
}
}
private static void do_add(Object[] stack, double[] sDbl, int stackTop,
Context cx)
{
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
double d;
boolean leftRightOrder;
if (rhs == UniqueTag.DOUBLE_MARK) {
d = sDbl[stackTop + 1];
if (lhs == UniqueTag.DOUBLE_MARK) {
sDbl[stackTop] += d;
return;
}
leftRightOrder = true;
// fallthrough to object + number code
} else if (lhs == UniqueTag.DOUBLE_MARK) {
d = sDbl[stackTop];
lhs = rhs;
leftRightOrder = false;
// fallthrough to object + number code
} else {
if (lhs instanceof Scriptable || rhs instanceof Scriptable) {
stack[stackTop] = ScriptRuntime.add(lhs, rhs, cx);
} else if (lhs instanceof String) {
String lstr = (String)lhs;
String rstr = ScriptRuntime.toString(rhs);
stack[stackTop] = lstr.concat(rstr);
} else if (rhs instanceof String) {
String lstr = ScriptRuntime.toString(lhs);
String rstr = (String)rhs;
stack[stackTop] = lstr.concat(rstr);
} else {
double lDbl = (lhs instanceof Number)
? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs);
double rDbl = (rhs instanceof Number)
? ((Number)rhs).doubleValue() : ScriptRuntime.toNumber(rhs);
stack[stackTop] = UniqueTag.DOUBLE_MARK;
sDbl[stackTop] = lDbl + rDbl;
}
return;
}
// handle object(lhs) + number(d) code
if (lhs instanceof Scriptable) {
rhs = ScriptRuntime.wrapNumber(d);
if (!leftRightOrder) {
Object tmp = lhs;
lhs = rhs;
rhs = tmp;
}
stack[stackTop] = ScriptRuntime.add(lhs, rhs, cx);
} else if (lhs instanceof String) {
String lstr = (String)lhs;
String rstr = ScriptRuntime.toString(d);
if (leftRightOrder) {
stack[stackTop] = lstr.concat(rstr);
} else {
stack[stackTop] = rstr.concat(lstr);
}
} else {
double lDbl = (lhs instanceof Number)
? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs);
stack[stackTop] = UniqueTag.DOUBLE_MARK;
sDbl[stackTop] = lDbl + d;
}
}
private static Object[] getArgsArray(Object[] stack, double[] sDbl,
int shift, int count)
{
if (count == 0) {
return ScriptRuntime.emptyArgs;
}
Object[] args = new Object[count];
for (int i = 0; i != count; ++i, ++shift) {
Object val = stack[shift];
if (val == UniqueTag.DOUBLE_MARK) {
val = ScriptRuntime.wrapNumber(sDbl[shift]);
}
args[i] = val;
}
return args;
}
private static void addInstructionCount(Context cx, CallFrame frame,
int extra)
{
cx.instructionCount += frame.pc - frame.pcPrevBranch + extra;
if (cx.instructionCount > cx.instructionThreshold) {
cx.observeInstructionCount(cx.instructionCount);
cx.instructionCount = 0;
}
}
}
| true | true | private static Object interpretLoop(Context cx, CallFrame frame,
Object throwable)
{
// throwable holds exception object to rethrow or catch
// It is also used for continuation restart in which case
// it holds ContinuationJump
final Object DBL_MRK = UniqueTag.DOUBLE_MARK;
final Object undefined = Undefined.instance;
final boolean instructionCounting = (cx.instructionThreshold != 0);
// arbitrary number to add to instructionCount when calling
// other functions
final int INVOCATION_COST = 100;
// arbitrary exception cost for instruction counting
final int EXCEPTION_COST = 100;
String stringReg = null;
int indexReg = -1;
if (cx.lastInterpreterFrame != null) {
// save the top frame from the previous interpretLoop
// invocation on the stack
if (cx.previousInterpreterInvocations == null) {
cx.previousInterpreterInvocations = new ObjArray();
}
cx.previousInterpreterInvocations.push(cx.lastInterpreterFrame);
}
// When restarting continuation throwable is not null and to jump
// to the code that rewind continuation state indexReg should be set
// to -1.
// With the normal call throwable == null and indexReg == -1 allows to
// catch bugs with using indeReg to access array elements before
// initializing indexReg.
GeneratorState generatorState = null;
if (throwable != null) {
if (throwable instanceof GeneratorState) {
generatorState = (GeneratorState) throwable;
// reestablish this call frame
enterFrame(cx, frame, ScriptRuntime.emptyArgs, true);
throwable = null;
} else if (!(throwable instanceof ContinuationJump)) {
// It should be continuation
Kit.codeBug();
}
}
Object interpreterResult = null;
double interpreterResultDbl = 0.0;
StateLoop: for (;;) {
withoutExceptions: try {
if (throwable != null) {
// Need to return both 'frame' and 'throwable' from
// 'processThrowable', so just added a 'throwable'
// member in 'frame'.
frame = processThrowable(cx, throwable, frame, indexReg,
instructionCounting);
throwable = frame.throwable;
frame.throwable = null;
} else {
if (generatorState == null && frame.frozen) Kit.codeBug();
}
// Use local variables for constant values in frame
// for faster access
Object[] stack = frame.stack;
double[] sDbl = frame.sDbl;
Object[] vars = frame.varSource.stack;
double[] varDbls = frame.varSource.sDbl;
int[] varAttributes = frame.varSource.stackAttributes;
byte[] iCode = frame.idata.itsICode;
String[] strings = frame.idata.itsStringTable;
// Use local for stackTop as well. Since execption handlers
// can only exist at statement level where stack is empty,
// it is necessary to save/restore stackTop only across
// function calls and normal returns.
int stackTop = frame.savedStackTop;
// Store new frame in cx which is used for error reporting etc.
cx.lastInterpreterFrame = frame;
Loop: for (;;) {
// Exception handler assumes that PC is already incremented
// pass the instruction start when it searches the
// exception handler
int op = iCode[frame.pc++];
jumplessRun: {
// Back indent to ease implementation reading
switch (op) {
case Icode_GENERATOR: {
if (!frame.frozen) {
// First time encountering this opcode: create new generator
// object and return
frame.pc--; // we want to come back here when we resume
CallFrame generatorFrame = captureFrameForGenerator(frame);
generatorFrame.frozen = true;
NativeGenerator generator = new NativeGenerator(frame.scope,
generatorFrame.fnOrScript, generatorFrame);
frame.result = generator;
break Loop;
} else {
// We are now resuming execution. Fall through to YIELD case.
}
}
// fall through...
case Token.YIELD: {
if (!frame.frozen) {
return freezeGenerator(cx, frame, stackTop, generatorState);
} else {
Object obj = thawGenerator(frame, stackTop, generatorState, op);
if (obj != Scriptable.NOT_FOUND) {
throwable = obj;
break withoutExceptions;
}
continue Loop;
}
}
case Icode_GENERATOR_END: {
// throw StopIteration
frame.frozen = true;
int sourceLine = getIndex(iCode, frame.pc);
generatorState.returnedException = new JavaScriptException(
NativeIterator.getStopIterationObject(frame.scope),
frame.idata.itsSourceFile, sourceLine);
break Loop;
}
case Token.THROW: {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
int sourceLine = getIndex(iCode, frame.pc);
throwable = new JavaScriptException(value,
frame.idata.itsSourceFile,
sourceLine);
break withoutExceptions;
}
case Token.RETHROW: {
indexReg += frame.localShift;
throwable = stack[indexReg];
break withoutExceptions;
}
case Token.GE :
case Token.LE :
case Token.GT :
case Token.LT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
object_compare:
{
number_compare:
{
double rDbl, lDbl;
if (rhs == DBL_MRK) {
rDbl = sDbl[stackTop + 1];
lDbl = stack_double(frame, stackTop);
} else if (lhs == DBL_MRK) {
rDbl = ScriptRuntime.toNumber(rhs);
lDbl = sDbl[stackTop];
} else {
break number_compare;
}
switch (op) {
case Token.GE:
valBln = (lDbl >= rDbl);
break object_compare;
case Token.LE:
valBln = (lDbl <= rDbl);
break object_compare;
case Token.GT:
valBln = (lDbl > rDbl);
break object_compare;
case Token.LT:
valBln = (lDbl < rDbl);
break object_compare;
default:
throw Kit.codeBug();
}
}
switch (op) {
case Token.GE:
valBln = ScriptRuntime.cmp_LE(rhs, lhs);
break;
case Token.LE:
valBln = ScriptRuntime.cmp_LE(lhs, rhs);
break;
case Token.GT:
valBln = ScriptRuntime.cmp_LT(rhs, lhs);
break;
case Token.LT:
valBln = ScriptRuntime.cmp_LT(lhs, rhs);
break;
default:
throw Kit.codeBug();
}
}
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.IN :
case Token.INSTANCEOF : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
boolean valBln;
if (op == Token.IN) {
valBln = ScriptRuntime.in(lhs, rhs, cx);
} else {
valBln = ScriptRuntime.instanceOf(lhs, rhs, cx);
}
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.EQ :
case Token.NE : {
--stackTop;
boolean valBln;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
if (rhs == DBL_MRK) {
if (lhs == DBL_MRK) {
valBln = (sDbl[stackTop] == sDbl[stackTop + 1]);
} else {
valBln = ScriptRuntime.eqNumber(sDbl[stackTop + 1], lhs);
}
} else {
if (lhs == DBL_MRK) {
valBln = ScriptRuntime.eqNumber(sDbl[stackTop], rhs);
} else {
valBln = ScriptRuntime.eq(lhs, rhs);
}
}
valBln ^= (op == Token.NE);
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.SHEQ :
case Token.SHNE : {
--stackTop;
boolean valBln = shallowEquals(stack, sDbl, stackTop);
valBln ^= (op == Token.SHNE);
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.IFNE :
if (stack_boolean(frame, stackTop--)) {
frame.pc += 2;
continue Loop;
}
break jumplessRun;
case Token.IFEQ :
if (!stack_boolean(frame, stackTop--)) {
frame.pc += 2;
continue Loop;
}
break jumplessRun;
case Icode_IFEQ_POP :
if (!stack_boolean(frame, stackTop--)) {
frame.pc += 2;
continue Loop;
}
stack[stackTop--] = null;
break jumplessRun;
case Token.GOTO :
break jumplessRun;
case Icode_GOSUB :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = frame.pc + 2;
break jumplessRun;
case Icode_STARTSUB :
if (stackTop == frame.emptyStackTop + 1) {
// Call from Icode_GOSUB: store return PC address in the local
indexReg += frame.localShift;
stack[indexReg] = stack[stackTop];
sDbl[indexReg] = sDbl[stackTop];
--stackTop;
} else {
// Call from exception handler: exception object is already stored
// in the local
if (stackTop != frame.emptyStackTop) Kit.codeBug();
}
continue Loop;
case Icode_RETSUB : {
// indexReg: local to store return address
if (instructionCounting) {
addInstructionCount(cx, frame, 0);
}
indexReg += frame.localShift;
Object value = stack[indexReg];
if (value != DBL_MRK) {
// Invocation from exception handler, restore object to rethrow
throwable = value;
break withoutExceptions;
}
// Normal return from GOSUB
frame.pc = (int)sDbl[indexReg];
if (instructionCounting) {
frame.pcPrevBranch = frame.pc;
}
continue Loop;
}
case Icode_POP :
stack[stackTop] = null;
stackTop--;
continue Loop;
case Icode_POP_RESULT :
frame.result = stack[stackTop];
frame.resultDbl = sDbl[stackTop];
stack[stackTop] = null;
--stackTop;
continue Loop;
case Icode_DUP :
stack[stackTop + 1] = stack[stackTop];
sDbl[stackTop + 1] = sDbl[stackTop];
stackTop++;
continue Loop;
case Icode_DUP2 :
stack[stackTop + 1] = stack[stackTop - 1];
sDbl[stackTop + 1] = sDbl[stackTop - 1];
stack[stackTop + 2] = stack[stackTop];
sDbl[stackTop + 2] = sDbl[stackTop];
stackTop += 2;
continue Loop;
case Icode_SWAP : {
Object o = stack[stackTop];
stack[stackTop] = stack[stackTop - 1];
stack[stackTop - 1] = o;
double d = sDbl[stackTop];
sDbl[stackTop] = sDbl[stackTop - 1];
sDbl[stackTop - 1] = d;
continue Loop;
}
case Token.RETURN :
frame.result = stack[stackTop];
frame.resultDbl = sDbl[stackTop];
--stackTop;
break Loop;
case Token.RETURN_RESULT :
break Loop;
case Icode_RETUNDEF :
frame.result = undefined;
break Loop;
case Token.BITNOT : {
int rIntValue = stack_int32(frame, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ~rIntValue;
continue Loop;
}
case Token.BITAND :
case Token.BITOR :
case Token.BITXOR :
case Token.LSH :
case Token.RSH : {
int lIntValue = stack_int32(frame, stackTop-1);
int rIntValue = stack_int32(frame, stackTop);
stack[--stackTop] = DBL_MRK;
switch (op) {
case Token.BITAND:
lIntValue &= rIntValue;
break;
case Token.BITOR:
lIntValue |= rIntValue;
break;
case Token.BITXOR:
lIntValue ^= rIntValue;
break;
case Token.LSH:
lIntValue <<= rIntValue;
break;
case Token.RSH:
lIntValue >>= rIntValue;
break;
}
sDbl[stackTop] = lIntValue;
continue Loop;
}
case Token.URSH : {
double lDbl = stack_double(frame, stackTop-1);
int rIntValue = stack_int32(frame, stackTop) & 0x1F;
stack[--stackTop] = DBL_MRK;
sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue;
continue Loop;
}
case Token.NEG :
case Token.POS : {
double rDbl = stack_double(frame, stackTop);
stack[stackTop] = DBL_MRK;
if (op == Token.NEG) {
rDbl = -rDbl;
}
sDbl[stackTop] = rDbl;
continue Loop;
}
case Token.ADD :
--stackTop;
do_add(stack, sDbl, stackTop, cx);
continue Loop;
case Token.SUB :
case Token.MUL :
case Token.DIV :
case Token.MOD : {
double rDbl = stack_double(frame, stackTop);
--stackTop;
double lDbl = stack_double(frame, stackTop);
stack[stackTop] = DBL_MRK;
switch (op) {
case Token.SUB:
lDbl -= rDbl;
break;
case Token.MUL:
lDbl *= rDbl;
break;
case Token.DIV:
lDbl /= rDbl;
break;
case Token.MOD:
lDbl %= rDbl;
break;
}
sDbl[stackTop] = lDbl;
continue Loop;
}
case Token.NOT :
stack[stackTop] = ScriptRuntime.wrapBoolean(
!stack_boolean(frame, stackTop));
continue Loop;
case Token.BINDNAME :
stack[++stackTop] = ScriptRuntime.bind(cx, frame.scope, stringReg);
continue Loop;
case Token.SETNAME : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setName(lhs, rhs, cx,
frame.scope, stringReg);
continue Loop;
}
case Icode_SETCONST: {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setConst(lhs, rhs, cx, stringReg);
continue Loop;
}
case Token.DELPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.delete(lhs, rhs, cx);
continue Loop;
}
case Token.GETPROPNOWARN : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getObjectPropNoWarn(lhs, stringReg, cx);
continue Loop;
}
case Token.GETPROP : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getObjectProp(lhs, stringReg, cx);
continue Loop;
}
case Token.SETPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setObjectProp(lhs, stringReg, rhs,
cx);
continue Loop;
}
case Icode_PROP_INC_DEC : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.propIncrDecr(lhs, stringReg,
cx, iCode[frame.pc]);
++frame.pc;
continue Loop;
}
case Token.GETELEM : {
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) {
lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
}
Object value;
Object id = stack[stackTop + 1];
if (id != DBL_MRK) {
value = ScriptRuntime.getObjectElem(lhs, id, cx);
} else {
double d = sDbl[stackTop + 1];
value = ScriptRuntime.getObjectIndex(lhs, d, cx);
}
stack[stackTop] = value;
continue Loop;
}
case Token.SETELEM : {
stackTop -= 2;
Object rhs = stack[stackTop + 2];
if (rhs == DBL_MRK) {
rhs = ScriptRuntime.wrapNumber(sDbl[stackTop + 2]);
}
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) {
lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
}
Object value;
Object id = stack[stackTop + 1];
if (id != DBL_MRK) {
value = ScriptRuntime.setObjectElem(lhs, id, rhs, cx);
} else {
double d = sDbl[stackTop + 1];
value = ScriptRuntime.setObjectIndex(lhs, d, rhs, cx);
}
stack[stackTop] = value;
continue Loop;
}
case Icode_ELEM_INC_DEC: {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.elemIncrDecr(lhs, rhs, cx,
iCode[frame.pc]);
++frame.pc;
continue Loop;
}
case Token.GET_REF : {
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refGet(ref, cx);
continue Loop;
}
case Token.SET_REF : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refSet(ref, value, cx);
continue Loop;
}
case Token.DEL_REF : {
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refDel(ref, cx);
continue Loop;
}
case Icode_REF_INC_DEC : {
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refIncrDecr(ref, cx, iCode[frame.pc]);
++frame.pc;
continue Loop;
}
case Token.LOCAL_LOAD :
++stackTop;
indexReg += frame.localShift;
stack[stackTop] = stack[indexReg];
sDbl[stackTop] = sDbl[indexReg];
continue Loop;
case Icode_LOCAL_CLEAR :
indexReg += frame.localShift;
stack[indexReg] = null;
continue Loop;
case Icode_NAME_AND_THIS :
// stringReg: name
++stackTop;
stack[stackTop] = ScriptRuntime.getNameFunctionAndThis(stringReg,
cx, frame.scope);
++stackTop;
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
case Icode_PROP_AND_THIS: {
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
// stringReg: property
stack[stackTop] = ScriptRuntime.getPropFunctionAndThis(obj, stringReg,
cx);
++stackTop;
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
}
case Icode_ELEM_AND_THIS: {
Object obj = stack[stackTop - 1];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop - 1]);
Object id = stack[stackTop];
if (id == DBL_MRK) id = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop - 1] = ScriptRuntime.getElemFunctionAndThis(obj, id, cx);
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
}
case Icode_VALUE_AND_THIS : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getValueFunctionAndThis(value, cx);
++stackTop;
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
}
case Icode_CALLSPECIAL : {
if (instructionCounting) {
cx.instructionCount += INVOCATION_COST;
}
int callType = iCode[frame.pc] & 0xFF;
boolean isNew = (iCode[frame.pc + 1] != 0);
int sourceLine = getIndex(iCode, frame.pc + 2);
// indexReg: number of arguments
if (isNew) {
// stack change: function arg0 .. argN -> newResult
stackTop -= indexReg;
Object function = stack[stackTop];
if (function == DBL_MRK)
function = ScriptRuntime.wrapNumber(sDbl[stackTop]);
Object[] outArgs = getArgsArray(
stack, sDbl, stackTop + 1, indexReg);
stack[stackTop] = ScriptRuntime.newSpecial(
cx, function, outArgs, frame.scope, callType);
} else {
// stack change: function thisObj arg0 .. argN -> result
stackTop -= 1 + indexReg;
// Call code generation ensure that stack here
// is ... Callable Scriptable
Scriptable functionThis = (Scriptable)stack[stackTop + 1];
Callable function = (Callable)stack[stackTop];
Object[] outArgs = getArgsArray(
stack, sDbl, stackTop + 2, indexReg);
stack[stackTop] = ScriptRuntime.callSpecial(
cx, function, functionThis, outArgs,
frame.scope, frame.thisObj, callType,
frame.idata.itsSourceFile, sourceLine);
}
frame.pc += 4;
continue Loop;
}
case Token.CALL :
case Icode_TAIL_CALL :
case Token.REF_CALL : {
if (instructionCounting) {
cx.instructionCount += INVOCATION_COST;
}
// stack change: function thisObj arg0 .. argN -> result
// indexReg: number of arguments
stackTop -= 1 + indexReg;
// CALL generation ensures that fun and funThisObj
// are already Scriptable and Callable objects respectively
Callable fun = (Callable)stack[stackTop];
Scriptable funThisObj = (Scriptable)stack[stackTop + 1];
if (op == Token.REF_CALL) {
Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 2,
indexReg);
stack[stackTop] = ScriptRuntime.callRef(fun, funThisObj,
outArgs, cx);
continue Loop;
}
Scriptable calleeScope = frame.scope;
if (frame.useActivation) {
calleeScope = ScriptableObject.getTopLevelScope(frame.scope);
}
if (fun instanceof InterpretedFunction) {
InterpretedFunction ifun = (InterpretedFunction)fun;
if (frame.fnOrScript.securityDomain == ifun.securityDomain) {
CallFrame callParentFrame = frame;
CallFrame calleeFrame = new CallFrame();
if (op == Icode_TAIL_CALL) {
// In principle tail call can re-use the current
// frame and its stack arrays but it is hard to
// do properly. Any exceptions that can legally
// happen during frame re-initialization including
// StackOverflowException during innocent looking
// System.arraycopy may leave the current frame
// data corrupted leading to undefined behaviour
// in the catch code bellow that unwinds JS stack
// on exceptions. Then there is issue about frame release
// end exceptions there.
// To avoid frame allocation a released frame
// can be cached for re-use which would also benefit
// non-tail calls but it is not clear that this caching
// would gain in performance due to potentially
// bad interaction with GC.
callParentFrame = frame.parentFrame;
// Release the current frame. See Bug #344501 to see why
// it is being done here.
exitFrame(cx, frame, null);
}
initFrame(cx, calleeScope, funThisObj, stack, sDbl,
stackTop + 2, indexReg, ifun, callParentFrame,
calleeFrame);
if (op != Icode_TAIL_CALL) {
frame.savedStackTop = stackTop;
frame.savedCallOp = op;
}
frame = calleeFrame;
continue StateLoop;
}
}
if (fun instanceof NativeContinuation) {
// Jump to the captured continuation
ContinuationJump cjump;
cjump = new ContinuationJump((NativeContinuation)fun, frame);
// continuation result is the first argument if any
// of continuation call
if (indexReg == 0) {
cjump.result = undefined;
} else {
cjump.result = stack[stackTop + 2];
cjump.resultDbl = sDbl[stackTop + 2];
}
// Start the real unwind job
throwable = cjump;
break withoutExceptions;
}
if (fun instanceof IdFunctionObject) {
IdFunctionObject ifun = (IdFunctionObject)fun;
if (NativeContinuation.isContinuationConstructor(ifun)) {
frame.stack[stackTop] = captureContinuation(cx,
frame.parentFrame, false);
continue Loop;
}
// Bug 405654 -- make best effort to keep Function.apply and
// Function.call within this interpreter loop invocation
if (BaseFunction.isApplyOrCall(ifun)) {
Callable applyCallable = ScriptRuntime.getCallable(funThisObj);
if (applyCallable instanceof InterpretedFunction) {
InterpretedFunction iApplyCallable = (InterpretedFunction)applyCallable;
if (frame.fnOrScript.securityDomain == iApplyCallable.securityDomain) {
frame = initFrameForApplyOrCall(cx, frame, indexReg,
stack, sDbl, stackTop, op, calleeScope, ifun,
iApplyCallable);
continue StateLoop;
}
}
}
}
// Bug 447697 -- make best effort to keep __noSuchMethod__ within this
// interpreter loop invocation
if (fun instanceof NoSuchMethodShim) {
// get the shim and the actual method
NoSuchMethodShim noSuchMethodShim = (NoSuchMethodShim) fun;
Callable noSuchMethodMethod = noSuchMethodShim.noSuchMethodMethod;
// if the method is in fact an InterpretedFunction
if (noSuchMethodMethod instanceof InterpretedFunction) {
InterpretedFunction ifun = (InterpretedFunction) noSuchMethodMethod;
if (frame.fnOrScript.securityDomain == ifun.securityDomain) {
frame = initFrameForNoSuchMethod(cx, frame, indexReg, stack, sDbl,
stackTop, op, funThisObj, calleeScope,
noSuchMethodShim, ifun);
continue StateLoop;
}
}
}
cx.lastInterpreterFrame = frame;
frame.savedCallOp = op;
frame.savedStackTop = stackTop;
stack[stackTop] = fun.call(cx, calleeScope, funThisObj,
getArgsArray(stack, sDbl, stackTop + 2, indexReg));
cx.lastInterpreterFrame = null;
continue Loop;
}
case Token.NEW : {
if (instructionCounting) {
cx.instructionCount += INVOCATION_COST;
}
// stack change: function arg0 .. argN -> newResult
// indexReg: number of arguments
stackTop -= indexReg;
Object lhs = stack[stackTop];
if (lhs instanceof InterpretedFunction) {
InterpretedFunction f = (InterpretedFunction)lhs;
if (frame.fnOrScript.securityDomain == f.securityDomain) {
Scriptable newInstance = f.createObject(cx, frame.scope);
CallFrame calleeFrame = new CallFrame();
initFrame(cx, frame.scope, newInstance, stack, sDbl,
stackTop + 1, indexReg, f, frame,
calleeFrame);
stack[stackTop] = newInstance;
frame.savedStackTop = stackTop;
frame.savedCallOp = op;
frame = calleeFrame;
continue StateLoop;
}
}
if (!(lhs instanceof Function)) {
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
throw ScriptRuntime.notFunctionError(lhs);
}
Function fun = (Function)lhs;
if (fun instanceof IdFunctionObject) {
IdFunctionObject ifun = (IdFunctionObject)fun;
if (NativeContinuation.isContinuationConstructor(ifun)) {
frame.stack[stackTop] =
captureContinuation(cx, frame.parentFrame, false);
continue Loop;
}
}
Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, indexReg);
stack[stackTop] = fun.construct(cx, frame.scope, outArgs);
continue Loop;
}
case Token.TYPEOF : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.typeof(lhs);
continue Loop;
}
case Icode_TYPEOFNAME :
stack[++stackTop] = ScriptRuntime.typeofName(frame.scope, stringReg);
continue Loop;
case Token.STRING :
stack[++stackTop] = stringReg;
continue Loop;
case Icode_SHORTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getShort(iCode, frame.pc);
frame.pc += 2;
continue Loop;
case Icode_INTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getInt(iCode, frame.pc);
frame.pc += 4;
continue Loop;
case Token.NUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = frame.idata.itsDoubleTable[indexReg];
continue Loop;
case Token.NAME :
stack[++stackTop] = ScriptRuntime.name(cx, frame.scope, stringReg);
continue Loop;
case Icode_NAME_INC_DEC :
stack[++stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, stringReg,
cx, iCode[frame.pc]);
++frame.pc;
continue Loop;
case Icode_SETCONSTVAR1:
indexReg = iCode[frame.pc++];
// fallthrough
case Token.SETCONSTVAR :
if (!frame.useActivation) {
if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) {
throw Context.reportRuntimeError1("msg.var.redecl",
frame.idata.argNames[indexReg]);
}
if ((varAttributes[indexReg] & ScriptableObject.UNINITIALIZED_CONST)
!= 0)
{
vars[indexReg] = stack[stackTop];
varAttributes[indexReg] &= ~ScriptableObject.UNINITIALIZED_CONST;
varDbls[indexReg] = sDbl[stackTop];
}
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stringReg = frame.idata.argNames[indexReg];
if (frame.scope instanceof ConstProperties) {
ConstProperties cp = (ConstProperties)frame.scope;
cp.putConst(stringReg, frame.scope, val);
} else
throw Kit.codeBug();
}
continue Loop;
case Icode_SETVAR1:
indexReg = iCode[frame.pc++];
// fallthrough
case Token.SETVAR :
if (!frame.useActivation) {
if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) {
vars[indexReg] = stack[stackTop];
varDbls[indexReg] = sDbl[stackTop];
}
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stringReg = frame.idata.argNames[indexReg];
frame.scope.put(stringReg, frame.scope, val);
}
continue Loop;
case Icode_GETVAR1:
indexReg = iCode[frame.pc++];
// fallthrough
case Token.GETVAR :
++stackTop;
if (!frame.useActivation) {
stack[stackTop] = vars[indexReg];
sDbl[stackTop] = varDbls[indexReg];
} else {
stringReg = frame.idata.argNames[indexReg];
stack[stackTop] = frame.scope.get(stringReg, frame.scope);
}
continue Loop;
case Icode_VAR_INC_DEC : {
// indexReg : varindex
++stackTop;
int incrDecrMask = iCode[frame.pc];
if (!frame.useActivation) {
stack[stackTop] = DBL_MRK;
Object varValue = vars[indexReg];
double d;
if (varValue == DBL_MRK) {
d = varDbls[indexReg];
} else {
d = ScriptRuntime.toNumber(varValue);
vars[indexReg] = DBL_MRK;
}
double d2 = ((incrDecrMask & Node.DECR_FLAG) == 0)
? d + 1.0 : d - 1.0;
varDbls[indexReg] = d2;
sDbl[stackTop] = ((incrDecrMask & Node.POST_FLAG) == 0) ? d2 : d;
} else {
String varName = frame.idata.argNames[indexReg];
stack[stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, varName,
cx, incrDecrMask);
}
++frame.pc;
continue Loop;
}
case Icode_ZERO :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 0;
continue Loop;
case Icode_ONE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 1;
continue Loop;
case Token.NULL :
stack[++stackTop] = null;
continue Loop;
case Token.THIS :
stack[++stackTop] = frame.thisObj;
continue Loop;
case Token.THISFN :
stack[++stackTop] = frame.fnOrScript;
continue Loop;
case Token.FALSE :
stack[++stackTop] = Boolean.FALSE;
continue Loop;
case Token.TRUE :
stack[++stackTop] = Boolean.TRUE;
continue Loop;
case Icode_UNDEF :
stack[++stackTop] = undefined;
continue Loop;
case Token.ENTERWITH : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
frame.scope = ScriptRuntime.enterWith(lhs, cx, frame.scope);
continue Loop;
}
case Token.LEAVEWITH :
frame.scope = ScriptRuntime.leaveWith(frame.scope);
continue Loop;
case Token.CATCH_SCOPE : {
// stack top: exception object
// stringReg: name of exception variable
// indexReg: local for exception scope
--stackTop;
indexReg += frame.localShift;
boolean afterFirstScope = (frame.idata.itsICode[frame.pc] != 0);
Throwable caughtException = (Throwable)stack[stackTop + 1];
Scriptable lastCatchScope;
if (!afterFirstScope) {
lastCatchScope = null;
} else {
lastCatchScope = (Scriptable)stack[indexReg];
}
stack[indexReg] = ScriptRuntime.newCatchScope(caughtException,
lastCatchScope, stringReg,
cx, frame.scope);
++frame.pc;
continue Loop;
}
case Token.ENUM_INIT_KEYS :
case Token.ENUM_INIT_VALUES :
case Token.ENUM_INIT_ARRAY : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
indexReg += frame.localShift;
int enumType = op == Token.ENUM_INIT_KEYS
? ScriptRuntime.ENUMERATE_KEYS :
op == Token.ENUM_INIT_VALUES
? ScriptRuntime.ENUMERATE_VALUES :
ScriptRuntime.ENUMERATE_ARRAY;
stack[indexReg] = ScriptRuntime.enumInit(lhs, cx, enumType);
continue Loop;
}
case Token.ENUM_NEXT :
case Token.ENUM_ID : {
indexReg += frame.localShift;
Object val = stack[indexReg];
++stackTop;
stack[stackTop] = (op == Token.ENUM_NEXT)
? (Object)ScriptRuntime.enumNext(val)
: (Object)ScriptRuntime.enumId(val, cx);
continue Loop;
}
case Token.REF_SPECIAL : {
//stringReg: name of special property
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.specialRef(obj, stringReg, cx);
continue Loop;
}
case Token.REF_MEMBER: {
//indexReg: flags
Object elem = stack[stackTop];
if (elem == DBL_MRK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.memberRef(obj, elem, cx, indexReg);
continue Loop;
}
case Token.REF_NS_MEMBER: {
//indexReg: flags
Object elem = stack[stackTop];
if (elem == DBL_MRK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object ns = stack[stackTop];
if (ns == DBL_MRK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.memberRef(obj, ns, elem, cx, indexReg);
continue Loop;
}
case Token.REF_NAME: {
//indexReg: flags
Object name = stack[stackTop];
if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.nameRef(name, cx, frame.scope,
indexReg);
continue Loop;
}
case Token.REF_NS_NAME: {
//indexReg: flags
Object name = stack[stackTop];
if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object ns = stack[stackTop];
if (ns == DBL_MRK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.nameRef(ns, name, cx, frame.scope,
indexReg);
continue Loop;
}
case Icode_SCOPE_LOAD :
indexReg += frame.localShift;
frame.scope = (Scriptable)stack[indexReg];
continue Loop;
case Icode_SCOPE_SAVE :
indexReg += frame.localShift;
stack[indexReg] = frame.scope;
continue Loop;
case Icode_CLOSURE_EXPR :
stack[++stackTop] = InterpretedFunction.createFunction(cx, frame.scope,
frame.fnOrScript,
indexReg);
continue Loop;
case Icode_CLOSURE_STMT :
initFunction(cx, frame.scope, frame.fnOrScript, indexReg);
continue Loop;
case Token.REGEXP :
stack[++stackTop] = frame.scriptRegExps[indexReg];
continue Loop;
case Icode_LITERAL_NEW :
// indexReg: number of values in the literal
++stackTop;
stack[stackTop] = new int[indexReg];
++stackTop;
stack[stackTop] = new Object[indexReg];
sDbl[stackTop] = 0;
continue Loop;
case Icode_LITERAL_SET : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
int i = (int)sDbl[stackTop];
((Object[])stack[stackTop])[i] = value;
sDbl[stackTop] = i + 1;
continue Loop;
}
case Icode_LITERAL_GETTER : {
Object value = stack[stackTop];
--stackTop;
int i = (int)sDbl[stackTop];
((Object[])stack[stackTop])[i] = value;
((int[])stack[stackTop - 1])[i] = -1;
sDbl[stackTop] = i + 1;
continue Loop;
}
case Icode_LITERAL_SETTER : {
Object value = stack[stackTop];
--stackTop;
int i = (int)sDbl[stackTop];
((Object[])stack[stackTop])[i] = value;
((int[])stack[stackTop - 1])[i] = +1;
sDbl[stackTop] = i + 1;
continue Loop;
}
case Token.ARRAYLIT :
case Icode_SPARE_ARRAYLIT :
case Token.OBJECTLIT : {
Object[] data = (Object[])stack[stackTop];
--stackTop;
int[] getterSetters = (int[])stack[stackTop];
Object val;
if (op == Token.OBJECTLIT) {
Object[] ids = (Object[])frame.idata.literalIds[indexReg];
val = ScriptRuntime.newObjectLiteral(ids, data, getterSetters, cx,
frame.scope);
} else {
int[] skipIndexces = null;
if (op == Icode_SPARE_ARRAYLIT) {
skipIndexces = (int[])frame.idata.literalIds[indexReg];
}
val = ScriptRuntime.newArrayLiteral(data, skipIndexces, cx,
frame.scope);
}
stack[stackTop] = val;
continue Loop;
}
case Icode_ENTERDQ : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
frame.scope = ScriptRuntime.enterDotQuery(lhs, frame.scope);
continue Loop;
}
case Icode_LEAVEDQ : {
boolean valBln = stack_boolean(frame, stackTop);
Object x = ScriptRuntime.updateDotQuery(valBln, frame.scope);
if (x != null) {
stack[stackTop] = x;
frame.scope = ScriptRuntime.leaveDotQuery(frame.scope);
frame.pc += 2;
continue Loop;
}
// reset stack and PC to code after ENTERDQ
--stackTop;
break jumplessRun;
}
case Token.DEFAULTNAMESPACE : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setDefaultNamespace(value, cx);
continue Loop;
}
case Token.ESCXMLATTR : {
Object value = stack[stackTop];
if (value != DBL_MRK) {
stack[stackTop] = ScriptRuntime.escapeAttributeValue(value, cx);
}
continue Loop;
}
case Token.ESCXMLTEXT : {
Object value = stack[stackTop];
if (value != DBL_MRK) {
stack[stackTop] = ScriptRuntime.escapeTextValue(value, cx);
}
continue Loop;
}
case Icode_DEBUGGER:
if (frame.debuggerFrame != null) {
frame.debuggerFrame.onDebuggerStatement(cx);
}
break Loop;
case Icode_LINE :
frame.pcSourceLineStart = frame.pc;
if (frame.debuggerFrame != null) {
int line = getIndex(iCode, frame.pc);
frame.debuggerFrame.onLineChange(cx, line);
}
frame.pc += 2;
continue Loop;
case Icode_REG_IND_C0:
indexReg = 0;
continue Loop;
case Icode_REG_IND_C1:
indexReg = 1;
continue Loop;
case Icode_REG_IND_C2:
indexReg = 2;
continue Loop;
case Icode_REG_IND_C3:
indexReg = 3;
continue Loop;
case Icode_REG_IND_C4:
indexReg = 4;
continue Loop;
case Icode_REG_IND_C5:
indexReg = 5;
continue Loop;
case Icode_REG_IND1:
indexReg = 0xFF & iCode[frame.pc];
++frame.pc;
continue Loop;
case Icode_REG_IND2:
indexReg = getIndex(iCode, frame.pc);
frame.pc += 2;
continue Loop;
case Icode_REG_IND4:
indexReg = getInt(iCode, frame.pc);
frame.pc += 4;
continue Loop;
case Icode_REG_STR_C0:
stringReg = strings[0];
continue Loop;
case Icode_REG_STR_C1:
stringReg = strings[1];
continue Loop;
case Icode_REG_STR_C2:
stringReg = strings[2];
continue Loop;
case Icode_REG_STR_C3:
stringReg = strings[3];
continue Loop;
case Icode_REG_STR1:
stringReg = strings[0xFF & iCode[frame.pc]];
++frame.pc;
continue Loop;
case Icode_REG_STR2:
stringReg = strings[getIndex(iCode, frame.pc)];
frame.pc += 2;
continue Loop;
case Icode_REG_STR4:
stringReg = strings[getInt(iCode, frame.pc)];
frame.pc += 4;
continue Loop;
default :
dumpICode(frame.idata);
throw new RuntimeException(
"Unknown icode : "+op+" @ pc : "+(frame.pc-1));
} // end of interpreter switch
} // end of jumplessRun label block
// This should be reachable only for jump implementation
// when pc points to encoded target offset
if (instructionCounting) {
addInstructionCount(cx, frame, 2);
}
int offset = getShort(iCode, frame.pc);
if (offset != 0) {
// -1 accounts for pc pointing to jump opcode + 1
frame.pc += offset - 1;
} else {
frame.pc = frame.idata.longJumps.
getExistingInt(frame.pc);
}
if (instructionCounting) {
frame.pcPrevBranch = frame.pc;
}
continue Loop;
} // end of Loop: for
exitFrame(cx, frame, null);
interpreterResult = frame.result;
interpreterResultDbl = frame.resultDbl;
if (frame.parentFrame != null) {
frame = frame.parentFrame;
if (frame.frozen) {
frame = frame.cloneFrozen();
}
setCallResult(
frame, interpreterResult, interpreterResultDbl);
interpreterResult = null; // Help GC
continue StateLoop;
}
break StateLoop;
} // end of interpreter withoutExceptions: try
catch (Throwable ex) {
if (throwable != null) {
// This is serious bug and it is better to track it ASAP
ex.printStackTrace(System.err);
throw new IllegalStateException();
}
throwable = ex;
}
// This should be reachable only after above catch or from
// finally when it needs to propagate exception or from
// explicit throw
if (throwable == null) Kit.codeBug();
// Exception type
final int EX_CATCH_STATE = 2; // Can execute JS catch
final int EX_FINALLY_STATE = 1; // Can execute JS finally
final int EX_NO_JS_STATE = 0; // Terminate JS execution
int exState;
ContinuationJump cjump = null;
if (generatorState != null &&
generatorState.operation == NativeGenerator.GENERATOR_CLOSE &&
throwable == generatorState.value)
{
exState = EX_FINALLY_STATE;
} else if (throwable instanceof JavaScriptException) {
exState = EX_CATCH_STATE;
} else if (throwable instanceof EcmaError) {
// an offical ECMA error object,
exState = EX_CATCH_STATE;
} else if (throwable instanceof EvaluatorException) {
exState = EX_CATCH_STATE;
} else if (throwable instanceof RuntimeException) {
exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
? EX_CATCH_STATE
: EX_FINALLY_STATE;
} else if (throwable instanceof Error) {
exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
? EX_CATCH_STATE
: EX_NO_JS_STATE;
} else if (throwable instanceof ContinuationJump) {
// It must be ContinuationJump
exState = EX_FINALLY_STATE;
cjump = (ContinuationJump)throwable;
} else {
exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
? EX_CATCH_STATE
: EX_FINALLY_STATE;
}
if (instructionCounting) {
try {
addInstructionCount(cx, frame, EXCEPTION_COST);
} catch (RuntimeException ex) {
throwable = ex;
exState = EX_FINALLY_STATE;
} catch (Error ex) {
// Error from instruction counting
// => unconditionally terminate JS
throwable = ex;
cjump = null;
exState = EX_NO_JS_STATE;
}
}
if (frame.debuggerFrame != null
&& throwable instanceof RuntimeException)
{
// Call debugger only for RuntimeException
RuntimeException rex = (RuntimeException)throwable;
try {
frame.debuggerFrame.onExceptionThrown(cx, rex);
} catch (Throwable ex) {
// Any exception from debugger
// => unconditionally terminate JS
throwable = ex;
cjump = null;
exState = EX_NO_JS_STATE;
}
}
for (;;) {
if (exState != EX_NO_JS_STATE) {
boolean onlyFinally = (exState != EX_CATCH_STATE);
indexReg = getExceptionHandler(frame, onlyFinally);
if (indexReg >= 0) {
// We caught an exception, restart the loop
// with exception pending the processing at the loop
// start
continue StateLoop;
}
}
// No allowed exception handlers in this frame, unwind
// to parent and try to look there
exitFrame(cx, frame, throwable);
frame = frame.parentFrame;
if (frame == null) { break; }
if (cjump != null && cjump.branchFrame == frame) {
// Continuation branch point was hit,
// restart the state loop to reenter continuation
indexReg = -1;
continue StateLoop;
}
}
// No more frames, rethrow the exception or deal with continuation
if (cjump != null) {
if (cjump.branchFrame != null) {
// The above loop should locate the top frame
Kit.codeBug();
}
if (cjump.capturedFrame != null) {
// Restarting detached continuation
indexReg = -1;
continue StateLoop;
}
// Return continuation result to the caller
interpreterResult = cjump.result;
interpreterResultDbl = cjump.resultDbl;
throwable = null;
}
break StateLoop;
} // end of StateLoop: for(;;)
// Do cleanups/restorations before the final return or throw
if (cx.previousInterpreterInvocations != null
&& cx.previousInterpreterInvocations.size() != 0)
{
cx.lastInterpreterFrame
= cx.previousInterpreterInvocations.pop();
} else {
// It was the last interpreter frame on the stack
cx.lastInterpreterFrame = null;
// Force GC of the value cx.previousInterpreterInvocations
cx.previousInterpreterInvocations = null;
}
if (throwable != null) {
if (throwable instanceof RuntimeException) {
throw (RuntimeException)throwable;
} else {
// Must be instance of Error or code bug
throw (Error)throwable;
}
}
return (interpreterResult != DBL_MRK)
? interpreterResult
: ScriptRuntime.wrapNumber(interpreterResultDbl);
}
| private static Object interpretLoop(Context cx, CallFrame frame,
Object throwable)
{
// throwable holds exception object to rethrow or catch
// It is also used for continuation restart in which case
// it holds ContinuationJump
final Object DBL_MRK = UniqueTag.DOUBLE_MARK;
final Object undefined = Undefined.instance;
final boolean instructionCounting = (cx.instructionThreshold != 0);
// arbitrary number to add to instructionCount when calling
// other functions
final int INVOCATION_COST = 100;
// arbitrary exception cost for instruction counting
final int EXCEPTION_COST = 100;
String stringReg = null;
int indexReg = -1;
if (cx.lastInterpreterFrame != null) {
// save the top frame from the previous interpretLoop
// invocation on the stack
if (cx.previousInterpreterInvocations == null) {
cx.previousInterpreterInvocations = new ObjArray();
}
cx.previousInterpreterInvocations.push(cx.lastInterpreterFrame);
}
// When restarting continuation throwable is not null and to jump
// to the code that rewind continuation state indexReg should be set
// to -1.
// With the normal call throwable == null and indexReg == -1 allows to
// catch bugs with using indeReg to access array elements before
// initializing indexReg.
GeneratorState generatorState = null;
if (throwable != null) {
if (throwable instanceof GeneratorState) {
generatorState = (GeneratorState) throwable;
// reestablish this call frame
enterFrame(cx, frame, ScriptRuntime.emptyArgs, true);
throwable = null;
} else if (!(throwable instanceof ContinuationJump)) {
// It should be continuation
Kit.codeBug();
}
}
Object interpreterResult = null;
double interpreterResultDbl = 0.0;
StateLoop: for (;;) {
withoutExceptions: try {
if (throwable != null) {
// Need to return both 'frame' and 'throwable' from
// 'processThrowable', so just added a 'throwable'
// member in 'frame'.
frame = processThrowable(cx, throwable, frame, indexReg,
instructionCounting);
throwable = frame.throwable;
frame.throwable = null;
} else {
if (generatorState == null && frame.frozen) Kit.codeBug();
}
// Use local variables for constant values in frame
// for faster access
Object[] stack = frame.stack;
double[] sDbl = frame.sDbl;
Object[] vars = frame.varSource.stack;
double[] varDbls = frame.varSource.sDbl;
int[] varAttributes = frame.varSource.stackAttributes;
byte[] iCode = frame.idata.itsICode;
String[] strings = frame.idata.itsStringTable;
// Use local for stackTop as well. Since execption handlers
// can only exist at statement level where stack is empty,
// it is necessary to save/restore stackTop only across
// function calls and normal returns.
int stackTop = frame.savedStackTop;
// Store new frame in cx which is used for error reporting etc.
cx.lastInterpreterFrame = frame;
Loop: for (;;) {
// Exception handler assumes that PC is already incremented
// pass the instruction start when it searches the
// exception handler
int op = iCode[frame.pc++];
jumplessRun: {
// Back indent to ease implementation reading
switch (op) {
case Icode_GENERATOR: {
if (!frame.frozen) {
// First time encountering this opcode: create new generator
// object and return
frame.pc--; // we want to come back here when we resume
CallFrame generatorFrame = captureFrameForGenerator(frame);
generatorFrame.frozen = true;
NativeGenerator generator = new NativeGenerator(frame.scope,
generatorFrame.fnOrScript, generatorFrame);
frame.result = generator;
break Loop;
} else {
// We are now resuming execution. Fall through to YIELD case.
}
}
// fall through...
case Token.YIELD: {
if (!frame.frozen) {
return freezeGenerator(cx, frame, stackTop, generatorState);
} else {
Object obj = thawGenerator(frame, stackTop, generatorState, op);
if (obj != Scriptable.NOT_FOUND) {
throwable = obj;
break withoutExceptions;
}
continue Loop;
}
}
case Icode_GENERATOR_END: {
// throw StopIteration
frame.frozen = true;
int sourceLine = getIndex(iCode, frame.pc);
generatorState.returnedException = new JavaScriptException(
NativeIterator.getStopIterationObject(frame.scope),
frame.idata.itsSourceFile, sourceLine);
break Loop;
}
case Token.THROW: {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
int sourceLine = getIndex(iCode, frame.pc);
throwable = new JavaScriptException(value,
frame.idata.itsSourceFile,
sourceLine);
break withoutExceptions;
}
case Token.RETHROW: {
indexReg += frame.localShift;
throwable = stack[indexReg];
break withoutExceptions;
}
case Token.GE :
case Token.LE :
case Token.GT :
case Token.LT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
object_compare:
{
number_compare:
{
double rDbl, lDbl;
if (rhs == DBL_MRK) {
rDbl = sDbl[stackTop + 1];
lDbl = stack_double(frame, stackTop);
} else if (lhs == DBL_MRK) {
rDbl = ScriptRuntime.toNumber(rhs);
lDbl = sDbl[stackTop];
} else {
break number_compare;
}
switch (op) {
case Token.GE:
valBln = (lDbl >= rDbl);
break object_compare;
case Token.LE:
valBln = (lDbl <= rDbl);
break object_compare;
case Token.GT:
valBln = (lDbl > rDbl);
break object_compare;
case Token.LT:
valBln = (lDbl < rDbl);
break object_compare;
default:
throw Kit.codeBug();
}
}
switch (op) {
case Token.GE:
valBln = ScriptRuntime.cmp_LE(rhs, lhs);
break;
case Token.LE:
valBln = ScriptRuntime.cmp_LE(lhs, rhs);
break;
case Token.GT:
valBln = ScriptRuntime.cmp_LT(rhs, lhs);
break;
case Token.LT:
valBln = ScriptRuntime.cmp_LT(lhs, rhs);
break;
default:
throw Kit.codeBug();
}
}
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.IN :
case Token.INSTANCEOF : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
boolean valBln;
if (op == Token.IN) {
valBln = ScriptRuntime.in(lhs, rhs, cx);
} else {
valBln = ScriptRuntime.instanceOf(lhs, rhs, cx);
}
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.EQ :
case Token.NE : {
--stackTop;
boolean valBln;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
if (rhs == DBL_MRK) {
if (lhs == DBL_MRK) {
valBln = (sDbl[stackTop] == sDbl[stackTop + 1]);
} else {
valBln = ScriptRuntime.eqNumber(sDbl[stackTop + 1], lhs);
}
} else {
if (lhs == DBL_MRK) {
valBln = ScriptRuntime.eqNumber(sDbl[stackTop], rhs);
} else {
valBln = ScriptRuntime.eq(lhs, rhs);
}
}
valBln ^= (op == Token.NE);
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.SHEQ :
case Token.SHNE : {
--stackTop;
boolean valBln = shallowEquals(stack, sDbl, stackTop);
valBln ^= (op == Token.SHNE);
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.IFNE :
if (stack_boolean(frame, stackTop--)) {
frame.pc += 2;
continue Loop;
}
break jumplessRun;
case Token.IFEQ :
if (!stack_boolean(frame, stackTop--)) {
frame.pc += 2;
continue Loop;
}
break jumplessRun;
case Icode_IFEQ_POP :
if (!stack_boolean(frame, stackTop--)) {
frame.pc += 2;
continue Loop;
}
stack[stackTop--] = null;
break jumplessRun;
case Token.GOTO :
break jumplessRun;
case Icode_GOSUB :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = frame.pc + 2;
break jumplessRun;
case Icode_STARTSUB :
if (stackTop == frame.emptyStackTop + 1) {
// Call from Icode_GOSUB: store return PC address in the local
indexReg += frame.localShift;
stack[indexReg] = stack[stackTop];
sDbl[indexReg] = sDbl[stackTop];
--stackTop;
} else {
// Call from exception handler: exception object is already stored
// in the local
if (stackTop != frame.emptyStackTop) Kit.codeBug();
}
continue Loop;
case Icode_RETSUB : {
// indexReg: local to store return address
if (instructionCounting) {
addInstructionCount(cx, frame, 0);
}
indexReg += frame.localShift;
Object value = stack[indexReg];
if (value != DBL_MRK) {
// Invocation from exception handler, restore object to rethrow
throwable = value;
break withoutExceptions;
}
// Normal return from GOSUB
frame.pc = (int)sDbl[indexReg];
if (instructionCounting) {
frame.pcPrevBranch = frame.pc;
}
continue Loop;
}
case Icode_POP :
stack[stackTop] = null;
stackTop--;
continue Loop;
case Icode_POP_RESULT :
frame.result = stack[stackTop];
frame.resultDbl = sDbl[stackTop];
stack[stackTop] = null;
--stackTop;
continue Loop;
case Icode_DUP :
stack[stackTop + 1] = stack[stackTop];
sDbl[stackTop + 1] = sDbl[stackTop];
stackTop++;
continue Loop;
case Icode_DUP2 :
stack[stackTop + 1] = stack[stackTop - 1];
sDbl[stackTop + 1] = sDbl[stackTop - 1];
stack[stackTop + 2] = stack[stackTop];
sDbl[stackTop + 2] = sDbl[stackTop];
stackTop += 2;
continue Loop;
case Icode_SWAP : {
Object o = stack[stackTop];
stack[stackTop] = stack[stackTop - 1];
stack[stackTop - 1] = o;
double d = sDbl[stackTop];
sDbl[stackTop] = sDbl[stackTop - 1];
sDbl[stackTop - 1] = d;
continue Loop;
}
case Token.RETURN :
frame.result = stack[stackTop];
frame.resultDbl = sDbl[stackTop];
--stackTop;
break Loop;
case Token.RETURN_RESULT :
break Loop;
case Icode_RETUNDEF :
frame.result = undefined;
break Loop;
case Token.BITNOT : {
int rIntValue = stack_int32(frame, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ~rIntValue;
continue Loop;
}
case Token.BITAND :
case Token.BITOR :
case Token.BITXOR :
case Token.LSH :
case Token.RSH : {
int lIntValue = stack_int32(frame, stackTop-1);
int rIntValue = stack_int32(frame, stackTop);
stack[--stackTop] = DBL_MRK;
switch (op) {
case Token.BITAND:
lIntValue &= rIntValue;
break;
case Token.BITOR:
lIntValue |= rIntValue;
break;
case Token.BITXOR:
lIntValue ^= rIntValue;
break;
case Token.LSH:
lIntValue <<= rIntValue;
break;
case Token.RSH:
lIntValue >>= rIntValue;
break;
}
sDbl[stackTop] = lIntValue;
continue Loop;
}
case Token.URSH : {
double lDbl = stack_double(frame, stackTop-1);
int rIntValue = stack_int32(frame, stackTop) & 0x1F;
stack[--stackTop] = DBL_MRK;
sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue;
continue Loop;
}
case Token.NEG :
case Token.POS : {
double rDbl = stack_double(frame, stackTop);
stack[stackTop] = DBL_MRK;
if (op == Token.NEG) {
rDbl = -rDbl;
}
sDbl[stackTop] = rDbl;
continue Loop;
}
case Token.ADD :
--stackTop;
do_add(stack, sDbl, stackTop, cx);
continue Loop;
case Token.SUB :
case Token.MUL :
case Token.DIV :
case Token.MOD : {
double rDbl = stack_double(frame, stackTop);
--stackTop;
double lDbl = stack_double(frame, stackTop);
stack[stackTop] = DBL_MRK;
switch (op) {
case Token.SUB:
lDbl -= rDbl;
break;
case Token.MUL:
lDbl *= rDbl;
break;
case Token.DIV:
lDbl /= rDbl;
break;
case Token.MOD:
lDbl %= rDbl;
break;
}
sDbl[stackTop] = lDbl;
continue Loop;
}
case Token.NOT :
stack[stackTop] = ScriptRuntime.wrapBoolean(
!stack_boolean(frame, stackTop));
continue Loop;
case Token.BINDNAME :
stack[++stackTop] = ScriptRuntime.bind(cx, frame.scope, stringReg);
continue Loop;
case Token.SETNAME : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setName(lhs, rhs, cx,
frame.scope, stringReg);
continue Loop;
}
case Icode_SETCONST: {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setConst(lhs, rhs, cx, stringReg);
continue Loop;
}
case Token.DELPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.delete(lhs, rhs, cx);
continue Loop;
}
case Token.GETPROPNOWARN : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getObjectPropNoWarn(lhs, stringReg, cx);
continue Loop;
}
case Token.GETPROP : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getObjectProp(lhs, stringReg, cx);
continue Loop;
}
case Token.SETPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setObjectProp(lhs, stringReg, rhs,
cx);
continue Loop;
}
case Icode_PROP_INC_DEC : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.propIncrDecr(lhs, stringReg,
cx, iCode[frame.pc]);
++frame.pc;
continue Loop;
}
case Token.GETELEM : {
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) {
lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
}
Object value;
Object id = stack[stackTop + 1];
if (id != DBL_MRK) {
value = ScriptRuntime.getObjectElem(lhs, id, cx);
} else {
double d = sDbl[stackTop + 1];
value = ScriptRuntime.getObjectIndex(lhs, d, cx);
}
stack[stackTop] = value;
continue Loop;
}
case Token.SETELEM : {
stackTop -= 2;
Object rhs = stack[stackTop + 2];
if (rhs == DBL_MRK) {
rhs = ScriptRuntime.wrapNumber(sDbl[stackTop + 2]);
}
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) {
lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
}
Object value;
Object id = stack[stackTop + 1];
if (id != DBL_MRK) {
value = ScriptRuntime.setObjectElem(lhs, id, rhs, cx);
} else {
double d = sDbl[stackTop + 1];
value = ScriptRuntime.setObjectIndex(lhs, d, rhs, cx);
}
stack[stackTop] = value;
continue Loop;
}
case Icode_ELEM_INC_DEC: {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.elemIncrDecr(lhs, rhs, cx,
iCode[frame.pc]);
++frame.pc;
continue Loop;
}
case Token.GET_REF : {
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refGet(ref, cx);
continue Loop;
}
case Token.SET_REF : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refSet(ref, value, cx);
continue Loop;
}
case Token.DEL_REF : {
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refDel(ref, cx);
continue Loop;
}
case Icode_REF_INC_DEC : {
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refIncrDecr(ref, cx, iCode[frame.pc]);
++frame.pc;
continue Loop;
}
case Token.LOCAL_LOAD :
++stackTop;
indexReg += frame.localShift;
stack[stackTop] = stack[indexReg];
sDbl[stackTop] = sDbl[indexReg];
continue Loop;
case Icode_LOCAL_CLEAR :
indexReg += frame.localShift;
stack[indexReg] = null;
continue Loop;
case Icode_NAME_AND_THIS :
// stringReg: name
++stackTop;
stack[stackTop] = ScriptRuntime.getNameFunctionAndThis(stringReg,
cx, frame.scope);
++stackTop;
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
case Icode_PROP_AND_THIS: {
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
// stringReg: property
stack[stackTop] = ScriptRuntime.getPropFunctionAndThis(obj, stringReg,
cx);
++stackTop;
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
}
case Icode_ELEM_AND_THIS: {
Object obj = stack[stackTop - 1];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop - 1]);
Object id = stack[stackTop];
if (id == DBL_MRK) id = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop - 1] = ScriptRuntime.getElemFunctionAndThis(obj, id, cx);
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
}
case Icode_VALUE_AND_THIS : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getValueFunctionAndThis(value, cx);
++stackTop;
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
}
case Icode_CALLSPECIAL : {
if (instructionCounting) {
cx.instructionCount += INVOCATION_COST;
}
int callType = iCode[frame.pc] & 0xFF;
boolean isNew = (iCode[frame.pc + 1] != 0);
int sourceLine = getIndex(iCode, frame.pc + 2);
// indexReg: number of arguments
if (isNew) {
// stack change: function arg0 .. argN -> newResult
stackTop -= indexReg;
Object function = stack[stackTop];
if (function == DBL_MRK)
function = ScriptRuntime.wrapNumber(sDbl[stackTop]);
Object[] outArgs = getArgsArray(
stack, sDbl, stackTop + 1, indexReg);
stack[stackTop] = ScriptRuntime.newSpecial(
cx, function, outArgs, frame.scope, callType);
} else {
// stack change: function thisObj arg0 .. argN -> result
stackTop -= 1 + indexReg;
// Call code generation ensure that stack here
// is ... Callable Scriptable
Scriptable functionThis = (Scriptable)stack[stackTop + 1];
Callable function = (Callable)stack[stackTop];
Object[] outArgs = getArgsArray(
stack, sDbl, stackTop + 2, indexReg);
stack[stackTop] = ScriptRuntime.callSpecial(
cx, function, functionThis, outArgs,
frame.scope, frame.thisObj, callType,
frame.idata.itsSourceFile, sourceLine);
}
frame.pc += 4;
continue Loop;
}
case Token.CALL :
case Icode_TAIL_CALL :
case Token.REF_CALL : {
if (instructionCounting) {
cx.instructionCount += INVOCATION_COST;
}
// stack change: function thisObj arg0 .. argN -> result
// indexReg: number of arguments
stackTop -= 1 + indexReg;
// CALL generation ensures that fun and funThisObj
// are already Scriptable and Callable objects respectively
Callable fun = (Callable)stack[stackTop];
Scriptable funThisObj = (Scriptable)stack[stackTop + 1];
if (op == Token.REF_CALL) {
Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 2,
indexReg);
stack[stackTop] = ScriptRuntime.callRef(fun, funThisObj,
outArgs, cx);
continue Loop;
}
Scriptable calleeScope = frame.scope;
if (frame.useActivation) {
calleeScope = ScriptableObject.getTopLevelScope(frame.scope);
}
if (fun instanceof InterpretedFunction) {
InterpretedFunction ifun = (InterpretedFunction)fun;
if (frame.fnOrScript.securityDomain == ifun.securityDomain) {
CallFrame callParentFrame = frame;
CallFrame calleeFrame = new CallFrame();
if (op == Icode_TAIL_CALL) {
// In principle tail call can re-use the current
// frame and its stack arrays but it is hard to
// do properly. Any exceptions that can legally
// happen during frame re-initialization including
// StackOverflowException during innocent looking
// System.arraycopy may leave the current frame
// data corrupted leading to undefined behaviour
// in the catch code bellow that unwinds JS stack
// on exceptions. Then there is issue about frame release
// end exceptions there.
// To avoid frame allocation a released frame
// can be cached for re-use which would also benefit
// non-tail calls but it is not clear that this caching
// would gain in performance due to potentially
// bad interaction with GC.
callParentFrame = frame.parentFrame;
// Release the current frame. See Bug #344501 to see why
// it is being done here.
exitFrame(cx, frame, null);
}
initFrame(cx, calleeScope, funThisObj, stack, sDbl,
stackTop + 2, indexReg, ifun, callParentFrame,
calleeFrame);
if (op != Icode_TAIL_CALL) {
frame.savedStackTop = stackTop;
frame.savedCallOp = op;
}
frame = calleeFrame;
continue StateLoop;
}
}
if (fun instanceof NativeContinuation) {
// Jump to the captured continuation
ContinuationJump cjump;
cjump = new ContinuationJump((NativeContinuation)fun, frame);
// continuation result is the first argument if any
// of continuation call
if (indexReg == 0) {
cjump.result = undefined;
} else {
cjump.result = stack[stackTop + 2];
cjump.resultDbl = sDbl[stackTop + 2];
}
// Start the real unwind job
throwable = cjump;
break withoutExceptions;
}
if (fun instanceof IdFunctionObject) {
IdFunctionObject ifun = (IdFunctionObject)fun;
if (NativeContinuation.isContinuationConstructor(ifun)) {
frame.stack[stackTop] = captureContinuation(cx,
frame.parentFrame, false);
continue Loop;
}
// Bug 405654 -- make best effort to keep Function.apply and
// Function.call within this interpreter loop invocation
if (BaseFunction.isApplyOrCall(ifun)) {
Callable applyCallable = ScriptRuntime.getCallable(funThisObj);
if (applyCallable instanceof InterpretedFunction) {
InterpretedFunction iApplyCallable = (InterpretedFunction)applyCallable;
if (frame.fnOrScript.securityDomain == iApplyCallable.securityDomain) {
frame = initFrameForApplyOrCall(cx, frame, indexReg,
stack, sDbl, stackTop, op, calleeScope, ifun,
iApplyCallable);
continue StateLoop;
}
}
}
}
// Bug 447697 -- make best effort to keep __noSuchMethod__ within this
// interpreter loop invocation
if (fun instanceof NoSuchMethodShim) {
// get the shim and the actual method
NoSuchMethodShim noSuchMethodShim = (NoSuchMethodShim) fun;
Callable noSuchMethodMethod = noSuchMethodShim.noSuchMethodMethod;
// if the method is in fact an InterpretedFunction
if (noSuchMethodMethod instanceof InterpretedFunction) {
InterpretedFunction ifun = (InterpretedFunction) noSuchMethodMethod;
if (frame.fnOrScript.securityDomain == ifun.securityDomain) {
frame = initFrameForNoSuchMethod(cx, frame, indexReg, stack, sDbl,
stackTop, op, funThisObj, calleeScope,
noSuchMethodShim, ifun);
continue StateLoop;
}
}
}
cx.lastInterpreterFrame = frame;
frame.savedCallOp = op;
frame.savedStackTop = stackTop;
stack[stackTop] = fun.call(cx, calleeScope, funThisObj,
getArgsArray(stack, sDbl, stackTop + 2, indexReg));
cx.lastInterpreterFrame = null;
continue Loop;
}
case Token.NEW : {
if (instructionCounting) {
cx.instructionCount += INVOCATION_COST;
}
// stack change: function arg0 .. argN -> newResult
// indexReg: number of arguments
stackTop -= indexReg;
Object lhs = stack[stackTop];
if (lhs instanceof InterpretedFunction) {
InterpretedFunction f = (InterpretedFunction)lhs;
if (frame.fnOrScript.securityDomain == f.securityDomain) {
Scriptable newInstance = f.createObject(cx, frame.scope);
CallFrame calleeFrame = new CallFrame();
initFrame(cx, frame.scope, newInstance, stack, sDbl,
stackTop + 1, indexReg, f, frame,
calleeFrame);
stack[stackTop] = newInstance;
frame.savedStackTop = stackTop;
frame.savedCallOp = op;
frame = calleeFrame;
continue StateLoop;
}
}
if (!(lhs instanceof Function)) {
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
throw ScriptRuntime.notFunctionError(lhs);
}
Function fun = (Function)lhs;
if (fun instanceof IdFunctionObject) {
IdFunctionObject ifun = (IdFunctionObject)fun;
if (NativeContinuation.isContinuationConstructor(ifun)) {
frame.stack[stackTop] =
captureContinuation(cx, frame.parentFrame, false);
continue Loop;
}
}
Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, indexReg);
stack[stackTop] = fun.construct(cx, frame.scope, outArgs);
continue Loop;
}
case Token.TYPEOF : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.typeof(lhs);
continue Loop;
}
case Icode_TYPEOFNAME :
stack[++stackTop] = ScriptRuntime.typeofName(frame.scope, stringReg);
continue Loop;
case Token.STRING :
stack[++stackTop] = stringReg;
continue Loop;
case Icode_SHORTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getShort(iCode, frame.pc);
frame.pc += 2;
continue Loop;
case Icode_INTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getInt(iCode, frame.pc);
frame.pc += 4;
continue Loop;
case Token.NUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = frame.idata.itsDoubleTable[indexReg];
continue Loop;
case Token.NAME :
stack[++stackTop] = ScriptRuntime.name(cx, frame.scope, stringReg);
continue Loop;
case Icode_NAME_INC_DEC :
stack[++stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, stringReg,
cx, iCode[frame.pc]);
++frame.pc;
continue Loop;
case Icode_SETCONSTVAR1:
indexReg = iCode[frame.pc++];
// fallthrough
case Token.SETCONSTVAR :
if (!frame.useActivation) {
if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) {
throw Context.reportRuntimeError1("msg.var.redecl",
frame.idata.argNames[indexReg]);
}
if ((varAttributes[indexReg] & ScriptableObject.UNINITIALIZED_CONST)
!= 0)
{
vars[indexReg] = stack[stackTop];
varAttributes[indexReg] &= ~ScriptableObject.UNINITIALIZED_CONST;
varDbls[indexReg] = sDbl[stackTop];
}
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stringReg = frame.idata.argNames[indexReg];
if (frame.scope instanceof ConstProperties) {
ConstProperties cp = (ConstProperties)frame.scope;
cp.putConst(stringReg, frame.scope, val);
} else
throw Kit.codeBug();
}
continue Loop;
case Icode_SETVAR1:
indexReg = iCode[frame.pc++];
// fallthrough
case Token.SETVAR :
if (!frame.useActivation) {
if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) {
vars[indexReg] = stack[stackTop];
varDbls[indexReg] = sDbl[stackTop];
}
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stringReg = frame.idata.argNames[indexReg];
frame.scope.put(stringReg, frame.scope, val);
}
continue Loop;
case Icode_GETVAR1:
indexReg = iCode[frame.pc++];
// fallthrough
case Token.GETVAR :
++stackTop;
if (!frame.useActivation) {
stack[stackTop] = vars[indexReg];
sDbl[stackTop] = varDbls[indexReg];
} else {
stringReg = frame.idata.argNames[indexReg];
stack[stackTop] = frame.scope.get(stringReg, frame.scope);
}
continue Loop;
case Icode_VAR_INC_DEC : {
// indexReg : varindex
++stackTop;
int incrDecrMask = iCode[frame.pc];
if (!frame.useActivation) {
stack[stackTop] = DBL_MRK;
Object varValue = vars[indexReg];
double d;
if (varValue == DBL_MRK) {
d = varDbls[indexReg];
} else {
d = ScriptRuntime.toNumber(varValue);
vars[indexReg] = DBL_MRK;
}
double d2 = ((incrDecrMask & Node.DECR_FLAG) == 0)
? d + 1.0 : d - 1.0;
varDbls[indexReg] = d2;
sDbl[stackTop] = ((incrDecrMask & Node.POST_FLAG) == 0) ? d2 : d;
} else {
String varName = frame.idata.argNames[indexReg];
stack[stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, varName,
cx, incrDecrMask);
}
++frame.pc;
continue Loop;
}
case Icode_ZERO :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 0;
continue Loop;
case Icode_ONE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 1;
continue Loop;
case Token.NULL :
stack[++stackTop] = null;
continue Loop;
case Token.THIS :
stack[++stackTop] = frame.thisObj;
continue Loop;
case Token.THISFN :
stack[++stackTop] = frame.fnOrScript;
continue Loop;
case Token.FALSE :
stack[++stackTop] = Boolean.FALSE;
continue Loop;
case Token.TRUE :
stack[++stackTop] = Boolean.TRUE;
continue Loop;
case Icode_UNDEF :
stack[++stackTop] = undefined;
continue Loop;
case Token.ENTERWITH : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
frame.scope = ScriptRuntime.enterWith(lhs, cx, frame.scope);
continue Loop;
}
case Token.LEAVEWITH :
frame.scope = ScriptRuntime.leaveWith(frame.scope);
continue Loop;
case Token.CATCH_SCOPE : {
// stack top: exception object
// stringReg: name of exception variable
// indexReg: local for exception scope
--stackTop;
indexReg += frame.localShift;
boolean afterFirstScope = (frame.idata.itsICode[frame.pc] != 0);
Throwable caughtException = (Throwable)stack[stackTop + 1];
Scriptable lastCatchScope;
if (!afterFirstScope) {
lastCatchScope = null;
} else {
lastCatchScope = (Scriptable)stack[indexReg];
}
stack[indexReg] = ScriptRuntime.newCatchScope(caughtException,
lastCatchScope, stringReg,
cx, frame.scope);
++frame.pc;
continue Loop;
}
case Token.ENUM_INIT_KEYS :
case Token.ENUM_INIT_VALUES :
case Token.ENUM_INIT_ARRAY : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
indexReg += frame.localShift;
int enumType = op == Token.ENUM_INIT_KEYS
? ScriptRuntime.ENUMERATE_KEYS :
op == Token.ENUM_INIT_VALUES
? ScriptRuntime.ENUMERATE_VALUES :
ScriptRuntime.ENUMERATE_ARRAY;
stack[indexReg] = ScriptRuntime.enumInit(lhs, cx, enumType);
continue Loop;
}
case Token.ENUM_NEXT :
case Token.ENUM_ID : {
indexReg += frame.localShift;
Object val = stack[indexReg];
++stackTop;
stack[stackTop] = (op == Token.ENUM_NEXT)
? (Object)ScriptRuntime.enumNext(val)
: (Object)ScriptRuntime.enumId(val, cx);
continue Loop;
}
case Token.REF_SPECIAL : {
//stringReg: name of special property
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.specialRef(obj, stringReg, cx);
continue Loop;
}
case Token.REF_MEMBER: {
//indexReg: flags
Object elem = stack[stackTop];
if (elem == DBL_MRK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.memberRef(obj, elem, cx, indexReg);
continue Loop;
}
case Token.REF_NS_MEMBER: {
//indexReg: flags
Object elem = stack[stackTop];
if (elem == DBL_MRK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object ns = stack[stackTop];
if (ns == DBL_MRK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.memberRef(obj, ns, elem, cx, indexReg);
continue Loop;
}
case Token.REF_NAME: {
//indexReg: flags
Object name = stack[stackTop];
if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.nameRef(name, cx, frame.scope,
indexReg);
continue Loop;
}
case Token.REF_NS_NAME: {
//indexReg: flags
Object name = stack[stackTop];
if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object ns = stack[stackTop];
if (ns == DBL_MRK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.nameRef(ns, name, cx, frame.scope,
indexReg);
continue Loop;
}
case Icode_SCOPE_LOAD :
indexReg += frame.localShift;
frame.scope = (Scriptable)stack[indexReg];
continue Loop;
case Icode_SCOPE_SAVE :
indexReg += frame.localShift;
stack[indexReg] = frame.scope;
continue Loop;
case Icode_CLOSURE_EXPR :
stack[++stackTop] = InterpretedFunction.createFunction(cx, frame.scope,
frame.fnOrScript,
indexReg);
continue Loop;
case Icode_CLOSURE_STMT :
initFunction(cx, frame.scope, frame.fnOrScript, indexReg);
continue Loop;
case Token.REGEXP :
stack[++stackTop] = frame.scriptRegExps[indexReg];
continue Loop;
case Icode_LITERAL_NEW :
// indexReg: number of values in the literal
++stackTop;
stack[stackTop] = new int[indexReg];
++stackTop;
stack[stackTop] = new Object[indexReg];
sDbl[stackTop] = 0;
continue Loop;
case Icode_LITERAL_SET : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
int i = (int)sDbl[stackTop];
((Object[])stack[stackTop])[i] = value;
sDbl[stackTop] = i + 1;
continue Loop;
}
case Icode_LITERAL_GETTER : {
Object value = stack[stackTop];
--stackTop;
int i = (int)sDbl[stackTop];
((Object[])stack[stackTop])[i] = value;
((int[])stack[stackTop - 1])[i] = -1;
sDbl[stackTop] = i + 1;
continue Loop;
}
case Icode_LITERAL_SETTER : {
Object value = stack[stackTop];
--stackTop;
int i = (int)sDbl[stackTop];
((Object[])stack[stackTop])[i] = value;
((int[])stack[stackTop - 1])[i] = +1;
sDbl[stackTop] = i + 1;
continue Loop;
}
case Token.ARRAYLIT :
case Icode_SPARE_ARRAYLIT :
case Token.OBJECTLIT : {
Object[] data = (Object[])stack[stackTop];
--stackTop;
int[] getterSetters = (int[])stack[stackTop];
Object val;
if (op == Token.OBJECTLIT) {
Object[] ids = (Object[])frame.idata.literalIds[indexReg];
val = ScriptRuntime.newObjectLiteral(ids, data, getterSetters, cx,
frame.scope);
} else {
int[] skipIndexces = null;
if (op == Icode_SPARE_ARRAYLIT) {
skipIndexces = (int[])frame.idata.literalIds[indexReg];
}
val = ScriptRuntime.newArrayLiteral(data, skipIndexces, cx,
frame.scope);
}
stack[stackTop] = val;
continue Loop;
}
case Icode_ENTERDQ : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
frame.scope = ScriptRuntime.enterDotQuery(lhs, frame.scope);
continue Loop;
}
case Icode_LEAVEDQ : {
boolean valBln = stack_boolean(frame, stackTop);
Object x = ScriptRuntime.updateDotQuery(valBln, frame.scope);
if (x != null) {
stack[stackTop] = x;
frame.scope = ScriptRuntime.leaveDotQuery(frame.scope);
frame.pc += 2;
continue Loop;
}
// reset stack and PC to code after ENTERDQ
--stackTop;
break jumplessRun;
}
case Token.DEFAULTNAMESPACE : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setDefaultNamespace(value, cx);
continue Loop;
}
case Token.ESCXMLATTR : {
Object value = stack[stackTop];
if (value != DBL_MRK) {
stack[stackTop] = ScriptRuntime.escapeAttributeValue(value, cx);
}
continue Loop;
}
case Token.ESCXMLTEXT : {
Object value = stack[stackTop];
if (value != DBL_MRK) {
stack[stackTop] = ScriptRuntime.escapeTextValue(value, cx);
}
continue Loop;
}
case Icode_DEBUGGER:
if (frame.debuggerFrame != null) {
frame.debuggerFrame.onDebuggerStatement(cx);
}
continue Loop;
case Icode_LINE :
frame.pcSourceLineStart = frame.pc;
if (frame.debuggerFrame != null) {
int line = getIndex(iCode, frame.pc);
frame.debuggerFrame.onLineChange(cx, line);
}
frame.pc += 2;
continue Loop;
case Icode_REG_IND_C0:
indexReg = 0;
continue Loop;
case Icode_REG_IND_C1:
indexReg = 1;
continue Loop;
case Icode_REG_IND_C2:
indexReg = 2;
continue Loop;
case Icode_REG_IND_C3:
indexReg = 3;
continue Loop;
case Icode_REG_IND_C4:
indexReg = 4;
continue Loop;
case Icode_REG_IND_C5:
indexReg = 5;
continue Loop;
case Icode_REG_IND1:
indexReg = 0xFF & iCode[frame.pc];
++frame.pc;
continue Loop;
case Icode_REG_IND2:
indexReg = getIndex(iCode, frame.pc);
frame.pc += 2;
continue Loop;
case Icode_REG_IND4:
indexReg = getInt(iCode, frame.pc);
frame.pc += 4;
continue Loop;
case Icode_REG_STR_C0:
stringReg = strings[0];
continue Loop;
case Icode_REG_STR_C1:
stringReg = strings[1];
continue Loop;
case Icode_REG_STR_C2:
stringReg = strings[2];
continue Loop;
case Icode_REG_STR_C3:
stringReg = strings[3];
continue Loop;
case Icode_REG_STR1:
stringReg = strings[0xFF & iCode[frame.pc]];
++frame.pc;
continue Loop;
case Icode_REG_STR2:
stringReg = strings[getIndex(iCode, frame.pc)];
frame.pc += 2;
continue Loop;
case Icode_REG_STR4:
stringReg = strings[getInt(iCode, frame.pc)];
frame.pc += 4;
continue Loop;
default :
dumpICode(frame.idata);
throw new RuntimeException(
"Unknown icode : "+op+" @ pc : "+(frame.pc-1));
} // end of interpreter switch
} // end of jumplessRun label block
// This should be reachable only for jump implementation
// when pc points to encoded target offset
if (instructionCounting) {
addInstructionCount(cx, frame, 2);
}
int offset = getShort(iCode, frame.pc);
if (offset != 0) {
// -1 accounts for pc pointing to jump opcode + 1
frame.pc += offset - 1;
} else {
frame.pc = frame.idata.longJumps.
getExistingInt(frame.pc);
}
if (instructionCounting) {
frame.pcPrevBranch = frame.pc;
}
continue Loop;
} // end of Loop: for
exitFrame(cx, frame, null);
interpreterResult = frame.result;
interpreterResultDbl = frame.resultDbl;
if (frame.parentFrame != null) {
frame = frame.parentFrame;
if (frame.frozen) {
frame = frame.cloneFrozen();
}
setCallResult(
frame, interpreterResult, interpreterResultDbl);
interpreterResult = null; // Help GC
continue StateLoop;
}
break StateLoop;
} // end of interpreter withoutExceptions: try
catch (Throwable ex) {
if (throwable != null) {
// This is serious bug and it is better to track it ASAP
ex.printStackTrace(System.err);
throw new IllegalStateException();
}
throwable = ex;
}
// This should be reachable only after above catch or from
// finally when it needs to propagate exception or from
// explicit throw
if (throwable == null) Kit.codeBug();
// Exception type
final int EX_CATCH_STATE = 2; // Can execute JS catch
final int EX_FINALLY_STATE = 1; // Can execute JS finally
final int EX_NO_JS_STATE = 0; // Terminate JS execution
int exState;
ContinuationJump cjump = null;
if (generatorState != null &&
generatorState.operation == NativeGenerator.GENERATOR_CLOSE &&
throwable == generatorState.value)
{
exState = EX_FINALLY_STATE;
} else if (throwable instanceof JavaScriptException) {
exState = EX_CATCH_STATE;
} else if (throwable instanceof EcmaError) {
// an offical ECMA error object,
exState = EX_CATCH_STATE;
} else if (throwable instanceof EvaluatorException) {
exState = EX_CATCH_STATE;
} else if (throwable instanceof RuntimeException) {
exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
? EX_CATCH_STATE
: EX_FINALLY_STATE;
} else if (throwable instanceof Error) {
exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
? EX_CATCH_STATE
: EX_NO_JS_STATE;
} else if (throwable instanceof ContinuationJump) {
// It must be ContinuationJump
exState = EX_FINALLY_STATE;
cjump = (ContinuationJump)throwable;
} else {
exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
? EX_CATCH_STATE
: EX_FINALLY_STATE;
}
if (instructionCounting) {
try {
addInstructionCount(cx, frame, EXCEPTION_COST);
} catch (RuntimeException ex) {
throwable = ex;
exState = EX_FINALLY_STATE;
} catch (Error ex) {
// Error from instruction counting
// => unconditionally terminate JS
throwable = ex;
cjump = null;
exState = EX_NO_JS_STATE;
}
}
if (frame.debuggerFrame != null
&& throwable instanceof RuntimeException)
{
// Call debugger only for RuntimeException
RuntimeException rex = (RuntimeException)throwable;
try {
frame.debuggerFrame.onExceptionThrown(cx, rex);
} catch (Throwable ex) {
// Any exception from debugger
// => unconditionally terminate JS
throwable = ex;
cjump = null;
exState = EX_NO_JS_STATE;
}
}
for (;;) {
if (exState != EX_NO_JS_STATE) {
boolean onlyFinally = (exState != EX_CATCH_STATE);
indexReg = getExceptionHandler(frame, onlyFinally);
if (indexReg >= 0) {
// We caught an exception, restart the loop
// with exception pending the processing at the loop
// start
continue StateLoop;
}
}
// No allowed exception handlers in this frame, unwind
// to parent and try to look there
exitFrame(cx, frame, throwable);
frame = frame.parentFrame;
if (frame == null) { break; }
if (cjump != null && cjump.branchFrame == frame) {
// Continuation branch point was hit,
// restart the state loop to reenter continuation
indexReg = -1;
continue StateLoop;
}
}
// No more frames, rethrow the exception or deal with continuation
if (cjump != null) {
if (cjump.branchFrame != null) {
// The above loop should locate the top frame
Kit.codeBug();
}
if (cjump.capturedFrame != null) {
// Restarting detached continuation
indexReg = -1;
continue StateLoop;
}
// Return continuation result to the caller
interpreterResult = cjump.result;
interpreterResultDbl = cjump.resultDbl;
throwable = null;
}
break StateLoop;
} // end of StateLoop: for(;;)
// Do cleanups/restorations before the final return or throw
if (cx.previousInterpreterInvocations != null
&& cx.previousInterpreterInvocations.size() != 0)
{
cx.lastInterpreterFrame
= cx.previousInterpreterInvocations.pop();
} else {
// It was the last interpreter frame on the stack
cx.lastInterpreterFrame = null;
// Force GC of the value cx.previousInterpreterInvocations
cx.previousInterpreterInvocations = null;
}
if (throwable != null) {
if (throwable instanceof RuntimeException) {
throw (RuntimeException)throwable;
} else {
// Must be instance of Error or code bug
throw (Error)throwable;
}
}
return (interpreterResult != DBL_MRK)
? interpreterResult
: ScriptRuntime.wrapNumber(interpreterResultDbl);
}
|
diff --git a/src/main/java/org/mybatis/spring/SqlSessionTemplate.java b/src/main/java/org/mybatis/spring/SqlSessionTemplate.java
index f88853d3..3f65c75b 100644
--- a/src/main/java/org/mybatis/spring/SqlSessionTemplate.java
+++ b/src/main/java/org/mybatis/spring/SqlSessionTemplate.java
@@ -1,355 +1,358 @@
/*
* Copyright 2010 The myBatis Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.spring;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.ibatis.reflection.ExceptionUtil;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.util.Assert;
/**
* Thread safe, Spring managed, {@code SqlSession} that works with Spring
* transaction management to ensure that that the actual SqlSession used is the
* one associated with the current Spring transaction. In addition, it manages
* the session life-cycle, including closing, committing or rolling back the
* session as necessary based on the Spring transaction configuration.
* <p>
* The template needs a SqlSessionFactory to create SqlSessions, passed as a
* constructor argument. It also can be constructed indicating the executor type
* to be used, if not, the default executor type, defined in the session factory
* will be used.
* <p>
* This template converts MyBatis PersistenceExceptions into unchecked
* DataAccessExceptions, using, by default, a {@code MyBatisExceptionTranslator}.
* <p>
* Because SqlSessionTemplate is thread safe, a single instance can be shared
* by all DAOs; there should also be a small memory savings by doing this. This
* pattern can be used in Spring configuration files as follows:
*
* <pre class="code">
* {@code
* <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
* <constructor-arg ref="sqlSessionFactory" />
* </bean>
* }
* </pre>
*
* @see SqlSessionFactory
* @see MyBatisExceptionTranslator
* @version $Id$
*/
public class SqlSessionTemplate implements SqlSession {
private final SqlSessionFactory sqlSessionFactory;
private final ExecutorType executorType;
private final SqlSession sqlSessionProxy;
private final PersistenceExceptionTranslator exceptionTranslator;
/**
* Constructs a Spring managed SqlSession with the {@code SqlSessionFactory}
* provided as an argument.
*
* @param sqlSessionFactory
*/
public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType());
}
/**
* Constructs a Spring managed SqlSession with the {@code SqlSessionFactory}
* provided as an argument and the given {@code ExecutorType}
* {@code ExecutorType} cannot be changed once the {@code SqlSessionTemplate}
* is constructed.
*
* @param sqlSessionFactory
* @param executorType
*/
public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType) {
this(sqlSessionFactory, executorType,
new MyBatisExceptionTranslator(
sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), true));
}
/**
* Constructs a Spring managed {@code SqlSession} with the given
* {@code SqlSessionFactory} and {@code ExecutorType}.
* A custom {@code SQLExceptionTranslator} can be provided as an
* argument so any {@code PersistenceException} thrown by MyBatis
* can be custom translated to a {@code RuntimeException}
* The {@code SQLExceptionTranslator} can also be null and thus no
* exception translation will be done and MyBatis exceptions will be
* thrown
*
* @param sqlSessionFactory
* @param executorType
* @param exceptionTranslator
*/
public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType,
PersistenceExceptionTranslator exceptionTranslator) {
Assert.notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required");
Assert.notNull(executorType, "Property 'executorType' is required");
this.sqlSessionFactory = sqlSessionFactory;
this.executorType = executorType;
this.exceptionTranslator = exceptionTranslator;
this.sqlSessionProxy = (SqlSession) Proxy.newProxyInstance(
SqlSessionFactory.class.getClassLoader(),
new Class[] { SqlSession.class },
new SqlSessionInterceptor());
}
public SqlSessionFactory getSqlSessionFactory() {
return this.sqlSessionFactory;
}
public ExecutorType getExecutorType() {
return this.executorType;
}
public PersistenceExceptionTranslator getPersistenceExceptionTranslator() {
return this.exceptionTranslator;
}
/**
* {@inheritDoc}
*/
public Object selectOne(String statement) {
return this.sqlSessionProxy.selectOne(statement);
}
/**
* {@inheritDoc}
*/
public Object selectOne(String statement, Object parameter) {
return this.sqlSessionProxy.selectOne(statement, parameter);
}
/**
* {@inheritDoc}
*/
public Map<?, ?> selectMap(String statement, String mapKey) {
return this.sqlSessionProxy.selectMap(statement, mapKey);
}
/**
* {@inheritDoc}
*/
public Map<?, ?> selectMap(String statement, Object parameter, String mapKey) {
return this.sqlSessionProxy.selectMap(statement, parameter, mapKey);
}
/**
* {@inheritDoc}
*/
public Map<?, ?> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) {
return this.sqlSessionProxy.selectMap(statement, parameter, mapKey, rowBounds);
}
/**
* {@inheritDoc}
*/
public List<?> selectList(String statement) {
return this.sqlSessionProxy.selectList(statement);
}
/**
* {@inheritDoc}
*/
public List<?> selectList(String statement, Object parameter) {
return this.sqlSessionProxy.selectList(statement, parameter);
}
/**
* {@inheritDoc}
*/
public List<?> selectList(String statement, Object parameter, RowBounds rowBounds) {
return this.sqlSessionProxy.selectList(statement, parameter, rowBounds);
}
/**
* {@inheritDoc}
*/
public void select(String statement, ResultHandler handler) {
this.sqlSessionProxy.select(statement, handler);
}
/**
* {@inheritDoc}
*/
public void select(String statement, Object parameter, ResultHandler handler) {
this.sqlSessionProxy.select(statement, parameter, handler);
}
/**
* {@inheritDoc}
*/
public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
this.sqlSessionProxy.select(statement, parameter, rowBounds, handler);
}
/**
* {@inheritDoc}
*/
public int insert(String statement) {
return this.sqlSessionProxy.insert(statement);
}
/**
* {@inheritDoc}
*/
public int insert(String statement, Object parameter) {
return this.sqlSessionProxy.insert(statement, parameter);
}
/**
* {@inheritDoc}
*/
public int update(String statement) {
return this.sqlSessionProxy.update(statement);
}
/**
* {@inheritDoc}
*/
public int update(String statement, Object parameter) {
return this.sqlSessionProxy.update(statement, parameter);
}
/**
* {@inheritDoc}
*/
public int delete(String statement) {
return this.sqlSessionProxy.delete(statement);
}
/**
* {@inheritDoc}
*/
public int delete(String statement, Object parameter) {
return this.sqlSessionProxy.delete(statement, parameter);
}
/**
* {@inheritDoc}
*/
public <T> T getMapper(Class<T> type) {
return getConfiguration().getMapper(type, this);
}
/**
* {@inheritDoc}
*/
public void commit() {
throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession");
}
/**
* {@inheritDoc}
*/
public void commit(boolean force) {
throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession");
}
/**
* {@inheritDoc}
*/
public void rollback() {
throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession");
}
/**
* {@inheritDoc}
*/
public void rollback(boolean force) {
throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession");
}
/**
* {@inheritDoc}
*/
public void close() {
throw new UnsupportedOperationException("Manual close is not allowed over a Spring managed SqlSession");
}
/**
* {@inheritDoc}
*/
public void clearCache() {
this.sqlSessionProxy.clearCache();
}
/**
* {@inheritDoc}
*/
public Configuration getConfiguration() {
return this.sqlSessionFactory.getConfiguration();
}
/**
* {@inheritDoc}
*/
public Connection getConnection() {
return this.sqlSessionProxy.getConnection();
}
/**
* Proxy needed to route MyBatis method calls to the proper SqlSession got
* from String's Transaction Manager
* It also unwraps exceptions thrown by {@code Method#invoke(Object, Object...)} to
* pass a {@code PersistenceException} to the {@code PersistenceExceptionTranslator}.
*/
private class SqlSessionInterceptor implements InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
final SqlSession sqlSession = SqlSessionUtils.getSqlSession(
SqlSessionTemplate.this.sqlSessionFactory,
SqlSessionTemplate.this.executorType,
SqlSessionTemplate.this.exceptionTranslator);
try {
Object result = method.invoke(sqlSession, args);
if (!SqlSessionUtils.isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
sqlSession.commit();
}
return result;
} catch (Throwable t) {
Throwable unwrapped = ExceptionUtil.unwrapThrowable(t);
if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
- unwrapped = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped);
+ Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped);
+ if (translated != null) {
+ unwrapped = translated;
+ }
}
throw unwrapped;
} finally {
SqlSessionUtils.closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
}
}
}
}
| true | true | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
final SqlSession sqlSession = SqlSessionUtils.getSqlSession(
SqlSessionTemplate.this.sqlSessionFactory,
SqlSessionTemplate.this.executorType,
SqlSessionTemplate.this.exceptionTranslator);
try {
Object result = method.invoke(sqlSession, args);
if (!SqlSessionUtils.isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
sqlSession.commit();
}
return result;
} catch (Throwable t) {
Throwable unwrapped = ExceptionUtil.unwrapThrowable(t);
if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
unwrapped = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped);
}
throw unwrapped;
} finally {
SqlSessionUtils.closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
}
}
| public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
final SqlSession sqlSession = SqlSessionUtils.getSqlSession(
SqlSessionTemplate.this.sqlSessionFactory,
SqlSessionTemplate.this.executorType,
SqlSessionTemplate.this.exceptionTranslator);
try {
Object result = method.invoke(sqlSession, args);
if (!SqlSessionUtils.isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
sqlSession.commit();
}
return result;
} catch (Throwable t) {
Throwable unwrapped = ExceptionUtil.unwrapThrowable(t);
if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped);
if (translated != null) {
unwrapped = translated;
}
}
throw unwrapped;
} finally {
SqlSessionUtils.closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
}
}
|
diff --git a/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java b/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java
index 8fe86e2..d28ec34 100644
--- a/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java
+++ b/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java
@@ -1,280 +1,280 @@
package uk.ac.gla.dcs.tp3.w.algorithm;
import java.util.LinkedList;
import uk.ac.gla.dcs.tp3.w.league.League;
import uk.ac.gla.dcs.tp3.w.league.Match;
import uk.ac.gla.dcs.tp3.w.league.Team;
public class Graph {
private Vertex[] vertices;
private int[][] matrix;
private Vertex source;
private Vertex sink;
/**
* No param constructor to create an empty Graph object
*/
public Graph() {
this(null, null);
}
/**
* Creator method for a network flow graph
*
* Creates a graph for use inside the network flow analysis, all weights are
* established.
*
* @param l
* a populated league object.
* @param t
* the team for which the network flow is being evaluated upon.
*/
public Graph(League l, Team t) {
if (l == null || t == null)
return;
// Number of team nodes is one less than total number of teams.
// The team nodes do not include the team being tested for elimination.
int teamTotal = l.getTeams().length;
// The r-combination of teamTotal for length 2 is the number of possible
// combinations for matches between the list of Teams-{t}.
int gameTotal = comb(teamTotal - 1, 2);
// Total number of vertices is the number of teams-1 + number of match
// pairs + source + sink.
vertices = new Vertex[teamTotal + gameTotal + 1];
// Set first vertex to be source, and last vertex to be sink.
// Create blank vertices for source and sink.
source = new Vertex(0);
sink = new Vertex(vertices.length - 1);
vertices[0] = source;
vertices[vertices.length - 1] = sink;
// Create vertices for each team node, and make them adjacent to
// the sink.
Team[] teamsReal = l.getTeams();
Team[] teams = new Team[teamsReal.length - 1];
// Remove team T from the working list of Teams
int pos = 0;
for (Team to : teamsReal)
if (!to.equals(t))
teams[pos++] = to;
// Create vertex for each team pair and make it adjacent from the
// source.
// Team[i] is in vertices[vertices.length -2 -i]
pos = vertices.length - 2;
for (int i = 0; i < teams.length; i++) {
vertices[pos] = new TeamVertex(teams[i], pos);
vertices[pos].getAdjList().add(
new AdjListNode(teams[i].getUpcomingMatches().length,
vertices[vertices.length - 1]));
pos--;
}
// Create vertex for each team pair and make it adjacent from the
// source.
pos = 1;
// TODO limit this to something more sensible
int infinity = Integer.MAX_VALUE;
for (int i = 0; i < teams.length; i++) {
- for (int j = 1; j < teams.length; j++) {
+ for (int j = i+1; j < teams.length; j++) {
vertices[pos] = new PairVertex(teams[i], teams[j], pos);
vertices[pos].getAdjList().add(
new AdjListNode(infinity, vertices[vertices.length - 2
- i]));
vertices[pos].getAdjList().add(
new AdjListNode(infinity, vertices[vertices.length - 2
- j]));
vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos]));
pos++;
}
}
// For each match not yet played and not involving t, increment the
// capacity of the vertex going from float->pair node of home and away
for (Match M : l.getFixtures()) {
if (!M.isPlayed()
&& !(M.getAwayTeam().equals(t) || M.getHomeTeam().equals(t))) {
Team home = M.getHomeTeam();
Team away = M.getAwayTeam();
for (AdjListNode A : vertices[0].getAdjList()) {
if (appropriateMatch(home, away, (PairVertex) A.getVertex())) {
A.incCapacity();
}
}
}
}
// Create the adjacency matrix representation of the graph.
matrix = new int[vertices.length][vertices.length];
for (int i = 0; i < vertices.length; i++) {
for (int j = 0; j < vertices.length; j++) {
matrix[i][j] = 0;
}
}
for (Vertex v : vertices) {
for (AdjListNode n : v.getAdjList()) {
matrix[v.getIndex()][n.getVertex().getIndex()] = n
.getCapacity();
}
}
}
/**
* Checks to see if the two given Teams make up the given pair vertex
*
* @param a
* One of the teams to be checked
* @param b
* The other team to be checked
* @param PV
* The pair vertex which should be made up my the two given teams
* @return boolean showing whether or not the pair vertex contains both
* teams
*/
private static boolean appropriateMatch(Team a, Team b, PairVertex PV) {
return (PV.getTeamA().equals(a) && PV.getTeamB().equals(b))
|| PV.getTeamA().equals(b) && PV.getTeamB().equals(a);
}
/**
* Gets this Graphs vertex list
*
* @return (Vertex[]) vertices
*/
public Vertex[] getV() {
return vertices;
}
/**
* sets this Graphs vertex list.
*
* @param v
* Vertex[]
*/
public void setV(Vertex[] v) {
this.vertices = v;
}
/**
* Gets this Graphs adjacency matrix representation
*
* @return (int[][]) matrix
*/
public int[][] getMatrix() {
return matrix;
}
/**
* Sets this Graphs adjacency matrix representation
*
* @param matrix
* int[][]
*/
public void setMatrix(int[][] matrix) {
this.matrix = matrix;
}
/**
* Gets this Graphs vertices length
*
* @return (int) vertices.length
*/
public int getSize() {
return vertices.length;
}
/**
* Gets this Graphs source vertex
*
* @return (Vertex) source
*/
public Vertex getSource() {
return source;
}
/**
* Sets this Graphs source vertex
*
* @param source
* Vertex
*/
public void setSource(Vertex source) {
this.source = source;
}
/**
* Gets this Graphs sink vertex
*
* @return (Vertex) sink
*/
public Vertex getSink() {
return sink;
}
/**
* Sets this Graphs sink vertex
*
* @param sink
* Vertex
*/
public void setSink(Vertex sink) {
this.sink = sink;
}
/**
* Factorial function
*
* Function to recursively determine the factorial of a number
*
* @param s
* int
* @return int value of s!
*/
private static int fact(int s) {
// For s < 2, the factorial is 1. Otherwise, multiply s by fact(s-1)
return (s < 2) ? 1 : s * fact(s - 1);
}
/**
* N choose R function
*
* Function to determine the value of N choose R
*
* @param n
* int
* @param r
* int
* @return int value of N choose R;
*/
private static int comb(int n, int r) {
// r-combination of size n is n!/r!(n-r)!
return (fact(n) / (fact(r) * fact(n - r)));
}
/**
* carry out a breadth first search/traversal of the graph
*/
public void bfs() {
// TODO Read over this code, I (GR) just dropped this in here from
// bfs-example.
for (Vertex v : vertices)
v.setVisited(false);
LinkedList<Vertex> queue = new LinkedList<Vertex>();
for (Vertex v : vertices) {
if (!v.getVisited()) {
v.setVisited(true);
v.setPredecessor(v.getIndex());
queue.add(v);
while (!queue.isEmpty()) {
Vertex u = queue.removeFirst();
LinkedList<AdjListNode> list = u.getAdjList();
for (AdjListNode node : list) {
Vertex w = node.getVertex();
if (!w.getVisited()) {
w.setVisited(true);
w.setPredecessor(u.getIndex());
queue.add(w);
}
}
}
}
}
}
}
| true | true | public Graph(League l, Team t) {
if (l == null || t == null)
return;
// Number of team nodes is one less than total number of teams.
// The team nodes do not include the team being tested for elimination.
int teamTotal = l.getTeams().length;
// The r-combination of teamTotal for length 2 is the number of possible
// combinations for matches between the list of Teams-{t}.
int gameTotal = comb(teamTotal - 1, 2);
// Total number of vertices is the number of teams-1 + number of match
// pairs + source + sink.
vertices = new Vertex[teamTotal + gameTotal + 1];
// Set first vertex to be source, and last vertex to be sink.
// Create blank vertices for source and sink.
source = new Vertex(0);
sink = new Vertex(vertices.length - 1);
vertices[0] = source;
vertices[vertices.length - 1] = sink;
// Create vertices for each team node, and make them adjacent to
// the sink.
Team[] teamsReal = l.getTeams();
Team[] teams = new Team[teamsReal.length - 1];
// Remove team T from the working list of Teams
int pos = 0;
for (Team to : teamsReal)
if (!to.equals(t))
teams[pos++] = to;
// Create vertex for each team pair and make it adjacent from the
// source.
// Team[i] is in vertices[vertices.length -2 -i]
pos = vertices.length - 2;
for (int i = 0; i < teams.length; i++) {
vertices[pos] = new TeamVertex(teams[i], pos);
vertices[pos].getAdjList().add(
new AdjListNode(teams[i].getUpcomingMatches().length,
vertices[vertices.length - 1]));
pos--;
}
// Create vertex for each team pair and make it adjacent from the
// source.
pos = 1;
// TODO limit this to something more sensible
int infinity = Integer.MAX_VALUE;
for (int i = 0; i < teams.length; i++) {
for (int j = 1; j < teams.length; j++) {
vertices[pos] = new PairVertex(teams[i], teams[j], pos);
vertices[pos].getAdjList().add(
new AdjListNode(infinity, vertices[vertices.length - 2
- i]));
vertices[pos].getAdjList().add(
new AdjListNode(infinity, vertices[vertices.length - 2
- j]));
vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos]));
pos++;
}
}
// For each match not yet played and not involving t, increment the
// capacity of the vertex going from float->pair node of home and away
for (Match M : l.getFixtures()) {
if (!M.isPlayed()
&& !(M.getAwayTeam().equals(t) || M.getHomeTeam().equals(t))) {
Team home = M.getHomeTeam();
Team away = M.getAwayTeam();
for (AdjListNode A : vertices[0].getAdjList()) {
if (appropriateMatch(home, away, (PairVertex) A.getVertex())) {
A.incCapacity();
}
}
}
}
// Create the adjacency matrix representation of the graph.
matrix = new int[vertices.length][vertices.length];
for (int i = 0; i < vertices.length; i++) {
for (int j = 0; j < vertices.length; j++) {
matrix[i][j] = 0;
}
}
for (Vertex v : vertices) {
for (AdjListNode n : v.getAdjList()) {
matrix[v.getIndex()][n.getVertex().getIndex()] = n
.getCapacity();
}
}
}
| public Graph(League l, Team t) {
if (l == null || t == null)
return;
// Number of team nodes is one less than total number of teams.
// The team nodes do not include the team being tested for elimination.
int teamTotal = l.getTeams().length;
// The r-combination of teamTotal for length 2 is the number of possible
// combinations for matches between the list of Teams-{t}.
int gameTotal = comb(teamTotal - 1, 2);
// Total number of vertices is the number of teams-1 + number of match
// pairs + source + sink.
vertices = new Vertex[teamTotal + gameTotal + 1];
// Set first vertex to be source, and last vertex to be sink.
// Create blank vertices for source and sink.
source = new Vertex(0);
sink = new Vertex(vertices.length - 1);
vertices[0] = source;
vertices[vertices.length - 1] = sink;
// Create vertices for each team node, and make them adjacent to
// the sink.
Team[] teamsReal = l.getTeams();
Team[] teams = new Team[teamsReal.length - 1];
// Remove team T from the working list of Teams
int pos = 0;
for (Team to : teamsReal)
if (!to.equals(t))
teams[pos++] = to;
// Create vertex for each team pair and make it adjacent from the
// source.
// Team[i] is in vertices[vertices.length -2 -i]
pos = vertices.length - 2;
for (int i = 0; i < teams.length; i++) {
vertices[pos] = new TeamVertex(teams[i], pos);
vertices[pos].getAdjList().add(
new AdjListNode(teams[i].getUpcomingMatches().length,
vertices[vertices.length - 1]));
pos--;
}
// Create vertex for each team pair and make it adjacent from the
// source.
pos = 1;
// TODO limit this to something more sensible
int infinity = Integer.MAX_VALUE;
for (int i = 0; i < teams.length; i++) {
for (int j = i+1; j < teams.length; j++) {
vertices[pos] = new PairVertex(teams[i], teams[j], pos);
vertices[pos].getAdjList().add(
new AdjListNode(infinity, vertices[vertices.length - 2
- i]));
vertices[pos].getAdjList().add(
new AdjListNode(infinity, vertices[vertices.length - 2
- j]));
vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos]));
pos++;
}
}
// For each match not yet played and not involving t, increment the
// capacity of the vertex going from float->pair node of home and away
for (Match M : l.getFixtures()) {
if (!M.isPlayed()
&& !(M.getAwayTeam().equals(t) || M.getHomeTeam().equals(t))) {
Team home = M.getHomeTeam();
Team away = M.getAwayTeam();
for (AdjListNode A : vertices[0].getAdjList()) {
if (appropriateMatch(home, away, (PairVertex) A.getVertex())) {
A.incCapacity();
}
}
}
}
// Create the adjacency matrix representation of the graph.
matrix = new int[vertices.length][vertices.length];
for (int i = 0; i < vertices.length; i++) {
for (int j = 0; j < vertices.length; j++) {
matrix[i][j] = 0;
}
}
for (Vertex v : vertices) {
for (AdjListNode n : v.getAdjList()) {
matrix[v.getIndex()][n.getVertex().getIndex()] = n
.getCapacity();
}
}
}
|
diff --git a/illamapedit/src/illarion/mapedit/render/GridRenderer.java b/illamapedit/src/illarion/mapedit/render/GridRenderer.java
index 890c3a42..d804988f 100644
--- a/illamapedit/src/illarion/mapedit/render/GridRenderer.java
+++ b/illamapedit/src/illarion/mapedit/render/GridRenderer.java
@@ -1,78 +1,78 @@
/*
* This file is part of the Illarion Mapeditor.
*
* Copyright © 2012 - Illarion e.V.
*
* The Illarion Mapeditor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The Illarion Mapeditor 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 Mapeditor. If not, see <http://www.gnu.org/licenses/>.
*/
package illarion.mapedit.render;
import illarion.common.util.Location;
import illarion.mapedit.data.Map;
import java.awt.*;
import java.awt.geom.AffineTransform;
/**
* This method renders the grid, to see the tiles better.
*
* @author Tim
*/
public class GridRenderer extends AbstractMapRenderer {
/**
* Creates a new map renderer
*/
public GridRenderer(final RendererManager manager) {
super(manager);
}
@Override
public void renderMap(final Graphics2D g) {
final Map map = getMap();
final int width = map.getWidth();
final int height = map.getHeight();
final AffineTransform transform = g.getTransform();
g.translate(getTranslateX(), getTranslateY() + ((getTileHeight() + 1) * getZoom()));
g.scale(getZoom(), getZoom());
g.setColor(Color.LIGHT_GRAY);
- for (int x = 0; x <= width; ++x) {
+ for (int x = 0; x <= height; ++x) {
g.drawLine(
Location.displayCoordinateX(x, 0, 0),
Location.displayCoordinateY(x, 0, 0),
Location.displayCoordinateX(x, width, 0),
Location.displayCoordinateY(x, width, 0));
}
- for (int y = 0; y <= height; ++y) {
+ for (int y = 0; y <= width; ++y) {
g.drawLine(
Location.displayCoordinateX(0, y, 0),
Location.displayCoordinateY(0, y, 0),
Location.displayCoordinateX(height, y, 0),
Location.displayCoordinateY(height, y, 0));
}
g.setTransform(transform);
}
@Override
protected int getRenderPriority() {
return 6;
}
}
| false | true | public void renderMap(final Graphics2D g) {
final Map map = getMap();
final int width = map.getWidth();
final int height = map.getHeight();
final AffineTransform transform = g.getTransform();
g.translate(getTranslateX(), getTranslateY() + ((getTileHeight() + 1) * getZoom()));
g.scale(getZoom(), getZoom());
g.setColor(Color.LIGHT_GRAY);
for (int x = 0; x <= width; ++x) {
g.drawLine(
Location.displayCoordinateX(x, 0, 0),
Location.displayCoordinateY(x, 0, 0),
Location.displayCoordinateX(x, width, 0),
Location.displayCoordinateY(x, width, 0));
}
for (int y = 0; y <= height; ++y) {
g.drawLine(
Location.displayCoordinateX(0, y, 0),
Location.displayCoordinateY(0, y, 0),
Location.displayCoordinateX(height, y, 0),
Location.displayCoordinateY(height, y, 0));
}
g.setTransform(transform);
}
| public void renderMap(final Graphics2D g) {
final Map map = getMap();
final int width = map.getWidth();
final int height = map.getHeight();
final AffineTransform transform = g.getTransform();
g.translate(getTranslateX(), getTranslateY() + ((getTileHeight() + 1) * getZoom()));
g.scale(getZoom(), getZoom());
g.setColor(Color.LIGHT_GRAY);
for (int x = 0; x <= height; ++x) {
g.drawLine(
Location.displayCoordinateX(x, 0, 0),
Location.displayCoordinateY(x, 0, 0),
Location.displayCoordinateX(x, width, 0),
Location.displayCoordinateY(x, width, 0));
}
for (int y = 0; y <= width; ++y) {
g.drawLine(
Location.displayCoordinateX(0, y, 0),
Location.displayCoordinateY(0, y, 0),
Location.displayCoordinateX(height, y, 0),
Location.displayCoordinateY(height, y, 0));
}
g.setTransform(transform);
}
|
diff --git a/src/uk/me/parabola/mkgmap/main/Main.java b/src/uk/me/parabola/mkgmap/main/Main.java
index bfaf53ed..cba28192 100644
--- a/src/uk/me/parabola/mkgmap/main/Main.java
+++ b/src/uk/me/parabola/mkgmap/main/Main.java
@@ -1,370 +1,371 @@
/*
* Copyright (C) 2007 Steve Ratcliffe
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* 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.
*
*
* Author: Steve Ratcliffe
* Create date: 24-Sep-2007
*/
package uk.me.parabola.mkgmap.main;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
import uk.me.parabola.imgfmt.ExitException;
import uk.me.parabola.log.Logger;
import uk.me.parabola.mkgmap.ArgumentProcessor;
import uk.me.parabola.mkgmap.CommandArgs;
import uk.me.parabola.mkgmap.CommandArgsReader;
import uk.me.parabola.mkgmap.Version;
import uk.me.parabola.mkgmap.combiners.Combiner;
import uk.me.parabola.mkgmap.combiners.FileInfo;
import uk.me.parabola.mkgmap.combiners.GmapsuppBuilder;
import uk.me.parabola.mkgmap.combiners.TdbBuilder;
import uk.me.parabola.mkgmap.osmstyle.StyleFileLoader;
import uk.me.parabola.mkgmap.osmstyle.StyleImpl;
import uk.me.parabola.mkgmap.osmstyle.eval.SyntaxException;
import uk.me.parabola.mkgmap.reader.osm.Style;
import uk.me.parabola.mkgmap.reader.osm.StyleInfo;
import uk.me.parabola.mkgmap.reader.overview.OverviewMapDataSource;
/**
* The new main program. There can be many filenames to process and there can
* be differing outputs determined by options. So the actual work is mostly
* done in other classes. This one just works out what is wanted.
*
* @author Steve Ratcliffe
*/
public class Main implements ArgumentProcessor {
private static final Logger log = Logger.getLogger(Main.class);
private final MapProcessor maker = new MapMaker();
// Final .img file combiners.
private final List<Combiner> combiners = new ArrayList<Combiner>();
private final Map<String, MapProcessor> processMap = new HashMap<String, MapProcessor>();
private String styleFile = "classpath:styles";
private boolean verbose;
private final List<Future<String>> futures = new LinkedList<Future<String>>();
private ExecutorService threadPool;
// default number of threads
private int maxJobs = 1;
/**
* The main program to make or combine maps. We now use a two pass process,
* first going through the arguments and make any maps and collect names
* to be used for creating summary files like the TDB and gmapsupp.
*
* @param args The command line arguments.
*/
public static void main(String[] args) {
// We need at least one argument.
if (args.length < 1) {
System.err.println("Usage: mkgmap [options...] <file.osm>");
printHelp(System.err, getLang(), "options");
return;
}
Main mm = new Main();
try {
// Read the command line arguments and process each filename found.
CommandArgsReader commandArgs = new CommandArgsReader(mm);
commandArgs.readArgs(args);
} catch (ExitException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
/**
* Grab the options help file and print it.
* @param err The output print stream to write to.
* @param lang A language hint. The help will be displayed in this
* language if it has been translated.
* @param file The help file to display.
*/
private static void printHelp(PrintStream err, String lang, String file) {
String path = "/help/" + lang + '/' + file;
InputStream stream = Main.class.getResourceAsStream(path);
if (stream == null) {
err.println("Could not find the help topic: " + file + ", sorry");
return;
}
BufferedReader r = new BufferedReader(new InputStreamReader(stream));
try {
String line;
while ((line = r.readLine()) != null)
err.println(line);
} catch (IOException e) {
err.println("Could not read the help topic: " + file + ", sorry");
}
}
public void startOptions() {
MapProcessor saver = new NameSaver();
processMap.put("img", saver);
// Todo: instead of the direct saver, modify the file with the correct
// family-id etc.
processMap.put("typ", saver);
// Normal map files.
processMap.put("rgn", saver);
processMap.put("tre", saver);
processMap.put("lbl", saver);
processMap.put("net", saver);
processMap.put("nod", saver);
}
/**
* Switch out to the appropriate class to process the filename.
*
* @param args The command arguments.
* @param filename The filename to process.
*/
public void processFilename(final CommandArgs args, final String filename) {
final String ext = extractExtension(filename);
log.debug("file", filename, ", extension is", ext);
final MapProcessor mp = mapMaker(ext);
if(threadPool == null) {
log.info("Creating thread pool with " + maxJobs + " threads");
threadPool = Executors.newFixedThreadPool(maxJobs);
}
log.info("Submitting job " + filename);
futures.add(threadPool.submit(new Callable<String>() {
public String call() {
String output = mp.makeMap(args, filename);
log.debug("adding output name", output);
return output;
}
}));
}
private MapProcessor mapMaker(String ext) {
MapProcessor mp = processMap.get(ext);
if (mp == null)
mp = maker;
return mp;
}
public void processOption(String opt, String val) {
log.debug("option:", opt, val);
if (opt.equals("number-of-files")) {
// This option always appears first. We use it to turn on/off
// generation of the overview files if there is only one file
// to process.
int n = Integer.valueOf(val);
if (n > 1)
addTdbBuilder();
} else if (opt.equals("tdbfile")) {
addTdbBuilder();
} else if (opt.equals("gmapsupp")) {
addCombiner(new GmapsuppBuilder());
} else if (opt.equals("help")) {
printHelp(System.out, getLang(), (val.length() > 0) ? val : "help");
} else if (opt.equals("style-file") || opt.equals("map-features")) {
styleFile = val;
} else if (opt.equals("verbose")) {
verbose = true;
} else if (opt.equals("list-styles")) {
listStyles();
} else if (opt.equals("max-jobs")) {
if(val.length() > 0)
maxJobs = Integer.parseInt(val);
else
maxJobs = Runtime.getRuntime().availableProcessors();
if(maxJobs < 1) {
log.warn("max-jobs has to be at least 1");
maxJobs = 1;
}
} else if (opt.equals("version")) {
System.err.println(Version.VERSION);
System.exit(0);
}
}
private void addTdbBuilder() {
TdbBuilder builder = new TdbBuilder();
builder.setOverviewSource(new OverviewMapDataSource());
addCombiner(builder);
}
private void listStyles() {
String[] names;
try {
StyleFileLoader loader = StyleFileLoader.createStyleLoader(styleFile, null);
names = loader.list();
loader.close();
} catch (FileNotFoundException e) {
log.debug("didn't find style file", e);
throw new ExitException("Could not list style file " + styleFile);
}
Arrays.sort(names);
System.out.println("The following styles are available:");
for (String name : names) {
Style style;
try {
style = new StyleImpl(styleFile, name);
} catch (SyntaxException e) {
System.err.println("Error in style: " + e.getMessage());
continue;
} catch (FileNotFoundException e) {
log.debug("could not find style", name);
try {
style = new StyleImpl(styleFile, null);
} catch (SyntaxException e1) {
System.err.println("Error in style: " + e1.getMessage());
continue;
} catch (FileNotFoundException e1) {
log.debug("could not find style", styleFile);
continue;
}
}
StyleInfo info = style.getInfo();
System.out.format("%-15s %6s: %s\n",
name,info.getVersion(), info.getSummary());
if (verbose) {
for (String s : info.getLongDescription().split("\n"))
System.out.printf("\t%s\n", s.trim());
}
}
}
private static String getLang() {
return "en";
}
private void addCombiner(Combiner combiner) {
combiners.add(combiner);
}
public void endOptions(CommandArgs args) {
List<String> filenames = new ArrayList<String>();
if(threadPool != null) {
threadPool.shutdown();
while(!futures.isEmpty()) {
try {
try {
// don't call get() until a job has finished
if(futures.get(0).isDone())
filenames.add(futures.remove(0).get());
else
Thread.sleep(10);
} catch (ExecutionException e) {
// Re throw the underlying exception
Throwable cause = e.getCause();
if (cause instanceof Exception)
throw (Exception) cause;
else
throw e;
}
} catch (Exception e) {
- if (args.getProperties().getProperty("keep-going", false)) {
+ if(args.getProperties().getProperty("keep-going", false)) {
System.err.println("ERROR: " + e.getMessage());
- System.err.println(" continuing regardless because --keep-going was given");
- } else {
- throw (RuntimeException) e;
+ }
+ else {
+ System.err.println("Exiting - if you want to carry on regardless, use the --keep-going option");
+ throw new ExitException(e.getMessage());
}
}
}
}
if (combiners.isEmpty())
return;
log.info("Combining maps");
// Get them all set up.
for (Combiner c : combiners)
c.init(args);
// Tell them about each filename
for (String file : filenames) {
if (file == null)
continue;
try {
log.info(" " + file);
FileInfo mapReader = FileInfo.getFileInfo(file);
for (Combiner c : combiners) {
c.onMapEnd(mapReader);
}
} catch (FileNotFoundException e) {
log.error("could not open file", e);
}
}
// All done, allow tidy up or file creation to happen
for (Combiner c : combiners) {
c.onFinish();
}
}
/**
* Get the extension of the filename, ignoring any compression suffix.
*
* @param filename The original filename.
* @return The file extension.
*/
private String extractExtension(String filename) {
String[] parts = filename.toLowerCase(Locale.ENGLISH).split("\\.");
List<String> ignore = Arrays.asList("gz", "bz2", "bz");
// We want the last part that is not gz, bz etc (and isn't the first part ;)
for (int i = parts.length - 1; i > 0; i--) {
String ext = parts[i];
if (!ignore.contains(ext))
return ext;
}
return "";
}
/**
* A null implementation that just returns the input name as the output.
*/
private static class NameSaver implements MapProcessor {
public String makeMap(CommandArgs args, String filename) {
return filename;
}
}
}
| false | true | public void endOptions(CommandArgs args) {
List<String> filenames = new ArrayList<String>();
if(threadPool != null) {
threadPool.shutdown();
while(!futures.isEmpty()) {
try {
try {
// don't call get() until a job has finished
if(futures.get(0).isDone())
filenames.add(futures.remove(0).get());
else
Thread.sleep(10);
} catch (ExecutionException e) {
// Re throw the underlying exception
Throwable cause = e.getCause();
if (cause instanceof Exception)
throw (Exception) cause;
else
throw e;
}
} catch (Exception e) {
if (args.getProperties().getProperty("keep-going", false)) {
System.err.println("ERROR: " + e.getMessage());
System.err.println(" continuing regardless because --keep-going was given");
} else {
throw (RuntimeException) e;
}
}
}
}
if (combiners.isEmpty())
return;
log.info("Combining maps");
// Get them all set up.
for (Combiner c : combiners)
c.init(args);
// Tell them about each filename
for (String file : filenames) {
if (file == null)
continue;
try {
log.info(" " + file);
FileInfo mapReader = FileInfo.getFileInfo(file);
for (Combiner c : combiners) {
c.onMapEnd(mapReader);
}
} catch (FileNotFoundException e) {
log.error("could not open file", e);
}
}
// All done, allow tidy up or file creation to happen
for (Combiner c : combiners) {
c.onFinish();
}
}
| public void endOptions(CommandArgs args) {
List<String> filenames = new ArrayList<String>();
if(threadPool != null) {
threadPool.shutdown();
while(!futures.isEmpty()) {
try {
try {
// don't call get() until a job has finished
if(futures.get(0).isDone())
filenames.add(futures.remove(0).get());
else
Thread.sleep(10);
} catch (ExecutionException e) {
// Re throw the underlying exception
Throwable cause = e.getCause();
if (cause instanceof Exception)
throw (Exception) cause;
else
throw e;
}
} catch (Exception e) {
if(args.getProperties().getProperty("keep-going", false)) {
System.err.println("ERROR: " + e.getMessage());
}
else {
System.err.println("Exiting - if you want to carry on regardless, use the --keep-going option");
throw new ExitException(e.getMessage());
}
}
}
}
if (combiners.isEmpty())
return;
log.info("Combining maps");
// Get them all set up.
for (Combiner c : combiners)
c.init(args);
// Tell them about each filename
for (String file : filenames) {
if (file == null)
continue;
try {
log.info(" " + file);
FileInfo mapReader = FileInfo.getFileInfo(file);
for (Combiner c : combiners) {
c.onMapEnd(mapReader);
}
} catch (FileNotFoundException e) {
log.error("could not open file", e);
}
}
// All done, allow tidy up or file creation to happen
for (Combiner c : combiners) {
c.onFinish();
}
}
|
diff --git a/src/com/herocraftonline/dev/heroes/skill/skills/SkillDrainsoul.java b/src/com/herocraftonline/dev/heroes/skill/skills/SkillDrainsoul.java
index 26eda57b..6f70d644 100644
--- a/src/com/herocraftonline/dev/heroes/skill/skills/SkillDrainsoul.java
+++ b/src/com/herocraftonline/dev/heroes/skill/skills/SkillDrainsoul.java
@@ -1,61 +1,60 @@
package com.herocraftonline.dev.heroes.skill.skills;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.util.config.ConfigurationNode;
import com.herocraftonline.dev.heroes.Heroes;
import com.herocraftonline.dev.heroes.persistence.Hero;
import com.herocraftonline.dev.heroes.skill.TargettedSkill;
import com.herocraftonline.dev.heroes.util.Messaging;
public class SkillDrainsoul extends TargettedSkill {
public SkillDrainsoul(Heroes plugin) {
super(plugin);
setName("Drainsoul");
setDescription("Absorb health from target");
setUsage("/skill drainsoul <target>");
setMinArgs(0);
setMaxArgs(1);
getIdentifiers().add("skill drainsoul");
}
@Override
public ConfigurationNode getDefaultConfig() {
ConfigurationNode node = super.getDefaultConfig();
node.setProperty("absorb-amount", 4);
return node;
}
@Override
public boolean use(Hero hero, LivingEntity target, String[] args) {
Player player = hero.getPlayer();
if (target.equals(hero.getPlayer())) {
Messaging.send(player, "You need a target!");
return false;
}
// Throw a dummy damage event to make it obey PvP restricting plugins
EntityDamageEvent event = new EntityDamageByEntityEvent(player, target, DamageCause.CUSTOM, 0);
plugin.getServer().getPluginManager().callEvent(event);
- if (event.isCancelled())
- return false;
+ if (event.isCancelled()) return false;
int absorbAmount = getSetting(hero.getHeroClass(), "absorb-amount", 4);
- hero.setHealth((double) absorbAmount);
+ hero.setHealth(hero.getHealth() + (double) absorbAmount);
hero.syncHealth();
plugin.getDamageManager().addSpellTarget((Entity) target);
target.damage(absorbAmount, player);
broadcastExecuteText(hero, target);
return true;
}
}
| false | true | public boolean use(Hero hero, LivingEntity target, String[] args) {
Player player = hero.getPlayer();
if (target.equals(hero.getPlayer())) {
Messaging.send(player, "You need a target!");
return false;
}
// Throw a dummy damage event to make it obey PvP restricting plugins
EntityDamageEvent event = new EntityDamageByEntityEvent(player, target, DamageCause.CUSTOM, 0);
plugin.getServer().getPluginManager().callEvent(event);
if (event.isCancelled())
return false;
int absorbAmount = getSetting(hero.getHeroClass(), "absorb-amount", 4);
hero.setHealth((double) absorbAmount);
hero.syncHealth();
plugin.getDamageManager().addSpellTarget((Entity) target);
target.damage(absorbAmount, player);
broadcastExecuteText(hero, target);
return true;
}
| public boolean use(Hero hero, LivingEntity target, String[] args) {
Player player = hero.getPlayer();
if (target.equals(hero.getPlayer())) {
Messaging.send(player, "You need a target!");
return false;
}
// Throw a dummy damage event to make it obey PvP restricting plugins
EntityDamageEvent event = new EntityDamageByEntityEvent(player, target, DamageCause.CUSTOM, 0);
plugin.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) return false;
int absorbAmount = getSetting(hero.getHeroClass(), "absorb-amount", 4);
hero.setHealth(hero.getHealth() + (double) absorbAmount);
hero.syncHealth();
plugin.getDamageManager().addSpellTarget((Entity) target);
target.damage(absorbAmount, player);
broadcastExecuteText(hero, target);
return true;
}
|
diff --git a/common/src/org/riotfamily/common/mapping/ReverseUrlHanderMappingAdapter.java b/common/src/org/riotfamily/common/mapping/ReverseUrlHanderMappingAdapter.java
index c1d7ae69d..816484bcc 100644
--- a/common/src/org/riotfamily/common/mapping/ReverseUrlHanderMappingAdapter.java
+++ b/common/src/org/riotfamily/common/mapping/ReverseUrlHanderMappingAdapter.java
@@ -1,132 +1,132 @@
/* 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.riotfamily.common.mapping;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.riotfamily.common.beans.property.MapPropertyAccessor;
import org.riotfamily.common.util.Generics;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.PropertyAccessor;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping;
public class ReverseUrlHanderMappingAdapter implements ReverseHandlerMappingAdapter {
private String servletPrefix = "";
public void setServletPrefix(String servletPrefix) {
this.servletPrefix = servletPrefix;
}
public boolean supports(HandlerMapping mapping) {
return mapping instanceof AbstractUrlHandlerMapping;
}
public ReverseHandlerMapping adapt(HandlerMapping mapping) {
return new ReverseUrlHandlerMapping((AbstractUrlHandlerMapping) mapping);
}
private class ReverseUrlHandlerMapping implements ReverseHandlerMapping {
private Map<String, List<HandlerUrl>> urlMap = Generics.newHashMap();
private ApplicationContext context;
@SuppressWarnings("unchecked")
public ReverseUrlHandlerMapping(AbstractUrlHandlerMapping mapping) {
context = mapping.getApplicationContext();
Map<String, ?> handlers = mapping.getHandlerMap();
for (Map.Entry<String,?> entry : handlers.entrySet()) {
String url = entry.getKey();
Object handler = entry.getValue();
String handlerName = getHandlerName(handler);
List<HandlerUrl> urls = urlMap.get(handlerName);
if (urls == null) {
urls = Generics.newLinkedList();
urlMap.put(handlerName, urls);
}
urls.add(new HandlerUrl(url));
Collections.sort(urls);
}
}
private String getHandlerName(Object handler) {
if (handler instanceof String) {
return (String) handler;
}
Map<String, ?> beans = context.getBeansOfType(
handler.getClass(), false, false);
for (Map.Entry<String, ?> entry : beans.entrySet()) {
if (entry.getValue().equals(handler)) {
return entry.getKey();
}
}
return null;
}
public String getUrlForHandler(String name, Object... vars) {
List<HandlerUrl> urls = urlMap.get(name);
if (urls != null) {
if (vars != null && vars.length == 1) {
Object var = vars[0];
if (var instanceof Map<?, ?>) {
return getUrl(urls, new MapPropertyAccessor((Map<?, ?>) var));
}
if (var instanceof Collection<?>) {
return getUrl(urls, (Collection<?>) var);
}
if (var.getClass().isArray()) {
return getUrl(urls, CollectionUtils.arrayToList(var));
}
if (var instanceof String
|| ClassUtils.isPrimitiveOrWrapper(var.getClass())) {
- return getUrl(urls, Collections.singletonList(vars));
+ return getUrl(urls, Collections.singletonList(var));
}
return getUrl(urls, new BeanWrapperImpl(var));
}
return getUrl(urls, CollectionUtils.arrayToList(vars));
}
return null;
}
private String getUrl(List<HandlerUrl> urls, PropertyAccessor pa) {
for (HandlerUrl uri : urls) {
if (uri.canFillIn(pa)) {
return servletPrefix + uri.fillIn(pa);
}
}
return null;
}
private String getUrl(List<HandlerUrl> urls, Collection<?> values) {
for (HandlerUrl uri : urls) {
if (uri.canFillIn(values)) {
return servletPrefix + uri.fillIn(values);
}
}
return null;
}
}
}
| true | true | public String getUrlForHandler(String name, Object... vars) {
List<HandlerUrl> urls = urlMap.get(name);
if (urls != null) {
if (vars != null && vars.length == 1) {
Object var = vars[0];
if (var instanceof Map<?, ?>) {
return getUrl(urls, new MapPropertyAccessor((Map<?, ?>) var));
}
if (var instanceof Collection<?>) {
return getUrl(urls, (Collection<?>) var);
}
if (var.getClass().isArray()) {
return getUrl(urls, CollectionUtils.arrayToList(var));
}
if (var instanceof String
|| ClassUtils.isPrimitiveOrWrapper(var.getClass())) {
return getUrl(urls, Collections.singletonList(vars));
}
return getUrl(urls, new BeanWrapperImpl(var));
}
return getUrl(urls, CollectionUtils.arrayToList(vars));
}
return null;
}
| public String getUrlForHandler(String name, Object... vars) {
List<HandlerUrl> urls = urlMap.get(name);
if (urls != null) {
if (vars != null && vars.length == 1) {
Object var = vars[0];
if (var instanceof Map<?, ?>) {
return getUrl(urls, new MapPropertyAccessor((Map<?, ?>) var));
}
if (var instanceof Collection<?>) {
return getUrl(urls, (Collection<?>) var);
}
if (var.getClass().isArray()) {
return getUrl(urls, CollectionUtils.arrayToList(var));
}
if (var instanceof String
|| ClassUtils.isPrimitiveOrWrapper(var.getClass())) {
return getUrl(urls, Collections.singletonList(var));
}
return getUrl(urls, new BeanWrapperImpl(var));
}
return getUrl(urls, CollectionUtils.arrayToList(vars));
}
return null;
}
|
diff --git a/splat/src/main/uk/ac/starlink/splat/vo/SSAMetadataFrame.java b/splat/src/main/uk/ac/starlink/splat/vo/SSAMetadataFrame.java
index d0dde504..d70ebacf 100644
--- a/splat/src/main/uk/ac/starlink/splat/vo/SSAMetadataFrame.java
+++ b/splat/src/main/uk/ac/starlink/splat/vo/SSAMetadataFrame.java
@@ -1,790 +1,790 @@
/*
* Copyright (C) 2001-2005 Central Laboratory of the Research Councils
* Copyright (C) 2008 Science and Technology Facilities Council
*
* History:
* 23-FEB-2012 (Margarida Castro Neves [email protected])
* Original version.
*/
package uk.ac.starlink.splat.vo;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.BufferedReader;
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 java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import uk.ac.starlink.splat.iface.HelpFrame;
import uk.ac.starlink.splat.iface.images.ImageHolder;
import uk.ac.starlink.splat.util.SplatCommunicator;
import uk.ac.starlink.splat.util.Transmitter;
import uk.ac.starlink.splat.util.Utilities;
import uk.ac.starlink.util.gui.BasicFileChooser;
import uk.ac.starlink.util.gui.BasicFileFilter;
import uk.ac.starlink.util.gui.ErrorDialog;
import uk.ac.starlink.splat.vo.SSAQueryBrowser.LocalAction;
import uk.ac.starlink.splat.vo.SSAQueryBrowser.MetadataInputParameter;
import uk.ac.starlink.splat.vo.SSAQueryBrowser.ResolverAction;
/**
* Class SSAMetadataServerFrame
*
* This class supports displaying metadata parameters that can be used for a SSA query,
* selecting parameters and modifying their values.
*
* @author Margarida Castro Neves
*/
public class SSAMetadataFrame extends JFrame implements ActionListener
{
/**
* Panel for the central region.
*/
protected JPanel centrePanel = new JPanel();
/**
* File chooser for storing and restoring server lists.
*/
protected BasicFileChooser fileChooser = null;
// used to trigger a new server metadata query by SSAQueryBrowser
private PropertyChangeSupport queryMetadata;
private static JTable metadataTable;
private static MetadataTableModel metadataTableModel;
/** The list of all input parameters read from the servers as a hash map */
private HashMap<String, MetadataInputParameter> metaParam=null;
// the metadata table
private static final int NRCOLS = 5; // the number of columns in the table
// the table indexes
private static final int SELECTED_INDEX = 0;
private static final int NR_SERVERS_INDEX = 1;
private static final int NAME_INDEX = 2;
private static final int VALUE_INDEX = 3;
private static final int DESCRIPTION_INDEX = 4;
// total number of servers that returned parameters
int nrServers;
// the table headers
String[] headers;
String[] headersToolTips;
// cell renderer for the parameter name column
ParamCellRenderer paramRenderer=null;
/**
* Constructor:
*/
//public SSAMetadataFrame( HashMap<String, MetadataInputParameter> metaParam , int nrServers)
public SSAMetadataFrame( HashMap<String, MetadataInputParameter> metaParam )
{
this.metaParam = metaParam;
//this.nrServers = nrServers;
initUI();
initMetadataTable();
initMenus();
initFrame();
queryMetadata = new PropertyChangeSupport(this);
} //initFrame
/**
* Constructor: creates an empty table
*/
public SSAMetadataFrame( )
{
metaParam = null;
// nrServers = 0;
initUI();
initMetadataTable();
initMenus();
initFrame();
queryMetadata = new PropertyChangeSupport(this);
} //initFrame
/**
* Initialize the metadata table
*/
public void initMetadataTable()
{
// the table headers
headers = new String[NRCOLS];
headers[SELECTED_INDEX] = "Use";
headers[NR_SERVERS_INDEX] = "Nr servers";
headers[NAME_INDEX] = "Name";
headers[VALUE_INDEX] = "Value";
headers[DESCRIPTION_INDEX] = "Description";
// the tooltip Texts for the headers
headersToolTips = new String[NRCOLS];
headersToolTips[SELECTED_INDEX] = "Select for Query";
headersToolTips[NR_SERVERS_INDEX] = "Nr servers supporting this parameter";
headersToolTips[NAME_INDEX] = "Parameter name";
headersToolTips[VALUE_INDEX] = "Parameter value";
headersToolTips[DESCRIPTION_INDEX] = "Description";
// Table of metadata parameters goes into a scrollpane in the center of
// window (along with a set of buttons, see initUI).
// set the model and change the appearance
// the table data
if (metaParam != null)
{
String[][] paramList = getParamList();
metadataTableModel = new MetadataTableModel(paramList, headers);
} else
metadataTableModel = new MetadataTableModel(headers);
metadataTable.setModel( metadataTableModel );
metadataTable.setShowGrid(true);
metadataTable.setGridColor(Color.lightGray);
metadataTable.getTableHeader().setReorderingAllowed(false);
paramRenderer = new ParamCellRenderer(); // set cell renderer for description column
adjustColumns();
}
/**
* updateMetadata( HashMap<String, MetadataInputParameter> metaParam )
* updates the metadata table information after a "refresh"
*
* @param metaParam
*/
public void updateMetadata(HashMap<String, MetadataInputParameter> metaParam )
{
metadataTableModel = new MetadataTableModel(headers);
metadataTable.setModel(metadataTableModel );
adjustColumns();
}
/**
* Transform the metadata Hash into a two-dimensional String array (an array of rows).
* The rows will be sorted by number of servers supporting the parameter
*
* @return the metadata array
*/
public String[][] getParamList()
{
// Iterate through metaParam, add the entries, populate the table
Collection<MetadataInputParameter> mp = metaParam.values();
String[][] metadataList = new String[mp.size()][NRCOLS];
Iterator<MetadataInputParameter> it = mp.iterator();
int row=0;
while (it.hasNext()) {
MetadataInputParameter mip = it.next();
metadataList[row][NR_SERVERS_INDEX] = Integer.toString(mip.getCounter());//+"/"+Integer.toString(nrServers); // nr supporting servers
metadataList[row][NAME_INDEX] = mip.getName().replace("INPUT:", ""); // name
metadataList[row][VALUE_INDEX] = mip.getValue(); // value (default value or "")
String unit = mip.getUnit();
String desc = mip.getDescription();
desc = desc.replaceAll("\n+", "<br>");
desc = desc.replaceAll("\t+", " ");
desc = desc.replaceAll("\\s+", " ");
if (unit != null && unit.length() >0) {
desc = desc + " ("+unit+")"; // description (unit)
}
metadataList[row][DESCRIPTION_INDEX] = desc; // description
row++;
} // while
Arrays.sort(metadataList, new SupportedComparator());
return metadataList;
}
/**
* comparator to sort the parameter list by the nr of servers that support a parameter
*/
class SupportedComparator implements Comparator<String[]>
{
public int compare(String[] object1, String[] object2) {
// compare the frequency counter
return ( Integer.parseInt(object2[NR_SERVERS_INDEX]) - Integer.parseInt(object1[NR_SERVERS_INDEX]) );
}
}
/**
* adjust column sizes, renderers and editors
*/
private void adjustColumns() {
JCheckBox cb = new JCheckBox();
JTextField tf = new JTextField();
metadataTable.getColumnModel().getColumn(SELECTED_INDEX).setCellEditor(new DefaultCellEditor(cb));
metadataTable.getColumnModel().getColumn(SELECTED_INDEX).setMaxWidth(30);
metadataTable.getColumnModel().getColumn(SELECTED_INDEX).setMinWidth(30);
metadataTable.getColumnModel().getColumn(NR_SERVERS_INDEX).setMaxWidth(60);
metadataTable.getColumnModel().getColumn(NAME_INDEX).setMinWidth(150);
metadataTable.getColumnModel().getColumn(VALUE_INDEX).setMinWidth(150);
metadataTable.getColumnModel().getColumn(VALUE_INDEX).setCellEditor(new DefaultCellEditor(tf));
metadataTable.getColumnModel().getColumn(NAME_INDEX).setCellRenderer(paramRenderer);
metadataTable.getColumnModel().getColumn (DESCRIPTION_INDEX).setMaxWidth(0);
// Remove the description column. Its contents will not be removed. They'll be displayed as tooltip text in the NAME_INDEX column.
metadataTable.removeColumn(metadataTable.getColumnModel().getColumn (DESCRIPTION_INDEX));
}
/**
* Retrieve parameter names and values from table and returns a query substring
* Only the parameters on selected rows, and having non-empty values will be added to the table
*/
public String getParamsQueryString()
{
String query="";
// iterate through all rows
for (int i=0; i< metadataTable.getRowCount(); i++)
{
if (rowChecked( i ))
{
String val = getTableData(i,VALUE_INDEX).toString().trim();
if (val != null && val.length() > 0) {
String name = getTableData(i,NAME_INDEX).toString().trim();
query += "&"+name+"="+val;
}
}
}
return query;
}
/**
* retrieves table content at cell position row, col
*
* @param row
* @param col
* @return
*/
private Object getTableData(int row, int col )
{
return metadataTable.getModel().getValueAt(row, col);
}
/**
* retrieves the state of the checkbox row (parameter selected)
*
* @param row
* @return - true if it is checked, false if unchecked
*/
private boolean rowChecked(int row)
{
Boolean val = (Boolean) metadataTable.getModel().getValueAt(row, SELECTED_INDEX);
if (Boolean.TRUE.equals(val))
return true;
else return false;
}
/**
* changes content to newValue at cell position row, col
*
* @param newValue
* @param row
* @param col
*/
private void setTableData(String newValue, int row, int col )
{
metadataTable.getModel().setValueAt(newValue, row, col);
}
/**
* Initialise the main part of the user interface.
*/
protected void initUI()
{
getContentPane().setLayout( new BorderLayout() );
metadataTable = new JTable( );
JScrollPane scroller = new JScrollPane( metadataTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
// metadataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
centrePanel.setLayout( new BorderLayout() );
centrePanel.add( scroller, BorderLayout.CENTER );
getContentPane().add( centrePanel, BorderLayout.CENTER );
centrePanel.setBorder( BorderFactory.createTitledBorder( "Optional Parameters" ) );
}
/**
* Initialise frame properties (disposal, title, menus etc.).
*/
protected void initFrame()
{
setTitle( Utilities.getTitle( "Select SSAP Parameters" ));
setDefaultCloseOperation( JFrame.HIDE_ON_CLOSE );
setSize( new Dimension( 425, 500 ) );
setVisible( true );
}
/**
* Initialise the menu bar, action bar and related actions.
*/
protected void initMenus()
{
// get the icons
// Get icons.
ImageIcon closeImage = new ImageIcon( ImageHolder.class.getResource( "close.gif" ) );
ImageIcon saveImage = new ImageIcon( ImageHolder.class.getResource( "savefile.gif" ) );
ImageIcon readImage = new ImageIcon( ImageHolder.class.getResource( "openfile.gif" ) );
// ImageIcon helpImage = new ImageIcon( ImageHolder.class.getResource( "help.gif" ) );
ImageIcon updateImage = new ImageIcon( ImageHolder.class.getResource("ssapservers.gif") );
ImageIcon resetImage = new ImageIcon( ImageHolder.class.getResource("reset.gif") );
// The Menu bar
// Add the menuBar.
JMenuBar menuBar = new JMenuBar();
setJMenuBar( menuBar );
// Create the File menu.
JMenu fileMenu = new JMenu( "File" );
fileMenu.setMnemonic( KeyEvent.VK_F );
menuBar.add( fileMenu );
JMenuItem saveFile = new JMenuItem("(S)ave Param List to File", saveImage);
saveFile.setMnemonic( KeyEvent.VK_S );
saveFile.addActionListener(this);
saveFile.setActionCommand( "save" );
fileMenu.add(saveFile);
JMenuItem readFile = new JMenuItem("Read Param List from (F)ile", readImage);
fileMenu.add(readFile);
readFile.setMnemonic( KeyEvent.VK_F );
readFile.addActionListener(this);
readFile.setActionCommand( "restore" );
JMenuItem loadFile = new JMenuItem("(U)pdate Params from servers", updateImage);
fileMenu.add(loadFile);
loadFile.setMnemonic( KeyEvent.VK_U );
loadFile.addActionListener(this);
loadFile.setActionCommand( "load" );
JMenuItem resetFile = new JMenuItem("(R)eset all values", resetImage);
fileMenu.add(loadFile);
resetFile.setMnemonic( KeyEvent.VK_R );
resetFile.addActionListener(this);
resetFile.setActionCommand( "reset" );
// Create the Help menu.
HelpFrame.createButtonHelpMenu( "ssa-window", "Help on window", menuBar, null );
// The Buttons bar
// the action buttons
JPanel buttonsPanel = new JPanel( new GridLayout(1,5) );
// Add action to save the parameter list into a file
JButton saveButton = new JButton( "Save" , saveImage );
saveButton.setActionCommand( "save" );
saveButton.setToolTipText( "Save parameter list to a file" );
saveButton.addActionListener( this );
buttonsPanel.add( saveButton );
// Add action to save the parameter list into a file
JButton restoreButton = new JButton( "Read" , readImage);
restoreButton.setActionCommand( "restore" );
restoreButton.setToolTipText( "Restore parameter list from a file" );
restoreButton.addActionListener( this );
buttonsPanel.add( restoreButton );
// Add action to query the servers for parameters
JButton queryButton = new JButton( "Update" , updateImage);
- queryButton.setActionCommand( "load" );
+ queryButton.setActionCommand( "refresh" );
queryButton.setToolTipText( "Query the servers for a current list of parameters" );
queryButton.addActionListener( this );
buttonsPanel.add( queryButton );
// Add action to do reset the form
JButton resetButton = new JButton( "Reset", resetImage );
resetButton.setActionCommand( "reset" );
resetButton.setToolTipText( "Clear all fields" );
resetButton.addActionListener( this );
buttonsPanel.add( resetButton );
// Add an action to close the window.
JButton closeButton = new JButton( "Close", closeImage );
//centrePanel.add( closeButton );
closeButton.addActionListener( this );
closeButton.setActionCommand( "close" );
closeButton.setToolTipText( "Close window" );
buttonsPanel.add( closeButton);
centrePanel.add( buttonsPanel, BorderLayout.SOUTH);
} // initMenus
/**
* Register new Property Change Listener
*/
public void addPropertyChangeListener(PropertyChangeListener l)
{
queryMetadata.addPropertyChangeListener(l);
}
/**
* action performed
* process the actions when a button is clicked
*/
public void actionPerformed(ActionEvent e) {
Object command = e.getActionCommand();
if ( command.equals( "save" ) ) // save table values to a file
{
saveMetadataToFile();
}
if ( command.equals( "load" ) ) // read saved table values from a file
{
readMetadataFromFile();
}
if ( command.equals( "refresh" ) ) // add new server to list
{
queryMetadata.firePropertyChange("refresh", false, true);
}
if ( command.equals( "reset" ) ) // reset text fields
{
resetFields();
}
if ( command.equals( "close" ) ) // close window
{
closeWindow();
}
} // actionPerformed
/**
* Close (hide) the window.
*/
private void closeWindow()
{
this.setVisible( false );
}
/**
* Open (show) the window.
*/
public void openWindow()
{
this.setVisible( true );
}
/**
* Reset all fields
*/
private void resetFields()
{
for (int i=0; i< metadataTable.getRowCount(); i++) {
String val = getTableData(i,VALUE_INDEX).toString().trim();
if (val != null && val.length() > 0) {
setTableData("", i,VALUE_INDEX);
}
}
} //resetFields
/**
* Initialise the file chooser to have the necessary filters.
*/
protected void initFileChooser()
{
if ( fileChooser == null ) {
fileChooser = new BasicFileChooser( false );
fileChooser.setMultiSelectionEnabled( false );
// Add a filter for XML files.
BasicFileFilter csvFileFilter =
new BasicFileFilter( "csv", "CSV files" );
fileChooser.addChoosableFileFilter( csvFileFilter );
// But allow all files as well.
fileChooser.addChoosableFileFilter
( fileChooser.getAcceptAllFileFilter() );
}
} //initFileChooser
/**
* Restore metadata that has been previously written to a
* CSV file. The file name is obtained interactively.
*/
public void readMetadataFromFile()
{
initFileChooser();
int result = fileChooser.showOpenDialog( this );
if ( result == JFileChooser.APPROVE_OPTION )
{
File file = fileChooser.getSelectedFile();
try {
readTable( file );
}
catch (Exception e) {
ErrorDialog.showError( this, e );
}
}
} // readMetadataFromFile
/**
* Interactively gets a file name and save current metadata table to it in CSV format
* a VOTable.
*/
public void saveMetadataToFile()
{
if ( metadataTable == null || metadataTable.getRowCount() == 0 ) {
JOptionPane.showMessageDialog( this,
"There are no parameters to save",
"No parameters", JOptionPane.ERROR_MESSAGE );
return;
}
initFileChooser();
int result = fileChooser.showSaveDialog( this );
if ( result == JFileChooser.APPROVE_OPTION ) {
File file = fileChooser.getSelectedFile();
try {
saveTable( file );
}
catch (Exception e) {
ErrorDialog.showError( this, e );
}
}
} // readMetadataFromFile
/**
* saveTable(file)
* saves the metadata table to a file in csv format
*
* @param paramFile - file where to save the table
* @throws IOException
*/
private void saveTable(File paramFile) throws IOException
{
BufferedWriter tableWriter = new BufferedWriter(new FileWriter(paramFile));
for ( int row=0; row< metadataTable.getRowCount(); row++) {
tableWriter.append(metadataTable.getValueAt(row, NR_SERVERS_INDEX).toString());
tableWriter.append(';');
tableWriter.append(metadataTable.getValueAt(row, NAME_INDEX).toString());
tableWriter.append(';');
tableWriter.append(metadataTable.getValueAt(row, VALUE_INDEX).toString());
tableWriter.append(';');
tableWriter.append(metadataTable.getValueAt(row, DESCRIPTION_INDEX).toString());
tableWriter.append('\n');
}
tableWriter.flush();
tableWriter.close();
} //saveTable()
/**
* readTable( File paramFile)
* reads the metadata table previously saved with saveTable() from a file in csv format
*
* @param paramFile - the csv file to be read
* @throws IOException
* @throws FileNotFoundException
*/
private void readTable(File paramFile) throws IOException, FileNotFoundException
{
MetadataTableModel newmodel = new MetadataTableModel(headers);
BufferedReader CSVFile = new BufferedReader(new FileReader(paramFile));
String tableRow = CSVFile.readLine();
while (tableRow != null) {
String [] paramRow = new String [NRCOLS];
paramRow = tableRow.split(";", NRCOLS);
newmodel.addRow(paramRow);
tableRow = CSVFile.readLine();
}
// Close the file once all data has been read.
CSVFile.close();
// set the new model
metadataTable.setModel(newmodel);
adjustColumns(); // adjust column sizes in the new model
} //readTable()
/**
* Adds a new row to the table
* @param mip the metadata parameter that will be added to the table
*/
public void addRow (MetadataInputParameter mip) {
String [] paramRow = new String [NRCOLS];
paramRow[NR_SERVERS_INDEX] = Integer.toString(mip.getCounter());//+"/"+Integer.toString(nrServers); // nr supporting servers
paramRow[NAME_INDEX] = mip.getName().replace("INPUT:", ""); // name
paramRow[VALUE_INDEX] = mip.getValue(); // value (default value or "")
String unit = mip.getUnit();
String desc = mip.getDescription();
if (desc != null)
{
// remove newline, tabs, and multiple spaces
desc = desc.replaceAll("\n+", " ");
desc = desc.replaceAll("\t+", " ");
desc = desc.replaceAll("\\s+", " ");
// insert linebreaks for multi-lined tooltip
int linelength=100;
int sum=0;
String [] words = desc.split( " " );
desc="";
for (int i=0; i<words.length; i++ ) {
sum+=words[i].length()+1;
if (sum > linelength) {
desc+="<br>"+words[i]+" ";
sum=words[i].length();
} else {
desc+=words[i]+" ";
}
}
}
if (unit != null && unit.length() >0) {
desc = desc + " ("+unit+")"; // description (unit)
}
paramRow[DESCRIPTION_INDEX] = desc; // description
MetadataTableModel mtm = (MetadataTableModel) metadataTable.getModel();
mtm.addRow( paramRow );
} //addRow
/**
* Set number of servers to the respective column in the table
* @param counter the nr of servers supporting the parameter
* @param name the name of the parameter
*/
public void setNrServers(int counter, String name) {
// boolean found=false;
int row=0;
String paramName = name.replace("INPUT:", "");
MetadataTableModel mtm = (MetadataTableModel) metadataTable.getModel();
while (row<mtm.getRowCount() )
{
if ( mtm.getValueAt(row, NAME_INDEX).toString().equalsIgnoreCase(paramName)) {
mtm.setValueAt(counter, row, NR_SERVERS_INDEX);
return;
}
row++;
}
}//setnrServers
/**
* the cell renderer for the parameter name column ( show description as toolTipText )
*
*/
class ParamCellRenderer extends JLabel implements TableCellRenderer
{
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
setText(value.toString());
setToolTipText("<html><p>"+table.getModel().getValueAt(row, DESCRIPTION_INDEX).toString()+"</p></html>");
if (isSelected)
setBackground(table.getSelectionBackground());
return this;
}
} //ParamCellRenderer
/**
* MetadataTableModel
* defines the model of the metadata table
*/
class MetadataTableModel extends DefaultTableModel
{
// creates a metadataTableModel with headers and data
public MetadataTableModel( String [][] data, String [] headers ) {
super(data, headers);
}
// creates a metadataTableModel with headers and no data rows
public MetadataTableModel( String [] headers ) {
super(headers, 0);
}
@Override
public boolean isCellEditable(int row, int column) {
return (column == VALUE_INDEX || column == SELECTED_INDEX ); // the Values column is editable
}
@Override
public Class getColumnClass(int column) {
if (column == SELECTED_INDEX )
return Boolean.class;
return String.class;
}
} //MetadataTableModel
} //SSAMetadataFrame
| true | true | protected void initMenus()
{
// get the icons
// Get icons.
ImageIcon closeImage = new ImageIcon( ImageHolder.class.getResource( "close.gif" ) );
ImageIcon saveImage = new ImageIcon( ImageHolder.class.getResource( "savefile.gif" ) );
ImageIcon readImage = new ImageIcon( ImageHolder.class.getResource( "openfile.gif" ) );
// ImageIcon helpImage = new ImageIcon( ImageHolder.class.getResource( "help.gif" ) );
ImageIcon updateImage = new ImageIcon( ImageHolder.class.getResource("ssapservers.gif") );
ImageIcon resetImage = new ImageIcon( ImageHolder.class.getResource("reset.gif") );
// The Menu bar
// Add the menuBar.
JMenuBar menuBar = new JMenuBar();
setJMenuBar( menuBar );
// Create the File menu.
JMenu fileMenu = new JMenu( "File" );
fileMenu.setMnemonic( KeyEvent.VK_F );
menuBar.add( fileMenu );
JMenuItem saveFile = new JMenuItem("(S)ave Param List to File", saveImage);
saveFile.setMnemonic( KeyEvent.VK_S );
saveFile.addActionListener(this);
saveFile.setActionCommand( "save" );
fileMenu.add(saveFile);
JMenuItem readFile = new JMenuItem("Read Param List from (F)ile", readImage);
fileMenu.add(readFile);
readFile.setMnemonic( KeyEvent.VK_F );
readFile.addActionListener(this);
readFile.setActionCommand( "restore" );
JMenuItem loadFile = new JMenuItem("(U)pdate Params from servers", updateImage);
fileMenu.add(loadFile);
loadFile.setMnemonic( KeyEvent.VK_U );
loadFile.addActionListener(this);
loadFile.setActionCommand( "load" );
JMenuItem resetFile = new JMenuItem("(R)eset all values", resetImage);
fileMenu.add(loadFile);
resetFile.setMnemonic( KeyEvent.VK_R );
resetFile.addActionListener(this);
resetFile.setActionCommand( "reset" );
// Create the Help menu.
HelpFrame.createButtonHelpMenu( "ssa-window", "Help on window", menuBar, null );
// The Buttons bar
// the action buttons
JPanel buttonsPanel = new JPanel( new GridLayout(1,5) );
// Add action to save the parameter list into a file
JButton saveButton = new JButton( "Save" , saveImage );
saveButton.setActionCommand( "save" );
saveButton.setToolTipText( "Save parameter list to a file" );
saveButton.addActionListener( this );
buttonsPanel.add( saveButton );
// Add action to save the parameter list into a file
JButton restoreButton = new JButton( "Read" , readImage);
restoreButton.setActionCommand( "restore" );
restoreButton.setToolTipText( "Restore parameter list from a file" );
restoreButton.addActionListener( this );
buttonsPanel.add( restoreButton );
// Add action to query the servers for parameters
JButton queryButton = new JButton( "Update" , updateImage);
queryButton.setActionCommand( "load" );
queryButton.setToolTipText( "Query the servers for a current list of parameters" );
queryButton.addActionListener( this );
buttonsPanel.add( queryButton );
// Add action to do reset the form
JButton resetButton = new JButton( "Reset", resetImage );
resetButton.setActionCommand( "reset" );
resetButton.setToolTipText( "Clear all fields" );
resetButton.addActionListener( this );
buttonsPanel.add( resetButton );
// Add an action to close the window.
JButton closeButton = new JButton( "Close", closeImage );
//centrePanel.add( closeButton );
closeButton.addActionListener( this );
closeButton.setActionCommand( "close" );
closeButton.setToolTipText( "Close window" );
buttonsPanel.add( closeButton);
centrePanel.add( buttonsPanel, BorderLayout.SOUTH);
} // initMenus
| protected void initMenus()
{
// get the icons
// Get icons.
ImageIcon closeImage = new ImageIcon( ImageHolder.class.getResource( "close.gif" ) );
ImageIcon saveImage = new ImageIcon( ImageHolder.class.getResource( "savefile.gif" ) );
ImageIcon readImage = new ImageIcon( ImageHolder.class.getResource( "openfile.gif" ) );
// ImageIcon helpImage = new ImageIcon( ImageHolder.class.getResource( "help.gif" ) );
ImageIcon updateImage = new ImageIcon( ImageHolder.class.getResource("ssapservers.gif") );
ImageIcon resetImage = new ImageIcon( ImageHolder.class.getResource("reset.gif") );
// The Menu bar
// Add the menuBar.
JMenuBar menuBar = new JMenuBar();
setJMenuBar( menuBar );
// Create the File menu.
JMenu fileMenu = new JMenu( "File" );
fileMenu.setMnemonic( KeyEvent.VK_F );
menuBar.add( fileMenu );
JMenuItem saveFile = new JMenuItem("(S)ave Param List to File", saveImage);
saveFile.setMnemonic( KeyEvent.VK_S );
saveFile.addActionListener(this);
saveFile.setActionCommand( "save" );
fileMenu.add(saveFile);
JMenuItem readFile = new JMenuItem("Read Param List from (F)ile", readImage);
fileMenu.add(readFile);
readFile.setMnemonic( KeyEvent.VK_F );
readFile.addActionListener(this);
readFile.setActionCommand( "restore" );
JMenuItem loadFile = new JMenuItem("(U)pdate Params from servers", updateImage);
fileMenu.add(loadFile);
loadFile.setMnemonic( KeyEvent.VK_U );
loadFile.addActionListener(this);
loadFile.setActionCommand( "load" );
JMenuItem resetFile = new JMenuItem("(R)eset all values", resetImage);
fileMenu.add(loadFile);
resetFile.setMnemonic( KeyEvent.VK_R );
resetFile.addActionListener(this);
resetFile.setActionCommand( "reset" );
// Create the Help menu.
HelpFrame.createButtonHelpMenu( "ssa-window", "Help on window", menuBar, null );
// The Buttons bar
// the action buttons
JPanel buttonsPanel = new JPanel( new GridLayout(1,5) );
// Add action to save the parameter list into a file
JButton saveButton = new JButton( "Save" , saveImage );
saveButton.setActionCommand( "save" );
saveButton.setToolTipText( "Save parameter list to a file" );
saveButton.addActionListener( this );
buttonsPanel.add( saveButton );
// Add action to save the parameter list into a file
JButton restoreButton = new JButton( "Read" , readImage);
restoreButton.setActionCommand( "restore" );
restoreButton.setToolTipText( "Restore parameter list from a file" );
restoreButton.addActionListener( this );
buttonsPanel.add( restoreButton );
// Add action to query the servers for parameters
JButton queryButton = new JButton( "Update" , updateImage);
queryButton.setActionCommand( "refresh" );
queryButton.setToolTipText( "Query the servers for a current list of parameters" );
queryButton.addActionListener( this );
buttonsPanel.add( queryButton );
// Add action to do reset the form
JButton resetButton = new JButton( "Reset", resetImage );
resetButton.setActionCommand( "reset" );
resetButton.setToolTipText( "Clear all fields" );
resetButton.addActionListener( this );
buttonsPanel.add( resetButton );
// Add an action to close the window.
JButton closeButton = new JButton( "Close", closeImage );
//centrePanel.add( closeButton );
closeButton.addActionListener( this );
closeButton.setActionCommand( "close" );
closeButton.setToolTipText( "Close window" );
buttonsPanel.add( closeButton);
centrePanel.add( buttonsPanel, BorderLayout.SOUTH);
} // initMenus
|
diff --git a/src/com/noshufou/android/su/UpdaterFragment.java b/src/com/noshufou/android/su/UpdaterFragment.java
index adb78c79..01f496c8 100644
--- a/src/com/noshufou/android/su/UpdaterFragment.java
+++ b/src/com/noshufou/android/su/UpdaterFragment.java
@@ -1,740 +1,740 @@
package com.noshufou.android.su;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.NotificationManager;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Build.VERSION;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.noshufou.android.su.util.Util;
public class UpdaterFragment extends ListFragment implements OnClickListener {
private static final String TAG = "Su.UpdaterFragment";
private String MANIFEST_URL;
private int CONSOLE_RED;
private int CONSOLE_GREEN;
private enum Step {
DOWNLOAD_MANIFEST,
DOWNLOAD_BUSYBOX;
}
private class Manifest {
public String version;
public int versionCode;
public String binaryUrl;
public String binaryMd5;
public String busyboxUrl;
public String busyboxMd5;
}
private Manifest mManifest;
private String mBusyboxPath = null;
private Step mCurrentStep = Step.DOWNLOAD_MANIFEST;
private ProgressBar mTitleProgress;
private ProgressBar mProgressBar;
private TextView mStatusText;
private Button mActionButton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
MANIFEST_URL = getString(Integer.parseInt(VERSION.SDK) < 5?
R.string.updater_manifest_legacy:R.string.updater_manifest);
CONSOLE_RED = getActivity().getResources().getColor(R.color.console_red);
CONSOLE_GREEN = getActivity().getResources().getColor(R.color.console_green);
View view = inflater.inflate(R.layout.fragment_updater, container, false);
((TextView)view.findViewById(R.id.title_text)).setText(R.string.updater_title);
mTitleProgress = (ProgressBar) view.findViewById(R.id.title_refresh_progress);
mProgressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
mStatusText = (TextView) view.findViewById(R.id.status);
mActionButton = (Button) view.findViewById(R.id.action_button);
mActionButton.setOnClickListener(this);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(new ConsoleAdapter(getActivity()));
getListAdapter().setNotifyOnChange(false);
mProgressBar.setInterpolator(getActivity(), android.R.anim.accelerate_decelerate_interpolator);
new UpdateTask().execute();
}
@Override
public void onClick(View view) {
new UpdateTask().execute();
}
@Override
public ConsoleAdapter getListAdapter() {
return (ConsoleAdapter) super.getListAdapter();
}
private class UpdateTask extends AsyncTask<Void, Object, Integer> {
public static final int STATUS_AWAITING_ACTION = 1;
public static final int STATUS_FINISHED_SUCCESSFUL = 2;
public static final int STATUS_FINISHED_FAIL = 3;
public static final int STATUS_FINISHED_NO_NEED = 4;
@Override
protected void onPreExecute() {
mTitleProgress.setVisibility(View.VISIBLE);
mStatusText.setText(R.string.updater_working);
mActionButton.setText(R.string.updater_working);
mActionButton.setEnabled(false);
}
@Override
protected Integer doInBackground(Void... params) {
int progressTotal = 0;
int progressStep = 0;
switch (mCurrentStep) {
case DOWNLOAD_MANIFEST:
progressTotal = 4;
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_download_manifest);
if (downloadFile(MANIFEST_URL, "manifest")) {
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
} else {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
// Parse manifest
// TODO: Actually parse the manifest here, as of now it's being
// done at download time.
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_parse_manifest);
if (mManifest == null) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Display the latest version
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_latest_version);
publishProgress(progressTotal, progressStep, progressStep,
mManifest.version, CONSOLE_GREEN);
// Check the currently installed version
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_installed_version);
int installedVersionCode = Util.getSuVersionCode();
String installedVersion = Util.getSuVersion();
if (installedVersionCode < mManifest.versionCode) {
publishProgress(progressTotal, progressStep, progressStep,
installedVersion, CONSOLE_RED);
mCurrentStep = Step.DOWNLOAD_BUSYBOX;
return STATUS_AWAITING_ACTION;
} else {
publishProgress(progressTotal, progressStep, progressStep,
installedVersion, CONSOLE_GREEN);
mCurrentStep = Step.DOWNLOAD_BUSYBOX;
return STATUS_FINISHED_NO_NEED;
}
case DOWNLOAD_BUSYBOX:
// Fix the db if necessary. A bug in the 2.3x binary could cause
// the su binary to fail if there is no prefs table, which would
// happen if the user never opened the app. Fringe case, but
// needs to be addressed.
boolean fixDb = (Util.getSuVersionCode() == 0);
if (fixDb) {
progressTotal = 16;
progressStep = 1;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_fix_db);
SQLiteDatabase db = null;
try {
db = getActivity().openOrCreateDatabase(
"permissions.sqlite", Context.MODE_PRIVATE, null);
// We just need to make sure all the tables exist and have the proper
// columns. We'll delete this DB at the end of the update.
db.execSQL("CREATE TABLE IF NOT EXISTS apps (_id INTEGER, uid INTEGER, " +
"package TEXT, name TEXT, exec_uid INTEGER, exec_cmd TEXT, " +
" allow INTEGER, PRIMARY KEY (_id), UNIQUE (uid,exec_uid,exec_cmd))");
db.execSQL("CREATE TABLE IF NOT EXISTS logs (_id INTEGER, app_id INTEGER, " +
"date INTEGER, type INTEGER, PRIMARY KEY (_id))");
db.execSQL("CREATE TABLE IF NOT EXISTS prefs (_id INTEGER, key TEXT, " +
"value TEXT, PRIMARY KEY (_id))");
} catch (SQLException e) {
Log.e(TAG, "Failed to fix database", e);
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
} finally {
// Make sure we close the DB here, or the su call will also fail.
if (db != null) {
db.close();
}
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
} else {
progressTotal = 15;
progressStep = 0;
}
// Download custom tiny busybox
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_download_busybox);
if (downloadFile(mManifest.busyboxUrl, "busybox")) {
try {
// Process process = Runtime.getRuntime().exec(new String[] { "chmod", "755", mBusyboxPath });
Process process = new ProcessBuilder()
.command("chmod", "755", mBusyboxPath)
.redirectErrorStream(true).start();
Log.d(TAG, "chmod 755 " + mBusyboxPath);
process.waitFor();
process.destroy();
} catch (IOException e) {
Log.e(TAG, "Failed to set busybox to executable", e);
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
} catch (InterruptedException e) {
Log.w(TAG, "Process interrupted", e);
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
} else {
Log.e(TAG, "Failed to download busybox");
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail);
return STATUS_FINISHED_FAIL;
}
// Verify md5sum of busybox
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_md5sum);
if (verifyFile(mBusyboxPath, mManifest.busyboxMd5)) {
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
} else {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
// Check where the current su binary is installed
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_installed_path);
String installedSu = whichSu();
Log.d(TAG, "su installed to " + installedSu);
if (installedSu == null) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_find_su_failed);
return STATUS_FINISHED_FAIL;
} else if (installedSu.equals("/sbin/su")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
installedSu, CONSOLE_RED);
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_bad_install_location);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
installedSu, CONSOLE_GREEN);
// Download new su binary
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_download_su);
String suPath;
if (downloadFile(mManifest.binaryUrl, "su")) {
suPath = getActivity().getFileStreamPath("su").toString();
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
} else {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
// Verify md5sum of su
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_md5sum);
if (verifyFile(suPath, mManifest.binaryMd5)) {
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
} else {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
Process process = null;
try { // Just use one try/catch for all the root commands
// Get root access
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_get_root);
process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
BufferedReader is = new BufferedReader(new InputStreamReader(
new DataInputStream(process.getInputStream())), 64);
os.writeBytes("id\n");
String inLine = is.readLine();
if (inLine == null) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
Pattern pattern = Pattern.compile("uid=([\\d]+)");
Matcher matcher = pattern.matcher(inLine);
if (!matcher.find() || !matcher.group(1).equals("0")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Remount system partition
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_remount_rw);
executeCommand(os, null, mBusyboxPath + " mount -o remount,rw /system");
inLine = executeCommand(os, is, mBusyboxPath + " touch /system/su && " +
mBusyboxPath + " echo YEAH");
if (inLine == null || !inLine.equals("YEAH")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_ok, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Copy su to /system. Put it in here first so it's on the system
// partition then use an atomic move to make sure we don't get
// corrupted
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_cp);
inLine = executeCommand(os, is, mBusyboxPath, "cp", suPath, "/system &&",
mBusyboxPath, "echo YEAH");
if (inLine == null || !inLine.equals("YEAH")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Check su md5sum again. Do it often to make sure everything is
// going good.
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_md5sum);
inLine = executeCommand(os, is, mBusyboxPath, "md5sum /system/su");
if (inLine == null || !inLine.split(" ")[0].equals(mManifest.binaryMd5)) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Move /system/su to wherer it belongs
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_mv);
inLine = executeCommand(os, is, mBusyboxPath, "mv /system/su", installedSu,
"&&", mBusyboxPath, "echo YEAH");
if (inLine == null || !inLine.equals("YEAH")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Check su md5sum again. Last time, I promise
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_md5sum);
// Can't use the verifyFile method here since we need to be root
- inLine = executeCommand(os, is, mBusyboxPath, "md5sum /system/bin/su");
+ inLine = executeCommand(os, is, mBusyboxPath, "md5sum", installedSu);
if (inLine == null || !inLine.split(" ")[0].equals(mManifest.binaryMd5)) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Change su file mode
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_chmod);
- inLine = executeCommand(os, is, mBusyboxPath, "chmod 06755 /system/bin/su &&",
+ inLine = executeCommand(os, is, mBusyboxPath, "chmod 06755", installedSu, "&&",
mBusyboxPath, "echo YEAH");
if (inLine == null || !inLine.equals("YEAH")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Remount system partition
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_remount_ro);
executeCommand(os, null, mBusyboxPath, "mount -o remount,ro /system");
inLine = executeCommand(os, is, mBusyboxPath, "touch /system/su ||",
mBusyboxPath, "echo YEAH");
if (inLine == null || !inLine.equals("YEAH")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_remount_ro_failed);
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
os.writeBytes("exit\n");
} catch (IOException e) {
Log.e(TAG, "Failed to execute root commands", e);
} finally {
process.destroy();
}
// Verify the proper version is installed.
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_installed_version);
installedVersionCode = Util.getSuVersionCode();
installedVersion = Util.getSuVersion();
if (installedVersionCode == mManifest.versionCode) {
publishProgress(progressTotal, progressStep, progressStep,
installedVersion, CONSOLE_GREEN);
} else {
publishProgress(progressTotal, progressStep, progressStep,
installedVersion, CONSOLE_RED);
mCurrentStep = Step.DOWNLOAD_BUSYBOX;
return STATUS_FINISHED_FAIL;
}
// Clean up
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_clean_up);
getActivity().deleteFile("busybox");
getActivity().deleteFile("su");
if (fixDb) {
getActivity().deleteDatabase("permissions.sqlite");
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
return STATUS_FINISHED_SUCCESSFUL;
}
return -1;
}
@Override
protected void onProgressUpdate(Object... values) {
getListAdapter().notifyDataSetChanged();
mProgressBar.setMax((Integer)values[0]);
mProgressBar.setProgress((Integer)values[1]);
mProgressBar.setSecondaryProgress((Integer)values[2]);
if (values.length == 4) {
addConsoleEntry((Integer)values[3]);
} else if (values.length == 5) {
if (values[3] instanceof String) {
addStatusToEntry((String)values[3], (Integer)values[4]);
} else {
addStatusToEntry((Integer)values[3], (Integer)values[4]);
}
}
}
@Override
protected void onPostExecute(Integer result) {
mTitleProgress.setVisibility(View.GONE);
mActionButton.setEnabled(true);
switch (result) {
case STATUS_AWAITING_ACTION:
mActionButton.setText(R.string.updater_update);
mStatusText.setText(R.string.updater_new_su_found);
break;
case STATUS_FINISHED_NO_NEED:
mActionButton.setText(R.string.updater_update_anyway);
mStatusText.setText(R.string.updater_current_installed);
break;
case STATUS_FINISHED_SUCCESSFUL:
mActionButton.setText(R.string.updater_cool);
mStatusText.setText(R.string.updater_su_updated);
NotificationManager nm = (NotificationManager) getActivity()
.getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(1);
break;
case STATUS_FINISHED_FAIL:
mActionButton.setText(R.string.updater_try_again);
mStatusText.setText(R.string.updater_update_failed);
}
}
}
private void addConsoleEntry(int res) {
ConsoleEntry entry = new ConsoleEntry(res);
getListAdapter().add(entry);
}
private void addStatusToEntry(int res, int color) {
addStatusToEntry(getActivity().getString(res), color);
}
private void addStatusToEntry(String status, int color) {
ConsoleEntry entry = getListAdapter().getItem(getListAdapter().getCount() - 1);
entry.status = status;
entry.statusColor = color;
}
private boolean downloadFile(String urlStr, String localName) {
BufferedInputStream bis = null;
try {
URL url = new URL(urlStr);
URLConnection urlCon = url.openConnection();
bis = new BufferedInputStream(urlCon.getInputStream());
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
bis.close();
if (localName.equals("manifest")) {
try {
JSONObject manifest = new JSONObject(new String(baf.toByteArray()));
mManifest = new Manifest();
mManifest.version = manifest.getString("version");
mManifest.versionCode = manifest.getInt("version-code");
mManifest.binaryUrl = manifest.getString("binary");
mManifest.binaryMd5 = manifest.getString("binary-md5sum");
mManifest.busyboxUrl = manifest.getString("busybox");
mManifest.busyboxMd5 = manifest.getString("busybox-md5sum");
} catch (JSONException e) {
Log.e(TAG, "Malformed manifest file", e);
}
return true;
} else {
FileOutputStream outFileStream = getActivity().openFileOutput(localName, 0);
outFileStream.write(baf.toByteArray());
outFileStream.close();
if (localName.equals("busybox")) {
mBusyboxPath = getActivity().getFilesDir().getAbsolutePath().concat("/busybox");
}
}
} catch (MalformedURLException e) {
Log.e(TAG, "Bad URL: " + urlStr, e);
return false;
} catch (IOException e) {
Log.e(TAG, "Problem downloading file: " + localName, e);
return false;
}
return true;
}
private boolean verifyFile(String path, String md5sum) {
if (mBusyboxPath == null) {
Log.e(TAG, "Busybox not present");
return false;
}
Process process = null;
try {
process = Runtime.getRuntime().exec(
new String[] { mBusyboxPath, "md5sum", path});
BufferedReader is = new BufferedReader(new InputStreamReader(
new DataInputStream(process.getInputStream())), 64);
BufferedReader es = new BufferedReader(new InputStreamReader(
new DataInputStream(process.getErrorStream())), 64);
for (int i = 0; i < 200; i++) {
if (is.ready()) break;
try {
Thread.sleep(5);
} catch (InterruptedException e) {
Log.w(TAG, "Sleep timer got interrupted...");
}
}
String inLine = null;
if (es.ready()) {
inLine = es.readLine();
Log.d(TAG, inLine);
}
if (is.ready()) {
inLine = is.readLine();
} else {
Log.e(TAG, "Could not check md5sum");
return false;
}
process.destroy();
if (!inLine.split(" ")[0].equals(md5sum)) {
Log.e(TAG, "Checksum mismatch");
return false;
}
} catch (IOException e) {
Log.e(TAG, "Checking of md5sum failed", e);
return false;
}
return true;
}
private String whichSu() {
if (mBusyboxPath == null) {
Log.e(TAG, "Busybox not present");
return null;
}
Process process = null;
try {
String cmd = mBusyboxPath + " which su";
Log.d(TAG, cmd);
process = Runtime.getRuntime().exec(cmd);
BufferedReader is = new BufferedReader(new InputStreamReader(
new DataInputStream(process.getInputStream())), 64);
for (int i = 0; i < 200; i++) {
if (is.ready()) break;
try {
Thread.sleep(5);
} catch (InterruptedException e) {
Log.w(TAG, "Sleep timer got interrupted...");
}
}
return is.readLine();
} catch (IOException e) {
Log.e(TAG, "Failed to find su binary");
} finally {
if (process != null) {
process.destroy();
}
}
return null;
}
private String executeCommand(DataOutputStream os, BufferedReader is, String... commands)
throws IOException {
if (commands.length == 0) return null;
StringBuilder command = new StringBuilder();
for (String s : commands) {
command.append(s).append(" ");
}
command.append("\n");
Log.d(TAG, command.toString());
os.writeBytes(command.toString());
if (is != null) {
for (int i = 0; i < 200; i++) {
if (is.ready()) break;
try {
Thread.sleep(5);
Log.d(TAG, "Slept " + i);
} catch (InterruptedException e) {
Log.w(TAG, "Sleep timer interrupted", e);
}
}
if (is.ready()) {
return is.readLine();
} else {
return null;
}
} else {
return null;
}
}
private class ConsoleAdapter extends ArrayAdapter<ConsoleEntry> {
ConsoleAdapter(Context context) {
super(context, R.layout.console_item, R.id.console_step);
}
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
this.setNotifyOnChange(false);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView status = (TextView) view.findViewById(R.id.console_status);
status.setText(getItem(position).status);
status.setTextColor(getItem(position).statusColor);
return view;
}
}
private class ConsoleEntry {
public String entry;
public String status;
public int statusColor;
public ConsoleEntry(int res) {
entry = getActivity().getString(res);
}
@Override
public String toString() {
return entry;
}
}
}
| false | true | protected Integer doInBackground(Void... params) {
int progressTotal = 0;
int progressStep = 0;
switch (mCurrentStep) {
case DOWNLOAD_MANIFEST:
progressTotal = 4;
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_download_manifest);
if (downloadFile(MANIFEST_URL, "manifest")) {
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
} else {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
// Parse manifest
// TODO: Actually parse the manifest here, as of now it's being
// done at download time.
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_parse_manifest);
if (mManifest == null) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Display the latest version
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_latest_version);
publishProgress(progressTotal, progressStep, progressStep,
mManifest.version, CONSOLE_GREEN);
// Check the currently installed version
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_installed_version);
int installedVersionCode = Util.getSuVersionCode();
String installedVersion = Util.getSuVersion();
if (installedVersionCode < mManifest.versionCode) {
publishProgress(progressTotal, progressStep, progressStep,
installedVersion, CONSOLE_RED);
mCurrentStep = Step.DOWNLOAD_BUSYBOX;
return STATUS_AWAITING_ACTION;
} else {
publishProgress(progressTotal, progressStep, progressStep,
installedVersion, CONSOLE_GREEN);
mCurrentStep = Step.DOWNLOAD_BUSYBOX;
return STATUS_FINISHED_NO_NEED;
}
case DOWNLOAD_BUSYBOX:
// Fix the db if necessary. A bug in the 2.3x binary could cause
// the su binary to fail if there is no prefs table, which would
// happen if the user never opened the app. Fringe case, but
// needs to be addressed.
boolean fixDb = (Util.getSuVersionCode() == 0);
if (fixDb) {
progressTotal = 16;
progressStep = 1;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_fix_db);
SQLiteDatabase db = null;
try {
db = getActivity().openOrCreateDatabase(
"permissions.sqlite", Context.MODE_PRIVATE, null);
// We just need to make sure all the tables exist and have the proper
// columns. We'll delete this DB at the end of the update.
db.execSQL("CREATE TABLE IF NOT EXISTS apps (_id INTEGER, uid INTEGER, " +
"package TEXT, name TEXT, exec_uid INTEGER, exec_cmd TEXT, " +
" allow INTEGER, PRIMARY KEY (_id), UNIQUE (uid,exec_uid,exec_cmd))");
db.execSQL("CREATE TABLE IF NOT EXISTS logs (_id INTEGER, app_id INTEGER, " +
"date INTEGER, type INTEGER, PRIMARY KEY (_id))");
db.execSQL("CREATE TABLE IF NOT EXISTS prefs (_id INTEGER, key TEXT, " +
"value TEXT, PRIMARY KEY (_id))");
} catch (SQLException e) {
Log.e(TAG, "Failed to fix database", e);
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
} finally {
// Make sure we close the DB here, or the su call will also fail.
if (db != null) {
db.close();
}
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
} else {
progressTotal = 15;
progressStep = 0;
}
// Download custom tiny busybox
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_download_busybox);
if (downloadFile(mManifest.busyboxUrl, "busybox")) {
try {
// Process process = Runtime.getRuntime().exec(new String[] { "chmod", "755", mBusyboxPath });
Process process = new ProcessBuilder()
.command("chmod", "755", mBusyboxPath)
.redirectErrorStream(true).start();
Log.d(TAG, "chmod 755 " + mBusyboxPath);
process.waitFor();
process.destroy();
} catch (IOException e) {
Log.e(TAG, "Failed to set busybox to executable", e);
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
} catch (InterruptedException e) {
Log.w(TAG, "Process interrupted", e);
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
} else {
Log.e(TAG, "Failed to download busybox");
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail);
return STATUS_FINISHED_FAIL;
}
// Verify md5sum of busybox
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_md5sum);
if (verifyFile(mBusyboxPath, mManifest.busyboxMd5)) {
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
} else {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
// Check where the current su binary is installed
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_installed_path);
String installedSu = whichSu();
Log.d(TAG, "su installed to " + installedSu);
if (installedSu == null) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_find_su_failed);
return STATUS_FINISHED_FAIL;
} else if (installedSu.equals("/sbin/su")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
installedSu, CONSOLE_RED);
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_bad_install_location);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
installedSu, CONSOLE_GREEN);
// Download new su binary
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_download_su);
String suPath;
if (downloadFile(mManifest.binaryUrl, "su")) {
suPath = getActivity().getFileStreamPath("su").toString();
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
} else {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
// Verify md5sum of su
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_md5sum);
if (verifyFile(suPath, mManifest.binaryMd5)) {
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
} else {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
Process process = null;
try { // Just use one try/catch for all the root commands
// Get root access
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_get_root);
process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
BufferedReader is = new BufferedReader(new InputStreamReader(
new DataInputStream(process.getInputStream())), 64);
os.writeBytes("id\n");
String inLine = is.readLine();
if (inLine == null) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
Pattern pattern = Pattern.compile("uid=([\\d]+)");
Matcher matcher = pattern.matcher(inLine);
if (!matcher.find() || !matcher.group(1).equals("0")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Remount system partition
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_remount_rw);
executeCommand(os, null, mBusyboxPath + " mount -o remount,rw /system");
inLine = executeCommand(os, is, mBusyboxPath + " touch /system/su && " +
mBusyboxPath + " echo YEAH");
if (inLine == null || !inLine.equals("YEAH")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_ok, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Copy su to /system. Put it in here first so it's on the system
// partition then use an atomic move to make sure we don't get
// corrupted
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_cp);
inLine = executeCommand(os, is, mBusyboxPath, "cp", suPath, "/system &&",
mBusyboxPath, "echo YEAH");
if (inLine == null || !inLine.equals("YEAH")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Check su md5sum again. Do it often to make sure everything is
// going good.
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_md5sum);
inLine = executeCommand(os, is, mBusyboxPath, "md5sum /system/su");
if (inLine == null || !inLine.split(" ")[0].equals(mManifest.binaryMd5)) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Move /system/su to wherer it belongs
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_mv);
inLine = executeCommand(os, is, mBusyboxPath, "mv /system/su", installedSu,
"&&", mBusyboxPath, "echo YEAH");
if (inLine == null || !inLine.equals("YEAH")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Check su md5sum again. Last time, I promise
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_md5sum);
// Can't use the verifyFile method here since we need to be root
inLine = executeCommand(os, is, mBusyboxPath, "md5sum /system/bin/su");
if (inLine == null || !inLine.split(" ")[0].equals(mManifest.binaryMd5)) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Change su file mode
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_chmod);
inLine = executeCommand(os, is, mBusyboxPath, "chmod 06755 /system/bin/su &&",
mBusyboxPath, "echo YEAH");
if (inLine == null || !inLine.equals("YEAH")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Remount system partition
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_remount_ro);
executeCommand(os, null, mBusyboxPath, "mount -o remount,ro /system");
inLine = executeCommand(os, is, mBusyboxPath, "touch /system/su ||",
mBusyboxPath, "echo YEAH");
if (inLine == null || !inLine.equals("YEAH")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_remount_ro_failed);
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
os.writeBytes("exit\n");
} catch (IOException e) {
Log.e(TAG, "Failed to execute root commands", e);
} finally {
process.destroy();
}
// Verify the proper version is installed.
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_installed_version);
installedVersionCode = Util.getSuVersionCode();
installedVersion = Util.getSuVersion();
if (installedVersionCode == mManifest.versionCode) {
publishProgress(progressTotal, progressStep, progressStep,
installedVersion, CONSOLE_GREEN);
} else {
publishProgress(progressTotal, progressStep, progressStep,
installedVersion, CONSOLE_RED);
mCurrentStep = Step.DOWNLOAD_BUSYBOX;
return STATUS_FINISHED_FAIL;
}
// Clean up
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_clean_up);
getActivity().deleteFile("busybox");
getActivity().deleteFile("su");
if (fixDb) {
getActivity().deleteDatabase("permissions.sqlite");
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
return STATUS_FINISHED_SUCCESSFUL;
}
return -1;
}
| protected Integer doInBackground(Void... params) {
int progressTotal = 0;
int progressStep = 0;
switch (mCurrentStep) {
case DOWNLOAD_MANIFEST:
progressTotal = 4;
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_download_manifest);
if (downloadFile(MANIFEST_URL, "manifest")) {
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
} else {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
// Parse manifest
// TODO: Actually parse the manifest here, as of now it's being
// done at download time.
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_parse_manifest);
if (mManifest == null) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Display the latest version
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_latest_version);
publishProgress(progressTotal, progressStep, progressStep,
mManifest.version, CONSOLE_GREEN);
// Check the currently installed version
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_installed_version);
int installedVersionCode = Util.getSuVersionCode();
String installedVersion = Util.getSuVersion();
if (installedVersionCode < mManifest.versionCode) {
publishProgress(progressTotal, progressStep, progressStep,
installedVersion, CONSOLE_RED);
mCurrentStep = Step.DOWNLOAD_BUSYBOX;
return STATUS_AWAITING_ACTION;
} else {
publishProgress(progressTotal, progressStep, progressStep,
installedVersion, CONSOLE_GREEN);
mCurrentStep = Step.DOWNLOAD_BUSYBOX;
return STATUS_FINISHED_NO_NEED;
}
case DOWNLOAD_BUSYBOX:
// Fix the db if necessary. A bug in the 2.3x binary could cause
// the su binary to fail if there is no prefs table, which would
// happen if the user never opened the app. Fringe case, but
// needs to be addressed.
boolean fixDb = (Util.getSuVersionCode() == 0);
if (fixDb) {
progressTotal = 16;
progressStep = 1;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_fix_db);
SQLiteDatabase db = null;
try {
db = getActivity().openOrCreateDatabase(
"permissions.sqlite", Context.MODE_PRIVATE, null);
// We just need to make sure all the tables exist and have the proper
// columns. We'll delete this DB at the end of the update.
db.execSQL("CREATE TABLE IF NOT EXISTS apps (_id INTEGER, uid INTEGER, " +
"package TEXT, name TEXT, exec_uid INTEGER, exec_cmd TEXT, " +
" allow INTEGER, PRIMARY KEY (_id), UNIQUE (uid,exec_uid,exec_cmd))");
db.execSQL("CREATE TABLE IF NOT EXISTS logs (_id INTEGER, app_id INTEGER, " +
"date INTEGER, type INTEGER, PRIMARY KEY (_id))");
db.execSQL("CREATE TABLE IF NOT EXISTS prefs (_id INTEGER, key TEXT, " +
"value TEXT, PRIMARY KEY (_id))");
} catch (SQLException e) {
Log.e(TAG, "Failed to fix database", e);
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
} finally {
// Make sure we close the DB here, or the su call will also fail.
if (db != null) {
db.close();
}
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
} else {
progressTotal = 15;
progressStep = 0;
}
// Download custom tiny busybox
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_download_busybox);
if (downloadFile(mManifest.busyboxUrl, "busybox")) {
try {
// Process process = Runtime.getRuntime().exec(new String[] { "chmod", "755", mBusyboxPath });
Process process = new ProcessBuilder()
.command("chmod", "755", mBusyboxPath)
.redirectErrorStream(true).start();
Log.d(TAG, "chmod 755 " + mBusyboxPath);
process.waitFor();
process.destroy();
} catch (IOException e) {
Log.e(TAG, "Failed to set busybox to executable", e);
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
} catch (InterruptedException e) {
Log.w(TAG, "Process interrupted", e);
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
} else {
Log.e(TAG, "Failed to download busybox");
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail);
return STATUS_FINISHED_FAIL;
}
// Verify md5sum of busybox
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_md5sum);
if (verifyFile(mBusyboxPath, mManifest.busyboxMd5)) {
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
} else {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
// Check where the current su binary is installed
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_installed_path);
String installedSu = whichSu();
Log.d(TAG, "su installed to " + installedSu);
if (installedSu == null) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_find_su_failed);
return STATUS_FINISHED_FAIL;
} else if (installedSu.equals("/sbin/su")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
installedSu, CONSOLE_RED);
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_bad_install_location);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
installedSu, CONSOLE_GREEN);
// Download new su binary
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_download_su);
String suPath;
if (downloadFile(mManifest.binaryUrl, "su")) {
suPath = getActivity().getFileStreamPath("su").toString();
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
} else {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
// Verify md5sum of su
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_md5sum);
if (verifyFile(suPath, mManifest.binaryMd5)) {
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
} else {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
Process process = null;
try { // Just use one try/catch for all the root commands
// Get root access
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_get_root);
process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
BufferedReader is = new BufferedReader(new InputStreamReader(
new DataInputStream(process.getInputStream())), 64);
os.writeBytes("id\n");
String inLine = is.readLine();
if (inLine == null) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
Pattern pattern = Pattern.compile("uid=([\\d]+)");
Matcher matcher = pattern.matcher(inLine);
if (!matcher.find() || !matcher.group(1).equals("0")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Remount system partition
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_remount_rw);
executeCommand(os, null, mBusyboxPath + " mount -o remount,rw /system");
inLine = executeCommand(os, is, mBusyboxPath + " touch /system/su && " +
mBusyboxPath + " echo YEAH");
if (inLine == null || !inLine.equals("YEAH")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_ok, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Copy su to /system. Put it in here first so it's on the system
// partition then use an atomic move to make sure we don't get
// corrupted
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_cp);
inLine = executeCommand(os, is, mBusyboxPath, "cp", suPath, "/system &&",
mBusyboxPath, "echo YEAH");
if (inLine == null || !inLine.equals("YEAH")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Check su md5sum again. Do it often to make sure everything is
// going good.
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_md5sum);
inLine = executeCommand(os, is, mBusyboxPath, "md5sum /system/su");
if (inLine == null || !inLine.split(" ")[0].equals(mManifest.binaryMd5)) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Move /system/su to wherer it belongs
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_mv);
inLine = executeCommand(os, is, mBusyboxPath, "mv /system/su", installedSu,
"&&", mBusyboxPath, "echo YEAH");
if (inLine == null || !inLine.equals("YEAH")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Check su md5sum again. Last time, I promise
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_md5sum);
// Can't use the verifyFile method here since we need to be root
inLine = executeCommand(os, is, mBusyboxPath, "md5sum", installedSu);
if (inLine == null || !inLine.split(" ")[0].equals(mManifest.binaryMd5)) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
return STATUS_FINISHED_FAIL;
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Change su file mode
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_chmod);
inLine = executeCommand(os, is, mBusyboxPath, "chmod 06755", installedSu, "&&",
mBusyboxPath, "echo YEAH");
if (inLine == null || !inLine.equals("YEAH")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
// Remount system partition
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_remount_ro);
executeCommand(os, null, mBusyboxPath, "mount -o remount,ro /system");
inLine = executeCommand(os, is, mBusyboxPath, "touch /system/su ||",
mBusyboxPath, "echo YEAH");
if (inLine == null || !inLine.equals("YEAH")) {
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_fail, CONSOLE_RED);
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_remount_ro_failed);
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
os.writeBytes("exit\n");
} catch (IOException e) {
Log.e(TAG, "Failed to execute root commands", e);
} finally {
process.destroy();
}
// Verify the proper version is installed.
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_check_installed_version);
installedVersionCode = Util.getSuVersionCode();
installedVersion = Util.getSuVersion();
if (installedVersionCode == mManifest.versionCode) {
publishProgress(progressTotal, progressStep, progressStep,
installedVersion, CONSOLE_GREEN);
} else {
publishProgress(progressTotal, progressStep, progressStep,
installedVersion, CONSOLE_RED);
mCurrentStep = Step.DOWNLOAD_BUSYBOX;
return STATUS_FINISHED_FAIL;
}
// Clean up
progressStep++;
publishProgress(progressTotal, progressStep - 1, progressStep,
R.string.updater_step_clean_up);
getActivity().deleteFile("busybox");
getActivity().deleteFile("su");
if (fixDb) {
getActivity().deleteDatabase("permissions.sqlite");
}
publishProgress(progressTotal, progressStep, progressStep,
R.string.updater_ok, CONSOLE_GREEN);
return STATUS_FINISHED_SUCCESSFUL;
}
return -1;
}
|
diff --git a/src/main/java/by/stub/database/thread/ConfigurationScanner.java b/src/main/java/by/stub/database/thread/ConfigurationScanner.java
index 513ad20..e455287 100644
--- a/src/main/java/by/stub/database/thread/ConfigurationScanner.java
+++ b/src/main/java/by/stub/database/thread/ConfigurationScanner.java
@@ -1,71 +1,79 @@
package by.stub.database.thread;
import by.stub.cli.ANSITerminal;
import by.stub.database.DataStore;
import by.stub.utils.StringUtils;
import by.stub.yaml.YamlParser;
import by.stub.yaml.stubs.StubHttpLifecycle;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
/**
* @author Alexander Zagniotov
* @since 11/6/12, 8:01 AM
*/
public final class ConfigurationScanner implements Runnable {
private long lastModified;
private final YamlParser yamlParser;
private final DataStore dataStore;
private static volatile boolean startFlag = true;
public ConfigurationScanner(final YamlParser yamlParser, final DataStore dataStore) {
this.yamlParser = yamlParser;
this.dataStore = dataStore;
}
@Override
public void run() {
try {
final String loadedConfigYamlPath = yamlParser.getLoadedConfigYamlPath();
final File loadedConfig = new File(loadedConfigYamlPath);
this.lastModified = loadedConfig.lastModified();
while (startFlag) {
Thread.sleep(3000);
final long currentFileModified = loadedConfig.lastModified();
if (this.lastModified >= currentFileModified) {
continue;
}
- this.lastModified = currentFileModified;
- final InputStream is = new FileInputStream(loadedConfigYamlPath);
- final Reader yamlReader = new InputStreamReader(is, StringUtils.utf8Charset());
- final List<StubHttpLifecycle> stubHttpLifecycles = yamlParser.parseAndLoad(yamlReader);
+ try {
+ this.lastModified = currentFileModified;
+ final InputStream is = new FileInputStream(loadedConfigYamlPath);
+ final Reader yamlReader = new InputStreamReader(is, StringUtils.utf8Charset());
+ final List<StubHttpLifecycle> stubHttpLifecycles = yamlParser.parseAndLoad(yamlReader);
- dataStore.resetStubHttpLifecycles(stubHttpLifecycles);
- ANSITerminal.ok(String.format("%sSuccessfully performed live reload of YAML configuration from: %s%s",
- "\n",
- loadedConfigYamlPath,
- "\n"));
+ dataStore.resetStubHttpLifecycles(stubHttpLifecycles);
+ ANSITerminal.ok(String.format("%sSuccessfully performed live reload of YAML configuration from: %s%s",
+ "\n",
+ loadedConfigYamlPath,
+ "\n"));
+ } catch (final Exception ex) {
+ ANSITerminal.warn("Could not reload YAML configuration: " + ex.toString());
+ ANSITerminal.error(String.format("%sFailed to perform live reload of YAML configuration from: %s%s",
+ "\n",
+ loadedConfigYamlPath,
+ "\n"));
+ }
}
} catch (final Exception ex) {
- ANSITerminal.error("Could not reload YAML configuration: " + ex.toString());
+ ANSITerminal.error("Could not perform live YAML scan: " + ex.toString());
}
}
public void stopScanner(final boolean toStop) {
synchronized (ConfigurationScanner.class) {
startFlag = toStop;
}
}
}
| false | true | public void run() {
try {
final String loadedConfigYamlPath = yamlParser.getLoadedConfigYamlPath();
final File loadedConfig = new File(loadedConfigYamlPath);
this.lastModified = loadedConfig.lastModified();
while (startFlag) {
Thread.sleep(3000);
final long currentFileModified = loadedConfig.lastModified();
if (this.lastModified >= currentFileModified) {
continue;
}
this.lastModified = currentFileModified;
final InputStream is = new FileInputStream(loadedConfigYamlPath);
final Reader yamlReader = new InputStreamReader(is, StringUtils.utf8Charset());
final List<StubHttpLifecycle> stubHttpLifecycles = yamlParser.parseAndLoad(yamlReader);
dataStore.resetStubHttpLifecycles(stubHttpLifecycles);
ANSITerminal.ok(String.format("%sSuccessfully performed live reload of YAML configuration from: %s%s",
"\n",
loadedConfigYamlPath,
"\n"));
}
} catch (final Exception ex) {
ANSITerminal.error("Could not reload YAML configuration: " + ex.toString());
}
}
| public void run() {
try {
final String loadedConfigYamlPath = yamlParser.getLoadedConfigYamlPath();
final File loadedConfig = new File(loadedConfigYamlPath);
this.lastModified = loadedConfig.lastModified();
while (startFlag) {
Thread.sleep(3000);
final long currentFileModified = loadedConfig.lastModified();
if (this.lastModified >= currentFileModified) {
continue;
}
try {
this.lastModified = currentFileModified;
final InputStream is = new FileInputStream(loadedConfigYamlPath);
final Reader yamlReader = new InputStreamReader(is, StringUtils.utf8Charset());
final List<StubHttpLifecycle> stubHttpLifecycles = yamlParser.parseAndLoad(yamlReader);
dataStore.resetStubHttpLifecycles(stubHttpLifecycles);
ANSITerminal.ok(String.format("%sSuccessfully performed live reload of YAML configuration from: %s%s",
"\n",
loadedConfigYamlPath,
"\n"));
} catch (final Exception ex) {
ANSITerminal.warn("Could not reload YAML configuration: " + ex.toString());
ANSITerminal.error(String.format("%sFailed to perform live reload of YAML configuration from: %s%s",
"\n",
loadedConfigYamlPath,
"\n"));
}
}
} catch (final Exception ex) {
ANSITerminal.error("Could not perform live YAML scan: " + ex.toString());
}
}
|
diff --git a/src/main/java/br/octahedron/figgo/modules/bank/data/BankTransactionDAO.java b/src/main/java/br/octahedron/figgo/modules/bank/data/BankTransactionDAO.java
index 88bc244..e1a415e 100644
--- a/src/main/java/br/octahedron/figgo/modules/bank/data/BankTransactionDAO.java
+++ b/src/main/java/br/octahedron/figgo/modules/bank/data/BankTransactionDAO.java
@@ -1,236 +1,236 @@
/*
* Straight - A system to manage financial demands for small and decentralized
* organizations.
* Copyright (C) 2011 Octahedron
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package br.octahedron.figgo.modules.bank.data;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeSet;
import javax.jdo.Query;
import br.octahedron.cotopaxi.datastore.jdo.GenericDAO;
import br.octahedron.figgo.modules.bank.TransactionInfoService;
/**
* A DAO for transactions.
*
* @author Danilo Queiroz
*/
public class BankTransactionDAO extends GenericDAO<BankTransaction> implements TransactionInfoService {
public BankTransactionDAO() {
super(BankTransaction.class);
}
public Collection<BankTransaction> getLastNTransactions(String accountId, int n) {
return this.getAllTransactions(accountId, n);
}
/*
* (non-Javadoc)
*
* @see br.octahedron.straight.bank.TransactionInfoService#getLastTransactions(java.lang.Long,
* java.lang.Long)
*/
@Override
public Collection<BankTransaction> getLastTransactions(String accountId, Long startDate) {
if (startDate == null) {
return this.getAllTransactions(accountId, Long.MIN_VALUE);
} else {
return this.getLastTransactionsFrom(accountId, startDate);
}
}
/*
* (non-Javadoc)
*
* @see
* br.octahedron.straight.bank.TransactionInfoService#getTransactionsByDateRange(java.lang.String
* , java.util.Date, java.util.Date)
*/
@Override
public Collection<BankTransaction> getTransactionsByDateRange(String accountId, Date startDate, Date endDate) {
Collection<BankTransaction> creditTransactions = this.getCreditTransactionsByDateRange(accountId, startDate, endDate);
Collection<BankTransaction> debitTransactions = this.getDebitTransactionsByDateRange(accountId, startDate, endDate);
return this.mergeTransactions(creditTransactions, debitTransactions, Long.MIN_VALUE);
}
@SuppressWarnings("unchecked")
protected Collection<BankTransaction> getCreditTransactionsByDateRange(String accountId, Date startDate, Date endDate) {
Query query = this.createQuery();
query.setFilter("accountDest == :accountId && timestamp >= :startDate && timestamp <= :endDate");
return (List<BankTransaction>) query.execute(accountId, startDate.getTime(), endDate.getTime());
}
@SuppressWarnings("unchecked")
protected Collection<BankTransaction> getDebitTransactionsByDateRange(String accountId, Date startDate, Date endDate) {
Query query = this.createQuery();
query.setFilter("accountOrig == :accountId && timestamp >= :startDate && timestamp <= :endDate");
return (List<BankTransaction>) query.execute(accountId, startDate.getTime(), endDate.getTime());
}
/**
* Returns an account credit amount specified by a date range
*
* @param accountId
* accountId of the account
* @param startDate
* startDate of the range
* @param endDate
* endDate of the range
*
* @return an amount representing the sum of all credit transactions of an account
*/
public BigDecimal getAmountCreditByDateRange(String accountId, Date startDate, Date endDate) {
Collection<BankTransaction> transactions = this.getCreditTransactionsByDateRange(accountId, startDate, endDate);
BigDecimal sum = BigDecimal.ZERO;
for (BankTransaction transaction : transactions) {
if (!transaction.getAccountOrig().equals(SystemAccount.ID)) {
sum = sum.add(transaction.getAmount());
}
}
return sum;
}
/**
* Returns the amount of transactions specified by a date range
*
* @param startDate
* startDate of the range
* @param endDate
* endDate of the range
*
* @return an amount representing the sum of all transactions made on the date range
*/
@SuppressWarnings("unchecked")
public BigDecimal getAllAmountByDateRange(Date startDate, Date endDate) {
Query query = this.createQuery();
query.setFilter("timestamp >= :startDate && timestamp <= :endDate");
List<BankTransaction> transactions = (List<BankTransaction>) query.execute(startDate.getTime(), endDate.getTime());
BigDecimal sum = BigDecimal.ZERO;
for (BankTransaction transaction : transactions) {
if (!transaction.getAccountOrig().equals(SystemAccount.ID)) {
sum = sum.add(transaction.getAmount());
}
}
return sum;
}
/**
* Get last transactions older than the given lastUsedTransaction
*/
@SuppressWarnings("unchecked")
private Collection<BankTransaction> getLastTransactionsFrom(String accountId, Long lastUsedTransaction) {
Query query = this.createQuery();
query.setFilter("timestamp >= :timestamp && accountOrig == :accId");
query.setOrdering("timestamp asc");
List<BankTransaction> transactions1 = (List<BankTransaction>) query.execute(lastUsedTransaction, accountId);
query = this.createQuery();
query.setFilter("timestamp >= :timestamp && accountDest == :accId");
query.setOrdering("timestamp asc");
List<BankTransaction> transactions2 = (List<BankTransaction>) query.execute(lastUsedTransaction, accountId);
return this.mergeTransactions(transactions1, transactions2, Long.MIN_VALUE);
}
/**
* Get all transactions for an account
*/
@SuppressWarnings("unchecked")
private Collection<BankTransaction> getAllTransactions(String accountId, long count) {
Query query = this.createQuery();
query.setFilter("accountOrig == :accId");
- query.setOrdering("timestamp asc");
+ query.setOrdering("timestamp desc");
if (count > 0) {
query.setRange(0, count);
}
List<BankTransaction> transactions1 = (List<BankTransaction>) query.execute(accountId);
query = this.createQuery();
query.setFilter("accountDest == :accId");
- query.setOrdering("timestamp asc");
+ query.setOrdering("timestamp desc");
if (count > 0) {
query.setRange(0, count);
}
List<BankTransaction> transactions2 = (List<BankTransaction>) query.execute(accountId);
return this.mergeTransactions(transactions1, transactions2, count);
}
/**
* Merges two transactions list ordering transactions by id (lower to higher)
*
* @param count
*
* @return a list with transactions from the two lists, ordered by id.
*/
private Collection<BankTransaction> mergeTransactions(Collection<BankTransaction> transactions1, Collection<BankTransaction> transactions2,
long count) {
TreeSet<BankTransaction> result = new TreeSet<BankTransaction>(new BankTransactionComparator());
result.addAll(transactions1);
result.addAll(transactions2);
if (count == Long.MIN_VALUE) {
return result;
} else {
List<BankTransaction> other = new LinkedList<BankTransaction>();
Iterator<BankTransaction> itr = result.descendingIterator();
while (itr.hasNext() && count != 0) {
other.add(itr.next());
count--;
}
return other;
}
}
/**
* Returns the whole amount injected on the bank by admin.
*
* @return an amount representing the whole injected amount on the bank
*/
@SuppressWarnings("unchecked")
public BigDecimal getBallast() {
Query query = this.createQuery();
query.setFilter("accountOrig == :accOrig");
List<BankTransaction> transactions = (List<BankTransaction>) query.execute(SystemAccount.ID);
BigDecimal sum = BigDecimal.ZERO;
for (BankTransaction transaction : transactions) {
sum = sum.add(transaction.getAmount());
}
return sum;
}
/**
* Compares banktransaction by timestamp. It ignores equals transactions, it means, if two
* transactions have the same timestamp it will -1 arbitrarily.
*/
private class BankTransactionComparator implements Comparator<BankTransaction> {
public int compare(BankTransaction o1, BankTransaction o2) {
int comp = o1.getTimestamp().compareTo(o2.getTimestamp());
return (comp != 0) ? comp : o1.getId().compareTo(o2.getId());
}
}
}
| false | true | private Collection<BankTransaction> getAllTransactions(String accountId, long count) {
Query query = this.createQuery();
query.setFilter("accountOrig == :accId");
query.setOrdering("timestamp asc");
if (count > 0) {
query.setRange(0, count);
}
List<BankTransaction> transactions1 = (List<BankTransaction>) query.execute(accountId);
query = this.createQuery();
query.setFilter("accountDest == :accId");
query.setOrdering("timestamp asc");
if (count > 0) {
query.setRange(0, count);
}
List<BankTransaction> transactions2 = (List<BankTransaction>) query.execute(accountId);
return this.mergeTransactions(transactions1, transactions2, count);
}
| private Collection<BankTransaction> getAllTransactions(String accountId, long count) {
Query query = this.createQuery();
query.setFilter("accountOrig == :accId");
query.setOrdering("timestamp desc");
if (count > 0) {
query.setRange(0, count);
}
List<BankTransaction> transactions1 = (List<BankTransaction>) query.execute(accountId);
query = this.createQuery();
query.setFilter("accountDest == :accId");
query.setOrdering("timestamp desc");
if (count > 0) {
query.setRange(0, count);
}
List<BankTransaction> transactions2 = (List<BankTransaction>) query.execute(accountId);
return this.mergeTransactions(transactions1, transactions2, count);
}
|
diff --git a/DailyAppLib/src/com/dailystudio/app/async/PeroidicalAsyncChecker.java b/DailyAppLib/src/com/dailystudio/app/async/PeroidicalAsyncChecker.java
index 59f2bee..4982582 100644
--- a/DailyAppLib/src/com/dailystudio/app/async/PeroidicalAsyncChecker.java
+++ b/DailyAppLib/src/com/dailystudio/app/async/PeroidicalAsyncChecker.java
@@ -1,40 +1,47 @@
package com.dailystudio.app.async;
import com.dailystudio.datetime.CalendarUtils;
import com.dailystudio.development.Logger;
import android.content.Context;
public abstract class PeroidicalAsyncChecker extends AsyncChecker {
public PeroidicalAsyncChecker(Context context) {
super(context);
}
public void runIfOnTime() {
final long now = System.currentTimeMillis();
final long interval = getCheckInterval();
final long lastTimestamp = getLastCheckTimestamp(mContext);
Logger.debug("lastTimestamp = %d(%s), current = %d(%s), checkInterval = %d(%s)",
lastTimestamp,
CalendarUtils.timeToReadableString(lastTimestamp),
now,
CalendarUtils.timeToReadableString(now),
interval,
CalendarUtils.durationToReadableString(interval));
final long elapsed = now - lastTimestamp;
+ /*
+ * XXX: elapsed < 0 means there is some time problem
+ * during last check, because the laststamp even large
+ * than current time, we should run this at once to
+ * correct this issue.
+ */
if (lastTimestamp == -1
- || (elapsed >= interval)) {
+ || (elapsed >= interval)
+ || (elapsed < 0)) {
run();
} else {
Logger.warnning("time elapsed(%s) less than interval, skip",
CalendarUtils.durationToReadableString(elapsed),
CalendarUtils.durationToReadableString(interval));
}
}
abstract public long getCheckInterval();
}
| false | true | public void runIfOnTime() {
final long now = System.currentTimeMillis();
final long interval = getCheckInterval();
final long lastTimestamp = getLastCheckTimestamp(mContext);
Logger.debug("lastTimestamp = %d(%s), current = %d(%s), checkInterval = %d(%s)",
lastTimestamp,
CalendarUtils.timeToReadableString(lastTimestamp),
now,
CalendarUtils.timeToReadableString(now),
interval,
CalendarUtils.durationToReadableString(interval));
final long elapsed = now - lastTimestamp;
if (lastTimestamp == -1
|| (elapsed >= interval)) {
run();
} else {
Logger.warnning("time elapsed(%s) less than interval, skip",
CalendarUtils.durationToReadableString(elapsed),
CalendarUtils.durationToReadableString(interval));
}
}
| public void runIfOnTime() {
final long now = System.currentTimeMillis();
final long interval = getCheckInterval();
final long lastTimestamp = getLastCheckTimestamp(mContext);
Logger.debug("lastTimestamp = %d(%s), current = %d(%s), checkInterval = %d(%s)",
lastTimestamp,
CalendarUtils.timeToReadableString(lastTimestamp),
now,
CalendarUtils.timeToReadableString(now),
interval,
CalendarUtils.durationToReadableString(interval));
final long elapsed = now - lastTimestamp;
/*
* XXX: elapsed < 0 means there is some time problem
* during last check, because the laststamp even large
* than current time, we should run this at once to
* correct this issue.
*/
if (lastTimestamp == -1
|| (elapsed >= interval)
|| (elapsed < 0)) {
run();
} else {
Logger.warnning("time elapsed(%s) less than interval, skip",
CalendarUtils.durationToReadableString(elapsed),
CalendarUtils.durationToReadableString(interval));
}
}
|
diff --git a/src/java/fedora/server/storage/replication/DefaultDOReplicator.java b/src/java/fedora/server/storage/replication/DefaultDOReplicator.java
index b93db7eca..b6fd40e18 100755
--- a/src/java/fedora/server/storage/replication/DefaultDOReplicator.java
+++ b/src/java/fedora/server/storage/replication/DefaultDOReplicator.java
@@ -1,2657 +1,2657 @@
package fedora.server.storage.replication;
import java.util.*;
import java.sql.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Pattern;
import fedora.server.errors.*;
import fedora.server.storage.*;
import fedora.server.storage.types.*;
import fedora.server.utilities.SQLUtility;
import fedora.server.Module;
import fedora.server.Server;
import fedora.server.storage.ConnectionPoolManager;
import fedora.server.errors.ModuleInitializationException;
/**
*
* <p><b>Title:</b> DefaultDOReplicator.java</p>
* <p><b>Description:</b> A Module that replicates digital object information
* to the dissemination database.</p>
*
* <p>Converts data read from the object reader interfaces and creates or
* updates the corresponding database rows in the dissemination database.</p>
*
* -----------------------------------------------------------------------------
*
* <p><b>License and Copyright: </b>The contents of this file are subject to the
* Mozilla Public License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License
* at <a href="http://www.mozilla.org/MPL">http://www.mozilla.org/MPL/.</a></p>
*
* <p>Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.</p>
*
* <p>The entire file consists of original code. Copyright © 2002, 2003 by The
* Rector and Visitors of the University of Virginia and Cornell University.
* All rights reserved.</p>
*
* -----------------------------------------------------------------------------
*
* @author Paul Charlton, [email protected]
* @version $Id$
*/
public class DefaultDOReplicator
extends Module
implements DOReplicator {
private ConnectionPool m_pool;
private RowInsertion m_ri;
private DBIDLookup m_dl;
// sdp - local.fedora.server conversion
private Pattern hostPattern = null;
private Pattern hostPortPattern = null;
private Pattern serializedLocalURLPattern = null;
/**
* Server instance to work with in this module.
*/
private Server server;
/** Port number on which the Fedora server is running; determined from
* fedora.fcfg config file.
*/
private static String fedoraServerPort = null;
/** Hostname of the Fedora server determined from
* fedora.fcfg config file, or (fallback) by hostIP.getHostName()
*/
private static String fedoraServerHost = null;
/** The IP address of the local host; determined dynamically. */
private static InetAddress hostIP = null;
public DefaultDOReplicator(Map moduleParameters, Server server, String role)
throws ModuleInitializationException {
super(moduleParameters, server, role);
}
public void initModule() {
}
public void postInitModule()
throws ModuleInitializationException {
try {
ConnectionPoolManager mgr=(ConnectionPoolManager)
getServer().getModule(
"fedora.server.storage.ConnectionPoolManager");
m_pool=mgr.getPool();
// sdp: insert new
hostIP = null;
fedoraServerPort = getServer().getParameter("fedoraServerPort");
getServer().logFinest("fedoraServerPort: " + fedoraServerPort);
hostIP = InetAddress.getLocalHost();
fedoraServerHost = getServer().getParameter("fedoraServerHost");
if (fedoraServerHost==null || fedoraServerHost.equals("")) {
fedoraServerHost=hostIP.getHostName();
}
hostPattern = Pattern.compile("http://"+fedoraServerHost+"/");
hostPortPattern = Pattern.compile("http://"+fedoraServerHost+":"+fedoraServerPort+"/");
serializedLocalURLPattern = Pattern.compile("http://local.fedora.server/");
//System.out.println("Replicator: hostPattern is " + hostPattern.pattern());
//System.out.println("Replicator: hostPortPattern is " + hostPortPattern.pattern());
//
} catch (ServerException se) {
throw new ModuleInitializationException(
"Error getting default pool: " + se.getMessage(),
getRole());
} catch (UnknownHostException se) {
throw new ModuleInitializationException(
"Error determining hostIP address: " + se.getMessage(),
getRole());
}
}
/**
* If the object has already been replicated, update the components
* and return true. Otherwise, return false.
*
* @ids=select doDbID from do where doPID='demo:5'
* if @ids.size=0, return false
* else:
* foreach $id in @ids
* ds=reader.getDatastream(id, null)
* update dsBind set dsLabel='mylabel', dsLocation='' where dsID='$id'
*
* // currentVersionId?
*
* @param reader a digital object reader.
* @return true is successful update; false oterhwise.
* @throws ReplicationException if replication fails for any reason.
*/
private boolean updateComponents(DOReader reader)
throws ReplicationException {
Connection connection=null;
Statement st=null;
ResultSet results=null;
boolean triedUpdate=false;
boolean failed=false;
logFinest("DefaultDOReplicator.updateComponents: Entering ------");
try {
connection=m_pool.getConnection();
st=connection.createStatement();
// get db ID for the digital object
results=logAndExecuteQuery(st, "SELECT doDbID,doState FROM do WHERE "
+ "doPID='" + reader.GetObjectPID() + "'");
if (!results.next()) {
logFinest("DefaultDOReplication.updateComponents: Object is "
+ "new; components dont need updating.");
return false;
}
int doDbID=results.getInt("doDbID");
String doState=results.getString("doState");
results.close();
ArrayList updates=new ArrayList();
// check if state has changed for the digital object
String objState = reader.GetObjectState();
if (!doState.equalsIgnoreCase(objState)) {
updates.add("UPDATE do SET doState='"+objState+"' WHERE doDbID=" + doDbID);
updates.add("UPDATE doRegistry SET objectState='"+objState+"' WHERE doPID='" + reader.GetObjectPID() + "'");
}
// check if any mods to datastreams for this digital object
results=logAndExecuteQuery(st, "SELECT dsID, dsLabel, dsLocation, dsCurrentVersionID, dsState "
+ "FROM dsBind WHERE doDbID=" + doDbID);
while (results.next()) {
String dsID=results.getString("dsID");
String dsLabel=results.getString("dsLabel");
String dsCurrentVersionID=results.getString("dsCurrentVersionID");
String dsState=results.getString("dsState");
// sdp - local.fedora.server conversion
String dsLocation=unencodeLocalURL(results.getString("dsLocation"));
// compare the latest version of the datastream to what's in the db...
// if different, add to update list
Datastream ds=reader.GetDatastream(dsID, null);
if (!ds.DSLabel.equals(dsLabel)
|| !ds.DSLocation.equals(dsLocation)
|| !ds.DSVersionID.equals(dsCurrentVersionID)
|| !ds.DSState.equals(dsState)) {
updates.add("UPDATE dsBind SET dsLabel='"
+ SQLUtility.aposEscape(ds.DSLabel) + "', dsLocation='"
// sdp - local.fedora.server conversion
+ SQLUtility.aposEscape(encodeLocalURL(ds.DSLocation))
+ "', dsCurrentVersionID='" + ds.DSVersionID + "', "
+ "dsState='" + ds.DSState + "' "
+ " WHERE doDbID=" + doDbID + " AND dsID='" + dsID + "'");
}
}
results.close();
// do any required updates via a transaction
if (updates.size()>0) {
connection.setAutoCommit(false);
triedUpdate=true;
for (int i=0; i<updates.size(); i++) {
String update=(String) updates.get(i);
logAndExecuteUpdate(st, update);
}
connection.commit();
} else {
logFinest("No datastream labels or locations changed.");
}
// check if any mods to disseminators for this object...
// first get a list of disseminator db IDs
results=logAndExecuteQuery(st, "SELECT dissDbID FROM doDissAssoc WHERE "
+ "doDbID="+doDbID);
HashSet dissDbIDs = new HashSet();
while (results.next()) {
dissDbIDs.add(new Integer(results.getInt("dissDbID")));
}
- if (dissDbIDs.size()==0) {
+ if (dissDbIDs.size()==0 || reader.GetDisseminators(null, null).length!=dissDbIDs.size()) {
logFinest("DefaultDOReplication.updateComponents: Object "
+ "has no disseminators; components dont need updating.");
return false;
}
results.close();
Iterator dissIter = dissDbIDs.iterator();
// Iterate over disseminators to check if any have been modified
while(dissIter.hasNext()) {
Integer dissDbID = (Integer) dissIter.next();
logFinest("Iterating, dissDbID: "+dissDbID);
// get disseminator info for this disseminator
results=logAndExecuteQuery(st, "SELECT diss.bDefDbID, diss.bMechDbID, bMech.bMechPID, diss.dissID, diss.dissLabel, diss.dissState "
+ "FROM diss,bMech WHERE bMech.bMechDbID=diss.bMechDbID AND diss.dissDbID=" + dissDbID);
updates=new ArrayList();
int bDefDbID = 0;
int bMechDbID = 0;
String dissID=null;
String dissLabel=null;
String dissState=null;
String bMechPID=null;
while(results.next()) {
bDefDbID = results.getInt("bDefDbID");
bMechDbID = results.getInt("bMechDbID");
dissID=results.getString("dissID");
dissLabel=results.getString("dissLabel");
dissState=results.getString("dissState");
bMechPID=results.getString("bMechPID");
}
results.close();
// compare the latest version of the disseminator with what's in the db...
// replace what's in db if they are different
Disseminator diss=reader.GetDisseminator(dissID, null);
if (diss == null) {
// xml object has no disseminators
// so this must be a purgeComponents or a new object
logFinest("DefaultDOReplicator.updateComponents: XML object has no disseminators");
return false;
}
if (!diss.dissLabel.equals(dissLabel)
|| !diss.bMechID.equals(bMechPID)
|| !diss.dissState.equals(dissState)) {
if (!diss.dissLabel.equals(dissLabel))
logFinest("dissLabel changed from '" + dissLabel + "' to '" + diss.dissLabel + "'");
if (!diss.dissState.equals(dissState))
logFinest("dissState changed from '" + dissState + "' to '" + diss.dissState + "'");
// we might need to set the bMechDbID to the id for the new one,
// if the mechanism changed
int newBMechDbID;
if (diss.bMechID.equals(bMechPID)) {
newBMechDbID=bMechDbID;
} else {
logFinest("bMechPID changed from '" + bMechPID + "' to '" + diss.bMechID + "'");
results=logAndExecuteQuery(st, "SELECT bMechDbID "
+ "FROM bMech "
+ "WHERE bMechPID='"
+ diss.bMechID + "'");
if (!results.next()) {
// shouldn't have gotten this far, but if so...
throw new ReplicationException("The behavior mechanism "
+ "changed to " + diss.bMechID + ", but there is no "
+ "record of that object in the dissemination db.");
}
newBMechDbID=results.getInt("bMechDbID");
results.close();
}
// update the diss table with all new, correct values
logAndExecuteUpdate(st, "UPDATE diss SET dissLabel='"
+ SQLUtility.aposEscape(diss.dissLabel)
+ "', bMechDbID=" + newBMechDbID + ", "
+ "dissID='" + diss.dissID + "', "
+ "dissState='" + diss.dissState + "' "
+ " WHERE dissDbID=" + dissDbID + " AND bDefDbID=" + bDefDbID + " AND bMechDbID=" + bMechDbID);
}
// compare the latest version of the disseminator's bindMap with what's in the db
// and replace what's in db if they are different
results=logAndExecuteQuery(st, "SELECT DISTINCT dsBindMap.dsBindMapID,dsBindMap.dsBindMapDbID FROM dsBind,dsBindMap WHERE "
+ "dsBind.doDbID=" + doDbID + " AND dsBindMap.dsBindMapDbID=dsBind.dsBindMapDbID "
+ "AND dsBindMap.bMechDbID="+bMechDbID);
String origDSBindMapID=null;
int origDSBindMapDbID=0;
while (results.next()) {
origDSBindMapID=results.getString("dsBindMapID");
origDSBindMapDbID=results.getInt("dsBindMapDbID");
}
results.close();
String newDSBindMapID=diss.dsBindMapID;
if (!newDSBindMapID.equals(origDSBindMapID)) {
// dsBindingMap was modified so remove original bindingMap and datastreams.
// BindingMaps can be shared by other objects so first check to see if
// the orignial bindingMap is bound to datastreams of any other objects.
Statement st2 = connection.createStatement();
results=logAndExecuteQuery(st2,"SELECT DISTINCT doDbId,dsBindMapDbId FROM dsBind WHERE dsBindMapDbId="+origDSBindMapDbID);
int numRows = 0;
while (results.next()) {
numRows++;
}
st2.close();
results.close();
if(numRows == 1) {
// The bindingMap is NOT shared by any other objects and can be removed.
int rowCount = logAndExecuteUpdate(st, "DELETE FROM dsBindMap WHERE dsBindMapDbID=" + origDSBindMapDbID);
logFinest("deleted "+rowCount+" rows from dsBindMapDbID");
} else {
// The bindingMap IS shared by other objects so leave bindingMap untouched.
logFinest("dsBindMapID: "+origDSBindMapID+" is shared by other objects; it will NOT be deleted");
}
int rowCount = logAndExecuteUpdate(st,"DELETE FROM dsBind WHERE doDbID=" + doDbID);
logFinest("deleted "+rowCount+" rows from dsBind");
// now add back new datastreams and dsBindMap associated with this disseminator
DSBindingMapAugmented[] allBindingMaps;
Disseminator disseminators[];
String bDefDBID;
String bindingMapDBID;
String bMechDBID;
String dissDBID;
String doDBID;
String doPID;
String doLabel;
String dsBindingKeyDBID;
allBindingMaps = reader.GetDSBindingMaps(null);
for (int i=0; i<allBindingMaps.length; ++i) {
// only update bindingMap that was modified
if (allBindingMaps[i].dsBindMapID.equals(newDSBindMapID)) {
bMechDBID = lookupBehaviorMechanismDBID(connection,
allBindingMaps[i].dsBindMechanismPID);
if (bMechDBID == null) {
throw new ReplicationException("BehaviorMechanism row "
+ "doesn't exist for PID: "
+ allBindingMaps[i].dsBindMechanismPID);
}
// Insert dsBindMap row if it doesn't exist.
bindingMapDBID = lookupDataStreamBindingMapDBID(connection,
bMechDBID, allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
// DataStreamBinding row doesn't exist, add it.
insertDataStreamBindingMapRow(connection, bMechDBID,
allBindingMaps[i].dsBindMapID,
allBindingMaps[i].dsBindMapLabel);
bindingMapDBID = lookupDataStreamBindingMapDBID(
connection,bMechDBID,allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
throw new ReplicationException(
"lookupdsBindMapDBID row "
+ "doesn't exist for bMechDBID: " + bMechDBID
+ ", dsBindingMapID: "
+ allBindingMaps[i].dsBindMapID);
}
}
logFinest("augmentedlength: "+allBindingMaps[i].dsBindingsAugmented.length);
for (int j=0; j<allBindingMaps[i].dsBindingsAugmented.length;
++j) {
logFinest("j: "+j);
dsBindingKeyDBID = lookupDataStreamBindingSpecDBID(
connection, bMechDBID,
allBindingMaps[i].dsBindingsAugmented[j].
bindKeyName);
if (dsBindingKeyDBID == null) {
throw new ReplicationException(
"lookupDataStreamBindingDBID row doesn't "
+ "exist for bMechDBID: " + bMechDBID
+ ", bindKeyName: " + allBindingMaps[i].
dsBindingsAugmented[j].bindKeyName + "i=" + i
+ " j=" + j);
}
// Insert DataStreamBinding row
insertDataStreamBindingRow(connection, new Integer(doDbID).toString(),
dsBindingKeyDBID,
bindingMapDBID,
allBindingMaps[i].dsBindingsAugmented[j].seqNo,
allBindingMaps[i].dsBindingsAugmented[j].
datastreamID,
allBindingMaps[i].dsBindingsAugmented[j].DSLabel,
allBindingMaps[i].dsBindingsAugmented[j].DSMIME,
// sdp - local.fedora.server conversion
encodeLocalURL(allBindingMaps[i].dsBindingsAugmented[j].DSLocation),
allBindingMaps[i].dsBindingsAugmented[j].DSControlGrp,
allBindingMaps[i].dsBindingsAugmented[j].DSVersionID,
"1",
"A");
}
}
}
}
}
} catch (SQLException sqle) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage());
} catch (ServerException se) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection!=null) {
try {
if (triedUpdate && failed) connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName()
+ ": " + th.getMessage());
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
connection.setAutoCommit(true);
} catch (SQLException sqle) {
logWarning("While cleaning up: " + sqle.getClass().getName()
+ ": " + sqle.getMessage());
} finally {
m_pool.free(connection);
}
}
}
}
logFinest("DefaultDOReplicator.updateComponents: Exiting ------");
return true;
}
private boolean addNewComponents(DOReader reader)
throws ReplicationException {
Connection connection=null;
Statement st=null;
ResultSet results=null;
boolean failed=false;
logFinest("DefaultDOReplicator.addNewComponents: Entering ------");
try {
String doPID = reader.GetObjectPID();
connection=m_pool.getConnection();
connection.setAutoCommit(false);
st=connection.createStatement();
// get db ID for the digital object
results=logAndExecuteQuery(st, "SELECT doDbID FROM do WHERE "
+ "doPID='" + doPID + "'");
if (!results.next()) {
logFinest("DefaultDOReplication.addNewComponents: Object is "
+ "new; components will be added as part of new object replication.");
return false;
}
int doDbID=results.getInt("doDbID");
results.close();
Disseminator[] dissArray = reader.GetDisseminators(null, null);
HashSet newDisseminators = new HashSet();
for (int j=0; j< dissArray.length; j++)
{
// Find disseminators that are NEW within an existing object
// (disseminator does not already exist in the database)
results=logAndExecuteQuery(st, "SELECT diss.dissDbID"
+ " FROM doDissAssoc, diss"
+ " WHERE doDissAssoc.doDbID=" + doDbID + " AND diss.dissID='" + dissArray[j].dissID + "'"
+ " AND doDissAssoc.dissDbID=diss.dissDbID");
if (!results.next()) {
// the disseminator does NOT exist in the database; it is NEW.
newDisseminators.add(dissArray[j]);
}
}
addDisseminators(doPID, (Disseminator[])newDisseminators.toArray(new Disseminator[0]), reader, connection);
connection.commit();
} catch (SQLException sqle) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage());
} catch (ServerException se) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
// TODO: make sure this makes sense here
if (connection!=null) {
try {
if (failed) connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName()
+ ": " + th.getMessage());
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
connection.setAutoCommit(true);
} catch (SQLException sqle) {
logWarning("While cleaning up: " + sqle.getClass().getName()
+ ": " + sqle.getMessage());
} finally {
m_pool.free(connection);
}
}
}
}
logFinest("DefaultDOReplicator.addNewComponents: Exiting ------");
return true;
}
/**
* <p> Removes components of a digital object from the database.</p>
*
* @param reader an instance a DOReader.
* @return True if the removal was successfult; false otherwise.
* @throws ReplicationException If any type of error occurs during the removal.
*/
private boolean purgeComponents(DOReader reader)
throws ReplicationException {
Connection connection=null;
Statement st=null;
ResultSet results=null;
boolean failed=false;
logFinest("DefaultDOReplication.purgeComponents: Entering -----");
try {
String doPID = reader.GetObjectPID();
connection=m_pool.getConnection();
connection.setAutoCommit(false);
st=connection.createStatement();
// get db ID for the digital object
results=logAndExecuteQuery(st, "SELECT doDbID FROM do WHERE "
+ "doPID='" + doPID + "'");
if (!results.next()) {
logFinest("DefaultDOReplication.purgeComponents: Object is "
+ "new; components will be added as part of new object replication.");
return false;
}
int doDbID=results.getInt("doDbID");
results.close();
// Get all disseminators that are in db for this object
HashSet dissDbIds = new HashSet();
results=logAndExecuteQuery(st, "SELECT dissDbID"
+ " FROM doDissAssoc"
+ " WHERE doDbID=" + doDbID);
while (results.next()) {
Integer id = new Integer(results.getInt("dissDbID"));
dissDbIds.add(id);
}
results.close();
logFinest("DefaultDOReplicator.purgeComponents: Found "
+ dissDbIds.size() + "dissDbId(s). ");
// Get all binding maps that are in db for this object
HashSet dsBindMapIds = new HashSet();
results=logAndExecuteQuery(st, "SELECT DISTINCT dsBindMapDbID "
+ " FROM dsBind WHERE doDbID=" + doDbID);
while (results.next()) {
Integer id = new Integer(results.getInt("dsBindMapDbID"));
dsBindMapIds.add(id);
}
results.close();
logFinest("DefaultDOReplicator.purgeComponents: Found "
+ dsBindMapIds.size() + "dsBindMapDbId(s). ");
// Now get all existing disseminators that are in xml object for this object
Disseminator[] dissArray = reader.GetDisseminators(null, null);
HashSet existingDisseminators = new HashSet();
HashSet purgedDisseminators = new HashSet();
for (int j=0; j< dissArray.length; j++)
{
// Find disseminators that have been removed within an existing object
// (disseminator(s) still exist in the database)
results=logAndExecuteQuery(st, "SELECT diss.dissDbID"
+ " FROM doDissAssoc, diss"
+ " WHERE doDissAssoc.doDbID=" + doDbID + " AND diss.dissID='" + dissArray[j].dissID + "'"
+ " AND doDissAssoc.dissDbID=diss.dissDbID");
if (!results.next()) {
// No disseminator was found in db so it must be new one
// indicating an instance of AddNewComponents rather than purgeComponents
logFinest("DefaultDOReplicator.purgeComponents: Disseminator not found in db; Assuming this is case of AddNewComponents");
return false;
} else {
Integer id = new Integer(results.getInt("dissDbID"));
existingDisseminators.add(id);
logFinest("DefaultDOReplicator.purgeComponents: Adding "
+ " dissDbId: " + id + " to list of Existing dissDbId(s). ");
}
results.close();
}
logFinest("DefaultDOReplicator.purgeComponents: Found "
+ existingDisseminators.size() + " existing dissDbId(s). ");
// Now get all existing dsbindmapids that are in xml object for this object
HashSet existingDsBindMapIds = new HashSet();
HashSet purgedDsBindMapIds = new HashSet();
for (int j=0; j< dissArray.length; j++)
{
// Find disseminators that have been removed within an existing object
// (disseminator(s) still exist in the database)
results=logAndExecuteQuery(st, "SELECT dsBindMapDbID, dsBindMapID"
+ " FROM dsBindMap,bMech,diss"
+ " WHERE dsBindMap.bmechDbID=bMech.bmechDbID AND bMech.bmechPID='" + dissArray[j].bMechID + "' "
+ " AND diss.dissID='" + dissArray[j].dissID + "' AND dsBindMapID='" + dissArray[j].dsBindMapID + "'");
if (!results.next()) {
// No disseminator was found in db so it must be new one
// indicating an instance of AddNewComponents rather than purgeComponents
logFinest("DefaultDOReplicator.purgeComponents: Disseminator not found in db; Assuming this is case of AddNewComponents");
return false;
} else {
Integer dsBindMapDbId = new Integer(results.getInt("dsBindMapDbID"));
String dsBindMapID = results.getString("dsBindMapID");
existingDsBindMapIds.add(dsBindMapDbId);
logFinest("DefaultDOReplicator.purgeComponents: Adding "
+ " dsBindMapDbId: " + dsBindMapDbId + " to list of Existing dsBindMapDbId(s). ");
}
results.close();
}
logFinest("DefaultDOReplicator.purgeComponents: Found "
+ existingDsBindMapIds.size() + " existing dsBindMapDbId(s). ");
// Compare what's in db with what's in xml object
Iterator dissDbIdIter = dissDbIds.iterator();
Iterator existingDissIter = existingDisseminators.iterator();
while (dissDbIdIter.hasNext()) {
Integer dissDbId = (Integer) dissDbIdIter.next();
if (existingDisseminators.contains(dissDbId)) {
// database disseminator exists in xml object
// so ignore
} else {
// database disseminator does not exist in xml object
// so remove it from database
purgedDisseminators.add(dissDbId);
logFinest("DefaultDOReplicator.purgeComponents: Adding "
+ " dissDbId: " + dissDbId + " to list of Purged dissDbId(s). ");
}
}
if (purgedDisseminators.isEmpty()) {
// no disseminators were removed so this must be an
// an instance of addComponent or updateComponent
logFinest("DefaultDOReplicator.purgeComponents: "
+ "No disseminators have been removed from object;"
+ " Assuming this a case of UpdateComponents");
return false;
}
// Compare what's in db with what's in xml object
Iterator dsBindMapIdIter = dsBindMapIds.iterator();
Iterator existingDsBindMapIdIter = existingDsBindMapIds.iterator();
while (dsBindMapIdIter.hasNext()) {
Integer dsBindMapDbId = (Integer) dsBindMapIdIter.next();
if (existingDsBindMapIds.contains(dsBindMapDbId)) {
// database disseminator exists in xml object
// so ignore
} else {
// database disseminator does not exist in xml object
// so remove it from database
purgedDsBindMapIds.add(dsBindMapDbId);
logFinest("DefaultDOReplicator.purgeComponents: Adding "
+ " dsBindMapDbId: " + dsBindMapDbId + " to list of Purged dsBindMapDbId(s). ");
}
}
if (purgedDsBindMapIds.isEmpty()) {
// no disseminators were removed so this must be an
// an instance of addComponent or updateComponent
logFinest("DefaultDOReplicator.purgeComponents: "
+ "No disseminators have been removed from object;"
+ " Assuming this a case of UpdateComponents");
return false;
}
purgeDisseminators(doPID, purgedDisseminators, purgedDsBindMapIds, reader, connection);
connection.commit();
} catch (SQLException sqle) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage());
} catch (ServerException se) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} finally {
// TODO: make sure this makes sense here
if (connection!=null) {
try {
if (failed) connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName()
+ ": " + th.getMessage());
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
connection.setAutoCommit(true);
} catch (SQLException sqle) {
logWarning("While cleaning up: " + sqle.getClass().getName()
+ ": " + sqle.getMessage());
} finally {
m_pool.free(connection);
}
}
}
}
logFinest("DefaultDOReplicator.purgeComponents: Exiting ------");
return true;
}
/**
* If the object has already been replicated, update the components
* and return true. Otherwise, return false.
*
* Currently bdef components cannot be updated, so this will
* simply return true if the bDef has already been replicated.
*
* @param reader a behavior definitionobject reader.
* @return true if bdef update successful; false otherwise.
* @throws ReplicationException if replication fails for any reason.
*/
private boolean updateComponents(BDefReader reader)
throws ReplicationException {
Connection connection=null;
Statement st=null;
ResultSet results=null;
boolean triedUpdate=false;
boolean failed=false;
try {
connection=m_pool.getConnection();
st=connection.createStatement();
results=logAndExecuteQuery(st, "SELECT bDefDbID,bDefState FROM bDef WHERE "
+ "bDefPID='" + reader.GetObjectPID() + "'");
if (!results.next()) {
logFinest("DefaultDOReplication.updateComponents: Object is "
+ "new; components dont need updating.");
return false;
}
int bDefDbID=results.getInt("bDefDbID");
String bDefState=results.getString("bDefState");
results.close();
ArrayList updates=new ArrayList();
// check if state has changed for the bdef object
String objState = reader.GetObjectState();
if (!bDefState.equalsIgnoreCase(objState)) {
updates.add("UPDATE bDef SET bDefState='"+objState+"' WHERE bDefDbID=" + bDefDbID);
updates.add("UPDATE doRegistry SET objectState='"+objState+"' WHERE doPID='" + reader.GetObjectPID() + "'");
}
// do any required updates via a transaction
if (updates.size()>0) {
connection.setAutoCommit(false);
triedUpdate=true;
for (int i=0; i<updates.size(); i++) {
String update=(String) updates.get(i);
logAndExecuteUpdate(st, update);
}
connection.commit();
} else {
logFinest("No datastream labels or locations changed.");
}
} catch (SQLException sqle) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage());
} catch (ServerException se) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} finally {
if (connection!=null) {
try {
if (triedUpdate && failed) connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName()
+ ": " + th.getMessage());
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
connection.setAutoCommit(true);
} catch (SQLException sqle) {
logWarning("While cleaning up: " + sqle.getClass().getName()
+ ": " + sqle.getMessage());
} finally {
m_pool.free(connection);
}
}
}
}
return true;
}
/**
* If the object has already been replicated, update the components
* and return true. Otherwise, return false.
*
* Currently bmech components cannot be updated, so this will
* simply return true if the bMech has already been replicated.
*
* @param reader a behavior mechanism object reader.
* @return true if bmech update successful; false otherwise.
* @throws ReplicationException if replication fails for any reason.
*/
private boolean updateComponents(BMechReader reader)
throws ReplicationException {
Connection connection=null;
Statement st=null;
ResultSet results=null;
boolean triedUpdate=false;
boolean failed=false;
try {
connection=m_pool.getConnection();
st=connection.createStatement();
results=logAndExecuteQuery(st, "SELECT bMechDbID,bMechState FROM bMech WHERE "
+ "bMechPID='" + reader.GetObjectPID() + "'");
if (!results.next()) {
logFinest("DefaultDOReplication.updateComponents: Object is "
+ "new; components dont need updating.");
return false;
}
int bMechDbID=results.getInt("bMechDbID");
String bMechState=results.getString("bMechState");
results.close();
ArrayList updates=new ArrayList();
// check if state has changed for the bdef object
String objState = reader.GetObjectState();
if (!bMechState.equalsIgnoreCase(objState)) {
updates.add("UPDATE bMech SET bMechState='"+objState+"' WHERE bMechDbID=" + bMechDbID);
updates.add("UPDATE doRegistry SET objectState='"+objState+"' WHERE doPID='" + reader.GetObjectPID() + "'");
}
// do any required updates via a transaction
if (updates.size()>0) {
connection.setAutoCommit(false);
triedUpdate=true;
for (int i=0; i<updates.size(); i++) {
String update=(String) updates.get(i);
logAndExecuteUpdate(st, update);
}
connection.commit();
} else {
logFinest("No datastream labels or locations changed.");
}
} catch (SQLException sqle) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage());
} catch (ServerException se) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} finally {
if (connection!=null) {
try {
if (triedUpdate && failed) connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName()
+ ": " + th.getMessage());
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
connection.setAutoCommit(true);
} catch (SQLException sqle) {
logWarning("While cleaning up: " + sqle.getClass().getName()
+ ": " + sqle.getMessage());
} finally {
m_pool.free(connection);
}
}
}
}
return true;
}
/**
* Replicates a Fedora behavior definition object.
*
* @param bDefReader behavior definition reader
* @exception ReplicationException replication processing error
* @exception SQLException JDBC, SQL error
*/
public void replicate(BDefReader bDefReader)
throws ReplicationException, SQLException {
if (!updateComponents(bDefReader)) {
Connection connection=null;
try {
MethodDef behaviorDefs[];
String bDefDBID;
String bDefPID;
String bDefLabel;
String methDBID;
String methodName;
String parmRequired;
String[] parmDomainValues;
connection = m_pool.getConnection();
connection.setAutoCommit(false);
// Insert Behavior Definition row
bDefPID = bDefReader.GetObjectPID();
bDefLabel = bDefReader.GetObjectLabel();
insertBehaviorDefinitionRow(connection, bDefPID, bDefLabel, bDefReader.GetObjectState());
// Insert method rows
bDefDBID = lookupBehaviorDefinitionDBID(connection, bDefPID);
if (bDefDBID == null) {
throw new ReplicationException(
"BehaviorDefinition row doesn't exist for PID: "
+ bDefPID);
}
behaviorDefs = bDefReader.getAbstractMethods(null);
for (int i=0; i<behaviorDefs.length; ++i) {
insertMethodRow(connection, bDefDBID,
behaviorDefs[i].methodName,
behaviorDefs[i].methodLabel);
// Insert method parm rows
methDBID = lookupMethodDBID(connection, bDefDBID,
behaviorDefs[i].methodName);
for (int j=0; j<behaviorDefs[i].methodParms.length; j++)
{
MethodParmDef[] methodParmDefs =
new MethodParmDef[behaviorDefs[i].methodParms.length];
methodParmDefs = behaviorDefs[i].methodParms;
parmRequired =
methodParmDefs[j].parmRequired ? "true" : "false";
parmDomainValues = methodParmDefs[j].parmDomainValues;
StringBuffer sb = new StringBuffer();
if (parmDomainValues != null && parmDomainValues.length > 0)
{
for (int k=0; k<parmDomainValues.length; k++)
{
if (k < parmDomainValues.length-1)
{
sb.append(parmDomainValues[k]+",");
} else
{
sb.append(parmDomainValues[k]);
}
}
} else
{
sb.append("null");
}
insertMethodParmRow(connection, methDBID, bDefDBID,
methodParmDefs[j].parmName,
methodParmDefs[j].parmDefaultValue,
sb.toString(),
parmRequired,
methodParmDefs[j].parmLabel,
methodParmDefs[j].parmType);
}
}
connection.commit();
} catch (ReplicationException re) {
throw re;
} catch (ServerException se) {
throw new ReplicationException("Replication exception caused by "
+ "ServerException - " + se.getMessage());
} finally {
if (connection!=null) {
try {
connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName() + ": " + th.getMessage());
} finally {
connection.setAutoCommit(true);
m_pool.free(connection);
}
}
}
}
}
/**
* Replicates a Fedora behavior mechanism object.
*
* @param bMechReader behavior mechanism reader
* @exception ReplicationException replication processing error
* @exception SQLException JDBC, SQL error
*/
public void replicate(BMechReader bMechReader)
throws ReplicationException, SQLException {
if (!updateComponents(bMechReader)) {
Connection connection=null;
try {
BMechDSBindSpec dsBindSpec;
MethodDefOperationBind behaviorBindings[];
MethodDefOperationBind behaviorBindingsEntry;
String bDefDBID;
String bDefPID;
String bMechDBID;
String bMechPID;
String bMechLabel;
String dsBindingKeyDBID;
String methodDBID;
String ordinality_flag;
String cardinality;
String[] parmDomainValues;
String parmRequired;
connection = m_pool.getConnection();
connection.setAutoCommit(false);
// Insert Behavior Mechanism row
dsBindSpec = bMechReader.getServiceDSInputSpec(null);
bDefPID = dsBindSpec.bDefPID;
bDefDBID = lookupBehaviorDefinitionDBID(connection, bDefPID);
if (bDefDBID == null) {
throw new ReplicationException("BehaviorDefinition row doesn't "
+ "exist for PID: " + bDefPID);
}
bMechPID = bMechReader.GetObjectPID();
bMechLabel = bMechReader.GetObjectLabel();
insertBehaviorMechanismRow(connection, bDefDBID, bMechPID,
bMechLabel, bMechReader.GetObjectState());
// Insert dsBindSpec rows
bMechDBID = lookupBehaviorMechanismDBID(connection, bMechPID);
if (bMechDBID == null) {
throw new ReplicationException("BehaviorMechanism row doesn't "
+ "exist for PID: " + bDefPID);
}
for (int i=0; i<dsBindSpec.dsBindRules.length; ++i) {
// Convert from type boolean to type String
ordinality_flag =
dsBindSpec.dsBindRules[i].ordinality ? "true" : "false";
// Convert from type int to type String
cardinality = Integer.toString(
dsBindSpec.dsBindRules[i].maxNumBindings);
insertDataStreamBindingSpecRow(connection,
bMechDBID, dsBindSpec.dsBindRules[i].bindingKeyName,
ordinality_flag, cardinality,
dsBindSpec.dsBindRules[i].bindingLabel);
// Insert dsMIME rows
dsBindingKeyDBID =
lookupDataStreamBindingSpecDBID(connection,
bMechDBID, dsBindSpec.dsBindRules[i].bindingKeyName);
if (dsBindingKeyDBID == null) {
throw new ReplicationException(
"dsBindSpec row doesn't exist for "
+ "bMechDBID: " + bMechDBID
+ ", binding key name: "
+ dsBindSpec.dsBindRules[i].bindingKeyName);
}
for (int j=0;
j<dsBindSpec.dsBindRules[i].bindingMIMETypes.length;
++j) {
insertDataStreamMIMERow(connection,
dsBindingKeyDBID,
dsBindSpec.dsBindRules[i].bindingMIMETypes[j]);
}
}
// Insert mechImpl rows
behaviorBindings = bMechReader.getServiceMethodBindings(null);
for (int i=0; i<behaviorBindings.length; ++i) {
behaviorBindingsEntry =
(MethodDefOperationBind)behaviorBindings[i];
if (!behaviorBindingsEntry.protocolType.equals("HTTP")) {
// For the time being, ignore bindings other than HTTP.
continue;
}
// Insert mechDefParm rows
methodDBID = lookupMethodDBID(connection, bDefDBID,
behaviorBindingsEntry.methodName);
if (methodDBID == null) {
throw new ReplicationException("Method row doesn't "
+ "exist for method name: "
+ behaviorBindingsEntry.methodName);
}
for (int j=0; j<behaviorBindings[i].methodParms.length; j++)
{
MethodParmDef[] methodParmDefs =
new MethodParmDef[behaviorBindings[i].methodParms.length];
methodParmDefs = behaviorBindings[i].methodParms;
//if (methodParmDefs[j].parmType.equalsIgnoreCase("fedora:defaultInputType"))
if (methodParmDefs[j].parmType.equalsIgnoreCase(MethodParmDef.DEFAULT_INPUT))
{
parmRequired =
methodParmDefs[j].parmRequired ? "true" : "false";
parmDomainValues = methodParmDefs[j].parmDomainValues;
StringBuffer sb = new StringBuffer();
if (parmDomainValues != null && parmDomainValues.length > 0)
{
for (int k=0; k<parmDomainValues.length; k++)
{
if (k < parmDomainValues.length-1)
{
sb.append(parmDomainValues[k]+",");
} else
{
sb.append(parmDomainValues[k]);
}
}
} else
{
if (sb.length() == 0) sb.append("null");
}
insertMechDefaultMethodParmRow(connection, methodDBID, bMechDBID,
methodParmDefs[j].parmName,
methodParmDefs[j].parmDefaultValue,
sb.toString(),
parmRequired,
methodParmDefs[j].parmLabel,
methodParmDefs[j].parmType);
}
}
for (int j=0; j<dsBindSpec.dsBindRules.length; ++j) {
dsBindingKeyDBID =
lookupDataStreamBindingSpecDBID(connection,
bMechDBID,
dsBindSpec.dsBindRules[j].bindingKeyName);
if (dsBindingKeyDBID == null) {
throw new ReplicationException(
"dsBindSpec "
+ "row doesn't exist for bMechDBID: "
+ bMechDBID + ", binding key name: "
+ dsBindSpec.dsBindRules[j].bindingKeyName);
}
for (int k=0; k<behaviorBindingsEntry.dsBindingKeys.length;
k++)
{
// A row is added to the mechImpl table for each
// method with a different BindingKeyName. In cases where
// a single method may have multiple binding keys,
// multiple rows are added for each different
// BindingKeyName for that method.
if (behaviorBindingsEntry.dsBindingKeys[k].
equalsIgnoreCase(
dsBindSpec.dsBindRules[j].bindingKeyName))
{
insertMechanismImplRow(connection, bMechDBID,
bDefDBID, methodDBID, dsBindingKeyDBID,
"http", "text/html",
// sdp - local.fedora.server conversion
encodeLocalURL(behaviorBindingsEntry.serviceBindingAddress),
encodeLocalURL(behaviorBindingsEntry.operationLocation), "1");
}
}
}
}
connection.commit();
} catch (ReplicationException re) {
re.printStackTrace();
throw re;
} catch (ServerException se) {
se.printStackTrace();
throw new ReplicationException(
"Replication exception caused by ServerException - "
+ se.getMessage());
} finally {
if (connection!=null) {
try {
connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName() + ": " + th.getMessage());
} finally {
connection.setAutoCommit(true);
m_pool.free(connection);
}
}
}
}
}
/**
* Replicates a Fedora data object.
*
* @param doReader data object reader
* @exception ReplicationException replication processing error
* @exception SQLException JDBC, SQL error
*/
public void replicate(DOReader doReader)
throws ReplicationException, SQLException {
// do updates if the object already existed
boolean componentsUpdated=false;
boolean componentsAdded=false;
boolean componentsPurged=purgeComponents(doReader);
logFinest("DefaultDOReplicator.replicate: componentsPurged: "+componentsPurged);
// Update operations are mutually exclusive
if (!componentsPurged) {
componentsUpdated=updateComponents(doReader);
logFinest("DefaultDOReplicator.replicate: componentsUpdated: "+componentsUpdated);
if (!componentsUpdated) {
// and do adds if the object already existed
componentsAdded=addNewComponents(doReader);
logFinest("DefaultDOReplicator.replicate: componentsAdded: "+componentsAdded);
}
}
if ( !componentsUpdated && !componentsAdded && !componentsPurged ) {
Connection connection=null;
try
{
DSBindingMapAugmented[] allBindingMaps;
Disseminator disseminators[];
String bDefDBID;
String bindingMapDBID;
String bMechDBID;
String dissDBID;
String doDBID;
String doPID;
String doLabel;
String dsBindingKeyDBID;
int rc;
doPID = doReader.GetObjectPID();
connection = m_pool.getConnection();
connection.setAutoCommit(false);
// Insert Digital Object row
doPID = doReader.GetObjectPID();
doLabel = doReader.GetObjectLabel();
insertDigitalObjectRow(connection, doPID, doLabel, doReader.GetObjectState());
doDBID = lookupDigitalObjectDBID(connection, doPID);
if (doDBID == null) {
throw new ReplicationException("do row doesn't "
+ "exist for PID: " + doPID);
}
// add disseminator components (which include associated datastream components)
disseminators = doReader.GetDisseminators(null, null);
addDisseminators(doPID, disseminators, doReader, connection);
connection.commit();
} catch (ReplicationException re) {
re.printStackTrace();
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + re.getClass().getName()
+ " \". The cause was \" " + re.getMessage() + " \"");
} catch (ServerException se) {
se.printStackTrace();
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} finally {
if (connection!=null) {
try {
connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName() + ": " + th.getMessage());
} finally {
connection.setAutoCommit(true);
m_pool.free(connection);
}
}
}
}
}
private ResultSet logAndExecuteQuery(Statement statement, String sql)
throws SQLException {
logFinest("Executing query: " + sql);
return statement.executeQuery(sql);
}
private int logAndExecuteUpdate(Statement statement, String sql)
throws SQLException {
logFinest("Executing update: " + sql);
return statement.executeUpdate(sql);
}
/**
* Gets a string suitable for a SQL WHERE clause, of the form
* <b>x=y1 or x=y2 or x=y3</b>...etc, where x is the value from the
* column, and y1 is composed of the integer values from the given set.
* <p></p>
* If the set doesn't contain any items, returns a condition that
* always evaluates to false, <b>1=2</b>.
*
* @param column value of the column.
* @param integers set of integers.
* @return string suitable for SQL WHERE clause.
*/
private String inIntegerSetWhereConditionString(String column,
Set integers) {
StringBuffer out=new StringBuffer();
Iterator iter=integers.iterator();
int n=0;
while (iter.hasNext()) {
if (n>0) {
out.append(" OR ");
}
out.append(column);
out.append('=');
int i=((Integer) iter.next()).intValue();
out.append(i);
n++;
}
if (n>0) {
return out.toString();
} else {
return "1=2";
}
}
/**
* Deletes all rows pertinent to the given behavior definition object,
* if they exist.
* <p></p>
* Pseudocode:
* <ul><pre>
* $bDefDbID=SELECT bDefDbID FROM bDef WHERE bDefPID=$PID
* DELETE FROM bDef,method,parm
* WHERE bDefDbID=$bDefDbID
* </pre></ul>
*
* @param connection a database connection.
* @param pid the idenitifer of a digital object.
* @throws SQLException If something totally unexpected happened.
*/
private void deleteBehaviorDefinition(Connection connection, String pid)
throws SQLException {
logFinest("Entered DefaultDOReplicator.deleteBehaviorDefinition");
Statement st=null;
ResultSet results=null;
try {
st=connection.createStatement();
//
// READ
//
logFinest("Checking BehaviorDefinition table for " + pid + "...");
results=logAndExecuteQuery(st, "SELECT bDefDbID FROM "
+ "bDef WHERE bDefPID='" + pid + "'");
if (!results.next()) {
// must not be a bdef...exit early
logFinest(pid + " wasn't found in BehaviorDefinition table..."
+ "skipping deletion as such.");
return;
}
int dbid=results.getInt("bDefDbID");
logFinest(pid + " was found in BehaviorDefinition table (DBID="
+ dbid + ")");
//
// WRITE
//
int rowCount;
logFinest("Attempting row deletion from BehaviorDefinition "
+ "table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM bDef "
+ "WHERE bDefDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from method table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM method WHERE "
+ "bDefDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from parm table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM parm WHERE "
+ "bDefDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
} finally {
if (results != null) results.close();
if (st!=null) st.close();
logFinest("Exiting DefaultDOReplicator.deleteBehaviorDefinition");
}
}
/**
* Deletes all rows pertinent to the given behavior mechanism object,
* if they exist.
* <p></p>
* Pseudocode:
* <ul><pre>
* $bMechDbID=SELECT bMechDbID
* FROM bMech WHERE bMechPID=$PID
* bMech
* @BKEYIDS=SELECT dsBindKeyDbID
* FROM dsBindSpec
* WHERE bMechDbID=$bMechDbID
* dsMIME WHERE dsBindKeyDbID in @BKEYIDS
* mechImpl
* </pre></ul>
*
* @param connection a database connection.
* @param pid the identifier of a digital object.
* @throws SQLException If something totally unexpected happened.
*/
private void deleteBehaviorMechanism(Connection connection, String pid)
throws SQLException {
logFinest("Entered DefaultDOReplicator.deleteBehaviorMechanism");
Statement st=null;
ResultSet results=null;
try {
st=connection.createStatement();
//
// READ
//
logFinest("Checking bMech table for " + pid + "...");
//results=logAndExecuteQuery(st, "SELECT bMechDbID, SMType_DBID "
results=logAndExecuteQuery(st, "SELECT bMechDbID "
+ "FROM bMech WHERE bMechPID='" + pid + "'");
if (!results.next()) {
// must not be a bmech...exit early
logFinest(pid + " wasn't found in bMech table..."
+ "skipping deletion as such.");
return;
}
int dbid=results.getInt("bMechDbID");
//int smtype_dbid=results.getInt("bMechDbID");
results.close();
logFinest(pid + " was found in bMech table (DBID="
// + dbid + ", SMTYPE_DBID=" + smtype_dbid + ")");
+ dbid);
logFinest("Getting dsBindKeyDbID(s) from dsBindSpec "
+ "table...");
HashSet dsBindingKeyIds=new HashSet();
results=logAndExecuteQuery(st, "SELECT dsBindKeyDbID from "
+ "dsBindSpec WHERE bMechDbID=" + dbid);
while (results.next()) {
dsBindingKeyIds.add(new Integer(
results.getInt("dsBindKeyDbID")));
}
results.close();
logFinest("Found " + dsBindingKeyIds.size()
+ " dsBindKeyDbID(s).");
//
// WRITE
//
int rowCount;
logFinest("Attempting row deletion from bMech table..");
rowCount=logAndExecuteUpdate(st, "DELETE FROM bMech "
+ "WHERE bMechDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from dsBindSpec "
+ "table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM "
+ "dsBindSpec WHERE bMechDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from dsMIME table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM dsMIME WHERE "
+ inIntegerSetWhereConditionString("dsBindKeyDbID",
dsBindingKeyIds));
logFinest("Deleted " + rowCount + " row(s).");
//logFinest("Attempting row deletion from StructMapType table...");
//rowCount=logAndExecuteUpdate(st, "DELETE FROM StructMapType WHERE "
// + "SMType_DBID=" + smtype_dbid);
//logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from dsBindMap table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBindMap WHERE "
+ "bMechDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from mechImpl table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM mechImpl WHERE "
+ "bMechDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from mechDefParm table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM mechDefParm "
+ "WHERE bMechDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
} finally {
if (results != null) results.close();
if (st!=null)st.close();
logFinest("Exiting DefaultDOReplicator.deleteBehaviorMechanism");
}
}
/**
* Deletes all rows pertinent to the given digital object (treated as a
* data object) if they exist.
* <p></p>
* Pseudocode:
* <ul><pre>
* $doDbID=SELECT doDbID FROM do where doPID=$PID
* @DISSIDS=SELECT dissDbID
* FROM doDissAssoc WHERE doDbID=$doDbID
* @BMAPIDS=SELECT dsBindMapDbID
* FROM dsBind WHERE doDbID=$doDbID
* do
* doDissAssoc where $doDbID=doDbID
* dsBind WHERE $doDbID=doDbID
* diss WHERE dissDbID in @DISSIDS
* dsBindMap WHERE dsBindMapDbID in @BMAPIDS
* </pre></ul>
*
* @param connection a databae connection.
* @param pid the identifier for a digital object.
* @throws SQLException If something totally unexpected happened.
*/
private void deleteDigitalObject(Connection connection, String pid)
throws SQLException {
logFinest("DefaultDOReplicator.deleteDigitalObject: Entering -----");
Statement st=null;
Statement st2=null;
Statement st3=null;
ResultSet results=null;
try {
st=connection.createStatement();
//
// READ
//
logFinest("Checking do table for " + pid + "...");
results=logAndExecuteQuery(st, "SELECT doDbID FROM "
+ "do WHERE doPID='" + pid + "'");
if (!results.next()) {
// must not be a digitalobject...exit early
logFinest(pid + " wasn't found in do table..."
+ "skipping deletion as such.");
return;
}
int dbid=results.getInt("doDbID");
results.close();
logFinest(pid + " was found in do table (DBID="
+ dbid + ")");
logFinest("Getting dissDbID(s) from doDissAssoc "
+ "table...");
HashSet dissIds=new HashSet();
HashSet dissIdsNotShared = new HashSet();
// Get all dissIds in db for this object
results=logAndExecuteQuery(st, "SELECT dissDbID from "
+ "doDissAssoc WHERE doDbID=" + dbid);
while (results.next()) {
dissIds.add(new Integer(results.getInt("dissDbID")));
}
results.close();
logFinest("Found " + dissIds.size() + " dissDbID(s).");
logFinest("Getting dissDbID(s) from doDissAssoc "
+ "table unique to this object...");
Iterator iterator = dissIds.iterator();
// Iterate over dissIds and separate those that are unique
// (i.e., not shared by other objects)
while (iterator.hasNext())
{
Integer id = (Integer)iterator.next();
logFinest("Getting occurrences of dissDbID(s) in "
+ "doDissAssoc table...");
results=logAndExecuteQuery(st, "SELECT COUNT(*) from "
+ "doDissAssoc WHERE dissDbID=" + id);
while (results.next())
{
Integer i1 = new Integer(results.getInt("COUNT(*)"));
if ( i1.intValue() == 1 )
{
// A dissDbID that occurs only once indicates that the
// disseminator is not used by other objects. In this case, we
// want to keep track of this dissDbID.
dissIdsNotShared.add(id);
logFinest("DefaultDOReplicator.deleteDigitalObject: added "
+ "dissDbId that was not shared: " + id);
}
}
results.close();
}
// Get all binding map Ids in db for this object.
HashSet bmapIds=new HashSet();
results=logAndExecuteQuery(st, "SELECT dsBindMapDbID FROM "
+ "dsBind WHERE doDbID=" + dbid);
while (results.next()) {
bmapIds.add(new Integer(results.getInt("dsBindMapDbID")));
}
results.close();
logFinest("Found " + bmapIds.size() + " dsBindMapDbID(s).");
// Iterate over bmapIds and separate those that are unique
// (i.e., not shared by other objects)
iterator = bmapIds.iterator();
HashSet bmapIdsNotShared = new HashSet();
while (iterator.hasNext() )
{
Integer id = (Integer)iterator.next();
ResultSet rs = null;
logFinest("Getting associated bmapId(s) that are unique "
+ "for this object in diss table...");
st2 = connection.createStatement();
rs=logAndExecuteQuery(st2, "SELECT DISTINCT doDbID FROM "
+ "dsBind WHERE dsBindMapDbID=" + id);
int rowCount = 0;
while (rs.next())
{
rowCount++;
}
if ( rowCount == 1 )
{
// A bmapId that occurs only once indicates that
// a bmapId is not used by other objects. In this case, we
// want to keep track of this bpamId.
bmapIdsNotShared.add(id);
logFinest("DefaultDOReplicator.deleteDigitalObject: added "
+ "dsBindMapDbId that was not shared: " + id);
}
rs.close();
st2.close();
}
//
// WRITE
//
int rowCount;
logFinest("Attempting row deletion from do table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM do "
+ "WHERE doDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from doDissAssoc "
+ "table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM "
+ "doDissAssoc WHERE doDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from dsBind table..");
rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBind "
+ "WHERE doDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
// Since dissIds can be shared by other objects in db, only remove
// those Ids that are not shared.
logFinest("Attempting row deletion from diss table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM diss WHERE "
+ inIntegerSetWhereConditionString("dissDbID", dissIdsNotShared));
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from dsBindMap "
+ "table...");
// Since bmapIds can be shared by other objects in db, only remove
// thos Ids that are not shared.
rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBindMap "
+ "WHERE " + inIntegerSetWhereConditionString(
"dsBindMapDbID", bmapIdsNotShared));
logFinest("Deleted " + rowCount + " row(s).");
} finally {
if (results != null) results.close();
if (st!=null) st.close();
if (st2!=null) st2.close();
logFinest("DefaultDOReplicator.deleteDigitalObject: Exiting -----");
}
}
/**
* Removes a digital object from the dissemination database.
* <p></p>
* If the object is a behavior definition or mechanism, it's deleted
* as such, and then an attempt is made to delete it as a data object
* as well.
* <p></p>
* Note that this does not do cascading check object dependencies at
* all. It is expected at this point that when this is called, any
* referencial integrity issues have been ironed out or checked as
* appropriate.
* <p></p>
* All deletions happen in a transaction. If any database errors occur,
* the change is rolled back.
*
* @param pid The pid of the object to delete.
* @throws ReplicationException If the request couldn't be fulfilled for
* any reason.
*/
public void delete(String pid)
throws ReplicationException {
logFinest("Entered DefaultDOReplicator.delete");
Connection connection=null;
try {
connection = m_pool.getConnection();
connection.setAutoCommit(false);
deleteBehaviorDefinition(connection, pid);
deleteBehaviorMechanism(connection, pid);
deleteDigitalObject(connection, pid);
connection.commit();
} catch (SQLException sqle) {
throw new ReplicationException("Error while replicator was trying "
+ "to delete " + pid + ". " + sqle.getMessage());
} finally {
if (connection!=null) {
try {
connection.rollback();
connection.setAutoCommit(true);
m_pool.free(connection);
} catch (SQLException sqle) {}
}
logFinest("Exiting DefaultDOReplicator.delete");
}
}
/**
*
* Inserts a Behavior Definition row.
*
* @param connection JDBC DBMS connection
* @param bDefPID Behavior definition PID
* @param bDefLabel Behavior definition label
* @param bDefState State of behavior definition object.
*
* @exception SQLException JDBC, SQL error
*/
public void insertBehaviorDefinitionRow(Connection connection, String bDefPID, String bDefLabel, String bDefState) throws SQLException {
String insertionStatement = "INSERT INTO bDef (bDefPID, bDefLabel, bDefState) VALUES ('" + bDefPID + "', '" + SQLUtility.aposEscape(bDefLabel) + "', '" + bDefState + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a Behavior Mechanism row.
*
* @param connection JDBC DBMS connection
* @param bDefDbID Behavior definition DBID
* @param bMechPID Behavior mechanism DBID
* @param bMechLabel Behavior mechanism label
* @param bMechState Statye of behavior mechanism object.
*
* @throws SQLException JDBC, SQL error
*/
public void insertBehaviorMechanismRow(Connection connection, String bDefDbID, String bMechPID, String bMechLabel, String bMechState) throws SQLException {
String insertionStatement = "INSERT INTO bMech (bDefDbID, bMechPID, bMechLabel, bMechState) VALUES ('" + bDefDbID + "', '" + bMechPID + "', '" + SQLUtility.aposEscape(bMechLabel) + "', '" + bMechState + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a DataStreamBindingRow row.
*
* @param connection JDBC DBMS connection
* @param doDbID Digital object DBID
* @param dsBindKeyDbID Datastream binding key DBID
* @param dsBindMapDbID Binding map DBID
* @param dsBindKeySeq Datastream binding key sequence number
* @param dsID Datastream ID
* @param dsLabel Datastream label
* @param dsMIME Datastream mime type
* @param dsLocation Datastream location
* @param dsControlGroupType Datastream type
* @param dsCurrentVersionID Datastream current version ID
* @param policyDbID Policy DBID
* @param dsState State of datastream.
*
* @exception SQLException JDBC, SQL error
*/
public void insertDataStreamBindingRow(Connection connection, String doDbID, String dsBindKeyDbID, String dsBindMapDbID, String dsBindKeySeq, String dsID, String dsLabel, String dsMIME, String dsLocation, String dsControlGroupType, String dsCurrentVersionID, String policyDbID, String dsState) throws SQLException {
String insertionStatement = "INSERT INTO dsBind (doDbID, dsBindKeyDbID, dsBindMapDbID, dsBindKeySeq, dsID, dsLabel, dsMIME, dsLocation, dsControlGroupType, dsCurrentVersionID, policyDbID, dsState) VALUES ('" + doDbID + "', '" + dsBindKeyDbID + "', '" + dsBindMapDbID + "', '" + dsBindKeySeq + "', '" + dsID + "', '" + SQLUtility.aposEscape(dsLabel) + "', '" + dsMIME + "', '" + dsLocation + "', '" + dsControlGroupType + "', '" + dsCurrentVersionID + "', '" + policyDbID + "', '" + dsState + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a dsBindMap row.
*
* @param connection JDBC DBMS connection
* @param bMechDbID Behavior mechanism DBID
* @param dsBindMapID Datastream binding map ID
* @param dsBindMapLabel Datastream binding map label
*
* @exception SQLException JDBC, SQL error
*/
public void insertDataStreamBindingMapRow(Connection connection, String bMechDbID, String dsBindMapID, String dsBindMapLabel) throws SQLException {
String insertionStatement = "INSERT INTO dsBindMap (bMechDbID, dsBindMapID, dsBindMapLabel) VALUES ('" + bMechDbID + "', '" + dsBindMapID + "', '" + SQLUtility.aposEscape(dsBindMapLabel) + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a dsBindSpec row.
*
* @param connection JDBC DBMS connection
* @param bMechDbID Behavior mechanism DBID
* @param dsBindSpecName Datastream binding spec name
* @param dsBindSpecOrdinality Datastream binding spec ordinality flag
* @param dsBindSpecCardinality Datastream binding cardinality
* @param dsBindSpecLabel Datastream binding spec lable
*
* @exception SQLException JDBC, SQL error
*/
public void insertDataStreamBindingSpecRow(Connection connection, String bMechDbID, String dsBindSpecName, String dsBindSpecOrdinality, String dsBindSpecCardinality, String dsBindSpecLabel) throws SQLException {
String insertionStatement = "INSERT INTO dsBindSpec (bMechDbID, dsBindSpecName, dsBindSpecOrdinality, dsBindSpecCardinality, dsBindSpecLabel) VALUES ('" + bMechDbID + "', '" + SQLUtility.aposEscape(dsBindSpecName) + "', '" + dsBindSpecOrdinality + "', '" + dsBindSpecCardinality + "', '" + SQLUtility.aposEscape(dsBindSpecLabel) + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a dsMIME row.
*
* @param connection JDBC DBMS connection
* @param dsBindKeyDbID Datastream binding key DBID
* @param dsMIMEName Datastream MIME type name
*
* @exception SQLException JDBC, SQL error
*/
public void insertDataStreamMIMERow(Connection connection, String dsBindKeyDbID, String dsMIMEName) throws SQLException {
String insertionStatement = "INSERT INTO dsMIME (dsBindKeyDbID, dsMIMEName) VALUES ('" + dsBindKeyDbID + "', '" + dsMIMEName + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a do row.
*
* @param connection JDBC DBMS connection
* @param doPID DigitalObject PID
* @param doLabel DigitalObject label
* @param doState State of digital object.
*
* @exception SQLException JDBC, SQL error
*/
public void insertDigitalObjectRow(Connection connection, String doPID, String doLabel, String doState) throws SQLException {
String insertionStatement = "INSERT INTO do (doPID, doLabel, doState) VALUES ('" + doPID + "', '" + SQLUtility.aposEscape(doLabel) + "', '" + doState + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a doDissAssoc row.
*
* @param connection JDBC DBMS connection
* @param doDbID DigitalObject DBID
* @param dissDbID Disseminator DBID
*
* @exception SQLException JDBC, SQL error
*/
public void insertDigitalObjectDissAssocRow(Connection connection, String doDbID, String dissDbID) throws SQLException {
String insertionStatement = "INSERT INTO doDissAssoc (doDbID, dissDbID) VALUES ('" + doDbID + "', '" + dissDbID + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a Disseminator row.
*
* @param connection JDBC DBMS connection
* @param bDefDbID Behavior definition DBID
* @param bMechDbID Behavior mechanism DBID
* @param dissID Disseminator ID
* @param dissLabel Disseminator label
* @param dissState State of disseminator.
*
* @exception SQLException JDBC, SQL error
*/
public void insertDisseminatorRow(Connection connection, String bDefDbID, String bMechDbID, String dissID, String dissLabel, String dissState) throws SQLException {
String insertionStatement = "INSERT INTO diss (bDefDbID, bMechDbID, dissID, dissLabel, dissState) VALUES ('" + bDefDbID + "', '" + bMechDbID + "', '" + dissID + "', '" + SQLUtility.aposEscape(dissLabel) + "', '" + dissState + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a mechImpl row.
*
* @param connection JDBC DBMS connection
* @param bMechDbID Behavior mechanism DBID
* @param bDefDbID Behavior definition DBID
* @param methodDbID Method DBID
* @param dsBindKeyDbID Datastream binding key DBID
* @param protocolType Mechanism implementation protocol type
* @param returnType Mechanism implementation return type
* @param addressLocation Mechanism implementation address location
* @param operationLocation Mechanism implementation operation location
* @param policyDbID Policy DBID
*
* @exception SQLException JDBC, SQL error
*/
public void insertMechanismImplRow(Connection connection, String bMechDbID, String bDefDbID, String methodDbID, String dsBindKeyDbID, String protocolType, String returnType, String addressLocation, String operationLocation, String policyDbID) throws SQLException {
String insertionStatement = "INSERT INTO mechImpl (bMechDbID, bDefDbID, methodDbID, dsBindKeyDbID, protocolType, returnType, addressLocation, operationLocation, policyDbID) VALUES ('" + bMechDbID + "', '" + bDefDbID + "', '" + methodDbID + "', '" + dsBindKeyDbID + "', '" + protocolType + "', '" + returnType + "', '" + addressLocation + "', '" + operationLocation + "', '" + policyDbID + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a method row.
*
* @param connection JDBC DBMS connection
* @param bDefDbID Behavior definition DBID
* @param methodName Behavior definition label
* @param methodLabel Behavior definition label
*
* @exception SQLException JDBC, SQL error
*/
public void insertMethodRow(Connection connection, String bDefDbID, String methodName, String methodLabel) throws SQLException {
String insertionStatement = "INSERT INTO method (bDefDbID, methodName, methodLabel) VALUES ('" + bDefDbID + "', '" + SQLUtility.aposEscape(methodName) + "', '" + SQLUtility.aposEscape(methodLabel) + "')";
insertGen(connection, insertionStatement);
}
/**
*
* @param connection An SQL Connection.
* @param methDBID The method database ID.
* @param bdefDBID The behavior Definition object database ID.
* @param parmName the parameter name.
* @param parmDefaultValue A default value for the parameter.
* @param parmDomainValues A list of possible values for the parameter.
* @param parmRequiredFlag A boolean flag indicating whether the
* parameter is required or not.
* @param parmLabel The parameter label.
* @param parmType The parameter type.
* @throws SQLException JDBC, SQL error
*/
public void insertMethodParmRow(Connection connection, String methDBID,
String bdefDBID, String parmName, String parmDefaultValue,
String parmDomainValues, String parmRequiredFlag,
String parmLabel, String parmType)
throws SQLException {
String insertionStatement = "INSERT INTO parm "
+ "(methodDbID, bDefDbID, parmName, parmDefaultValue, "
+ "parmDomainValues, parmRequiredFlag, parmLabel, "
+ "parmType) VALUES ('"
+ methDBID + "', '" + bdefDBID + "', '"
+ SQLUtility.aposEscape(parmName) + "', '" + SQLUtility.aposEscape(parmDefaultValue) + "', '"
+ SQLUtility.aposEscape(parmDomainValues) + "', '"
+ parmRequiredFlag + "', '" + SQLUtility.aposEscape(parmLabel) + "', '"
+ parmType + "')";
insertGen(connection, insertionStatement);
}
/**
*
* @param connection An SQL Connection.
* @param methDBID The method database ID.
* @param bmechDBID The behavior Mechanism object database ID.
* @param parmName the parameter name.
* @param parmDefaultValue A default value for the parameter.
* @param parmRequiredFlag A boolean flag indicating whether the
* parameter is required or not.
* @param parmDomainValues A list of possible values for the parameter.
* @param parmLabel The parameter label.
* @param parmType The parameter type.
* @throws SQLException JDBC, SQL error
*/
public void insertMechDefaultMethodParmRow(Connection connection, String methDBID,
String bmechDBID, String parmName, String parmDefaultValue,
String parmDomainValues, String parmRequiredFlag,
String parmLabel, String parmType)
throws SQLException {
String insertionStatement = "INSERT INTO mechDefParm "
+ "(methodDbID, bMechDbID, defParmName, defParmDefaultValue, "
+ "defParmDomainValues, defParmRequiredFlag, defParmLabel, "
+ "defParmType) VALUES ('"
+ methDBID + "', '" + bmechDBID + "', '"
+ SQLUtility.aposEscape(parmName) + "', '" + SQLUtility.aposEscape(parmDefaultValue) + "', '"
+ SQLUtility.aposEscape(parmDomainValues) + "', '"
+ parmRequiredFlag + "', '" + SQLUtility.aposEscape(parmLabel) + "', '"
+ parmType + "')";
insertGen(connection, insertionStatement);
}
/**
*
* General JDBC row insertion method.
*
* @param connection JDBC DBMS connection
* @param insertionStatement SQL row insertion statement
*
* @exception SQLException JDBC, SQL error
*/
public void insertGen(Connection connection, String insertionStatement) throws SQLException {
int rowCount = 0;
Statement statement = null;
statement = connection.createStatement();
logFinest("Doing DB Insert: " + insertionStatement);
rowCount = statement.executeUpdate(insertionStatement);
statement.close();
}
/**
*
* Looks up a BehaviorDefinition DBID.
*
* @param connection JDBC DBMS connection
* @param bDefPID Behavior definition PID
*
* @return The DBID of the specified Behavior Definition row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupBehaviorDefinitionDBID(Connection connection, String bDefPID) throws StorageDeviceException {
return lookupDBID1(connection, "bDefDbID", "bDef", "bDefPID", bDefPID);
}
/**
*
* Looks up a BehaviorMechanism DBID.
*
* @param connection JDBC DBMS connection
* @param bMechPID Behavior mechanism PID
*
* @return The DBID of the specified Behavior Mechanism row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupBehaviorMechanismDBID(Connection connection, String bMechPID) throws StorageDeviceException {
return lookupDBID1(connection, "bMechDbID", "bMech", "bMechPID", bMechPID);
}
/**
*
* Looks up a dsBindMap DBID.
*
* @param connection JDBC DBMS connection
* @param bMechDBID Behavior mechanism DBID
* @param dsBindingMapID Data stream binding map ID
*
* @return The DBID of the specified dsBindMap row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupDataStreamBindingMapDBID(Connection connection, String bMechDBID, String dsBindingMapID) throws StorageDeviceException {
return lookupDBID2FirstNum(connection, "dsBindMapDbID", "dsBindMap", "bMechDbID", bMechDBID, "dsBindMapID", dsBindingMapID);
}
public String lookupDsBindingMapDBID(Connection connection, String bMechDBID, String dsBindingMapID) throws StorageDeviceException {
return lookupDBID2FirstNum(connection, "dissDbID", "diss", "bMechDbID", bMechDBID, "dsBindMapID", dsBindingMapID);
}
/**
*
* Looks up a dsBindSpec DBID.
*
* @param connection JDBC DBMS connection
* @param bMechDBID Behavior mechanism DBID
* @param dsBindingSpecName Data stream binding spec name
*
* @return The DBID of the specified dsBindSpec row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupDataStreamBindingSpecDBID(Connection connection, String bMechDBID, String dsBindingSpecName) throws StorageDeviceException {
return lookupDBID2FirstNum(connection, "dsBindKeyDbID", "dsBindSpec", "bMechDbID", bMechDBID, "dsBindSpecName", dsBindingSpecName);
}
/**
*
* Looks up a do DBID.
*
* @param connection JDBC DBMS connection
* @param doPID Data object PID
*
* @return The DBID of the specified DigitalObject row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupDigitalObjectDBID(Connection connection, String doPID) throws StorageDeviceException {
return lookupDBID1(connection, "doDbID", "do", "doPID", doPID);
}
/**
*
* Looks up a Disseminator DBID.
*
* @param connection JDBC DBMS connection
* @param bDefDBID Behavior definition DBID
* @param bMechDBID Behavior mechanism DBID
* @param dissID Disseminator ID
*
* @return The DBID of the specified Disseminator row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupDisseminatorDBID(Connection connection, String bDefDBID, String bMechDBID, String dissID) throws StorageDeviceException {
Statement statement = null;
ResultSet rs = null;
String query = null;
String ID = null;
try
{
query = "SELECT dissDbID FROM diss WHERE ";
query += "bDefDbID = " + bDefDBID + " AND ";
query += "bMechDbID = " + bMechDBID + " AND ";
query += "dissID = '" + dissID + "'";
logFinest("Doing Query: " + query);
statement = connection.createStatement();
rs = statement.executeQuery(query);
while (rs.next())
ID = rs.getString(1);
} catch (Throwable th)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + th.getClass().getName()
+ " \". The cause was \" " + th.getMessage() + " \"");
} finally
{
try
{
if (rs != null) rs.close();
if (statement != null) statement.close();
} catch (SQLException sqle)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage() + " \"");
}
}
return ID;
}
/**
*
* Looks up a method DBID.
*
* @param connection JDBC DBMS connection
* @param bDefDBID Behavior definition DBID
* @param methName Method name
*
* @return The DBID of the specified method row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupMethodDBID(Connection connection, String bDefDBID, String methName) throws StorageDeviceException {
return lookupDBID2FirstNum(connection, "methodDbID", "method", "bDefDbID", bDefDBID, "methodName", methName);
}
/**
*
* General JDBC lookup method with 1 lookup column value.
*
* @param connection JDBC DBMS connection
* @param DBIDName DBID column name
* @param tableName Table name
* @param lookupColumnName Lookup column name
* @param lookupColumnValue Lookup column value
*
* @return The DBID of the specified row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupDBID1(Connection connection, String DBIDName, String tableName, String lookupColumnName, String lookupColumnValue) throws StorageDeviceException {
String query = null;
String ID = null;
Statement statement = null;
ResultSet rs = null;
try
{
query = "SELECT " + DBIDName + " FROM " + tableName + " WHERE ";
query += lookupColumnName + " = '" + lookupColumnValue + "'";
logFinest("Doing Query: " + query);
statement = connection.createStatement();
rs = statement.executeQuery(query);
while (rs.next())
ID = rs.getString(1);
} catch (Throwable th)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + th.getClass().getName()
+ " \". The cause was \" " + th.getMessage() + " \"");
} finally
{
try
{
if (rs != null) rs.close();
if (statement != null) statement.close();
} catch (SQLException sqle)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage() + " \"");
}
}
return ID;
}
/**
*
* General JDBC lookup method with 2 lookup column values.
*
* @param connection JDBC DBMS connection
* @param DBIDName DBID Column name
* @param tableName Table name
* @param lookupColumnName1 First lookup column name
* @param lookupColumnValue1 First lookup column value
* @param lookupColumnName2 Second lookup column name
* @param lookupColumnValue2 Second lookup column value
*
* @return The DBID of the specified row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupDBID2(Connection connection, String DBIDName, String tableName, String lookupColumnName1, String lookupColumnValue1, String lookupColumnName2, String lookupColumnValue2) throws StorageDeviceException {
String query = null;
String ID = null;
Statement statement = null;
ResultSet rs = null;
try
{
query = "SELECT " + DBIDName + " FROM " + tableName + " WHERE ";
query += lookupColumnName1 + " = '" + lookupColumnValue1 + "' AND ";
query += lookupColumnName2 + " = '" + lookupColumnValue2 + "'";
logFinest("Doing Query: " + query);
statement = connection.createStatement();
rs = statement.executeQuery(query);
while (rs.next())
ID = rs.getString(1);
} catch (Throwable th)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + th.getClass().getName()
+ " \". The cause was \" " + th.getMessage() + " \"");
} finally
{
try
{
if (rs != null) rs.close();
if (statement != null) statement.close();
} catch (SQLException sqle)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage() + " \"");
}
}
return ID;
}
public String lookupDBID2FirstNum(Connection connection, String DBIDName, String tableName, String lookupColumnName1, String lookupColumnValue1, String lookupColumnName2, String lookupColumnValue2) throws StorageDeviceException {
String query = null;
String ID = null;
Statement statement = null;
ResultSet rs = null;
try
{
query = "SELECT " + DBIDName + " FROM " + tableName + " WHERE ";
query += lookupColumnName1 + " =" + lookupColumnValue1 + " AND ";
query += lookupColumnName2 + " = '" + lookupColumnValue2 + "'";
logFinest("Doing Query: " + query);
statement = connection.createStatement();
rs = statement.executeQuery(query);
while (rs.next())
ID = rs.getString(1);
} catch (Throwable th)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + th.getClass().getName()
+ " \". The cause was \" " + th.getMessage() + " \"");
} finally
{
try
{
if (rs != null) rs.close();
if (statement != null) statement.close();
} catch (SQLException sqle)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage() + " \"");
}
}
return ID;
}
private String encodeLocalURL(String locationString)
{
// Replace any occurences of the host:port of the local Fedora
// server with the internal serialization string "local.fedora.server."
// This will make sure that local URLs (self-referential to the
// local server) will be recognizable if the server host and
// port configuration changes after an object is stored in the
// repository.
if (fedoraServerPort.equalsIgnoreCase("80") &&
hostPattern.matcher(locationString).find())
{
//System.out.println("port is 80 and host-only pattern found - convert to l.f.s");
return hostPattern.matcher(
locationString).replaceAll("http://local.fedora.server/");
}
else
{
//System.out.println("looking for hostPort pattern to convert to l.f.s");
return hostPortPattern.matcher(
locationString).replaceAll("http://local.fedora.server/");
}
}
private String unencodeLocalURL(String storedLocationString)
{
// Replace any occurrences of the internal serialization string
// "local.fedora.server" with the current host and port of the
// local Fedora server. This translates local URLs (self-referential
// to the local server) back into resolvable URLs that reflect
// the currently configured host and port for the server.
if (fedoraServerPort.equalsIgnoreCase("80"))
{
return serializedLocalURLPattern.matcher(
storedLocationString).replaceAll(fedoraServerHost);
}
else
{
return serializedLocalURLPattern.matcher(
storedLocationString).replaceAll(
fedoraServerHost+":"+fedoraServerPort);
}
}
private void addDisseminators(String doPID, Disseminator[] disseminators, DOReader doReader, Connection connection)
throws ReplicationException, SQLException, ServerException
{
DSBindingMapAugmented[] allBindingMaps;
String bDefDBID;
String bindingMapDBID;
String bMechDBID;
String dissDBID;
String doDBID;
String doLabel;
String dsBindingKeyDBID;
int rc;
doDBID = lookupDigitalObjectDBID(connection, doPID);
for (int i=0; i<disseminators.length; ++i) {
bDefDBID = lookupBehaviorDefinitionDBID(connection,
disseminators[i].bDefID);
if (bDefDBID == null) {
throw new ReplicationException("BehaviorDefinition row "
+ "doesn't exist for PID: "
+ disseminators[i].bDefID);
}
bMechDBID = lookupBehaviorMechanismDBID(connection,
disseminators[i].bMechID);
if (bMechDBID == null) {
throw new ReplicationException("BehaviorMechanism row "
+ "doesn't exist for PID: "
+ disseminators[i].bMechID);
}
// Insert Disseminator row if it doesn't exist.
dissDBID = lookupDisseminatorDBID(connection, bDefDBID,
bMechDBID, disseminators[i].dissID);
if (dissDBID == null) {
// Disseminator row doesn't exist, add it.
insertDisseminatorRow(connection, bDefDBID, bMechDBID,
disseminators[i].dissID, disseminators[i].dissLabel, disseminators[i].dissState);
//insertDisseminatorRow(connection, bDefDBID, bMechDBID,
//disseminators[i].dissID, disseminators[i].dissLabel, disseminators[i].dissState, disseminators[i].dsBindMapID);
dissDBID = lookupDisseminatorDBID(connection, bDefDBID,
bMechDBID, disseminators[i].dissID);
if (dissDBID == null) {
throw new ReplicationException("diss row "
+ "doesn't exist for PID: "
+ disseminators[i].dissID);
}
}
// Insert doDissAssoc row
insertDigitalObjectDissAssocRow(connection, doDBID,
dissDBID);
}
allBindingMaps = doReader.GetDSBindingMaps(null);
for (int i=0; i<allBindingMaps.length; ++i) {
bMechDBID = lookupBehaviorMechanismDBID(connection,
allBindingMaps[i].dsBindMechanismPID);
if (bMechDBID == null) {
throw new ReplicationException("BehaviorMechanism row "
+ "doesn't exist for PID: "
+ allBindingMaps[i].dsBindMechanismPID);
}
// Insert dsBindMap row if it doesn't exist.
bindingMapDBID = lookupDataStreamBindingMapDBID(connection,
bMechDBID, allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
// DataStreamBinding row doesn't exist, add it.
insertDataStreamBindingMapRow(connection, bMechDBID,
allBindingMaps[i].dsBindMapID,
allBindingMaps[i].dsBindMapLabel);
bindingMapDBID = lookupDataStreamBindingMapDBID(
connection,bMechDBID,allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
throw new ReplicationException(
"lookupdsBindMapDBID row "
+ "doesn't exist for bMechDBID: " + bMechDBID
+ ", dsBindingMapID: "
+ allBindingMaps[i].dsBindMapID);
}
}
for (int j=0; j<allBindingMaps[i].dsBindingsAugmented.length;
++j) {
dsBindingKeyDBID = lookupDataStreamBindingSpecDBID(
connection, bMechDBID,
allBindingMaps[i].dsBindingsAugmented[j].
bindKeyName);
if (dsBindingKeyDBID == null) {
throw new ReplicationException(
"lookupDataStreamBindingDBID row doesn't "
+ "exist for bMechDBID: " + bMechDBID
+ ", bindKeyName: " + allBindingMaps[i].
dsBindingsAugmented[j].bindKeyName + "i=" + i
+ " j=" + j);
}
// Insert DataStreamBinding row
//dissDBID = lookupDsBindingMapDBID(connection, bMechDBID, allBindingMaps[i].dsBindMapID);
//if (dissDBID==null) {
// throw new ReplicationException(
// "lookupDsBindingDBID row doesn't "
// + "exist for bMechDBID: " + bMechDBID
// + ", bindMapID: " + allBindingMaps[i].dsBindMapID + "i=" + i
// + " j=" + j);
//}
//System.out.println("dissDBID: "+dissDBID+" bmechDBID: "+bMechDBID+" bindmapID: "+allBindingMaps[i].dsBindMapID);
insertDataStreamBindingRow(connection, doDBID,
dsBindingKeyDBID,
bindingMapDBID,
//dissDBID,
allBindingMaps[i].dsBindingsAugmented[j].seqNo,
allBindingMaps[i].dsBindingsAugmented[j].
datastreamID,
allBindingMaps[i].dsBindingsAugmented[j].DSLabel,
allBindingMaps[i].dsBindingsAugmented[j].DSMIME,
// sdp - local.fedora.server conversion
encodeLocalURL(allBindingMaps[i].dsBindingsAugmented[j].DSLocation),
allBindingMaps[i].dsBindingsAugmented[j].DSControlGrp,
allBindingMaps[i].dsBindingsAugmented[j].DSVersionID,
"1",
"A");
}
}
return;
}
/**
* <p> Permanently removes a disseminator from the database incuding
* all associated datastream bindings and datastream binding maps.
* Associated entries are removed from the following db tables:</p>
* <ul>
* <li>doDissAssoc - all entries matching pid of data object.</li>
* <li>diss - all entries matching disseminator ID provided that no
* other objects depend on this disseminator.</li>
* <li>dsBind - all entries matching pid of data object.</li>
* <li>dsBindMap - all entries matching associated bMech object pid
* provided that no other objects depend on this binding map.</li>
* </ul>
* @param pid Persistent identifier for the data object.
* @param dissIds Set of disseminator IDs to be removed.
* @param doReader An instance of DOReader.
* @param connection A database connection.
* @throws SQLException If something totally unexpected happened.
*/
private void purgeDisseminators(String pid, HashSet dissIds, HashSet bmapIds, DOReader doReader, Connection connection)
throws SQLException
{
logFinest("DefaultDOReplicator.purgeDisseminators: Entering ------");
Statement st=null;
Statement st2=null;
ResultSet results=null;
try {
st=connection.createStatement();
//
// READ
//
logFinest("Checking do table for " + pid + "...");
results=logAndExecuteQuery(st, "SELECT doDbID FROM "
+ "do WHERE doPID='" + pid + "'");
if (!results.next()) {
// must not be a digitalobject...exit early
logFinest(pid + " wasn't found in do table..."
+ "skipping deletion as such.");
return;
}
int dbid=results.getInt("doDbID");
results.close();
logFinest(pid + " was found in do table (DBID="
+ dbid + ")");
logFinest("Getting dissDbID(s) from doDissAssoc "
+ "table...");
HashSet dissIdsNotShared = new HashSet();
logFinest("Getting dissDbID(s) from doDissAssoc "
+ "table unique to this object...");
logFinest("DefaultDOReplicator.purgeDisseminators: Found "
+ dissIds.size() + " dissDbId(s). ");
// Iterate over dissIds and separate those that are unique
// (i.e., not shared by other objects)
Iterator iterator = dissIds.iterator();
while (iterator.hasNext())
{
Integer id = (Integer)iterator.next();
logFinest("Getting occurrences of dissDbID(s) in "
+ "doDissAssoc table...");
results=logAndExecuteQuery(st, "SELECT COUNT(*) from "
+ "doDissAssoc WHERE dissDbID=" + id);
while (results.next())
{
Integer i1 = new Integer(results.getInt("COUNT(*)"));
if ( i1.intValue() == 1 )
{
// A dissDbID that occurs only once indicates that the
// disseminator is not used by other objects. In this case,
// we want to keep track of this dissDbID.
dissIdsNotShared.add(id);
}
}
results.close();
}
// Iterate over bmapIds and separate those that are unique
// (i.e., not shared by other objects)
logFinest("DefaultDOReplicator.purgeDisseminators: Found "
+ bmapIds.size() + " dsBindMapDbId(s). ");
iterator = bmapIds.iterator();
HashSet bmapIdsInUse = new HashSet();
HashSet bmapIdsShared = new HashSet();
HashSet bmapIdsNotShared = new HashSet();
while (iterator.hasNext() )
{
Integer id = (Integer)iterator.next();
ResultSet rs = null;
logFinest("Getting associated bmapId(s) that are unique "
+ "for this object in diss table...");
st2 = connection.createStatement();
rs=logAndExecuteQuery(st2, "SELECT DISTINCT doDbID FROM "
+ "dsBind WHERE dsBindMapDbID=" + id);
int rowCount = 0;
while (rs.next())
{
rowCount++;
}
if ( rowCount == 1 )
{
// A dsBindMapDbId that occurs only once indicates that
// the dsBindMapId is not used by other objects. In this case,
// we want to keep track of this dsBindMapDbId.
bmapIdsNotShared.add(id);
}
rs.close();
st2.close();
}
//
// WRITE
//
int rowCount;
// In doDissAssoc table, we are removing rows specific to the
// doDbId, so remove all dissDbIds (both shared and nonShared).
logFinest("Attempting row deletion from doDissAssoc "
+ "table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM "
+ "doDissAssoc WHERE doDbID=" + dbid
+ " AND ( " + inIntegerSetWhereConditionString("dissDbID", dissIds) + " )");
logFinest("Deleted " + rowCount + " row(s).");
// In dsBind table, we are removing rows specific to the doDbID,
// so remove all dsBindMapIds (both shared and nonShared).
logFinest("Attempting row deletion from dsBind table..");
rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBind "
+ "WHERE doDbID=" + dbid
+ " AND ( " + inIntegerSetWhereConditionString("dsBindMapDbID", bmapIds) + " )");
// In diss table, dissDbIds can be shared by other objects so only
// remove dissDbIds that are not shared.
logFinest("Attempting row deletion from diss table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM diss WHERE "
+ inIntegerSetWhereConditionString("dissDbID", dissIdsNotShared));
logFinest("Deleted " + rowCount + " row(s).");
// In dsBindMap table, dsBindMapIds can be shared by other objects
// so only remove dsBindMapIds that are not shared.
logFinest("Attempting row deletion from dsBindMap "
+ "table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBindMap "
+ "WHERE " + inIntegerSetWhereConditionString(
"dsBindMapDbID", bmapIdsNotShared));
logFinest("Deleted " + rowCount + " row(s).");
} finally {
if (results != null) results.close();
if (st!=null) st.close();
if (st2!=null) st2.close();
logFinest("DefaultDOReplicator.purgeDisseminators: Exiting ------");
}
}
}
| true | true | private boolean updateComponents(DOReader reader)
throws ReplicationException {
Connection connection=null;
Statement st=null;
ResultSet results=null;
boolean triedUpdate=false;
boolean failed=false;
logFinest("DefaultDOReplicator.updateComponents: Entering ------");
try {
connection=m_pool.getConnection();
st=connection.createStatement();
// get db ID for the digital object
results=logAndExecuteQuery(st, "SELECT doDbID,doState FROM do WHERE "
+ "doPID='" + reader.GetObjectPID() + "'");
if (!results.next()) {
logFinest("DefaultDOReplication.updateComponents: Object is "
+ "new; components dont need updating.");
return false;
}
int doDbID=results.getInt("doDbID");
String doState=results.getString("doState");
results.close();
ArrayList updates=new ArrayList();
// check if state has changed for the digital object
String objState = reader.GetObjectState();
if (!doState.equalsIgnoreCase(objState)) {
updates.add("UPDATE do SET doState='"+objState+"' WHERE doDbID=" + doDbID);
updates.add("UPDATE doRegistry SET objectState='"+objState+"' WHERE doPID='" + reader.GetObjectPID() + "'");
}
// check if any mods to datastreams for this digital object
results=logAndExecuteQuery(st, "SELECT dsID, dsLabel, dsLocation, dsCurrentVersionID, dsState "
+ "FROM dsBind WHERE doDbID=" + doDbID);
while (results.next()) {
String dsID=results.getString("dsID");
String dsLabel=results.getString("dsLabel");
String dsCurrentVersionID=results.getString("dsCurrentVersionID");
String dsState=results.getString("dsState");
// sdp - local.fedora.server conversion
String dsLocation=unencodeLocalURL(results.getString("dsLocation"));
// compare the latest version of the datastream to what's in the db...
// if different, add to update list
Datastream ds=reader.GetDatastream(dsID, null);
if (!ds.DSLabel.equals(dsLabel)
|| !ds.DSLocation.equals(dsLocation)
|| !ds.DSVersionID.equals(dsCurrentVersionID)
|| !ds.DSState.equals(dsState)) {
updates.add("UPDATE dsBind SET dsLabel='"
+ SQLUtility.aposEscape(ds.DSLabel) + "', dsLocation='"
// sdp - local.fedora.server conversion
+ SQLUtility.aposEscape(encodeLocalURL(ds.DSLocation))
+ "', dsCurrentVersionID='" + ds.DSVersionID + "', "
+ "dsState='" + ds.DSState + "' "
+ " WHERE doDbID=" + doDbID + " AND dsID='" + dsID + "'");
}
}
results.close();
// do any required updates via a transaction
if (updates.size()>0) {
connection.setAutoCommit(false);
triedUpdate=true;
for (int i=0; i<updates.size(); i++) {
String update=(String) updates.get(i);
logAndExecuteUpdate(st, update);
}
connection.commit();
} else {
logFinest("No datastream labels or locations changed.");
}
// check if any mods to disseminators for this object...
// first get a list of disseminator db IDs
results=logAndExecuteQuery(st, "SELECT dissDbID FROM doDissAssoc WHERE "
+ "doDbID="+doDbID);
HashSet dissDbIDs = new HashSet();
while (results.next()) {
dissDbIDs.add(new Integer(results.getInt("dissDbID")));
}
if (dissDbIDs.size()==0) {
logFinest("DefaultDOReplication.updateComponents: Object "
+ "has no disseminators; components dont need updating.");
return false;
}
results.close();
Iterator dissIter = dissDbIDs.iterator();
// Iterate over disseminators to check if any have been modified
while(dissIter.hasNext()) {
Integer dissDbID = (Integer) dissIter.next();
logFinest("Iterating, dissDbID: "+dissDbID);
// get disseminator info for this disseminator
results=logAndExecuteQuery(st, "SELECT diss.bDefDbID, diss.bMechDbID, bMech.bMechPID, diss.dissID, diss.dissLabel, diss.dissState "
+ "FROM diss,bMech WHERE bMech.bMechDbID=diss.bMechDbID AND diss.dissDbID=" + dissDbID);
updates=new ArrayList();
int bDefDbID = 0;
int bMechDbID = 0;
String dissID=null;
String dissLabel=null;
String dissState=null;
String bMechPID=null;
while(results.next()) {
bDefDbID = results.getInt("bDefDbID");
bMechDbID = results.getInt("bMechDbID");
dissID=results.getString("dissID");
dissLabel=results.getString("dissLabel");
dissState=results.getString("dissState");
bMechPID=results.getString("bMechPID");
}
results.close();
// compare the latest version of the disseminator with what's in the db...
// replace what's in db if they are different
Disseminator diss=reader.GetDisseminator(dissID, null);
if (diss == null) {
// xml object has no disseminators
// so this must be a purgeComponents or a new object
logFinest("DefaultDOReplicator.updateComponents: XML object has no disseminators");
return false;
}
if (!diss.dissLabel.equals(dissLabel)
|| !diss.bMechID.equals(bMechPID)
|| !diss.dissState.equals(dissState)) {
if (!diss.dissLabel.equals(dissLabel))
logFinest("dissLabel changed from '" + dissLabel + "' to '" + diss.dissLabel + "'");
if (!diss.dissState.equals(dissState))
logFinest("dissState changed from '" + dissState + "' to '" + diss.dissState + "'");
// we might need to set the bMechDbID to the id for the new one,
// if the mechanism changed
int newBMechDbID;
if (diss.bMechID.equals(bMechPID)) {
newBMechDbID=bMechDbID;
} else {
logFinest("bMechPID changed from '" + bMechPID + "' to '" + diss.bMechID + "'");
results=logAndExecuteQuery(st, "SELECT bMechDbID "
+ "FROM bMech "
+ "WHERE bMechPID='"
+ diss.bMechID + "'");
if (!results.next()) {
// shouldn't have gotten this far, but if so...
throw new ReplicationException("The behavior mechanism "
+ "changed to " + diss.bMechID + ", but there is no "
+ "record of that object in the dissemination db.");
}
newBMechDbID=results.getInt("bMechDbID");
results.close();
}
// update the diss table with all new, correct values
logAndExecuteUpdate(st, "UPDATE diss SET dissLabel='"
+ SQLUtility.aposEscape(diss.dissLabel)
+ "', bMechDbID=" + newBMechDbID + ", "
+ "dissID='" + diss.dissID + "', "
+ "dissState='" + diss.dissState + "' "
+ " WHERE dissDbID=" + dissDbID + " AND bDefDbID=" + bDefDbID + " AND bMechDbID=" + bMechDbID);
}
// compare the latest version of the disseminator's bindMap with what's in the db
// and replace what's in db if they are different
results=logAndExecuteQuery(st, "SELECT DISTINCT dsBindMap.dsBindMapID,dsBindMap.dsBindMapDbID FROM dsBind,dsBindMap WHERE "
+ "dsBind.doDbID=" + doDbID + " AND dsBindMap.dsBindMapDbID=dsBind.dsBindMapDbID "
+ "AND dsBindMap.bMechDbID="+bMechDbID);
String origDSBindMapID=null;
int origDSBindMapDbID=0;
while (results.next()) {
origDSBindMapID=results.getString("dsBindMapID");
origDSBindMapDbID=results.getInt("dsBindMapDbID");
}
results.close();
String newDSBindMapID=diss.dsBindMapID;
if (!newDSBindMapID.equals(origDSBindMapID)) {
// dsBindingMap was modified so remove original bindingMap and datastreams.
// BindingMaps can be shared by other objects so first check to see if
// the orignial bindingMap is bound to datastreams of any other objects.
Statement st2 = connection.createStatement();
results=logAndExecuteQuery(st2,"SELECT DISTINCT doDbId,dsBindMapDbId FROM dsBind WHERE dsBindMapDbId="+origDSBindMapDbID);
int numRows = 0;
while (results.next()) {
numRows++;
}
st2.close();
results.close();
if(numRows == 1) {
// The bindingMap is NOT shared by any other objects and can be removed.
int rowCount = logAndExecuteUpdate(st, "DELETE FROM dsBindMap WHERE dsBindMapDbID=" + origDSBindMapDbID);
logFinest("deleted "+rowCount+" rows from dsBindMapDbID");
} else {
// The bindingMap IS shared by other objects so leave bindingMap untouched.
logFinest("dsBindMapID: "+origDSBindMapID+" is shared by other objects; it will NOT be deleted");
}
int rowCount = logAndExecuteUpdate(st,"DELETE FROM dsBind WHERE doDbID=" + doDbID);
logFinest("deleted "+rowCount+" rows from dsBind");
// now add back new datastreams and dsBindMap associated with this disseminator
DSBindingMapAugmented[] allBindingMaps;
Disseminator disseminators[];
String bDefDBID;
String bindingMapDBID;
String bMechDBID;
String dissDBID;
String doDBID;
String doPID;
String doLabel;
String dsBindingKeyDBID;
allBindingMaps = reader.GetDSBindingMaps(null);
for (int i=0; i<allBindingMaps.length; ++i) {
// only update bindingMap that was modified
if (allBindingMaps[i].dsBindMapID.equals(newDSBindMapID)) {
bMechDBID = lookupBehaviorMechanismDBID(connection,
allBindingMaps[i].dsBindMechanismPID);
if (bMechDBID == null) {
throw new ReplicationException("BehaviorMechanism row "
+ "doesn't exist for PID: "
+ allBindingMaps[i].dsBindMechanismPID);
}
// Insert dsBindMap row if it doesn't exist.
bindingMapDBID = lookupDataStreamBindingMapDBID(connection,
bMechDBID, allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
// DataStreamBinding row doesn't exist, add it.
insertDataStreamBindingMapRow(connection, bMechDBID,
allBindingMaps[i].dsBindMapID,
allBindingMaps[i].dsBindMapLabel);
bindingMapDBID = lookupDataStreamBindingMapDBID(
connection,bMechDBID,allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
throw new ReplicationException(
"lookupdsBindMapDBID row "
+ "doesn't exist for bMechDBID: " + bMechDBID
+ ", dsBindingMapID: "
+ allBindingMaps[i].dsBindMapID);
}
}
logFinest("augmentedlength: "+allBindingMaps[i].dsBindingsAugmented.length);
for (int j=0; j<allBindingMaps[i].dsBindingsAugmented.length;
++j) {
logFinest("j: "+j);
dsBindingKeyDBID = lookupDataStreamBindingSpecDBID(
connection, bMechDBID,
allBindingMaps[i].dsBindingsAugmented[j].
bindKeyName);
if (dsBindingKeyDBID == null) {
throw new ReplicationException(
"lookupDataStreamBindingDBID row doesn't "
+ "exist for bMechDBID: " + bMechDBID
+ ", bindKeyName: " + allBindingMaps[i].
dsBindingsAugmented[j].bindKeyName + "i=" + i
+ " j=" + j);
}
// Insert DataStreamBinding row
insertDataStreamBindingRow(connection, new Integer(doDbID).toString(),
dsBindingKeyDBID,
bindingMapDBID,
allBindingMaps[i].dsBindingsAugmented[j].seqNo,
allBindingMaps[i].dsBindingsAugmented[j].
datastreamID,
allBindingMaps[i].dsBindingsAugmented[j].DSLabel,
allBindingMaps[i].dsBindingsAugmented[j].DSMIME,
// sdp - local.fedora.server conversion
encodeLocalURL(allBindingMaps[i].dsBindingsAugmented[j].DSLocation),
allBindingMaps[i].dsBindingsAugmented[j].DSControlGrp,
allBindingMaps[i].dsBindingsAugmented[j].DSVersionID,
"1",
"A");
}
}
}
}
}
} catch (SQLException sqle) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage());
} catch (ServerException se) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection!=null) {
try {
if (triedUpdate && failed) connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName()
+ ": " + th.getMessage());
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
connection.setAutoCommit(true);
} catch (SQLException sqle) {
logWarning("While cleaning up: " + sqle.getClass().getName()
+ ": " + sqle.getMessage());
} finally {
m_pool.free(connection);
}
}
}
}
logFinest("DefaultDOReplicator.updateComponents: Exiting ------");
return true;
}
| private boolean updateComponents(DOReader reader)
throws ReplicationException {
Connection connection=null;
Statement st=null;
ResultSet results=null;
boolean triedUpdate=false;
boolean failed=false;
logFinest("DefaultDOReplicator.updateComponents: Entering ------");
try {
connection=m_pool.getConnection();
st=connection.createStatement();
// get db ID for the digital object
results=logAndExecuteQuery(st, "SELECT doDbID,doState FROM do WHERE "
+ "doPID='" + reader.GetObjectPID() + "'");
if (!results.next()) {
logFinest("DefaultDOReplication.updateComponents: Object is "
+ "new; components dont need updating.");
return false;
}
int doDbID=results.getInt("doDbID");
String doState=results.getString("doState");
results.close();
ArrayList updates=new ArrayList();
// check if state has changed for the digital object
String objState = reader.GetObjectState();
if (!doState.equalsIgnoreCase(objState)) {
updates.add("UPDATE do SET doState='"+objState+"' WHERE doDbID=" + doDbID);
updates.add("UPDATE doRegistry SET objectState='"+objState+"' WHERE doPID='" + reader.GetObjectPID() + "'");
}
// check if any mods to datastreams for this digital object
results=logAndExecuteQuery(st, "SELECT dsID, dsLabel, dsLocation, dsCurrentVersionID, dsState "
+ "FROM dsBind WHERE doDbID=" + doDbID);
while (results.next()) {
String dsID=results.getString("dsID");
String dsLabel=results.getString("dsLabel");
String dsCurrentVersionID=results.getString("dsCurrentVersionID");
String dsState=results.getString("dsState");
// sdp - local.fedora.server conversion
String dsLocation=unencodeLocalURL(results.getString("dsLocation"));
// compare the latest version of the datastream to what's in the db...
// if different, add to update list
Datastream ds=reader.GetDatastream(dsID, null);
if (!ds.DSLabel.equals(dsLabel)
|| !ds.DSLocation.equals(dsLocation)
|| !ds.DSVersionID.equals(dsCurrentVersionID)
|| !ds.DSState.equals(dsState)) {
updates.add("UPDATE dsBind SET dsLabel='"
+ SQLUtility.aposEscape(ds.DSLabel) + "', dsLocation='"
// sdp - local.fedora.server conversion
+ SQLUtility.aposEscape(encodeLocalURL(ds.DSLocation))
+ "', dsCurrentVersionID='" + ds.DSVersionID + "', "
+ "dsState='" + ds.DSState + "' "
+ " WHERE doDbID=" + doDbID + " AND dsID='" + dsID + "'");
}
}
results.close();
// do any required updates via a transaction
if (updates.size()>0) {
connection.setAutoCommit(false);
triedUpdate=true;
for (int i=0; i<updates.size(); i++) {
String update=(String) updates.get(i);
logAndExecuteUpdate(st, update);
}
connection.commit();
} else {
logFinest("No datastream labels or locations changed.");
}
// check if any mods to disseminators for this object...
// first get a list of disseminator db IDs
results=logAndExecuteQuery(st, "SELECT dissDbID FROM doDissAssoc WHERE "
+ "doDbID="+doDbID);
HashSet dissDbIDs = new HashSet();
while (results.next()) {
dissDbIDs.add(new Integer(results.getInt("dissDbID")));
}
if (dissDbIDs.size()==0 || reader.GetDisseminators(null, null).length!=dissDbIDs.size()) {
logFinest("DefaultDOReplication.updateComponents: Object "
+ "has no disseminators; components dont need updating.");
return false;
}
results.close();
Iterator dissIter = dissDbIDs.iterator();
// Iterate over disseminators to check if any have been modified
while(dissIter.hasNext()) {
Integer dissDbID = (Integer) dissIter.next();
logFinest("Iterating, dissDbID: "+dissDbID);
// get disseminator info for this disseminator
results=logAndExecuteQuery(st, "SELECT diss.bDefDbID, diss.bMechDbID, bMech.bMechPID, diss.dissID, diss.dissLabel, diss.dissState "
+ "FROM diss,bMech WHERE bMech.bMechDbID=diss.bMechDbID AND diss.dissDbID=" + dissDbID);
updates=new ArrayList();
int bDefDbID = 0;
int bMechDbID = 0;
String dissID=null;
String dissLabel=null;
String dissState=null;
String bMechPID=null;
while(results.next()) {
bDefDbID = results.getInt("bDefDbID");
bMechDbID = results.getInt("bMechDbID");
dissID=results.getString("dissID");
dissLabel=results.getString("dissLabel");
dissState=results.getString("dissState");
bMechPID=results.getString("bMechPID");
}
results.close();
// compare the latest version of the disseminator with what's in the db...
// replace what's in db if they are different
Disseminator diss=reader.GetDisseminator(dissID, null);
if (diss == null) {
// xml object has no disseminators
// so this must be a purgeComponents or a new object
logFinest("DefaultDOReplicator.updateComponents: XML object has no disseminators");
return false;
}
if (!diss.dissLabel.equals(dissLabel)
|| !diss.bMechID.equals(bMechPID)
|| !diss.dissState.equals(dissState)) {
if (!diss.dissLabel.equals(dissLabel))
logFinest("dissLabel changed from '" + dissLabel + "' to '" + diss.dissLabel + "'");
if (!diss.dissState.equals(dissState))
logFinest("dissState changed from '" + dissState + "' to '" + diss.dissState + "'");
// we might need to set the bMechDbID to the id for the new one,
// if the mechanism changed
int newBMechDbID;
if (diss.bMechID.equals(bMechPID)) {
newBMechDbID=bMechDbID;
} else {
logFinest("bMechPID changed from '" + bMechPID + "' to '" + diss.bMechID + "'");
results=logAndExecuteQuery(st, "SELECT bMechDbID "
+ "FROM bMech "
+ "WHERE bMechPID='"
+ diss.bMechID + "'");
if (!results.next()) {
// shouldn't have gotten this far, but if so...
throw new ReplicationException("The behavior mechanism "
+ "changed to " + diss.bMechID + ", but there is no "
+ "record of that object in the dissemination db.");
}
newBMechDbID=results.getInt("bMechDbID");
results.close();
}
// update the diss table with all new, correct values
logAndExecuteUpdate(st, "UPDATE diss SET dissLabel='"
+ SQLUtility.aposEscape(diss.dissLabel)
+ "', bMechDbID=" + newBMechDbID + ", "
+ "dissID='" + diss.dissID + "', "
+ "dissState='" + diss.dissState + "' "
+ " WHERE dissDbID=" + dissDbID + " AND bDefDbID=" + bDefDbID + " AND bMechDbID=" + bMechDbID);
}
// compare the latest version of the disseminator's bindMap with what's in the db
// and replace what's in db if they are different
results=logAndExecuteQuery(st, "SELECT DISTINCT dsBindMap.dsBindMapID,dsBindMap.dsBindMapDbID FROM dsBind,dsBindMap WHERE "
+ "dsBind.doDbID=" + doDbID + " AND dsBindMap.dsBindMapDbID=dsBind.dsBindMapDbID "
+ "AND dsBindMap.bMechDbID="+bMechDbID);
String origDSBindMapID=null;
int origDSBindMapDbID=0;
while (results.next()) {
origDSBindMapID=results.getString("dsBindMapID");
origDSBindMapDbID=results.getInt("dsBindMapDbID");
}
results.close();
String newDSBindMapID=diss.dsBindMapID;
if (!newDSBindMapID.equals(origDSBindMapID)) {
// dsBindingMap was modified so remove original bindingMap and datastreams.
// BindingMaps can be shared by other objects so first check to see if
// the orignial bindingMap is bound to datastreams of any other objects.
Statement st2 = connection.createStatement();
results=logAndExecuteQuery(st2,"SELECT DISTINCT doDbId,dsBindMapDbId FROM dsBind WHERE dsBindMapDbId="+origDSBindMapDbID);
int numRows = 0;
while (results.next()) {
numRows++;
}
st2.close();
results.close();
if(numRows == 1) {
// The bindingMap is NOT shared by any other objects and can be removed.
int rowCount = logAndExecuteUpdate(st, "DELETE FROM dsBindMap WHERE dsBindMapDbID=" + origDSBindMapDbID);
logFinest("deleted "+rowCount+" rows from dsBindMapDbID");
} else {
// The bindingMap IS shared by other objects so leave bindingMap untouched.
logFinest("dsBindMapID: "+origDSBindMapID+" is shared by other objects; it will NOT be deleted");
}
int rowCount = logAndExecuteUpdate(st,"DELETE FROM dsBind WHERE doDbID=" + doDbID);
logFinest("deleted "+rowCount+" rows from dsBind");
// now add back new datastreams and dsBindMap associated with this disseminator
DSBindingMapAugmented[] allBindingMaps;
Disseminator disseminators[];
String bDefDBID;
String bindingMapDBID;
String bMechDBID;
String dissDBID;
String doDBID;
String doPID;
String doLabel;
String dsBindingKeyDBID;
allBindingMaps = reader.GetDSBindingMaps(null);
for (int i=0; i<allBindingMaps.length; ++i) {
// only update bindingMap that was modified
if (allBindingMaps[i].dsBindMapID.equals(newDSBindMapID)) {
bMechDBID = lookupBehaviorMechanismDBID(connection,
allBindingMaps[i].dsBindMechanismPID);
if (bMechDBID == null) {
throw new ReplicationException("BehaviorMechanism row "
+ "doesn't exist for PID: "
+ allBindingMaps[i].dsBindMechanismPID);
}
// Insert dsBindMap row if it doesn't exist.
bindingMapDBID = lookupDataStreamBindingMapDBID(connection,
bMechDBID, allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
// DataStreamBinding row doesn't exist, add it.
insertDataStreamBindingMapRow(connection, bMechDBID,
allBindingMaps[i].dsBindMapID,
allBindingMaps[i].dsBindMapLabel);
bindingMapDBID = lookupDataStreamBindingMapDBID(
connection,bMechDBID,allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
throw new ReplicationException(
"lookupdsBindMapDBID row "
+ "doesn't exist for bMechDBID: " + bMechDBID
+ ", dsBindingMapID: "
+ allBindingMaps[i].dsBindMapID);
}
}
logFinest("augmentedlength: "+allBindingMaps[i].dsBindingsAugmented.length);
for (int j=0; j<allBindingMaps[i].dsBindingsAugmented.length;
++j) {
logFinest("j: "+j);
dsBindingKeyDBID = lookupDataStreamBindingSpecDBID(
connection, bMechDBID,
allBindingMaps[i].dsBindingsAugmented[j].
bindKeyName);
if (dsBindingKeyDBID == null) {
throw new ReplicationException(
"lookupDataStreamBindingDBID row doesn't "
+ "exist for bMechDBID: " + bMechDBID
+ ", bindKeyName: " + allBindingMaps[i].
dsBindingsAugmented[j].bindKeyName + "i=" + i
+ " j=" + j);
}
// Insert DataStreamBinding row
insertDataStreamBindingRow(connection, new Integer(doDbID).toString(),
dsBindingKeyDBID,
bindingMapDBID,
allBindingMaps[i].dsBindingsAugmented[j].seqNo,
allBindingMaps[i].dsBindingsAugmented[j].
datastreamID,
allBindingMaps[i].dsBindingsAugmented[j].DSLabel,
allBindingMaps[i].dsBindingsAugmented[j].DSMIME,
// sdp - local.fedora.server conversion
encodeLocalURL(allBindingMaps[i].dsBindingsAugmented[j].DSLocation),
allBindingMaps[i].dsBindingsAugmented[j].DSControlGrp,
allBindingMaps[i].dsBindingsAugmented[j].DSVersionID,
"1",
"A");
}
}
}
}
}
} catch (SQLException sqle) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage());
} catch (ServerException se) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection!=null) {
try {
if (triedUpdate && failed) connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName()
+ ": " + th.getMessage());
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
connection.setAutoCommit(true);
} catch (SQLException sqle) {
logWarning("While cleaning up: " + sqle.getClass().getName()
+ ": " + sqle.getMessage());
} finally {
m_pool.free(connection);
}
}
}
}
logFinest("DefaultDOReplicator.updateComponents: Exiting ------");
return true;
}
|
diff --git a/src/com/kh/beatbot/midi/MidiNote.java b/src/com/kh/beatbot/midi/MidiNote.java
index 42da1aab..7603eb88 100644
--- a/src/com/kh/beatbot/midi/MidiNote.java
+++ b/src/com/kh/beatbot/midi/MidiNote.java
@@ -1,136 +1,137 @@
package com.kh.beatbot.midi;
import com.kh.beatbot.global.GlobalVars;
import com.kh.beatbot.midi.event.MidiEvent;
import com.kh.beatbot.midi.event.NoteOff;
import com.kh.beatbot.midi.event.NoteOn;
import com.kh.beatbot.view.helper.LevelsViewHelper;
public class MidiNote {
NoteOn noteOn;
NoteOff noteOff;
public MidiNote(NoteOn noteOn, NoteOff noteOff) {
this.noteOn = noteOn;
this.noteOff = noteOff;
}
public MidiNote getCopy() {
NoteOn noteOnCopy = new NoteOn(noteOn.getTick(), 0, noteOn.getNoteValue(), noteOn.getVelocity(), noteOn.getPan(), noteOn.getPitch());
NoteOff noteOffCopy = new NoteOff(noteOff.getTick(), 0, noteOff.getNoteValue(), noteOff.getVelocity(), noteOff.getPan(), noteOn.getPitch());
return new MidiNote(noteOnCopy, noteOffCopy);
}
public MidiEvent getOnEvent() {
return noteOn;
}
public MidiEvent getOffEvent() {
return noteOff;
}
public long getOnTick() {
return noteOn.getTick();
}
public long getOffTick() {
return noteOff.getTick();
}
public int getNoteValue() {
return noteOn.getNoteValue();
}
public float getVelocity() {
return noteOn.getVelocity();
}
public float getPan() {
return noteOn.getPan();
}
public float getPitch() {
return noteOn.getPitch();
}
public void setVelocity(float velocity) {
velocity = clipLevel(velocity);
noteOn.setVelocity(velocity);
noteOff.setVelocity(velocity);
}
public void setPan(float pan) {
pan = clipLevel(pan);
noteOn.setPan(pan);
noteOff.setPan(pan);
}
public void setPitch(float pitch) {
pitch = clipLevel(pitch);
noteOn.setPitch(pitch);
noteOff.setPitch(pitch);
}
// clip the level to be within the min/max allowed
// (0-1)
private float clipLevel(float level) {
if (level < 0)
return 0;
if (level > 1)
return 1;
return level;
}
public void setOnTick(long onTick) {
if (onTick >= 0)
noteOn.setTick(onTick);
else
noteOn.setTick(0);
}
public void setOffTick(long offTick) {
if (offTick > getOnTick())
this.noteOff.setTick(offTick);
}
public void setNote(int note) {
if (note < 0)
return;
this.noteOn.setNoteValue(note);
this.noteOff.setNoteValue(note);
}
public long getNoteLength() {
return noteOff.getTick() - noteOn.getTick();
}
public float getLevel(LevelsViewHelper.LevelMode levelMode) {
if (levelMode == LevelsViewHelper.LevelMode.VOLUME)
return noteOn.getVelocity();
else if (levelMode == LevelsViewHelper.LevelMode.PAN)
return noteOn.getPan();
else if (levelMode == LevelsViewHelper.LevelMode.PITCH)
return noteOn.getPitch();
return 0;
}
public void setLevel(LevelsViewHelper.LevelMode levelMode, float level) {
+ float clippedLevel = clipLevel(level);
if (levelMode == LevelsViewHelper.LevelMode.VOLUME) {
- setVelocity(level);
- setVolume(getNoteValue(), getOnTick(), level);
+ setVelocity(clippedLevel);
+ setVolume(getNoteValue(), getOnTick(), clippedLevel);
}
else if (levelMode == LevelsViewHelper.LevelMode.PAN) {
- setPan(level);
- setPan(getNoteValue(), getOnTick(), level);
+ setPan(clippedLevel);
+ setPan(getNoteValue(), getOnTick(), clippedLevel);
}
else if (levelMode == LevelsViewHelper.LevelMode.PITCH) {
- setPitch(level);
- setPitch(getNoteValue(), getOnTick(), level);
+ setPitch(clippedLevel);
+ setPitch(getNoteValue(), getOnTick(), clippedLevel);
}
}
public native void setVolume(int track, long onTick, float volume);
public native void setPan(int track, long onTick, float pan);
public native void setPitch(int track, long onTick, float pitch);
}
| false | true | public void setLevel(LevelsViewHelper.LevelMode levelMode, float level) {
if (levelMode == LevelsViewHelper.LevelMode.VOLUME) {
setVelocity(level);
setVolume(getNoteValue(), getOnTick(), level);
}
else if (levelMode == LevelsViewHelper.LevelMode.PAN) {
setPan(level);
setPan(getNoteValue(), getOnTick(), level);
}
else if (levelMode == LevelsViewHelper.LevelMode.PITCH) {
setPitch(level);
setPitch(getNoteValue(), getOnTick(), level);
}
}
| public void setLevel(LevelsViewHelper.LevelMode levelMode, float level) {
float clippedLevel = clipLevel(level);
if (levelMode == LevelsViewHelper.LevelMode.VOLUME) {
setVelocity(clippedLevel);
setVolume(getNoteValue(), getOnTick(), clippedLevel);
}
else if (levelMode == LevelsViewHelper.LevelMode.PAN) {
setPan(clippedLevel);
setPan(getNoteValue(), getOnTick(), clippedLevel);
}
else if (levelMode == LevelsViewHelper.LevelMode.PITCH) {
setPitch(clippedLevel);
setPitch(getNoteValue(), getOnTick(), clippedLevel);
}
}
|
diff --git a/src/jp/muo/smsproxy/SmsReceiver.java b/src/jp/muo/smsproxy/SmsReceiver.java
index 80856bc..c7c811e 100644
--- a/src/jp/muo/smsproxy/SmsReceiver.java
+++ b/src/jp/muo/smsproxy/SmsReceiver.java
@@ -1,33 +1,36 @@
package jp.muo.smsproxy;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class SmsReceiver extends BroadcastReceiver {
public static final String TAG = "smsProxy";
@Override
public void onReceive(Context context, Intent intent) {
// Log.d(TAG, "received");
SmsProxyManager mgr = new SmsProxyManager(context);
mgr.setType(SmsProxyManager.Mode.SMS);
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
if (bundle != null && mgr.isEnabled() && !mgr.getProxyTo().equals("")) {
String msgText = "";
Object[] pdus = (Object[]) bundle.get("pdus");
+ if (pdus.length == 0) {
+ return;
+ }
// Log.d(TAG, Integer.toString(pdus.length) + " messages found");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
msgText += "fwd " + msgs[i].getOriginatingAddress() + ":\n";
msgText += msgs[i].getMessageBody().toString() + "\n";
}
// Log.d(TAG, "msg: " + msgText);
mgr.send(msgText);
}
}
}
| true | true | public void onReceive(Context context, Intent intent) {
// Log.d(TAG, "received");
SmsProxyManager mgr = new SmsProxyManager(context);
mgr.setType(SmsProxyManager.Mode.SMS);
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
if (bundle != null && mgr.isEnabled() && !mgr.getProxyTo().equals("")) {
String msgText = "";
Object[] pdus = (Object[]) bundle.get("pdus");
// Log.d(TAG, Integer.toString(pdus.length) + " messages found");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
msgText += "fwd " + msgs[i].getOriginatingAddress() + ":\n";
msgText += msgs[i].getMessageBody().toString() + "\n";
}
// Log.d(TAG, "msg: " + msgText);
mgr.send(msgText);
}
}
| public void onReceive(Context context, Intent intent) {
// Log.d(TAG, "received");
SmsProxyManager mgr = new SmsProxyManager(context);
mgr.setType(SmsProxyManager.Mode.SMS);
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
if (bundle != null && mgr.isEnabled() && !mgr.getProxyTo().equals("")) {
String msgText = "";
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus.length == 0) {
return;
}
// Log.d(TAG, Integer.toString(pdus.length) + " messages found");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
msgText += "fwd " + msgs[i].getOriginatingAddress() + ":\n";
msgText += msgs[i].getMessageBody().toString() + "\n";
}
// Log.d(TAG, "msg: " + msgText);
mgr.send(msgText);
}
}
|
diff --git a/Evil.java b/Evil.java
index 77d5098..7407c80 100644
--- a/Evil.java
+++ b/Evil.java
@@ -1,143 +1,145 @@
import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;
import org.antlr.stringtemplate.*;
import java.io.*;
import java.util.Vector;
import java.util.HashMap;
public class Evil
{
public static void main(String[] args)
{
parseParameters(args);
CommonTokenStream tokens = new CommonTokenStream(createLexer());
EvilParser parser = new EvilParser(tokens);
EvilParser.program_return ret = null;
try
{
ret = parser.program();
}
catch (org.antlr.runtime.RecognitionException e)
{
error(e.toString());
}
CommonTree t = (CommonTree)ret.getTree();
if (_displayAST && t != null)
{
DOTTreeGenerator gen = new DOTTreeGenerator();
StringTemplate st = gen.toDOT(t);
System.out.println(st);
}
/*
To create and invoke a tree parser. Modify with the appropriate
name of the tree parser and the appropriate start rule.
*/
try
{
CommonTreeNodeStream nodes = new CommonTreeNodeStream(t);
nodes.setTokenStream(tokens);
TypeCheck tparser = new TypeCheck(nodes);
MyBoolean verified = new MyBoolean();
verified.setTrue();
boolean checked = true;
tparser.verify(verified);
- if(verified.isTrue()) {
- nodes.reset();
- CFG controlflow = new CFG(nodes);
- controlflow.setFile(_inputFile);
- controlflow.generate();
- }
+ if(verified.isTrue()) {
+ nodes.reset();
+ CFG controlflow = new CFG(nodes);
+ controlflow.setFile(_inputFile);
+ controlflow.generate();
+ } else {
+ System.exit(1);
+ }
}
catch (org.antlr.runtime.RecognitionException e)
{
error(e.toString());
}
}
private static final String DISPLAYAST = "-displayAST";
private static final String FUNCTIONINLINE = "-finline";
private static final String NOFUNCTIONINLINE = "-nofinline";
private static final String DEADCODE = "-deadcode";
private static final String NODEADCODE = "-nodeadcode";
private static String _inputFile = null;
private static boolean _displayAST = false;
private static void parseParameters(String [] args)
{
for (int i = 0; i < args.length; i++)
{
if (args[i].equals(DISPLAYAST))
{
_displayAST = true;
}
else if (args[i].equals(FUNCTIONINLINE))
{
Block.FUNCTION_INLINING = true;
}
else if (args[i].equals(NOFUNCTIONINLINE))
{
Block.FUNCTION_INLINING = false;
}
else if (args[i].equals(DEADCODE))
{
Block.DEAD_CODE = true;
}
else if (args[i].equals(NODEADCODE))
{
Block.DEAD_CODE = false;
}
else if (args[i].charAt(0) == '-')
{
System.err.println("unexpected option: " + args[i]);
System.exit(1);
}
else if (_inputFile != null)
{
System.err.println("too many files specified");
System.exit(1);
}
else
{
_inputFile = args[i];
}
}
}
private static void error(String msg)
{
System.err.println(msg);
System.exit(1);
}
private static EvilLexer createLexer()
{
try
{
ANTLRInputStream input;
if (_inputFile == null)
{
input = new ANTLRInputStream(System.in);
}
else
{
input = new ANTLRInputStream(
new BufferedInputStream(new FileInputStream(_inputFile)));
}
return new EvilLexer(input);
}
catch (java.io.IOException e)
{
System.err.println("file not found: " + _inputFile);
System.exit(1);
return null;
}
}
}
| true | true | public static void main(String[] args)
{
parseParameters(args);
CommonTokenStream tokens = new CommonTokenStream(createLexer());
EvilParser parser = new EvilParser(tokens);
EvilParser.program_return ret = null;
try
{
ret = parser.program();
}
catch (org.antlr.runtime.RecognitionException e)
{
error(e.toString());
}
CommonTree t = (CommonTree)ret.getTree();
if (_displayAST && t != null)
{
DOTTreeGenerator gen = new DOTTreeGenerator();
StringTemplate st = gen.toDOT(t);
System.out.println(st);
}
/*
To create and invoke a tree parser. Modify with the appropriate
name of the tree parser and the appropriate start rule.
*/
try
{
CommonTreeNodeStream nodes = new CommonTreeNodeStream(t);
nodes.setTokenStream(tokens);
TypeCheck tparser = new TypeCheck(nodes);
MyBoolean verified = new MyBoolean();
verified.setTrue();
boolean checked = true;
tparser.verify(verified);
if(verified.isTrue()) {
nodes.reset();
CFG controlflow = new CFG(nodes);
controlflow.setFile(_inputFile);
controlflow.generate();
}
}
catch (org.antlr.runtime.RecognitionException e)
{
error(e.toString());
}
}
| public static void main(String[] args)
{
parseParameters(args);
CommonTokenStream tokens = new CommonTokenStream(createLexer());
EvilParser parser = new EvilParser(tokens);
EvilParser.program_return ret = null;
try
{
ret = parser.program();
}
catch (org.antlr.runtime.RecognitionException e)
{
error(e.toString());
}
CommonTree t = (CommonTree)ret.getTree();
if (_displayAST && t != null)
{
DOTTreeGenerator gen = new DOTTreeGenerator();
StringTemplate st = gen.toDOT(t);
System.out.println(st);
}
/*
To create and invoke a tree parser. Modify with the appropriate
name of the tree parser and the appropriate start rule.
*/
try
{
CommonTreeNodeStream nodes = new CommonTreeNodeStream(t);
nodes.setTokenStream(tokens);
TypeCheck tparser = new TypeCheck(nodes);
MyBoolean verified = new MyBoolean();
verified.setTrue();
boolean checked = true;
tparser.verify(verified);
if(verified.isTrue()) {
nodes.reset();
CFG controlflow = new CFG(nodes);
controlflow.setFile(_inputFile);
controlflow.generate();
} else {
System.exit(1);
}
}
catch (org.antlr.runtime.RecognitionException e)
{
error(e.toString());
}
}
|
diff --git a/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatTaskCompleteListener.java b/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatTaskCompleteListener.java
index 4e97b4cf6..ac17ffba7 100644
--- a/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatTaskCompleteListener.java
+++ b/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatTaskCompleteListener.java
@@ -1,121 +1,121 @@
package com.todoroo.astrid.repeats;
import java.text.ParseException;
import java.util.Date;
import java.util.TimeZone;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.google.ical.iter.RecurrenceIterator;
import com.google.ical.iter.RecurrenceIteratorFactory;
import com.google.ical.values.DateTimeValueImpl;
import com.google.ical.values.DateValue;
import com.google.ical.values.DateValueImpl;
import com.google.ical.values.Frequency;
import com.google.ical.values.RRule;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.service.ExceptionService;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.astrid.api.AstridApiConstants;
import com.todoroo.astrid.model.Task;
import com.todoroo.astrid.service.TaskService;
public class RepeatTaskCompleteListener extends BroadcastReceiver {
@Autowired
private TaskService taskService;
@Autowired
private ExceptionService exceptionService;
@Override
public void onReceive(Context context, Intent intent) {
long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1);
if(taskId == -1)
return;
DependencyInjectionService.getInstance().inject(this);
Task task = taskService.fetchById(taskId, Task.ID, Task.RECURRENCE,
Task.DUE_DATE, Task.FLAGS, Task.HIDE_UNTIL);
if(task == null)
return;
String recurrence = task.getValue(Task.RECURRENCE);
- if(recurrence.length() > 0) {
+ if(recurrence != null && recurrence.length() > 0) {
DateValue repeatFrom;
Date repeatFromDate = new Date();
DateValue today = new DateValueImpl(repeatFromDate.getYear() + 1900,
repeatFromDate.getMonth() + 1, repeatFromDate.getDate());
if(task.hasDueDate() && !task.getFlag(Task.FLAGS, Task.FLAG_REPEAT_AFTER_COMPLETION)) {
repeatFromDate = new Date(task.getValue(Task.DUE_DATE));
if(task.hasDueTime()) {
repeatFrom = new DateTimeValueImpl(repeatFromDate.getYear() + 1900,
repeatFromDate.getMonth() + 1, repeatFromDate.getDate(),
repeatFromDate.getHours(), repeatFromDate.getMinutes(), repeatFromDate.getSeconds());
} else {
repeatFrom = new DateValueImpl(repeatFromDate.getYear() + 1900,
repeatFromDate.getMonth() + 1, repeatFromDate.getDate());
}
} else {
repeatFrom = today;
}
// invoke the recurrence iterator
try {
long newDueDate;
RRule rrule = new RRule(recurrence);
if(rrule.getFreq() == Frequency.HOURLY) {
newDueDate = task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME,
repeatFromDate.getTime() + DateUtilities.ONE_HOUR * rrule.getInterval());
} else {
RecurrenceIterator iterator = RecurrenceIteratorFactory.createRecurrenceIterator(rrule,
repeatFrom, TimeZone.getDefault());
DateValue nextDate;
if(repeatFrom.compareTo(today) < 0) {
iterator.advanceTo(today);
if(!iterator.hasNext())
return;
nextDate = iterator.next();
} else {
iterator.advanceTo(repeatFrom);
if(!iterator.hasNext())
return;
nextDate = iterator.next();
nextDate = iterator.next();
}
if(nextDate instanceof DateTimeValueImpl) {
DateTimeValueImpl newDateTime = (DateTimeValueImpl)nextDate;
newDueDate = task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME,
Date.UTC(newDateTime.year() - 1900, newDateTime.month() - 1,
newDateTime.day(), newDateTime.hour(),
newDateTime.minute(), newDateTime.second()));
} else {
newDueDate = task.createDueDate(Task.URGENCY_SPECIFIC_DAY,
new Date(nextDate.year() - 1900, nextDate.month() - 1,
nextDate.day()).getTime());
}
}
long hideUntil = task.getValue(Task.HIDE_UNTIL);
if(hideUntil > 0 && task.getValue(Task.DUE_DATE) > 0) {
hideUntil += newDueDate - task.getValue(Task.DUE_DATE);
}
task = taskService.clone(task);
task.setValue(Task.DUE_DATE, newDueDate);
task.setValue(Task.HIDE_UNTIL, hideUntil);
task.setValue(Task.COMPLETION_DATE, 0L);
taskService.save(task, false);
} catch (ParseException e) {
exceptionService.reportError("recurrence-rule: " + recurrence, e); //$NON-NLS-1$
}
}
}
}
| true | true | public void onReceive(Context context, Intent intent) {
long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1);
if(taskId == -1)
return;
DependencyInjectionService.getInstance().inject(this);
Task task = taskService.fetchById(taskId, Task.ID, Task.RECURRENCE,
Task.DUE_DATE, Task.FLAGS, Task.HIDE_UNTIL);
if(task == null)
return;
String recurrence = task.getValue(Task.RECURRENCE);
if(recurrence.length() > 0) {
DateValue repeatFrom;
Date repeatFromDate = new Date();
DateValue today = new DateValueImpl(repeatFromDate.getYear() + 1900,
repeatFromDate.getMonth() + 1, repeatFromDate.getDate());
if(task.hasDueDate() && !task.getFlag(Task.FLAGS, Task.FLAG_REPEAT_AFTER_COMPLETION)) {
repeatFromDate = new Date(task.getValue(Task.DUE_DATE));
if(task.hasDueTime()) {
repeatFrom = new DateTimeValueImpl(repeatFromDate.getYear() + 1900,
repeatFromDate.getMonth() + 1, repeatFromDate.getDate(),
repeatFromDate.getHours(), repeatFromDate.getMinutes(), repeatFromDate.getSeconds());
} else {
repeatFrom = new DateValueImpl(repeatFromDate.getYear() + 1900,
repeatFromDate.getMonth() + 1, repeatFromDate.getDate());
}
} else {
repeatFrom = today;
}
// invoke the recurrence iterator
try {
long newDueDate;
RRule rrule = new RRule(recurrence);
if(rrule.getFreq() == Frequency.HOURLY) {
newDueDate = task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME,
repeatFromDate.getTime() + DateUtilities.ONE_HOUR * rrule.getInterval());
} else {
RecurrenceIterator iterator = RecurrenceIteratorFactory.createRecurrenceIterator(rrule,
repeatFrom, TimeZone.getDefault());
DateValue nextDate;
if(repeatFrom.compareTo(today) < 0) {
iterator.advanceTo(today);
if(!iterator.hasNext())
return;
nextDate = iterator.next();
} else {
iterator.advanceTo(repeatFrom);
if(!iterator.hasNext())
return;
nextDate = iterator.next();
nextDate = iterator.next();
}
if(nextDate instanceof DateTimeValueImpl) {
DateTimeValueImpl newDateTime = (DateTimeValueImpl)nextDate;
newDueDate = task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME,
Date.UTC(newDateTime.year() - 1900, newDateTime.month() - 1,
newDateTime.day(), newDateTime.hour(),
newDateTime.minute(), newDateTime.second()));
} else {
newDueDate = task.createDueDate(Task.URGENCY_SPECIFIC_DAY,
new Date(nextDate.year() - 1900, nextDate.month() - 1,
nextDate.day()).getTime());
}
}
long hideUntil = task.getValue(Task.HIDE_UNTIL);
if(hideUntil > 0 && task.getValue(Task.DUE_DATE) > 0) {
hideUntil += newDueDate - task.getValue(Task.DUE_DATE);
}
task = taskService.clone(task);
task.setValue(Task.DUE_DATE, newDueDate);
task.setValue(Task.HIDE_UNTIL, hideUntil);
task.setValue(Task.COMPLETION_DATE, 0L);
taskService.save(task, false);
} catch (ParseException e) {
exceptionService.reportError("recurrence-rule: " + recurrence, e); //$NON-NLS-1$
}
}
}
| public void onReceive(Context context, Intent intent) {
long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1);
if(taskId == -1)
return;
DependencyInjectionService.getInstance().inject(this);
Task task = taskService.fetchById(taskId, Task.ID, Task.RECURRENCE,
Task.DUE_DATE, Task.FLAGS, Task.HIDE_UNTIL);
if(task == null)
return;
String recurrence = task.getValue(Task.RECURRENCE);
if(recurrence != null && recurrence.length() > 0) {
DateValue repeatFrom;
Date repeatFromDate = new Date();
DateValue today = new DateValueImpl(repeatFromDate.getYear() + 1900,
repeatFromDate.getMonth() + 1, repeatFromDate.getDate());
if(task.hasDueDate() && !task.getFlag(Task.FLAGS, Task.FLAG_REPEAT_AFTER_COMPLETION)) {
repeatFromDate = new Date(task.getValue(Task.DUE_DATE));
if(task.hasDueTime()) {
repeatFrom = new DateTimeValueImpl(repeatFromDate.getYear() + 1900,
repeatFromDate.getMonth() + 1, repeatFromDate.getDate(),
repeatFromDate.getHours(), repeatFromDate.getMinutes(), repeatFromDate.getSeconds());
} else {
repeatFrom = new DateValueImpl(repeatFromDate.getYear() + 1900,
repeatFromDate.getMonth() + 1, repeatFromDate.getDate());
}
} else {
repeatFrom = today;
}
// invoke the recurrence iterator
try {
long newDueDate;
RRule rrule = new RRule(recurrence);
if(rrule.getFreq() == Frequency.HOURLY) {
newDueDate = task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME,
repeatFromDate.getTime() + DateUtilities.ONE_HOUR * rrule.getInterval());
} else {
RecurrenceIterator iterator = RecurrenceIteratorFactory.createRecurrenceIterator(rrule,
repeatFrom, TimeZone.getDefault());
DateValue nextDate;
if(repeatFrom.compareTo(today) < 0) {
iterator.advanceTo(today);
if(!iterator.hasNext())
return;
nextDate = iterator.next();
} else {
iterator.advanceTo(repeatFrom);
if(!iterator.hasNext())
return;
nextDate = iterator.next();
nextDate = iterator.next();
}
if(nextDate instanceof DateTimeValueImpl) {
DateTimeValueImpl newDateTime = (DateTimeValueImpl)nextDate;
newDueDate = task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME,
Date.UTC(newDateTime.year() - 1900, newDateTime.month() - 1,
newDateTime.day(), newDateTime.hour(),
newDateTime.minute(), newDateTime.second()));
} else {
newDueDate = task.createDueDate(Task.URGENCY_SPECIFIC_DAY,
new Date(nextDate.year() - 1900, nextDate.month() - 1,
nextDate.day()).getTime());
}
}
long hideUntil = task.getValue(Task.HIDE_UNTIL);
if(hideUntil > 0 && task.getValue(Task.DUE_DATE) > 0) {
hideUntil += newDueDate - task.getValue(Task.DUE_DATE);
}
task = taskService.clone(task);
task.setValue(Task.DUE_DATE, newDueDate);
task.setValue(Task.HIDE_UNTIL, hideUntil);
task.setValue(Task.COMPLETION_DATE, 0L);
taskService.save(task, false);
} catch (ParseException e) {
exceptionService.reportError("recurrence-rule: " + recurrence, e); //$NON-NLS-1$
}
}
}
|
diff --git a/plugins/org.jboss.tools.forge.ui.ext/src/org/jboss/tools/forge/ui/ext/autocomplete/InputComponentProposalProvider.java b/plugins/org.jboss.tools.forge.ui.ext/src/org/jboss/tools/forge/ui/ext/autocomplete/InputComponentProposalProvider.java
index 72fbbaa3..6cbd3335 100644
--- a/plugins/org.jboss.tools.forge.ui.ext/src/org/jboss/tools/forge/ui/ext/autocomplete/InputComponentProposalProvider.java
+++ b/plugins/org.jboss.tools.forge.ui.ext/src/org/jboss/tools/forge/ui/ext/autocomplete/InputComponentProposalProvider.java
@@ -1,42 +1,44 @@
/*
* Copyright 2013 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.tools.forge.ui.ext.autocomplete;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.fieldassist.ContentProposal;
import org.eclipse.jface.fieldassist.IContentProposal;
import org.eclipse.jface.fieldassist.IContentProposalProvider;
import org.jboss.forge.addon.ui.input.InputComponent;
import org.jboss.forge.addon.ui.input.UICompleter;
import org.jboss.tools.forge.ui.ext.context.UIContextImpl;
public class InputComponentProposalProvider implements IContentProposalProvider {
private InputComponent<?, Object> component;
private UICompleter<Object> completer;
private UIContextImpl context;
public InputComponentProposalProvider(UIContextImpl context,
InputComponent<?, Object> component, UICompleter<Object> completer) {
this.context = context;
this.component = component;
this.completer = completer;
}
@Override
public IContentProposal[] getProposals(String contents, int position) {
List<IContentProposal> proposals = new ArrayList<IContentProposal>();
- for (String proposal : completer.getCompletionProposals(context,
+ for (Object proposal : completer.getCompletionProposals(context,
component, contents)) {
- proposals.add(new ContentProposal(proposal));
+ if (proposal != null) {
+ proposals.add(new ContentProposal(proposal.toString()));
+ }
}
return proposals.toArray(new IContentProposal[proposals.size()]);
}
}
| false | true | public IContentProposal[] getProposals(String contents, int position) {
List<IContentProposal> proposals = new ArrayList<IContentProposal>();
for (String proposal : completer.getCompletionProposals(context,
component, contents)) {
proposals.add(new ContentProposal(proposal));
}
return proposals.toArray(new IContentProposal[proposals.size()]);
}
| public IContentProposal[] getProposals(String contents, int position) {
List<IContentProposal> proposals = new ArrayList<IContentProposal>();
for (Object proposal : completer.getCompletionProposals(context,
component, contents)) {
if (proposal != null) {
proposals.add(new ContentProposal(proposal.toString()));
}
}
return proposals.toArray(new IContentProposal[proposals.size()]);
}
|
diff --git a/core/src/main/java/org/remus/manage/KeyWorker.java b/core/src/main/java/org/remus/manage/KeyWorker.java
index b8cf750..626f95d 100644
--- a/core/src/main/java/org/remus/manage/KeyWorker.java
+++ b/core/src/main/java/org/remus/manage/KeyWorker.java
@@ -1,267 +1,272 @@
package org.remus.manage;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.thrift.TException;
import org.remus.JSON;
import org.remus.core.AppletInstance;
import org.remus.core.PipelineSubmission;
import org.remus.plugin.PeerManager;
import org.remus.thrift.AppletRef;
import org.remus.thrift.JobState;
import org.remus.thrift.JobStatus;
import org.remus.thrift.NotImplemented;
import org.remus.thrift.RemusNet;
import org.remus.thrift.WorkDesc;
import org.remus.thrift.WorkMode;
public class KeyWorker extends InstanceWorker {
public KeyWorker(PeerManager peerManager, AppletInstance ai) {
super(peerManager, ai);
logger.debug("KEYWORKER:" + ai + " started");
state = WORKING;
}
public static final int MAX_REFRESH_TIME = 30 * 1000;
int state;
Set<RemoteJob> remoteJobs = new HashSet<RemoteJob>();
Map<String,Set<Integer>> activeWork = new HashMap<String, Set<Integer>>();
public boolean checkWork() throws NotImplemented, TException {
long [] workIDs;
boolean workChange = false;
int activeCount = 0;
//Check existing jobs
Map<RemoteJob,Boolean> removeSet = new HashMap<RemoteJob,Boolean>();
for (RemoteJob rj : remoteJobs) {
logger.debug("Checking " + rj.getPeerID() + " for " + rj.getJobID() + " " + ai);
try {
RemusNet.Iface worker = peerManager.getPeer(rj.getPeerID());
if (worker != null) {
JobStatus s = worker.jobStatus(rj.getJobID());
if (s.status == JobState.DONE) {
workChange = true;
for (long i = rj.getWorkStart(); i < rj.getWorkEnd(); i++) {
ai.finishWork(i, rj.getPeerID(), s.emitCount);
}
removeSet.put(rj, true);
logger.info("Worker Finished: " + rj.getJobID());
} else if (s.status == JobState.ERROR) {
workChange = true;
for (long i = rj.getWorkStart(); i < rj.getWorkEnd(); i++) {
ai.errorWork(i, s.errorMsg);
}
removeSet.put(rj, false);
logger.warn("JOB ERROR: " + ai + " job:" + rj.getJobID() + " " + s.errorMsg);
} else if (s.status == JobState.UNKNOWN) {
logger.warn("Worker lost job: " + rj.getJobID());
} else {
activeCount += 1;
}
peerManager.returnPeer(worker);
}
} catch (TException e) {
logger.warn("Worker Connection Failed: " + rj.getPeerID());
removeSet.put(rj, false);
peerManager.peerFailure(rj.getPeerID());
} catch (NotImplemented e) {
logger.warn("Worker Call Error: " + rj.getPeerID());
removeSet.put(rj, false);
}
}
for (RemoteJob rj : removeSet.keySet()) {
returnPeer(rj.getPeerID());
removeRemoteJob(ai, rj, removeSet.get(rj));
}
workIDs = getAppletWorkCache(ai);
if (workIDs != null) {
int curPos = 0;
while (curPos < workIDs.length) {
if (workIDs[curPos] == -1) {
curPos++;
} else {
int last = curPos;
do {
curPos++;
- } while (curPos < workIDs.length && workIDs[curPos] - workIDs[last] == curPos - last);
- workAssign(ai, borrowPeer(), workIDs[last], workIDs[curPos - 1] + 1);
- for (int i = last; i < curPos; i++) {
- workIDs[i] = -1;
+ } while (curPos < workIDs.length && workIDs[curPos] - workIDs[last] == curPos - last);
+ String peerID = borrowPeer();
+ if (peerID != null) {
+ workAssign(ai, peerID, workIDs[last], workIDs[curPos - 1] + 1);
+ for (int i = last; i < curPos; i++) {
+ workIDs[i] = -1;
+ }
+ } else {
+ logger.debug("Avalible peer not found");
}
workChange = true;
}
}
}
return workChange;
}
private void workAssign(AppletInstance ai, String peerID, long workStart, long workEnd) {
try {
PipelineSubmission instanceInfo = ai.getInstanceInfo();
if (instanceInfo == null) {
return;
}
WorkDesc wdesc = new WorkDesc();
wdesc.setWorkStack(new AppletRef());
wdesc.workStack.setPipeline(ai.getPipeline().getID());
wdesc.workStack.setInstance(ai.getInstance().toString());
wdesc.workStack.setApplet(ai.getApplet().getID());
wdesc.setWorkStart(workStart);
wdesc.setWorkEnd(workEnd);
wdesc.setLang(ai.getApplet().getType());
logger.info("Assigning " + ai + ":" + workStart + "-" + workEnd + " to " + peerID + " " + wdesc.workStack);
wdesc.setInfoJSON(JSON.dumps(instanceInfo));
RemusNet.Iface worker = peerManager.getPeer(peerID);
if (worker == null) {
return;
}
int mode = ai.getApplet().getMode();
if (mode == WorkMode.AGENT.getValue()) {
logger.info("Agent Operation");
wdesc.setMode(WorkMode.MAP);
String jobID = worker.jobRequest(peerManager.getManager(), peerManager.getAttachStore(), wdesc);
addRemoteJob(ai, new RemoteJob(peerID, jobID, workStart, workEnd));
} else {
wdesc.setMode(WorkMode.findByValue(mode));
String jobID = worker.jobRequest(peerManager.getDataServer(), peerManager.getAttachStore(), wdesc);
addRemoteJob(ai, new RemoteJob(peerID, jobID, workStart, workEnd));
}
peerManager.returnPeer(worker);
} catch (TException e) {
e.printStackTrace();
} catch (NotImplemented e) {
e.printStackTrace();
}
}
int assignRate = 1;
private long [] getAppletWorkCache(AppletInstance ai) throws NotImplemented, TException {
Set<String> peers = peerManager.getWorkers();
long [] workIDs = null;
synchronized (workIDCache) {
if (workIDCache.containsKey(ai) && workIDCache.get(ai) != null && workIDCache.get(ai).length != 0) {
workIDs = workIDCache.get(ai);
Arrays.sort(workIDs);
} else {
workIDs = ai.getReadyJobs(assignRate * peers.size());
workIDCache.put(ai, workIDs);
}
}
for (RemoteJob rj :remoteJobs) {
for (int i = 0; i < workIDs.length; i++) {
if (workIDs[i] >= rj.getWorkStart() && workIDs[i] < rj.getWorkEnd()) {
workIDs[i] = -1;
}
}
}
boolean valid = false;
for (int i = 0; i < workIDs.length; i++) {
if (workIDs[i] != -1) {
valid = true;
}
}
if (valid) {
Arrays.sort(workIDs);
return workIDs;
}
if (ai.isComplete()) {
state = DONE;
}
if (ai.isInError()) {
state = ERROR;
}
workIDCache.put(ai, new long [0]);
return null;
}
private Map<AppletInstance,long []> workIDCache = new HashMap<AppletInstance, long[]>();
private void flushAppletWorkCache() {
synchronized (workIDCache) {
List<AppletInstance> removeList = new LinkedList<AppletInstance>();
for (AppletInstance ai : workIDCache.keySet()) {
if (workIDCache.get(ai) == null || workIDCache.get(ai).length == 0) {
removeList.add(ai);
}
}
for (AppletInstance ai : removeList) {
workIDCache.remove(ai);
}
}
}
private void addRemoteJob(AppletInstance ai, RemoteJob rj) {
remoteJobs.add(rj);
}
private void removeRemoteJob(AppletInstance ai, RemoteJob rj, boolean adjustAssignRate) {
if (adjustAssignRate) {
int newAssignRate = assignRate;
long runTime = (new Date()).getTime() - rj.getStartTime();
if (runTime > MAX_REFRESH_TIME) {
newAssignRate /= 2;
}
newAssignRate++;
logger.info("ASSIGN RATE: " + ai + " " + newAssignRate);
assignRate = newAssignRate;
}
try {
RemusNet.Iface worker = peerManager.getPeer(rj.getPeerID());
worker.jobCancel(rj.getJobID());
peerManager.returnPeer(worker);
} catch (NotImplemented e) {
e.printStackTrace();
} catch (TException e) {
peerManager.peerFailure(rj.getPeerID());
e.printStackTrace();
}
remoteJobs.remove(rj);
}
@Override
public boolean isDone() {
if ( state == DONE ) {
return true;
}
return false;
}
@Override
public void removeJob() {
// TODO Auto-generated method stub
}
}
| true | true | public boolean checkWork() throws NotImplemented, TException {
long [] workIDs;
boolean workChange = false;
int activeCount = 0;
//Check existing jobs
Map<RemoteJob,Boolean> removeSet = new HashMap<RemoteJob,Boolean>();
for (RemoteJob rj : remoteJobs) {
logger.debug("Checking " + rj.getPeerID() + " for " + rj.getJobID() + " " + ai);
try {
RemusNet.Iface worker = peerManager.getPeer(rj.getPeerID());
if (worker != null) {
JobStatus s = worker.jobStatus(rj.getJobID());
if (s.status == JobState.DONE) {
workChange = true;
for (long i = rj.getWorkStart(); i < rj.getWorkEnd(); i++) {
ai.finishWork(i, rj.getPeerID(), s.emitCount);
}
removeSet.put(rj, true);
logger.info("Worker Finished: " + rj.getJobID());
} else if (s.status == JobState.ERROR) {
workChange = true;
for (long i = rj.getWorkStart(); i < rj.getWorkEnd(); i++) {
ai.errorWork(i, s.errorMsg);
}
removeSet.put(rj, false);
logger.warn("JOB ERROR: " + ai + " job:" + rj.getJobID() + " " + s.errorMsg);
} else if (s.status == JobState.UNKNOWN) {
logger.warn("Worker lost job: " + rj.getJobID());
} else {
activeCount += 1;
}
peerManager.returnPeer(worker);
}
} catch (TException e) {
logger.warn("Worker Connection Failed: " + rj.getPeerID());
removeSet.put(rj, false);
peerManager.peerFailure(rj.getPeerID());
} catch (NotImplemented e) {
logger.warn("Worker Call Error: " + rj.getPeerID());
removeSet.put(rj, false);
}
}
for (RemoteJob rj : removeSet.keySet()) {
returnPeer(rj.getPeerID());
removeRemoteJob(ai, rj, removeSet.get(rj));
}
workIDs = getAppletWorkCache(ai);
if (workIDs != null) {
int curPos = 0;
while (curPos < workIDs.length) {
if (workIDs[curPos] == -1) {
curPos++;
} else {
int last = curPos;
do {
curPos++;
} while (curPos < workIDs.length && workIDs[curPos] - workIDs[last] == curPos - last);
workAssign(ai, borrowPeer(), workIDs[last], workIDs[curPos - 1] + 1);
for (int i = last; i < curPos; i++) {
workIDs[i] = -1;
}
workChange = true;
}
}
}
return workChange;
}
| public boolean checkWork() throws NotImplemented, TException {
long [] workIDs;
boolean workChange = false;
int activeCount = 0;
//Check existing jobs
Map<RemoteJob,Boolean> removeSet = new HashMap<RemoteJob,Boolean>();
for (RemoteJob rj : remoteJobs) {
logger.debug("Checking " + rj.getPeerID() + " for " + rj.getJobID() + " " + ai);
try {
RemusNet.Iface worker = peerManager.getPeer(rj.getPeerID());
if (worker != null) {
JobStatus s = worker.jobStatus(rj.getJobID());
if (s.status == JobState.DONE) {
workChange = true;
for (long i = rj.getWorkStart(); i < rj.getWorkEnd(); i++) {
ai.finishWork(i, rj.getPeerID(), s.emitCount);
}
removeSet.put(rj, true);
logger.info("Worker Finished: " + rj.getJobID());
} else if (s.status == JobState.ERROR) {
workChange = true;
for (long i = rj.getWorkStart(); i < rj.getWorkEnd(); i++) {
ai.errorWork(i, s.errorMsg);
}
removeSet.put(rj, false);
logger.warn("JOB ERROR: " + ai + " job:" + rj.getJobID() + " " + s.errorMsg);
} else if (s.status == JobState.UNKNOWN) {
logger.warn("Worker lost job: " + rj.getJobID());
} else {
activeCount += 1;
}
peerManager.returnPeer(worker);
}
} catch (TException e) {
logger.warn("Worker Connection Failed: " + rj.getPeerID());
removeSet.put(rj, false);
peerManager.peerFailure(rj.getPeerID());
} catch (NotImplemented e) {
logger.warn("Worker Call Error: " + rj.getPeerID());
removeSet.put(rj, false);
}
}
for (RemoteJob rj : removeSet.keySet()) {
returnPeer(rj.getPeerID());
removeRemoteJob(ai, rj, removeSet.get(rj));
}
workIDs = getAppletWorkCache(ai);
if (workIDs != null) {
int curPos = 0;
while (curPos < workIDs.length) {
if (workIDs[curPos] == -1) {
curPos++;
} else {
int last = curPos;
do {
curPos++;
} while (curPos < workIDs.length && workIDs[curPos] - workIDs[last] == curPos - last);
String peerID = borrowPeer();
if (peerID != null) {
workAssign(ai, peerID, workIDs[last], workIDs[curPos - 1] + 1);
for (int i = last; i < curPos; i++) {
workIDs[i] = -1;
}
} else {
logger.debug("Avalible peer not found");
}
workChange = true;
}
}
}
return workChange;
}
|
diff --git a/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletRequestImpl.java b/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletRequestImpl.java
index 52c3ee1d3..2b548d9d1 100644
--- a/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletRequestImpl.java
+++ b/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletRequestImpl.java
@@ -1,983 +1,986 @@
/*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.mobicents.servlet.sip.message;
import gov.nist.javax.sip.header.ims.PathHeader;
import java.io.BufferedReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import java.util.Vector;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.sip.Address;
import javax.servlet.sip.AuthInfo;
import javax.servlet.sip.B2buaHelper;
import javax.servlet.sip.Proxy;
import javax.servlet.sip.SipApplicationRouterInfo;
import javax.servlet.sip.SipApplicationRoutingDirective;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
import javax.servlet.sip.SipSession;
import javax.servlet.sip.SipURI;
import javax.servlet.sip.TooManyHopsException;
import javax.servlet.sip.URI;
import javax.servlet.sip.SipSession.State;
import javax.sip.ClientTransaction;
import javax.sip.Dialog;
import javax.sip.DialogState;
import javax.sip.ServerTransaction;
import javax.sip.SipException;
import javax.sip.SipProvider;
import javax.sip.Transaction;
import javax.sip.header.AuthorizationHeader;
import javax.sip.header.ContactHeader;
import javax.sip.header.FromHeader;
import javax.sip.header.MaxForwardsHeader;
import javax.sip.header.ProxyAuthenticateHeader;
import javax.sip.header.RecordRouteHeader;
import javax.sip.header.RouteHeader;
import javax.sip.header.ToHeader;
import javax.sip.header.ViaHeader;
import javax.sip.header.WWWAuthenticateHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mobicents.servlet.sip.JainSipUtils;
import org.mobicents.servlet.sip.SipFactories;
import org.mobicents.servlet.sip.address.AddressImpl;
import org.mobicents.servlet.sip.address.SipURIImpl;
import org.mobicents.servlet.sip.address.TelURLImpl;
import org.mobicents.servlet.sip.address.URIImpl;
import org.mobicents.servlet.sip.core.RoutingState;
import org.mobicents.servlet.sip.core.SipApplicationDispatcherImpl;
import org.mobicents.servlet.sip.proxy.ProxyImpl;
import org.mobicents.servlet.sip.security.AuthInfoEntry;
import org.mobicents.servlet.sip.security.AuthInfoImpl;
import org.mobicents.servlet.sip.security.authentication.DigestAuthenticator;
public class SipServletRequestImpl extends SipServletMessageImpl implements
SipServletRequest, Cloneable {
private static Log logger = LogFactory.getLog(SipServletRequestImpl.class);
/* Linked request (for b2bua) */
private SipServletRequestImpl linkedRequest;
private boolean createDialog;
/*
* Popped route header - when we are the UAS we pop and keep the route
* header
*/
private RouteHeader popedRouteHeader;
/* Cache the application routing directive in the record route header */
private SipApplicationRoutingDirective routingDirective = SipApplicationRoutingDirective.NEW;
private RoutingState routingState;
private B2buaHelper b2buahelper;
private SipServletResponse lastFinalResponse;
public SipServletRequestImpl(Request request, SipFactoryImpl sipFactoryImpl,
SipSession sipSession, Transaction transaction, Dialog dialog,
boolean createDialog) {
super(request, sipFactoryImpl, transaction, sipSession, dialog);
this.createDialog = createDialog;
routingState = RoutingState.INITIAL;
}
@Override
public boolean isSystemHeader(String headerName) {
String hName = getFullHeaderName(headerName);
/*
* Contact is a system header field in messages other than REGISTER
* requests and responses, 3xx and 485 responses, and 200/OPTIONS
* responses so it is not contained in system headers and as such
* as a special treatment
*/
boolean isSystemHeader = systemHeaders.contains(hName);
if (isSystemHeader)
return isSystemHeader;
boolean isContactSystem = false;
Request request = (Request) this.message;
String method = request.getMethod();
if (method.equals(Request.REGISTER)) {
isContactSystem = false;
} else {
isContactSystem = true;
}
if (isContactSystem && hName.equals(ContactHeader.NAME)) {
isSystemHeader = true;
} else {
isSystemHeader = false;
}
return isSystemHeader;
}
public SipServletRequest createCancel() {
if (!((Request) message).getMethod().equals(Request.INVITE)) {
throw new IllegalStateException(
"Cannot create CANCEL for non inivte");
}
if (super.getTransaction() == null
|| super.getTransaction() instanceof ServerTransaction)
throw new IllegalStateException("No client transaction found!");
try {
Request request = (Request) super.message;
String transport = JainSipUtils.findTransport(request);
SipProvider sipProvider = sipFactoryImpl.getSipNetworkInterfaceManager().findMatchingListeningPoint(transport, false).getSipProvider();
Request cancelRequest = ((ClientTransaction) getTransaction())
.createCancel();
ClientTransaction clientTransaction = sipProvider
.getNewClientTransaction(cancelRequest);
SipServletRequest newRequest = new SipServletRequestImpl(
cancelRequest, sipFactoryImpl, super.session,
clientTransaction, getTransaction().getDialog(), false);
return newRequest;
} catch (SipException ex) {
throw new IllegalStateException("Could not create cancel", ex);
}
}
/*
* (non-Javadoc)
*
* @see javax.servlet.sip.SipServletRequest#createResponse(int)
*/
public SipServletResponse createResponse(int statusCode) {
return createResponse(statusCode, null);
}
public SipServletResponse createResponse(int statusCode, String reasonPhrase) {
if (super.getTransaction() == null
|| super.getTransaction() instanceof ClientTransaction) {
throw new IllegalStateException(
"Cannot create a response - not a server transaction");
}
try {
Request request = this.getTransaction().getRequest();
Response response = SipFactories.messageFactory.createResponse(
statusCode, request);
if(reasonPhrase!=null) {
response.setReasonPhrase(reasonPhrase);
}
//add a To tag for all responses except Trying
if(statusCode > Response.TRYING && statusCode <= Response.SESSION_NOT_ACCEPTABLE) {
ToHeader toHeader = (ToHeader) response
.getHeader(ToHeader.NAME);
// If we already have a to tag, dont create new
if (toHeader.getTag() == null) {
String localTag = null;
if(getTransaction().getDialog() != null) {
localTag = getTransaction().getDialog().getLocalTag();
// if a dialog has already been created
// reuse local tag
if(localTag != null && localTag.length() > 0) {
toHeader.setTag(localTag);
} else {
toHeader.setTag(Integer.toString((int) (Math.random()*10000000)));
}
} else {
toHeader.setTag(Integer.toString((int) (Math.random()*10000000)));
}
if (statusCode == Response.OK ) {
//Following restrictions in JSR 289 Section 4.1.3 Contact Header Field
if(!Request.REGISTER.equals(request.getMethod()) && !Request.OPTIONS.equals(request.getMethod())) {
// Add the contact header for the dialog.
String transport = ((ViaHeader) request
.getHeader(ViaHeader.NAME)).getTransport();
ContactHeader contactHeader = JainSipUtils
.createContactHeader(super.sipFactoryImpl.getSipNetworkInterfaceManager(), transport, null);
response.setHeader(contactHeader);
}
}
}
}
//Application Routing : Adding the recorded route headers as route headers, should it be Via Headers ?
ListIterator<RecordRouteHeader> recordRouteHeaders = request.getHeaders(RecordRouteHeader.NAME);
while (recordRouteHeaders.hasNext()) {
RecordRouteHeader recordRouteHeader = (RecordRouteHeader) recordRouteHeaders
.next();
RouteHeader routeHeader = SipFactories.headerFactory.createRouteHeader(recordRouteHeader.getAddress());
response.addHeader(routeHeader);
}
return new SipServletResponseImpl(response, super.sipFactoryImpl,
(ServerTransaction) getTransaction(), session, getDialog(), this);
} catch (ParseException ex) {
throw new IllegalArgumentException("Bad status code" + statusCode,
ex);
}
}
public B2buaHelper getB2buaHelper() {
if (this.transactionApplicationData.getProxy() != null)
throw new IllegalStateException("Proxy already present");
if (this.b2buahelper != null)
return this.b2buahelper;
try {
if (this.getTransaction() != null
&& this.getTransaction().getDialog() == null) {
Request request = (Request) super.message;
String transport = JainSipUtils.findTransport(request);
SipProvider sipProvider = sipFactoryImpl.getSipNetworkInterfaceManager().findMatchingListeningPoint(
transport, false).getSipProvider();
Dialog dialog = sipProvider.getNewDialog(this
.getTransaction());
this.session.setSessionCreatingDialog(dialog);
dialog.setApplicationData( this.transactionApplicationData);
}
this.b2buahelper = new B2buaHelperImpl(this);
this.createDialog = true; // flag that we want to create a dialog for outgoing request.
return this.b2buahelper;
} catch (SipException ex) {
throw new IllegalStateException("Cannot get B2BUAHelper");
}
}
public ServletInputStream getInputStream() throws IOException {
return null;
}
public int getMaxForwards() {
return ((MaxForwardsHeader) ((Request) message)
.getHeader(MaxForwardsHeader.NAME)).getMaxForwards();
}
/*
* (non-Javadoc)
*
* @see javax.servlet.sip.SipServletRequest#getPoppedRoute()
*/
public Address getPoppedRoute() {
AddressImpl addressImpl = null;
if (this.popedRouteHeader != null) {
addressImpl = new AddressImpl(this.popedRouteHeader.getAddress());
}
return addressImpl;
}
/**
* Set the popped route
*
* @param routeHeader
* the popped route header to set
*/
public void setPoppedRoute(RouteHeader routeHeader) {
this.popedRouteHeader = routeHeader;
}
/**
*
* @TODO -- deal with maxforwards header.
*/
public Proxy getProxy() throws TooManyHopsException {
if ( this.b2buahelper != null ) throw new IllegalStateException("Cannot proxy request");
return getProxy(true);
}
public Proxy getProxy(boolean create) throws TooManyHopsException {
if ( this.b2buahelper != null ) throw new IllegalStateException("Cannot proxy request");
if (create && transactionApplicationData.getProxy() == null) {
ProxyImpl proxy = new ProxyImpl(this, super.sipFactoryImpl);
this.transactionApplicationData.setProxy(proxy);
getSipSession().setSupervisedMode(proxy.getSupervised());
}
return this.transactionApplicationData.getProxy();
}
/*
* (non-Javadoc)
*
* @see javax.servlet.sip.SipServletRequest#getReader()
*/
public BufferedReader getReader() throws IOException {
return null;
}
/*
* (non-Javadoc)
*
* @see javax.servlet.sip.SipServletRequest#getRequestURI()
*/
public URI getRequestURI() {
Request request = (Request) super.message;
if (request.getRequestURI() instanceof javax.sip.address.SipURI)
return new SipURIImpl((javax.sip.address.SipURI) request
.getRequestURI());
else if (request.getRequestURI() instanceof javax.sip.address.TelURL)
return new TelURLImpl((javax.sip.address.TelURL) request
.getRequestURI());
else
throw new UnsupportedOperationException("Unsupported scheme");
}
/*
* (non-Javadoc)
*
* @see javax.servlet.sip.SipServletRequest#isInitial()
*/
public boolean isInitial() {
/** When initiating requests from a servlet (c2d for example)
* the following requests would be recognized as initial since
* there is no previous information in them and the session is
* not available yet. This may be fixed is a cleaner way if the
* decision initial/noninitial is made after the session mapping.
*
* TODO: FIXME: MESSAGE requests can be both initial and noninitial
* so they still may be misclassified.
*/
if(SipApplicationDispatcherImpl.nonInitialSipRequestMethods.contains(this.getMethod())) {
return false;
}
return this.routingState.equals(RoutingState.INITIAL) ||
this.routingState.equals(RoutingState.PROXIED) ||
this.routingState.equals(RoutingState.RELAYED);
}
public void pushPath(Address uri) {
if (logger.isDebugEnabled())
logger.debug("Pushing path into message of value [" + uri + "]");
try {
javax.sip.header.Header p = SipFactories.headerFactory
.createHeader(PathHeader.NAME, uri.toString());
this.message.addFirst(p);
} catch (Exception e) {
logger.error("Error while pushing path [" + uri + "]");
throw new IllegalArgumentException("Error pushing path ", e);
}
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletRequest#pushRoute(javax.servlet.sip.Address)
*/
public void pushRoute(Address address) {
javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI) ((AddressImpl) address)
.getAddress().getURI();
pushRoute(sipUri);
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletRequest#pushRoute(javax.servlet.sip.SipURI)
*/
public void pushRoute(SipURI uri) {
javax.sip.address.SipURI sipUri = ((SipURIImpl) uri).getSipURI();
sipUri.setLrParam();
pushRoute(sipUri);
}
/**
* Pushes a route header on initial request based on the jain sip sipUri given on parameter
* @param sipUri the jain sip sip uri to use to construct the route header to push on the request
*/
private void pushRoute(javax.sip.address.SipURI sipUri) {
if(isInitial()) {
if (logger.isDebugEnabled())
logger.debug("Pushing route into message of value [" + sipUri
+ "]");
sipUri.setLrParam();
try {
javax.sip.header.Header p = SipFactories.headerFactory
.createRouteHeader(SipFactories.addressFactory
.createAddress(sipUri));
this.message.addFirst(p);
} catch (SipException e) {
logger.error("Error while pushing route [" + sipUri + "]");
throw new IllegalArgumentException("Error pushing route ", e);
}
} else {
//as per JSR 289 Section 11.1.3 Pushing Route Header Field Values
// pushRoute can only be done on the initial requests.
// Subsequent requests within a dialog follow the route set.
// Any attempt to do a pushRoute on a subsequent request in a dialog
// MUST throw and IllegalStateException.
throw new IllegalStateException("Cannot push route on subsequent requests, only intial ones");
}
}
public void setMaxForwards(int n) {
MaxForwardsHeader mfh = (MaxForwardsHeader) this.message
.getHeader(MaxForwardsHeader.NAME);
try {
if (mfh != null) {
mfh.setMaxForwards(n);
}
} catch (Exception ex) {
String s = "Error while setting max forwards";
logger.error(s, ex);
throw new IllegalArgumentException(s, ex);
}
}
public void setRequestURI(URI uri) {
Request request = (Request) message;
URIImpl uriImpl = (URIImpl) uri;
javax.sip.address.URI wrappedUri = uriImpl.getURI();
request.setRequestURI(wrappedUri);
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletRequest#setRoutingDirective(javax.servlet.sip.SipApplicationRoutingDirective, javax.servlet.sip.SipServletRequest)
*/
public void setRoutingDirective(SipApplicationRoutingDirective directive,
SipServletRequest origRequest) throws IllegalStateException {
SipServletRequestImpl origRequestImpl = (SipServletRequestImpl) origRequest;
//@jean.deruelle Commenting this out, why origRequestImpl.isCommitted() is needed ?
// if ((directive == SipApplicationRoutingDirective.REVERSE || directive == SipApplicationRoutingDirective.CONTINUE)
// && (!origRequestImpl.isInitial() || origRequestImpl.isCommitted())) {
// If directive is CONTINUE or REVERSE, the parameter origRequest must be an
//initial request dispatched by the container to this application,
//i.e. origRequest.isInitial() must be true
if ((directive == SipApplicationRoutingDirective.REVERSE ||
directive == SipApplicationRoutingDirective.CONTINUE)){
if(origRequestImpl == null ||
!origRequestImpl.isInitial()) {
if(logger.isDebugEnabled()) {
logger.debug("directive to set : " + directive);
logger.debug("Original Request Routing State : " + origRequestImpl.getRoutingState());
}
throw new IllegalStateException(
"Bad state -- cannot set routing directive");
} else {
//set AR State Info from previous request
session.setStateInfo(origRequestImpl.getSipSession().getStateInfo());
//needed for application composition
currentApplicationName = origRequestImpl.getCurrentApplicationName();
//linking the requests
//FIXME one request can be linked to many more as for B2BUA
origRequestImpl.setLinkedRequest(this);
setLinkedRequest(origRequestImpl);
}
} else {
//This request must be a request created in a new SipSession
//or from an initial request, and must not have been sent.
//If any one of these preconditions are not met, the method throws an IllegalStateException.
if(!State.INITIAL.equals(session.getState()) && session.getOngoingTransactions().size() > 0) {
if(logger.isDebugEnabled()) {
logger.debug("session state : " + session.getState());
logger.debug("numbers of ongoing transactions : " + session.getOngoingTransactions().size());
}
throw new IllegalStateException(
"Bad state -- cannot set routing directive");
}
}
routingDirective = directive;
linkedRequest = origRequestImpl;
//@jean.deruelle Commenting this out, is this really needed ?
// RecordRouteHeader rrh = (RecordRouteHeader) request
// .getHeader(RecordRouteHeader.NAME);
// javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI) rrh
// .getAddress().getURI();
//
// try {
// if (directive == SipApplicationRoutingDirective.NEW) {
// sipUri.setParameter("rd", "NEW");
// } else if (directive == SipApplicationRoutingDirective.REVERSE) {
// sipUri.setParameter("rd", "REVERSE");
// } else if (directive == SipApplicationRoutingDirective.CONTINUE) {
// sipUri.setParameter("rd", "CONTINUE");
// }
//
// } catch (Exception ex) {
// String s = "error while setting routing directive";
// logger.error(s, ex);
// throw new IllegalArgumentException(s, ex);
// }
}
/*
* (non-Javadoc)
*
* @see javax.servlet.ServletRequest#getLocalName()
*/
public String getLocalName() {
// TODO Auto-generated method stub
return null;
}
public Locale getLocale() {
// TODO Auto-generated method stub
return null;
}
public Enumeration getLocales() {
// TODO Auto-generated method stub
return null;
}
/*
* (non-Javadoc)
*
* @see javax.servlet.ServletRequest#getParameter(java.lang.String)
*/
public String getParameter(String name) {
RecordRouteHeader rrh = (RecordRouteHeader) message
.getHeader(RecordRouteHeader.NAME);
return rrh.getParameter(name);
}
/*
* (non-Javadoc)
* @see javax.servlet.ServletRequest#getParameterMap()
*/
public Map<String, String> getParameterMap() {
RecordRouteHeader rrh = (RecordRouteHeader) message
.getHeader(RecordRouteHeader.NAME);
HashMap<String, String> retval = new HashMap<String, String>();
Iterator<String> parameterNamesIt = rrh.getParameterNames();
while (parameterNamesIt.hasNext()) {
String parameterName = (String) parameterNamesIt.next();
retval.put(parameterName, rrh.getParameter(parameterName));
}
return retval;
}
/*
* (non-Javadoc)
* @see javax.servlet.ServletRequest#getParameterNames()
*/
public Enumeration<String> getParameterNames() {
RecordRouteHeader rrh = (RecordRouteHeader) message
.getHeader(RecordRouteHeader.NAME);
Vector<String> retval = new Vector<String>();
Iterator<String> parameterNamesIt = rrh.getParameterNames();
while (parameterNamesIt.hasNext()) {
String parameterName = (String) parameterNamesIt.next();
retval.add(parameterName);
}
return retval.elements();
}
/*
* (non-Javadoc)
*
* @see javax.servlet.ServletRequest#getParameterValues(java.lang.String)
*/
public String[] getParameterValues(String arg0) {
// TODO Auto-generated method stub
return null;
}
public String getRealPath(String arg0) {
// TODO Auto-generated method stub
return null;
}
public String getRemoteHost() {
// TODO Auto-generated method stub
return null;
}
public RequestDispatcher getRequestDispatcher(String arg0) {
// TODO Auto-generated method stub
return null;
}
public String getScheme() {
// TODO Auto-generated method stub
return null;
}
public String getServerName() {
// TODO Auto-generated method stub
return null;
}
public int getServerPort() {
// TODO Auto-generated method stub
return 0;
}
public void removeAttribute(String arg0) {
// TODO Auto-generated method stub
}
/**
* @return the routingDirective
*/
public SipApplicationRoutingDirective getRoutingDirective() {
return routingDirective;
}
/*
* (non-Javadoc)
*
* @see org.mobicents.servlet.sip.message.SipServletMessageImpl#send()
*/
@Override
public void send() {
try {
Request request = (Request) super.message;
String transport = JainSipUtils.findTransport(request);
if(Request.ACK.equals(request.getMethod())) {
super.session.getSessionCreatingDialog().sendAck(request);
return;
}
//Added for initial requests only (that are not REGISTER) not for subsequent requests
if(isInitial() && !Request.REGISTER.equalsIgnoreCase(request.getMethod())) {
- if(getSipSession().getProxyBranch() == null) // If the app is proxying it already does that
+ // Additional checks for https://sip-servlets.dev.java.net/issues/show_bug.cgi?id=29
+ if(getSipSession().getProxyBranch() == null ||
+ (transactionApplicationData.getProxy() != null &&
+ transactionApplicationData.getProxy().getRecordRoute())) // If the app is proxying it already does that
{
//Add a record route header for app composition
addAppCompositionRRHeader();
}
SipApplicationRouterInfo routerInfo = sipFactoryImpl.getNextInterestedApplication(this);
if(routerInfo.getNextApplicationName() != null) {
if(logger.isDebugEnabled()) {
logger.debug("routing back to the container " +
"since the following app is interested " + routerInfo.getNextApplicationName());
}
//add a route header to direct the request back to the container
//to check if there is any other apps interested in it
addInfoForRoutingBackToContainer(session.getKey().getApplicationName());
} else {
if(logger.isDebugEnabled()) {
logger.debug("routing outside the container " +
"since no more apps are is interested.");
}
}
}
if (super.getTransaction() == null) {
SipProvider sipProvider = sipFactoryImpl.getSipNetworkInterfaceManager().findMatchingListeningPoint(
transport, false).getSipProvider();
ContactHeader contactHeader = (ContactHeader)request.getHeader(ContactHeader.NAME);
if(contactHeader == null) {
FromHeader fromHeader = (FromHeader) request.getHeader(FromHeader.NAME);
//TODO what about other schemes ?
String fromName = ((javax.sip.address.SipURI)fromHeader.getAddress().getURI()).getUser();
// Create the contact name address.
contactHeader =
JainSipUtils.createContactHeader(sipFactoryImpl.getSipNetworkInterfaceManager(), transport, fromName);
request.addHeader(contactHeader);
}
if(logger.isDebugEnabled()) {
logger.debug("Getting new Client Tx for request " + request);
}
ClientTransaction ctx = sipProvider
.getNewClientTransaction(request);
super.session.setSessionCreatingTransaction(ctx);
Dialog dialog = ctx.getDialog();
if (dialog == null && this.createDialog) {
dialog = sipProvider.getNewDialog(ctx);
super.session.setSessionCreatingDialog(dialog);
if(logger.isDebugEnabled()) {
logger.debug("new Dialog for request " + request + ", ref = " + dialog);
}
}
//Keeping the transactions mapping in application data for CANCEL handling
if(linkedRequest != null) {
//keeping the client transaction in the server transaction's application data
((TransactionApplicationData)linkedRequest.getTransaction().getApplicationData()).setTransaction(ctx);
if(linkedRequest.getDialog() != null && linkedRequest.getDialog().getApplicationData() != null) {
((TransactionApplicationData)linkedRequest.getDialog().getApplicationData()).setTransaction(ctx);
}
//keeping the server transaction in the client transaction's application data
this.transactionApplicationData.setTransaction(linkedRequest.getTransaction());
if(dialog!= null && dialog.getApplicationData() != null) {
((TransactionApplicationData)dialog.getApplicationData()).setTransaction(linkedRequest.getTransaction());
}
}
// Make the dialog point here so that when the dialog event
// comes in we can find the session quickly.
if (dialog != null) {
dialog.setApplicationData(this.transactionApplicationData);
}
// SIP Request is ALWAYS pointed to by the client tx.
// Notice that the tx appplication data is cached in the request
// copied over to the tx so it can be quickly accessed when response
// arrives.
ctx.setApplicationData(this.transactionApplicationData);
super.setTransaction(ctx);
}
//tells the application dispatcher to stop routing the linked request
// (in this case it would be the original request) since it has been relayed
if(linkedRequest != null &&
!SipApplicationRoutingDirective.NEW.equals(routingDirective)) {
if(!RoutingState.PROXIED.equals(linkedRequest.getRoutingState())) {
linkedRequest.setRoutingState(RoutingState.RELAYED);
}
}
// Update Session state
super.session.updateStateOnSubsequentRequest(this, false);
// If dialog does not exist or has no state.
if (getDialog() == null || getDialog().getState() == null
|| getDialog().getState() == DialogState.EARLY) {
logger.info("Sending the request " + request);
((ClientTransaction) super.getTransaction()).sendRequest();
} else {
// This is a subsequent (an in-dialog) request.
// we don't redirect it to the container for now
logger.info("Sending the in dialog request " + request);
getDialog().sendRequest((ClientTransaction) getTransaction());
}
super.session.addOngoingTransaction(getTransaction());
//updating the last accessed times
getSipSession().setLastAccessedTime(System.currentTimeMillis());
getSipSession().getSipApplicationSession().setLastAccessedTime(System.currentTimeMillis());
} catch (Exception ex) {
throw new IllegalStateException("Error sending request",ex);
}
}
/**
* Add a route header to route back to the container
* @param applicationName the application name that was chosen by the AR to route the request
* @throws ParseException
*/
public void addInfoForRoutingBackToContainer(String applicationName) throws ParseException {
Request request = (Request) super.message;
javax.sip.address.SipURI sipURI = JainSipUtils.createRecordRouteURI(
sipFactoryImpl.getSipNetworkInterfaceManager(),
JainSipUtils.findTransport(request));
sipURI.setLrParam();
sipURI.setParameter(SipApplicationDispatcherImpl.ROUTE_PARAM_DIRECTIVE,
routingDirective.toString());
sipURI.setParameter(SipApplicationDispatcherImpl.ROUTE_PARAM_PREV_APPLICATION_NAME,
applicationName);
javax.sip.address.Address routeAddress =
SipFactories.addressFactory.createAddress(sipURI);
RouteHeader routeHeader =
SipFactories.headerFactory.createRouteHeader(routeAddress);
request.addHeader(routeHeader);
}
/**
* Add a record route header for app composition
* @throws ParseException if anything goes wrong while creating the record route header
* @throws SipException
* @throws NullPointerException
*/
public void addAppCompositionRRHeader()
throws ParseException, SipException {
Request request = (Request) super.message;
javax.sip.address.SipURI sipURI = JainSipUtils.createRecordRouteURI(
sipFactoryImpl.getSipNetworkInterfaceManager(),
JainSipUtils.findTransport(request));
sipURI.setParameter(SipApplicationDispatcherImpl.RR_PARAM_APPLICATION_NAME, session.getKey().getApplicationName());
sipURI.setParameter(SipApplicationDispatcherImpl.RR_PARAM_HANDLER_NAME, session.getHandler());
sipURI.setLrParam();
javax.sip.address.Address recordRouteAddress =
SipFactories.addressFactory.createAddress(sipURI);
RecordRouteHeader recordRouteHeader =
SipFactories.headerFactory.createRecordRouteHeader(recordRouteAddress);
request.addLast(recordRouteHeader);
}
public void setLinkedRequest(SipServletRequestImpl linkedRequest) {
this.linkedRequest = linkedRequest;
}
public SipServletRequestImpl getLinkedRequest() {
return this.linkedRequest;
}
/**
* @return the routingState
*/
public RoutingState getRoutingState() {
return routingState;
}
/**
* @param routingState the routingState to set
*/
public void setRoutingState(RoutingState routingState) throws IllegalStateException {
//JSR 289 Section 11.2.3 && 10.2.6
if(routingState.equals(RoutingState.CANCELLED) &&
(this.routingState.equals(RoutingState.FINAL_RESPONSE_SENT) ||
this.routingState.equals(RoutingState.PROXIED))) {
throw new IllegalStateException("Cannot cancel final response already sent!");
}
if((routingState.equals(RoutingState.FINAL_RESPONSE_SENT)||
routingState.equals(RoutingState.PROXIED)) && this.routingState.equals(RoutingState.CANCELLED)) {
throw new IllegalStateException("Cancel received and already replied with a 487!");
}
this.routingState = routingState;
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletRequest#addAuthHeader(javax.servlet.sip.SipServletResponse, javax.servlet.sip.AuthInfo)
*/
public void addAuthHeader(SipServletResponse challengeResponse,
AuthInfo authInfo) {
AuthInfoImpl authInfoImpl = (AuthInfoImpl) authInfo;
SipServletResponseImpl response =
(SipServletResponseImpl) challengeResponse;
// First check for WWWAuthentication headers
ListIterator authHeaderIterator =
response.getMessage().getHeaders(WWWAuthenticateHeader.NAME);
while(authHeaderIterator.hasNext()) {
WWWAuthenticateHeader wwwAuthHeader =
(WWWAuthenticateHeader) authHeaderIterator.next();
String uri = wwwAuthHeader.getParameter("uri");
AuthInfoEntry authInfoEntry = authInfoImpl.getAuthInfo(wwwAuthHeader.getRealm());
if(authInfoEntry == null) throw new SecurityException(
"Cannot add authorization header. No credentials for the following realm: " + wwwAuthHeader.getRealm());
addChallengeResponse(wwwAuthHeader,
authInfoEntry.getUserName(),
authInfoEntry.getPassword(),
this.getRequestURI().toString());
}
// Now check for Proxy-Authentication
authHeaderIterator =
response.getMessage().getHeaders(ProxyAuthenticateHeader.NAME);
while(authHeaderIterator.hasNext()) {
ProxyAuthenticateHeader wwwAuthHeader =
(ProxyAuthenticateHeader) authHeaderIterator.next();
String uri = wwwAuthHeader.getParameter("uri");
AuthInfoEntry authInfoEntry = authInfoImpl.getAuthInfo(wwwAuthHeader.getRealm());
if(authInfoEntry == null) throw new SecurityException(
"No credentials for the following realm: " + wwwAuthHeader.getRealm());
addChallengeResponse(wwwAuthHeader,
authInfoEntry.getUserName(),
authInfoEntry.getPassword(),
this.getRequestURI().toString());
}
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletRequest#addAuthHeader(javax.servlet.sip.SipServletResponse, java.lang.String, java.lang.String)
*/
public void addAuthHeader(SipServletResponse challengeResponse,
String username, String password) {
SipServletResponseImpl response =
(SipServletResponseImpl) challengeResponse;
ListIterator authHeaderIterator =
response.getMessage().getHeaders(WWWAuthenticateHeader.NAME);
// First
while(authHeaderIterator.hasNext()) {
WWWAuthenticateHeader wwwAuthHeader =
(WWWAuthenticateHeader) authHeaderIterator.next();
String uri = wwwAuthHeader.getParameter("uri");
addChallengeResponse(wwwAuthHeader, username, password, uri);
}
authHeaderIterator =
response.getMessage().getHeaders(ProxyAuthenticateHeader.NAME);
while(authHeaderIterator.hasNext()) {
ProxyAuthenticateHeader wwwAuthHeader =
(ProxyAuthenticateHeader) authHeaderIterator.next();
String uri = wwwAuthHeader.getParameter("uri");
addChallengeResponse(wwwAuthHeader, username, password, uri);
}
}
private void addChallengeResponse(
WWWAuthenticateHeader wwwAuthHeader,
String username,
String password,
String uri) {
AuthorizationHeader authorization = DigestAuthenticator.getAuthorizationHeader(
getMethod(),
uri,
"", // TODO: What is this entity-body?
wwwAuthHeader,
username,
password);
this.getMessage().addHeader(authorization);
}
/**
* @return the finalResponse
*/
public SipServletResponse getLastFinalResponse() {
return lastFinalResponse;
}
/**
* @param finalResponse the finalResponse to set
*/
public void setLastFinalResponse(SipServletResponse finalResponse) {
if(finalResponse.getStatus() >= 200 &&
(lastFinalResponse == null || lastFinalResponse.getStatus() < finalResponse.getStatus())) {
this.lastFinalResponse = finalResponse;
}
}
}
| true | true | public void send() {
try {
Request request = (Request) super.message;
String transport = JainSipUtils.findTransport(request);
if(Request.ACK.equals(request.getMethod())) {
super.session.getSessionCreatingDialog().sendAck(request);
return;
}
//Added for initial requests only (that are not REGISTER) not for subsequent requests
if(isInitial() && !Request.REGISTER.equalsIgnoreCase(request.getMethod())) {
if(getSipSession().getProxyBranch() == null) // If the app is proxying it already does that
{
//Add a record route header for app composition
addAppCompositionRRHeader();
}
SipApplicationRouterInfo routerInfo = sipFactoryImpl.getNextInterestedApplication(this);
if(routerInfo.getNextApplicationName() != null) {
if(logger.isDebugEnabled()) {
logger.debug("routing back to the container " +
"since the following app is interested " + routerInfo.getNextApplicationName());
}
//add a route header to direct the request back to the container
//to check if there is any other apps interested in it
addInfoForRoutingBackToContainer(session.getKey().getApplicationName());
} else {
if(logger.isDebugEnabled()) {
logger.debug("routing outside the container " +
"since no more apps are is interested.");
}
}
}
if (super.getTransaction() == null) {
SipProvider sipProvider = sipFactoryImpl.getSipNetworkInterfaceManager().findMatchingListeningPoint(
transport, false).getSipProvider();
ContactHeader contactHeader = (ContactHeader)request.getHeader(ContactHeader.NAME);
if(contactHeader == null) {
FromHeader fromHeader = (FromHeader) request.getHeader(FromHeader.NAME);
//TODO what about other schemes ?
String fromName = ((javax.sip.address.SipURI)fromHeader.getAddress().getURI()).getUser();
// Create the contact name address.
contactHeader =
JainSipUtils.createContactHeader(sipFactoryImpl.getSipNetworkInterfaceManager(), transport, fromName);
request.addHeader(contactHeader);
}
if(logger.isDebugEnabled()) {
logger.debug("Getting new Client Tx for request " + request);
}
ClientTransaction ctx = sipProvider
.getNewClientTransaction(request);
super.session.setSessionCreatingTransaction(ctx);
Dialog dialog = ctx.getDialog();
if (dialog == null && this.createDialog) {
dialog = sipProvider.getNewDialog(ctx);
super.session.setSessionCreatingDialog(dialog);
if(logger.isDebugEnabled()) {
logger.debug("new Dialog for request " + request + ", ref = " + dialog);
}
}
//Keeping the transactions mapping in application data for CANCEL handling
if(linkedRequest != null) {
//keeping the client transaction in the server transaction's application data
((TransactionApplicationData)linkedRequest.getTransaction().getApplicationData()).setTransaction(ctx);
if(linkedRequest.getDialog() != null && linkedRequest.getDialog().getApplicationData() != null) {
((TransactionApplicationData)linkedRequest.getDialog().getApplicationData()).setTransaction(ctx);
}
//keeping the server transaction in the client transaction's application data
this.transactionApplicationData.setTransaction(linkedRequest.getTransaction());
if(dialog!= null && dialog.getApplicationData() != null) {
((TransactionApplicationData)dialog.getApplicationData()).setTransaction(linkedRequest.getTransaction());
}
}
// Make the dialog point here so that when the dialog event
// comes in we can find the session quickly.
if (dialog != null) {
dialog.setApplicationData(this.transactionApplicationData);
}
// SIP Request is ALWAYS pointed to by the client tx.
// Notice that the tx appplication data is cached in the request
// copied over to the tx so it can be quickly accessed when response
// arrives.
ctx.setApplicationData(this.transactionApplicationData);
super.setTransaction(ctx);
}
//tells the application dispatcher to stop routing the linked request
// (in this case it would be the original request) since it has been relayed
if(linkedRequest != null &&
!SipApplicationRoutingDirective.NEW.equals(routingDirective)) {
if(!RoutingState.PROXIED.equals(linkedRequest.getRoutingState())) {
linkedRequest.setRoutingState(RoutingState.RELAYED);
}
}
// Update Session state
super.session.updateStateOnSubsequentRequest(this, false);
// If dialog does not exist or has no state.
if (getDialog() == null || getDialog().getState() == null
|| getDialog().getState() == DialogState.EARLY) {
logger.info("Sending the request " + request);
((ClientTransaction) super.getTransaction()).sendRequest();
} else {
// This is a subsequent (an in-dialog) request.
// we don't redirect it to the container for now
logger.info("Sending the in dialog request " + request);
getDialog().sendRequest((ClientTransaction) getTransaction());
}
super.session.addOngoingTransaction(getTransaction());
//updating the last accessed times
getSipSession().setLastAccessedTime(System.currentTimeMillis());
getSipSession().getSipApplicationSession().setLastAccessedTime(System.currentTimeMillis());
} catch (Exception ex) {
throw new IllegalStateException("Error sending request",ex);
}
}
| public void send() {
try {
Request request = (Request) super.message;
String transport = JainSipUtils.findTransport(request);
if(Request.ACK.equals(request.getMethod())) {
super.session.getSessionCreatingDialog().sendAck(request);
return;
}
//Added for initial requests only (that are not REGISTER) not for subsequent requests
if(isInitial() && !Request.REGISTER.equalsIgnoreCase(request.getMethod())) {
// Additional checks for https://sip-servlets.dev.java.net/issues/show_bug.cgi?id=29
if(getSipSession().getProxyBranch() == null ||
(transactionApplicationData.getProxy() != null &&
transactionApplicationData.getProxy().getRecordRoute())) // If the app is proxying it already does that
{
//Add a record route header for app composition
addAppCompositionRRHeader();
}
SipApplicationRouterInfo routerInfo = sipFactoryImpl.getNextInterestedApplication(this);
if(routerInfo.getNextApplicationName() != null) {
if(logger.isDebugEnabled()) {
logger.debug("routing back to the container " +
"since the following app is interested " + routerInfo.getNextApplicationName());
}
//add a route header to direct the request back to the container
//to check if there is any other apps interested in it
addInfoForRoutingBackToContainer(session.getKey().getApplicationName());
} else {
if(logger.isDebugEnabled()) {
logger.debug("routing outside the container " +
"since no more apps are is interested.");
}
}
}
if (super.getTransaction() == null) {
SipProvider sipProvider = sipFactoryImpl.getSipNetworkInterfaceManager().findMatchingListeningPoint(
transport, false).getSipProvider();
ContactHeader contactHeader = (ContactHeader)request.getHeader(ContactHeader.NAME);
if(contactHeader == null) {
FromHeader fromHeader = (FromHeader) request.getHeader(FromHeader.NAME);
//TODO what about other schemes ?
String fromName = ((javax.sip.address.SipURI)fromHeader.getAddress().getURI()).getUser();
// Create the contact name address.
contactHeader =
JainSipUtils.createContactHeader(sipFactoryImpl.getSipNetworkInterfaceManager(), transport, fromName);
request.addHeader(contactHeader);
}
if(logger.isDebugEnabled()) {
logger.debug("Getting new Client Tx for request " + request);
}
ClientTransaction ctx = sipProvider
.getNewClientTransaction(request);
super.session.setSessionCreatingTransaction(ctx);
Dialog dialog = ctx.getDialog();
if (dialog == null && this.createDialog) {
dialog = sipProvider.getNewDialog(ctx);
super.session.setSessionCreatingDialog(dialog);
if(logger.isDebugEnabled()) {
logger.debug("new Dialog for request " + request + ", ref = " + dialog);
}
}
//Keeping the transactions mapping in application data for CANCEL handling
if(linkedRequest != null) {
//keeping the client transaction in the server transaction's application data
((TransactionApplicationData)linkedRequest.getTransaction().getApplicationData()).setTransaction(ctx);
if(linkedRequest.getDialog() != null && linkedRequest.getDialog().getApplicationData() != null) {
((TransactionApplicationData)linkedRequest.getDialog().getApplicationData()).setTransaction(ctx);
}
//keeping the server transaction in the client transaction's application data
this.transactionApplicationData.setTransaction(linkedRequest.getTransaction());
if(dialog!= null && dialog.getApplicationData() != null) {
((TransactionApplicationData)dialog.getApplicationData()).setTransaction(linkedRequest.getTransaction());
}
}
// Make the dialog point here so that when the dialog event
// comes in we can find the session quickly.
if (dialog != null) {
dialog.setApplicationData(this.transactionApplicationData);
}
// SIP Request is ALWAYS pointed to by the client tx.
// Notice that the tx appplication data is cached in the request
// copied over to the tx so it can be quickly accessed when response
// arrives.
ctx.setApplicationData(this.transactionApplicationData);
super.setTransaction(ctx);
}
//tells the application dispatcher to stop routing the linked request
// (in this case it would be the original request) since it has been relayed
if(linkedRequest != null &&
!SipApplicationRoutingDirective.NEW.equals(routingDirective)) {
if(!RoutingState.PROXIED.equals(linkedRequest.getRoutingState())) {
linkedRequest.setRoutingState(RoutingState.RELAYED);
}
}
// Update Session state
super.session.updateStateOnSubsequentRequest(this, false);
// If dialog does not exist or has no state.
if (getDialog() == null || getDialog().getState() == null
|| getDialog().getState() == DialogState.EARLY) {
logger.info("Sending the request " + request);
((ClientTransaction) super.getTransaction()).sendRequest();
} else {
// This is a subsequent (an in-dialog) request.
// we don't redirect it to the container for now
logger.info("Sending the in dialog request " + request);
getDialog().sendRequest((ClientTransaction) getTransaction());
}
super.session.addOngoingTransaction(getTransaction());
//updating the last accessed times
getSipSession().setLastAccessedTime(System.currentTimeMillis());
getSipSession().getSipApplicationSession().setLastAccessedTime(System.currentTimeMillis());
} catch (Exception ex) {
throw new IllegalStateException("Error sending request",ex);
}
}
|
diff --git a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/ChangeDataDirTest.java b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/ChangeDataDirTest.java
index 0a7ce08..ae7b9fc 100644
--- a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/ChangeDataDirTest.java
+++ b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/ChangeDataDirTest.java
@@ -1,263 +1,265 @@
package org.eclipse.mylar.tests.integration;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import junit.framework.TestCase;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.mylar.bugzilla.ui.BugzillaUiPlugin;
import org.eclipse.mylar.bugzilla.ui.tasklist.BugzillaTask;
import org.eclipse.mylar.bugzilla.ui.tasklist.BugzillaTaskHandler;
import org.eclipse.mylar.core.InteractionEvent;
import org.eclipse.mylar.core.MylarPlugin;
import org.eclipse.mylar.core.internal.MylarContextManager;
import org.eclipse.mylar.monitor.MylarMonitorPlugin;
import org.eclipse.mylar.tasklist.ITask;
import org.eclipse.mylar.tasklist.MylarTaskListPlugin;
import org.eclipse.mylar.tasklist.internal.Task;
import org.eclipse.mylar.tasklist.internal.TaskListManager;
/**
* Tests changes to the main mylar data directory location.
*
* @author Wesley Coelho
* @author Mik Kersten (rewrites)
*/
public class ChangeDataDirTest extends TestCase {
private String newDataDir = null;
private final String defaultDir = MylarPlugin.getDefault().getDefaultDataDirectory();
private TaskListManager manager = MylarTaskListPlugin.getTaskListManager();
protected void setUp() throws Exception {
super.setUp();
newDataDir = ResourcesPlugin.getWorkspace().getRoot().getLocation().toString()
+ '/' + ChangeDataDirTest.class.getSimpleName();
File dir = new File(newDataDir);
dir.mkdir();
dir.deleteOnExit();
MylarTaskListPlugin.getTaskListManager().createNewTaskList();
MylarTaskListPlugin.getDefault().getTaskListSaveManager().saveTaskListAndContexts();
}
protected void tearDown() throws Exception {
super.tearDown();
MylarPlugin.getDefault().setDataDirectory(defaultDir);
}
public void testMonitorFileMove() {
+ MylarMonitorPlugin.getDefault().startMonitoring();
MylarMonitorPlugin.getDefault().getInteractionLogger().interactionObserved(InteractionEvent.makeCommand("id", "delta"));
String oldPath = MylarMonitorPlugin.getDefault().getInteractionLogger().getOutputFile().getAbsolutePath();
assertTrue(new File(oldPath).exists());
MylarPlugin.getDefault().setDataDirectory(newDataDir);
assertFalse(new File(oldPath).exists());
String newPath = MylarMonitorPlugin.getDefault().getInteractionLogger().getOutputFile().getAbsolutePath();
assertTrue(new File(newPath).exists());
assertTrue(MylarMonitorPlugin.getDefault().getInteractionLogger().getOutputFile().exists());
String monitorFileName = MylarMonitorPlugin.MONITOR_LOG_NAME + MylarContextManager.CONTEXT_FILE_EXTENSION;
List<String> newFiles = Arrays.asList(new File(newDataDir).list());
assertTrue(newFiles.toString(), newFiles.contains(monitorFileName));
List<String> filesLeft = Arrays.asList(new File(defaultDir).list());
assertFalse(filesLeft.toString(), filesLeft.contains(monitorFileName));
+ MylarMonitorPlugin.getDefault().stopMonitoring();
}
public void testDefaultDataDirectoryMove() {
String workspaceRelativeDir = ResourcesPlugin.getWorkspace().getRoot().getLocation().toString()
+ '/' + ".mylar";
assertTrue(defaultDir.equals(workspaceRelativeDir));
MylarPlugin.getDefault().setDataDirectory(newDataDir);
assertTrue(MylarPlugin.getDefault().getDataDirectory().equals(newDataDir));
}
public void testTaskMove() {
String handle = "task-1";
ITask task = new Task(handle, "label", true);
manager.moveToRoot(task);
ITask readTaskBeforeMove = manager.getTaskForHandle(handle, true);
MylarTaskListPlugin.getDefault().getTaskListSaveManager().copyDataDirContentsTo(newDataDir);
MylarPlugin.getDefault().setDataDirectory(newDataDir);
ITask readTaskAfterMove = manager.getTaskForHandle(handle, true);
assertNotNull(readTaskAfterMove);
assertEquals(readTaskBeforeMove.getCreationDate(), readTaskAfterMove.getCreationDate());
}
public void testBugzillaTaskMove() {
String handle = BugzillaUiPlugin.getDefault().createBugHandleIdentifier(1);
BugzillaTask bugzillaTask = new BugzillaTask(handle, "bug1", true, true);
addBugzillaTask(bugzillaTask);
Date refreshDate = new Date();
bugzillaTask.setLastRefresh(refreshDate);
BugzillaTask readTaskBeforeMove = (BugzillaTask)manager.getTaskForHandle(handle, true);
assertNotNull(readTaskBeforeMove);
assertEquals(refreshDate, readTaskBeforeMove.getLastRefresh());
MylarTaskListPlugin.getDefault().getTaskListSaveManager().copyDataDirContentsTo(newDataDir);
MylarPlugin.getDefault().setDataDirectory(newDataDir);
BugzillaTask readTaskAfterMove = (BugzillaTask)manager.getTaskForHandle(handle, true);
assertNotNull(readTaskAfterMove);
assertEquals(refreshDate, readTaskAfterMove.getLastRefresh());
}
private void addBugzillaTask(BugzillaTask newTask) {
BugzillaTaskHandler handler = new BugzillaTaskHandler();
handler.taskAdded(newTask);
MylarTaskListPlugin.getTaskListManager().moveToRoot(newTask);
}
// /**
// * Tests moving the main mylar data directory to another location (Without
// * copying existing data to the new directory)
// */
// public void testChangeMainDataDir() {
//
// ITask mainDataDirTask = createAndSaveTask("Main Task", false);
//
//// MylarPlugin.getDefault().setDataDirectory(newDataDir);
// assertEquals(0, manager.getTaskList().getRootTasks().size());
//
// // Check that the main data dir task isn't in the list or the folder
// File taskFile = new File(MylarPlugin.getDefault().getDataDirectory() + File.separator
// + mainDataDirTask.getContextPath() + MylarTaskListPlugin.FILE_EXTENSION);
// assertFalse(taskFile.exists());
// assertNull(manager.getTaskForHandle(mainDataDirTask.getHandleIdentifier(), false));
//
// // Check that a newly created task appears in the right place (method
// // will check)
// ITask newDataDirTask = createAndSaveTask("New Data Dir", false);
// taskFile = new File(MylarPlugin.getDefault().getDataDirectory() + File.separator
// + newDataDirTask.getContextPath() + MylarTaskListPlugin.FILE_EXTENSION);
// assertTrue(taskFile.exists());
//
// // Check for other the tasklist file in the new dir
// File destTaskListFile = new File(MylarPlugin.getDefault().getDataDirectory() + File.separator
// + MylarTaskListPlugin.DEFAULT_TASK_LIST_FILE);
// assertTrue(destTaskListFile.exists());
//
// // Switch back to the main task directory
// MylarPlugin.getDefault().setDataDirectory(MylarPlugin.getDefault().getDefaultDataDirectory());
//
// // Check that the previously created main dir task is in the task list and its file exists
// assertNotNull(manager.getTaskForHandle(mainDataDirTask.getHandleIdentifier(), false));
// taskFile = new File(MylarPlugin.getDefault().getDataDirectory() + File.separator
// + mainDataDirTask.getContextPath() + MylarTaskListPlugin.FILE_EXTENSION);
// assertTrue(taskFile.exists());
//
// // Check that the task created in the "New Data Dir" isn't there now
// // that we're back to the main dir
// assertNull(manager.getTaskForHandle(newDataDirTask.getHandleIdentifier(), false));
//
// }
//
// /**
// * Creates a task with an interaction event and checks that it has been
// * properly saved in the currently active data directory
// */
// protected ITask createAndSaveTask(String taskName, boolean createBugzillaTask) {
//
// // Create the task and add it to the root of the task list
// BugzillaTask newTask = null;
// if (!createBugzillaTask) {
// String handle = MylarTaskListPlugin.getTaskListManager().genUniqueTaskHandle();
// newTask = new BugzillaTask(handle, "bug1", true, true);//new Task(MylarTaskListPlugin.getTaskListManager().genUniqueTaskHandle(), taskName, true);
// manager.moveToRoot(newTask);
// } else {
// newTask = new BugzillaTask(MylarTaskListPlugin.getTaskListManager().genUniqueTaskHandle(), taskName, true,
// true);
// addBugzillaTask(newTask);
// }
//
// MylarContext mockContext = MylarPlugin.getContextManager().loadContext(newTask.getHandleIdentifier(),
// newTask.getContextPath());
// InteractionEvent event = new InteractionEvent(InteractionEvent.Kind.EDIT, "structureKind", "handle", "originId");
// mockContext.parseEvent(event);
// MylarPlugin.getContextManager().contextActivated(mockContext);
//
// // Save the context file and check that it exists
// MylarPlugin.getContextManager().saveContext(mockContext.getId(), newTask.getContextPath());
// File taskFile = new File(MylarPlugin.getDefault().getDataDirectory() + File.separator
// + newTask.getContextPath() + MylarContextManager.CONTEXT_FILE_EXTENSION);
// assertTrue(MylarPlugin.getContextManager().hasContext(newTask.getContextPath()));
// assertTrue(taskFile.exists());
//
// return newTask;
// }
//
// /**
// * Same as above but using bugzilla tasks Tests moving the main mylar data
// * directory to another location (Without copying existing data to the new
// * directory)
// */
// public void testChangeMainDataDirBugzilla() {
//
// // Create a task in the main dir and context with an interaction event
// // to be saved
// ITask mainDataDirTask = createAndSaveTask("Main Task", true);
//
// // Set time to see if the right task data is returned by the registry
// // mechanism
// mainDataDirTask.setElapsedTime(ELAPSED_TIME1);
//
// // Save tasklist
// MylarTaskListPlugin.getDefault().getTaskListSaveManager().saveTaskListAndContexts();
//
// // Temp check that the task is there
// assertNotNull(manager.getTaskForHandle(mainDataDirTask.getHandleIdentifier(), false));
//
// // Switch task directory
// MylarPlugin.getDefault().setDataDirectory(newDataDir);
//
// // Check that there are no tasks in the tasklist after switching to the
// // empty dir
// assertTrue(manager.getTaskList().getRootTasks().size() == 0);
//
// // Check that the main data dir task isn't in the list or the folder
// File taskFile = new File(MylarPlugin.getDefault().getDataDirectory() + File.separator
// + mainDataDirTask.getContextPath() + MylarTaskListPlugin.FILE_EXTENSION);
// assertFalse(taskFile.exists());
// assertNull(manager.getTaskForHandle(mainDataDirTask.getHandleIdentifier(), false));
//
// // Check that a newly created task appears in the right place (method
// // will check)
// ITask newDataDirTask = createAndSaveTask("New Data Dir", true);
// taskFile = new File(MylarPlugin.getDefault().getDataDirectory() + File.separator
// + newDataDirTask.getContextPath() + MylarTaskListPlugin.FILE_EXTENSION);
// assertTrue(taskFile.exists());
//
// // Check for tasklist file in the new dir
// File destTaskListFile = new File(MylarPlugin.getDefault().getDataDirectory() + File.separator
// + MylarTaskListPlugin.DEFAULT_TASK_LIST_FILE);
// assertTrue(destTaskListFile.exists());
//
// MylarPlugin.getDefault().setDataDirectory(MylarPlugin.getDefault().getDefaultDataDirectory());
//
// // Check that the previously created main dir task is in the task list
// // and its file exists
// assertNotNull(manager.getTaskForHandle(mainDataDirTask.getHandleIdentifier(), false));
// taskFile = new File(MylarPlugin.getDefault().getDataDirectory() + File.separator
// + mainDataDirTask.getContextPath() + MylarTaskListPlugin.FILE_EXTENSION);
// assertTrue(taskFile.exists());
//
// // Check that the elapsed time is still right
// assertTrue(manager.getTaskForHandle(mainDataDirTask.getHandleIdentifier(), false).getElapsedTime() == ELAPSED_TIME1);
//
// // Check that the task created in the "New Data Dir" isn't there now
// // that we're back to the main dir
// assertNull(manager.getTaskForHandle(newDataDirTask.getHandleIdentifier(), false));
// }
}
| false | true | public void testMonitorFileMove() {
MylarMonitorPlugin.getDefault().getInteractionLogger().interactionObserved(InteractionEvent.makeCommand("id", "delta"));
String oldPath = MylarMonitorPlugin.getDefault().getInteractionLogger().getOutputFile().getAbsolutePath();
assertTrue(new File(oldPath).exists());
MylarPlugin.getDefault().setDataDirectory(newDataDir);
assertFalse(new File(oldPath).exists());
String newPath = MylarMonitorPlugin.getDefault().getInteractionLogger().getOutputFile().getAbsolutePath();
assertTrue(new File(newPath).exists());
assertTrue(MylarMonitorPlugin.getDefault().getInteractionLogger().getOutputFile().exists());
String monitorFileName = MylarMonitorPlugin.MONITOR_LOG_NAME + MylarContextManager.CONTEXT_FILE_EXTENSION;
List<String> newFiles = Arrays.asList(new File(newDataDir).list());
assertTrue(newFiles.toString(), newFiles.contains(monitorFileName));
List<String> filesLeft = Arrays.asList(new File(defaultDir).list());
assertFalse(filesLeft.toString(), filesLeft.contains(monitorFileName));
}
| public void testMonitorFileMove() {
MylarMonitorPlugin.getDefault().startMonitoring();
MylarMonitorPlugin.getDefault().getInteractionLogger().interactionObserved(InteractionEvent.makeCommand("id", "delta"));
String oldPath = MylarMonitorPlugin.getDefault().getInteractionLogger().getOutputFile().getAbsolutePath();
assertTrue(new File(oldPath).exists());
MylarPlugin.getDefault().setDataDirectory(newDataDir);
assertFalse(new File(oldPath).exists());
String newPath = MylarMonitorPlugin.getDefault().getInteractionLogger().getOutputFile().getAbsolutePath();
assertTrue(new File(newPath).exists());
assertTrue(MylarMonitorPlugin.getDefault().getInteractionLogger().getOutputFile().exists());
String monitorFileName = MylarMonitorPlugin.MONITOR_LOG_NAME + MylarContextManager.CONTEXT_FILE_EXTENSION;
List<String> newFiles = Arrays.asList(new File(newDataDir).list());
assertTrue(newFiles.toString(), newFiles.contains(monitorFileName));
List<String> filesLeft = Arrays.asList(new File(defaultDir).list());
assertFalse(filesLeft.toString(), filesLeft.contains(monitorFileName));
MylarMonitorPlugin.getDefault().stopMonitoring();
}
|
diff --git a/backend/mongodb/src/main/java/cl/own/usi/dao/impl/mongo/ScoreDAOMongoImpl.java b/backend/mongodb/src/main/java/cl/own/usi/dao/impl/mongo/ScoreDAOMongoImpl.java
index 235ef33..5e8bc0d 100644
--- a/backend/mongodb/src/main/java/cl/own/usi/dao/impl/mongo/ScoreDAOMongoImpl.java
+++ b/backend/mongodb/src/main/java/cl/own/usi/dao/impl/mongo/ScoreDAOMongoImpl.java
@@ -1,178 +1,178 @@
package cl.own.usi.dao.impl.mongo;
import static cl.own.usi.dao.impl.mongo.DaoHelper.bonusField;
import static cl.own.usi.dao.impl.mongo.DaoHelper.orderByScoreAndNames;
import static cl.own.usi.dao.impl.mongo.DaoHelper.scoreField;
import static cl.own.usi.dao.impl.mongo.DaoHelper.userIdField;
import static cl.own.usi.dao.impl.mongo.DaoHelper.usersCollection;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import cl.own.usi.dao.ScoreDAO;
import cl.own.usi.model.User;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
@Repository
public class ScoreDAOMongoImpl implements ScoreDAO {
@Autowired
DB db;
private Logger logger = LoggerFactory.getLogger(this.getClass());
private List<User> getUsers(DBObject query, DBObject querySubset,
int expectedSize) {
DBCollection dbUsers = db.getCollection(usersCollection);
DBCursor dbCursor = dbUsers.find(query, querySubset).sort(
orderByScoreAndNames);
List<User> users = new ArrayList<User>(expectedSize);
while (dbCursor.hasNext()) {
DBObject dbUser = dbCursor.next();
User user = DaoHelper.fromDBObject(dbUser);
users.add(user);
}
return users;
}
@Override
public List<User> getTop(int limit) {
// TODO set the fields we want, take everything for now
DBObject query = new BasicDBObject();
DBObject subset = new BasicDBObject();
subset.put("$slice", limit);
DBObject querySubset = new BasicDBObject();
querySubset.put("comment", subset);
List<User> users = getUsers(query, querySubset, limit);
logger.debug("get the {} top scores : {}", limit, users);
return users;
}
@Override
public List<User> getBefore(User user, int limit) {
DBObject criteria = new BasicDBObject();
criteria.put("$gt", user.getScore());
DBObject query = new BasicDBObject();
query.put(scoreField, criteria);
DBObject subset = new BasicDBObject();
subset.put("$slice", -limit);
DBObject querySubset = new BasicDBObject();
querySubset.put("comment", subset);
List<User> users = getUsers(query, querySubset, limit);
logger.debug("get the {} users before {} : {} ", new Object[] { limit,
user.getUserId(), users });
return users;
}
@Override
public List<User> getAfter(User user, int limit) {
DBObject criteria = new BasicDBObject();
criteria.put("$lt", user.getScore());
DBObject query = new BasicDBObject();
query.put(scoreField, criteria);
DBObject subset = new BasicDBObject();
subset.put("$slice", limit);
DBObject querySubset = new BasicDBObject();
querySubset.put("comment", subset);
List<User> users = getUsers(query, querySubset, limit);
logger.debug("get the {} users after {} : {} ", new Object[] { limit,
user.getUserId(), users });
return users;
}
@Override
public int setBadAnswer(String userId, int questionNumber) {
DBCollection dbUsers = db.getCollection(usersCollection);
DBObject dbUser = new BasicDBObject();
dbUser.put(userIdField, userId);
DBObject dbBonus = new BasicDBObject();
dbBonus.put(bonusField, 0);
DBObject dbSetBonus = new BasicDBObject();
dbSetBonus.put("$set", dbBonus);
DBObject user = dbUsers.findAndModify(dbUser, dbSetBonus);
Integer score = (Integer) user.get(scoreField);
logger.debug("setBadAnswer for user {} whose score is now {}", userId,
score);
return score.intValue();
}
@Override
public int setGoodAnswer(String userId, int questionNumber,
int questionValue) {
DBCollection dbUsers = db.getCollection(usersCollection);
// Get the current score and bonus
DBObject dbId = new BasicDBObject();
dbId.put(userIdField, userId);
DBObject dbUser = dbUsers.findOne(dbId);
int bonus = (Integer) dbUser.get(bonusField);
int score = (Integer) dbUser.get(scoreField);
- // TODO Et si un user r�pond � 3 questions correctes d'affil�e,
- // mais loupe le temps de r�ponse pour la 4�me, la 5�me r�ponse
+ // TODO Et si un user repond a 3 questions correctes d'affilee,
+ // mais loupe le temps de reponse pour la 4eme, la 5eme reponse
// si elle est correct ne doit pas profiter des 3 questions
- // pr�c�dente enregirstr�es.
+ // precedente enregirstrees.
int newScore = score + bonus + questionValue;
int newBonus = bonus + 1;
DBObject dbScoreAndBonus = new BasicDBObject();
dbScoreAndBonus.put(scoreField, Integer.valueOf(newScore));
dbScoreAndBonus.put(bonusField, Integer.valueOf(newBonus));
DBObject dbSetScoreAndBonus = new BasicDBObject();
dbSetScoreAndBonus.put("$set", dbScoreAndBonus);
dbUsers.findAndModify(dbId, dbSetScoreAndBonus);
logger.debug(
"setGoodAnswer for user {} whose previous score was {} and is now {}",
new Object[] { userId, score, newScore });
return newScore;
}
@Override
public void flushUsers() {
// TODO Auto-generated method stub
}
@Override
public void computeRankings() {
// not needed in this implementation
}
}
| false | true | public int setGoodAnswer(String userId, int questionNumber,
int questionValue) {
DBCollection dbUsers = db.getCollection(usersCollection);
// Get the current score and bonus
DBObject dbId = new BasicDBObject();
dbId.put(userIdField, userId);
DBObject dbUser = dbUsers.findOne(dbId);
int bonus = (Integer) dbUser.get(bonusField);
int score = (Integer) dbUser.get(scoreField);
// TODO Et si un user r�pond � 3 questions correctes d'affil�e,
// mais loupe le temps de r�ponse pour la 4�me, la 5�me r�ponse
// si elle est correct ne doit pas profiter des 3 questions
// pr�c�dente enregirstr�es.
int newScore = score + bonus + questionValue;
int newBonus = bonus + 1;
DBObject dbScoreAndBonus = new BasicDBObject();
dbScoreAndBonus.put(scoreField, Integer.valueOf(newScore));
dbScoreAndBonus.put(bonusField, Integer.valueOf(newBonus));
DBObject dbSetScoreAndBonus = new BasicDBObject();
dbSetScoreAndBonus.put("$set", dbScoreAndBonus);
dbUsers.findAndModify(dbId, dbSetScoreAndBonus);
logger.debug(
"setGoodAnswer for user {} whose previous score was {} and is now {}",
new Object[] { userId, score, newScore });
return newScore;
}
| public int setGoodAnswer(String userId, int questionNumber,
int questionValue) {
DBCollection dbUsers = db.getCollection(usersCollection);
// Get the current score and bonus
DBObject dbId = new BasicDBObject();
dbId.put(userIdField, userId);
DBObject dbUser = dbUsers.findOne(dbId);
int bonus = (Integer) dbUser.get(bonusField);
int score = (Integer) dbUser.get(scoreField);
// TODO Et si un user repond a 3 questions correctes d'affilee,
// mais loupe le temps de reponse pour la 4eme, la 5eme reponse
// si elle est correct ne doit pas profiter des 3 questions
// precedente enregirstrees.
int newScore = score + bonus + questionValue;
int newBonus = bonus + 1;
DBObject dbScoreAndBonus = new BasicDBObject();
dbScoreAndBonus.put(scoreField, Integer.valueOf(newScore));
dbScoreAndBonus.put(bonusField, Integer.valueOf(newBonus));
DBObject dbSetScoreAndBonus = new BasicDBObject();
dbSetScoreAndBonus.put("$set", dbScoreAndBonus);
dbUsers.findAndModify(dbId, dbSetScoreAndBonus);
logger.debug(
"setGoodAnswer for user {} whose previous score was {} and is now {}",
new Object[] { userId, score, newScore });
return newScore;
}
|
diff --git a/src/com/android/browser/IntentHandler.java b/src/com/android/browser/IntentHandler.java
index e17fdc55..77db5384 100644
--- a/src/com/android/browser/IntentHandler.java
+++ b/src/com/android/browser/IntentHandler.java
@@ -1,359 +1,363 @@
/*
* 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.browser;
import com.android.browser.search.SearchEngine;
import com.android.common.Search;
import com.android.common.speech.LoggingEvents;
import android.app.Activity;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Browser;
import android.provider.MediaStore;
import android.speech.RecognizerResultsIntent;
import android.text.TextUtils;
import android.util.Patterns;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Handle all browser related intents
*/
public class IntentHandler {
// "source" parameter for Google search suggested by the browser
final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
// "source" parameter for Google search from unknown source
final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
/* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
private Activity mActivity;
private Controller mController;
private TabControl mTabControl;
private BrowserSettings mSettings;
public IntentHandler(Activity browser, Controller controller) {
mActivity = browser;
mController = controller;
mTabControl = mController.getTabControl();
mSettings = controller.getSettings();
}
void onNewIntent(Intent intent) {
Tab current = mTabControl.getCurrentTab();
// When a tab is closed on exit, the current tab index is set to -1.
// Reset before proceed as Browser requires the current tab to be set.
if (current == null) {
// Try to reset the tab in case the index was incorrect.
current = mTabControl.getTab(0);
if (current == null) {
// No tabs at all so just ignore this intent.
return;
}
mController.setActiveTab(current);
}
final String action = intent.getAction();
final int flags = intent.getFlags();
if (Intent.ACTION_MAIN.equals(action) ||
(flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
// just resume the browser
return;
}
if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(action)) {
mController.bookmarksOrHistoryPicker(false);
return;
}
mController.removeComboView();
// In case the SearchDialog is open.
((SearchManager) mActivity.getSystemService(Context.SEARCH_SERVICE))
.stopSearch();
boolean activateVoiceSearch = RecognizerResultsIntent
.ACTION_VOICE_SEARCH_RESULTS.equals(action);
if (Intent.ACTION_VIEW.equals(action)
|| Intent.ACTION_SEARCH.equals(action)
|| MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
|| Intent.ACTION_WEB_SEARCH.equals(action)
|| activateVoiceSearch) {
if (current.isInVoiceSearchMode()) {
String title = current.getVoiceDisplayTitle();
if (title != null && title.equals(intent.getStringExtra(
SearchManager.QUERY))) {
// The user submitted the same search as the last voice
// search, so do nothing.
return;
}
if (Intent.ACTION_SEARCH.equals(action)
&& current.voiceSearchSourceIsGoogle()) {
Intent logIntent = new Intent(
LoggingEvents.ACTION_LOG_EVENT);
logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
LoggingEvents.VoiceSearch.QUERY_UPDATED);
logIntent.putExtra(
LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
intent.getDataString());
mActivity.sendBroadcast(logIntent);
// Note, onPageStarted will revert the voice title bar
// When http://b/issue?id=2379215 is fixed, we should update
// the title bar here.
}
}
// If this was a search request (e.g. search query directly typed into the address bar),
// pass it on to the default web search provider.
if (handleWebSearchIntent(mActivity, mController, intent)) {
return;
}
UrlData urlData = getUrlDataFromIntent(intent);
if (urlData.isEmpty()) {
urlData = new UrlData(mSettings.getHomePage());
}
+ if (intent.getBooleanExtra(Browser.EXTRA_CREATE_NEW_TAB, false)) {
+ mController.openTabAndShow(mTabControl.getCurrentTab(), urlData, false, null);
+ return;
+ }
final String appId = intent
.getStringExtra(Browser.EXTRA_APPLICATION_ID);
if ((Intent.ACTION_VIEW.equals(action)
// If a voice search has no appId, it means that it came
// from the browser. In that case, reuse the current tab.
|| (activateVoiceSearch && appId != null))
&& !mActivity.getPackageName().equals(appId)
&& (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Tab appTab = mTabControl.getTabFromId(appId);
if (appTab != null) {
mController.reuseTab(appTab, appId, urlData);
return;
} else {
// No matching application tab, try to find a regular tab
// with a matching url.
appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
if (appTab != null) {
if (current != appTab) {
mController.switchToTab(mTabControl.getTabIndex(appTab));
}
// Otherwise, we are already viewing the correct tab.
} else {
// if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
// will be opened in a new tab unless we have reached
// MAX_TABS. Then the url will be opened in the current
// tab. If a new tab is created, it will have "true" for
// exit on close.
mController.openTabAndShow(null, urlData, true, appId);
}
}
} else {
if (!urlData.isEmpty()
&& urlData.mUrl.startsWith("about:debug")) {
if ("about:debug.dom".equals(urlData.mUrl)) {
current.getWebView().dumpDomTree(false);
} else if ("about:debug.dom.file".equals(urlData.mUrl)) {
current.getWebView().dumpDomTree(true);
} else if ("about:debug.render".equals(urlData.mUrl)) {
current.getWebView().dumpRenderTree(false);
} else if ("about:debug.render.file".equals(urlData.mUrl)) {
current.getWebView().dumpRenderTree(true);
} else if ("about:debug.display".equals(urlData.mUrl)) {
current.getWebView().dumpDisplayTree();
} else if ("about:debug.nav".equals(urlData.mUrl)) {
current.getWebView().debugDump();
} else {
mSettings.toggleDebugSettings(mActivity);
}
return;
}
// Get rid of the subwindow if it exists
mController.dismissSubWindow(current);
// If the current Tab is being used as an application tab,
// remove the association, since the new Intent means that it is
// no longer associated with that application.
current.setAppId(null);
mController.loadUrlDataIn(current, urlData);
}
}
}
protected UrlData getUrlDataFromIntent(Intent intent) {
String url = "";
Map<String, String> headers = null;
if (intent != null
&& (intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) {
final String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action)) {
url = UrlUtils.smartUrlFilter(intent.getData());
if (url != null && url.startsWith("http")) {
final Bundle pairs = intent
.getBundleExtra(Browser.EXTRA_HEADERS);
if (pairs != null && !pairs.isEmpty()) {
Iterator<String> iter = pairs.keySet().iterator();
headers = new HashMap<String, String>();
while (iter.hasNext()) {
String key = iter.next();
headers.put(key, pairs.getString(key));
}
}
}
} else if (Intent.ACTION_SEARCH.equals(action)
|| MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
|| Intent.ACTION_WEB_SEARCH.equals(action)) {
url = intent.getStringExtra(SearchManager.QUERY);
if (url != null) {
// In general, we shouldn't modify URL from Intent.
// But currently, we get the user-typed URL from search box as well.
url = UrlUtils.fixUrl(url);
url = UrlUtils.smartUrlFilter(url);
String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
if (url.contains(searchSource)) {
String source = null;
final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
if (appData != null) {
source = appData.getString(Search.SOURCE);
}
if (TextUtils.isEmpty(source)) {
source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
}
url = url.replace(searchSource, "&source=android-"+source+"&");
}
}
}
}
return new UrlData(url, headers, intent);
}
/**
* Launches the default web search activity with the query parameters if the given intent's data
* are identified as plain search terms and not URLs/shortcuts.
* @return true if the intent was handled and web search activity was launched, false if not.
*/
static boolean handleWebSearchIntent(Activity activity,
Controller controller, Intent intent) {
if (intent == null) return false;
String url = null;
final String action = intent.getAction();
if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
action)) {
return false;
}
if (Intent.ACTION_VIEW.equals(action)) {
Uri data = intent.getData();
if (data != null) url = data.toString();
} else if (Intent.ACTION_SEARCH.equals(action)
|| MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
|| Intent.ACTION_WEB_SEARCH.equals(action)) {
url = intent.getStringExtra(SearchManager.QUERY);
}
return handleWebSearchRequest(activity, controller, url,
intent.getBundleExtra(SearchManager.APP_DATA),
intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
}
/**
* Launches the default web search activity with the query parameters if the given url string
* was identified as plain search terms and not URL/shortcut.
* @return true if the request was handled and web search activity was launched, false if not.
*/
private static boolean handleWebSearchRequest(Activity activity,
Controller controller, String inUrl, Bundle appData,
String extraData) {
if (inUrl == null) return false;
// In general, we shouldn't modify URL from Intent.
// But currently, we get the user-typed URL from search box as well.
String url = UrlUtils.fixUrl(inUrl).trim();
if (TextUtils.isEmpty(url)) return false;
// URLs are handled by the regular flow of control, so
// return early.
if (Patterns.WEB_URL.matcher(url).matches()
|| UrlUtils.ACCEPTED_URI_SCHEMA.matcher(url).matches()) {
return false;
}
final ContentResolver cr = activity.getContentResolver();
final String newUrl = url;
if (controller == null || controller.getTabControl() == null
|| controller.getTabControl().getCurrentWebView() == null
|| !controller.getTabControl().getCurrentWebView()
.isPrivateBrowsingEnabled()) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... unused) {
Browser.addSearchUrl(cr, newUrl);
return null;
}
}.execute();
}
SearchEngine searchEngine = BrowserSettings.getInstance().getSearchEngine();
if (searchEngine == null) return false;
searchEngine.startSearch(activity, url, appData, extraData);
return true;
}
/**
* A UrlData class to abstract how the content will be set to WebView.
* This base class uses loadUrl to show the content.
*/
static class UrlData {
final String mUrl;
final Map<String, String> mHeaders;
final Intent mVoiceIntent;
UrlData(String url) {
this.mUrl = url;
this.mHeaders = null;
this.mVoiceIntent = null;
}
UrlData(String url, Map<String, String> headers, Intent intent) {
this.mUrl = url;
this.mHeaders = headers;
if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
.equals(intent.getAction())) {
this.mVoiceIntent = intent;
} else {
this.mVoiceIntent = null;
}
}
boolean isEmpty() {
return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
}
/**
* Load this UrlData into the given Tab. Use loadUrlDataIn to update
* the title bar as well.
*/
public void loadIn(Tab t) {
if (mVoiceIntent != null) {
t.activateVoiceSearchMode(mVoiceIntent);
} else {
t.getWebView().loadUrl(mUrl, mHeaders);
}
}
}
}
| true | true | void onNewIntent(Intent intent) {
Tab current = mTabControl.getCurrentTab();
// When a tab is closed on exit, the current tab index is set to -1.
// Reset before proceed as Browser requires the current tab to be set.
if (current == null) {
// Try to reset the tab in case the index was incorrect.
current = mTabControl.getTab(0);
if (current == null) {
// No tabs at all so just ignore this intent.
return;
}
mController.setActiveTab(current);
}
final String action = intent.getAction();
final int flags = intent.getFlags();
if (Intent.ACTION_MAIN.equals(action) ||
(flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
// just resume the browser
return;
}
if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(action)) {
mController.bookmarksOrHistoryPicker(false);
return;
}
mController.removeComboView();
// In case the SearchDialog is open.
((SearchManager) mActivity.getSystemService(Context.SEARCH_SERVICE))
.stopSearch();
boolean activateVoiceSearch = RecognizerResultsIntent
.ACTION_VOICE_SEARCH_RESULTS.equals(action);
if (Intent.ACTION_VIEW.equals(action)
|| Intent.ACTION_SEARCH.equals(action)
|| MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
|| Intent.ACTION_WEB_SEARCH.equals(action)
|| activateVoiceSearch) {
if (current.isInVoiceSearchMode()) {
String title = current.getVoiceDisplayTitle();
if (title != null && title.equals(intent.getStringExtra(
SearchManager.QUERY))) {
// The user submitted the same search as the last voice
// search, so do nothing.
return;
}
if (Intent.ACTION_SEARCH.equals(action)
&& current.voiceSearchSourceIsGoogle()) {
Intent logIntent = new Intent(
LoggingEvents.ACTION_LOG_EVENT);
logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
LoggingEvents.VoiceSearch.QUERY_UPDATED);
logIntent.putExtra(
LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
intent.getDataString());
mActivity.sendBroadcast(logIntent);
// Note, onPageStarted will revert the voice title bar
// When http://b/issue?id=2379215 is fixed, we should update
// the title bar here.
}
}
// If this was a search request (e.g. search query directly typed into the address bar),
// pass it on to the default web search provider.
if (handleWebSearchIntent(mActivity, mController, intent)) {
return;
}
UrlData urlData = getUrlDataFromIntent(intent);
if (urlData.isEmpty()) {
urlData = new UrlData(mSettings.getHomePage());
}
final String appId = intent
.getStringExtra(Browser.EXTRA_APPLICATION_ID);
if ((Intent.ACTION_VIEW.equals(action)
// If a voice search has no appId, it means that it came
// from the browser. In that case, reuse the current tab.
|| (activateVoiceSearch && appId != null))
&& !mActivity.getPackageName().equals(appId)
&& (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Tab appTab = mTabControl.getTabFromId(appId);
if (appTab != null) {
mController.reuseTab(appTab, appId, urlData);
return;
} else {
// No matching application tab, try to find a regular tab
// with a matching url.
appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
if (appTab != null) {
if (current != appTab) {
mController.switchToTab(mTabControl.getTabIndex(appTab));
}
// Otherwise, we are already viewing the correct tab.
} else {
// if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
// will be opened in a new tab unless we have reached
// MAX_TABS. Then the url will be opened in the current
// tab. If a new tab is created, it will have "true" for
// exit on close.
mController.openTabAndShow(null, urlData, true, appId);
}
}
} else {
if (!urlData.isEmpty()
&& urlData.mUrl.startsWith("about:debug")) {
if ("about:debug.dom".equals(urlData.mUrl)) {
current.getWebView().dumpDomTree(false);
} else if ("about:debug.dom.file".equals(urlData.mUrl)) {
current.getWebView().dumpDomTree(true);
} else if ("about:debug.render".equals(urlData.mUrl)) {
current.getWebView().dumpRenderTree(false);
} else if ("about:debug.render.file".equals(urlData.mUrl)) {
current.getWebView().dumpRenderTree(true);
} else if ("about:debug.display".equals(urlData.mUrl)) {
current.getWebView().dumpDisplayTree();
} else if ("about:debug.nav".equals(urlData.mUrl)) {
current.getWebView().debugDump();
} else {
mSettings.toggleDebugSettings(mActivity);
}
return;
}
// Get rid of the subwindow if it exists
mController.dismissSubWindow(current);
// If the current Tab is being used as an application tab,
// remove the association, since the new Intent means that it is
// no longer associated with that application.
current.setAppId(null);
mController.loadUrlDataIn(current, urlData);
}
}
}
| void onNewIntent(Intent intent) {
Tab current = mTabControl.getCurrentTab();
// When a tab is closed on exit, the current tab index is set to -1.
// Reset before proceed as Browser requires the current tab to be set.
if (current == null) {
// Try to reset the tab in case the index was incorrect.
current = mTabControl.getTab(0);
if (current == null) {
// No tabs at all so just ignore this intent.
return;
}
mController.setActiveTab(current);
}
final String action = intent.getAction();
final int flags = intent.getFlags();
if (Intent.ACTION_MAIN.equals(action) ||
(flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
// just resume the browser
return;
}
if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(action)) {
mController.bookmarksOrHistoryPicker(false);
return;
}
mController.removeComboView();
// In case the SearchDialog is open.
((SearchManager) mActivity.getSystemService(Context.SEARCH_SERVICE))
.stopSearch();
boolean activateVoiceSearch = RecognizerResultsIntent
.ACTION_VOICE_SEARCH_RESULTS.equals(action);
if (Intent.ACTION_VIEW.equals(action)
|| Intent.ACTION_SEARCH.equals(action)
|| MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
|| Intent.ACTION_WEB_SEARCH.equals(action)
|| activateVoiceSearch) {
if (current.isInVoiceSearchMode()) {
String title = current.getVoiceDisplayTitle();
if (title != null && title.equals(intent.getStringExtra(
SearchManager.QUERY))) {
// The user submitted the same search as the last voice
// search, so do nothing.
return;
}
if (Intent.ACTION_SEARCH.equals(action)
&& current.voiceSearchSourceIsGoogle()) {
Intent logIntent = new Intent(
LoggingEvents.ACTION_LOG_EVENT);
logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
LoggingEvents.VoiceSearch.QUERY_UPDATED);
logIntent.putExtra(
LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
intent.getDataString());
mActivity.sendBroadcast(logIntent);
// Note, onPageStarted will revert the voice title bar
// When http://b/issue?id=2379215 is fixed, we should update
// the title bar here.
}
}
// If this was a search request (e.g. search query directly typed into the address bar),
// pass it on to the default web search provider.
if (handleWebSearchIntent(mActivity, mController, intent)) {
return;
}
UrlData urlData = getUrlDataFromIntent(intent);
if (urlData.isEmpty()) {
urlData = new UrlData(mSettings.getHomePage());
}
if (intent.getBooleanExtra(Browser.EXTRA_CREATE_NEW_TAB, false)) {
mController.openTabAndShow(mTabControl.getCurrentTab(), urlData, false, null);
return;
}
final String appId = intent
.getStringExtra(Browser.EXTRA_APPLICATION_ID);
if ((Intent.ACTION_VIEW.equals(action)
// If a voice search has no appId, it means that it came
// from the browser. In that case, reuse the current tab.
|| (activateVoiceSearch && appId != null))
&& !mActivity.getPackageName().equals(appId)
&& (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Tab appTab = mTabControl.getTabFromId(appId);
if (appTab != null) {
mController.reuseTab(appTab, appId, urlData);
return;
} else {
// No matching application tab, try to find a regular tab
// with a matching url.
appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
if (appTab != null) {
if (current != appTab) {
mController.switchToTab(mTabControl.getTabIndex(appTab));
}
// Otherwise, we are already viewing the correct tab.
} else {
// if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
// will be opened in a new tab unless we have reached
// MAX_TABS. Then the url will be opened in the current
// tab. If a new tab is created, it will have "true" for
// exit on close.
mController.openTabAndShow(null, urlData, true, appId);
}
}
} else {
if (!urlData.isEmpty()
&& urlData.mUrl.startsWith("about:debug")) {
if ("about:debug.dom".equals(urlData.mUrl)) {
current.getWebView().dumpDomTree(false);
} else if ("about:debug.dom.file".equals(urlData.mUrl)) {
current.getWebView().dumpDomTree(true);
} else if ("about:debug.render".equals(urlData.mUrl)) {
current.getWebView().dumpRenderTree(false);
} else if ("about:debug.render.file".equals(urlData.mUrl)) {
current.getWebView().dumpRenderTree(true);
} else if ("about:debug.display".equals(urlData.mUrl)) {
current.getWebView().dumpDisplayTree();
} else if ("about:debug.nav".equals(urlData.mUrl)) {
current.getWebView().debugDump();
} else {
mSettings.toggleDebugSettings(mActivity);
}
return;
}
// Get rid of the subwindow if it exists
mController.dismissSubWindow(current);
// If the current Tab is being used as an application tab,
// remove the association, since the new Intent means that it is
// no longer associated with that application.
current.setAppId(null);
mController.loadUrlDataIn(current, urlData);
}
}
}
|
diff --git a/tests/org.jboss.tools.dummy.ui.bot.test/src/org/jboss/tools/dummy/ui/bot/test/DummyTest.java b/tests/org.jboss.tools.dummy.ui.bot.test/src/org/jboss/tools/dummy/ui/bot/test/DummyTest.java
index 68766d12..f231a82f 100644
--- a/tests/org.jboss.tools.dummy.ui.bot.test/src/org/jboss/tools/dummy/ui/bot/test/DummyTest.java
+++ b/tests/org.jboss.tools.dummy.ui.bot.test/src/org/jboss/tools/dummy/ui/bot/test/DummyTest.java
@@ -1,69 +1,69 @@
package org.jboss.tools.dummy.ui.bot.test;
import static org.eclipse.swtbot.swt.finder.waits.Conditions.shellIsActive;
import static org.junit.Assert.assertEquals;
import org.apache.log4j.Logger;
import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot;
import org.eclipse.swtbot.swt.finder.junit.SWTBotJunit4ClassRunner;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Dummy bot tests - designed to test jenkins slaves
* @author jpeterka
*
*/
@RunWith(SWTBotJunit4ClassRunner.class)
public class DummyTest {
Logger log = Logger.getLogger("");
@BeforeClass
public static void before() {
}
@Test
public void dummyTest() {
String prefMenu = "Preferences";
String prefDlg = prefMenu;
String windowMenu = "Window";
if (isOSX()) {
- prefMenu = "Preferences...";
+ prefMenu = "Preferences";
windowMenu = "Eclipse";
}
SWTWorkbenchBot bot = new SWTWorkbenchBot();
bot.menu(windowMenu).menu(prefMenu).click();
bot.waitUntil(shellIsActive(prefDlg), 10000);
SWTBotShell shell = bot.shell(prefDlg);
assertEquals(prefDlg,shell.getText());
bot.activeShell().close();
}
@Test
public void hundredTimes() {
final int cycles = 100;
for (int i = 0 ; i < cycles ; i++)
{
dummyTest();
log.info(i+1 + "/" + cycles + " try passed");
}
}
@AfterClass
public static void after() {
SWTWorkbenchBot bot = new SWTWorkbenchBot();
bot.closeAllShells();
}
public boolean isOSX() {
String osName = System.getProperty("os.name");
boolean osX = osName.contains("OS X");
log.info("OS Name: " + osName);
return osX;
}
}
| true | true | public void dummyTest() {
String prefMenu = "Preferences";
String prefDlg = prefMenu;
String windowMenu = "Window";
if (isOSX()) {
prefMenu = "Preferences...";
windowMenu = "Eclipse";
}
SWTWorkbenchBot bot = new SWTWorkbenchBot();
bot.menu(windowMenu).menu(prefMenu).click();
bot.waitUntil(shellIsActive(prefDlg), 10000);
SWTBotShell shell = bot.shell(prefDlg);
assertEquals(prefDlg,shell.getText());
bot.activeShell().close();
}
| public void dummyTest() {
String prefMenu = "Preferences";
String prefDlg = prefMenu;
String windowMenu = "Window";
if (isOSX()) {
prefMenu = "Preferences";
windowMenu = "Eclipse";
}
SWTWorkbenchBot bot = new SWTWorkbenchBot();
bot.menu(windowMenu).menu(prefMenu).click();
bot.waitUntil(shellIsActive(prefDlg), 10000);
SWTBotShell shell = bot.shell(prefDlg);
assertEquals(prefDlg,shell.getText());
bot.activeShell().close();
}
|
diff --git a/melati/src/main/java/org/melati/MelatiUtil.java b/melati/src/main/java/org/melati/MelatiUtil.java
index 51329c0dc..4ca282756 100644
--- a/melati/src/main/java/org/melati/MelatiUtil.java
+++ b/melati/src/main/java/org/melati/MelatiUtil.java
@@ -1,276 +1,276 @@
/*
* $Source$
* $Revision$
*
* Copyright (C) 2000 Tim Joyce
*
* Part of Melati (http://melati.org), a framework for the rapid
* development of clean, maintainable web applications.
*
* Melati is free software; Permission is granted to copy, distribute
* and/or modify this software under the terms either:
*
* a) 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,
*
* or
*
* b) any version of the Melati Software License, as published
* at http://melati.org
*
* You should have received a copy of the GNU General Public License and
* the Melati Software License along with this program;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA to obtain the
* GNU General Public License and visit http://melati.org to obtain the
* Melati Software License.
*
* Feel free to contact the Developers of Melati (http://melati.org),
* if you would like to work out a different arrangement than the options
* outlined here. It is our intention to allow Melati to be used by as
* wide an audience as possible.
*
* 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.
*
* Contact details for copyright holder:
*
* Tim Joyce <[email protected]>
* http://paneris.org/
* 68 Sandbanks Rd, Poole, Dorset. BH14 8BY. UK
*/
package org.melati;
import java.util.Enumeration;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import org.melati.poem.Persistent;
import org.melati.poem.Column;
import org.melati.template.TemplateContext;
import org.melati.template.TempletAdaptor;
import org.melati.template.TempletAdaptorConstructionMelatiException;
import org.melati.util.Tree;
import org.melati.util.JSDynamicTree;
/**
* MelatiUtil is a place where useful Static methods can be put.
*/
public class MelatiUtil {
public static void extractFields(TemplateContext context, Persistent object) {
for (Enumeration c = object.getTable().columns(); c.hasMoreElements();) {
Column column = (Column)c.nextElement();
String formFieldName = "field_" + column.getName();
String rawString = context.getForm(formFieldName);
String adaptorFieldName = formFieldName + "-adaptor";
String adaptorName = context.getForm(adaptorFieldName);
if (adaptorName != null) {
TempletAdaptor adaptor;
try {
// FIXME cache this instantiation
adaptor = (TempletAdaptor)Class.forName(adaptorName).newInstance();
}
catch (Exception e) {
throw new TempletAdaptorConstructionMelatiException(
adaptorFieldName, adaptorName, e);
}
column.setRaw(object, adaptor.rawFrom(context, formFieldName));
- }
- else {
+ } else {
if (rawString != null) {
+ rawString = rawString.trim();
if (rawString.equals("")) {
if (column.getType().getNullable())
column.setRaw(object, null);
else
column.setRawString(object, "");
+ } else {
+ column.setRawString(object, rawString);
}
- else
- column.setRawString(object, rawString);
}
}
}
}
public static Object extractField(TemplateContext context, String fieldName)
throws TempletAdaptorConstructionMelatiException {
String rawString = context.getForm(fieldName);
String adaptorFieldName = fieldName + "-adaptor";
String adaptorName = context.getForm(adaptorFieldName);
if (adaptorName != null) {
TempletAdaptor adaptor;
try {
// FIXME cache this instantiation
adaptor = (TempletAdaptor)Class.forName(adaptorName).newInstance();
}
catch (Exception e) {
throw new TempletAdaptorConstructionMelatiException(
adaptorFieldName, adaptorName, e);
}
return adaptor.rawFrom(context, fieldName);
}
return rawString;
}
// get a tree object
public JSDynamicTree getJSDynamicTree(Tree tree) {
return new JSDynamicTree(tree);
}
/**
* Modify or add a form parameter setting (query string component) in a URL.
*
* @param uri A URI
* @param query A query string
* @param field The parameter's name
* @param value The new value for the parameter (unencoded)
* @return <TT><I>uri</I>?<I>query</I></TT> with <TT>field=value</TT>.
* If there is already a binding for <TT>field</TT> in the
* query string it is replaced, not duplicated.
* @see org.melati.util.MelatiUtil
*/
public static String sameURLWith(String uri, String query,
String field, String value) {
return uri + "?" + sameQueryWith(query, field, value);
}
/**
* Modify or add a form parameter setting (query string component) in the URL
* for a servlet request.
*
* @param request A servlet request
* @param field The parameter's name
* @param value The new value for the parameter (unencoded)
* @return The request's URL with <TT>field=value</TT>. If there is
* already a binding for <TT>field</TT> in the query string
* it is replaced, not duplicated. If there is no query
* string, one is added.
* @see org.melati.util.MelatiUtil
*/
public static String sameURLWith(HttpServletRequest request,
String field, String value) {
return sameURLWith(request.getRequestURI(), request.getQueryString(),
field, value);
}
/**
* Modify or add a form parameter setting (query string component) in a query
* string.
*
* @param qs A query string
* @param field The parameter's name
* @param value The new value for the parameter (unencoded)
* @return <TT>qs</TT> with <TT>field=value</TT>.
* If there is already a binding for <TT>field</TT> in the
* query string it is replaced, not duplicated.
* @see org.melati.util.MelatiUtil
*/
public static String sameQueryWith(String qs, String field, String value) {
String fenc = URLEncoder.encode(field);
String fenceq = fenc + '=';
String fev = fenceq + URLEncoder.encode(value);
if (qs == null || qs.equals("")) return fev;
int i;
if (qs.startsWith(fenceq)) i = 0;
else {
i = qs.indexOf('&' + fenceq);
if (i == -1) return qs + '&' + fev;
++i;
}
int a = qs.indexOf('&', i);
return qs.substring(0, i) + fev + (a == -1 ? "" : qs.substring(a));
}
/**
* a useful utility method that gets a value from the Form. It will return
* null if the value is "" or not present
*
* @param context - a template context
* @param field - the name of the field to get
*
* @return - the value of the field requested
*/
public static String getFormNulled(TemplateContext context, String field) {
return getForm(context,field,null);
}
/**
* a useful utility method that gets a value from the Form. It will return
* the default if the value is "" or not present
*
* @param context - a template context
* @param field - the name of the field to get
* @param def - the default value if the field is "" or not present
*
* @return - the value of the field requested
*/
public static String getForm(TemplateContext context, String field,
String def) {
String val = context.getForm(field);
if (val == null) return def;
return val.trim().equals("")?def:val;
}
/**
* a useful utility method that gets a value from the Form as an Integer.
* It will return null if the value is "" or not present
*
* @param context - a template context
* @param field - the name of the field to get
* @param def - the default value if the field is "" or not present
*
* @return - the value of the field requested
*/
public static Integer getFormInteger(TemplateContext context, String field,
Integer def) {
String val = getFormNulled(context,field);
return val==null?def:new Integer(val);
}
/**
* a useful utility method that gets a value from the Form as an Integer.
* It will return null if the value is "" or not present
*
* @param context - a template context
* @param field - the name of the field to get
*
* @return - the value of the field requested
*/
public static Integer getFormInteger(TemplateContext context, String field) {
return getFormInteger(context,field,null);
}
/**
* a useful utility method that tests weather a field is present in a Form,
* returning a Boolean.
*
* @param context - a template context
* @param field - the name of the field to get
*
* @return - TRUE or FALSE depending if the field is present
*/
public static Boolean getFormBoolean(TemplateContext context, String field) {
return getFormNulled(context,field) == null ? Boolean.FALSE : Boolean.TRUE;
}
}
| false | true | public static void extractFields(TemplateContext context, Persistent object) {
for (Enumeration c = object.getTable().columns(); c.hasMoreElements();) {
Column column = (Column)c.nextElement();
String formFieldName = "field_" + column.getName();
String rawString = context.getForm(formFieldName);
String adaptorFieldName = formFieldName + "-adaptor";
String adaptorName = context.getForm(adaptorFieldName);
if (adaptorName != null) {
TempletAdaptor adaptor;
try {
// FIXME cache this instantiation
adaptor = (TempletAdaptor)Class.forName(adaptorName).newInstance();
}
catch (Exception e) {
throw new TempletAdaptorConstructionMelatiException(
adaptorFieldName, adaptorName, e);
}
column.setRaw(object, adaptor.rawFrom(context, formFieldName));
}
else {
if (rawString != null) {
if (rawString.equals("")) {
if (column.getType().getNullable())
column.setRaw(object, null);
else
column.setRawString(object, "");
}
else
column.setRawString(object, rawString);
}
}
}
}
| public static void extractFields(TemplateContext context, Persistent object) {
for (Enumeration c = object.getTable().columns(); c.hasMoreElements();) {
Column column = (Column)c.nextElement();
String formFieldName = "field_" + column.getName();
String rawString = context.getForm(formFieldName);
String adaptorFieldName = formFieldName + "-adaptor";
String adaptorName = context.getForm(adaptorFieldName);
if (adaptorName != null) {
TempletAdaptor adaptor;
try {
// FIXME cache this instantiation
adaptor = (TempletAdaptor)Class.forName(adaptorName).newInstance();
}
catch (Exception e) {
throw new TempletAdaptorConstructionMelatiException(
adaptorFieldName, adaptorName, e);
}
column.setRaw(object, adaptor.rawFrom(context, formFieldName));
} else {
if (rawString != null) {
rawString = rawString.trim();
if (rawString.equals("")) {
if (column.getType().getNullable())
column.setRaw(object, null);
else
column.setRawString(object, "");
} else {
column.setRawString(object, rawString);
}
}
}
}
}
|
diff --git a/src/main/java/com/mycompany/app/App.java b/src/main/java/com/mycompany/app/App.java
index 93b3c86..52ac766 100644
--- a/src/main/java/com/mycompany/app/App.java
+++ b/src/main/java/com/mycompany/app/App.java
@@ -1,18 +1,18 @@
package com.mycompany.app;
public class App
{
public static void main( String[] args )
{
String str1 = null;
String str2 = "str";
System.out.println("Hello World! "+str1.equals(str2));
String test1 = "123";
char[] test2 = null;
- String.copyValueOf(test2);
+ test1 = String.copyValueOf(test2);
System.out.println("Hello World! "+test1);
System.out.println("Hello World! "+test2);
}
}
| true | true | public static void main( String[] args )
{
String str1 = null;
String str2 = "str";
System.out.println("Hello World! "+str1.equals(str2));
String test1 = "123";
char[] test2 = null;
String.copyValueOf(test2);
System.out.println("Hello World! "+test1);
System.out.println("Hello World! "+test2);
}
| public static void main( String[] args )
{
String str1 = null;
String str2 = "str";
System.out.println("Hello World! "+str1.equals(str2));
String test1 = "123";
char[] test2 = null;
test1 = String.copyValueOf(test2);
System.out.println("Hello World! "+test1);
System.out.println("Hello World! "+test2);
}
|
diff --git a/src/java/org/grails/plugins/easyui/EasyuiDomainClassMarshaller.java b/src/java/org/grails/plugins/easyui/EasyuiDomainClassMarshaller.java
index c56de15..034731b 100644
--- a/src/java/org/grails/plugins/easyui/EasyuiDomainClassMarshaller.java
+++ b/src/java/org/grails/plugins/easyui/EasyuiDomainClassMarshaller.java
@@ -1,194 +1,194 @@
package org.grails.plugins.easyui;
import grails.converters.JSON;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.commons.lang.BooleanUtils;
import org.codehaus.groovy.grails.commons.DomainClassArtefactHandler;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsClassUtils;
import org.codehaus.groovy.grails.commons.GrailsDomainClass;
import org.codehaus.groovy.grails.commons.GrailsDomainClassProperty;
import org.codehaus.groovy.grails.support.proxy.DefaultProxyHandler;
import org.codehaus.groovy.grails.support.proxy.ProxyHandler;
import org.codehaus.groovy.grails.web.converters.ConverterUtil;
import org.codehaus.groovy.grails.web.converters.exceptions.ConverterException;
import org.codehaus.groovy.grails.web.converters.marshaller.ObjectMarshaller;
import org.codehaus.groovy.grails.web.json.JSONWriter;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
public class EasyuiDomainClassMarshaller implements ObjectMarshaller<JSON> {
public static final String COMPLETE_MARSHALLER = "easyui-show";
private boolean includeVersion;
private boolean exportOneToMany;
private ProxyHandler proxyHandler;
private GrailsApplication application;
public EasyuiDomainClassMarshaller(GrailsApplication application) {
this(true, false, application);
}
public EasyuiDomainClassMarshaller(boolean includeVersion, GrailsApplication application) {
this(includeVersion, false, application);
}
public EasyuiDomainClassMarshaller(boolean includeVersion, boolean exportOneToMany, GrailsApplication application) {
this(includeVersion, exportOneToMany, new DefaultProxyHandler(), application);
}
public EasyuiDomainClassMarshaller(boolean includeVersion, boolean exportOneToMany, ProxyHandler proxyHandler, GrailsApplication application){
this.includeVersion = includeVersion;
this.exportOneToMany = exportOneToMany;
this.proxyHandler = proxyHandler;
this.application = application;
}
public boolean isIncludeVersion(){
return includeVersion;
}
public void setIncludeVersion(boolean includeVersion){
this.includeVersion = includeVersion;
}
@Override
public boolean supports(Object object) {
String name = ConverterUtil.trimProxySuffix(object.getClass().getName());
return application.isArtefactOfType(DomainClassArtefactHandler.TYPE, name);
}
protected String concatPropertyName(String parentName, String propertyName)
{
return parentName == null ? propertyName : parentName.concat("_").concat(propertyName);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void writeProperties(Object obj, JSON json, String parentName, Class<?> ignoredClass) {
JSONWriter writer = json.getWriter();
obj = proxyHandler.unwrapIfProxy(obj);
Class<?> clazz = obj.getClass();
GrailsDomainClass domainClass = (GrailsDomainClass)application.getArtefact("Domain", ConverterUtil.trimProxySuffix(clazz.getName()));
GrailsDomainClassProperty id = domainClass.getIdentifier();
Object idValue = extractValue(obj, id);
json.property(concatPropertyName(parentName, "id"), idValue);
if(parentName == null && isIncludeVersion()) {
GrailsDomainClassProperty versionProperty = domainClass.getVersion();
Object version = extractValue(obj, versionProperty);
if(version != null) {
json.property("version", version);
}
}
BeanWrapper beanWrapper = new BeanWrapperImpl(obj);
GrailsDomainClassProperty[] properties = domainClass.getPersistentProperties();
Collection<String> transients = (Collection<String>) GrailsClassUtils.getStaticPropertyValue(obj.getClass(), GrailsDomainClassProperty.TRANSIENT);
Set<GrailsDomainClassProperty> exportProperties = new HashSet<GrailsDomainClassProperty>();
for (GrailsDomainClassProperty property : properties)
exportProperties.add(property);
if (transients != null) {
for (String propName : transients)
exportProperties.add(domainClass.getPropertyByName(propName));
}
for (GrailsDomainClassProperty property : exportProperties) {
if(!property.isAssociation() ) {
writer.key(concatPropertyName(parentName, property.getName()));
Object val = beanWrapper.getPropertyValue(property.getName());
if (val instanceof Boolean)
val = BooleanUtils.toStringTrueFalse((Boolean) val);
json.convertAnother(val);
}
else {
Object referenceObject = beanWrapper.getPropertyValue(property.getName());
if(isRenderDomainClassRelations()) {
if(referenceObject == null)
writer.value(null);
else {
referenceObject = proxyHandler.unwrapIfProxy(referenceObject);
if(referenceObject instanceof SortedMap){
referenceObject = new TreeMap((SortedMap)referenceObject);
}
else if(referenceObject instanceof SortedSet) {
referenceObject = new TreeSet((SortedSet)referenceObject);
}
else if(referenceObject instanceof Set) {
referenceObject = new HashSet((Set)referenceObject);
} else
if(referenceObject instanceof Map) {
referenceObject = new HashMap((Map)referenceObject);
} else if(referenceObject instanceof Collection) {
referenceObject = new ArrayList((Collection)referenceObject);
}
json.convertAnother(referenceObject);
}
}
if (property.isCircular()) {
writer.key(concatPropertyName(parentName, property.getName() + "_id"));
Object val = (referenceObject != null) ? new BeanWrapperImpl(referenceObject).getPropertyValue("id") : null;
writer.value(val);
}
else if(referenceObject == null) {
writer.key(concatPropertyName(parentName, property.getName()));
json.value(null);
}
else {
GrailsDomainClass referencedDomainClass = property.getReferencedDomainClass();
if(referencedDomainClass == null || property.isEmbedded() || GrailsClassUtils.isJdk5Enum(property.getType())) {
json.convertAnother(referenceObject);
}
else if(property.isOneToOne() || property.isManyToOne() || property.isEmbedded()) {
if(ignoredClass == null || !ignoredClass.isAssignableFrom(property.getType()))
writeProperties(referenceObject, json, concatPropertyName(parentName, property.getName()), null);
}
else if (this.exportOneToMany) {
if (referenceObject instanceof Collection) {
writer.key(concatPropertyName(parentName, property.getName()));
Collection o = (Collection) referenceObject;
writer.array();
for (Object el : o) {
writer.object();
- writeProperties(el, json, null, clazz);
+ writeProperties(el, json, null, domainClass.getClazz());
writer.endObject();
}
writer.endArray();
}
}
}
}
}
}
protected Object extractValue(Object domainObject, GrailsDomainClassProperty property) {
return (new BeanWrapperImpl(domainObject)).getPropertyValue(property.getName());
}
protected boolean isRenderDomainClassRelations() {
return false;
}
@Override
public void marshalObject(Object value, JSON json) throws ConverterException {
JSONWriter writer = json.getWriter();
writer.object();
writeProperties(value, json, null, null);
writer.endObject();
}
}
| true | true | protected void writeProperties(Object obj, JSON json, String parentName, Class<?> ignoredClass) {
JSONWriter writer = json.getWriter();
obj = proxyHandler.unwrapIfProxy(obj);
Class<?> clazz = obj.getClass();
GrailsDomainClass domainClass = (GrailsDomainClass)application.getArtefact("Domain", ConverterUtil.trimProxySuffix(clazz.getName()));
GrailsDomainClassProperty id = domainClass.getIdentifier();
Object idValue = extractValue(obj, id);
json.property(concatPropertyName(parentName, "id"), idValue);
if(parentName == null && isIncludeVersion()) {
GrailsDomainClassProperty versionProperty = domainClass.getVersion();
Object version = extractValue(obj, versionProperty);
if(version != null) {
json.property("version", version);
}
}
BeanWrapper beanWrapper = new BeanWrapperImpl(obj);
GrailsDomainClassProperty[] properties = domainClass.getPersistentProperties();
Collection<String> transients = (Collection<String>) GrailsClassUtils.getStaticPropertyValue(obj.getClass(), GrailsDomainClassProperty.TRANSIENT);
Set<GrailsDomainClassProperty> exportProperties = new HashSet<GrailsDomainClassProperty>();
for (GrailsDomainClassProperty property : properties)
exportProperties.add(property);
if (transients != null) {
for (String propName : transients)
exportProperties.add(domainClass.getPropertyByName(propName));
}
for (GrailsDomainClassProperty property : exportProperties) {
if(!property.isAssociation() ) {
writer.key(concatPropertyName(parentName, property.getName()));
Object val = beanWrapper.getPropertyValue(property.getName());
if (val instanceof Boolean)
val = BooleanUtils.toStringTrueFalse((Boolean) val);
json.convertAnother(val);
}
else {
Object referenceObject = beanWrapper.getPropertyValue(property.getName());
if(isRenderDomainClassRelations()) {
if(referenceObject == null)
writer.value(null);
else {
referenceObject = proxyHandler.unwrapIfProxy(referenceObject);
if(referenceObject instanceof SortedMap){
referenceObject = new TreeMap((SortedMap)referenceObject);
}
else if(referenceObject instanceof SortedSet) {
referenceObject = new TreeSet((SortedSet)referenceObject);
}
else if(referenceObject instanceof Set) {
referenceObject = new HashSet((Set)referenceObject);
} else
if(referenceObject instanceof Map) {
referenceObject = new HashMap((Map)referenceObject);
} else if(referenceObject instanceof Collection) {
referenceObject = new ArrayList((Collection)referenceObject);
}
json.convertAnother(referenceObject);
}
}
if (property.isCircular()) {
writer.key(concatPropertyName(parentName, property.getName() + "_id"));
Object val = (referenceObject != null) ? new BeanWrapperImpl(referenceObject).getPropertyValue("id") : null;
writer.value(val);
}
else if(referenceObject == null) {
writer.key(concatPropertyName(parentName, property.getName()));
json.value(null);
}
else {
GrailsDomainClass referencedDomainClass = property.getReferencedDomainClass();
if(referencedDomainClass == null || property.isEmbedded() || GrailsClassUtils.isJdk5Enum(property.getType())) {
json.convertAnother(referenceObject);
}
else if(property.isOneToOne() || property.isManyToOne() || property.isEmbedded()) {
if(ignoredClass == null || !ignoredClass.isAssignableFrom(property.getType()))
writeProperties(referenceObject, json, concatPropertyName(parentName, property.getName()), null);
}
else if (this.exportOneToMany) {
if (referenceObject instanceof Collection) {
writer.key(concatPropertyName(parentName, property.getName()));
Collection o = (Collection) referenceObject;
writer.array();
for (Object el : o) {
writer.object();
writeProperties(el, json, null, clazz);
writer.endObject();
}
writer.endArray();
}
}
}
}
}
}
| protected void writeProperties(Object obj, JSON json, String parentName, Class<?> ignoredClass) {
JSONWriter writer = json.getWriter();
obj = proxyHandler.unwrapIfProxy(obj);
Class<?> clazz = obj.getClass();
GrailsDomainClass domainClass = (GrailsDomainClass)application.getArtefact("Domain", ConverterUtil.trimProxySuffix(clazz.getName()));
GrailsDomainClassProperty id = domainClass.getIdentifier();
Object idValue = extractValue(obj, id);
json.property(concatPropertyName(parentName, "id"), idValue);
if(parentName == null && isIncludeVersion()) {
GrailsDomainClassProperty versionProperty = domainClass.getVersion();
Object version = extractValue(obj, versionProperty);
if(version != null) {
json.property("version", version);
}
}
BeanWrapper beanWrapper = new BeanWrapperImpl(obj);
GrailsDomainClassProperty[] properties = domainClass.getPersistentProperties();
Collection<String> transients = (Collection<String>) GrailsClassUtils.getStaticPropertyValue(obj.getClass(), GrailsDomainClassProperty.TRANSIENT);
Set<GrailsDomainClassProperty> exportProperties = new HashSet<GrailsDomainClassProperty>();
for (GrailsDomainClassProperty property : properties)
exportProperties.add(property);
if (transients != null) {
for (String propName : transients)
exportProperties.add(domainClass.getPropertyByName(propName));
}
for (GrailsDomainClassProperty property : exportProperties) {
if(!property.isAssociation() ) {
writer.key(concatPropertyName(parentName, property.getName()));
Object val = beanWrapper.getPropertyValue(property.getName());
if (val instanceof Boolean)
val = BooleanUtils.toStringTrueFalse((Boolean) val);
json.convertAnother(val);
}
else {
Object referenceObject = beanWrapper.getPropertyValue(property.getName());
if(isRenderDomainClassRelations()) {
if(referenceObject == null)
writer.value(null);
else {
referenceObject = proxyHandler.unwrapIfProxy(referenceObject);
if(referenceObject instanceof SortedMap){
referenceObject = new TreeMap((SortedMap)referenceObject);
}
else if(referenceObject instanceof SortedSet) {
referenceObject = new TreeSet((SortedSet)referenceObject);
}
else if(referenceObject instanceof Set) {
referenceObject = new HashSet((Set)referenceObject);
} else
if(referenceObject instanceof Map) {
referenceObject = new HashMap((Map)referenceObject);
} else if(referenceObject instanceof Collection) {
referenceObject = new ArrayList((Collection)referenceObject);
}
json.convertAnother(referenceObject);
}
}
if (property.isCircular()) {
writer.key(concatPropertyName(parentName, property.getName() + "_id"));
Object val = (referenceObject != null) ? new BeanWrapperImpl(referenceObject).getPropertyValue("id") : null;
writer.value(val);
}
else if(referenceObject == null) {
writer.key(concatPropertyName(parentName, property.getName()));
json.value(null);
}
else {
GrailsDomainClass referencedDomainClass = property.getReferencedDomainClass();
if(referencedDomainClass == null || property.isEmbedded() || GrailsClassUtils.isJdk5Enum(property.getType())) {
json.convertAnother(referenceObject);
}
else if(property.isOneToOne() || property.isManyToOne() || property.isEmbedded()) {
if(ignoredClass == null || !ignoredClass.isAssignableFrom(property.getType()))
writeProperties(referenceObject, json, concatPropertyName(parentName, property.getName()), null);
}
else if (this.exportOneToMany) {
if (referenceObject instanceof Collection) {
writer.key(concatPropertyName(parentName, property.getName()));
Collection o = (Collection) referenceObject;
writer.array();
for (Object el : o) {
writer.object();
writeProperties(el, json, null, domainClass.getClazz());
writer.endObject();
}
writer.endArray();
}
}
}
}
}
}
|
diff --git a/src/com/justjournal/CachedHeadlineBean.java b/src/com/justjournal/CachedHeadlineBean.java
index 990142b3..fd0b7fc4 100644
--- a/src/com/justjournal/CachedHeadlineBean.java
+++ b/src/com/justjournal/CachedHeadlineBean.java
@@ -1,148 +1,154 @@
/*
Copyright (c) 2005, Lucas Holt
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
Neither the name of the Just Journal nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package com.justjournal;
import com.justjournal.db.DateTimeBean;
import com.justjournal.db.RssCacheDao;
import com.justjournal.db.RssCacheTo;
import org.apache.log4j.Category;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
/**
* Stores RSS content collected from the internet into a datastore,
* retrieves stored versions, and spits out HTML to render them.
* <p/>
* Created by IntelliJ IDEA.
* User: laffer1
* Date: Apr 27, 2005
* Time: 8:15:45 PM
*
* @author Lucas Holt
* @version 1.0
*/
public final class CachedHeadlineBean
extends HeadlineBean {
private static Category log = Category.getInstance(CachedHeadlineBean.class.getName());
protected void getRssDocument(final String uri)
throws Exception {
if (log.isDebugEnabled())
log.debug("Starting getRssDocument()");
RssCacheDao dao = new RssCacheDao();
RssCacheTo rss;
InputStreamReader ir;
StringBuffer sbx = new StringBuffer();
BufferedReader buff;
final java.util.GregorianCalendar calendarg = new java.util.GregorianCalendar();
rss = dao.view(uri);
if (rss != null && rss.getUri() != null && rss.getUri().length() > 10) {
if (log.isDebugEnabled())
log.debug("Record found with uri: " + uri);
DateTimeBean dt = rss.getLastUpdated();
if (dt.getDay() != calendarg.get(java.util.Calendar.DATE)) {
if (log.isDebugEnabled())
log.debug("getRssDocument() Day doesn't match: " + uri);
u = new URL(uri);
ir = new InputStreamReader(u.openStream(), "UTF-8");
buff = new BufferedReader(ir);
String input;
while ((input = buff.readLine()) != null) {
sbx.append(StringUtil.replace(input, '\'', "\\\'"));
}
buff.close();
- rss.setContent(sbx.toString());
+ rss.setContent(sbx.toString().trim());
+ // sun can't make their own rss feeds complaint
+ if (rss.getContent().startsWith("<rss"))
+ rss.setContent("<?xml version=\"1.0\"?>\n");
dao.update(rss);
} else {
if (log.isDebugEnabled())
log.debug("Hit end.. no date change.");
}
} else {
if (log.isDebugEnabled())
log.debug("Fetch uri: " + uri);
rss = new RssCacheTo();
//Open the file for reading:
u = new URL(uri);
ir = new InputStreamReader(u.openStream(), "UTF-8");
buff = new BufferedReader(ir);
String input;
while ((input = buff.readLine()) != null) {
sbx.append(StringUtil.replace(input, '\'', "\\\'"));
}
buff.close();
log.debug(sbx.toString());
try {
rss.setUri(uri);
rss.setInterval(24);
- rss.setContent(sbx.toString());
+ rss.setContent(sbx.toString().trim());
+ // sun can't make their own rss feeds complaint
+ if (rss.getContent().startsWith("<rss"))
+ rss.setContent("<?xml version=\"1.0\"?>\n");
dao.add(rss);
} catch (java.lang.NullPointerException n) {
if (log.isDebugEnabled())
log.debug("Null pointer exception creating/adding rss cache object to db.");
}
}
if (log.isDebugEnabled())
log.debug("getRssDocument() Retrieved uri from database: " + uri);
log.debug(sbx.toString());
StringReader sr = new StringReader(rss.getContent());
org.xml.sax.InputSource saxy = new org.xml.sax.InputSource(sr);
builder = factory.newDocumentBuilder();
document = builder.parse(saxy);
if (log.isDebugEnabled())
log.debug("Hit end of getRssDocument() for " + uri);
}
}
| false | true | protected void getRssDocument(final String uri)
throws Exception {
if (log.isDebugEnabled())
log.debug("Starting getRssDocument()");
RssCacheDao dao = new RssCacheDao();
RssCacheTo rss;
InputStreamReader ir;
StringBuffer sbx = new StringBuffer();
BufferedReader buff;
final java.util.GregorianCalendar calendarg = new java.util.GregorianCalendar();
rss = dao.view(uri);
if (rss != null && rss.getUri() != null && rss.getUri().length() > 10) {
if (log.isDebugEnabled())
log.debug("Record found with uri: " + uri);
DateTimeBean dt = rss.getLastUpdated();
if (dt.getDay() != calendarg.get(java.util.Calendar.DATE)) {
if (log.isDebugEnabled())
log.debug("getRssDocument() Day doesn't match: " + uri);
u = new URL(uri);
ir = new InputStreamReader(u.openStream(), "UTF-8");
buff = new BufferedReader(ir);
String input;
while ((input = buff.readLine()) != null) {
sbx.append(StringUtil.replace(input, '\'', "\\\'"));
}
buff.close();
rss.setContent(sbx.toString());
dao.update(rss);
} else {
if (log.isDebugEnabled())
log.debug("Hit end.. no date change.");
}
} else {
if (log.isDebugEnabled())
log.debug("Fetch uri: " + uri);
rss = new RssCacheTo();
//Open the file for reading:
u = new URL(uri);
ir = new InputStreamReader(u.openStream(), "UTF-8");
buff = new BufferedReader(ir);
String input;
while ((input = buff.readLine()) != null) {
sbx.append(StringUtil.replace(input, '\'', "\\\'"));
}
buff.close();
log.debug(sbx.toString());
try {
rss.setUri(uri);
rss.setInterval(24);
rss.setContent(sbx.toString());
dao.add(rss);
} catch (java.lang.NullPointerException n) {
if (log.isDebugEnabled())
log.debug("Null pointer exception creating/adding rss cache object to db.");
}
}
if (log.isDebugEnabled())
log.debug("getRssDocument() Retrieved uri from database: " + uri);
log.debug(sbx.toString());
StringReader sr = new StringReader(rss.getContent());
org.xml.sax.InputSource saxy = new org.xml.sax.InputSource(sr);
builder = factory.newDocumentBuilder();
document = builder.parse(saxy);
if (log.isDebugEnabled())
log.debug("Hit end of getRssDocument() for " + uri);
}
| protected void getRssDocument(final String uri)
throws Exception {
if (log.isDebugEnabled())
log.debug("Starting getRssDocument()");
RssCacheDao dao = new RssCacheDao();
RssCacheTo rss;
InputStreamReader ir;
StringBuffer sbx = new StringBuffer();
BufferedReader buff;
final java.util.GregorianCalendar calendarg = new java.util.GregorianCalendar();
rss = dao.view(uri);
if (rss != null && rss.getUri() != null && rss.getUri().length() > 10) {
if (log.isDebugEnabled())
log.debug("Record found with uri: " + uri);
DateTimeBean dt = rss.getLastUpdated();
if (dt.getDay() != calendarg.get(java.util.Calendar.DATE)) {
if (log.isDebugEnabled())
log.debug("getRssDocument() Day doesn't match: " + uri);
u = new URL(uri);
ir = new InputStreamReader(u.openStream(), "UTF-8");
buff = new BufferedReader(ir);
String input;
while ((input = buff.readLine()) != null) {
sbx.append(StringUtil.replace(input, '\'', "\\\'"));
}
buff.close();
rss.setContent(sbx.toString().trim());
// sun can't make their own rss feeds complaint
if (rss.getContent().startsWith("<rss"))
rss.setContent("<?xml version=\"1.0\"?>\n");
dao.update(rss);
} else {
if (log.isDebugEnabled())
log.debug("Hit end.. no date change.");
}
} else {
if (log.isDebugEnabled())
log.debug("Fetch uri: " + uri);
rss = new RssCacheTo();
//Open the file for reading:
u = new URL(uri);
ir = new InputStreamReader(u.openStream(), "UTF-8");
buff = new BufferedReader(ir);
String input;
while ((input = buff.readLine()) != null) {
sbx.append(StringUtil.replace(input, '\'', "\\\'"));
}
buff.close();
log.debug(sbx.toString());
try {
rss.setUri(uri);
rss.setInterval(24);
rss.setContent(sbx.toString().trim());
// sun can't make their own rss feeds complaint
if (rss.getContent().startsWith("<rss"))
rss.setContent("<?xml version=\"1.0\"?>\n");
dao.add(rss);
} catch (java.lang.NullPointerException n) {
if (log.isDebugEnabled())
log.debug("Null pointer exception creating/adding rss cache object to db.");
}
}
if (log.isDebugEnabled())
log.debug("getRssDocument() Retrieved uri from database: " + uri);
log.debug(sbx.toString());
StringReader sr = new StringReader(rss.getContent());
org.xml.sax.InputSource saxy = new org.xml.sax.InputSource(sr);
builder = factory.newDocumentBuilder();
document = builder.parse(saxy);
if (log.isDebugEnabled())
log.debug("Hit end of getRssDocument() for " + uri);
}
|
diff --git a/examples/numberguess/src/test/java/org/jboss/seam/wicket/example/numberguess/test/HomePageTest.java b/examples/numberguess/src/test/java/org/jboss/seam/wicket/example/numberguess/test/HomePageTest.java
index baaa748..1cdee4a 100644
--- a/examples/numberguess/src/test/java/org/jboss/seam/wicket/example/numberguess/test/HomePageTest.java
+++ b/examples/numberguess/src/test/java/org/jboss/seam/wicket/example/numberguess/test/HomePageTest.java
@@ -1,81 +1,81 @@
package org.jboss.seam.wicket.example.numberguess.test;
import javax.inject.Inject;
import org.apache.wicket.util.tester.FormTester;
import org.jboss.arquillian.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.seam.wicket.SeamApplication;
import org.jboss.seam.wicket.example.numberguess.HomePage;
import org.jboss.seam.wicket.example.numberguess.NumberGuessApplication;
import org.jboss.seam.wicket.example.numberguess.test.util.MavenArtifactResolver;
import org.jboss.seam.wicket.mock.SeamWicketTester;
import org.jboss.seam.wicket.util.NonContextual;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test class for HomePage and SeamWicketTester.
*
* @author oranheim
*/
@RunWith(Arquillian.class)
public class HomePageTest
{
@Deployment
public static WebArchive createTestArchive()
{
return ShrinkWrap.create(WebArchive.class, "test.war")
.addPackage(SeamApplication.class.getPackage())
.addPackage(NonContextual.class.getPackage())
.addPackage(NumberGuessApplication.class.getPackage())
.addPackage(SeamWicketTester.class.getPackage())
// ugh, arquillian, don't make this so painful :(
.addResource("org/jboss/seam/wicket/example/numberguess/HomePage.html", "WEB-INF/classes/org/jboss/seam/wicket/example/numberguess/HomePage.html")
.addWebResource("test-jetty-env.xml", "jetty-env.xml")
.addWebResource(EmptyAsset.INSTANCE, "beans.xml")
.addLibraries(
- MavenArtifactResolver.resolve("org.jboss.seam.solder:seam-solder:3.0.0.Beta1"),
- MavenArtifactResolver.resolve("org.apache.wicket:wicket:1.4.14"))
+ MavenArtifactResolver.resolve("org.jboss.seam.solder:seam-solder:3.0.0.Beta2"),
+ MavenArtifactResolver.resolve("org.apache.wicket:wicket:1.4.15"))
.setWebXML("test-web.xml");
}
@Inject
SeamWicketTester tester;
@Test
public void testGuessNumber() throws Exception
{
Assert.assertNotNull(tester);
tester.startPage(HomePage.class);
FormTester form = tester.newFormTester("NumberGuessMain");
Assert.assertNotNull(form);
form.setValue("inputGuess", "1");
form.submit("GuessButton");
tester.assertRenderedPage(HomePage.class);
}
@Test
public void testRestart() throws Exception
{
Assert.assertNotNull(tester);
tester.startPage(HomePage.class);
FormTester form = tester.newFormTester("NumberGuessMain");
Assert.assertNotNull(form);
form.submit("RestartButton");
tester.assertRenderedPage(HomePage.class);
}
}
| true | true | public static WebArchive createTestArchive()
{
return ShrinkWrap.create(WebArchive.class, "test.war")
.addPackage(SeamApplication.class.getPackage())
.addPackage(NonContextual.class.getPackage())
.addPackage(NumberGuessApplication.class.getPackage())
.addPackage(SeamWicketTester.class.getPackage())
// ugh, arquillian, don't make this so painful :(
.addResource("org/jboss/seam/wicket/example/numberguess/HomePage.html", "WEB-INF/classes/org/jboss/seam/wicket/example/numberguess/HomePage.html")
.addWebResource("test-jetty-env.xml", "jetty-env.xml")
.addWebResource(EmptyAsset.INSTANCE, "beans.xml")
.addLibraries(
MavenArtifactResolver.resolve("org.jboss.seam.solder:seam-solder:3.0.0.Beta1"),
MavenArtifactResolver.resolve("org.apache.wicket:wicket:1.4.14"))
.setWebXML("test-web.xml");
}
| public static WebArchive createTestArchive()
{
return ShrinkWrap.create(WebArchive.class, "test.war")
.addPackage(SeamApplication.class.getPackage())
.addPackage(NonContextual.class.getPackage())
.addPackage(NumberGuessApplication.class.getPackage())
.addPackage(SeamWicketTester.class.getPackage())
// ugh, arquillian, don't make this so painful :(
.addResource("org/jboss/seam/wicket/example/numberguess/HomePage.html", "WEB-INF/classes/org/jboss/seam/wicket/example/numberguess/HomePage.html")
.addWebResource("test-jetty-env.xml", "jetty-env.xml")
.addWebResource(EmptyAsset.INSTANCE, "beans.xml")
.addLibraries(
MavenArtifactResolver.resolve("org.jboss.seam.solder:seam-solder:3.0.0.Beta2"),
MavenArtifactResolver.resolve("org.apache.wicket:wicket:1.4.15"))
.setWebXML("test-web.xml");
}
|
diff --git a/dspace/src/org/dspace/content/InstallItem.java b/dspace/src/org/dspace/content/InstallItem.java
index e0f1c9102..3a7743e50 100644
--- a/dspace/src/org/dspace/content/InstallItem.java
+++ b/dspace/src/org/dspace/content/InstallItem.java
@@ -1,177 +1,178 @@
/*
* InstallItem.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2001, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.content;
import java.io.IOException;
import java.sql.SQLException;
import org.dspace.browse.Browse;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.Context;
import org.dspace.core.Constants;
import org.dspace.eperson.EPerson;
import org.dspace.handle.HandleManager;
import org.dspace.search.DSIndexer;
import org.dspace.storage.rdbms.TableRowIterator;
import org.dspace.storage.rdbms.DatabaseManager;
/**
* Support to install item in the archive
*
* @author dstuve
* @version $Revision$
*/
public class InstallItem
{
public static Item installItem(Context c, InProgressSubmission is)
throws SQLException, IOException, AuthorizeException
{
return installItem(c, is, c.getCurrentUser());
}
public static Item installItem(Context c, InProgressSubmission is, EPerson e)
throws SQLException, IOException, AuthorizeException
{
Item item = is.getItem();
// create accession date
DCDate now = DCDate.getCurrent();
item.addDC("date", "accessioned", null, now.toString());
item.addDC("date", "available", null, now.toString());
// create issue date if not present
DCValue[] currentDateIssued = item.getDC("date", "issued", null);
if(currentDateIssued.length == 0)
{
item.addDC("date", "issued", null, now.toString());
}
// create handle
String handle = HandleManager.createHandle(c, item);
// Add handle as identifier.uri DC value
item.addDC("identifier", "uri", null, handle);
// Add format.mimetype and format.extent DC values
Bitstream[] bitstreams = item.getNonInternalBitstreams();
for (int i = 0; i < bitstreams.length; i++)
{
BitstreamFormat bf = bitstreams[i].getFormat();
item.addDC("format",
"extent",
null,
String.valueOf(bitstreams[i].getSize()));
item.addDC("format", "mimetype", null, bf.getMIMEType());
}
String provDescription = "Made available in DSpace on " + now +
" (GMT). " + getBitstreamProvenanceMessage(item);
if (currentDateIssued.length != 0)
{
DCDate d = new DCDate(currentDateIssued[0].value);
provDescription = provDescription + " Previous issue date: " +
d.toString();
}
// Add provenance description
item.addDC("description", "provenance", "en", provDescription);
// create collection2item mapping
is.getCollection().addItem(item);
// create date.available
// set in_archive=true
item.setArchived(true);
// save changes ;-)
item.update();
// add item to search and browse indices
DSIndexer.indexItem(c, item);
- Browse.itemAdded(c, item);
+ // item.update() above adds item to browse indices
+ //Browse.itemChanged(c, item);
// remove in-progress submission
is.deleteWrapper();
// remove the submit authorization policies
// and replace them with the collection's READ
// policies
// FIXME: this is an inelegant hack, but out of time!
TableRowIterator tri = DatabaseManager.query(c,
"resourcepolicy",
"SELECT * FROM resourcepolicy WHERE " +
"resource_type_id=" + Constants.COLLECTION + " AND " +
"resource_id=" + is.getCollection().getID() + " AND " +
"action_id=" + Constants.READ );
item.replaceAllPolicies(tri);
return item;
}
/** generate provenance-worthy description of the bitstreams
* contained in an item
*/
public static String getBitstreamProvenanceMessage(Item myitem)
{
// Get non-internal format bitstreams
Bitstream[] bitstreams = myitem.getNonInternalBitstreams();
// Create provenance description
String mymessage = "No. of bitstreams: " + bitstreams.length + "\n";
// Add sizes and checksums of bitstreams
for (int j = 0; j < bitstreams.length; j++)
{
mymessage = mymessage + bitstreams[j].getName() + ": " +
bitstreams[j].getSize() + " bytes, checksum: " +
bitstreams[j].getChecksum() + " (" +
bitstreams[j].getChecksumAlgorithm() + ")\n";
}
return mymessage;
}
}
| true | true | public static Item installItem(Context c, InProgressSubmission is, EPerson e)
throws SQLException, IOException, AuthorizeException
{
Item item = is.getItem();
// create accession date
DCDate now = DCDate.getCurrent();
item.addDC("date", "accessioned", null, now.toString());
item.addDC("date", "available", null, now.toString());
// create issue date if not present
DCValue[] currentDateIssued = item.getDC("date", "issued", null);
if(currentDateIssued.length == 0)
{
item.addDC("date", "issued", null, now.toString());
}
// create handle
String handle = HandleManager.createHandle(c, item);
// Add handle as identifier.uri DC value
item.addDC("identifier", "uri", null, handle);
// Add format.mimetype and format.extent DC values
Bitstream[] bitstreams = item.getNonInternalBitstreams();
for (int i = 0; i < bitstreams.length; i++)
{
BitstreamFormat bf = bitstreams[i].getFormat();
item.addDC("format",
"extent",
null,
String.valueOf(bitstreams[i].getSize()));
item.addDC("format", "mimetype", null, bf.getMIMEType());
}
String provDescription = "Made available in DSpace on " + now +
" (GMT). " + getBitstreamProvenanceMessage(item);
if (currentDateIssued.length != 0)
{
DCDate d = new DCDate(currentDateIssued[0].value);
provDescription = provDescription + " Previous issue date: " +
d.toString();
}
// Add provenance description
item.addDC("description", "provenance", "en", provDescription);
// create collection2item mapping
is.getCollection().addItem(item);
// create date.available
// set in_archive=true
item.setArchived(true);
// save changes ;-)
item.update();
// add item to search and browse indices
DSIndexer.indexItem(c, item);
Browse.itemAdded(c, item);
// remove in-progress submission
is.deleteWrapper();
// remove the submit authorization policies
// and replace them with the collection's READ
// policies
// FIXME: this is an inelegant hack, but out of time!
TableRowIterator tri = DatabaseManager.query(c,
"resourcepolicy",
"SELECT * FROM resourcepolicy WHERE " +
"resource_type_id=" + Constants.COLLECTION + " AND " +
"resource_id=" + is.getCollection().getID() + " AND " +
"action_id=" + Constants.READ );
item.replaceAllPolicies(tri);
return item;
}
| public static Item installItem(Context c, InProgressSubmission is, EPerson e)
throws SQLException, IOException, AuthorizeException
{
Item item = is.getItem();
// create accession date
DCDate now = DCDate.getCurrent();
item.addDC("date", "accessioned", null, now.toString());
item.addDC("date", "available", null, now.toString());
// create issue date if not present
DCValue[] currentDateIssued = item.getDC("date", "issued", null);
if(currentDateIssued.length == 0)
{
item.addDC("date", "issued", null, now.toString());
}
// create handle
String handle = HandleManager.createHandle(c, item);
// Add handle as identifier.uri DC value
item.addDC("identifier", "uri", null, handle);
// Add format.mimetype and format.extent DC values
Bitstream[] bitstreams = item.getNonInternalBitstreams();
for (int i = 0; i < bitstreams.length; i++)
{
BitstreamFormat bf = bitstreams[i].getFormat();
item.addDC("format",
"extent",
null,
String.valueOf(bitstreams[i].getSize()));
item.addDC("format", "mimetype", null, bf.getMIMEType());
}
String provDescription = "Made available in DSpace on " + now +
" (GMT). " + getBitstreamProvenanceMessage(item);
if (currentDateIssued.length != 0)
{
DCDate d = new DCDate(currentDateIssued[0].value);
provDescription = provDescription + " Previous issue date: " +
d.toString();
}
// Add provenance description
item.addDC("description", "provenance", "en", provDescription);
// create collection2item mapping
is.getCollection().addItem(item);
// create date.available
// set in_archive=true
item.setArchived(true);
// save changes ;-)
item.update();
// add item to search and browse indices
DSIndexer.indexItem(c, item);
// item.update() above adds item to browse indices
//Browse.itemChanged(c, item);
// remove in-progress submission
is.deleteWrapper();
// remove the submit authorization policies
// and replace them with the collection's READ
// policies
// FIXME: this is an inelegant hack, but out of time!
TableRowIterator tri = DatabaseManager.query(c,
"resourcepolicy",
"SELECT * FROM resourcepolicy WHERE " +
"resource_type_id=" + Constants.COLLECTION + " AND " +
"resource_id=" + is.getCollection().getID() + " AND " +
"action_id=" + Constants.READ );
item.replaceAllPolicies(tri);
return item;
}
|
diff --git a/modules/grouping/src/test/org/apache/lucene/search/grouping/AllGroupsCollectorTest.java b/modules/grouping/src/test/org/apache/lucene/search/grouping/AllGroupsCollectorTest.java
index 00153e7f9..cff33202d 100644
--- a/modules/grouping/src/test/org/apache/lucene/search/grouping/AllGroupsCollectorTest.java
+++ b/modules/grouping/src/test/org/apache/lucene/search/grouping/AllGroupsCollectorTest.java
@@ -1,109 +1,109 @@
package org.apache.lucene.search.grouping;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.LuceneTestCase;
public class AllGroupsCollectorTest extends LuceneTestCase {
public void testTotalGroupCount() throws Exception {
final String groupField = "author";
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(
random,
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random)).setMergePolicy(newLogMergePolicy()));
// 0
Document doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "1", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 1
doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random text blob", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "2", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 2
doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random textual data", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "3", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
w.commit(); // To ensure a second segment
// 3
doc = new Document();
doc.add(new Field(groupField, "author2", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "4", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 4
doc = new Document();
doc.add(new Field(groupField, "author3", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "5", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 5
doc = new Document();
doc.add(new Field(groupField, "author3", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "random blob", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "6", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 6 -- no author field
doc = new Document();
doc.add(new Field("content", "random word stuck in alot of other text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "6", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
IndexSearcher indexSearcher = new IndexSearcher(w.getReader());
w.close();
- AllGroupsCollector c1 = new AllGroupsCollector(groupField);
+ TermAllGroupsCollector c1 = new TermAllGroupsCollector(groupField);
indexSearcher.search(new TermQuery(new Term("content", "random")), c1);
assertEquals(4, c1.getGroupCount());
- AllGroupsCollector c2 = new AllGroupsCollector(groupField);
+ TermAllGroupsCollector c2 = new TermAllGroupsCollector(groupField);
indexSearcher.search(new TermQuery(new Term("content", "some")), c2);
assertEquals(3, c2.getGroupCount());
- AllGroupsCollector c3 = new AllGroupsCollector(groupField);
+ TermAllGroupsCollector c3 = new TermAllGroupsCollector(groupField);
indexSearcher.search(new TermQuery(new Term("content", "blob")), c3);
assertEquals(2, c3.getGroupCount());
indexSearcher.getIndexReader().close();
dir.close();
}
}
| false | true | public void testTotalGroupCount() throws Exception {
final String groupField = "author";
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(
random,
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random)).setMergePolicy(newLogMergePolicy()));
// 0
Document doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "1", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 1
doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random text blob", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "2", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 2
doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random textual data", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "3", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
w.commit(); // To ensure a second segment
// 3
doc = new Document();
doc.add(new Field(groupField, "author2", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "4", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 4
doc = new Document();
doc.add(new Field(groupField, "author3", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "5", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 5
doc = new Document();
doc.add(new Field(groupField, "author3", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "random blob", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "6", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 6 -- no author field
doc = new Document();
doc.add(new Field("content", "random word stuck in alot of other text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "6", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
IndexSearcher indexSearcher = new IndexSearcher(w.getReader());
w.close();
AllGroupsCollector c1 = new AllGroupsCollector(groupField);
indexSearcher.search(new TermQuery(new Term("content", "random")), c1);
assertEquals(4, c1.getGroupCount());
AllGroupsCollector c2 = new AllGroupsCollector(groupField);
indexSearcher.search(new TermQuery(new Term("content", "some")), c2);
assertEquals(3, c2.getGroupCount());
AllGroupsCollector c3 = new AllGroupsCollector(groupField);
indexSearcher.search(new TermQuery(new Term("content", "blob")), c3);
assertEquals(2, c3.getGroupCount());
indexSearcher.getIndexReader().close();
dir.close();
}
| public void testTotalGroupCount() throws Exception {
final String groupField = "author";
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(
random,
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random)).setMergePolicy(newLogMergePolicy()));
// 0
Document doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "1", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 1
doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random text blob", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "2", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 2
doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random textual data", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "3", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
w.commit(); // To ensure a second segment
// 3
doc = new Document();
doc.add(new Field(groupField, "author2", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "4", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 4
doc = new Document();
doc.add(new Field(groupField, "author3", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "5", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 5
doc = new Document();
doc.add(new Field(groupField, "author3", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "random blob", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "6", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 6 -- no author field
doc = new Document();
doc.add(new Field("content", "random word stuck in alot of other text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "6", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
IndexSearcher indexSearcher = new IndexSearcher(w.getReader());
w.close();
TermAllGroupsCollector c1 = new TermAllGroupsCollector(groupField);
indexSearcher.search(new TermQuery(new Term("content", "random")), c1);
assertEquals(4, c1.getGroupCount());
TermAllGroupsCollector c2 = new TermAllGroupsCollector(groupField);
indexSearcher.search(new TermQuery(new Term("content", "some")), c2);
assertEquals(3, c2.getGroupCount());
TermAllGroupsCollector c3 = new TermAllGroupsCollector(groupField);
indexSearcher.search(new TermQuery(new Term("content", "blob")), c3);
assertEquals(2, c3.getGroupCount());
indexSearcher.getIndexReader().close();
dir.close();
}
|
diff --git a/viewer/src/main/java/nl/b3p/viewer/image/CombineStaticImageUrl.java b/viewer/src/main/java/nl/b3p/viewer/image/CombineStaticImageUrl.java
index c65665f0c..4272ebac1 100644
--- a/viewer/src/main/java/nl/b3p/viewer/image/CombineStaticImageUrl.java
+++ b/viewer/src/main/java/nl/b3p/viewer/image/CombineStaticImageUrl.java
@@ -1,100 +1,100 @@
/*
* Copyright (C) 2012-2013 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.viewer.image;
/**
*
* @author Roy Braam
*/
public class CombineStaticImageUrl extends CombineImageUrl{
private Bbox bbox;
private Integer x;
private Integer y;
private Integer width;
private Integer height;
public CombineStaticImageUrl(){}
private CombineStaticImageUrl(CombineStaticImageUrl csiu) {
super(csiu);
this.bbox= new Bbox(csiu.bbox);
this.x=csiu.getX();
this.y=csiu.getY();
this.width=csiu.getWidth();
this.height=csiu.getHeight();
}
@Override
public CombineImageUrl calculateNewUrl(ImageBbox imbbox) {
CombineStaticImageUrl csiu = new CombineStaticImageUrl(this);
double unitsX =imbbox.getUnitsPixelX();
double unitsY =imbbox.getUnitsPixelY();
csiu.width= (int)Math.round(csiu.getBbox().getWidth()/unitsX);
- csiu.height= (int)Math.round(csiu.getBbox().getWidth()/unitsX);
+ csiu.height= (int)Math.round(csiu.getBbox().getHeight()/unitsY);
csiu.x= (int)Math.round((csiu.getBbox().getMinx()-imbbox.getBbox().getMinx())/unitsX);
csiu.y= (int)Math.round((imbbox.getBbox().getMaxy()-csiu.getBbox().getMaxy())/unitsY);
return csiu;
}
//<editor-fold defaultstate="collapsed" desc="Getters/setters">
public Bbox getBbox() {
return bbox;
}
public void setBbox(Bbox bbox) {
this.bbox = bbox;
}
public Integer getX() {
return x;
}
public void setX(Integer x) {
this.x = x;
}
public Integer getY() {
return y;
}
public void setY(Integer y) {
this.y = y;
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
//</editor-fold>
}
| true | true | public CombineImageUrl calculateNewUrl(ImageBbox imbbox) {
CombineStaticImageUrl csiu = new CombineStaticImageUrl(this);
double unitsX =imbbox.getUnitsPixelX();
double unitsY =imbbox.getUnitsPixelY();
csiu.width= (int)Math.round(csiu.getBbox().getWidth()/unitsX);
csiu.height= (int)Math.round(csiu.getBbox().getWidth()/unitsX);
csiu.x= (int)Math.round((csiu.getBbox().getMinx()-imbbox.getBbox().getMinx())/unitsX);
csiu.y= (int)Math.round((imbbox.getBbox().getMaxy()-csiu.getBbox().getMaxy())/unitsY);
return csiu;
}
| public CombineImageUrl calculateNewUrl(ImageBbox imbbox) {
CombineStaticImageUrl csiu = new CombineStaticImageUrl(this);
double unitsX =imbbox.getUnitsPixelX();
double unitsY =imbbox.getUnitsPixelY();
csiu.width= (int)Math.round(csiu.getBbox().getWidth()/unitsX);
csiu.height= (int)Math.round(csiu.getBbox().getHeight()/unitsY);
csiu.x= (int)Math.round((csiu.getBbox().getMinx()-imbbox.getBbox().getMinx())/unitsX);
csiu.y= (int)Math.round((imbbox.getBbox().getMaxy()-csiu.getBbox().getMaxy())/unitsY);
return csiu;
}
|
diff --git a/user/src/com/google/gwt/user/tools/WebAppCreator.java b/user/src/com/google/gwt/user/tools/WebAppCreator.java
index 4b8debc22..7fb8ff2c5 100644
--- a/user/src/com/google/gwt/user/tools/WebAppCreator.java
+++ b/user/src/com/google/gwt/user/tools/WebAppCreator.java
@@ -1,507 +1,511 @@
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.user.tools;
import com.google.gwt.dev.About;
import com.google.gwt.dev.ArgProcessorBase;
import com.google.gwt.dev.Compiler;
import com.google.gwt.dev.DevMode;
import com.google.gwt.dev.GwtVersion;
import com.google.gwt.dev.util.Util;
import com.google.gwt.user.tools.util.ArgHandlerIgnore;
import com.google.gwt.user.tools.util.ArgHandlerOverwrite;
import com.google.gwt.user.tools.util.CreatorUtilities;
import com.google.gwt.util.tools.ArgHandlerExtra;
import com.google.gwt.util.tools.ArgHandlerFlag;
import com.google.gwt.util.tools.ArgHandlerOutDir;
import com.google.gwt.util.tools.ArgHandlerString;
import com.google.gwt.util.tools.Utility;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Creates a GWT application skeleton.
*/
public final class WebAppCreator {
class ArgProcessor extends ArgProcessorBase {
private final class ArgHandlerOutDirExtension extends ArgHandlerOutDir {
@Override
public void setDir(File dir) {
outDir = dir;
}
}
public ArgProcessor() {
registerHandler(new ArgHandlerOverwriteExtension());
registerHandler(new ArgHandlerIgnoreExtension());
registerHandler(new ArgHandlerModuleName());
registerHandler(new ArgHandlerOutDirExtension());
registerHandler(new ArgHandlerNoEclipse());
registerHandler(new ArgHandlerOnlyEclipse());
registerHandler(new ArgHandlerJUnitPath());
registerHandler(new ArgHandlerMaven());
registerHandler(new ArgHandlerNoAnt());
}
@Override
protected String getName() {
return WebAppCreator.class.getName();
}
}
private final class ArgHandlerIgnoreExtension extends ArgHandlerIgnore {
@Override
public boolean setFlag() {
if (overwrite) {
System.err.println("-ignore cannot be used with -overwrite");
return false;
}
ignore = true;
return true;
}
}
private final class ArgHandlerModuleName extends ArgHandlerExtra {
@Override
public boolean addExtraArg(String arg) {
if (moduleName != null) {
System.err.println("Too many arguments.");
return false;
}
if (!CreatorUtilities.isValidModuleName(arg)) {
System.err.println("'"
+ arg
+ "' does not appear to be a valid fully-qualified Java class name.");
return false;
}
moduleName = arg;
return true;
}
@Override
public String getPurpose() {
return "The name of the module to create (e.g. com.example.myapp.MyApp)";
}
@Override
public String[] getTagArgs() {
return new String[] {"moduleName"};
}
@Override
public boolean isRequired() {
return true;
}
}
private final class ArgHandlerNoEclipse extends ArgHandlerFlag {
@Override
public String getPurpose() {
return "Do not generate eclipse files";
}
@Override
public String getTag() {
return "-XnoEclipse";
}
@Override
public boolean isUndocumented() {
return true;
}
@Override
public boolean setFlag() {
noEclipse = true;
return true;
}
}
private final class ArgHandlerOnlyEclipse extends ArgHandlerFlag {
@Override
public String getPurpose() {
return "Generate only eclipse files";
}
@Override
public String getTag() {
return "-XonlyEclipse";
}
@Override
public boolean isUndocumented() {
return true;
}
@Override
public boolean setFlag() {
onlyEclipse = true;
return true;
}
}
private final class ArgHandlerOverwriteExtension extends ArgHandlerOverwrite {
@Override
public boolean setFlag() {
if (ignore) {
System.err.println("-overwrite cannot be used with -ignore");
return false;
}
overwrite = true;
return true;
}
}
private final class ArgHandlerJUnitPath extends ArgHandlerString {
@Override
public String[] getDefaultArgs() {
return null;
}
@Override
public String getPurpose() {
return "Specifies the path to your junit.jar (optional)";
}
@Override
public String getTag() {
return "-junit";
}
@Override
public String[] getTagArgs() {
return new String[] {"pathToJUnitJar"};
}
@Override
public boolean isRequired() {
return false;
}
@Override
public boolean setString(String str) {
File f = new File(str);
if (!f.exists() || !f.isFile()) {
System.err.println("File not found: " + str);
return false;
}
junitPath = str;
return true;
}
}
private final class ArgHandlerMaven extends ArgHandlerFlag {
@Override
public String getPurpose() {
return "Create a maven2 project structure and pom file (default disabled)";
}
@Override
public String getTag() {
return "-maven";
}
@Override
public boolean setFlag() {
maven = true;
return true;
}
}
private final class ArgHandlerNoAnt extends ArgHandlerFlag {
@Override
public String getPurpose() {
return "Do not create an ant configuration file";
}
@Override
public String getTag() {
return "-noant";
}
@Override
public boolean setFlag() {
ant = false;
return true;
}
}
private static final class FileCreator {
private final File destDir;
private final String destName;
private final String sourceName;
public FileCreator(File destDir, String destName, String sourceName) {
this.destDir = destDir;
this.sourceName = sourceName;
this.destName = destName;
}
}
public static void main(String[] args) {
System.exit(doMain(args) ? 0 : 1);
}
protected static boolean doMain(String... args) {
WebAppCreator creator = new WebAppCreator();
ArgProcessor argProcessor = creator.new ArgProcessor();
if (argProcessor.processArgs(args)) {
return creator.run();
}
return false;
}
private boolean ant = true;
private boolean ignore = false;
private boolean maven = false;
private String moduleName;
private boolean noEclipse;
private boolean onlyEclipse;
private File outDir;
private boolean overwrite = false;
private String junitPath = null;
/**
* Create the sample app.
*
* @throws IOException if any disk write fails
* @deprecated as of GWT 2.1, replaced by {@link #doRun(String)}
*/
@Deprecated
protected void doRun() throws IOException {
doRun(Utility.getInstallPath());
}
/**
* Create the sample app.
*
* @param installPath directory containing GWT libraries
* @throws IOException if any disk write fails
*/
protected void doRun(String installPath) throws IOException {
// GWT libraries
String gwtUserPath = installPath + '/' + "gwt-user.jar";
String gwtDevPath = installPath + '/' + "gwt-dev.jar";
+ String gwtValidationPath = installPath + '/' + "validation-api-1.0.0.GA.jar";
+ String gwtValidationSourcesPath = installPath + '/' + "validation-api-1.0.0.GA-sources.jar";
// Public builds generate a DTD reference.
String gwtModuleDtd = "";
GwtVersion gwtVersion = About.getGwtVersionObject();
if (gwtVersion.isNoNagVersion()) {
gwtModuleDtd = "\n<!DOCTYPE module PUBLIC \"-//Google Inc.//DTD Google Web Toolkit "
+ About.getGwtVersionNum()
+ "//EN\" \"http://google-web-toolkit.googlecode.com/svn/tags/"
+ About.getGwtVersionNum()
+ "/distro-source/core/src/gwt-module.dtd\">";
}
// Compute module package and name.
int pos = moduleName.lastIndexOf('.');
String modulePackageName = moduleName.substring(0, pos);
String moduleShortName = moduleName.substring(pos + 1);
// pro-actively let ant user know that this script can also create tests.
if (junitPath == null && !maven) {
System.err.println("Not creating tests because -junit argument was not specified.\n");
}
// Compute module name and directories
String srcFolder = maven ? "src/main/java" : "src";
String testFolder = maven ? "src/test/java" : "test";
String warFolder = maven ? "src/main/webapp" : "war";
File srcDir = Utility.getDirectory(outDir, srcFolder, true);
File warDir = Utility.getDirectory(outDir, warFolder, true);
File webInfDir = Utility.getDirectory(warDir, "WEB-INF", true);
File libDir = Utility.getDirectory(webInfDir, "lib", true);
File moduleDir = Utility.getDirectory(srcDir, modulePackageName.replace(
'.', '/'), true);
File clientDir = Utility.getDirectory(moduleDir, "client", true);
File serverDir = Utility.getDirectory(moduleDir, "server", true);
File sharedDir = Utility.getDirectory(moduleDir, "shared", true);
File moduleTestDir = Utility.getDirectory(outDir, testFolder + "/"
+ modulePackageName.replace('.', '/'), true);
File clientTestDir = Utility.getDirectory(moduleTestDir, "client", true);
// Create a map of replacements
Map<String, String> replacements = new HashMap<String, String>();
replacements.put("@moduleShortName", moduleShortName);
replacements.put("@modulePackageName", modulePackageName);
replacements.put("@moduleName", moduleName);
replacements.put("@clientPackage", modulePackageName + ".client");
replacements.put("@serverPackage", modulePackageName + ".server");
replacements.put("@sharedPackage", modulePackageName + ".shared");
replacements.put("@gwtSdk", installPath);
replacements.put("@gwtUserPath", gwtUserPath);
replacements.put("@gwtDevPath", gwtDevPath);
+ replacements.put("@gwtValidationPath", gwtValidationPath);
+ replacements.put("@gwtValidationSourcesPath", gwtValidationSourcesPath);
replacements.put("@gwtVersion", About.getGwtVersionNum());
replacements.put("@gwtModuleDtd", gwtModuleDtd);
replacements.put("@shellClass", DevMode.class.getName());
replacements.put("@compileClass", Compiler.class.getName());
replacements.put("@startupUrl", moduleShortName + ".html");
replacements.put("@renameTo", moduleShortName.toLowerCase());
replacements.put("@moduleNameJUnit", moduleName + "JUnit");
replacements.put("@srcFolder", srcFolder);
replacements.put("@testFolder", testFolder);
replacements.put("@warFolder", warFolder);
// Add command to copy gwt-servlet-deps.jar into libs, unless this is a
// maven project. Maven projects should include libs as maven dependencies.
String copyServletDeps = "";
if (!maven) {
copyServletDeps = "<copy todir=\"" + warFolder + "/WEB-INF/lib\" "
+ "file=\"${gwt.sdk}/gwt-servlet-deps.jar\" />";
}
replacements.put("@copyServletDeps", copyServletDeps);
// Collect the list of server libs to include on the eclipse classpath.
StringBuilder serverLibs = new StringBuilder();
if (libDir.exists()) {
for (File file : libDir.listFiles()) {
if (file.getName().toLowerCase().endsWith(".jar")) {
serverLibs.append(" <classpathentry kind=\"lib\" path=\"war/WEB-INF/lib/");
serverLibs.append(file.getName());
serverLibs.append("\"/>\n");
}
}
}
replacements.put("@serverClasspathLibs", serverLibs.toString());
String antEclipseRule = "";
if (noEclipse) {
/*
* Generate a rule into the build file that allows for the generation of
* an eclipse project later on. This is primarily for distro samples. This
* is a quick and dirty way to inject a build rule, but it works.
*/
antEclipseRule = "\n\n"
+ " <target name=\"eclipse.generate\" depends=\"libs\" description=\"Generate eclipse project\">\n"
+ " <java failonerror=\"true\" fork=\"true\" classname=\""
+ this.getClass().getName() + "\">\n" + " <classpath>\n"
+ " <path refid=\"project.class.path\"/>\n"
+ " </classpath>\n" + " <arg value=\"-XonlyEclipse\"/>\n"
+ " <arg value=\"-ignore\"/>\n" + " <arg value=\""
+ moduleName + "\"/>\n" + " </java>\n" + " </target>";
} else {
antEclipseRule = "";
}
replacements.put("@antEclipseRule", antEclipseRule);
{
String testTargetsBegin = "";
String testTargetsEnd = "";
String junitJarPath = junitPath;
String eclipseTestDir = "";
if (junitPath != null || maven) {
eclipseTestDir = "\n <classpathentry kind=\"src\" path=\""
+ testFolder + "\"/>";
}
if (junitPath == null) {
testTargetsBegin = "\n<!--"
+ "\n"
+ "Test targets suppressed because -junit argument was not specified when running webAppCreator.\n";
testTargetsEnd = "-->\n";
junitJarPath = "path_to_the_junit_jar";
}
replacements.put("@testTargetsBegin", testTargetsBegin);
replacements.put("@testTargetsEnd", testTargetsEnd);
replacements.put("@junitJar", junitJarPath);
replacements.put("@eclipseTestDir", eclipseTestDir);
}
// Create a list with the files to create
List<FileCreator> files = new ArrayList<FileCreator>();
if (!onlyEclipse) {
files.add(new FileCreator(moduleDir, moduleShortName + ".gwt.xml",
"Module.gwt.xml"));
files.add(new FileCreator(warDir, moduleShortName + ".html",
"AppHtml.html"));
files.add(new FileCreator(warDir, moduleShortName + ".css", "AppCss.css"));
files.add(new FileCreator(webInfDir, "web.xml", "web.xml"));
files.add(new FileCreator(clientDir, moduleShortName + ".java",
"AppClassTemplate.java"));
files.add(new FileCreator(clientDir, "GreetingService.java",
"RpcClientTemplate.java"));
files.add(new FileCreator(clientDir, "GreetingServiceAsync.java",
"RpcAsyncClientTemplate.java"));
files.add(new FileCreator(serverDir, "GreetingServiceImpl.java",
"RpcServerTemplate.java"));
files.add(new FileCreator(sharedDir, "FieldVerifier.java",
"SharedClassTemplate.java"));
if (ant) {
files.add(new FileCreator(outDir, "build.xml", "project.ant.xml"));
}
if (maven) {
files.add(new FileCreator(outDir, "pom.xml", "project.maven.xml"));
}
files.add(new FileCreator(outDir, "README.txt", "README.txt"));
if (junitPath != null || maven) {
// create the test file.
files.add(new FileCreator(moduleTestDir, moduleShortName
+ "JUnit.gwt.xml", "JUnit.gwt.xml"));
files.add(new FileCreator(clientTestDir, moduleShortName + "Test"
+ ".java", "JUnitClassTemplate.java"));
}
}
if (!noEclipse) {
files.add(new FileCreator(outDir, ".project", ".project"));
files.add(new FileCreator(outDir, ".classpath", ".classpath"));
files.add(new FileCreator(outDir, moduleShortName + ".launch",
"App.launch"));
if (junitPath != null || maven) {
files.add(new FileCreator(outDir, moduleShortName + "Test-dev.launch",
"JUnit-dev.launch"));
files.add(new FileCreator(outDir, moduleShortName + "Test-prod.launch",
"JUnit-prod.launch"));
}
}
// copy source files, replacing the content as needed
for (FileCreator fileCreator : files) {
URL url = WebAppCreator.class.getResource(fileCreator.sourceName + "src");
if (url == null) {
throw new FileNotFoundException(fileCreator.sourceName + "src");
}
File file = Utility.createNormalFile(fileCreator.destDir,
fileCreator.destName, overwrite, ignore);
if (file != null) {
String data = Util.readURLAsString(url);
Utility.writeTemplateFile(file, data, replacements);
}
}
}
protected boolean run() {
try {
doRun(Utility.getInstallPath());
return true;
} catch (IOException e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
return false;
}
}
}
| false | true | protected void doRun(String installPath) throws IOException {
// GWT libraries
String gwtUserPath = installPath + '/' + "gwt-user.jar";
String gwtDevPath = installPath + '/' + "gwt-dev.jar";
// Public builds generate a DTD reference.
String gwtModuleDtd = "";
GwtVersion gwtVersion = About.getGwtVersionObject();
if (gwtVersion.isNoNagVersion()) {
gwtModuleDtd = "\n<!DOCTYPE module PUBLIC \"-//Google Inc.//DTD Google Web Toolkit "
+ About.getGwtVersionNum()
+ "//EN\" \"http://google-web-toolkit.googlecode.com/svn/tags/"
+ About.getGwtVersionNum()
+ "/distro-source/core/src/gwt-module.dtd\">";
}
// Compute module package and name.
int pos = moduleName.lastIndexOf('.');
String modulePackageName = moduleName.substring(0, pos);
String moduleShortName = moduleName.substring(pos + 1);
// pro-actively let ant user know that this script can also create tests.
if (junitPath == null && !maven) {
System.err.println("Not creating tests because -junit argument was not specified.\n");
}
// Compute module name and directories
String srcFolder = maven ? "src/main/java" : "src";
String testFolder = maven ? "src/test/java" : "test";
String warFolder = maven ? "src/main/webapp" : "war";
File srcDir = Utility.getDirectory(outDir, srcFolder, true);
File warDir = Utility.getDirectory(outDir, warFolder, true);
File webInfDir = Utility.getDirectory(warDir, "WEB-INF", true);
File libDir = Utility.getDirectory(webInfDir, "lib", true);
File moduleDir = Utility.getDirectory(srcDir, modulePackageName.replace(
'.', '/'), true);
File clientDir = Utility.getDirectory(moduleDir, "client", true);
File serverDir = Utility.getDirectory(moduleDir, "server", true);
File sharedDir = Utility.getDirectory(moduleDir, "shared", true);
File moduleTestDir = Utility.getDirectory(outDir, testFolder + "/"
+ modulePackageName.replace('.', '/'), true);
File clientTestDir = Utility.getDirectory(moduleTestDir, "client", true);
// Create a map of replacements
Map<String, String> replacements = new HashMap<String, String>();
replacements.put("@moduleShortName", moduleShortName);
replacements.put("@modulePackageName", modulePackageName);
replacements.put("@moduleName", moduleName);
replacements.put("@clientPackage", modulePackageName + ".client");
replacements.put("@serverPackage", modulePackageName + ".server");
replacements.put("@sharedPackage", modulePackageName + ".shared");
replacements.put("@gwtSdk", installPath);
replacements.put("@gwtUserPath", gwtUserPath);
replacements.put("@gwtDevPath", gwtDevPath);
replacements.put("@gwtVersion", About.getGwtVersionNum());
replacements.put("@gwtModuleDtd", gwtModuleDtd);
replacements.put("@shellClass", DevMode.class.getName());
replacements.put("@compileClass", Compiler.class.getName());
replacements.put("@startupUrl", moduleShortName + ".html");
replacements.put("@renameTo", moduleShortName.toLowerCase());
replacements.put("@moduleNameJUnit", moduleName + "JUnit");
replacements.put("@srcFolder", srcFolder);
replacements.put("@testFolder", testFolder);
replacements.put("@warFolder", warFolder);
// Add command to copy gwt-servlet-deps.jar into libs, unless this is a
// maven project. Maven projects should include libs as maven dependencies.
String copyServletDeps = "";
if (!maven) {
copyServletDeps = "<copy todir=\"" + warFolder + "/WEB-INF/lib\" "
+ "file=\"${gwt.sdk}/gwt-servlet-deps.jar\" />";
}
replacements.put("@copyServletDeps", copyServletDeps);
// Collect the list of server libs to include on the eclipse classpath.
StringBuilder serverLibs = new StringBuilder();
if (libDir.exists()) {
for (File file : libDir.listFiles()) {
if (file.getName().toLowerCase().endsWith(".jar")) {
serverLibs.append(" <classpathentry kind=\"lib\" path=\"war/WEB-INF/lib/");
serverLibs.append(file.getName());
serverLibs.append("\"/>\n");
}
}
}
replacements.put("@serverClasspathLibs", serverLibs.toString());
String antEclipseRule = "";
if (noEclipse) {
/*
* Generate a rule into the build file that allows for the generation of
* an eclipse project later on. This is primarily for distro samples. This
* is a quick and dirty way to inject a build rule, but it works.
*/
antEclipseRule = "\n\n"
+ " <target name=\"eclipse.generate\" depends=\"libs\" description=\"Generate eclipse project\">\n"
+ " <java failonerror=\"true\" fork=\"true\" classname=\""
+ this.getClass().getName() + "\">\n" + " <classpath>\n"
+ " <path refid=\"project.class.path\"/>\n"
+ " </classpath>\n" + " <arg value=\"-XonlyEclipse\"/>\n"
+ " <arg value=\"-ignore\"/>\n" + " <arg value=\""
+ moduleName + "\"/>\n" + " </java>\n" + " </target>";
} else {
antEclipseRule = "";
}
replacements.put("@antEclipseRule", antEclipseRule);
{
String testTargetsBegin = "";
String testTargetsEnd = "";
String junitJarPath = junitPath;
String eclipseTestDir = "";
if (junitPath != null || maven) {
eclipseTestDir = "\n <classpathentry kind=\"src\" path=\""
+ testFolder + "\"/>";
}
if (junitPath == null) {
testTargetsBegin = "\n<!--"
+ "\n"
+ "Test targets suppressed because -junit argument was not specified when running webAppCreator.\n";
testTargetsEnd = "-->\n";
junitJarPath = "path_to_the_junit_jar";
}
replacements.put("@testTargetsBegin", testTargetsBegin);
replacements.put("@testTargetsEnd", testTargetsEnd);
replacements.put("@junitJar", junitJarPath);
replacements.put("@eclipseTestDir", eclipseTestDir);
}
// Create a list with the files to create
List<FileCreator> files = new ArrayList<FileCreator>();
if (!onlyEclipse) {
files.add(new FileCreator(moduleDir, moduleShortName + ".gwt.xml",
"Module.gwt.xml"));
files.add(new FileCreator(warDir, moduleShortName + ".html",
"AppHtml.html"));
files.add(new FileCreator(warDir, moduleShortName + ".css", "AppCss.css"));
files.add(new FileCreator(webInfDir, "web.xml", "web.xml"));
files.add(new FileCreator(clientDir, moduleShortName + ".java",
"AppClassTemplate.java"));
files.add(new FileCreator(clientDir, "GreetingService.java",
"RpcClientTemplate.java"));
files.add(new FileCreator(clientDir, "GreetingServiceAsync.java",
"RpcAsyncClientTemplate.java"));
files.add(new FileCreator(serverDir, "GreetingServiceImpl.java",
"RpcServerTemplate.java"));
files.add(new FileCreator(sharedDir, "FieldVerifier.java",
"SharedClassTemplate.java"));
if (ant) {
files.add(new FileCreator(outDir, "build.xml", "project.ant.xml"));
}
if (maven) {
files.add(new FileCreator(outDir, "pom.xml", "project.maven.xml"));
}
files.add(new FileCreator(outDir, "README.txt", "README.txt"));
if (junitPath != null || maven) {
// create the test file.
files.add(new FileCreator(moduleTestDir, moduleShortName
+ "JUnit.gwt.xml", "JUnit.gwt.xml"));
files.add(new FileCreator(clientTestDir, moduleShortName + "Test"
+ ".java", "JUnitClassTemplate.java"));
}
}
if (!noEclipse) {
files.add(new FileCreator(outDir, ".project", ".project"));
files.add(new FileCreator(outDir, ".classpath", ".classpath"));
files.add(new FileCreator(outDir, moduleShortName + ".launch",
"App.launch"));
if (junitPath != null || maven) {
files.add(new FileCreator(outDir, moduleShortName + "Test-dev.launch",
"JUnit-dev.launch"));
files.add(new FileCreator(outDir, moduleShortName + "Test-prod.launch",
"JUnit-prod.launch"));
}
}
// copy source files, replacing the content as needed
for (FileCreator fileCreator : files) {
URL url = WebAppCreator.class.getResource(fileCreator.sourceName + "src");
if (url == null) {
throw new FileNotFoundException(fileCreator.sourceName + "src");
}
File file = Utility.createNormalFile(fileCreator.destDir,
fileCreator.destName, overwrite, ignore);
if (file != null) {
String data = Util.readURLAsString(url);
Utility.writeTemplateFile(file, data, replacements);
}
}
}
| protected void doRun(String installPath) throws IOException {
// GWT libraries
String gwtUserPath = installPath + '/' + "gwt-user.jar";
String gwtDevPath = installPath + '/' + "gwt-dev.jar";
String gwtValidationPath = installPath + '/' + "validation-api-1.0.0.GA.jar";
String gwtValidationSourcesPath = installPath + '/' + "validation-api-1.0.0.GA-sources.jar";
// Public builds generate a DTD reference.
String gwtModuleDtd = "";
GwtVersion gwtVersion = About.getGwtVersionObject();
if (gwtVersion.isNoNagVersion()) {
gwtModuleDtd = "\n<!DOCTYPE module PUBLIC \"-//Google Inc.//DTD Google Web Toolkit "
+ About.getGwtVersionNum()
+ "//EN\" \"http://google-web-toolkit.googlecode.com/svn/tags/"
+ About.getGwtVersionNum()
+ "/distro-source/core/src/gwt-module.dtd\">";
}
// Compute module package and name.
int pos = moduleName.lastIndexOf('.');
String modulePackageName = moduleName.substring(0, pos);
String moduleShortName = moduleName.substring(pos + 1);
// pro-actively let ant user know that this script can also create tests.
if (junitPath == null && !maven) {
System.err.println("Not creating tests because -junit argument was not specified.\n");
}
// Compute module name and directories
String srcFolder = maven ? "src/main/java" : "src";
String testFolder = maven ? "src/test/java" : "test";
String warFolder = maven ? "src/main/webapp" : "war";
File srcDir = Utility.getDirectory(outDir, srcFolder, true);
File warDir = Utility.getDirectory(outDir, warFolder, true);
File webInfDir = Utility.getDirectory(warDir, "WEB-INF", true);
File libDir = Utility.getDirectory(webInfDir, "lib", true);
File moduleDir = Utility.getDirectory(srcDir, modulePackageName.replace(
'.', '/'), true);
File clientDir = Utility.getDirectory(moduleDir, "client", true);
File serverDir = Utility.getDirectory(moduleDir, "server", true);
File sharedDir = Utility.getDirectory(moduleDir, "shared", true);
File moduleTestDir = Utility.getDirectory(outDir, testFolder + "/"
+ modulePackageName.replace('.', '/'), true);
File clientTestDir = Utility.getDirectory(moduleTestDir, "client", true);
// Create a map of replacements
Map<String, String> replacements = new HashMap<String, String>();
replacements.put("@moduleShortName", moduleShortName);
replacements.put("@modulePackageName", modulePackageName);
replacements.put("@moduleName", moduleName);
replacements.put("@clientPackage", modulePackageName + ".client");
replacements.put("@serverPackage", modulePackageName + ".server");
replacements.put("@sharedPackage", modulePackageName + ".shared");
replacements.put("@gwtSdk", installPath);
replacements.put("@gwtUserPath", gwtUserPath);
replacements.put("@gwtDevPath", gwtDevPath);
replacements.put("@gwtValidationPath", gwtValidationPath);
replacements.put("@gwtValidationSourcesPath", gwtValidationSourcesPath);
replacements.put("@gwtVersion", About.getGwtVersionNum());
replacements.put("@gwtModuleDtd", gwtModuleDtd);
replacements.put("@shellClass", DevMode.class.getName());
replacements.put("@compileClass", Compiler.class.getName());
replacements.put("@startupUrl", moduleShortName + ".html");
replacements.put("@renameTo", moduleShortName.toLowerCase());
replacements.put("@moduleNameJUnit", moduleName + "JUnit");
replacements.put("@srcFolder", srcFolder);
replacements.put("@testFolder", testFolder);
replacements.put("@warFolder", warFolder);
// Add command to copy gwt-servlet-deps.jar into libs, unless this is a
// maven project. Maven projects should include libs as maven dependencies.
String copyServletDeps = "";
if (!maven) {
copyServletDeps = "<copy todir=\"" + warFolder + "/WEB-INF/lib\" "
+ "file=\"${gwt.sdk}/gwt-servlet-deps.jar\" />";
}
replacements.put("@copyServletDeps", copyServletDeps);
// Collect the list of server libs to include on the eclipse classpath.
StringBuilder serverLibs = new StringBuilder();
if (libDir.exists()) {
for (File file : libDir.listFiles()) {
if (file.getName().toLowerCase().endsWith(".jar")) {
serverLibs.append(" <classpathentry kind=\"lib\" path=\"war/WEB-INF/lib/");
serverLibs.append(file.getName());
serverLibs.append("\"/>\n");
}
}
}
replacements.put("@serverClasspathLibs", serverLibs.toString());
String antEclipseRule = "";
if (noEclipse) {
/*
* Generate a rule into the build file that allows for the generation of
* an eclipse project later on. This is primarily for distro samples. This
* is a quick and dirty way to inject a build rule, but it works.
*/
antEclipseRule = "\n\n"
+ " <target name=\"eclipse.generate\" depends=\"libs\" description=\"Generate eclipse project\">\n"
+ " <java failonerror=\"true\" fork=\"true\" classname=\""
+ this.getClass().getName() + "\">\n" + " <classpath>\n"
+ " <path refid=\"project.class.path\"/>\n"
+ " </classpath>\n" + " <arg value=\"-XonlyEclipse\"/>\n"
+ " <arg value=\"-ignore\"/>\n" + " <arg value=\""
+ moduleName + "\"/>\n" + " </java>\n" + " </target>";
} else {
antEclipseRule = "";
}
replacements.put("@antEclipseRule", antEclipseRule);
{
String testTargetsBegin = "";
String testTargetsEnd = "";
String junitJarPath = junitPath;
String eclipseTestDir = "";
if (junitPath != null || maven) {
eclipseTestDir = "\n <classpathentry kind=\"src\" path=\""
+ testFolder + "\"/>";
}
if (junitPath == null) {
testTargetsBegin = "\n<!--"
+ "\n"
+ "Test targets suppressed because -junit argument was not specified when running webAppCreator.\n";
testTargetsEnd = "-->\n";
junitJarPath = "path_to_the_junit_jar";
}
replacements.put("@testTargetsBegin", testTargetsBegin);
replacements.put("@testTargetsEnd", testTargetsEnd);
replacements.put("@junitJar", junitJarPath);
replacements.put("@eclipseTestDir", eclipseTestDir);
}
// Create a list with the files to create
List<FileCreator> files = new ArrayList<FileCreator>();
if (!onlyEclipse) {
files.add(new FileCreator(moduleDir, moduleShortName + ".gwt.xml",
"Module.gwt.xml"));
files.add(new FileCreator(warDir, moduleShortName + ".html",
"AppHtml.html"));
files.add(new FileCreator(warDir, moduleShortName + ".css", "AppCss.css"));
files.add(new FileCreator(webInfDir, "web.xml", "web.xml"));
files.add(new FileCreator(clientDir, moduleShortName + ".java",
"AppClassTemplate.java"));
files.add(new FileCreator(clientDir, "GreetingService.java",
"RpcClientTemplate.java"));
files.add(new FileCreator(clientDir, "GreetingServiceAsync.java",
"RpcAsyncClientTemplate.java"));
files.add(new FileCreator(serverDir, "GreetingServiceImpl.java",
"RpcServerTemplate.java"));
files.add(new FileCreator(sharedDir, "FieldVerifier.java",
"SharedClassTemplate.java"));
if (ant) {
files.add(new FileCreator(outDir, "build.xml", "project.ant.xml"));
}
if (maven) {
files.add(new FileCreator(outDir, "pom.xml", "project.maven.xml"));
}
files.add(new FileCreator(outDir, "README.txt", "README.txt"));
if (junitPath != null || maven) {
// create the test file.
files.add(new FileCreator(moduleTestDir, moduleShortName
+ "JUnit.gwt.xml", "JUnit.gwt.xml"));
files.add(new FileCreator(clientTestDir, moduleShortName + "Test"
+ ".java", "JUnitClassTemplate.java"));
}
}
if (!noEclipse) {
files.add(new FileCreator(outDir, ".project", ".project"));
files.add(new FileCreator(outDir, ".classpath", ".classpath"));
files.add(new FileCreator(outDir, moduleShortName + ".launch",
"App.launch"));
if (junitPath != null || maven) {
files.add(new FileCreator(outDir, moduleShortName + "Test-dev.launch",
"JUnit-dev.launch"));
files.add(new FileCreator(outDir, moduleShortName + "Test-prod.launch",
"JUnit-prod.launch"));
}
}
// copy source files, replacing the content as needed
for (FileCreator fileCreator : files) {
URL url = WebAppCreator.class.getResource(fileCreator.sourceName + "src");
if (url == null) {
throw new FileNotFoundException(fileCreator.sourceName + "src");
}
File file = Utility.createNormalFile(fileCreator.destDir,
fileCreator.destName, overwrite, ignore);
if (file != null) {
String data = Util.readURLAsString(url);
Utility.writeTemplateFile(file, data, replacements);
}
}
}
|
diff --git a/deployables/serviceengines/servicemix-jsr181/src/main/java/org/apache/servicemix/jsr181/Jsr181ExchangeProcessor.java b/deployables/serviceengines/servicemix-jsr181/src/main/java/org/apache/servicemix/jsr181/Jsr181ExchangeProcessor.java
index d9de080f6..997e5655e 100644
--- a/deployables/serviceengines/servicemix-jsr181/src/main/java/org/apache/servicemix/jsr181/Jsr181ExchangeProcessor.java
+++ b/deployables/serviceengines/servicemix-jsr181/src/main/java/org/apache/servicemix/jsr181/Jsr181ExchangeProcessor.java
@@ -1,166 +1,167 @@
/*
* 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.servicemix.jsr181;
import java.io.ByteArrayOutputStream;
import java.util.Iterator;
import javax.activation.DataHandler;
import javax.jbi.messaging.DeliveryChannel;
import javax.jbi.messaging.ExchangeStatus;
import javax.jbi.messaging.Fault;
import javax.jbi.messaging.InOptionalOut;
import javax.jbi.messaging.InOut;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.NormalizedMessage;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import org.apache.servicemix.JbiConstants;
import org.apache.servicemix.common.ExchangeProcessor;
import org.apache.servicemix.jbi.jaxp.StAXSourceTransformer;
import org.apache.servicemix.jbi.jaxp.StringSource;
import org.apache.servicemix.jsr181.xfire.JbiTransport;
import org.codehaus.xfire.MessageContext;
import org.codehaus.xfire.XFire;
import org.codehaus.xfire.attachments.Attachment;
import org.codehaus.xfire.attachments.Attachments;
import org.codehaus.xfire.attachments.JavaMailAttachments;
import org.codehaus.xfire.attachments.SimpleAttachment;
import org.codehaus.xfire.exchange.InMessage;
import org.codehaus.xfire.fault.XFireFault;
import org.codehaus.xfire.service.OperationInfo;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.transport.Channel;
import org.codehaus.xfire.transport.Transport;
public class Jsr181ExchangeProcessor implements ExchangeProcessor {
public static final String SOAP_FAULT_CODE = "org.apache.servicemix.soap.fault.code";
public static final String SOAP_FAULT_SUBCODE = "org.apache.servicemix.soap.fault.subcode";
public static final String SOAP_FAULT_REASON = "org.apache.servicemix.soap.fault.reason";
public static final String SOAP_FAULT_NODE = "org.apache.servicemix.soap.fault.node";
public static final String SOAP_FAULT_ROLE = "org.apache.servicemix.soap.fault.role";
protected DeliveryChannel channel;
protected Jsr181Endpoint endpoint;
protected StAXSourceTransformer transformer;
public Jsr181ExchangeProcessor(Jsr181Endpoint endpoint) {
this.endpoint = endpoint;
this.transformer = new StAXSourceTransformer();
}
public void process(MessageExchange exchange) throws Exception {
if (exchange.getStatus() == ExchangeStatus.DONE) {
return;
} else if (exchange.getStatus() == ExchangeStatus.ERROR) {
return;
}
// TODO: clean this code
XFire xfire = endpoint.getXFire();
Service service = endpoint.getXFireService();
Transport t = xfire.getTransportManager().getTransport(JbiTransport.JBI_BINDING);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Channel c = t.createChannel();
MessageContext ctx = new MessageContext();
ctx.setXFire(xfire);
ctx.setService(service);
ctx.setProperty(Channel.BACKCHANNEL_URI, out);
ctx.setExchange(new org.codehaus.xfire.exchange.MessageExchange(ctx));
InMessage msg = new InMessage();
ctx.getExchange().setInMessage(msg);
if (exchange.getOperation() != null) {
OperationInfo op = service.getServiceInfo().getOperation(exchange.getOperation().getLocalPart());
if (op != null) {
ctx.getExchange().setOperation(op);
}
}
ctx.setCurrentMessage(msg);
NormalizedMessage in = exchange.getMessage("in");
msg.setXMLStreamReader(getXMLStreamReader(in.getContent()));
if (in.getAttachmentNames() != null && in.getAttachmentNames().size() > 0) {
JavaMailAttachments attachments = new JavaMailAttachments();
for (Iterator it = in.getAttachmentNames().iterator(); it.hasNext();) {
String name = (String) it.next();
DataHandler dh = in.getAttachment(name);
attachments.addPart(new SimpleAttachment(name, dh));
}
msg.setAttachments(attachments);
}
JBIContext.setMessageExchange(exchange);
try {
c.receive(ctx, msg);
} finally {
JBIContext.setMessageExchange(null);
}
c.close();
// Set response or DONE status
if (isInAndOut(exchange)) {
- String charSet = ctx.getOutMessage().getEncoding();
if (ctx.getExchange().hasFaultMessage() && ctx.getExchange().getFaultMessage().getBody() != null) {
+ String charSet = ctx.getExchange().getFaultMessage().getEncoding();
Fault fault = exchange.createFault();
fault.setContent(new StringSource(out.toString(charSet)));
XFireFault xFault = (XFireFault) ctx.getExchange().getFaultMessage().getBody();
fault.setProperty(SOAP_FAULT_CODE, xFault.getFaultCode());
fault.setProperty(SOAP_FAULT_REASON, xFault.getReason());
fault.setProperty(SOAP_FAULT_ROLE, xFault.getRole());
fault.setProperty(SOAP_FAULT_SUBCODE, xFault.getSubCode());
exchange.setFault(fault);
} else {
+ String charSet = ctx.getOutMessage().getEncoding();
NormalizedMessage outMsg = exchange.createMessage();
Attachments attachments = ctx.getCurrentMessage().getAttachments();
if (attachments != null) {
for (Iterator it = attachments.getParts(); it.hasNext();) {
Attachment att = (Attachment) it.next();
outMsg.addAttachment(att.getId(), att.getDataHandler());
}
}
outMsg.setContent(new StringSource(out.toString(charSet)));
exchange.setMessage(outMsg, "out");
}
if (exchange.isTransacted() && Boolean.TRUE.equals(exchange.getProperty(JbiConstants.SEND_SYNC))) {
channel.sendSync(exchange);
} else {
channel.send(exchange);
}
} else {
exchange.setStatus(ExchangeStatus.DONE);
channel.send(exchange);
}
}
public void start() throws Exception {
channel = endpoint.getServiceUnit().getComponent().getComponentContext().getDeliveryChannel();
}
public void stop() throws Exception {
}
protected XMLStreamReader getXMLStreamReader(Source source) throws TransformerException, XMLStreamException {
return transformer.toXMLStreamReader(source);
}
protected boolean isInAndOut(MessageExchange exchange) {
return exchange instanceof InOut || exchange instanceof InOptionalOut;
}
}
| false | true | public void process(MessageExchange exchange) throws Exception {
if (exchange.getStatus() == ExchangeStatus.DONE) {
return;
} else if (exchange.getStatus() == ExchangeStatus.ERROR) {
return;
}
// TODO: clean this code
XFire xfire = endpoint.getXFire();
Service service = endpoint.getXFireService();
Transport t = xfire.getTransportManager().getTransport(JbiTransport.JBI_BINDING);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Channel c = t.createChannel();
MessageContext ctx = new MessageContext();
ctx.setXFire(xfire);
ctx.setService(service);
ctx.setProperty(Channel.BACKCHANNEL_URI, out);
ctx.setExchange(new org.codehaus.xfire.exchange.MessageExchange(ctx));
InMessage msg = new InMessage();
ctx.getExchange().setInMessage(msg);
if (exchange.getOperation() != null) {
OperationInfo op = service.getServiceInfo().getOperation(exchange.getOperation().getLocalPart());
if (op != null) {
ctx.getExchange().setOperation(op);
}
}
ctx.setCurrentMessage(msg);
NormalizedMessage in = exchange.getMessage("in");
msg.setXMLStreamReader(getXMLStreamReader(in.getContent()));
if (in.getAttachmentNames() != null && in.getAttachmentNames().size() > 0) {
JavaMailAttachments attachments = new JavaMailAttachments();
for (Iterator it = in.getAttachmentNames().iterator(); it.hasNext();) {
String name = (String) it.next();
DataHandler dh = in.getAttachment(name);
attachments.addPart(new SimpleAttachment(name, dh));
}
msg.setAttachments(attachments);
}
JBIContext.setMessageExchange(exchange);
try {
c.receive(ctx, msg);
} finally {
JBIContext.setMessageExchange(null);
}
c.close();
// Set response or DONE status
if (isInAndOut(exchange)) {
String charSet = ctx.getOutMessage().getEncoding();
if (ctx.getExchange().hasFaultMessage() && ctx.getExchange().getFaultMessage().getBody() != null) {
Fault fault = exchange.createFault();
fault.setContent(new StringSource(out.toString(charSet)));
XFireFault xFault = (XFireFault) ctx.getExchange().getFaultMessage().getBody();
fault.setProperty(SOAP_FAULT_CODE, xFault.getFaultCode());
fault.setProperty(SOAP_FAULT_REASON, xFault.getReason());
fault.setProperty(SOAP_FAULT_ROLE, xFault.getRole());
fault.setProperty(SOAP_FAULT_SUBCODE, xFault.getSubCode());
exchange.setFault(fault);
} else {
NormalizedMessage outMsg = exchange.createMessage();
Attachments attachments = ctx.getCurrentMessage().getAttachments();
if (attachments != null) {
for (Iterator it = attachments.getParts(); it.hasNext();) {
Attachment att = (Attachment) it.next();
outMsg.addAttachment(att.getId(), att.getDataHandler());
}
}
outMsg.setContent(new StringSource(out.toString(charSet)));
exchange.setMessage(outMsg, "out");
}
if (exchange.isTransacted() && Boolean.TRUE.equals(exchange.getProperty(JbiConstants.SEND_SYNC))) {
channel.sendSync(exchange);
} else {
channel.send(exchange);
}
} else {
exchange.setStatus(ExchangeStatus.DONE);
channel.send(exchange);
}
}
| public void process(MessageExchange exchange) throws Exception {
if (exchange.getStatus() == ExchangeStatus.DONE) {
return;
} else if (exchange.getStatus() == ExchangeStatus.ERROR) {
return;
}
// TODO: clean this code
XFire xfire = endpoint.getXFire();
Service service = endpoint.getXFireService();
Transport t = xfire.getTransportManager().getTransport(JbiTransport.JBI_BINDING);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Channel c = t.createChannel();
MessageContext ctx = new MessageContext();
ctx.setXFire(xfire);
ctx.setService(service);
ctx.setProperty(Channel.BACKCHANNEL_URI, out);
ctx.setExchange(new org.codehaus.xfire.exchange.MessageExchange(ctx));
InMessage msg = new InMessage();
ctx.getExchange().setInMessage(msg);
if (exchange.getOperation() != null) {
OperationInfo op = service.getServiceInfo().getOperation(exchange.getOperation().getLocalPart());
if (op != null) {
ctx.getExchange().setOperation(op);
}
}
ctx.setCurrentMessage(msg);
NormalizedMessage in = exchange.getMessage("in");
msg.setXMLStreamReader(getXMLStreamReader(in.getContent()));
if (in.getAttachmentNames() != null && in.getAttachmentNames().size() > 0) {
JavaMailAttachments attachments = new JavaMailAttachments();
for (Iterator it = in.getAttachmentNames().iterator(); it.hasNext();) {
String name = (String) it.next();
DataHandler dh = in.getAttachment(name);
attachments.addPart(new SimpleAttachment(name, dh));
}
msg.setAttachments(attachments);
}
JBIContext.setMessageExchange(exchange);
try {
c.receive(ctx, msg);
} finally {
JBIContext.setMessageExchange(null);
}
c.close();
// Set response or DONE status
if (isInAndOut(exchange)) {
if (ctx.getExchange().hasFaultMessage() && ctx.getExchange().getFaultMessage().getBody() != null) {
String charSet = ctx.getExchange().getFaultMessage().getEncoding();
Fault fault = exchange.createFault();
fault.setContent(new StringSource(out.toString(charSet)));
XFireFault xFault = (XFireFault) ctx.getExchange().getFaultMessage().getBody();
fault.setProperty(SOAP_FAULT_CODE, xFault.getFaultCode());
fault.setProperty(SOAP_FAULT_REASON, xFault.getReason());
fault.setProperty(SOAP_FAULT_ROLE, xFault.getRole());
fault.setProperty(SOAP_FAULT_SUBCODE, xFault.getSubCode());
exchange.setFault(fault);
} else {
String charSet = ctx.getOutMessage().getEncoding();
NormalizedMessage outMsg = exchange.createMessage();
Attachments attachments = ctx.getCurrentMessage().getAttachments();
if (attachments != null) {
for (Iterator it = attachments.getParts(); it.hasNext();) {
Attachment att = (Attachment) it.next();
outMsg.addAttachment(att.getId(), att.getDataHandler());
}
}
outMsg.setContent(new StringSource(out.toString(charSet)));
exchange.setMessage(outMsg, "out");
}
if (exchange.isTransacted() && Boolean.TRUE.equals(exchange.getProperty(JbiConstants.SEND_SYNC))) {
channel.sendSync(exchange);
} else {
channel.send(exchange);
}
} else {
exchange.setStatus(ExchangeStatus.DONE);
channel.send(exchange);
}
}
|
diff --git a/CheapTrick/src/com/zappos/ct/tests/Works10_Test.java b/CheapTrick/src/com/zappos/ct/tests/Works10_Test.java
index 06e2983..cb16d04 100755
--- a/CheapTrick/src/com/zappos/ct/tests/Works10_Test.java
+++ b/CheapTrick/src/com/zappos/ct/tests/Works10_Test.java
@@ -1,42 +1,42 @@
package com.zappos.ct.tests;
import com.zappos.ct.SeleniumBase;
import com.zappos.ct.ScreenshotListener;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
//@Listeners(ScreenshotListener.class)
public class Works10_Test extends SeleniumBase {
@Test
public void HomePageTest() throws Exception {
- WebDriver drive10r = getDriver();
+ WebDriver driver = getDriver();
Thread.sleep(2000);
driver.get("http://www.zappos.com");
WebElement element = driver.findElement(By.name("term"));
element.sendKeys("Green Shoes");
element.submit();
/* (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("green shoes");
}
});*/
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
}
| true | true | public void HomePageTest() throws Exception {
WebDriver drive10r = getDriver();
Thread.sleep(2000);
driver.get("http://www.zappos.com");
WebElement element = driver.findElement(By.name("term"));
element.sendKeys("Green Shoes");
element.submit();
/* (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("green shoes");
}
});*/
| public void HomePageTest() throws Exception {
WebDriver driver = getDriver();
Thread.sleep(2000);
driver.get("http://www.zappos.com");
WebElement element = driver.findElement(By.name("term"));
element.sendKeys("Green Shoes");
element.submit();
/* (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("green shoes");
}
});*/
|
diff --git a/src/com/untamedears/citadel/command/commands/FortifyCommand.java b/src/com/untamedears/citadel/command/commands/FortifyCommand.java
index 048fd7e..6faa4e6 100644
--- a/src/com/untamedears/citadel/command/commands/FortifyCommand.java
+++ b/src/com/untamedears/citadel/command/commands/FortifyCommand.java
@@ -1,97 +1,97 @@
package com.untamedears.citadel.command.commands;
import static com.untamedears.citadel.Utility.getSecurityLevel;
import static com.untamedears.citadel.Utility.sendMessage;
import static com.untamedears.citadel.Utility.setMultiMode;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.untamedears.citadel.Citadel;
import com.untamedears.citadel.GroupManager;
import com.untamedears.citadel.PlacementMode;
import com.untamedears.citadel.SecurityLevel;
import com.untamedears.citadel.command.PlayerCommand;
import com.untamedears.citadel.entity.Faction;
import com.untamedears.citadel.entity.PlayerState;
import com.untamedears.citadel.entity.ReinforcementMaterial;
/**
* User: JonnyD
* Date: 7/18/12
* Time: 11:57 PM
*/
public class FortifyCommand extends PlayerCommand {
public FortifyCommand() {
super("Fority Mode");
setDescription("Toggle fortification mode");
setUsage("/ctfortify §8[security-level]");
setArgumentRange(0, 2);
setIdentifiers(new String[] {"ctfortify", "ctf"});
}
public boolean execute(CommandSender sender, String[] args) {
Player player = (Player) sender;
PlayerState state = PlayerState.get(player);
String secLevel = null;
String groupName = null;
if(args.length != 0){
secLevel = args[0];
if(args.length == 2){
groupName = args[1];
}
}
if(secLevel != null && secLevel.equalsIgnoreCase("group")){
if(groupName == null || groupName.isEmpty() || groupName.equals("")){
sender.sendMessage(new StringBuilder().append("§cYou must specify a group in group fortification mode").toString());
sender.sendMessage(new StringBuilder().append("§cUsage:§e ").append("/ctfortify §8group <group-name>").toString());
return true;
}
GroupManager groupManager = Citadel.getGroupManager();
Faction group = groupManager.getGroup(groupName);
if(group == null){
sendMessage(sender, ChatColor.RED, "Group doesn't exist");
return true;
}
String senderName = sender.getName();
if(!group.isFounder(senderName) && !group.isModerator(senderName)){
sendMessage(sender, ChatColor.RED, "Invalid permission to use this group");
return true;
}
if(group.isPersonalGroup()){
sendMessage(sender, ChatColor.RED, "You cannot share your default group");
return true;
}
state.setFaction(group);
} else {
state.setFaction(Citadel.getMemberManager().getMember(player).getPersonalGroup());
}
SecurityLevel securityLevel = getSecurityLevel(args, player);
if (securityLevel == null) return false;
ReinforcementMaterial material = ReinforcementMaterial.get(player.getItemInHand().getType());
if (state.getMode() == PlacementMode.FORTIFICATION) {
// Only change material if a valid reinforcement material in hand and not current reinforcement
- if (material != null && material != state.getFortificationMaterial()) {
+ if (material != null && material != state.getReinforcementMaterial()) {
// Switch reinforcement materials without turning off and on again
state.reset();
state.setFortificationMaterial(material);
}
setMultiMode(PlacementMode.FORTIFICATION, securityLevel, args, player, state);
} else {
if (material == null) {
sendMessage(sender, ChatColor.YELLOW, "Invalid reinforcement material %s", player.getItemInHand().getType().name());
} else {
state.setFortificationMaterial(material);
setMultiMode(PlacementMode.FORTIFICATION, securityLevel, args, player, state);
}
}
return true;
}
}
| true | true | public boolean execute(CommandSender sender, String[] args) {
Player player = (Player) sender;
PlayerState state = PlayerState.get(player);
String secLevel = null;
String groupName = null;
if(args.length != 0){
secLevel = args[0];
if(args.length == 2){
groupName = args[1];
}
}
if(secLevel != null && secLevel.equalsIgnoreCase("group")){
if(groupName == null || groupName.isEmpty() || groupName.equals("")){
sender.sendMessage(new StringBuilder().append("§cYou must specify a group in group fortification mode").toString());
sender.sendMessage(new StringBuilder().append("§cUsage:§e ").append("/ctfortify §8group <group-name>").toString());
return true;
}
GroupManager groupManager = Citadel.getGroupManager();
Faction group = groupManager.getGroup(groupName);
if(group == null){
sendMessage(sender, ChatColor.RED, "Group doesn't exist");
return true;
}
String senderName = sender.getName();
if(!group.isFounder(senderName) && !group.isModerator(senderName)){
sendMessage(sender, ChatColor.RED, "Invalid permission to use this group");
return true;
}
if(group.isPersonalGroup()){
sendMessage(sender, ChatColor.RED, "You cannot share your default group");
return true;
}
state.setFaction(group);
} else {
state.setFaction(Citadel.getMemberManager().getMember(player).getPersonalGroup());
}
SecurityLevel securityLevel = getSecurityLevel(args, player);
if (securityLevel == null) return false;
ReinforcementMaterial material = ReinforcementMaterial.get(player.getItemInHand().getType());
if (state.getMode() == PlacementMode.FORTIFICATION) {
// Only change material if a valid reinforcement material in hand and not current reinforcement
if (material != null && material != state.getFortificationMaterial()) {
// Switch reinforcement materials without turning off and on again
state.reset();
state.setFortificationMaterial(material);
}
setMultiMode(PlacementMode.FORTIFICATION, securityLevel, args, player, state);
} else {
if (material == null) {
sendMessage(sender, ChatColor.YELLOW, "Invalid reinforcement material %s", player.getItemInHand().getType().name());
} else {
state.setFortificationMaterial(material);
setMultiMode(PlacementMode.FORTIFICATION, securityLevel, args, player, state);
}
}
return true;
}
| public boolean execute(CommandSender sender, String[] args) {
Player player = (Player) sender;
PlayerState state = PlayerState.get(player);
String secLevel = null;
String groupName = null;
if(args.length != 0){
secLevel = args[0];
if(args.length == 2){
groupName = args[1];
}
}
if(secLevel != null && secLevel.equalsIgnoreCase("group")){
if(groupName == null || groupName.isEmpty() || groupName.equals("")){
sender.sendMessage(new StringBuilder().append("§cYou must specify a group in group fortification mode").toString());
sender.sendMessage(new StringBuilder().append("§cUsage:§e ").append("/ctfortify §8group <group-name>").toString());
return true;
}
GroupManager groupManager = Citadel.getGroupManager();
Faction group = groupManager.getGroup(groupName);
if(group == null){
sendMessage(sender, ChatColor.RED, "Group doesn't exist");
return true;
}
String senderName = sender.getName();
if(!group.isFounder(senderName) && !group.isModerator(senderName)){
sendMessage(sender, ChatColor.RED, "Invalid permission to use this group");
return true;
}
if(group.isPersonalGroup()){
sendMessage(sender, ChatColor.RED, "You cannot share your default group");
return true;
}
state.setFaction(group);
} else {
state.setFaction(Citadel.getMemberManager().getMember(player).getPersonalGroup());
}
SecurityLevel securityLevel = getSecurityLevel(args, player);
if (securityLevel == null) return false;
ReinforcementMaterial material = ReinforcementMaterial.get(player.getItemInHand().getType());
if (state.getMode() == PlacementMode.FORTIFICATION) {
// Only change material if a valid reinforcement material in hand and not current reinforcement
if (material != null && material != state.getReinforcementMaterial()) {
// Switch reinforcement materials without turning off and on again
state.reset();
state.setFortificationMaterial(material);
}
setMultiMode(PlacementMode.FORTIFICATION, securityLevel, args, player, state);
} else {
if (material == null) {
sendMessage(sender, ChatColor.YELLOW, "Invalid reinforcement material %s", player.getItemInHand().getType().name());
} else {
state.setFortificationMaterial(material);
setMultiMode(PlacementMode.FORTIFICATION, securityLevel, args, player, state);
}
}
return true;
}
|
diff --git a/org.eclipse.jdt.debug/eval/org/eclipse/jdt/internal/debug/eval/ast/instructions/Instruction.java b/org.eclipse.jdt.debug/eval/org/eclipse/jdt/internal/debug/eval/ast/instructions/Instruction.java
index 01317d30f..2a58e56a6 100644
--- a/org.eclipse.jdt.debug/eval/org/eclipse/jdt/internal/debug/eval/ast/instructions/Instruction.java
+++ b/org.eclipse.jdt.debug/eval/org/eclipse/jdt/internal/debug/eval/ast/instructions/Instruction.java
@@ -1,330 +1,330 @@
package org.eclipse.jdt.internal.debug.eval.ast.instructions;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import com.sun.jdi.InvocationException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.model.IVariable;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.debug.core.IJavaArrayType;
import org.eclipse.jdt.debug.core.IJavaClassType;
import org.eclipse.jdt.debug.core.IJavaDebugTarget;
import org.eclipse.jdt.debug.core.IJavaInterfaceType;
import org.eclipse.jdt.debug.core.IJavaObject;
import org.eclipse.jdt.debug.core.IJavaType;
import org.eclipse.jdt.debug.core.IJavaValue;
import org.eclipse.jdt.debug.core.IJavaVariable;
import org.eclipse.jdt.internal.debug.eval.ast.engine.IRuntimeContext;
import org.eclipse.jdt.internal.debug.eval.ast.engine.Interpreter;
/**
* Common behavoir for instructions.
*/
public abstract class Instruction {
private Interpreter fInterpreter;
public abstract int getSize();
public void setInterpreter(Interpreter interpreter) {
fInterpreter= interpreter;
}
public void setLastValue(IJavaValue value) {
fInterpreter.setLastValue(value);
}
public void stop() {
fInterpreter.stop();
}
public static int getBinaryPromotionType(int left, int right) {
return fTypeTable[left][right];
}
public abstract void execute() throws CoreException;
protected IRuntimeContext getContext() {
return fInterpreter.getContext();
}
protected IJavaDebugTarget getVM() {
return getContext().getVM();
}
/**
* Return the internal variable with the given name.
*
* @see Interpreter#getInternalVariable(String)
*/
protected IVariable getInternalVariable(String name) {
return fInterpreter.getInternalVariable(name);
}
/**
* Create and return a new internal variable with the given name
* and the given type.
*
* @see Interpreter#createInternalVariable(String, String)
*/
protected IVariable createInternalVariable(String name, IJavaType referencType) throws CoreException {
return fInterpreter.createInternalVariable(name, referencType);
}
/**
* Answers the instance of Class that the given type represents.
*/
protected IJavaObject getClassObject(IJavaType type) throws CoreException {
if (type instanceof IJavaClassType) {
return ((IJavaClassType)type).getClassObject();
}
if (type instanceof IJavaInterfaceType) {
return ((IJavaInterfaceType)type).getClassObject();
}
return null;
}
protected void jump(int offset) {
fInterpreter.jump(offset);
}
protected void push(Object object) {
fInterpreter.push(object);
}
protected Object pop() {
return fInterpreter.pop();
}
protected IJavaValue popValue() throws CoreException {
Object element = fInterpreter.pop();
if (element instanceof IJavaVariable) {
return (IJavaValue)((IJavaVariable)element).getValue();
}
return (IJavaValue)element;
}
protected void pushNewValue(boolean value) {
fInterpreter.push(newValue(value));
}
protected IJavaValue newValue(boolean value) {
return getVM().newValue(value);
}
protected void pushNewValue(byte value) {
fInterpreter.push(newValue(value));
}
protected IJavaValue newValue(byte value) {
return getVM().newValue(value);
}
protected void pushNewValue(short value) {
fInterpreter.push(newValue(value));
}
protected IJavaValue newValue(short value) {
return getVM().newValue(value);
}
protected void pushNewValue(int value) {
fInterpreter.push(newValue(value));
}
protected IJavaValue newValue(int value) {
return getVM().newValue(value);
}
protected void pushNewValue(long value) {
fInterpreter.push(newValue(value));
}
protected IJavaValue newValue(long value) {
return getVM().newValue(value);
}
protected void pushNewValue(char value) {
fInterpreter.push(newValue(value));
}
protected IJavaValue newValue(char value) {
return getVM().newValue(value);
}
protected void pushNewValue(float value) {
fInterpreter.push(newValue(value));
}
protected IJavaValue newValue(float value) {
return getVM().newValue(value);
}
protected void pushNewValue(double value) {
fInterpreter.push(newValue(value));
}
protected IJavaValue newValue(double value) {
return getVM().newValue(value);
}
protected void pushNewValue(String value) {
fInterpreter.push(newValue(value));
}
protected IJavaValue newValue(String value) {
return getVM().newValue(value);
}
protected void pushNullValue() {
fInterpreter.push(nullValue());
}
protected IJavaValue nullValue() {
return getVM().nullValue();
}
public static int getUnaryPromotionType(int typeId) {
return fTypeTable[typeId][T_int];
}
protected IJavaType getType(String qualifiedName) throws CoreException {
// Force the class to be loaded, and record the class reference
// for later use if there are multiple classes with the same name.
IJavaObject classReference= classForName(qualifiedName);
IJavaType[] types= getVM().getJavaTypes(qualifiedName);
checkTypes(types);
if (types.length == 1) {
// Found only one class.
return types[0];
} else {
// Found many classes, look for the right one for this scope.
if (classReference == null) {
throw new CoreException(null); // could not resolve type
}
for(int i= 0, length= types.length; i < length; i++) {
IJavaType type= types[i];
if (classReference.equals(getClassObject(type))) {
return type;
}
}
// At this point a very strange thing has happened,
// the VM was able to return multiple types in the classesByName
// call, but none of them were the class that was returned in
// the classForName call.
throw new CoreException(null);
}
}
protected IJavaArrayType getArrayType(String typeSignature, int dimension) throws CoreException {
- String qualifiedName = Signature.toString(typeSignature);
+ String qualifiedName = RuntimeSignature.toString(typeSignature);
String braces = ""; //$NON-NLS-1$
for (int i = 0; i < dimension; i++) {
qualifiedName += "[]"; //$NON-NLS-1$
braces += "["; //$NON-NLS-1$
}
String signature = braces + typeSignature;
// Force the class to be loaded, and record the class reference
// for later use if there are multiple classes with the same name.
IJavaObject classReference= classForName(signature);
if (classReference == null) {
throw new CoreException(null); // could not resolve type
}
IJavaType[] types= getVM().getJavaTypes(qualifiedName);
checkTypes(types);
if (types.length == 1) {
// Found only one class.
return (IJavaArrayType)types[0];
} else {
// Found many classes, look for the right one for this scope.
for(int i= 0, length= types.length; i < length; i++) {
IJavaType type= types[i];
if (classReference.equals(getClassObject(type))) {
return (IJavaArrayType)type;
}
}
// At this point a very strange thing has happened,
// the VM was able to return multiple types in the classesByName
// call, but none of them were the class that was returned in
// the classForName call.
throw new CoreException(null);
}
}
protected IJavaObject classForName(String qualifiedName) throws CoreException {
IJavaType[] types= getVM().getJavaTypes(CLASS);
checkTypes(types);
if (types.length != 1) {
throw new CoreException(null);
}
IJavaType receiver= types[0];
IJavaValue[] args = new IJavaValue[] {newValue(qualifiedName)};
try {
return (IJavaObject)((IJavaClassType)receiver).sendMessage(FOR_NAME, FOR_NAME_SIGNATURE, args, getContext().getThread());
} catch (CoreException e) {
if (e.getStatus().getException() instanceof InvocationException) {
// Don't throw ClassNotFoundException
if (((InvocationException)e.getStatus().getException()).exception().referenceType().name().equals("java.lang.ClassNotFoundException")) {
return null;
}
}
throw e;
}
}
protected void checkTypes(IJavaType[] types) throws CoreException {
if (types == null || types.length == 0) {
throw new CoreException(null); // unable to resolve type
}
}
static public final int T_undefined =0;
static public final int T_Object =1;
static public final int T_char =2;
static public final int T_byte =3;
static public final int T_short =4;
static public final int T_boolean =5;
static public final int T_void =6;
static public final int T_long =7;
static public final int T_double =8;
static public final int T_float =9;
static public final int T_int =10;
static public final int T_String =11;
static public final int T_null =12;
private static final int[][] fTypeTable= {
/* undefined */ {T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined},
/* object */ {T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_String, T_undefined},
/* char */ {T_undefined, T_undefined, T_int, T_int, T_int, T_undefined, T_undefined, T_long, T_double, T_float, T_int, T_String, T_undefined},
/* byte */ {T_undefined, T_undefined, T_int, T_int, T_int, T_undefined, T_undefined, T_long, T_double, T_float, T_int, T_String, T_undefined},
/* short */ {T_undefined, T_undefined, T_int, T_int, T_int, T_undefined, T_undefined, T_long, T_double, T_float, T_int, T_String, T_undefined},
/* boolean */ {T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_boolean, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_String, T_undefined},
/* void */ {T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined},
/* long */ {T_undefined, T_undefined, T_long, T_long, T_long, T_undefined, T_undefined, T_long, T_double, T_float, T_long, T_String, T_undefined},
/* double */ {T_undefined, T_undefined, T_double, T_double, T_double, T_undefined, T_undefined, T_double, T_double, T_double, T_double, T_String, T_undefined},
/* float */ {T_undefined, T_undefined, T_float, T_float, T_float, T_undefined, T_undefined, T_float, T_double, T_float, T_float, T_String, T_undefined},
/* int */ {T_undefined, T_undefined, T_int, T_int, T_int, T_undefined, T_undefined, T_long, T_double, T_float, T_int, T_String, T_undefined},
/* String */ {T_undefined, T_String, T_String, T_String, T_String, T_String, T_undefined, T_String, T_String, T_String, T_String, T_String, T_String},
/* null */ {T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_undefined, T_String, T_undefined},
};
public static final String CLASS= "java.lang.Class"; //$NON-NLS-1$
public static final String FOR_NAME= "forName"; //$NON-NLS-1$
public static final String FOR_NAME_SIGNATURE= "(Ljava/lang/String;)Ljava/lang/Class;"; //$NON-NLS-1$
}
| true | true | protected IJavaArrayType getArrayType(String typeSignature, int dimension) throws CoreException {
String qualifiedName = Signature.toString(typeSignature);
String braces = ""; //$NON-NLS-1$
for (int i = 0; i < dimension; i++) {
qualifiedName += "[]"; //$NON-NLS-1$
braces += "["; //$NON-NLS-1$
}
String signature = braces + typeSignature;
// Force the class to be loaded, and record the class reference
// for later use if there are multiple classes with the same name.
IJavaObject classReference= classForName(signature);
if (classReference == null) {
throw new CoreException(null); // could not resolve type
}
IJavaType[] types= getVM().getJavaTypes(qualifiedName);
checkTypes(types);
if (types.length == 1) {
// Found only one class.
return (IJavaArrayType)types[0];
} else {
// Found many classes, look for the right one for this scope.
for(int i= 0, length= types.length; i < length; i++) {
IJavaType type= types[i];
if (classReference.equals(getClassObject(type))) {
return (IJavaArrayType)type;
}
}
// At this point a very strange thing has happened,
// the VM was able to return multiple types in the classesByName
// call, but none of them were the class that was returned in
// the classForName call.
throw new CoreException(null);
}
}
| protected IJavaArrayType getArrayType(String typeSignature, int dimension) throws CoreException {
String qualifiedName = RuntimeSignature.toString(typeSignature);
String braces = ""; //$NON-NLS-1$
for (int i = 0; i < dimension; i++) {
qualifiedName += "[]"; //$NON-NLS-1$
braces += "["; //$NON-NLS-1$
}
String signature = braces + typeSignature;
// Force the class to be loaded, and record the class reference
// for later use if there are multiple classes with the same name.
IJavaObject classReference= classForName(signature);
if (classReference == null) {
throw new CoreException(null); // could not resolve type
}
IJavaType[] types= getVM().getJavaTypes(qualifiedName);
checkTypes(types);
if (types.length == 1) {
// Found only one class.
return (IJavaArrayType)types[0];
} else {
// Found many classes, look for the right one for this scope.
for(int i= 0, length= types.length; i < length; i++) {
IJavaType type= types[i];
if (classReference.equals(getClassObject(type))) {
return (IJavaArrayType)type;
}
}
// At this point a very strange thing has happened,
// the VM was able to return multiple types in the classesByName
// call, but none of them were the class that was returned in
// the classForName call.
throw new CoreException(null);
}
}
|
diff --git a/src/org/apache/xml/utils/NodeVector.java b/src/org/apache/xml/utils/NodeVector.java
index d9338a52..ae957b48 100644
--- a/src/org/apache/xml/utils/NodeVector.java
+++ b/src/org/apache/xml/utils/NodeVector.java
@@ -1,739 +1,740 @@
/*
* 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.
*/
/*
* $Id$
*/
package org.apache.xml.utils;
import java.io.Serializable;
import org.apache.xml.dtm.DTM;
/**
* A very simple table that stores a list of Nodes.
* @xsl.usage internal
*/
public class NodeVector implements Serializable, Cloneable
{
static final long serialVersionUID = -713473092200731870L;
/**
* Size of blocks to allocate.
* @serial
*/
private int m_blocksize;
/**
* Array of nodes this points to.
* @serial
*/
private int m_map[];
/**
* Number of nodes in this NodeVector.
* @serial
*/
protected int m_firstFree = 0;
/**
* Size of the array this points to.
* @serial
*/
private int m_mapSize; // lazy initialization
/**
* Default constructor.
*/
public NodeVector()
{
m_blocksize = 32;
m_mapSize = 0;
}
/**
* Construct a NodeVector, using the given block size.
*
* @param blocksize Size of blocks to allocate
*/
public NodeVector(int blocksize)
{
m_blocksize = blocksize;
m_mapSize = 0;
}
/**
* Get a cloned LocPathIterator.
*
* @return A clone of this
*
* @throws CloneNotSupportedException
*/
public Object clone() throws CloneNotSupportedException
{
NodeVector clone = (NodeVector) super.clone();
if ((null != this.m_map) && (this.m_map == clone.m_map))
{
clone.m_map = new int[this.m_map.length];
System.arraycopy(this.m_map, 0, clone.m_map, 0, this.m_map.length);
}
return clone;
}
/**
* Get the length of the list.
*
* @return Number of nodes in this NodeVector
*/
public int size()
{
return m_firstFree;
}
/**
* Append a Node onto the vector.
*
* @param value Node to add to the vector
*/
public void addElement(int value)
{
if ((m_firstFree + 1) >= m_mapSize)
{
if (null == m_map)
{
m_map = new int[m_blocksize];
m_mapSize = m_blocksize;
}
else
{
m_mapSize += m_blocksize;
int newMap[] = new int[m_mapSize];
System.arraycopy(m_map, 0, newMap, 0, m_firstFree + 1);
m_map = newMap;
}
}
m_map[m_firstFree] = value;
m_firstFree++;
}
/**
* Append a Node onto the vector.
*
* @param value Node to add to the vector
*/
public final void push(int value)
{
int ff = m_firstFree;
if ((ff + 1) >= m_mapSize)
{
if (null == m_map)
{
m_map = new int[m_blocksize];
m_mapSize = m_blocksize;
}
else
{
m_mapSize += m_blocksize;
int newMap[] = new int[m_mapSize];
System.arraycopy(m_map, 0, newMap, 0, ff + 1);
m_map = newMap;
}
}
m_map[ff] = value;
ff++;
m_firstFree = ff;
}
/**
* Pop a node from the tail of the vector and return the result.
*
* @return the node at the tail of the vector
*/
public final int pop()
{
m_firstFree--;
int n = m_map[m_firstFree];
m_map[m_firstFree] = DTM.NULL;
return n;
}
/**
* Pop a node from the tail of the vector and return the
* top of the stack after the pop.
*
* @return The top of the stack after it's been popped
*/
public final int popAndTop()
{
m_firstFree--;
m_map[m_firstFree] = DTM.NULL;
return (m_firstFree == 0) ? DTM.NULL : m_map[m_firstFree - 1];
}
/**
* Pop a node from the tail of the vector.
*/
public final void popQuick()
{
m_firstFree--;
m_map[m_firstFree] = DTM.NULL;
}
/**
* Return the node at the top of the stack without popping the stack.
* Special purpose method for TransformerImpl, pushElemTemplateElement.
* Performance critical.
*
* @return Node at the top of the stack or null if stack is empty.
*/
public final int peepOrNull()
{
return ((null != m_map) && (m_firstFree > 0))
? m_map[m_firstFree - 1] : DTM.NULL;
}
/**
* Push a pair of nodes into the stack.
* Special purpose method for TransformerImpl, pushElemTemplateElement.
* Performance critical.
*
* @param v1 First node to add to vector
* @param v2 Second node to add to vector
*/
public final void pushPair(int v1, int v2)
{
if (null == m_map)
{
m_map = new int[m_blocksize];
m_mapSize = m_blocksize;
}
else
{
if ((m_firstFree + 2) >= m_mapSize)
{
m_mapSize += m_blocksize;
int newMap[] = new int[m_mapSize];
System.arraycopy(m_map, 0, newMap, 0, m_firstFree);
m_map = newMap;
}
}
m_map[m_firstFree] = v1;
m_map[m_firstFree + 1] = v2;
m_firstFree += 2;
}
/**
* Pop a pair of nodes from the tail of the stack.
* Special purpose method for TransformerImpl, pushElemTemplateElement.
* Performance critical.
*/
public final void popPair()
{
m_firstFree -= 2;
m_map[m_firstFree] = DTM.NULL;
m_map[m_firstFree + 1] = DTM.NULL;
}
/**
* Set the tail of the stack to the given node.
* Special purpose method for TransformerImpl, pushElemTemplateElement.
* Performance critical.
*
* @param n Node to set at the tail of vector
*/
public final void setTail(int n)
{
m_map[m_firstFree - 1] = n;
}
/**
* Set the given node one position from the tail.
* Special purpose method for TransformerImpl, pushElemTemplateElement.
* Performance critical.
*
* @param n Node to set
*/
public final void setTailSub1(int n)
{
m_map[m_firstFree - 2] = n;
}
/**
* Return the node at the tail of the vector without popping
* Special purpose method for TransformerImpl, pushElemTemplateElement.
* Performance critical.
*
* @return Node at the tail of the vector
*/
public final int peepTail()
{
return m_map[m_firstFree - 1];
}
/**
* Return the node one position from the tail without popping.
* Special purpose method for TransformerImpl, pushElemTemplateElement.
* Performance critical.
*
* @return Node one away from the tail
*/
public final int peepTailSub1()
{
return m_map[m_firstFree - 2];
}
/**
* Insert a node in order in the list.
*
* @param value Node to insert
*/
public void insertInOrder(int value)
{
for (int i = 0; i < m_firstFree; i++)
{
if (value < m_map[i])
{
insertElementAt(value, i);
return;
}
}
addElement(value);
}
/**
* Inserts the specified node in this vector at the specified index.
* Each component in this vector with an index greater or equal to
* the specified index is shifted upward to have an index one greater
* than the value it had previously.
*
* @param value Node to insert
* @param at Position where to insert
*/
public void insertElementAt(int value, int at)
{
if (null == m_map)
{
m_map = new int[m_blocksize];
m_mapSize = m_blocksize;
}
else if ((m_firstFree + 1) >= m_mapSize)
{
m_mapSize += m_blocksize;
int newMap[] = new int[m_mapSize];
System.arraycopy(m_map, 0, newMap, 0, m_firstFree + 1);
m_map = newMap;
}
if (at <= (m_firstFree - 1))
{
System.arraycopy(m_map, at, m_map, at + 1, m_firstFree - at);
}
m_map[at] = value;
m_firstFree++;
}
/**
* Append the nodes to the list.
*
* @param nodes NodeVector to append to this list
*/
public void appendNodes(NodeVector nodes)
{
int nNodes = nodes.size();
if (null == m_map)
{
m_mapSize = nNodes + m_blocksize;
m_map = new int[m_mapSize];
}
else if ((m_firstFree + nNodes) >= m_mapSize)
{
m_mapSize += (nNodes + m_blocksize);
int newMap[] = new int[m_mapSize];
System.arraycopy(m_map, 0, newMap, 0, m_firstFree + nNodes);
m_map = newMap;
}
System.arraycopy(nodes.m_map, 0, m_map, m_firstFree, nNodes);
m_firstFree += nNodes;
}
/**
* Inserts the specified node in this vector at the specified index.
* Each component in this vector with an index greater or equal to
* the specified index is shifted upward to have an index one greater
* than the value it had previously.
*/
public void removeAllElements()
{
if (null == m_map)
return;
for (int i = 0; i < m_firstFree; i++)
{
m_map[i] = DTM.NULL;
}
m_firstFree = 0;
}
/**
* Set the length to zero, but don't clear the array.
*/
public void RemoveAllNoClear()
{
if (null == m_map)
return;
m_firstFree = 0;
}
/**
* Removes the first occurrence of the argument from this vector.
* If the object is found in this vector, each component in the vector
* with an index greater or equal to the object's index is shifted
* downward to have an index one smaller than the value it had
* previously.
*
* @param s Node to remove from the list
*
* @return True if the node was successfully removed
*/
public boolean removeElement(int s)
{
if (null == m_map)
return false;
for (int i = 0; i < m_firstFree; i++)
{
int node = m_map[i];
if (node == s)
{
if (i > m_firstFree)
System.arraycopy(m_map, i + 1, m_map, i - 1, m_firstFree - i);
else
m_map[i] = DTM.NULL;
m_firstFree--;
return true;
}
}
return false;
}
/**
* Deletes the component at the specified index. Each component in
* this vector with an index greater or equal to the specified
* index is shifted downward to have an index one smaller than
* the value it had previously.
*
* @param i Index of node to remove
*/
public void removeElementAt(int i)
{
if (null == m_map)
return;
if (i > m_firstFree)
System.arraycopy(m_map, i + 1, m_map, i - 1, m_firstFree - i);
else
m_map[i] = DTM.NULL;
}
/**
* Sets the component at the specified index of this vector to be the
* specified object. The previous component at that position is discarded.
*
* The index must be a value greater than or equal to 0 and less
* than the current size of the vector.
*
* @param node Node to set
* @param index Index of where to set the node
*/
public void setElementAt(int node, int index)
{
if (null == m_map)
{
m_map = new int[m_blocksize];
m_mapSize = m_blocksize;
}
if(index == -1)
addElement(node);
m_map[index] = node;
}
/**
* Get the nth element.
*
* @param i Index of node to get
*
* @return Node at specified index
*/
public int elementAt(int i)
{
if (null == m_map)
return DTM.NULL;
return m_map[i];
}
/**
* Tell if the table contains the given node.
*
* @param s Node to look for
*
* @return True if the given node was found.
*/
public boolean contains(int s)
{
if (null == m_map)
return false;
for (int i = 0; i < m_firstFree; i++)
{
int node = m_map[i];
if (node == s)
return true;
}
return false;
}
/**
* Searches for the first occurence of the given argument,
* beginning the search at index, and testing for equality
* using the equals method.
*
* @param elem Node to look for
* @param index Index of where to start the search
* @return the index of the first occurrence of the object
* argument in this vector at position index or later in the
* vector; returns -1 if the object is not found.
*/
public int indexOf(int elem, int index)
{
if (null == m_map)
return -1;
for (int i = index; i < m_firstFree; i++)
{
int node = m_map[i];
if (node == elem)
return i;
}
return -1;
}
/**
* Searches for the first occurence of the given argument,
* beginning the search at index, and testing for equality
* using the equals method.
*
* @param elem Node to look for
* @return the index of the first occurrence of the object
* argument in this vector at position index or later in the
* vector; returns -1 if the object is not found.
*/
public int indexOf(int elem)
{
if (null == m_map)
return -1;
for (int i = 0; i < m_firstFree; i++)
{
int node = m_map[i];
if (node == elem)
return i;
}
return -1;
}
/**
* Sort an array using a quicksort algorithm.
*
* @param a The array to be sorted.
* @param lo0 The low index.
* @param hi0 The high index.
*
* @throws Exception
*/
public void sort(int a[], int lo0, int hi0) throws Exception
{
int lo = lo0;
int hi = hi0;
// pause(lo, hi);
if (lo >= hi)
{
return;
}
else if (lo == hi - 1)
{
/*
* sort a two element list by swapping if necessary
*/
if (a[lo] > a[hi])
{
int T = a[lo];
a[lo] = a[hi];
a[hi] = T;
}
return;
}
/*
* Pick a pivot and move it out of the way
*/
- int pivot = a[(lo + hi) / 2];
+ int mid = (lo + hi) >>> 1;
+ int pivot = a[mid];
- a[(lo + hi) / 2] = a[hi];
+ a[mid] = a[hi];
a[hi] = pivot;
while (lo < hi)
{
/*
* Search forward from a[lo] until an element is found that
* is greater than the pivot or lo >= hi
*/
while (a[lo] <= pivot && lo < hi)
{
lo++;
}
/*
* Search backward from a[hi] until element is found that
* is less than the pivot, or lo >= hi
*/
while (pivot <= a[hi] && lo < hi)
{
hi--;
}
/*
* Swap elements a[lo] and a[hi]
*/
if (lo < hi)
{
int T = a[lo];
a[lo] = a[hi];
a[hi] = T;
// pause();
}
// if (stopRequested) {
// return;
// }
}
/*
* Put the median in the "center" of the list
*/
a[hi0] = a[hi];
a[hi] = pivot;
/*
* Recursive calls, elements a[lo0] to a[lo-1] are less than or
* equal to pivot, elements a[hi+1] to a[hi0] are greater than
* pivot.
*/
sort(a, lo0, lo - 1);
sort(a, hi + 1, hi0);
}
/**
* Sort an array using a quicksort algorithm.
*
* @throws Exception
*/
public void sort() throws Exception
{
sort(m_map, 0, m_firstFree - 1);
}
}
| false | true | public void sort(int a[], int lo0, int hi0) throws Exception
{
int lo = lo0;
int hi = hi0;
// pause(lo, hi);
if (lo >= hi)
{
return;
}
else if (lo == hi - 1)
{
/*
* sort a two element list by swapping if necessary
*/
if (a[lo] > a[hi])
{
int T = a[lo];
a[lo] = a[hi];
a[hi] = T;
}
return;
}
/*
* Pick a pivot and move it out of the way
*/
int pivot = a[(lo + hi) / 2];
a[(lo + hi) / 2] = a[hi];
a[hi] = pivot;
while (lo < hi)
{
/*
* Search forward from a[lo] until an element is found that
* is greater than the pivot or lo >= hi
*/
while (a[lo] <= pivot && lo < hi)
{
lo++;
}
/*
* Search backward from a[hi] until element is found that
* is less than the pivot, or lo >= hi
*/
while (pivot <= a[hi] && lo < hi)
{
hi--;
}
/*
* Swap elements a[lo] and a[hi]
*/
if (lo < hi)
{
int T = a[lo];
a[lo] = a[hi];
a[hi] = T;
// pause();
}
// if (stopRequested) {
// return;
// }
}
/*
* Put the median in the "center" of the list
*/
a[hi0] = a[hi];
a[hi] = pivot;
/*
* Recursive calls, elements a[lo0] to a[lo-1] are less than or
* equal to pivot, elements a[hi+1] to a[hi0] are greater than
* pivot.
*/
sort(a, lo0, lo - 1);
sort(a, hi + 1, hi0);
}
| public void sort(int a[], int lo0, int hi0) throws Exception
{
int lo = lo0;
int hi = hi0;
// pause(lo, hi);
if (lo >= hi)
{
return;
}
else if (lo == hi - 1)
{
/*
* sort a two element list by swapping if necessary
*/
if (a[lo] > a[hi])
{
int T = a[lo];
a[lo] = a[hi];
a[hi] = T;
}
return;
}
/*
* Pick a pivot and move it out of the way
*/
int mid = (lo + hi) >>> 1;
int pivot = a[mid];
a[mid] = a[hi];
a[hi] = pivot;
while (lo < hi)
{
/*
* Search forward from a[lo] until an element is found that
* is greater than the pivot or lo >= hi
*/
while (a[lo] <= pivot && lo < hi)
{
lo++;
}
/*
* Search backward from a[hi] until element is found that
* is less than the pivot, or lo >= hi
*/
while (pivot <= a[hi] && lo < hi)
{
hi--;
}
/*
* Swap elements a[lo] and a[hi]
*/
if (lo < hi)
{
int T = a[lo];
a[lo] = a[hi];
a[hi] = T;
// pause();
}
// if (stopRequested) {
// return;
// }
}
/*
* Put the median in the "center" of the list
*/
a[hi0] = a[hi];
a[hi] = pivot;
/*
* Recursive calls, elements a[lo0] to a[lo-1] are less than or
* equal to pivot, elements a[hi+1] to a[hi0] are greater than
* pivot.
*/
sort(a, lo0, lo - 1);
sort(a, hi + 1, hi0);
}
|
diff --git a/org/xbill/DNS/ExtendedResolver.java b/org/xbill/DNS/ExtendedResolver.java
index aa76d2f..0927453 100644
--- a/org/xbill/DNS/ExtendedResolver.java
+++ b/org/xbill/DNS/ExtendedResolver.java
@@ -1,337 +1,339 @@
// Copyright (c) 1999 Brian Wellington ([email protected])
// Portions Copyright (c) 1999 Network Associates, Inc.
package org.xbill.DNS;
import java.util.*;
import java.io.*;
import java.net.*;
import org.xbill.Task.*;
/**
* An implementation of Resolver that can send queries to multiple servers,
* sending the queries multiple times if necessary.
* @see Resolver
*
* @author Brian Wellington
*/
public class ExtendedResolver implements Resolver {
class QElement {
Object obj;
int res;
public
QElement(Object _obj, int _res) {
obj = _obj;
res = _res;
}
}
class Receiver implements ResolverListener {
Vector queue;
Hashtable idMap;
public
Receiver(Vector _queue, Hashtable _idMap) {
queue = _queue;
idMap = _idMap;
}
public void
enqueueInfo(int id, Object obj) {
Integer ID, R;
int r;
synchronized (idMap) {
ID = new Integer(id);
R = (Integer)idMap.get(ID);
if (R == null)
return;
r = R.intValue();
idMap.remove(ID);
}
synchronized (queue) {
QElement qe = new QElement(obj, r);
queue.addElement(qe);
queue.notify();
}
}
public void
receiveMessage(int id, Message m) {
enqueueInfo(id, m);
}
public void
handleException(int id, Exception e) {
System.out.println("got an exception: " + e);
enqueueInfo(id, e);
}
}
private static final int quantum = 30;
private static final byte retries = 3;
private Vector resolvers;
private void
init() {
resolvers = new Vector();
}
/**
* Creates a new Extended Resolver. FindServer is used to locate the servers
* for which SimpleResolver contexts should be initialized.
* @see SimpleResolver
* @see FindServer
* @exception UnknownHostException Failure occured initializing SimpleResolvers
*/
public
ExtendedResolver() throws UnknownHostException {
init();
String [] servers = FindServer.servers();
if (servers != null) {
for (int i = 0; i < servers.length; i++) {
Resolver r = new SimpleResolver(servers[i]);
r.setTimeout(quantum);
resolvers.addElement(r);
}
}
else
resolvers.addElement(new SimpleResolver());
}
/**
* Creates a new Extended Resolver
* @param servers An array of server names for which SimpleResolver
* contexts should be initialized.
* @see SimpleResolver
* @exception UnknownHostException Failure occured initializing SimpleResolvers
*/
public
ExtendedResolver(String [] servers) throws UnknownHostException {
init();
for (int i = 0; i < servers.length; i++) {
Resolver r = new SimpleResolver(servers[i]);
r.setTimeout(quantum);
resolvers.addElement(r);
}
}
/**
* Creates a new Extended Resolver
* @param res An array of pre-initialized Resolvers is provided.
* @see SimpleResolver
* @exception UnknownHostException Failure occured initializing SimpleResolvers
*/
public
ExtendedResolver(Resolver [] res) throws UnknownHostException {
init();
for (int i = 0; i < res.length; i++)
resolvers.addElement(res[i]);
}
private void
sendTo(Message query, Receiver receiver, Hashtable idMap, int r) {
Resolver res = (Resolver) resolvers.elementAt(r);
synchronized (idMap) {
int id = res.sendAsync(query, receiver);
idMap.put(new Integer(id), new Integer(r));
}
}
/** Sets the port to communicate with on the servers */
public void
setPort(int port) {
for (int i = 0; i < resolvers.size(); i++)
((Resolver)resolvers.elementAt(i)).setPort(port);
}
/** Sets whether TCP connections will be sent by default */
public void
setTCP(boolean flag) {
for (int i = 0; i < resolvers.size(); i++)
((Resolver)resolvers.elementAt(i)).setTCP(flag);
}
/** Sets whether truncated responses will be returned */
public void
setIgnoreTruncation(boolean flag) {
for (int i = 0; i < resolvers.size(); i++)
((Resolver)resolvers.elementAt(i)).setIgnoreTruncation(flag);
}
/** Sets the EDNS version used on outgoing messages (only 0 is meaningful) */
public void
setEDNS(int level) {
for (int i = 0; i < resolvers.size(); i++)
((Resolver)resolvers.elementAt(i)).setEDNS(level);
}
/** Specifies the TSIG key that messages will be signed with */
public void
setTSIGKey(String name, String key) {
for (int i = 0; i < resolvers.size(); i++)
((Resolver)resolvers.elementAt(i)).setTSIGKey(name, key);
}
/**
* Specifies the TSIG key (with the same name as the local host) that messages
* will be signed with
*/
public void
setTSIGKey(String key) {
for (int i = 0; i < resolvers.size(); i++)
((Resolver)resolvers.elementAt(i)).setTSIGKey(key);
}
/** Sets the amount of time to wait for a response before giving up */
public void
setTimeout(int secs) {
for (int i = 0; i < resolvers.size(); i++)
((Resolver)resolvers.elementAt(i)).setTimeout(secs);
}
/**
* Sends a message, and waits for a response. Multiple servers are queried,
* and queries are sent multiple times until either a successful response
* is received, or it is clear that there is no successful response.
* @return The response
*/
public Message
send(Message query) throws IOException {
int q, r;
Message best = null;
IOException bestException = null;
boolean [] invalid = new boolean[resolvers.size()];
byte [] sent = new byte[resolvers.size()];
+ byte [] recvd = new byte[resolvers.size()];
Vector queue = new Vector();
Hashtable idMap = new Hashtable();
Receiver receiver = new Receiver(queue, idMap);
while (true) {
Message m;
boolean waiting = false;
QElement qe;
synchronized (queue) {
for (r = 0; r < resolvers.size(); r++) {
- if (sent[r] == 0) {
+ if (sent[r] == recvd[r] && sent[r] < retries) {
sendTo(query, receiver, idMap, r);
sent[r]++;
waiting = true;
break;
}
- if (!invalid[r] && sent[r] < retries)
+ else if (recvd[r] < sent[r])
waiting = true;
}
if (!waiting)
break;
try {
queue.wait();
}
catch (InterruptedException e) {
}
if (queue.size() == 0)
continue;
qe = (QElement) queue.firstElement();
queue.removeElement(qe);
if (qe.obj instanceof Message)
m = (Message) qe.obj;
else
m = null;
r = qe.res;
+ recvd[r]++;
}
if (m == null) {
IOException e = (IOException) qe.obj;
if (!(e instanceof InterruptedIOException))
invalid[r] = true;
if (bestException == null)
bestException = e;
}
else {
byte rcode = m.getHeader().getRcode();
if (rcode == Rcode.NOERROR)
return m;
else {
if (best == null)
best = m;
else {
byte bestrcode;
bestrcode = best.getHeader().getRcode();
if (rcode == Rcode.NXDOMAIN &&
bestrcode != Rcode.NXDOMAIN)
best = m;
}
invalid[r] = true;
}
}
}
if (best != null)
return best;
throw bestException;
}
private int
uniqueID(Message m) {
Record r = m.getQuestion();
return (((r.getName().hashCode() & 0xFFFF) << 16) +
(r.getType() << 8) +
(hashCode() & 0xFF));
}
/**
* Asynchronously sends a message, registering a listener to receive a callback
* Multiple asynchronous lookups can be performed in parallel.
* @return An identifier
*/
public int
sendAsync(final Message query, final ResolverListener listener) {
final int id = uniqueID(query);
String name = this.getClass() + ": " + query.getQuestion().getName();
WorkerThread.assignThread(new ResolveThread(this, query, id, listener),
name);
return id;
}
/**
* Sends a zone transfer message to the first known server, and waits for a
* response. This should be further tuned later.
* @return The response
*/
public
Message sendAXFR(Message query) throws IOException {
return ((Resolver)resolvers.elementAt(0)).sendAXFR(query);
}
/** Returns the i'th resolver used by this ExtendedResolver */
public Resolver
getResolver(int i) {
if (i < resolvers.size())
return (Resolver)resolvers.elementAt(i);
return null;
}
/** Returns all resolvers used by this ExtendedResolver */
public Resolver []
getResolvers() {
Resolver [] res = new Resolver[resolvers.size()];
for (int i = 0; i < resolvers.size(); i++)
res[i] = (Resolver) resolvers.elementAt(i);
return res;
}
/** Adds a new resolver to be used by this ExtendedResolver */
public void
addResolver(Resolver r) {
resolvers.addElement(r);
}
/** Deletes a resolver used by this ExtendedResolver */
public void
deleteResolver(Resolver r) {
resolvers.removeElement(r);
}
}
| false | true | public Message
send(Message query) throws IOException {
int q, r;
Message best = null;
IOException bestException = null;
boolean [] invalid = new boolean[resolvers.size()];
byte [] sent = new byte[resolvers.size()];
Vector queue = new Vector();
Hashtable idMap = new Hashtable();
Receiver receiver = new Receiver(queue, idMap);
while (true) {
Message m;
boolean waiting = false;
QElement qe;
synchronized (queue) {
for (r = 0; r < resolvers.size(); r++) {
if (sent[r] == 0) {
sendTo(query, receiver, idMap, r);
sent[r]++;
waiting = true;
break;
}
if (!invalid[r] && sent[r] < retries)
waiting = true;
}
if (!waiting)
break;
try {
queue.wait();
}
catch (InterruptedException e) {
}
if (queue.size() == 0)
continue;
qe = (QElement) queue.firstElement();
queue.removeElement(qe);
if (qe.obj instanceof Message)
m = (Message) qe.obj;
else
m = null;
r = qe.res;
}
if (m == null) {
IOException e = (IOException) qe.obj;
if (!(e instanceof InterruptedIOException))
invalid[r] = true;
if (bestException == null)
bestException = e;
}
else {
byte rcode = m.getHeader().getRcode();
if (rcode == Rcode.NOERROR)
return m;
else {
if (best == null)
best = m;
else {
byte bestrcode;
bestrcode = best.getHeader().getRcode();
if (rcode == Rcode.NXDOMAIN &&
bestrcode != Rcode.NXDOMAIN)
best = m;
}
invalid[r] = true;
}
}
}
if (best != null)
return best;
throw bestException;
}
| public Message
send(Message query) throws IOException {
int q, r;
Message best = null;
IOException bestException = null;
boolean [] invalid = new boolean[resolvers.size()];
byte [] sent = new byte[resolvers.size()];
byte [] recvd = new byte[resolvers.size()];
Vector queue = new Vector();
Hashtable idMap = new Hashtable();
Receiver receiver = new Receiver(queue, idMap);
while (true) {
Message m;
boolean waiting = false;
QElement qe;
synchronized (queue) {
for (r = 0; r < resolvers.size(); r++) {
if (sent[r] == recvd[r] && sent[r] < retries) {
sendTo(query, receiver, idMap, r);
sent[r]++;
waiting = true;
break;
}
else if (recvd[r] < sent[r])
waiting = true;
}
if (!waiting)
break;
try {
queue.wait();
}
catch (InterruptedException e) {
}
if (queue.size() == 0)
continue;
qe = (QElement) queue.firstElement();
queue.removeElement(qe);
if (qe.obj instanceof Message)
m = (Message) qe.obj;
else
m = null;
r = qe.res;
recvd[r]++;
}
if (m == null) {
IOException e = (IOException) qe.obj;
if (!(e instanceof InterruptedIOException))
invalid[r] = true;
if (bestException == null)
bestException = e;
}
else {
byte rcode = m.getHeader().getRcode();
if (rcode == Rcode.NOERROR)
return m;
else {
if (best == null)
best = m;
else {
byte bestrcode;
bestrcode = best.getHeader().getRcode();
if (rcode == Rcode.NXDOMAIN &&
bestrcode != Rcode.NXDOMAIN)
best = m;
}
invalid[r] = true;
}
}
}
if (best != null)
return best;
throw bestException;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.