diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/main/java/com/amee/domain/data/NuItemValueMap.java b/src/main/java/com/amee/domain/data/NuItemValueMap.java
index e97613f..dbc16bb 100644
--- a/src/main/java/com/amee/domain/data/NuItemValueMap.java
+++ b/src/main/java/com/amee/domain/data/NuItemValueMap.java
@@ -1,150 +1,150 @@
package com.amee.domain.data;
import com.amee.domain.item.BaseItemValue;
import com.amee.platform.science.ExternalHistoryValue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.persistence.Transient;
import java.util.*;
/**
* A Map of {@link BaseItemValue} instances.
* <p/>
* The keys will be the {@link BaseItemValue} paths. The entries will be a Set of {@link BaseItemValue} instances. The Set will
* consist of a single entry for single-valued {@link BaseItemValue} histories.
*/
@SuppressWarnings("unchecked")
public class NuItemValueMap extends HashMap {
Log log = LogFactory.getLog(getClass());
@Transient
private transient ItemValueMap adapter;
/**
* Get the head {@link BaseItemValue} in the historical sequence.
*
* @param path - the {@link BaseItemValue} path.
* @return the head {@link BaseItemValue} in the historical sequence.
*/
public BaseItemValue get(String path) {
BaseItemValue itemValue = null;
TreeSet<BaseItemValue> series = (TreeSet<BaseItemValue>) super.get(path);
if (series != null) {
itemValue = series.first();
}
return itemValue;
}
/**
* Get the list of active {@link BaseItemValue}s at the passed start Date.
*
* @param startDate - the active {@link BaseItemValue} will be that starting immediately prior-to or on this date.
* @return the set of active {@link BaseItemValue}s at the passed start Date.
*/
public List<BaseItemValue> getAll(Date startDate) {
List<BaseItemValue> itemValues = new ArrayList();
for (Object path : super.keySet()) {
BaseItemValue itemValue = get((String) path, startDate);
if (itemValue != null) {
itemValues.add(itemValue);
} else {
log.warn("getAll() Got null BaseItemValue: path=" + path + ", startDate=" + startDate);
}
}
return itemValues;
}
/**
* Get the active {@link BaseItemValue} at the passed start Date.
*
* @param path - the {@link BaseItemValue} path.
* @param startDate - the active {@link BaseItemValue} will be that starting immediately prior-to or on this date.
* @return the active {@link BaseItemValue} at the passed start Date.
*/
public BaseItemValue get(String path, Date startDate) {
BaseItemValue itemValue = null;
Set<BaseItemValue> series = (TreeSet<BaseItemValue>) super.get(path);
if (series != null) {
itemValue = find(series, startDate);
}
return itemValue;
}
public void put(String path, BaseItemValue itemValue) {
// Create TreeSet if it does not exist for this path.
if (!containsKey(path)) {
super.put(path, new TreeSet<BaseItemValue>(new Comparator<BaseItemValue>() {
public int compare(BaseItemValue iv1, BaseItemValue iv2) {
if (ExternalHistoryValue.class.isAssignableFrom(iv1.getClass()) &&
ExternalHistoryValue.class.isAssignableFrom(iv2.getClass())) {
// Both BaseItemValue are part of a history, compare their startDates.
return ((ExternalHistoryValue) iv1).getStartDate().compareTo(((ExternalHistoryValue) iv2).getStartDate());
} else if (ExternalHistoryValue.class.isAssignableFrom(iv1.getClass())) {
// The first BaseItemValue is historical, but the second is not, so it needs to
// come after the second BaseItemValue.
- return -1;
+ return 1;
} else if (ExternalHistoryValue.class.isAssignableFrom(iv2.getClass())) {
// The second BaseItemValue is historical, but the first is not, so it needs to
// come after the first BaseItemValue.
- return 1;
+ return -1;
} else {
// Both BaseItemValue are not historical. This should not happen but consider them equal.
log.warn("put() Two non-historical BaseItemValues with the same path should not exist.");
return 0;
}
}
}));
}
// Add itemValue to the TreeSet for this path.
Set<BaseItemValue> itemValues = (Set<BaseItemValue>) super.get(path);
itemValues.add(itemValue);
}
/**
* Get all instances of {@link BaseItemValue} with the passed path.
*
* @param path - the {@link BaseItemValue} path.
* @return the List of {@link BaseItemValue}. Will be empty is there exists no {@link BaseItemValue}s with this path.
*/
public List<BaseItemValue> getAll(String path) {
Object o = super.get(path);
return o != null ? new ArrayList((TreeSet<BaseItemValue>)o) : new ArrayList();
}
/**
* Find the active BaseItemValue at startDate. The active BaseItemValue is the one occurring at or
* immediately before startDate.
*
* @param itemValues
* @param startDate
* @return the discovered BaseItemValue, or null if not found
*/
private static BaseItemValue find(Set<BaseItemValue> itemValues, Date startDate) {
BaseItemValue selected = null;
for (BaseItemValue itemValue : itemValues) {
if (ExternalHistoryValue.class.isAssignableFrom(itemValue.getClass())) {
if (!((ExternalHistoryValue) itemValue).getStartDate().after(startDate)) {
selected = itemValue;
// TODO: Enable this.
// selected.setHistoryAvailable(itemValues.size() > 1);
// break;
throw new UnsupportedOperationException();
}
} else {
// Non-historical values always come first.
selected = itemValue;
}
}
return selected;
}
public ItemValueMap getAdapter() {
return adapter;
}
public void setAdapter(ItemValueMap adapter) {
this.adapter = adapter;
}
}
| false | true | public void put(String path, BaseItemValue itemValue) {
// Create TreeSet if it does not exist for this path.
if (!containsKey(path)) {
super.put(path, new TreeSet<BaseItemValue>(new Comparator<BaseItemValue>() {
public int compare(BaseItemValue iv1, BaseItemValue iv2) {
if (ExternalHistoryValue.class.isAssignableFrom(iv1.getClass()) &&
ExternalHistoryValue.class.isAssignableFrom(iv2.getClass())) {
// Both BaseItemValue are part of a history, compare their startDates.
return ((ExternalHistoryValue) iv1).getStartDate().compareTo(((ExternalHistoryValue) iv2).getStartDate());
} else if (ExternalHistoryValue.class.isAssignableFrom(iv1.getClass())) {
// The first BaseItemValue is historical, but the second is not, so it needs to
// come after the second BaseItemValue.
return -1;
} else if (ExternalHistoryValue.class.isAssignableFrom(iv2.getClass())) {
// The second BaseItemValue is historical, but the first is not, so it needs to
// come after the first BaseItemValue.
return 1;
} else {
// Both BaseItemValue are not historical. This should not happen but consider them equal.
log.warn("put() Two non-historical BaseItemValues with the same path should not exist.");
return 0;
}
}
}));
}
// Add itemValue to the TreeSet for this path.
Set<BaseItemValue> itemValues = (Set<BaseItemValue>) super.get(path);
itemValues.add(itemValue);
}
| public void put(String path, BaseItemValue itemValue) {
// Create TreeSet if it does not exist for this path.
if (!containsKey(path)) {
super.put(path, new TreeSet<BaseItemValue>(new Comparator<BaseItemValue>() {
public int compare(BaseItemValue iv1, BaseItemValue iv2) {
if (ExternalHistoryValue.class.isAssignableFrom(iv1.getClass()) &&
ExternalHistoryValue.class.isAssignableFrom(iv2.getClass())) {
// Both BaseItemValue are part of a history, compare their startDates.
return ((ExternalHistoryValue) iv1).getStartDate().compareTo(((ExternalHistoryValue) iv2).getStartDate());
} else if (ExternalHistoryValue.class.isAssignableFrom(iv1.getClass())) {
// The first BaseItemValue is historical, but the second is not, so it needs to
// come after the second BaseItemValue.
return 1;
} else if (ExternalHistoryValue.class.isAssignableFrom(iv2.getClass())) {
// The second BaseItemValue is historical, but the first is not, so it needs to
// come after the first BaseItemValue.
return -1;
} else {
// Both BaseItemValue are not historical. This should not happen but consider them equal.
log.warn("put() Two non-historical BaseItemValues with the same path should not exist.");
return 0;
}
}
}));
}
// Add itemValue to the TreeSet for this path.
Set<BaseItemValue> itemValues = (Set<BaseItemValue>) super.get(path);
itemValues.add(itemValue);
}
|
diff --git a/src/test/java/com/ning/http/client/async/PostWithQSTest.java b/src/test/java/com/ning/http/client/async/PostWithQSTest.java
index 9e16598df..b40b132bd 100644
--- a/src/test/java/com/ning/http/client/async/PostWithQSTest.java
+++ b/src/test/java/com/ning/http/client/async/PostWithQSTest.java
@@ -1,85 +1,85 @@
package com.ning.http.client.async;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.Response;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.AbstractHandler;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
/**
* Tests POST request with Query String.
*
* @author Hubert Iwaniuk
*/
public class PostWithQSTest extends AbstractBasicTest {
/** POST with QS server part. */
private class PostWithQSHandler extends AbstractHandler {
public void handle(String s,
HttpServletRequest request,
HttpServletResponse response,
int i) throws IOException, ServletException {
if ("POST".equalsIgnoreCase(request.getMethod())) {
String qs = request.getQueryString();
ServletInputStream is = request.getInputStream();
- if (qs != null && !qs.isEmpty() && is.available() == 3) {
+ if (qs != null && !qs.equals("") && is.available() == 3) {
response.setStatus(HttpServletResponse.SC_OK);
byte buf[] = new byte[is.available()];
is.readLine(buf, 0, is.available());
ServletOutputStream os = response.getOutputStream();
os.println(new String(buf));
os.flush();
os.close();
} else {
response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
}
} else { // this handler is to handle POST request
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
}
}
@Test
public void postWithQS() throws IOException, ExecutionException, TimeoutException, InterruptedException {
AsyncHttpClient client = new AsyncHttpClient();
Future<Response> f = client.preparePost("http://localhost:" + PORT + "/?a=b").setBody("abc".getBytes()).execute();
Response resp = f.get(3, TimeUnit.SECONDS);
assertNotNull(resp);
assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK);
}
@BeforeClass(alwaysRun = true)
public void setUpGlobal() throws Exception {
server = new Server();
BasicConfigurator.configure();
Connector listener = new SelectChannelConnector();
listener.setHost("127.0.0.1");
listener.setPort(PORT);
server.addConnector(listener);
server.setHandler(new PostWithQSHandler());
server.start();
log.info("Local HTTP server started successfully");
}
}
| true | true | public void handle(String s,
HttpServletRequest request,
HttpServletResponse response,
int i) throws IOException, ServletException {
if ("POST".equalsIgnoreCase(request.getMethod())) {
String qs = request.getQueryString();
ServletInputStream is = request.getInputStream();
if (qs != null && !qs.isEmpty() && is.available() == 3) {
response.setStatus(HttpServletResponse.SC_OK);
byte buf[] = new byte[is.available()];
is.readLine(buf, 0, is.available());
ServletOutputStream os = response.getOutputStream();
os.println(new String(buf));
os.flush();
os.close();
} else {
response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
}
} else { // this handler is to handle POST request
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
}
| public void handle(String s,
HttpServletRequest request,
HttpServletResponse response,
int i) throws IOException, ServletException {
if ("POST".equalsIgnoreCase(request.getMethod())) {
String qs = request.getQueryString();
ServletInputStream is = request.getInputStream();
if (qs != null && !qs.equals("") && is.available() == 3) {
response.setStatus(HttpServletResponse.SC_OK);
byte buf[] = new byte[is.available()];
is.readLine(buf, 0, is.available());
ServletOutputStream os = response.getOutputStream();
os.println(new String(buf));
os.flush();
os.close();
} else {
response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
}
} else { // this handler is to handle POST request
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
}
|
diff --git a/src/org/hackystat/sensor/ant/issue/IssueEvent.java b/src/org/hackystat/sensor/ant/issue/IssueEvent.java
index 7319840..65b4d57 100644
--- a/src/org/hackystat/sensor/ant/issue/IssueEvent.java
+++ b/src/org/hackystat/sensor/ant/issue/IssueEvent.java
@@ -1,151 +1,151 @@
package org.hackystat.sensor.ant.issue;
import java.util.Date;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndEntryImpl;
/**
* A record of an issue change event.
* @author Shaoxuan
*
*/
public class IssueEvent {
private String author;
private String id;
private String link;
private String status;
private int issueNumber;
private int updateNumber = 0;
private Date updatedDate;
private String comment;
private static final String googleIssueFeedContentPrefix = "<pre>";
private static final String googleIssueFeedContentSuffix = "</pre>";
private static final String statusPrefix = "Status:";
private static final String labelPrefix = "Label:";
/**
* Create an issue event instance with the information extract from the given entry.
* @param entry a SyndEntryImpl.
* @throws Exception if error occur.
*/
public IssueEvent(SyndEntryImpl entry) throws Exception {
this.author = entry.getAuthor();
this.id = entry.getUri();
this.link = entry.getLink();
this.updatedDate = entry.getUpdatedDate();
if (entry.getContents().size() != 1) {
throw new Exception("Unsupport: There are more than one contents in the entry.");
}
//[1] extract issue number and update number from title
String[] titleWords = entry.getTitle().trim().split(" ");
if (titleWords.length > 5 &&
titleWords[0].equals("Update") && titleWords[3].equals("issue")) { //Update
this.updateNumber = Integer.valueOf(titleWords[1]);
this.issueNumber = Integer.valueOf(titleWords[4]);
}
else if (titleWords.length > 3 &&
titleWords[0].equals("Issue") && titleWords[2].equals("created:")) { //Create
status = "Created";
//TODO should extract more detail from the issue page.
this.issueNumber = Integer.valueOf(titleWords[1]);
}
//[2] extract comment and status from content
SyndContent syndContent = (SyndContent)entry.getContents().get(0);
String content = syndContent.getValue().replace(googleIssueFeedContentPrefix, "").
replace(googleIssueFeedContentSuffix, "").trim();
content = content.replace("<br/>", " ");
if (updateNumber > 0) {
//extract status, which is the word following Status:, and comment.
- if (content.contains(statusPrefix)) {
+ if (content.contains(statusPrefix) || content.contains(labelPrefix) ) {
int statusStartIndex = content.lastIndexOf(statusPrefix);
- statusStartIndex = statusStartIndex == -1 ? content.length() - 1 : statusStartIndex;
+ statusStartIndex = (statusStartIndex == -1) ? content.length() - 1 : statusStartIndex;
int labelStartIndex = content.lastIndexOf(labelPrefix);
- labelStartIndex = labelStartIndex == -1 ? content.length() - 1 : labelStartIndex;
+ labelStartIndex = (labelStartIndex == -1) ? content.length() - 1 : labelStartIndex;
comment = content.substring(0,
(statusStartIndex < labelStartIndex ? statusStartIndex : labelStartIndex));
int statusEndIndex = content.indexOf(" ", statusStartIndex + statusPrefix.length() + 1);
statusEndIndex = statusEndIndex == -1 ? content.length() - 1 : statusEndIndex;
status = content.substring(statusStartIndex + statusPrefix.length(), statusEndIndex).trim();
}
else {
comment = content;
}
}
else {
comment = content;
}
}
/**
* Gets a string representation of this instance.
*
* @return The string representation.
*/
@Override
public String toString() {
return "Issue " + this.getIssueNumber() + ", Update " + this.getUpdateNumber() +
", Author=" + this.getAuthor() + ", status=" + status + ", updateDate=" +
this.getUpdatedDate() + ", id=" + this.getId();
}
/**
* @return the issueNumber
*/
public int getIssueNumber() {
return issueNumber;
}
/**
* @return the status
*/
public String getStatus() {
return status;
}
/**
* @return the author
*/
public String getAuthor() {
return author;
}
/**
* @return the updatedDate
*/
public Date getUpdatedDate() {
return new Date(updatedDate.getTime());
}
/**
* @return the comment
*/
public String getComment() {
return comment;
}
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @return the link
*/
public String getLink() {
return link;
}
/**
* @return the updateNumber
*/
public int getUpdateNumber() {
return updateNumber;
}
}
| false | true | public IssueEvent(SyndEntryImpl entry) throws Exception {
this.author = entry.getAuthor();
this.id = entry.getUri();
this.link = entry.getLink();
this.updatedDate = entry.getUpdatedDate();
if (entry.getContents().size() != 1) {
throw new Exception("Unsupport: There are more than one contents in the entry.");
}
//[1] extract issue number and update number from title
String[] titleWords = entry.getTitle().trim().split(" ");
if (titleWords.length > 5 &&
titleWords[0].equals("Update") && titleWords[3].equals("issue")) { //Update
this.updateNumber = Integer.valueOf(titleWords[1]);
this.issueNumber = Integer.valueOf(titleWords[4]);
}
else if (titleWords.length > 3 &&
titleWords[0].equals("Issue") && titleWords[2].equals("created:")) { //Create
status = "Created";
//TODO should extract more detail from the issue page.
this.issueNumber = Integer.valueOf(titleWords[1]);
}
//[2] extract comment and status from content
SyndContent syndContent = (SyndContent)entry.getContents().get(0);
String content = syndContent.getValue().replace(googleIssueFeedContentPrefix, "").
replace(googleIssueFeedContentSuffix, "").trim();
content = content.replace("<br/>", " ");
if (updateNumber > 0) {
//extract status, which is the word following Status:, and comment.
if (content.contains(statusPrefix)) {
int statusStartIndex = content.lastIndexOf(statusPrefix);
statusStartIndex = statusStartIndex == -1 ? content.length() - 1 : statusStartIndex;
int labelStartIndex = content.lastIndexOf(labelPrefix);
labelStartIndex = labelStartIndex == -1 ? content.length() - 1 : labelStartIndex;
comment = content.substring(0,
(statusStartIndex < labelStartIndex ? statusStartIndex : labelStartIndex));
int statusEndIndex = content.indexOf(" ", statusStartIndex + statusPrefix.length() + 1);
statusEndIndex = statusEndIndex == -1 ? content.length() - 1 : statusEndIndex;
status = content.substring(statusStartIndex + statusPrefix.length(), statusEndIndex).trim();
}
else {
comment = content;
}
}
else {
comment = content;
}
}
| public IssueEvent(SyndEntryImpl entry) throws Exception {
this.author = entry.getAuthor();
this.id = entry.getUri();
this.link = entry.getLink();
this.updatedDate = entry.getUpdatedDate();
if (entry.getContents().size() != 1) {
throw new Exception("Unsupport: There are more than one contents in the entry.");
}
//[1] extract issue number and update number from title
String[] titleWords = entry.getTitle().trim().split(" ");
if (titleWords.length > 5 &&
titleWords[0].equals("Update") && titleWords[3].equals("issue")) { //Update
this.updateNumber = Integer.valueOf(titleWords[1]);
this.issueNumber = Integer.valueOf(titleWords[4]);
}
else if (titleWords.length > 3 &&
titleWords[0].equals("Issue") && titleWords[2].equals("created:")) { //Create
status = "Created";
//TODO should extract more detail from the issue page.
this.issueNumber = Integer.valueOf(titleWords[1]);
}
//[2] extract comment and status from content
SyndContent syndContent = (SyndContent)entry.getContents().get(0);
String content = syndContent.getValue().replace(googleIssueFeedContentPrefix, "").
replace(googleIssueFeedContentSuffix, "").trim();
content = content.replace("<br/>", " ");
if (updateNumber > 0) {
//extract status, which is the word following Status:, and comment.
if (content.contains(statusPrefix) || content.contains(labelPrefix) ) {
int statusStartIndex = content.lastIndexOf(statusPrefix);
statusStartIndex = (statusStartIndex == -1) ? content.length() - 1 : statusStartIndex;
int labelStartIndex = content.lastIndexOf(labelPrefix);
labelStartIndex = (labelStartIndex == -1) ? content.length() - 1 : labelStartIndex;
comment = content.substring(0,
(statusStartIndex < labelStartIndex ? statusStartIndex : labelStartIndex));
int statusEndIndex = content.indexOf(" ", statusStartIndex + statusPrefix.length() + 1);
statusEndIndex = statusEndIndex == -1 ? content.length() - 1 : statusEndIndex;
status = content.substring(statusStartIndex + statusPrefix.length(), statusEndIndex).trim();
}
else {
comment = content;
}
}
else {
comment = content;
}
}
|
diff --git a/src/main/java/uk/org/rbc1b/roms/controller/common/model/PersonModel.java b/src/main/java/uk/org/rbc1b/roms/controller/common/model/PersonModel.java
index 660d9d82..4e1a03a5 100644
--- a/src/main/java/uk/org/rbc1b/roms/controller/common/model/PersonModel.java
+++ b/src/main/java/uk/org/rbc1b/roms/controller/common/model/PersonModel.java
@@ -1,186 +1,186 @@
/*
* The MIT License
*
* Copyright 2013 RBC1B.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package uk.org.rbc1b.roms.controller.common.model;
import java.sql.Date;
import uk.org.rbc1b.roms.db.Address;
/**
* Model for a person, including links to their roles.
*
* @author oliver
*/
public class PersonModel {
private Integer id;
private String uri;
private String editUri;
private java.sql.Date birthDate;
private EntityModel congregation;
private String forename;
private String middleName;
private String surname;
private Address address;
private String telephone;
private String mobile;
private String workPhone;
private String email;
private String comments;
/**
* @return the person display name - "forename surname"
*/
public String getDisplayName() {
return forename + " " + surname;
}
/**
* @return the person display initials
*/
public String getInitials() {
StringBuilder builder = new StringBuilder();
- if (forename != null) {
+ if (forename != null && !forename.isEmpty()) {
builder.append(forename.charAt(0));
}
- if (middleName != null) {
+ if (middleName != null && !middleName.isEmpty()) {
builder.append(middleName.charAt(0));
}
- if (surname != null) {
+ if (surname != null && !surname.isEmpty()) {
builder.append(surname.charAt(0));
}
return builder.toString();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getEditUri() {
return editUri;
}
public void setEditUri(String editUri) {
this.editUri = editUri;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public EntityModel getCongregation() {
return congregation;
}
public void setCongregation(EntityModel congregation) {
this.congregation = congregation;
}
public String getForename() {
return forename;
}
public void setForename(String forename) {
this.forename = forename;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getWorkPhone() {
return workPhone;
}
public void setWorkPhone(String workPhone) {
this.workPhone = workPhone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
}
| false | true | public String getInitials() {
StringBuilder builder = new StringBuilder();
if (forename != null) {
builder.append(forename.charAt(0));
}
if (middleName != null) {
builder.append(middleName.charAt(0));
}
if (surname != null) {
builder.append(surname.charAt(0));
}
return builder.toString();
}
| public String getInitials() {
StringBuilder builder = new StringBuilder();
if (forename != null && !forename.isEmpty()) {
builder.append(forename.charAt(0));
}
if (middleName != null && !middleName.isEmpty()) {
builder.append(middleName.charAt(0));
}
if (surname != null && !surname.isEmpty()) {
builder.append(surname.charAt(0));
}
return builder.toString();
}
|
diff --git a/gerrithudsontrigger/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/GerritManagement.java b/gerrithudsontrigger/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/GerritManagement.java
index 0a17e2cf..ea458969 100644
--- a/gerrithudsontrigger/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/GerritManagement.java
+++ b/gerrithudsontrigger/src/main/java/com/sonyericsson/hudson/plugins/gerrit/trigger/GerritManagement.java
@@ -1,375 +1,375 @@
/*
* The MIT License
*
* Copyright 2010 Sony Ericsson Mobile Communications. All rights reserved.
* Copyright 2012 Sony Mobile Communications AB. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.sonyericsson.hudson.plugins.gerrit.trigger;
import com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritSendCommandQueue;
import com.sonyericsson.hudson.plugins.gerrit.trigger.config.Config;
import com.sonyericsson.hudson.plugins.gerrit.trigger.config.IGerritHudsonTriggerConfig;
import com.sonyericsson.hudson.plugins.gerrit.trigger.config.PluginConfig;
import com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.GerritAdministrativeMonitor;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.Functions;
import hudson.model.AdministrativeMonitor;
import hudson.model.AutoCompletionCandidates;
import hudson.model.Describable;
import hudson.model.Failure;
import hudson.model.Descriptor;
import hudson.model.Hudson;
import hudson.model.ManagementLink;
import hudson.model.Saveable;
import hudson.util.FormValidation;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.ServletException;
import jenkins.model.Jenkins;
import jenkins.model.ModelObjectWithContextMenu;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.CharEncoding;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.bind.JavaScriptMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.sonyericsson.hudson.plugins.gerrit.trigger.utils.StringUtil.PLUGIN_IMAGES_URL;
/**
* Management link for configuring the global configuration of this trigger.
*
* @author Robert Sandell <[email protected]>
*/
@Extension
public class GerritManagement extends ManagementLink implements StaplerProxy, Describable<GerritManagement>,
Saveable, ModelObjectWithContextMenu {
/**
* The relative url name for this management link.
* As returned by {@link #getUrlName()}.
*/
public static final String URL_NAME = "gerrit-trigger";
private static final Logger logger = LoggerFactory.getLogger(GerritManagement.class);
@Override
public String getIconFileName() {
return PLUGIN_IMAGES_URL + "icon.png";
}
@Override
public String getUrlName() {
return URL_NAME;
}
@Override
public String getDisplayName() {
return Messages.DisplayName();
}
@Override
public String getDescription() {
return Messages.PluginDescription();
}
@Override
public DescriptorImpl getDescriptor() {
return Hudson.getInstance().getDescriptorByType(DescriptorImpl.class);
}
@Override
public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
ContextMenu menu = new ContextMenu();
menu.add("newServer", Functions.joinPath(Jenkins.getInstance().getRootUrl(), Functions.getResourcePath(),
"images", "24x24", "new-package.png"), Messages.AddNewServer());
for (GerritServer server : getServers()) {
menu.add(server);
}
return menu;
}
/**
* Descriptor is only used for UI form bindings.
*/
@Extension
public static final class DescriptorImpl extends Descriptor<GerritManagement> {
@Override
public String getDisplayName() {
return null; // unused
}
/**
* Returns the list containing the GerritServer descriptor.
*
* @return the list of descriptors containing GerritServer's descriptor.
*/
public static DescriptorExtensionList<GerritServer, GerritServer.DescriptorImpl> serverDescriptorList() {
return Jenkins.getInstance()
.<GerritServer, GerritServer.DescriptorImpl>getDescriptorList(GerritServer.class);
}
/**
* Auto-completion for the "copy from" field in the new server page.
*
* @param value the value that the user has typed in the textbox.
* @return the list of server names, depending on the current value in the textbox.
*/
public AutoCompletionCandidates doAutoCompleteCopyNewItemFrom(@QueryParameter final String value) {
final AutoCompletionCandidates r = new AutoCompletionCandidates();
for (String s : PluginImpl.getInstance().getServerNames()) {
if (s.startsWith(value)) {
r.add(s);
}
}
return r;
}
}
/**
* Gets the list of GerritServer.
*
* @return the list of GerritServer.
*/
@SuppressWarnings("unused") //Called from Jelly
public List<GerritServer> getServers() {
return PluginImpl.getInstance().getServers();
}
/**
* Used when redirected to a server.
* @param encodedServerName the server name encoded by URLEncoder.encode(name,"UTF-8").
* @return the GerritServer object.
*/
@SuppressWarnings("unused") //Called from Jelly
public GerritServer getServer(String encodedServerName) {
String serverName;
try {
serverName = URLDecoder.decode(encodedServerName, CharEncoding.UTF_8);
} catch (Exception ex) {
serverName = URLDecoder.decode(encodedServerName);
}
return PluginImpl.getInstance().getServer(serverName);
}
/**
* Used when getting server status from JavaScript.
*
* @return the json array of server status.
*/
@JavaScriptMethod
public JSONObject getServerStatuses() {
JSONObject root = new JSONObject();
JSONArray array = new JSONArray();
JSONObject obj;
for (GerritServer server : PluginImpl.getInstance().getServers()) {
String status;
if (server.isPseudoMode()) {
status = "na";
} else {
if (server.isConnected()) {
- status ="up";
+ status = "up";
} else {
- status ="down";
+ status = "down";
}
}
obj = new JSONObject();
obj.put("name", server.getName());
obj.put("frontEndUrl", server.getConfig().getGerritFrontEndUrl());
obj.put("serverUrl", server.getUrlName());
obj.put("version", server.getGerritVersion());
obj.put("status", status);
array.add(obj);
}
root.put("servers", array);
return root;
}
/**
* Add a new server.
*
* @param req the StaplerRequest
* @param rsp the StaplerResponse
* @throws IOException when error sending redirect back to the list of servers
* @return the new GerritServer
*/
public GerritServer doAddNewServer(StaplerRequest req, StaplerResponse rsp) throws IOException {
String serverName = req.getParameter("name");
PluginImpl plugin = PluginImpl.getInstance();
if (plugin.containsServer(serverName)) {
throw new Failure("A server already exists with the name '" + serverName + "'");
} else if (GerritServer.ANY_SERVER.equals(serverName)) {
throw new Failure("Illegal server name '" + serverName + "'");
}
GerritServer server = new GerritServer(serverName);
PluginConfig pluginConfig = PluginImpl.getInstance().getPluginConfig();
server.getConfig().setNumberOfSendingWorkerThreads(pluginConfig.getNumberOfSendingWorkerThreads());
String mode = req.getParameter("mode");
if (mode != null && mode.equals("copy")) { //"Copy Existing Server Configuration" has been chosen
String from = req.getParameter("from");
GerritServer fromServer = plugin.getServer(from);
if (fromServer != null) {
server.setConfig(new Config(fromServer.getConfig()));
plugin.addServer(server);
server.start();
} else {
throw new Failure("Server '" + from + "' does not exist!");
}
} else {
plugin.addServer(server);
server.start();
}
plugin.save();
rsp.sendRedirect("./server/" + URLEncoder.encode(serverName, CharEncoding.UTF_8));
return server;
}
@Override
public Object getTarget() {
Hudson.getInstance().checkPermission(Hudson.ADMINISTER);
return this;
}
@Override
public void save() throws IOException {
logger.debug("SAVE!!!");
}
/**
* Returns this singleton.
* @return the single loaded instance if this class.
*/
public static GerritManagement get() {
return ManagementLink.all().get(GerritManagement.class);
}
/**
* Get the plugin config.
*
* @return the plugin config.
*/
public static PluginConfig getPluginConfig() {
return PluginImpl.getInstance().getPluginConfig();
}
/**
* Get the config of a server.
*
* @param serverName the name of the server for which we want to get the config.
* @return the config.
* @see GerritServer#getConfig()
*/
public static IGerritHudsonTriggerConfig getConfig(String serverName) {
GerritServer server = PluginImpl.getInstance().getServer(serverName);
if (server != null) {
return server.getConfig();
} else {
logger.error("Could not find the Gerrit Server: {}", serverName);
return null;
}
}
/**
* The AdministrativeMonitor related to Gerrit.
* convenience method for the jelly page.
*
* @return the monitor if it could be found, or null otherwise.
*/
@SuppressWarnings("unused") //Called from Jelly
public GerritAdministrativeMonitor getAdministrativeMonitor() {
for (AdministrativeMonitor monitor : AdministrativeMonitor.all()) {
if (monitor instanceof GerritAdministrativeMonitor) {
return (GerritAdministrativeMonitor)monitor;
}
}
return null;
}
/**
* Convenience method for jelly. Get the list of Gerrit server names.
*
* @return the list of server names as a list.
*/
public List<String> getServerNames() {
return PluginImpl.getInstance().getServerNames();
}
/**
* Checks whether server name already exists.
*
* @param value the value of the name field.
* @return ok or error.
*/
public FormValidation doNameFreeCheck(@QueryParameter("value") final String value) {
if (PluginImpl.getInstance().containsServer(value)) {
return FormValidation.error("The server name " + value + " is already in use!");
} else if (GerritServer.ANY_SERVER.equals(value)) {
return FormValidation.error("Illegal name " + value + "!");
} else {
return FormValidation.ok();
}
}
/**
* Saves the form to the configuration and disk.
*
* @param req StaplerRequest
* @param rsp StaplerResponse
* @throws ServletException if something unfortunate happens.
* @throws IOException if something unfortunate happens.
* @throws InterruptedException if something unfortunate happens.
*/
public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws ServletException,
IOException,
InterruptedException {
if (logger.isDebugEnabled()) {
logger.debug("submit {}", req.toString());
}
JSONObject form = req.getSubmittedForm();
PluginConfig pluginConfig = PluginImpl.getInstance().getPluginConfig();
pluginConfig.setValues(form);
PluginImpl.getInstance().save();
GerritSendCommandQueue.configure(pluginConfig);
//TODO reconfigure the incoming worker threads as well
rsp.sendRedirect(".");
}
}
| false | true | public JSONObject getServerStatuses() {
JSONObject root = new JSONObject();
JSONArray array = new JSONArray();
JSONObject obj;
for (GerritServer server : PluginImpl.getInstance().getServers()) {
String status;
if (server.isPseudoMode()) {
status = "na";
} else {
if (server.isConnected()) {
status ="up";
} else {
status ="down";
}
}
obj = new JSONObject();
obj.put("name", server.getName());
obj.put("frontEndUrl", server.getConfig().getGerritFrontEndUrl());
obj.put("serverUrl", server.getUrlName());
obj.put("version", server.getGerritVersion());
obj.put("status", status);
array.add(obj);
}
root.put("servers", array);
return root;
}
| public JSONObject getServerStatuses() {
JSONObject root = new JSONObject();
JSONArray array = new JSONArray();
JSONObject obj;
for (GerritServer server : PluginImpl.getInstance().getServers()) {
String status;
if (server.isPseudoMode()) {
status = "na";
} else {
if (server.isConnected()) {
status = "up";
} else {
status = "down";
}
}
obj = new JSONObject();
obj.put("name", server.getName());
obj.put("frontEndUrl", server.getConfig().getGerritFrontEndUrl());
obj.put("serverUrl", server.getUrlName());
obj.put("version", server.getGerritVersion());
obj.put("status", status);
array.add(obj);
}
root.put("servers", array);
return root;
}
|
diff --git a/BetterBatteryStats/src/com/asksven/betterbatterystats/data/StatsProvider.java b/BetterBatteryStats/src/com/asksven/betterbatterystats/data/StatsProvider.java
index 784113e2..f6f40c94 100644
--- a/BetterBatteryStats/src/com/asksven/betterbatterystats/data/StatsProvider.java
+++ b/BetterBatteryStats/src/com/asksven/betterbatterystats/data/StatsProvider.java
@@ -1,1645 +1,1646 @@
/*
* Copyright (C) 2011-2012 asksven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asksven.betterbatterystats.data;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
import android.app.ActivityManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import com.asksven.android.common.kernelutils.Alarm;
import com.asksven.android.common.kernelutils.AlarmsDumpsys;
import com.asksven.android.common.kernelutils.NativeKernelWakelock;
import com.asksven.android.common.kernelutils.RootDetection;
import com.asksven.android.common.kernelutils.Wakelocks;
import com.asksven.android.common.privateapiproxies.BatteryStatsProxy;
import com.asksven.android.common.privateapiproxies.BatteryStatsTypes;
import com.asksven.android.common.privateapiproxies.Misc;
import com.asksven.android.common.privateapiproxies.NetworkUsage;
import com.asksven.android.common.privateapiproxies.Process;
import com.asksven.android.common.privateapiproxies.StatElement;
import com.asksven.android.common.privateapiproxies.Wakelock;
import com.asksven.android.common.utils.DataStorage;
import com.asksven.android.common.utils.DateUtils;
import com.asksven.android.common.utils.GenericLogger;
import com.asksven.betterbatterystats.R;
/**
* Singleton provider for all the statistics
* @author sven
*
*/
public class StatsProvider
{
/** the singleton instance */
static StatsProvider m_statsProvider = null;
/** the application context */
static Context m_context = null;
/** constant for custom stats */
// dependent on arrays.xml
public final static int STATS_CHARGED = 0;
public final static int STATS_UNPLUGGED = 3;
public final static int STATS_CUSTOM = 4;
/** the logger tag */
static String TAG = "StatsProvider";
/** the text when no custom reference is set */
static String NO_CUST_REF = "No custom reference was set";
/** the storage for references */
static References m_myRefs = null;
static References m_myRefSinceUnplugged = null;
static References m_myRefSinceCharged = null;
/**
* The constructor (hidden)
*/
private StatsProvider()
{
}
/**
* returns a singleton instance
* @param ctx the application context
* @return the singleton StatsProvider
*/
public static StatsProvider getInstance(Context ctx)
{
if (m_statsProvider == null)
{
m_statsProvider = new StatsProvider();
m_context = ctx;
m_myRefs = new References();
}
return m_statsProvider;
}
/**
* Get the Stat to be displayed
* @return a List of StatElements sorted (descending)
*/
public ArrayList<StatElement> getStatList(int iStat, int iStatType, int iSort)
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(m_context);
boolean bFilterStats = sharedPrefs.getBoolean("filter_data", true);
int iPctType = Integer.valueOf(sharedPrefs.getString("default_wl_ref", "0"));
try
{
switch (iStat)
{
// constants are related to arrays.xml string-array name="stats"
case 4:
return getProcessStatList(bFilterStats, iStatType, iSort);
case 1:
return getWakelockStatList(bFilterStats, iStatType, iPctType, iSort);
case 0:
return getOtherUsageStatList(bFilterStats, iStatType);
case 2:
return getNativeKernelWakelockStatList(bFilterStats, iStatType, iPctType, iSort);
case 3:
return getAlarmsStatList(bFilterStats, iStatType);
}
}
catch (Exception e)
{
Log.e(TAG, "Exception: " + e.getMessage());
}
return new ArrayList<StatElement>();
}
/**
* Get the Alarm Stat to be displayed
* @param bFilter defines if zero-values should be filtered out
* @return a List of Other usages sorted by duration (descending)
* @throws Exception if the API call failed
*/
public ArrayList<StatElement> getAlarmsStatList(boolean bFilter, int iStatType) throws Exception
{
ArrayList<StatElement> myStats = new ArrayList<StatElement>();
ArrayList<Alarm> myAlarms = AlarmsDumpsys.getAlarms();
Collections.sort(myAlarms);
ArrayList<Alarm> myRetAlarms = new ArrayList<Alarm>();
// if we are using custom ref. always retrieve "stats current"
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
String strCurrent = myAlarms.toString();
String strRef = "";
switch (iStatType)
{
case STATS_UNPLUGGED:
if ( (m_myRefSinceUnplugged != null) && (m_myRefSinceUnplugged.m_refAlarms != null) )
{
strRef = m_myRefSinceUnplugged.m_refAlarms.toString();
}
break;
case STATS_CHARGED:
if ( (m_myRefSinceCharged != null) && (m_myRefSinceCharged.m_refAlarms != null) )
{
strRef = m_myRefSinceCharged.m_refAlarms.toString();
}
break;
case STATS_CUSTOM:
if ( (m_myRefs != null) && (m_myRefs.m_refAlarms != null))
{
strRef = m_myRefs.m_refAlarms.toString();
}
break;
case BatteryStatsTypes.STATS_CURRENT:
strRef = "no reference to substract";
break;
default:
Log.e(TAG, "Unknown StatType " + iStatType + ". No reference found");
break;
}
// Log.i(TAG, "Substracting " + strRef + " from " + strCurrent);
for (int i = 0; i < myAlarms.size(); i++)
{
Alarm alarm = myAlarms.get(i);
if ( (!bFilter) || ((alarm.getWakeups()) > 0) )
{
// native kernel wakelocks are parsed from /proc/wakelocks
// and do not know any references "since charged" and "since unplugged"
// those are implemented using special references
switch (iStatType)
{
case STATS_CUSTOM:
// case a)
// we need t return a delta containing
// if a process is in the new list but not in the custom ref
// the full time is returned
// if a process is in the reference return the delta
// a process can not have disapeared in btwn so we don't need
// to test the reverse case
if (m_myRefs != null)
{
alarm.substractFromRef(m_myRefs.m_refAlarms);
// we must recheck if the delta process is still above threshold
if ( (!bFilter) || ((alarm.getWakeups()) > 0) )
{
myRetAlarms.add( alarm);
}
}
else
{
myRetAlarms.clear();
myRetAlarms.add(new Alarm(NO_CUST_REF));
}
break;
case STATS_UNPLUGGED:
if (m_myRefSinceUnplugged != null)
{
alarm.substractFromRef(m_myRefSinceUnplugged.m_refAlarms);
// we must recheck if the delta process is still above threshold
if ( (!bFilter) || ((alarm.getWakeups()) > 0) )
{
myRetAlarms.add( alarm);
}
}
else
{
myRetAlarms.clear();
myRetAlarms.add(new Alarm("No reference since unplugged set yet"));
}
break;
case STATS_CHARGED:
if (m_myRefSinceCharged != null)
{
alarm.substractFromRef(m_myRefSinceCharged.m_refAlarms);
// we must recheck if the delta process is still above threshold
if ( (!bFilter) || ((alarm.getWakeups()) > 0) )
{
myRetAlarms.add(alarm);
}
}
else
{
myRetAlarms.clear();
myRetAlarms.add(new Alarm("No reference since charged yet"));
}
break;
case BatteryStatsTypes.STATS_CURRENT:
// we must recheck if the delta process is still above threshold
myRetAlarms.add(alarm);
break;
}
}
}
for (int i=0; i < myRetAlarms.size(); i++)
{
myStats.add((StatElement) myRetAlarms.get(i));
}
// Log.i(TAG, "Result " + myStats.toString());
return myStats;
}
/**
* Get the Process Stat to be displayed
* @param bFilter defines if zero-values should be filtered out
* @return a List of Wakelocks sorted by duration (descending)
* @throws Exception if the API call failed
*/
public ArrayList<StatElement> getProcessStatList(boolean bFilter, int iStatType, int iSort) throws Exception
{
BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context);
ArrayList<StatElement> myStats = new ArrayList<StatElement>();
ArrayList<Process> myProcesses = null;
ArrayList<Process> myRetProcesses = new ArrayList<Process>();
// if we are using custom ref. always retrieve "stats current"
if (iStatType == STATS_CUSTOM)
{
myProcesses = mStats.getProcessStats(m_context, BatteryStatsTypes.STATS_CURRENT);
}
else
{
myProcesses = mStats.getProcessStats(m_context, iStatType);
}
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
//Collections.sort(myProcesses);
for (int i = 0; i < myProcesses.size(); i++)
{
Process ps = myProcesses.get(i);
if ( (!bFilter) || ((ps.getSystemTime() + ps.getUserTime()) > 0) )
{
// we must distinguish two situations
// a) we use custom stat type
// b) we use regular stat type
if (iStatType == STATS_CUSTOM)
{
// case a)
// we need t return a delta containing
// if a process is in the new list but not in the custom ref
// the full time is returned
// if a process is in the reference return the delta
// a process can not have disapeared in btwn so we don't need
// to test the reverse case
if (m_myRefs != null)
{
ps.substractFromRef(m_myRefs.m_refProcesses);
// we must recheck if the delta process is still above threshold
if ( (!bFilter) || ((ps.getSystemTime() + ps.getUserTime()) > 0) )
{
myRetProcesses.add(ps);
}
}
else
{
myRetProcesses.clear();
myRetProcesses.add(new Process(NO_CUST_REF, 1, 1, 1));
}
}
else
{
// case b) nothing special
myRetProcesses.add(ps);
}
}
}
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
switch (iSort)
{
case 0:
// by Duration
Comparator<Process> myCompTime = new Process.ProcessTimeComparator();
Collections.sort(myRetProcesses, myCompTime);
break;
case 1:
// by Count
Comparator<Process> myCompCount = new Process.ProcessCountComparator();
Collections.sort(myRetProcesses, myCompCount);
break;
}
for (int i=0; i < myRetProcesses.size(); i++)
{
myStats.add((StatElement) myRetProcesses.get(i));
}
return myStats;
}
/**
* Get the Wakelock Stat to be displayed
* @param bFilter defines if zero-values should be filtered out
* @return a List of Wakelocks sorted by duration (descending)
* @throws Exception if the API call failed
*/
public ArrayList<StatElement> getWakelockStatList(boolean bFilter, int iStatType, int iPctType, int iSort) throws Exception
{
ArrayList<StatElement> myStats = new ArrayList<StatElement>();
BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context);
ArrayList<Wakelock> myWakelocks = null;
ArrayList<Wakelock> myRetWakelocks = new ArrayList<Wakelock>();
// if we are using custom ref. always retrieve "stats current"
if (iStatType == STATS_CUSTOM)
{
myWakelocks = mStats.getWakelockStats(m_context, BatteryStatsTypes.WAKE_TYPE_PARTIAL, BatteryStatsTypes.STATS_CURRENT, iPctType);
}
else
{
myWakelocks = mStats.getWakelockStats(m_context, BatteryStatsTypes.WAKE_TYPE_PARTIAL, iStatType, iPctType);
}
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
Collections.sort(myWakelocks);
for (int i = 0; i < myWakelocks.size(); i++)
{
Wakelock wl = myWakelocks.get(i);
if ( (!bFilter) || ((wl.getDuration()/1000) > 0) )
{
// we must distinguish two situations
// a) we use custom stat type
// b) we use regular stat type
if (iStatType == STATS_CUSTOM)
{
// case a)
// we need t return a delta containing
// if a process is in the new list but not in the custom ref
// the full time is returned
// if a process is in the reference return the delta
// a process can not have disapeared in btwn so we don't need
// to test the reverse case
if (m_myRefs != null)
{
wl.substractFromRef(m_myRefs.m_refWakelocks);
// we must recheck if the delta process is still above threshold
if ( (!bFilter) || ((wl.getDuration()/1000) > 0) )
{
myRetWakelocks.add( wl);
}
}
else
{
myRetWakelocks.clear();
myRetWakelocks.add(new Wakelock(1, NO_CUST_REF, 1, 1, 1));
}
}
else
{
// case b) nothing special
myRetWakelocks.add(wl);
}
}
}
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
switch (iSort)
{
case 0:
// by Duration
Comparator<Wakelock> myCompTime = new Wakelock.WakelockTimeComparator();
Collections.sort(myRetWakelocks, myCompTime);
break;
case 1:
// by Count
Comparator<Wakelock> myCompCount = new Wakelock.WakelockCountComparator();
Collections.sort(myRetWakelocks, myCompCount);
break;
}
for (int i=0; i < myRetWakelocks.size(); i++)
{
myStats.add((StatElement) myRetWakelocks.get(i));
}
// @todo add sorting by settings here: Collections.sort......
return myStats;
}
/**
* Get the Kernel Wakelock Stat to be displayed
* @param bFilter defines if zero-values should be filtered out
* @return a List of Wakelocks sorted by duration (descending)
* @throws Exception if the API call failed
*/
public ArrayList<StatElement> getNativeKernelWakelockStatList(boolean bFilter, int iStatType, int iPctType, int iSort) throws Exception
{
ArrayList<StatElement> myStats = new ArrayList<StatElement>();
ArrayList<NativeKernelWakelock> myKernelWakelocks = Wakelocks.parseProcWakelocks();
ArrayList<NativeKernelWakelock> myRetKernelWakelocks = new ArrayList<NativeKernelWakelock>();
// if we are using custom ref. always retrieve "stats current"
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
Collections.sort(myKernelWakelocks);
String strCurrent = myKernelWakelocks.toString();
String strRef = "";
switch (iStatType)
{
case STATS_UNPLUGGED:
if ( (m_myRefSinceUnplugged != null) && (m_myRefSinceUnplugged.m_refKernelWakelocks != null) )
{
strRef = m_myRefSinceUnplugged.m_refKernelWakelocks.toString();
}
break;
case STATS_CHARGED:
if ( (m_myRefSinceCharged != null) && (m_myRefSinceCharged.m_refKernelWakelocks != null) )
{
strRef = m_myRefSinceCharged.m_refKernelWakelocks.toString();
}
break;
case STATS_CUSTOM:
if ( (m_myRefs != null) && (m_myRefs.m_refKernelWakelocks != null))
{
strRef = m_myRefs.m_refKernelWakelocks.toString();
}
break;
case BatteryStatsTypes.STATS_CURRENT:
strRef = "no reference to substract";
break;
default:
Log.e(TAG, "Unknown StatType " + iStatType + ". No reference found");
break;
}
// Log.i(TAG, "Substracting " + strRef + " from " + strCurrent);
for (int i = 0; i < myKernelWakelocks.size(); i++)
{
NativeKernelWakelock wl = myKernelWakelocks.get(i);
if ( (!bFilter) || ((wl.getDuration()) > 0) )
{
// native kernel wakelocks are parsed from /proc/wakelocks
// and do not know any references "since charged" and "since unplugged"
// those are implemented using special references
switch (iStatType)
{
case STATS_CUSTOM:
// case a)
// we need t return a delta containing
// if a process is in the new list but not in the custom ref
// the full time is returned
// if a process is in the reference return the delta
// a process can not have disapeared in btwn so we don't need
// to test the reverse case
if (m_myRefs != null)
{
wl.substractFromRef(m_myRefs.m_refKernelWakelocks);
// we must recheck if the delta process is still above threshold
if ( (!bFilter) || ((wl.getDuration()) > 0) )
{
myRetKernelWakelocks.add( wl);
}
}
else
{
myRetKernelWakelocks.clear();
myRetKernelWakelocks.add(new NativeKernelWakelock(NO_CUST_REF, 1, 1, 1, 1, 1, 1, 1, 1, 1));
}
break;
case STATS_UNPLUGGED:
if (m_myRefSinceUnplugged != null)
{
wl.substractFromRef(m_myRefSinceUnplugged.m_refKernelWakelocks);
// we must recheck if the delta process is still above threshold
if ( (!bFilter) || ((wl.getDuration()) > 0) )
{
myRetKernelWakelocks.add( wl);
}
}
else
{
myRetKernelWakelocks.clear();
myRetKernelWakelocks.add(new NativeKernelWakelock("No reference since unplugged set yet", 1, 1, 1, 1, 1, 1, 1, 1, 1));
}
break;
case STATS_CHARGED:
if (m_myRefSinceCharged != null)
{
wl.substractFromRef(m_myRefSinceCharged.m_refKernelWakelocks);
// we must recheck if the delta process is still above threshold
if ( (!bFilter) || ((wl.getDuration()) > 0) )
{
myRetKernelWakelocks.add( wl);
}
}
else
{
myRetKernelWakelocks.clear();
myRetKernelWakelocks.add(new NativeKernelWakelock("No reference since charged yet", 1, 1, 1, 1, 1, 1, 1, 1, 1));
}
break;
case BatteryStatsTypes.STATS_CURRENT:
// we must recheck if the delta process is still above threshold
myRetKernelWakelocks.add( wl);
break;
}
}
}
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
switch (iSort)
{
case 0:
// by Duration
Comparator<NativeKernelWakelock> myCompTime = new NativeKernelWakelock.TimeComparator();
Collections.sort(myRetKernelWakelocks, myCompTime);
break;
case 1:
// by Count
Comparator<NativeKernelWakelock> myCompCount = new NativeKernelWakelock.CountComparator();
Collections.sort(myRetKernelWakelocks, myCompCount);
break;
}
for (int i=0; i < myRetKernelWakelocks.size(); i++)
{
myStats.add((StatElement) myRetKernelWakelocks.get(i));
}
// Log.i(TAG, "Result " + myStats.toString());
return myStats;
}
/**
* Get the Network Usage Stat to be displayed
* @param bFilter defines if zero-values should be filtered out
* @return a List of Network usages sorted by duration (descending)
* @throws Exception if the API call failed
*/
public ArrayList<StatElement> getNetworkUsageStatList(boolean bFilter, int iStatType) throws Exception
{
ArrayList<StatElement> myStats = new ArrayList<StatElement>();
BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context);
ArrayList<NetworkUsage> myUsages = null;
// if we are using custom ref. always retrieve "stats current"
if (iStatType == STATS_CUSTOM)
{
myUsages = mStats.getNetworkUsageStats(m_context, BatteryStatsTypes.STATS_CURRENT);
}
else
{
myUsages = mStats.getNetworkUsageStats(m_context, iStatType);
}
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
Collections.sort(myUsages);
for (int i = 0; i < myUsages.size(); i++)
{
NetworkUsage usage = myUsages.get(i);
if ( (!bFilter) || ((usage.getBytesReceived() + usage.getBytesSent()) > 0) )
{
// we must distinguish two situations
// a) we use custom stat type
// b) we use regular stat type
if (iStatType == STATS_CUSTOM)
{
// case a)
// we need t return a delta containing
// if a process is in the new list but not in the custom ref
// the full time is returned
// if a process is in the reference return the delta
// a process can not have disapeared in btwn so we don't need
// to test the reverse case
usage.substractFromRef(m_myRefs.m_refNetwork);
// we must recheck if the delta process is still above threshold
if ( (!bFilter) || ((usage.getBytesReceived() + usage.getBytesSent()) > 0) )
{
myStats.add((StatElement) usage);
}
}
else
{
// case b) nothing special
myStats.add((StatElement) usage);
}
}
}
return myStats;
}
/**
* Get the Other Usage Stat to be displayed
* @param bFilter defines if zero-values should be filtered out
* @return a List of Other usages sorted by duration (descending)
* @throws Exception if the API call failed
*/
public ArrayList<StatElement> getOtherUsageStatList(boolean bFilter, int iStatType) throws Exception
{
BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context);
ArrayList<StatElement> myStats = new ArrayList<StatElement>();
// List to store the other usages to
ArrayList<Misc> myUsages = new ArrayList<Misc>();
long rawRealtime = SystemClock.elapsedRealtime() * 1000;
long batteryRealtime = mStats.getBatteryRealtime(rawRealtime);
long whichRealtime = 0;
long timeBatteryUp = 0;
long timeScreenOn = 0;
long timePhoneOn = 0;
long timeWifiOn = 0;
long timeWifiRunning = 0;
long timeWifiMulticast = 0;
long timeWifiLocked = 0;
long timeWifiScan = 0;
long timeAudioOn = 0;
long timeVideoOn = 0;
long timeBluetoothOn = 0;
long timeDeepSleep = 0;
long timeNoDataConnection = 0;
long timeSignalNone = 0;
long timeSignalPoor = 0;
long timeSignalModerate = 0;
long timeSignalGood = 0;
long timeSignalGreat = 0;
// if we are using custom ref. always retrieve "stats current"
if (iStatType == STATS_CUSTOM)
{
whichRealtime = mStats.computeBatteryRealtime(rawRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeBatteryUp = mStats.computeBatteryUptime(SystemClock.uptimeMillis() * 1000, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeScreenOn = mStats.getScreenOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timePhoneOn = mStats.getPhoneOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiOn = mStats.getWifiOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiRunning = mStats.getGlobalWifiRunningTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiMulticast = mStats.getWifiMulticastTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiLocked = mStats.getFullWifiLockTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiScan = mStats.getScanWifiLockTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeAudioOn = mStats.getAudioTurnedOnTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeVideoOn = mStats.getVideoTurnedOnTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeBluetoothOn = mStats.getBluetoothOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeNoDataConnection= mStats.getPhoneDataConnectionTime(BatteryStatsTypes.DATA_CONNECTION_NONE, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeSignalNone = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_NONE_OR_UNKNOWN, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeSignalPoor = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_POOR, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeSignalModerate = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_MODERATE, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeSignalGood = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_GOOD, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeSignalGreat = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_GREAT, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
}
else
{
whichRealtime = mStats.computeBatteryRealtime(rawRealtime, iStatType) / 1000;
timeBatteryUp = mStats.computeBatteryUptime(SystemClock.uptimeMillis() * 1000, iStatType) / 1000;
timeScreenOn = mStats.getScreenOnTime(batteryRealtime, iStatType) / 1000;
timePhoneOn = mStats.getPhoneOnTime(batteryRealtime, iStatType) / 1000;
timeWifiOn = mStats.getWifiOnTime(batteryRealtime, iStatType) / 1000;
timeWifiRunning = mStats.getGlobalWifiRunningTime(batteryRealtime, iStatType) / 1000;
timeWifiMulticast = mStats.getWifiMulticastTime(m_context, batteryRealtime, iStatType) / 1000;
timeWifiLocked = mStats.getFullWifiLockTime(m_context, batteryRealtime, iStatType) / 1000;
timeWifiScan = mStats.getScanWifiLockTime(m_context, batteryRealtime, iStatType) / 1000;
timeAudioOn = mStats.getAudioTurnedOnTime(m_context, batteryRealtime, iStatType) / 1000;
timeVideoOn = mStats.getVideoTurnedOnTime(m_context, batteryRealtime, iStatType) / 1000;
timeBluetoothOn = mStats.getBluetoothOnTime(batteryRealtime, iStatType) / 1000;
timeNoDataConnection= mStats.getPhoneDataConnectionTime(BatteryStatsTypes.DATA_CONNECTION_NONE, batteryRealtime, iStatType) / 1000;
timeSignalNone = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_NONE_OR_UNKNOWN, batteryRealtime, iStatType) / 1000;
timeSignalPoor = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_POOR, batteryRealtime, iStatType) / 1000;
timeSignalModerate = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_MODERATE, batteryRealtime, iStatType) / 1000;
timeSignalGood = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_GOOD, batteryRealtime, iStatType) / 1000;
timeSignalGreat = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_GREAT, batteryRealtime, iStatType) / 1000;
}
// deep sleep times are independent of stat type
timeDeepSleep = (SystemClock.elapsedRealtime() - SystemClock.uptimeMillis());
long timeElapsed = SystemClock.elapsedRealtime();
Misc deepSleepUsage = new Misc("Deep Sleep", timeDeepSleep, timeElapsed);
+ Log.d(TAG, "Added Deep sleep:" + deepSleepUsage.getData());
// special processing for deep sleep: we must calculate times for stat types != CUSTOM
if (iStatType == STATS_CHARGED)
{
if (m_myRefSinceCharged != null)
{
deepSleepUsage.substractFromRef(m_myRefSinceCharged.m_refOther);
if ( (!bFilter) || (deepSleepUsage.getTimeOn() > 0) )
{
myUsages.add(deepSleepUsage);
}
}
}
else if (iStatType == STATS_UNPLUGGED)
{
if (m_myRefSinceUnplugged != null)
{
deepSleepUsage.substractFromRef(m_myRefSinceUnplugged.m_refOther);
if ( (!bFilter) || (deepSleepUsage.getTimeOn() > 0) )
{
myUsages.add(deepSleepUsage);
}
}
}
else
{
myUsages.add(deepSleepUsage);
}
if (timeBatteryUp > 0)
{
myUsages.add(new Misc("Awake", timeBatteryUp, whichRealtime));
}
if (timeScreenOn > 0)
{
myUsages.add(new Misc("Screen On", timeScreenOn, whichRealtime));
}
if (timePhoneOn > 0)
{
myUsages.add(new Misc("Phone On", timePhoneOn, whichRealtime));
}
if (timeWifiOn > 0)
{
myUsages.add(new Misc("Wifi On", timeWifiOn, whichRealtime));
}
if (timeWifiRunning > 0)
{
myUsages.add(new Misc("Wifi Running", timeWifiRunning, whichRealtime));
}
if (timeBluetoothOn > 0)
{
myUsages.add(new Misc("Bluetooth On", timeBluetoothOn, whichRealtime));
}
if (timeNoDataConnection > 0)
{
myUsages.add(new Misc("No Data Connection", timeNoDataConnection, whichRealtime));
}
if (timeSignalNone > 0)
{
myUsages.add(new Misc("No or Unknown Signal", timeSignalNone, whichRealtime));
}
if (timeSignalPoor > 0)
{
myUsages.add(new Misc("Poor Signal", timeSignalPoor, whichRealtime));
}
if (timeSignalModerate > 0)
{
myUsages.add(new Misc("Moderate Signal", timeSignalModerate, whichRealtime));
}
if (timeSignalGood > 0)
{
myUsages.add(new Misc("Good Signal", timeSignalGood, whichRealtime));
}
if (timeSignalGreat > 0)
{
myUsages.add(new Misc("Great Signal", timeSignalGreat, whichRealtime));
}
// if (timeWifiMulticast > 0)
// {
// myUsages.add(new Misc("Wifi Multicast On", timeWifiMulticast, whichRealtime));
// }
//
// if (timeWifiLocked > 0)
// {
// myUsages.add(new Misc("Wifi Locked", timeWifiLocked, whichRealtime));
// }
//
// if (timeWifiScan > 0)
// {
// myUsages.add(new Misc("Wifi Scan", timeWifiScan, whichRealtime));
// }
//
// if (timeAudioOn > 0)
// {
// myUsages.add(new Misc("Video On", timeAudioOn, whichRealtime));
// }
//
// if (timeVideoOn > 0)
// {
// myUsages.add(new Misc("Video On", timeVideoOn, whichRealtime));
// }
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
Collections.sort(myUsages);
for (int i = 0; i < myUsages.size(); i++)
{
Misc usage = myUsages.get(i);
if ( (!bFilter) || (usage.getTimeOn() > 0) )
{
if (iStatType == STATS_CUSTOM)
{
// case a)
// we need t return a delta containing
// if a process is in the new list but not in the custom ref
// the full time is returned
// if a process is in the reference return the delta
// a process can not have disapeared in btwn so we don't need
// to test the reverse case
if (m_myRefs != null)
{
usage.substractFromRef(m_myRefs.m_refOther);
if ( (!bFilter) || (usage.getTimeOn() > 0) )
{
myStats.add((StatElement) usage);
}
}
else
{
myStats.clear();
myStats.add(new Misc(NO_CUST_REF, 1, 1));
}
}
else
{
// case b)
// nothing special
myStats.add((StatElement) usage);
}
}
}
return myStats;
}
public StatElement getElementByKey(ArrayList<StatElement> myList, String key)
{
StatElement ret = null;
if (myList == null)
{
Log.e(TAG, "getElementByKey failed: null list");
return null;
}
for (int i=0; i < myList.size(); i++)
{
StatElement item = myList.get(i);
if (item.getName().equals(key))
{
ret = item;
break;
}
}
if (ret == null)
{
Log.e(TAG, "getElementByKey failed: " + key + " was not found");
}
return ret;
}
public long sum (ArrayList<StatElement> myList)
{
long ret = 0;
if (myList == null)
{
Log.d(TAG, "sum was called with a null list");
return 0;
}
if (myList.size() == 0)
{
Log.d(TAG, "sum was called with an empty list");
return 0;
}
for (int i=0; i < myList.size(); i++)
{
// make sure nothing goes wrong
try
{
StatElement item = myList.get(i);
ret += item.getValues()[0];
}
catch (Exception e)
{
Log.e(TAG, "An error occcured " + e.getMessage());
GenericLogger.stackTrace(TAG, e.getStackTrace());
}
}
return ret;
}
/**
* Returns true if a custom ref was stored
* @return true is a custom ref exists
*/
public boolean hasCustomRef()
{
return ( (m_myRefs != null) && (m_myRefs.m_refOther != null) );
}
/**
* Returns true if a since charged ref was stored
* @return true is a since charged ref exists
*/
public boolean hasSinceChargedRef()
{
return ( (m_myRefSinceCharged != null) && (m_myRefSinceCharged.m_refKernelWakelocks != null) );
}
/**
* Returns true if a since unplugged ref was stored
* @return true is a since unplugged ref exists
*/
public boolean hasSinceUnpluggedRef()
{
return ( (m_myRefSinceUnplugged != null) && (m_myRefSinceUnplugged.m_refKernelWakelocks != null) );
}
/**
* Saves all data to a point in time defined by user
* This data will be used in a custom "since..." stat type
*/
public void setCustomReference(int iSort)
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(m_context);
boolean bFilterStats = sharedPrefs.getBoolean("filter_data", true);
int iPctType = Integer.valueOf(sharedPrefs.getString("default_wl_ref", "0"));
try
{
if (m_myRefs != null)
{
m_myRefs.m_refOther = null;
m_myRefs.m_refWakelocks = null;
m_myRefs.m_refKernelWakelocks = null;
m_myRefs.m_refAlarms = null;
m_myRefs.m_refProcesses = null;
m_myRefs.m_refNetwork = null;
}
else
{
m_myRefs = new References();
}
// create a copy of each list for further reference
m_myRefs.m_refOther = getOtherUsageStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT);
m_myRefs.m_refWakelocks = getWakelockStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT, iPctType, iSort);
m_myRefs.m_refKernelWakelocks = getNativeKernelWakelockStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT, iPctType, iSort);
m_myRefs.m_refAlarms = getAlarmsStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT);
m_myRefs.m_refProcesses = getProcessStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT, iSort);
m_myRefs.m_refNetwork = getNetworkUsageStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT);
m_myRefs.m_refBatteryRealtime = getBatteryRealtime(BatteryStatsTypes.STATS_CURRENT);
serializeCustomRefToFile();
}
catch (Exception e)
{
Log.e(TAG, "Exception: " + e.getMessage());
//Toast.makeText(m_context, "an error occured while creating the custom reference", Toast.LENGTH_SHORT).show();
m_myRefs.m_refOther = null;
m_myRefs.m_refWakelocks = null;
m_myRefs.m_refKernelWakelocks = null;
m_myRefs.m_refAlarms = null;
m_myRefs.m_refProcesses = null;
m_myRefs.m_refNetwork = null;
m_myRefs.m_refBatteryRealtime = 0;
}
}
/**
* Saves data when battery is fully charged
* This data will be used in the "since charged" stat type
*/
public void setReferenceSinceCharged(int iSort)
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(m_context);
boolean bFilterStats = sharedPrefs.getBoolean("filter_data", true);
int iPctType = Integer.valueOf(sharedPrefs.getString("default_wl_ref", "0"));
try
{
m_myRefSinceCharged = new References();
m_myRefSinceCharged.m_refOther = null;
m_myRefSinceCharged.m_refWakelocks = null;
m_myRefSinceCharged.m_refKernelWakelocks = null;
m_myRefSinceCharged.m_refAlarms = null;
m_myRefSinceCharged.m_refProcesses = null;
m_myRefSinceCharged.m_refNetwork = null;
m_myRefSinceCharged.m_refKernelWakelocks = getNativeKernelWakelockStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT, iPctType, iSort);
m_myRefSinceCharged.m_refAlarms = getAlarmsStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT);
m_myRefSinceCharged.m_refOther = getOtherUsageStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT);
m_myRefSinceCharged.m_refBatteryRealtime = getBatteryRealtime(BatteryStatsTypes.STATS_CURRENT);
serializeSinceChargedRefToFile();
}
catch (Exception e)
{
Log.e(TAG, "Exception: " + e.getMessage());
Toast.makeText(m_context, "an error occured while creating the custom reference", Toast.LENGTH_SHORT).show();
m_myRefSinceCharged.m_refOther = null;
m_myRefSinceCharged.m_refWakelocks = null;
m_myRefSinceCharged.m_refKernelWakelocks = null;
m_myRefSinceCharged.m_refAlarms = null;
m_myRefSinceCharged.m_refProcesses = null;
m_myRefSinceCharged.m_refNetwork = null;
m_myRefSinceCharged.m_refBatteryRealtime = 0;
}
}
/**
* Saves data when the phone is unplugged
* This data will be used in the "since unplugged" stat type
*/
public void setReferenceSinceUnplugged(int iSort)
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(m_context);
boolean bFilterStats = sharedPrefs.getBoolean("filter_data", true);
int iPctType = Integer.valueOf(sharedPrefs.getString("default_wl_ref", "0"));
try
{
m_myRefSinceUnplugged = new References();
m_myRefSinceUnplugged.m_refOther = null;
m_myRefSinceUnplugged.m_refWakelocks = null;
m_myRefSinceUnplugged.m_refKernelWakelocks = null;
m_myRefSinceUnplugged.m_refAlarms = null;
m_myRefSinceUnplugged.m_refProcesses = null;
m_myRefSinceUnplugged.m_refNetwork = null;
m_myRefSinceUnplugged.m_refKernelWakelocks = getNativeKernelWakelockStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT, iPctType, iSort);
m_myRefSinceUnplugged.m_refAlarms = getAlarmsStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT);
m_myRefSinceUnplugged.m_refOther = getOtherUsageStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT);
m_myRefSinceUnplugged.m_refBatteryRealtime = getBatteryRealtime(BatteryStatsTypes.STATS_CURRENT);
serializeSinceUnpluggedRefToFile();
}
catch (Exception e)
{
Log.e(TAG, "Exception: " + e.getMessage());
Toast.makeText(m_context, "an error occured while creating the custom reference", Toast.LENGTH_SHORT).show();
m_myRefSinceUnplugged.m_refOther = null;
m_myRefSinceUnplugged.m_refWakelocks = null;
m_myRefSinceUnplugged.m_refKernelWakelocks = null;
m_myRefSinceUnplugged.m_refAlarms = null;
m_myRefSinceUnplugged.m_refProcesses = null;
m_myRefSinceUnplugged.m_refNetwork = null;
m_myRefSinceUnplugged.m_refBatteryRealtime = 0;
}
}
/**
* Restores state from a bundle
* @param savedInstanceState a bundle
*/
public void restoreFromBundle(Bundle savedInstanceState)
{
m_myRefs.m_refWakelocks = (ArrayList<StatElement>) savedInstanceState.getSerializable("wakelockstate");
m_myRefs.m_refKernelWakelocks = (ArrayList<StatElement>) savedInstanceState.getSerializable("nativekernelwakelockstate");
m_myRefs.m_refAlarms = (ArrayList<StatElement>) savedInstanceState.getSerializable("alarmstate");
m_myRefs.m_refProcesses = (ArrayList<StatElement>) savedInstanceState.getSerializable("processstate");
m_myRefs.m_refOther = (ArrayList<StatElement>) savedInstanceState.getSerializable("otherstate");
m_myRefs.m_refBatteryRealtime = (Long) savedInstanceState.getSerializable("batteryrealtime");
}
/**
* Writes states to a bundle to be temporarily persisted
* @param savedInstanceState a bundle
*/
public void writeToBundle(Bundle savedInstanceState)
{
if (hasCustomRef())
{
savedInstanceState.putSerializable("wakelockstate", m_myRefs.m_refWakelocks);
savedInstanceState.putSerializable("nativekernelwakelockstate", m_myRefs.m_refKernelWakelocks);
savedInstanceState.putSerializable("alarmstate", m_myRefs.m_refAlarms);
savedInstanceState.putSerializable("processstate", m_myRefs.m_refProcesses);
savedInstanceState.putSerializable("otherstate", m_myRefs.m_refOther);
savedInstanceState.putSerializable("networkstate", m_myRefs.m_refNetwork);
savedInstanceState.putSerializable("batteryrealtime", m_myRefs.m_refBatteryRealtime);
}
}
public void serializeCustomRefToFile()
{
if (hasCustomRef())
{
DataStorage.objectToFile(m_context, "custom_ref", m_myRefs);
}
}
public void serializeSinceChargedRefToFile()
{
DataStorage.objectToFile(m_context, "since_charged_ref", m_myRefSinceCharged);
}
public void serializeSinceUnpluggedRefToFile()
{
DataStorage.objectToFile(m_context, "since_unplugged_ref", m_myRefSinceUnplugged);
}
public void deserializeFromFile()
{
m_myRefs = (References) DataStorage.fileToObject(m_context, "custom_ref");
m_myRefSinceCharged = (References) DataStorage.fileToObject(m_context, "since_charged_ref");
m_myRefSinceUnplugged = (References) DataStorage.fileToObject(m_context, "since_unplugged_ref");
}
public void deletedSerializedRefs()
{
References myEmptyRef = new References();
DataStorage.objectToFile(m_context, "custom_ref", myEmptyRef);
DataStorage.objectToFile(m_context, "since_charged_ref", myEmptyRef);
DataStorage.objectToFile(m_context, "since_unplugged_ref", myEmptyRef);
}
/**
* Returns the battery realtime since a given reference
* @param iStatType the reference
* @return the battery realtime
*/
public long getBatteryRealtime(int iStatType)
{
BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context);
if (mStats == null)
{
// an error has occured
return -1;
}
long whichRealtime = 0;
long rawRealtime = SystemClock.elapsedRealtime() * 1000;
if ( (iStatType == StatsProvider.STATS_CUSTOM) && (m_myRefs != null) )
{
whichRealtime = mStats.computeBatteryRealtime(rawRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
whichRealtime -= m_myRefs.m_refBatteryRealtime;
}
else
{
whichRealtime = mStats.computeBatteryRealtime(rawRealtime, iStatType) / 1000;
}
return whichRealtime;
}
/**
* Dumps relevant data to an output file
*
*/
public void writeDumpToFile(int iStatType, int iSort)
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(m_context);
boolean bFilterStats = sharedPrefs.getBoolean("filter_data", true);
int iPctType = Integer.valueOf(sharedPrefs.getString("default_wl_ref", "0"));
if (!DataStorage.isExternalStorageWritable())
{
Log.e(TAG, "External storage can not be written");
Toast.makeText(m_context, "External Storage can not be written", Toast.LENGTH_SHORT).show();
}
try
{
// open file for writing
File root = Environment.getExternalStorageDirectory();
// check if file can be written
if (root.canWrite())
{
String strFilename = "BetterBatteryStats-" + DateUtils.now("yyyy-MM-dd_HHmmssSSS") + ".txt";
File dumpFile = new File(root, strFilename);
FileWriter fw = new FileWriter(dumpFile);
BufferedWriter out = new BufferedWriter(fw);
// write header
out.write("===================\n");
out.write("General Information\n");
out.write("===================\n");
PackageInfo pinfo = m_context.getPackageManager().getPackageInfo(m_context.getPackageName(), 0);
out.write("BetterBatteryStats version: " + pinfo.versionName + "\n");
out.write("Creation Date: " + DateUtils.now() + "\n");
out.write("Statistic Type: (" + iStatType + ") " + statTypeToLabel(iStatType) + "\n");
out.write("Since " + DateUtils.formatDuration(getBatteryRealtime(iStatType)) + "\n");
out.write("VERSION.RELEASE: " + Build.VERSION.RELEASE+"\n");
out.write("BRAND: "+Build.BRAND+"\n");
out.write("DEVICE: "+Build.DEVICE+"\n");
out.write("MANUFACTURER: "+Build.MANUFACTURER+"\n");
out.write("MODEL: "+Build.MODEL+"\n");
out.write("RADIO: "+Build.RADIO+"\n");
out.write("BOOTLOADER: "+Build.BOOTLOADER+"\n");
out.write("FINGERPRINT: "+Build.FINGERPRINT+"\n");
out.write("HARDWARE: "+Build.HARDWARE+"\n");
out.write("ID: "+Build.ID+"\n");
out.write("Rooted: "+ RootDetection.hasSuRights("dumpsys alarm") + "\n");
// write timing info
boolean bDumpChapter = sharedPrefs.getBoolean("show_other", true);
if (bDumpChapter)
{
out.write("===========\n");
out.write("Other Usage\n");
out.write("===========\n");
dumpList(getOtherUsageStatList(bFilterStats, iStatType), out);
}
bDumpChapter = sharedPrefs.getBoolean("show_pwl", true);
if (bDumpChapter)
{
// write wakelock info
out.write("=========\n");
out.write("Wakelocks\n");
out.write("=========\n");
dumpList(getWakelockStatList(bFilterStats, iStatType, iPctType, iSort), out);
}
bDumpChapter = sharedPrefs.getBoolean("show_kwl", true);
if (bDumpChapter)
{
// write kernel wakelock info
out.write("================\n");
out.write("Kernel Wakelocks\n");
out.write("================\n");
dumpList(getNativeKernelWakelockStatList(bFilterStats, iStatType, iPctType, iSort), out);
}
bDumpChapter = sharedPrefs.getBoolean("show_proc", false);
if (bDumpChapter)
{
// write process info
out.write("=========\n");
out.write("Processes\n");
out.write("=========\n");
dumpList(getProcessStatList(bFilterStats, iStatType, iSort), out);
}
bDumpChapter = sharedPrefs.getBoolean("show_alarm", true);
if (bDumpChapter)
{
// write alarms info
out.write("======================\n");
out.write("Alarms (requires root)\n");
out.write("======================\n");
dumpList(getAlarmsStatList(bFilterStats, iStatType), out);
}
// write network info
//out.write("=======\n");
//out.write("Network\n");
//out.write("=======\n");
//dumpList(getNetworkUsageStatList(bFilterStats, m_iStatType), out);
bDumpChapter = sharedPrefs.getBoolean("show_serv", false);
if (bDumpChapter)
{
out.write("========\n");
out.write("Services\n");
out.write("========\n");
out.write("Active since: The time when the service was first made active, either by someone starting or binding to it.\n");
out.write("Last activity: The time when there was last activity in the service (either explicit requests to start it or clients binding to it)\n");
out.write("See http://developer.android.com/reference/android/app/ActivityManager.RunningServiceInfo.html\n");
ActivityManager am = (ActivityManager)m_context.getSystemService(m_context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> rs = am.getRunningServices(50);
for (int i=0; i < rs.size(); i++) {
ActivityManager.RunningServiceInfo rsi = rs.get(i);
out.write(rsi.process + " (" + rsi.service.getClassName() + ")\n");
out.write(" Active since: " + DateUtils.formatDuration(rsi.activeSince) + "\n");
out.write(" Last activity: " + DateUtils.formatDuration(rsi.lastActivityTime) + "\n");
out.write(" Crash count:" + rsi.crashCount + "\n");
}
}
// see http://androidsnippets.com/show-all-running-services
// close file
out.close();
Toast.makeText(m_context, "Dump witten: " + strFilename, Toast.LENGTH_SHORT).show();
}
else
{
Log.i(TAG, "Write error. " + Environment.getExternalStorageDirectory() + " couldn't be written");
Toast.makeText(m_context, "No dump created. " + Environment.getExternalStorageDirectory() + " is probably unmounted.", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
Log.e(TAG, "Exception: " + e.getMessage());
// Toast.makeText(m_context, "an error occured while dumping the statistics", Toast.LENGTH_SHORT).show();
}
}
/**
* Dump the elements on one list
* @param myList a list of StatElement
*/
private void dumpList(List<StatElement> myList, BufferedWriter out) throws IOException
{
if (myList != null)
{
for (int i = 0; i < myList.size(); i++)
{
out.write(myList.get(i).getDumpData(m_context) + "\n");
}
}
}
/**
* translate the stat type (see arrays.xml) to the corresponding label
* @param position the spinner position
* @return the stat type
*/
public static String statTypeToLabel(int statType)
{
String strRet = "";
switch (statType)
{
case 0:
strRet = "Since Charged";
break;
case 3:
strRet = "Since Unplugged";
break;
case 4:
strRet = "Custom Reference";
break;
}
return strRet;
}
/**
* translate the stat type (see arrays.xml) to the corresponding short label
* @param position the spinner position
* @return the stat type
*/
public static String statTypeToLabelShort(int statType)
{
String strRet = "";
switch (statType)
{
case 0:
strRet = "Charged";
break;
case 3:
strRet = "Unpl.";
break;
case 4:
strRet = "Custom";
break;
}
return strRet;
}
/**
* translate the stat type (see arrays.xml) to the corresponding label
* @param position the spinner position
* @return the stat type
*/
public String statTypeToUrl(int statType)
{
String strRet = statTypeToLabel(statType);
// remove spaces
StringTokenizer st = new StringTokenizer(strRet," ",false);
String strCleaned = "";
while (st.hasMoreElements())
{
strCleaned += st.nextElement();
}
return strCleaned;
}
/**
* translate the stat (see arrays.xml) to the corresponding label
* @param position the spinner position
* @return the stat
*/
private String statToLabel(int iStat)
{
String strRet = "";
String[] statsArray = m_context.getResources().getStringArray(R.array.stats);
strRet = statsArray[iStat];
// switch (iStat)
// {
// // constants are related to arrays.xml string-array name="stats"
// case 0:
// strRet = "Process";
// break;
//
// case 1:
// strRet = "Partial Wakelocks";
// break;
//
// case 2:
// strRet = "Other";
// break;
//
// case 3:
// strRet = "Kernel Wakelocks";
// break;
//
// case 4:
// strRet = "Alarms";
// break;
//
// }
return strRet;
}
/**
* translate the stat (see arrays.xml) to the corresponding label
* @param position the spinner position
* @return the stat
*/
public String statToUrl(int stat)
{
String strRet = statToLabel(stat);
// remove spaces
StringTokenizer st = new StringTokenizer(strRet," ",false);
String strCleaned = "";
while (st.hasMoreElements())
{
strCleaned += st.nextElement();
}
return strCleaned;
}
/**
* translate the spinner position (see arrays.xml) to the stat type
* @param position the spinner position
* @return the stat type
*/
public static int statTypeFromPosition(int position)
{
int iRet = 0;
switch (position)
{
case 0:
iRet = STATS_CHARGED;
break;
case 1:
iRet = STATS_UNPLUGGED;
break;
case 2:
iRet = STATS_CUSTOM;
break;
}
return iRet;
}
/**
* translate the stat type to the spinner position (see arrays.xml)
* @param iStatType the stat type
* @return the spinner position
*/
public int positionFromStatType(int iStatType)
{
int iRet = 0;
switch (iStatType)
{
case 0:
iRet = 0;
break;
case 1:
iRet = 1;
break;
case 2:
iRet = 2;
break;
}
return iRet;
}
}
| true | true | public ArrayList<StatElement> getOtherUsageStatList(boolean bFilter, int iStatType) throws Exception
{
BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context);
ArrayList<StatElement> myStats = new ArrayList<StatElement>();
// List to store the other usages to
ArrayList<Misc> myUsages = new ArrayList<Misc>();
long rawRealtime = SystemClock.elapsedRealtime() * 1000;
long batteryRealtime = mStats.getBatteryRealtime(rawRealtime);
long whichRealtime = 0;
long timeBatteryUp = 0;
long timeScreenOn = 0;
long timePhoneOn = 0;
long timeWifiOn = 0;
long timeWifiRunning = 0;
long timeWifiMulticast = 0;
long timeWifiLocked = 0;
long timeWifiScan = 0;
long timeAudioOn = 0;
long timeVideoOn = 0;
long timeBluetoothOn = 0;
long timeDeepSleep = 0;
long timeNoDataConnection = 0;
long timeSignalNone = 0;
long timeSignalPoor = 0;
long timeSignalModerate = 0;
long timeSignalGood = 0;
long timeSignalGreat = 0;
// if we are using custom ref. always retrieve "stats current"
if (iStatType == STATS_CUSTOM)
{
whichRealtime = mStats.computeBatteryRealtime(rawRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeBatteryUp = mStats.computeBatteryUptime(SystemClock.uptimeMillis() * 1000, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeScreenOn = mStats.getScreenOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timePhoneOn = mStats.getPhoneOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiOn = mStats.getWifiOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiRunning = mStats.getGlobalWifiRunningTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiMulticast = mStats.getWifiMulticastTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiLocked = mStats.getFullWifiLockTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiScan = mStats.getScanWifiLockTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeAudioOn = mStats.getAudioTurnedOnTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeVideoOn = mStats.getVideoTurnedOnTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeBluetoothOn = mStats.getBluetoothOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeNoDataConnection= mStats.getPhoneDataConnectionTime(BatteryStatsTypes.DATA_CONNECTION_NONE, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeSignalNone = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_NONE_OR_UNKNOWN, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeSignalPoor = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_POOR, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeSignalModerate = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_MODERATE, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeSignalGood = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_GOOD, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeSignalGreat = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_GREAT, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
}
else
{
whichRealtime = mStats.computeBatteryRealtime(rawRealtime, iStatType) / 1000;
timeBatteryUp = mStats.computeBatteryUptime(SystemClock.uptimeMillis() * 1000, iStatType) / 1000;
timeScreenOn = mStats.getScreenOnTime(batteryRealtime, iStatType) / 1000;
timePhoneOn = mStats.getPhoneOnTime(batteryRealtime, iStatType) / 1000;
timeWifiOn = mStats.getWifiOnTime(batteryRealtime, iStatType) / 1000;
timeWifiRunning = mStats.getGlobalWifiRunningTime(batteryRealtime, iStatType) / 1000;
timeWifiMulticast = mStats.getWifiMulticastTime(m_context, batteryRealtime, iStatType) / 1000;
timeWifiLocked = mStats.getFullWifiLockTime(m_context, batteryRealtime, iStatType) / 1000;
timeWifiScan = mStats.getScanWifiLockTime(m_context, batteryRealtime, iStatType) / 1000;
timeAudioOn = mStats.getAudioTurnedOnTime(m_context, batteryRealtime, iStatType) / 1000;
timeVideoOn = mStats.getVideoTurnedOnTime(m_context, batteryRealtime, iStatType) / 1000;
timeBluetoothOn = mStats.getBluetoothOnTime(batteryRealtime, iStatType) / 1000;
timeNoDataConnection= mStats.getPhoneDataConnectionTime(BatteryStatsTypes.DATA_CONNECTION_NONE, batteryRealtime, iStatType) / 1000;
timeSignalNone = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_NONE_OR_UNKNOWN, batteryRealtime, iStatType) / 1000;
timeSignalPoor = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_POOR, batteryRealtime, iStatType) / 1000;
timeSignalModerate = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_MODERATE, batteryRealtime, iStatType) / 1000;
timeSignalGood = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_GOOD, batteryRealtime, iStatType) / 1000;
timeSignalGreat = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_GREAT, batteryRealtime, iStatType) / 1000;
}
// deep sleep times are independent of stat type
timeDeepSleep = (SystemClock.elapsedRealtime() - SystemClock.uptimeMillis());
long timeElapsed = SystemClock.elapsedRealtime();
Misc deepSleepUsage = new Misc("Deep Sleep", timeDeepSleep, timeElapsed);
// special processing for deep sleep: we must calculate times for stat types != CUSTOM
if (iStatType == STATS_CHARGED)
{
if (m_myRefSinceCharged != null)
{
deepSleepUsage.substractFromRef(m_myRefSinceCharged.m_refOther);
if ( (!bFilter) || (deepSleepUsage.getTimeOn() > 0) )
{
myUsages.add(deepSleepUsage);
}
}
}
else if (iStatType == STATS_UNPLUGGED)
{
if (m_myRefSinceUnplugged != null)
{
deepSleepUsage.substractFromRef(m_myRefSinceUnplugged.m_refOther);
if ( (!bFilter) || (deepSleepUsage.getTimeOn() > 0) )
{
myUsages.add(deepSleepUsage);
}
}
}
else
{
myUsages.add(deepSleepUsage);
}
if (timeBatteryUp > 0)
{
myUsages.add(new Misc("Awake", timeBatteryUp, whichRealtime));
}
if (timeScreenOn > 0)
{
myUsages.add(new Misc("Screen On", timeScreenOn, whichRealtime));
}
if (timePhoneOn > 0)
{
myUsages.add(new Misc("Phone On", timePhoneOn, whichRealtime));
}
if (timeWifiOn > 0)
{
myUsages.add(new Misc("Wifi On", timeWifiOn, whichRealtime));
}
if (timeWifiRunning > 0)
{
myUsages.add(new Misc("Wifi Running", timeWifiRunning, whichRealtime));
}
if (timeBluetoothOn > 0)
{
myUsages.add(new Misc("Bluetooth On", timeBluetoothOn, whichRealtime));
}
if (timeNoDataConnection > 0)
{
myUsages.add(new Misc("No Data Connection", timeNoDataConnection, whichRealtime));
}
if (timeSignalNone > 0)
{
myUsages.add(new Misc("No or Unknown Signal", timeSignalNone, whichRealtime));
}
if (timeSignalPoor > 0)
{
myUsages.add(new Misc("Poor Signal", timeSignalPoor, whichRealtime));
}
if (timeSignalModerate > 0)
{
myUsages.add(new Misc("Moderate Signal", timeSignalModerate, whichRealtime));
}
if (timeSignalGood > 0)
{
myUsages.add(new Misc("Good Signal", timeSignalGood, whichRealtime));
}
if (timeSignalGreat > 0)
{
myUsages.add(new Misc("Great Signal", timeSignalGreat, whichRealtime));
}
// if (timeWifiMulticast > 0)
// {
// myUsages.add(new Misc("Wifi Multicast On", timeWifiMulticast, whichRealtime));
// }
//
// if (timeWifiLocked > 0)
// {
// myUsages.add(new Misc("Wifi Locked", timeWifiLocked, whichRealtime));
// }
//
// if (timeWifiScan > 0)
// {
// myUsages.add(new Misc("Wifi Scan", timeWifiScan, whichRealtime));
// }
//
// if (timeAudioOn > 0)
// {
// myUsages.add(new Misc("Video On", timeAudioOn, whichRealtime));
// }
//
// if (timeVideoOn > 0)
// {
// myUsages.add(new Misc("Video On", timeVideoOn, whichRealtime));
// }
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
Collections.sort(myUsages);
for (int i = 0; i < myUsages.size(); i++)
{
Misc usage = myUsages.get(i);
if ( (!bFilter) || (usage.getTimeOn() > 0) )
{
if (iStatType == STATS_CUSTOM)
{
// case a)
// we need t return a delta containing
// if a process is in the new list but not in the custom ref
// the full time is returned
// if a process is in the reference return the delta
// a process can not have disapeared in btwn so we don't need
// to test the reverse case
if (m_myRefs != null)
{
usage.substractFromRef(m_myRefs.m_refOther);
if ( (!bFilter) || (usage.getTimeOn() > 0) )
{
myStats.add((StatElement) usage);
}
}
else
{
myStats.clear();
myStats.add(new Misc(NO_CUST_REF, 1, 1));
}
}
else
{
// case b)
// nothing special
myStats.add((StatElement) usage);
}
}
}
return myStats;
}
| public ArrayList<StatElement> getOtherUsageStatList(boolean bFilter, int iStatType) throws Exception
{
BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context);
ArrayList<StatElement> myStats = new ArrayList<StatElement>();
// List to store the other usages to
ArrayList<Misc> myUsages = new ArrayList<Misc>();
long rawRealtime = SystemClock.elapsedRealtime() * 1000;
long batteryRealtime = mStats.getBatteryRealtime(rawRealtime);
long whichRealtime = 0;
long timeBatteryUp = 0;
long timeScreenOn = 0;
long timePhoneOn = 0;
long timeWifiOn = 0;
long timeWifiRunning = 0;
long timeWifiMulticast = 0;
long timeWifiLocked = 0;
long timeWifiScan = 0;
long timeAudioOn = 0;
long timeVideoOn = 0;
long timeBluetoothOn = 0;
long timeDeepSleep = 0;
long timeNoDataConnection = 0;
long timeSignalNone = 0;
long timeSignalPoor = 0;
long timeSignalModerate = 0;
long timeSignalGood = 0;
long timeSignalGreat = 0;
// if we are using custom ref. always retrieve "stats current"
if (iStatType == STATS_CUSTOM)
{
whichRealtime = mStats.computeBatteryRealtime(rawRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeBatteryUp = mStats.computeBatteryUptime(SystemClock.uptimeMillis() * 1000, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeScreenOn = mStats.getScreenOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timePhoneOn = mStats.getPhoneOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiOn = mStats.getWifiOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiRunning = mStats.getGlobalWifiRunningTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiMulticast = mStats.getWifiMulticastTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiLocked = mStats.getFullWifiLockTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiScan = mStats.getScanWifiLockTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeAudioOn = mStats.getAudioTurnedOnTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeVideoOn = mStats.getVideoTurnedOnTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeBluetoothOn = mStats.getBluetoothOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeNoDataConnection= mStats.getPhoneDataConnectionTime(BatteryStatsTypes.DATA_CONNECTION_NONE, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeSignalNone = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_NONE_OR_UNKNOWN, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeSignalPoor = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_POOR, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeSignalModerate = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_MODERATE, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeSignalGood = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_GOOD, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeSignalGreat = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_GREAT, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
}
else
{
whichRealtime = mStats.computeBatteryRealtime(rawRealtime, iStatType) / 1000;
timeBatteryUp = mStats.computeBatteryUptime(SystemClock.uptimeMillis() * 1000, iStatType) / 1000;
timeScreenOn = mStats.getScreenOnTime(batteryRealtime, iStatType) / 1000;
timePhoneOn = mStats.getPhoneOnTime(batteryRealtime, iStatType) / 1000;
timeWifiOn = mStats.getWifiOnTime(batteryRealtime, iStatType) / 1000;
timeWifiRunning = mStats.getGlobalWifiRunningTime(batteryRealtime, iStatType) / 1000;
timeWifiMulticast = mStats.getWifiMulticastTime(m_context, batteryRealtime, iStatType) / 1000;
timeWifiLocked = mStats.getFullWifiLockTime(m_context, batteryRealtime, iStatType) / 1000;
timeWifiScan = mStats.getScanWifiLockTime(m_context, batteryRealtime, iStatType) / 1000;
timeAudioOn = mStats.getAudioTurnedOnTime(m_context, batteryRealtime, iStatType) / 1000;
timeVideoOn = mStats.getVideoTurnedOnTime(m_context, batteryRealtime, iStatType) / 1000;
timeBluetoothOn = mStats.getBluetoothOnTime(batteryRealtime, iStatType) / 1000;
timeNoDataConnection= mStats.getPhoneDataConnectionTime(BatteryStatsTypes.DATA_CONNECTION_NONE, batteryRealtime, iStatType) / 1000;
timeSignalNone = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_NONE_OR_UNKNOWN, batteryRealtime, iStatType) / 1000;
timeSignalPoor = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_POOR, batteryRealtime, iStatType) / 1000;
timeSignalModerate = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_MODERATE, batteryRealtime, iStatType) / 1000;
timeSignalGood = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_GOOD, batteryRealtime, iStatType) / 1000;
timeSignalGreat = mStats.getPhoneSignalStrengthTime(BatteryStatsTypes.SIGNAL_STRENGTH_GREAT, batteryRealtime, iStatType) / 1000;
}
// deep sleep times are independent of stat type
timeDeepSleep = (SystemClock.elapsedRealtime() - SystemClock.uptimeMillis());
long timeElapsed = SystemClock.elapsedRealtime();
Misc deepSleepUsage = new Misc("Deep Sleep", timeDeepSleep, timeElapsed);
Log.d(TAG, "Added Deep sleep:" + deepSleepUsage.getData());
// special processing for deep sleep: we must calculate times for stat types != CUSTOM
if (iStatType == STATS_CHARGED)
{
if (m_myRefSinceCharged != null)
{
deepSleepUsage.substractFromRef(m_myRefSinceCharged.m_refOther);
if ( (!bFilter) || (deepSleepUsage.getTimeOn() > 0) )
{
myUsages.add(deepSleepUsage);
}
}
}
else if (iStatType == STATS_UNPLUGGED)
{
if (m_myRefSinceUnplugged != null)
{
deepSleepUsage.substractFromRef(m_myRefSinceUnplugged.m_refOther);
if ( (!bFilter) || (deepSleepUsage.getTimeOn() > 0) )
{
myUsages.add(deepSleepUsage);
}
}
}
else
{
myUsages.add(deepSleepUsage);
}
if (timeBatteryUp > 0)
{
myUsages.add(new Misc("Awake", timeBatteryUp, whichRealtime));
}
if (timeScreenOn > 0)
{
myUsages.add(new Misc("Screen On", timeScreenOn, whichRealtime));
}
if (timePhoneOn > 0)
{
myUsages.add(new Misc("Phone On", timePhoneOn, whichRealtime));
}
if (timeWifiOn > 0)
{
myUsages.add(new Misc("Wifi On", timeWifiOn, whichRealtime));
}
if (timeWifiRunning > 0)
{
myUsages.add(new Misc("Wifi Running", timeWifiRunning, whichRealtime));
}
if (timeBluetoothOn > 0)
{
myUsages.add(new Misc("Bluetooth On", timeBluetoothOn, whichRealtime));
}
if (timeNoDataConnection > 0)
{
myUsages.add(new Misc("No Data Connection", timeNoDataConnection, whichRealtime));
}
if (timeSignalNone > 0)
{
myUsages.add(new Misc("No or Unknown Signal", timeSignalNone, whichRealtime));
}
if (timeSignalPoor > 0)
{
myUsages.add(new Misc("Poor Signal", timeSignalPoor, whichRealtime));
}
if (timeSignalModerate > 0)
{
myUsages.add(new Misc("Moderate Signal", timeSignalModerate, whichRealtime));
}
if (timeSignalGood > 0)
{
myUsages.add(new Misc("Good Signal", timeSignalGood, whichRealtime));
}
if (timeSignalGreat > 0)
{
myUsages.add(new Misc("Great Signal", timeSignalGreat, whichRealtime));
}
// if (timeWifiMulticast > 0)
// {
// myUsages.add(new Misc("Wifi Multicast On", timeWifiMulticast, whichRealtime));
// }
//
// if (timeWifiLocked > 0)
// {
// myUsages.add(new Misc("Wifi Locked", timeWifiLocked, whichRealtime));
// }
//
// if (timeWifiScan > 0)
// {
// myUsages.add(new Misc("Wifi Scan", timeWifiScan, whichRealtime));
// }
//
// if (timeAudioOn > 0)
// {
// myUsages.add(new Misc("Video On", timeAudioOn, whichRealtime));
// }
//
// if (timeVideoOn > 0)
// {
// myUsages.add(new Misc("Video On", timeVideoOn, whichRealtime));
// }
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
Collections.sort(myUsages);
for (int i = 0; i < myUsages.size(); i++)
{
Misc usage = myUsages.get(i);
if ( (!bFilter) || (usage.getTimeOn() > 0) )
{
if (iStatType == STATS_CUSTOM)
{
// case a)
// we need t return a delta containing
// if a process is in the new list but not in the custom ref
// the full time is returned
// if a process is in the reference return the delta
// a process can not have disapeared in btwn so we don't need
// to test the reverse case
if (m_myRefs != null)
{
usage.substractFromRef(m_myRefs.m_refOther);
if ( (!bFilter) || (usage.getTimeOn() > 0) )
{
myStats.add((StatElement) usage);
}
}
else
{
myStats.clear();
myStats.add(new Misc(NO_CUST_REF, 1, 1));
}
}
else
{
// case b)
// nothing special
myStats.add((StatElement) usage);
}
}
}
return myStats;
}
|
diff --git a/gfa-core/src/main/java/com/lemoulinstudio/gfa/core/time/RenderTimer.java b/gfa-core/src/main/java/com/lemoulinstudio/gfa/core/time/RenderTimer.java
index 7c3c4a3..0a6d769 100755
--- a/gfa-core/src/main/java/com/lemoulinstudio/gfa/core/time/RenderTimer.java
+++ b/gfa-core/src/main/java/com/lemoulinstudio/gfa/core/time/RenderTimer.java
@@ -1,118 +1,120 @@
package com.lemoulinstudio.gfa.core.time;
import com.lemoulinstudio.gfa.core.dma.Dma;
import com.lemoulinstudio.gfa.core.gfx.Lcd;
import com.lemoulinstudio.gfa.core.memory.GfaMMU;
import com.lemoulinstudio.gfa.core.memory.IORegisterSpace_8_16_32;
public class RenderTimer {
private IORegisterSpace_8_16_32 ioMem;
private Lcd lcd;
private Dma dma0;
private Dma dma1;
private Dma dma2;
private Dma dma3;
private int xDisplay;
private int yDisplay;
private boolean oldIsInHBlank;
private boolean oldIsInVBlank;
private boolean oldIsVCountMatch;
public RenderTimer() {
reset();
}
public void connectToMemory(GfaMMU memory) {
ioMem = (IORegisterSpace_8_16_32) memory.getMemoryBank(0x04);
}
public void connectToLcd(Lcd lcd) {
this.lcd = lcd;
}
public void connectToDma0(Dma dma0) {
this.dma0 = dma0;
}
public void connectToDma1(Dma dma1) {
this.dma1 = dma1;
}
public void connectToDma2(Dma dma2) {
this.dma2 = dma2;
}
public void connectToDma3(Dma dma3) {
this.dma3 = dma3;
}
public final void reset() {
xDisplay = 0;
yDisplay = 0;
oldIsInHBlank = false;
oldIsInVBlank = false;
oldIsVCountMatch = false;
}
public void addTime(int nbCycles) {
// Update hValue and vValue.
xDisplay += nbCycles;
if (xDisplay >= 308 * 4) {
xDisplay -= 308 * 4;
yDisplay++;
if (yDisplay >= 228)
yDisplay = 0;
ioMem.setYScanline(yDisplay);
}
// Update the bits of the display status.
boolean isInHBlank = (xDisplay >= 240 * 4);
boolean isInVBlank = (yDisplay >= 160);
boolean isVCountMatch = (yDisplay == ioMem.getVCountValue());
ioMem.setIsHBlank(isInHBlank);
ioMem.setIsVBlank(isInVBlank);
ioMem.setIsVCountMatch(isVCountMatch);
// Check if it is time to draw a line.
if (!oldIsInHBlank && isInHBlank && !isInVBlank)
lcd.drawLine(yDisplay);
// Handle the trigger of the DMAs and the HBlank interrupt.
- if (!oldIsInHBlank && isInHBlank && !isInVBlank) {
- dma0.notifyHBlank();
- dma1.notifyHBlank();
- dma2.notifyHBlank();
- dma3.notifyHBlank();
+ if (!oldIsInHBlank && isInHBlank) {
+ if (!isInVBlank) {
+ dma0.notifyHBlank();
+ dma1.notifyHBlank();
+ dma2.notifyHBlank();
+ dma3.notifyHBlank();
+ }
if (ioMem.isHBlankInterruptEnabled())
ioMem.genInterrupt(IORegisterSpace_8_16_32.hBlankInterruptBit);
}
// Handle the trigger of the DMAs and the VBlank interrupt.
if (!oldIsInVBlank && isInVBlank) {
dma0.notifyVBlank();
dma1.notifyVBlank();
dma2.notifyVBlank();
dma3.notifyVBlank();
if (ioMem.isVBlankInterruptEnabled())
ioMem.genInterrupt(IORegisterSpace_8_16_32.vBlankInterruptBit);
}
// Handle the trigger of the VCount interrupt.
if (!oldIsVCountMatch && isVCountMatch)
if (ioMem.isVCountInterruptEnabled())
ioMem.genInterrupt(IORegisterSpace_8_16_32.vCountInterruptBit);
oldIsInHBlank = isInHBlank;
oldIsInVBlank = isInVBlank;
oldIsVCountMatch = isVCountMatch;
}
}
| true | true | public void addTime(int nbCycles) {
// Update hValue and vValue.
xDisplay += nbCycles;
if (xDisplay >= 308 * 4) {
xDisplay -= 308 * 4;
yDisplay++;
if (yDisplay >= 228)
yDisplay = 0;
ioMem.setYScanline(yDisplay);
}
// Update the bits of the display status.
boolean isInHBlank = (xDisplay >= 240 * 4);
boolean isInVBlank = (yDisplay >= 160);
boolean isVCountMatch = (yDisplay == ioMem.getVCountValue());
ioMem.setIsHBlank(isInHBlank);
ioMem.setIsVBlank(isInVBlank);
ioMem.setIsVCountMatch(isVCountMatch);
// Check if it is time to draw a line.
if (!oldIsInHBlank && isInHBlank && !isInVBlank)
lcd.drawLine(yDisplay);
// Handle the trigger of the DMAs and the HBlank interrupt.
if (!oldIsInHBlank && isInHBlank && !isInVBlank) {
dma0.notifyHBlank();
dma1.notifyHBlank();
dma2.notifyHBlank();
dma3.notifyHBlank();
if (ioMem.isHBlankInterruptEnabled())
ioMem.genInterrupt(IORegisterSpace_8_16_32.hBlankInterruptBit);
}
// Handle the trigger of the DMAs and the VBlank interrupt.
if (!oldIsInVBlank && isInVBlank) {
dma0.notifyVBlank();
dma1.notifyVBlank();
dma2.notifyVBlank();
dma3.notifyVBlank();
if (ioMem.isVBlankInterruptEnabled())
ioMem.genInterrupt(IORegisterSpace_8_16_32.vBlankInterruptBit);
}
// Handle the trigger of the VCount interrupt.
if (!oldIsVCountMatch && isVCountMatch)
if (ioMem.isVCountInterruptEnabled())
ioMem.genInterrupt(IORegisterSpace_8_16_32.vCountInterruptBit);
oldIsInHBlank = isInHBlank;
oldIsInVBlank = isInVBlank;
oldIsVCountMatch = isVCountMatch;
}
| public void addTime(int nbCycles) {
// Update hValue and vValue.
xDisplay += nbCycles;
if (xDisplay >= 308 * 4) {
xDisplay -= 308 * 4;
yDisplay++;
if (yDisplay >= 228)
yDisplay = 0;
ioMem.setYScanline(yDisplay);
}
// Update the bits of the display status.
boolean isInHBlank = (xDisplay >= 240 * 4);
boolean isInVBlank = (yDisplay >= 160);
boolean isVCountMatch = (yDisplay == ioMem.getVCountValue());
ioMem.setIsHBlank(isInHBlank);
ioMem.setIsVBlank(isInVBlank);
ioMem.setIsVCountMatch(isVCountMatch);
// Check if it is time to draw a line.
if (!oldIsInHBlank && isInHBlank && !isInVBlank)
lcd.drawLine(yDisplay);
// Handle the trigger of the DMAs and the HBlank interrupt.
if (!oldIsInHBlank && isInHBlank) {
if (!isInVBlank) {
dma0.notifyHBlank();
dma1.notifyHBlank();
dma2.notifyHBlank();
dma3.notifyHBlank();
}
if (ioMem.isHBlankInterruptEnabled())
ioMem.genInterrupt(IORegisterSpace_8_16_32.hBlankInterruptBit);
}
// Handle the trigger of the DMAs and the VBlank interrupt.
if (!oldIsInVBlank && isInVBlank) {
dma0.notifyVBlank();
dma1.notifyVBlank();
dma2.notifyVBlank();
dma3.notifyVBlank();
if (ioMem.isVBlankInterruptEnabled())
ioMem.genInterrupt(IORegisterSpace_8_16_32.vBlankInterruptBit);
}
// Handle the trigger of the VCount interrupt.
if (!oldIsVCountMatch && isVCountMatch)
if (ioMem.isVCountInterruptEnabled())
ioMem.genInterrupt(IORegisterSpace_8_16_32.vCountInterruptBit);
oldIsInHBlank = isInHBlank;
oldIsInVBlank = isInVBlank;
oldIsVCountMatch = isVCountMatch;
}
|
diff --git a/modules/DesktopImport/src/main/java/org/gephi/desktop/importer/ReportPanel.java b/modules/DesktopImport/src/main/java/org/gephi/desktop/importer/ReportPanel.java
index 325e7d346..5b15effea 100644
--- a/modules/DesktopImport/src/main/java/org/gephi/desktop/importer/ReportPanel.java
+++ b/modules/DesktopImport/src/main/java/org/gephi/desktop/importer/ReportPanel.java
@@ -1,880 +1,880 @@
/*
Copyright 2008-2010 Gephi
Authors : Mathieu Bastian <[email protected]>
Website : http://www.gephi.org
This file is part of Gephi.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
Copyright 2011 Gephi Consortium. All rights reserved.
The contents of this file are subject to the terms of either the GNU
General Public License Version 3 only ("GPL") or the Common
Development and Distribution License("CDDL") (collectively, the
"License"). You may not use this file except in compliance with the
License. You can obtain a copy of the License at
http://gephi.org/about/legal/license-notice/
or /cddl-1.0.txt and /gpl-3.0.txt. See the License for the
specific language governing permissions and limitations under the
License. When distributing the software, include this License Header
Notice in each file and include the License files at
/cddl-1.0.txt and /gpl-3.0.txt. If applicable, add the following below the
License Header, with the fields enclosed by brackets [] replaced by
your own identifying information:
"Portions Copyrighted [year] [name of copyright owner]"
If you wish your version of this file to be governed by only the CDDL
or only the GPL Version 3, indicate your decision by adding
"[Contributor] elects to include this software in this distribution
under the [CDDL or GPL Version 3] license." If you do not indicate a
single choice of license, a recipient has the option to distribute
your version of this file under either the CDDL, the GPL Version 3 or
to extend the choice of license to its licensees as provided above.
However, if you add GPL Version 3 code and therefore, elected the GPL
Version 3 license, then the option applies only if the new code is
made subject to such option by the copyright holder.
Contributor(s):
Portions Copyrighted 2011 Gephi Consortium.
*/
package org.gephi.desktop.importer;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.List;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JRootPane;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import org.gephi.io.importer.api.Container;
import org.gephi.io.importer.api.ContainerUnloader;
import org.gephi.io.importer.api.EdgeDirectionDefault;
import org.gephi.io.importer.api.EdgeWeightMergeStrategy;
import org.gephi.io.importer.api.Issue;
import org.gephi.io.importer.api.Report;
import org.gephi.io.processor.spi.Processor;
import org.gephi.io.processor.spi.ProcessorUI;
import org.gephi.ui.components.BusyUtils;
import org.netbeans.swing.outline.DefaultOutlineModel;
import org.netbeans.swing.outline.OutlineModel;
import org.netbeans.swing.outline.RenderDataProvider;
import org.netbeans.swing.outline.RowModel;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
import org.openide.util.NbPreferences;
/**
*
* @author Mathieu Bastian
*/
public class ReportPanel extends javax.swing.JPanel {
//Preferences
private final static String SHOW_ISSUES = "ReportPanel_Show_Issues";
private final static String SHOW_REPORT = "ReportPanel_Show_Report";
private final static int ISSUES_LIMIT = 5000;
private ThreadGroup fillingThreads;
//Icons
private ImageIcon infoIcon;
private ImageIcon warningIcon;
private ImageIcon severeIcon;
private ImageIcon criticalIcon;
//Container
private Container container;
//UI
private ButtonGroup processorGroup = new ButtonGroup();
public ReportPanel() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
initComponents();
initIcons();
initProcessors();
initProcessorsUI();
initMoreOptionsPanel();
initMergeStrategyCombo();
}
});
} catch (InterruptedException ex) {
Exceptions.printStackTrace(ex);
} catch (InvocationTargetException ex) {
Exceptions.printStackTrace(ex);
}
fillingThreads = new ThreadGroup("Report Panel Issues");
autoscaleCheckbox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (autoscaleCheckbox.isSelected() != container.getUnloader().isAutoScale()) {
container.getLoader().setAutoScale(autoscaleCheckbox.isSelected());
}
}
});
createMissingNodesCheckbox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (createMissingNodesCheckbox.isSelected() != container.getUnloader().allowAutoNode()) {
container.getLoader().setAllowAutoNode(createMissingNodesCheckbox.isSelected());
}
}
});
moreOptionsLink.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
moreOptionsPanel.setVisible(!moreOptionsPanel.isVisible());
JRootPane rootPane = SwingUtilities.getRootPane(ReportPanel.this);
((JDialog) rootPane.getParent()).pack();
}
});
edgesMergeStrategyCombo.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
int g = edgesMergeStrategyCombo.getSelectedIndex();
switch (g) {
case 0:
container.getLoader().setEdgesMergeStrategy(EdgeWeightMergeStrategy.SUM);
break;
case 1:
container.getLoader().setEdgesMergeStrategy(EdgeWeightMergeStrategy.AVG);
break;
case 2:
container.getLoader().setEdgesMergeStrategy(EdgeWeightMergeStrategy.MIN);
break;
case 3:
container.getLoader().setEdgesMergeStrategy(EdgeWeightMergeStrategy.MAX);
break;
}
}
});
selfLoopCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (selfLoopCheckBox.isSelected() != container.getUnloader().allowSelfLoop()) {
container.getLoader().setAllowSelfLoop(selfLoopCheckBox.isSelected());
}
}
});
}
public void initIcons() {
infoIcon = new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/importer/resources/info.png"));
warningIcon = new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/importer/resources/warning.gif"));
severeIcon = new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/importer/resources/severe.png"));
criticalIcon = new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/importer/resources/critical.png"));
}
public void setData(Report report, Container container) {
this.container = container;
initGraphTypeCombo(container);
report.pruneReport(ISSUES_LIMIT);
fillIssues(report);
fillReport(report);
fillStats(container);
fillParameters(container);
}
private void removeTabbedPane() {
tabbedPane.setVisible(false);
}
private void initMergeStrategyCombo() {
DefaultComboBoxModel mergeStrategryModel = new DefaultComboBoxModel(new String[]{
NbBundle.getMessage(ReportPanel.class, "ReportPanel.mergeStrategy.sum"),
NbBundle.getMessage(ReportPanel.class, "ReportPanel.mergeStrategy.avg"),
NbBundle.getMessage(ReportPanel.class, "ReportPanel.mergeStrategy.min"),
NbBundle.getMessage(ReportPanel.class, "ReportPanel.mergeStrategy.max")});
edgesMergeStrategyCombo.setModel(mergeStrategryModel);
}
private void initMoreOptionsPanel() {
moreOptionsPanel.setVisible(false);
}
private void initGraphTypeCombo(final Container container) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
String directedStr = NbBundle.getMessage(ReportPanel.class, "ReportPanel.graphType.directed");
String undirectedStr = NbBundle.getMessage(ReportPanel.class, "ReportPanel.graphType.undirected");
String mixedStr = NbBundle.getMessage(ReportPanel.class, "ReportPanel.graphType.mixed");
DefaultComboBoxModel comboModel = new DefaultComboBoxModel();
EdgeDirectionDefault dir = container.getUnloader().getEdgeDefault();
switch (dir) {
case DIRECTED:
comboModel.addElement(directedStr);
comboModel.addElement(undirectedStr);
comboModel.addElement(mixedStr);
break;
case UNDIRECTED:
comboModel.addElement(undirectedStr);
comboModel.addElement(mixedStr);
break;
case MIXED:
comboModel.addElement(directedStr);
comboModel.addElement(undirectedStr);
comboModel.addElement(mixedStr);
break;
}
graphTypeCombo.setModel(comboModel);
}
});
graphTypeCombo.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
int g = graphTypeCombo.getSelectedIndex();
EdgeDirectionDefault dir = container.getUnloader().getEdgeDefault();
if (dir.equals(EdgeDirectionDefault.UNDIRECTED)) {
switch (g) {
case 0:
container.getLoader().setEdgeDefault(EdgeDirectionDefault.UNDIRECTED);
break;
case 1:
container.getLoader().setEdgeDefault(EdgeDirectionDefault.MIXED);
break;
}
} else {
switch (g) {
case 0:
container.getLoader().setEdgeDefault(EdgeDirectionDefault.DIRECTED);
break;
case 1:
container.getLoader().setEdgeDefault(EdgeDirectionDefault.UNDIRECTED);
break;
case 2:
container.getLoader().setEdgeDefault(EdgeDirectionDefault.MIXED);
break;
}
}
}
});
}
private void fillIssues(Report report) {
final List<Issue> issues = report.getIssues();
if (issues.isEmpty()) {
JLabel label = new JLabel(NbBundle.getMessage(getClass(), "ReportPanel.noIssues"));
label.setHorizontalAlignment(SwingConstants.CENTER);
tab1ScrollPane.setViewportView(label);
} else {
//Busy label
final BusyUtils.BusyLabel busyLabel = BusyUtils.createCenteredBusyLabel(tab1ScrollPane, "Retrieving issues...", issuesOutline);
//Thread
Thread thread = new Thread(fillingThreads, new Runnable() {
@Override
public void run() {
busyLabel.setBusy(true);
final TreeModel treeMdl = new IssueTreeModel(issues);
final OutlineModel mdl = DefaultOutlineModel.createOutlineModel(treeMdl, new IssueRowModel(), true);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
issuesOutline.setRootVisible(false);
issuesOutline.setRenderDataProvider(new IssueRenderer());
issuesOutline.setModel(mdl);
busyLabel.setBusy(false);
}
});
}
}, "Report Panel Issues Outline");
if (NbPreferences.forModule(ReportPanel.class).getBoolean(SHOW_ISSUES, true)) {
thread.start();
}
}
}
private void fillReport(final Report report) {
Thread thread = new Thread(fillingThreads, new Runnable() {
@Override
public void run() {
final String str = report.getText();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
reportEditor.setText(str);
}
});
}
}, "Report Panel Issues Report");
if (NbPreferences.forModule(ReportPanel.class).getBoolean(SHOW_REPORT, true)) {
thread.start();
}
}
private void fillParameters(final Container container) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
//Autoscale
autoscaleCheckbox.setSelected(container.getUnloader().isAutoScale());
selfLoopCheckBox.setSelected(container.getUnloader().allowSelfLoop());
createMissingNodesCheckbox.setSelected(container.getUnloader().allowAutoNode());
switch (container.getUnloader().getEdgeDefault()) {
case DIRECTED:
graphTypeCombo.setSelectedIndex(0);
break;
case UNDIRECTED:
graphTypeCombo.setSelectedIndex(1);
break;
case MIXED:
graphTypeCombo.setSelectedIndex(2);
break;
}
switch (container.getUnloader().getEdgesMergeStrategy()) {
case SUM:
edgesMergeStrategyCombo.setSelectedIndex(0);
break;
case AVG:
edgesMergeStrategyCombo.setSelectedIndex(1);
break;
case MIN:
edgesMergeStrategyCombo.setSelectedIndex(2);
break;
case MAX:
edgesMergeStrategyCombo.setSelectedIndex(3);
break;
}
}
});
}
private void fillStats(final Container container) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
//Source
String source = container.getSource();
String[] label = source.split("\\.");
if (label.length > 2 && label[label.length - 2].matches("\\d+")) { //case of temp file
source = source.replaceFirst("." + label[label.length - 2], "");
}
sourceLabel.setText(source);
ContainerUnloader unloader = container.getUnloader();
//Node & Edge count
int nodeCount = unloader.getNodeCount();
int edgeCount = unloader.getEdgeCount();
nodeCountLabel.setText("" + nodeCount);
edgeCountLabel.setText("" + edgeCount);
//Dynamic & Hierarchical graph
String yes = NbBundle.getMessage(getClass(), "ReportPanel.yes");
String no = NbBundle.getMessage(getClass(), "ReportPanel.no");
dynamicLabel.setText(container.isDynamicGraph() ? yes : no);
dynamicAttsLabel.setText(container.hasDynamicAttributes() ? yes : no);
multigraphLabel.setText(container.isMultiGraph() ? yes : no);
}
});
}
private static final Object PROCESSOR_KEY = new Object();
private void initProcessors() {
int i = 0;
for (Processor processor : Lookup.getDefault().lookupAll(Processor.class)) {
JRadioButton radio = new JRadioButton(processor.getDisplayName());
radio.setSelected(i == 0);
radio.putClientProperty(PROCESSOR_KEY, processor);
processorGroup.add(radio);
GridBagConstraints constraints = new GridBagConstraints(0, i++, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0);
processorPanel.add(radio, constraints);
}
}
private void initProcessorsUI() {
for (Enumeration<AbstractButton> enumeration = processorGroup.getElements(); enumeration.hasMoreElements();) {
AbstractButton radioButton = enumeration.nextElement();
Processor p = (Processor) radioButton.getClientProperty(PROCESSOR_KEY);
//Enabled
ProcessorUI pui = getProcessorUI(p);
if (pui != null) {
radioButton.setEnabled(pui.isValid(container));
}
}
}
public void destroy() {
fillingThreads.interrupt();
}
public Processor getProcessor() {
for (Enumeration<AbstractButton> enumeration = processorGroup.getElements(); enumeration.hasMoreElements();) {
AbstractButton radioButton = enumeration.nextElement();
if (radioButton.isSelected()) {
return (Processor) radioButton.getClientProperty(PROCESSOR_KEY);
}
}
return null;
}
private ProcessorUI getProcessorUI(Processor processor) {
for (ProcessorUI pui : Lookup.getDefault().lookupAll(ProcessorUI.class)) {
if (pui.isUIFoProcessor(processor)) {
return pui;
}
}
return null;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
processorStrategyRadio = new javax.swing.ButtonGroup();
labelSrc = new javax.swing.JLabel();
sourceLabel = new javax.swing.JLabel();
tabbedPane = new javax.swing.JTabbedPane();
tab1ScrollPane = new javax.swing.JScrollPane();
issuesOutline = new org.netbeans.swing.outline.Outline();
tab2ScrollPane = new javax.swing.JScrollPane();
reportEditor = new javax.swing.JEditorPane();
labelGraphType = new javax.swing.JLabel();
graphTypeCombo = new javax.swing.JComboBox();
processorPanel = new javax.swing.JPanel();
statsPanel = new javax.swing.JPanel();
labelNodeCount = new javax.swing.JLabel();
labelEdgeCount = new javax.swing.JLabel();
nodeCountLabel = new javax.swing.JLabel();
edgeCountLabel = new javax.swing.JLabel();
dynamicLabel = new javax.swing.JLabel();
labelDynamic = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
labelMultiGraph = new javax.swing.JLabel();
multigraphLabel = new javax.swing.JLabel();
labelDynamicAtts = new javax.swing.JLabel();
dynamicAttsLabel = new javax.swing.JLabel();
moreOptionsLink = new org.jdesktop.swingx.JXHyperlink();
moreOptionsPanel = new javax.swing.JPanel();
autoscaleCheckbox = new javax.swing.JCheckBox();
createMissingNodesCheckbox = new javax.swing.JCheckBox();
selfLoopCheckBox = new javax.swing.JCheckBox();
labelParallelEdgesMergeStrategy = new javax.swing.JLabel();
edgesMergeStrategyCombo = new javax.swing.JComboBox();
labelSrc.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelSrc.text")); // NOI18N
sourceLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.sourceLabel.text")); // NOI18N
- issuesOutline.setPreferredSize(new java.awt.Dimension(650, 0));
tab1ScrollPane.setViewportView(issuesOutline);
tabbedPane.addTab(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.tab1ScrollPane.TabConstraints.tabTitle"), tab1ScrollPane); // NOI18N
tab2ScrollPane.setViewportView(reportEditor);
tabbedPane.addTab(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.tab2ScrollPane.TabConstraints.tabTitle"), tab2ScrollPane); // NOI18N
labelGraphType.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelGraphType.text")); // NOI18N
processorPanel.setLayout(new java.awt.GridBagLayout());
statsPanel.setLayout(new java.awt.GridBagLayout());
labelNodeCount.setFont(labelNodeCount.getFont().deriveFont(labelNodeCount.getFont().getStyle() | java.awt.Font.BOLD));
labelNodeCount.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelNodeCount.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 6, 0);
statsPanel.add(labelNodeCount, gridBagConstraints);
labelEdgeCount.setFont(labelEdgeCount.getFont().deriveFont(labelEdgeCount.getFont().getStyle() | java.awt.Font.BOLD));
labelEdgeCount.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelEdgeCount.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
statsPanel.add(labelEdgeCount, gridBagConstraints);
nodeCountLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
nodeCountLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.nodeCountLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 6, 0);
statsPanel.add(nodeCountLabel, gridBagConstraints);
edgeCountLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
edgeCountLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.edgeCountLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 0);
statsPanel.add(edgeCountLabel, gridBagConstraints);
dynamicLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.dynamicLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 6, 0);
statsPanel.add(dynamicLabel, gridBagConstraints);
labelDynamic.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelDynamic.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 6, 0);
statsPanel.add(labelDynamic, gridBagConstraints);
jLabel1.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.jLabel1.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
statsPanel.add(jLabel1, gridBagConstraints);
labelMultiGraph.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelMultiGraph.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 6, 0);
statsPanel.add(labelMultiGraph, gridBagConstraints);
multigraphLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.multigraphLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 6, 0);
statsPanel.add(multigraphLabel, gridBagConstraints);
labelDynamicAtts.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelDynamicAtts.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 6, 0);
statsPanel.add(labelDynamicAtts, gridBagConstraints);
dynamicAttsLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.dynamicAttsLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 6, 0);
statsPanel.add(dynamicAttsLabel, gridBagConstraints);
moreOptionsLink.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.moreOptionsLink.text")); // NOI18N
moreOptionsLink.setClickedColor(new java.awt.Color(0, 51, 255));
moreOptionsPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
autoscaleCheckbox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.autoscaleCheckbox.text")); // NOI18N
autoscaleCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.autoscaleCheckbox.toolTipText")); // NOI18N
createMissingNodesCheckbox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.createMissingNodesCheckbox.text")); // NOI18N
createMissingNodesCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.createMissingNodesCheckbox.toolTipText")); // NOI18N
selfLoopCheckBox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.selfLoopCheckBox.text")); // NOI18N
selfLoopCheckBox.setToolTipText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.selfLoopCheckBox.toolTipText")); // NOI18N
selfLoopCheckBox.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
labelParallelEdgesMergeStrategy.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelParallelEdgesMergeStrategy.text")); // NOI18N
javax.swing.GroupLayout moreOptionsPanelLayout = new javax.swing.GroupLayout(moreOptionsPanel);
moreOptionsPanel.setLayout(moreOptionsPanelLayout);
moreOptionsPanelLayout.setHorizontalGroup(
moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addComponent(autoscaleCheckbox, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(labelParallelEdgesMergeStrategy)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(edgesMergeStrategyCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addGroup(moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(createMissingNodesCheckbox)
.addComponent(selfLoopCheckBox))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
moreOptionsPanelLayout.setVerticalGroup(
moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelParallelEdgesMergeStrategy)
.addComponent(edgesMergeStrategyCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(autoscaleCheckbox))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(createMissingNodesCheckbox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(selfLoopCheckBox)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addComponent(tabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
+ .addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(labelSrc)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sourceLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(labelGraphType)
.addGap(18, 18, 18)
.addComponent(graphTypeCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(statsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addComponent(processorPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
+ .addGroup(layout.createSequentialGroup()
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(moreOptionsLink, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addGap(8, 8, 8))))
+ .addGap(8, 8, 8))
+ .addGroup(layout.createSequentialGroup()
+ .addGap(18, 18, 18)
+ .addComponent(processorPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(moreOptionsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelSrc)
.addComponent(sourceLabel))
.addGap(18, 18, 18)
.addComponent(tabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelGraphType)
.addComponent(graphTypeCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(moreOptionsLink, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(moreOptionsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
- .addComponent(statsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addComponent(processorPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE))
- .addGap(22, 22, 22))
+ .addComponent(statsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 122, Short.MAX_VALUE)
+ .addComponent(processorPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JCheckBox autoscaleCheckbox;
private javax.swing.JCheckBox createMissingNodesCheckbox;
private javax.swing.JLabel dynamicAttsLabel;
private javax.swing.JLabel dynamicLabel;
private javax.swing.JLabel edgeCountLabel;
private javax.swing.JComboBox edgesMergeStrategyCombo;
private javax.swing.JComboBox graphTypeCombo;
private org.netbeans.swing.outline.Outline issuesOutline;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel labelDynamic;
private javax.swing.JLabel labelDynamicAtts;
private javax.swing.JLabel labelEdgeCount;
private javax.swing.JLabel labelGraphType;
private javax.swing.JLabel labelMultiGraph;
private javax.swing.JLabel labelNodeCount;
private javax.swing.JLabel labelParallelEdgesMergeStrategy;
private javax.swing.JLabel labelSrc;
private org.jdesktop.swingx.JXHyperlink moreOptionsLink;
private javax.swing.JPanel moreOptionsPanel;
private javax.swing.JLabel multigraphLabel;
private javax.swing.JLabel nodeCountLabel;
private javax.swing.JPanel processorPanel;
private javax.swing.ButtonGroup processorStrategyRadio;
private javax.swing.JEditorPane reportEditor;
private javax.swing.JCheckBox selfLoopCheckBox;
private javax.swing.JLabel sourceLabel;
private javax.swing.JPanel statsPanel;
private javax.swing.JScrollPane tab1ScrollPane;
private javax.swing.JScrollPane tab2ScrollPane;
private javax.swing.JTabbedPane tabbedPane;
// End of variables declaration//GEN-END:variables
private class IssueTreeModel implements TreeModel {
private List<Issue> issues;
public IssueTreeModel(List<Issue> issues) {
this.issues = issues;
}
@Override
public Object getRoot() {
return "root";
}
@Override
public Object getChild(Object parent, int index) {
return issues.get(index);
}
@Override
public int getChildCount(Object parent) {
return issues.size();
}
@Override
public boolean isLeaf(Object node) {
if (node instanceof Issue) {
return true;
}
return false;
}
@Override
public void valueForPathChanged(TreePath path, Object newValue) {
}
@Override
public int getIndexOfChild(Object parent, Object child) {
return issues.indexOf(child);
}
@Override
public void addTreeModelListener(TreeModelListener l) {
}
@Override
public void removeTreeModelListener(TreeModelListener l) {
}
}
private class IssueRowModel implements RowModel {
@Override
public int getColumnCount() {
return 1;
}
@Override
public Object getValueFor(Object node, int column) {
if (node instanceof Issue) {
Issue issue = (Issue) node;
return issue.getLevel().toString();
}
return "";
}
@Override
public Class getColumnClass(int column) {
return String.class;
}
@Override
public boolean isCellEditable(Object node, int column) {
return false;
}
@Override
public void setValueFor(Object node, int column, Object value) {
}
@Override
public String getColumnName(int column) {
return NbBundle.getMessage(ReportPanel.class, "ReportPanel.issueTable.issues");
}
}
private class IssueRenderer implements RenderDataProvider {
@Override
public String getDisplayName(Object o) {
Issue issue = (Issue) o;
return issue.getMessage();
}
@Override
public boolean isHtmlDisplayName(Object o) {
return false;
}
@Override
public Color getBackground(Object o) {
return null;
}
@Override
public Color getForeground(Object o) {
return null;
}
@Override
public String getTooltipText(Object o) {
return "";
}
@Override
public Icon getIcon(Object o) {
Issue issue = (Issue) o;
switch (issue.getLevel()) {
case INFO:
return infoIcon;
case WARNING:
return warningIcon;
case SEVERE:
return severeIcon;
case CRITICAL:
return criticalIcon;
}
return null;
}
}
}
| false | true | private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
processorStrategyRadio = new javax.swing.ButtonGroup();
labelSrc = new javax.swing.JLabel();
sourceLabel = new javax.swing.JLabel();
tabbedPane = new javax.swing.JTabbedPane();
tab1ScrollPane = new javax.swing.JScrollPane();
issuesOutline = new org.netbeans.swing.outline.Outline();
tab2ScrollPane = new javax.swing.JScrollPane();
reportEditor = new javax.swing.JEditorPane();
labelGraphType = new javax.swing.JLabel();
graphTypeCombo = new javax.swing.JComboBox();
processorPanel = new javax.swing.JPanel();
statsPanel = new javax.swing.JPanel();
labelNodeCount = new javax.swing.JLabel();
labelEdgeCount = new javax.swing.JLabel();
nodeCountLabel = new javax.swing.JLabel();
edgeCountLabel = new javax.swing.JLabel();
dynamicLabel = new javax.swing.JLabel();
labelDynamic = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
labelMultiGraph = new javax.swing.JLabel();
multigraphLabel = new javax.swing.JLabel();
labelDynamicAtts = new javax.swing.JLabel();
dynamicAttsLabel = new javax.swing.JLabel();
moreOptionsLink = new org.jdesktop.swingx.JXHyperlink();
moreOptionsPanel = new javax.swing.JPanel();
autoscaleCheckbox = new javax.swing.JCheckBox();
createMissingNodesCheckbox = new javax.swing.JCheckBox();
selfLoopCheckBox = new javax.swing.JCheckBox();
labelParallelEdgesMergeStrategy = new javax.swing.JLabel();
edgesMergeStrategyCombo = new javax.swing.JComboBox();
labelSrc.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelSrc.text")); // NOI18N
sourceLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.sourceLabel.text")); // NOI18N
issuesOutline.setPreferredSize(new java.awt.Dimension(650, 0));
tab1ScrollPane.setViewportView(issuesOutline);
tabbedPane.addTab(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.tab1ScrollPane.TabConstraints.tabTitle"), tab1ScrollPane); // NOI18N
tab2ScrollPane.setViewportView(reportEditor);
tabbedPane.addTab(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.tab2ScrollPane.TabConstraints.tabTitle"), tab2ScrollPane); // NOI18N
labelGraphType.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelGraphType.text")); // NOI18N
processorPanel.setLayout(new java.awt.GridBagLayout());
statsPanel.setLayout(new java.awt.GridBagLayout());
labelNodeCount.setFont(labelNodeCount.getFont().deriveFont(labelNodeCount.getFont().getStyle() | java.awt.Font.BOLD));
labelNodeCount.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelNodeCount.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 6, 0);
statsPanel.add(labelNodeCount, gridBagConstraints);
labelEdgeCount.setFont(labelEdgeCount.getFont().deriveFont(labelEdgeCount.getFont().getStyle() | java.awt.Font.BOLD));
labelEdgeCount.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelEdgeCount.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
statsPanel.add(labelEdgeCount, gridBagConstraints);
nodeCountLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
nodeCountLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.nodeCountLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 6, 0);
statsPanel.add(nodeCountLabel, gridBagConstraints);
edgeCountLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
edgeCountLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.edgeCountLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 0);
statsPanel.add(edgeCountLabel, gridBagConstraints);
dynamicLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.dynamicLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 6, 0);
statsPanel.add(dynamicLabel, gridBagConstraints);
labelDynamic.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelDynamic.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 6, 0);
statsPanel.add(labelDynamic, gridBagConstraints);
jLabel1.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.jLabel1.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
statsPanel.add(jLabel1, gridBagConstraints);
labelMultiGraph.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelMultiGraph.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 6, 0);
statsPanel.add(labelMultiGraph, gridBagConstraints);
multigraphLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.multigraphLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 6, 0);
statsPanel.add(multigraphLabel, gridBagConstraints);
labelDynamicAtts.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelDynamicAtts.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 6, 0);
statsPanel.add(labelDynamicAtts, gridBagConstraints);
dynamicAttsLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.dynamicAttsLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 6, 0);
statsPanel.add(dynamicAttsLabel, gridBagConstraints);
moreOptionsLink.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.moreOptionsLink.text")); // NOI18N
moreOptionsLink.setClickedColor(new java.awt.Color(0, 51, 255));
moreOptionsPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
autoscaleCheckbox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.autoscaleCheckbox.text")); // NOI18N
autoscaleCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.autoscaleCheckbox.toolTipText")); // NOI18N
createMissingNodesCheckbox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.createMissingNodesCheckbox.text")); // NOI18N
createMissingNodesCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.createMissingNodesCheckbox.toolTipText")); // NOI18N
selfLoopCheckBox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.selfLoopCheckBox.text")); // NOI18N
selfLoopCheckBox.setToolTipText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.selfLoopCheckBox.toolTipText")); // NOI18N
selfLoopCheckBox.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
labelParallelEdgesMergeStrategy.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelParallelEdgesMergeStrategy.text")); // NOI18N
javax.swing.GroupLayout moreOptionsPanelLayout = new javax.swing.GroupLayout(moreOptionsPanel);
moreOptionsPanel.setLayout(moreOptionsPanelLayout);
moreOptionsPanelLayout.setHorizontalGroup(
moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addComponent(autoscaleCheckbox, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(labelParallelEdgesMergeStrategy)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(edgesMergeStrategyCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addGroup(moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(createMissingNodesCheckbox)
.addComponent(selfLoopCheckBox))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
moreOptionsPanelLayout.setVerticalGroup(
moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelParallelEdgesMergeStrategy)
.addComponent(edgesMergeStrategyCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(autoscaleCheckbox))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(createMissingNodesCheckbox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(selfLoopCheckBox)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(labelSrc)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sourceLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(labelGraphType)
.addGap(18, 18, 18)
.addComponent(graphTypeCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(statsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(processorPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(moreOptionsLink, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(8, 8, 8))))
.addComponent(moreOptionsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelSrc)
.addComponent(sourceLabel))
.addGap(18, 18, 18)
.addComponent(tabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelGraphType)
.addComponent(graphTypeCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(moreOptionsLink, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(moreOptionsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(statsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(processorPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(22, 22, 22))
);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
processorStrategyRadio = new javax.swing.ButtonGroup();
labelSrc = new javax.swing.JLabel();
sourceLabel = new javax.swing.JLabel();
tabbedPane = new javax.swing.JTabbedPane();
tab1ScrollPane = new javax.swing.JScrollPane();
issuesOutline = new org.netbeans.swing.outline.Outline();
tab2ScrollPane = new javax.swing.JScrollPane();
reportEditor = new javax.swing.JEditorPane();
labelGraphType = new javax.swing.JLabel();
graphTypeCombo = new javax.swing.JComboBox();
processorPanel = new javax.swing.JPanel();
statsPanel = new javax.swing.JPanel();
labelNodeCount = new javax.swing.JLabel();
labelEdgeCount = new javax.swing.JLabel();
nodeCountLabel = new javax.swing.JLabel();
edgeCountLabel = new javax.swing.JLabel();
dynamicLabel = new javax.swing.JLabel();
labelDynamic = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
labelMultiGraph = new javax.swing.JLabel();
multigraphLabel = new javax.swing.JLabel();
labelDynamicAtts = new javax.swing.JLabel();
dynamicAttsLabel = new javax.swing.JLabel();
moreOptionsLink = new org.jdesktop.swingx.JXHyperlink();
moreOptionsPanel = new javax.swing.JPanel();
autoscaleCheckbox = new javax.swing.JCheckBox();
createMissingNodesCheckbox = new javax.swing.JCheckBox();
selfLoopCheckBox = new javax.swing.JCheckBox();
labelParallelEdgesMergeStrategy = new javax.swing.JLabel();
edgesMergeStrategyCombo = new javax.swing.JComboBox();
labelSrc.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelSrc.text")); // NOI18N
sourceLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.sourceLabel.text")); // NOI18N
tab1ScrollPane.setViewportView(issuesOutline);
tabbedPane.addTab(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.tab1ScrollPane.TabConstraints.tabTitle"), tab1ScrollPane); // NOI18N
tab2ScrollPane.setViewportView(reportEditor);
tabbedPane.addTab(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.tab2ScrollPane.TabConstraints.tabTitle"), tab2ScrollPane); // NOI18N
labelGraphType.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelGraphType.text")); // NOI18N
processorPanel.setLayout(new java.awt.GridBagLayout());
statsPanel.setLayout(new java.awt.GridBagLayout());
labelNodeCount.setFont(labelNodeCount.getFont().deriveFont(labelNodeCount.getFont().getStyle() | java.awt.Font.BOLD));
labelNodeCount.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelNodeCount.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 6, 0);
statsPanel.add(labelNodeCount, gridBagConstraints);
labelEdgeCount.setFont(labelEdgeCount.getFont().deriveFont(labelEdgeCount.getFont().getStyle() | java.awt.Font.BOLD));
labelEdgeCount.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelEdgeCount.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
statsPanel.add(labelEdgeCount, gridBagConstraints);
nodeCountLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
nodeCountLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.nodeCountLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 6, 0);
statsPanel.add(nodeCountLabel, gridBagConstraints);
edgeCountLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
edgeCountLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.edgeCountLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 0);
statsPanel.add(edgeCountLabel, gridBagConstraints);
dynamicLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.dynamicLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 6, 0);
statsPanel.add(dynamicLabel, gridBagConstraints);
labelDynamic.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelDynamic.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 6, 0);
statsPanel.add(labelDynamic, gridBagConstraints);
jLabel1.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.jLabel1.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
statsPanel.add(jLabel1, gridBagConstraints);
labelMultiGraph.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelMultiGraph.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 6, 0);
statsPanel.add(labelMultiGraph, gridBagConstraints);
multigraphLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.multigraphLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 6, 0);
statsPanel.add(multigraphLabel, gridBagConstraints);
labelDynamicAtts.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelDynamicAtts.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 6, 0);
statsPanel.add(labelDynamicAtts, gridBagConstraints);
dynamicAttsLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.dynamicAttsLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 6, 0);
statsPanel.add(dynamicAttsLabel, gridBagConstraints);
moreOptionsLink.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.moreOptionsLink.text")); // NOI18N
moreOptionsLink.setClickedColor(new java.awt.Color(0, 51, 255));
moreOptionsPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
autoscaleCheckbox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.autoscaleCheckbox.text")); // NOI18N
autoscaleCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.autoscaleCheckbox.toolTipText")); // NOI18N
createMissingNodesCheckbox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.createMissingNodesCheckbox.text")); // NOI18N
createMissingNodesCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.createMissingNodesCheckbox.toolTipText")); // NOI18N
selfLoopCheckBox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.selfLoopCheckBox.text")); // NOI18N
selfLoopCheckBox.setToolTipText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.selfLoopCheckBox.toolTipText")); // NOI18N
selfLoopCheckBox.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
labelParallelEdgesMergeStrategy.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelParallelEdgesMergeStrategy.text")); // NOI18N
javax.swing.GroupLayout moreOptionsPanelLayout = new javax.swing.GroupLayout(moreOptionsPanel);
moreOptionsPanel.setLayout(moreOptionsPanelLayout);
moreOptionsPanelLayout.setHorizontalGroup(
moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addComponent(autoscaleCheckbox, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(labelParallelEdgesMergeStrategy)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(edgesMergeStrategyCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addGroup(moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(createMissingNodesCheckbox)
.addComponent(selfLoopCheckBox))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
moreOptionsPanelLayout.setVerticalGroup(
moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelParallelEdgesMergeStrategy)
.addComponent(edgesMergeStrategyCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(autoscaleCheckbox))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(createMissingNodesCheckbox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(selfLoopCheckBox)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(labelSrc)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sourceLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(labelGraphType)
.addGap(18, 18, 18)
.addComponent(graphTypeCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(statsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(moreOptionsLink, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(8, 8, 8))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(processorPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(moreOptionsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelSrc)
.addComponent(sourceLabel))
.addGap(18, 18, 18)
.addComponent(tabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelGraphType)
.addComponent(graphTypeCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(moreOptionsLink, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(moreOptionsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(statsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 122, Short.MAX_VALUE)
.addComponent(processorPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/DownloadTask.java b/src/DownloadTask.java
index a7cdd94..d23c1c5 100644
--- a/src/DownloadTask.java
+++ b/src/DownloadTask.java
@@ -1,162 +1,162 @@
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class DownloadTask {
private int threadNumber = 5; //default thread number
private ExecutorService pool; //We use thread pool
private String path = ""; //the resource url
private static File file; // Point to the storage file
private Lock poolLock = new ReentrantLock();
private Condition allDone = poolLock.newCondition();
private int doneNumber = 0;
private LinkedList<File> files;
public int getThreadNumber() {
return threadNumber;
}
public String getPath() {
return path;
}
public static File getFile() {
return file;
}
public DownloadTask(String path, String filename) {
this.path = path;
file = new File(filename);
this.pool = Executors.newFixedThreadPool(this.threadNumber);
}
public DownloadTask(String path, String filename, int threadNumber) {
this.path = path;
file = new File(filename);
this.threadNumber = threadNumber;
this.pool = Executors.newFixedThreadPool(this.threadNumber);
}
public boolean download() {
URL url = null;
try {
url = new URL(path);
} catch (MalformedURLException e2) {
e2.printStackTrace();
}
URLConnection openConnection = null;
int totalLength = 0;
int partLength = 0;
try {
openConnection = url.openConnection();
openConnection.connect();
totalLength = openConnection.getContentLength();
partLength = totalLength / threadNumber;
} catch (IOException e) {
e.printStackTrace();
return false;
}
for (int i = 0; i < threadNumber; i++) {
final int seq = i;
final int finalPartLength = partLength;
final File logfile = new File(file.getName() +"_log");
if (i < threadNumber - 1) {
pool.execute(new Runnable() {
@Override
public void run() {
download(path, finalPartLength * seq, finalPartLength
- * (seq + 1) - 1, logfile, i);
+ * (seq + 1) - 1, logfile, seq);
}
});
} else {
final int finalTotalLength = totalLength;
pool.execute(new Runnable() {
@Override
public void run() {
download(path, finalPartLength * seq,
- finalTotalLength - 1, logfile, i);
+ finalTotalLength - 1, logfile, seq);
}
});
}
}
poolLock.lock();
try {
while (doneNumber < threadNumber) {
try {
allDone.await();
pool.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
poolLock.unlock();
}
return true;
}
private void download(String path, int start, int end, File logfile, int seq) {
URL url = null;
try {
url = new URL(path);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
HttpURLConnection openConnection = null;
InputStream bs = null;
RandomAccessFile fs = null;
byte[] buf = new byte[8096];
int size = 0;
long count = DownloadHelper.readOffset(seq);
try {
openConnection = (HttpURLConnection) url.openConnection();
openConnection.setRequestProperty("RANGE", "bytes=" + start + "-"
+ end);
openConnection.connect();
bs = openConnection.getInputStream();
fs = new RandomAccessFile(file, "rw");
int off = start;
RandomAccessFile fos = new RandomAccessFile(logfile, "rw");
while ((size = bs.read(buf)) != -1) {
fs.seek(off);
fs.write(buf, 0, size);
count += size;
DownloadHelper.writeOffSet(seq, count);
off += size;
}
poolLock.lock();
try {
doneNumber++;
allDone.signalAll();
} finally {
poolLock.unlock();
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bs.close();
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| false | true | public boolean download() {
URL url = null;
try {
url = new URL(path);
} catch (MalformedURLException e2) {
e2.printStackTrace();
}
URLConnection openConnection = null;
int totalLength = 0;
int partLength = 0;
try {
openConnection = url.openConnection();
openConnection.connect();
totalLength = openConnection.getContentLength();
partLength = totalLength / threadNumber;
} catch (IOException e) {
e.printStackTrace();
return false;
}
for (int i = 0; i < threadNumber; i++) {
final int seq = i;
final int finalPartLength = partLength;
final File logfile = new File(file.getName() +"_log");
if (i < threadNumber - 1) {
pool.execute(new Runnable() {
@Override
public void run() {
download(path, finalPartLength * seq, finalPartLength
* (seq + 1) - 1, logfile, i);
}
});
} else {
final int finalTotalLength = totalLength;
pool.execute(new Runnable() {
@Override
public void run() {
download(path, finalPartLength * seq,
finalTotalLength - 1, logfile, i);
}
});
}
}
poolLock.lock();
try {
while (doneNumber < threadNumber) {
try {
allDone.await();
pool.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
poolLock.unlock();
}
return true;
}
| public boolean download() {
URL url = null;
try {
url = new URL(path);
} catch (MalformedURLException e2) {
e2.printStackTrace();
}
URLConnection openConnection = null;
int totalLength = 0;
int partLength = 0;
try {
openConnection = url.openConnection();
openConnection.connect();
totalLength = openConnection.getContentLength();
partLength = totalLength / threadNumber;
} catch (IOException e) {
e.printStackTrace();
return false;
}
for (int i = 0; i < threadNumber; i++) {
final int seq = i;
final int finalPartLength = partLength;
final File logfile = new File(file.getName() +"_log");
if (i < threadNumber - 1) {
pool.execute(new Runnable() {
@Override
public void run() {
download(path, finalPartLength * seq, finalPartLength
* (seq + 1) - 1, logfile, seq);
}
});
} else {
final int finalTotalLength = totalLength;
pool.execute(new Runnable() {
@Override
public void run() {
download(path, finalPartLength * seq,
finalTotalLength - 1, logfile, seq);
}
});
}
}
poolLock.lock();
try {
while (doneNumber < threadNumber) {
try {
allDone.await();
pool.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
poolLock.unlock();
}
return true;
}
|
diff --git a/src/tests/org/xins/tests/server/IPFilterTests.java b/src/tests/org/xins/tests/server/IPFilterTests.java
index b69547bda..fb2b78d24 100644
--- a/src/tests/org/xins/tests/server/IPFilterTests.java
+++ b/src/tests/org/xins/tests/server/IPFilterTests.java
@@ -1,189 +1,188 @@
/*
* $Id$
*/
package org.xins.tests.server;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.xins.server.IPFilter;
import org.xins.util.text.ParseException;
/**
* Tests for class <code>IPFilter</code>.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*/
public class IPFilterTests extends TestCase {
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
/**
* Returns a test suite with all test cases defined by this class.
*
* @return
* the test suite, never <code>null</code>.
*/
public static Test suite() {
return new TestSuite(IPFilterTests.class);
}
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Constructor
//-------------------------------------------------------------------------
/**
* Constructs a new <code>IPFilterTests</code> test suite with
* the specified name. The name will be passed to the superconstructor.
*
* @param name
* the name for this test suite.
*/
public IPFilterTests(String name) {
super(name);
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
/**
* Performs setup for the tests.
*/
protected void setUp() {
// empty
}
public void testGetExpression() throws Throwable {
doTestGetExpression("1.2.3.4/1");
doTestGetExpression("0.0.0.0/0");
doTestGetExpression("194.134.168.213/32");
doTestGetExpression("194.13.1.213/20");
}
private void doTestGetExpression(String expression)
throws Throwable {
IPFilter filter = IPFilter.parseFilter(expression);
assertNotNull(filter);
assertEquals(expression, filter.getExpression());
assertEquals(expression, filter.getExpression());
}
public void testParseFilter() throws Throwable {
try {
IPFilter.parseFilter(null);
fail("IPFilter.parseFilter(null) should throw an IllegalArgumentException.");
} catch (IllegalArgumentException exception) {
// as expected
}
doTestParseFilter("abcd", false);
doTestParseFilter("abcd/24", false);
doTestParseFilter("a.b.c.d/12", false);
doTestParseFilter("1.2.3.4", false);
doTestParseFilter("1.2.3.4/", false);
doTestParseFilter("1.2.3.4/a", false);
doTestParseFilter("1.2.3.4/-1", false);
doTestParseFilter("1.2.3.4/0", true);
doTestParseFilter("1.2.3.4/5", true);
doTestParseFilter("1.2.3.4/5a", false);
doTestParseFilter("1.2.3.4a/5", false);
doTestParseFilter("1.2.3.4//5", false);
doTestParseFilter("1.2.3.4/32", true);
doTestParseFilter("1.2.3.4/33", false);
doTestParseFilter("1.2.3.4/1234567890123456", false);
}
private void doTestParseFilter(String expression, boolean okay)
throws Throwable {
if (! okay) {
try {
IPFilter.parseFilter(expression);
fail("IPFilter.parse(\"" + expression + "\") should throw a ParseException.");
} catch (ParseException exception) {
// as expected
}
} else {
IPFilter filter = IPFilter.parseFilter(expression);
assertNotNull(filter);
}
}
public void testIsAuthorized() throws Throwable {
IPFilter filter = IPFilter.parseFilter("194.134.168.213/32");
assertNotNull(filter);
try {
filter.isAuthorized(null);
fail("IPFilter.isAuthorized(null) should throw an IllegalArgumentException.");
return;
} catch (IllegalArgumentException exception) {
// as expected
}
doTestIsAuthorized(filter, "abcd", false, false);
doTestIsAuthorized(filter, "abcd", false, false);
doTestIsAuthorized(filter, "abcd/24", false, false);
doTestIsAuthorized(filter, "a.b.c.d", false, false);
doTestIsAuthorized(filter, "a.b.c.d/12", false, false);
- doTestIsAuthorized(filter, "1.2.3.4", false, false);
doTestIsAuthorized(filter, "1.2.3.4/", false, false);
doTestIsAuthorized(filter, "1.2.3.4/a", false, false);
doTestIsAuthorized(filter, "1.2.3.4/-1", false, false);
doTestIsAuthorized(filter, "1.2.3.4/0", false, false);
doTestIsAuthorized(filter, "1.2.3.4/5", false, false);
doTestIsAuthorized(filter, "1.2.3.4/5a", false, false);
doTestIsAuthorized(filter, "1.2.3.4a/5", false, false);
doTestIsAuthorized(filter, "1.2.3.4//5", false, false);
doTestIsAuthorized(filter, "1.2.3.4/32", false, false);
doTestIsAuthorized(filter, "1.2.3.4/33", false, false);
doTestIsAuthorized(filter, "1.2.3.4/1234567890123456", false, false);
doTestIsAuthorized(filter, "1.2.3.4", true, false);
doTestIsAuthorized(filter, "194.134.168.213", true, true);
doTestIsAuthorized(filter, "194.134.168.212", true, false);
doTestIsAuthorized(filter, "194.134.168.214", true, false);
}
private void doTestIsAuthorized(IPFilter filter,
String ip,
boolean validIP,
boolean shouldBeAuth)
throws Throwable {
if (validIP) {
boolean auth = filter.isAuthorized(ip);
if (shouldBeAuth && !auth) {
fail("IPFilter.isAuthorized(\"" + ip + "\") should return true for \"" + filter + "\".");
} else if (!shouldBeAuth && auth) {
fail("IPFilter.isAuthorized(\"" + ip + "\") should return false for \"" + filter + "\".");
}
} else {
try {
filter.isAuthorized(ip);
fail("IPFilter.isAuthorized(\"" + ip + "\") should throw a ParseException.");
return;
} catch (ParseException exception) {
// as expected
}
}
}
}
| true | true | public void testIsAuthorized() throws Throwable {
IPFilter filter = IPFilter.parseFilter("194.134.168.213/32");
assertNotNull(filter);
try {
filter.isAuthorized(null);
fail("IPFilter.isAuthorized(null) should throw an IllegalArgumentException.");
return;
} catch (IllegalArgumentException exception) {
// as expected
}
doTestIsAuthorized(filter, "abcd", false, false);
doTestIsAuthorized(filter, "abcd", false, false);
doTestIsAuthorized(filter, "abcd/24", false, false);
doTestIsAuthorized(filter, "a.b.c.d", false, false);
doTestIsAuthorized(filter, "a.b.c.d/12", false, false);
doTestIsAuthorized(filter, "1.2.3.4", false, false);
doTestIsAuthorized(filter, "1.2.3.4/", false, false);
doTestIsAuthorized(filter, "1.2.3.4/a", false, false);
doTestIsAuthorized(filter, "1.2.3.4/-1", false, false);
doTestIsAuthorized(filter, "1.2.3.4/0", false, false);
doTestIsAuthorized(filter, "1.2.3.4/5", false, false);
doTestIsAuthorized(filter, "1.2.3.4/5a", false, false);
doTestIsAuthorized(filter, "1.2.3.4a/5", false, false);
doTestIsAuthorized(filter, "1.2.3.4//5", false, false);
doTestIsAuthorized(filter, "1.2.3.4/32", false, false);
doTestIsAuthorized(filter, "1.2.3.4/33", false, false);
doTestIsAuthorized(filter, "1.2.3.4/1234567890123456", false, false);
doTestIsAuthorized(filter, "1.2.3.4", true, false);
doTestIsAuthorized(filter, "194.134.168.213", true, true);
doTestIsAuthorized(filter, "194.134.168.212", true, false);
doTestIsAuthorized(filter, "194.134.168.214", true, false);
}
| public void testIsAuthorized() throws Throwable {
IPFilter filter = IPFilter.parseFilter("194.134.168.213/32");
assertNotNull(filter);
try {
filter.isAuthorized(null);
fail("IPFilter.isAuthorized(null) should throw an IllegalArgumentException.");
return;
} catch (IllegalArgumentException exception) {
// as expected
}
doTestIsAuthorized(filter, "abcd", false, false);
doTestIsAuthorized(filter, "abcd", false, false);
doTestIsAuthorized(filter, "abcd/24", false, false);
doTestIsAuthorized(filter, "a.b.c.d", false, false);
doTestIsAuthorized(filter, "a.b.c.d/12", false, false);
doTestIsAuthorized(filter, "1.2.3.4/", false, false);
doTestIsAuthorized(filter, "1.2.3.4/a", false, false);
doTestIsAuthorized(filter, "1.2.3.4/-1", false, false);
doTestIsAuthorized(filter, "1.2.3.4/0", false, false);
doTestIsAuthorized(filter, "1.2.3.4/5", false, false);
doTestIsAuthorized(filter, "1.2.3.4/5a", false, false);
doTestIsAuthorized(filter, "1.2.3.4a/5", false, false);
doTestIsAuthorized(filter, "1.2.3.4//5", false, false);
doTestIsAuthorized(filter, "1.2.3.4/32", false, false);
doTestIsAuthorized(filter, "1.2.3.4/33", false, false);
doTestIsAuthorized(filter, "1.2.3.4/1234567890123456", false, false);
doTestIsAuthorized(filter, "1.2.3.4", true, false);
doTestIsAuthorized(filter, "194.134.168.213", true, true);
doTestIsAuthorized(filter, "194.134.168.212", true, false);
doTestIsAuthorized(filter, "194.134.168.214", true, false);
}
|
diff --git a/src/main/java/com/norcode/bukkit/buildinabox/listeners/PlayerListener.java b/src/main/java/com/norcode/bukkit/buildinabox/listeners/PlayerListener.java
index ea55b26..86e2bc9 100644
--- a/src/main/java/com/norcode/bukkit/buildinabox/listeners/PlayerListener.java
+++ b/src/main/java/com/norcode/bukkit/buildinabox/listeners/PlayerListener.java
@@ -1,296 +1,299 @@
package com.norcode.bukkit.buildinabox.listeners;
import com.norcode.bukkit.buildinabox.*;
import com.norcode.bukkit.buildinabox.BuildChest.UnlockingTask;
import com.norcode.bukkit.buildinabox.events.BIABLockEvent;
import com.norcode.bukkit.buildinabox.events.BIABPlaceEvent;
import com.norcode.bukkit.schematica.Session;
import com.norcode.bukkit.schematica.exceptions.SchematicSaveException;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Result;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.util.Vector;
import java.util.EnumSet;
public class PlayerListener implements Listener {
BuildInABox plugin;
EnumSet lockableBlockTypes = EnumSet.of(Material.CHEST, Material.TRAPPED_CHEST,
Material.TRAP_DOOR, Material.WOODEN_DOOR, Material.IRON_DOOR, Material.FURNACE,
Material.DISPENSER, Material.DROPPER, Material.HOPPER, Material.BREWING_STAND,
Material.JUKEBOX, Material.ANVIL, Material.BURNING_FURNACE, Material.BEACON);
public PlayerListener(BuildInABox plugin) {
this.plugin = plugin;
}
@EventHandler(ignoreCancelled=true)
public void onPlayerLogin(PlayerLoginEvent event) {
if (plugin.updater == null) return;
if (event.getPlayer().hasPermission("biab.admin")) {
final String playerName = event.getPlayer().getName();
plugin.getServer().getScheduler().runTaskLaterAsynchronously(plugin, new Runnable() {
public void run() {
Player player = plugin.getServer().getPlayer(playerName);
if (player != null && player.isOnline()) {
switch (plugin.updater.getResult()) {
case UPDATE_AVAILABLE:
player.sendMessage(BuildInABox.getNormalMsg("update-available", "http://dev.bukkit.org/server-mods/build-in-a-box/"));
break;
case SUCCESS:
player.sendMessage(BuildInABox.getNormalMsg("update-downloaded"));
break;
}
}
}
}, 20);
}
}
@EventHandler(ignoreCancelled=true, priority = EventPriority.LOW)
public void onPlayerSelection(PlayerInteractEvent event) {
if (event.getItem() != null && event.getItem().getTypeId() == plugin.getConfig().getInt("selection-wand-id", 294)) { // GOLD_HOE
if (!event.getPlayer().hasPermission("biab.select")) {
return;
}
if (event.getPlayer().hasMetadata("biab-pending-save") && event.getClickedBlock().getTypeId() == plugin.cfg.getChestBlockId()) {
plugin.debug("Offset selected.");
BuildingPlan planData = (BuildingPlan) event.getPlayer().getMetadata("biab-pending-save").get(0).value();
event.getPlayer().removeMetadata("biab-pending-save", plugin);
BuildingPlan plan = null;
try {
plan = BuildingPlan.fromClipboard(plugin, event.getPlayer(), planData.getName(), event.getClickedBlock().getLocation());
} catch (SchematicSaveException e) {
e.printStackTrace();
event.getPlayer().sendMessage(BuildInABox.getErrorMsg("save-failed"));
return;
}
plan.setFilename(planData.getFilename());
plan.setDisplayName(planData.getDisplayName());
plan.setDescription(planData.getDescription());
plugin.getDataStore().saveBuildingPlan(plan);
plan.registerPermissions();
event.getPlayer().sendMessage(BuildInABox.getSuccessMsg("building-plan-saved", plan.getDisplayName()));
} else {
Session session = plugin.getPlayerSession(event.getPlayer());
if (event.getClickedBlock() != null) {
Vector v = event.getClickedBlock().getLocation().toVector();
if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
session.getSelection().setPt1(event.getClickedBlock().getLocation());
event.getPlayer().sendMessage(BuildInABox.getSuccessMsg("selection-pt1-set", "X:" + v.getBlockX() + " Y:" + v.getBlockY() + " Z:" + v.getBlockZ()));
} else if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
session.getSelection().setPt2(event.getClickedBlock().getLocation());
event.getPlayer().sendMessage(BuildInABox.getSuccessMsg("selection-pt2-set", "X:" + v.getBlockX() + " Y:" + v.getBlockY() + " Z:" + v.getBlockZ()));
} else {
return;
}
}
}
event.setCancelled(true);
event.setUseInteractedBlock(Result.DENY);
event.setUseItemInHand(Result.DENY);
}
}
@EventHandler(ignoreCancelled=true, priority = EventPriority.NORMAL)
public void onPlayerInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
Block block = event.getClickedBlock();
+ if (block == null) {
+ return;
+ }
if (block.getTypeId() == plugin.cfg.getChestBlockId()) {
if (block.hasMetadata("buildInABox")) {
BuildChest bc = (BuildChest) block.getMetadata("buildInABox").get(0).value();
if (!bc.canInteract()) {
event.setCancelled(true);
event.setUseInteractedBlock(Result.DENY);
event.setUseItemInHand(Result.DENY);
return;
}
bc.updateActivity();
if (bc.isPreviewing() && bc.getPreviewingPlayer().equals(player.getName())) {
if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
// Cancel
bc.endPreview(player);
} else if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
// build
bc.build(player);
}
} else {
long now = System.currentTimeMillis();
if (bc.isLocking()) {
if (!bc.getLockingTask().lockingPlayer.equals(player.getName())) {
if (plugin.getConfig().getBoolean("allow-unlocking-others", true)) {
if (player.hasPermission("biab.unlock.others")) {
BIABLockEvent le = new BIABLockEvent(player, bc, (bc.getLockingTask() instanceof UnlockingTask) ? BIABLockEvent.Type.UNLOCK_CANCEL : BIABLockEvent.Type.LOCK_CANCEL);
plugin.getServer().getPluginManager().callEvent(le);
if (le.isCancelled()) {
return;
}
String msgKey = "lock-attempt-cancelled";
if (bc.getLockingTask() instanceof UnlockingTask) {
msgKey = "un" + msgKey;
}
player.sendMessage(BuildInABox.getNormalMsg(msgKey, bc.getLockingTask().lockingPlayer));
bc.getLockingTask().cancel();
} else {
player.sendMessage(BuildInABox.getErrorMsg("no-permission"));
}
}
} else {
bc.getLockingTask().cancel();
}
} else if (player.hasMetadata("biab-permanent-timeout")) {
long timeout = player.getMetadata("biab-permanent-timeout").get(0).asLong();
if (timeout > now) {
if (plugin.getConfig().getBoolean("protect-buildings", true)) {
bc.unprotect();
plugin.getDataStore().deleteChest(bc.getId());
}
}
player.removeMetadata("biab-permanent-timeout", plugin);
} else if (now - bc.getLastClicked() < plugin.getConfig().getInt("double-click-interval",2000)
&& bc.getLastClickType().equals(event.getAction())
&& player.getName().equals(bc.getLastClickedBy())) {
if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
// pick up
if (!bc.isLocked()) {
if (player.hasPermission("biab.pickup." + bc.getPlan().getName().toLowerCase())) {
bc.pickup(player);
} else {
player.sendMessage(BuildInABox.getErrorMsg("no-permission"));
}
}
} else if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
// lock/unlock
if (plugin.getConfig().getBoolean("allow-locking", true)) {
if (bc.isLocked()) {
if (bc.getLockedBy().equals(player.getName())) {
if (player.hasPermission("biab.unlock." + bc.getPlan().getName().toLowerCase())) {
bc.unlock(player);
} else {
player.sendMessage(BuildInABox.getErrorMsg("no-permission"));
}
} else if (plugin.getConfig().getBoolean("allow-unlocking-others")) {
if (player.hasPermission("biab.unlock.others")) {
bc.unlock(player);
} else {
player.sendMessage(BuildInABox.getErrorMsg("no-permission"));
}
}
} else {
if (player.hasPermission("biab.lock." + bc.getPlan().getName().toLowerCase())) {
bc.lock(player);
} else {
player.sendMessage(BuildInABox.getErrorMsg("no-permission"));
}
}
}
}
bc.setLastClicked(-1);
bc.setLastClickType(null);
bc.setLastClickedBy(null);
} else {
bc.setLastClicked(now);
bc.setLastClickType(event.getAction());
bc.setLastClickedBy(event.getPlayer().getName());
player.sendMessage(bc.getDescription());
}
}
event.setCancelled(true);
event.setUseInteractedBlock(Result.DENY);
event.setUseItemInHand(Result.DENY);
}
}
}
@EventHandler(ignoreCancelled=true)
public void onPlaceEnderchest(final BlockPlaceEvent event) {
if (event.getBlock().getTypeId() == plugin.cfg.getChestBlockId()) {
if (plugin.getConfig().getBoolean("prevent-placing-enderchests", false)) {
ChestData data = plugin.getDataStore().fromItemStack(event.getItemInHand());
if (data == null) {
event.setCancelled(true);
}
}
}
}
@EventHandler(ignoreCancelled=true, priority=EventPriority.HIGH)
public void onBlockPlace(final BlockPlaceEvent event) {
ChestData data = plugin.getDataStore().fromItemStack(event.getItemInHand());
if (data != null) {
if (!event.getPlayer().hasPermission("biab.place." + data.getPlanName().toLowerCase())) {
event.getPlayer().sendMessage(BuildInABox.getErrorMsg("no-permission"));
event.setCancelled(true);
event.setBuild(false);
return;
}
BIABPlaceEvent placeEvent = new BIABPlaceEvent(event.getPlayer(), event.getBlock().getLocation(), event.getItemInHand(), data);
plugin.getServer().getPluginManager().callEvent(placeEvent);
if (placeEvent.isCancelled()) {
event.setCancelled(true);
return;
}
data.setLocation(event.getBlock().getLocation());
data.setLastActivity(System.currentTimeMillis());
final BuildChest bc = new BuildChest(data);
event.getBlock().setMetadata("buildInABox", new FixedMetadataValue(plugin, bc));
event.getPlayer().getInventory().setItemInHand(null);
plugin.getServer().getScheduler().runTaskLater(plugin, new Runnable() {
public void run() {
if (event.getPlayer().isOnline()) {
bc.preview(event.getPlayer());
plugin.checkCarrying(event.getPlayer());
}
}
}, 1);
} else if (plugin.getConfig().getBoolean("prevent-placing-enderchests", false)) {
event.setCancelled(true);
event.setBuild(false);
}
}
@EventHandler(ignoreCancelled=true)
public void onPlayerQuit(PlayerQuitEvent event) {
event.getPlayer().removeMetadata("biab-selection-session", plugin);
}
@EventHandler(ignoreCancelled=false, priority=EventPriority.HIGHEST)
public void onFakeBlockPlace(final BlockPlaceEvent event) {
if (event instanceof FakeBlockPlaceEvent) {
// prevent them from getting logged.
((FakeBlockPlaceEvent) event).setWasCancelled(event.isCancelled());
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled=true)
public void onPlayerInteractLocked(PlayerInteractEvent event) {
if (plugin.cfg.isLockingEnabled()) {
if (lockableBlockTypes.contains(event.getClickedBlock().getType())) {
if (event.getClickedBlock().hasMetadata("biab-block")) {
BuildChest bc = (BuildChest) event.getClickedBlock().getMetadata("biab-block").get(0).value();
if (bc.isLocked() && !bc.getLockedBy().equals(event.getPlayer().getName())) {
event.getPlayer().sendMessage(BuildInABox.getErrorMsg("building-is-locked", bc.getPlan().getDisplayName(), bc.getLockedBy()));
event.setCancelled(true);
event.setUseInteractedBlock(Result.DENY);
}
}
}
}
}
}
| true | true | public void onPlayerInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
Block block = event.getClickedBlock();
if (block.getTypeId() == plugin.cfg.getChestBlockId()) {
if (block.hasMetadata("buildInABox")) {
BuildChest bc = (BuildChest) block.getMetadata("buildInABox").get(0).value();
if (!bc.canInteract()) {
event.setCancelled(true);
event.setUseInteractedBlock(Result.DENY);
event.setUseItemInHand(Result.DENY);
return;
}
bc.updateActivity();
if (bc.isPreviewing() && bc.getPreviewingPlayer().equals(player.getName())) {
if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
// Cancel
bc.endPreview(player);
} else if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
// build
bc.build(player);
}
} else {
long now = System.currentTimeMillis();
if (bc.isLocking()) {
if (!bc.getLockingTask().lockingPlayer.equals(player.getName())) {
if (plugin.getConfig().getBoolean("allow-unlocking-others", true)) {
if (player.hasPermission("biab.unlock.others")) {
BIABLockEvent le = new BIABLockEvent(player, bc, (bc.getLockingTask() instanceof UnlockingTask) ? BIABLockEvent.Type.UNLOCK_CANCEL : BIABLockEvent.Type.LOCK_CANCEL);
plugin.getServer().getPluginManager().callEvent(le);
if (le.isCancelled()) {
return;
}
String msgKey = "lock-attempt-cancelled";
if (bc.getLockingTask() instanceof UnlockingTask) {
msgKey = "un" + msgKey;
}
player.sendMessage(BuildInABox.getNormalMsg(msgKey, bc.getLockingTask().lockingPlayer));
bc.getLockingTask().cancel();
} else {
player.sendMessage(BuildInABox.getErrorMsg("no-permission"));
}
}
} else {
bc.getLockingTask().cancel();
}
} else if (player.hasMetadata("biab-permanent-timeout")) {
long timeout = player.getMetadata("biab-permanent-timeout").get(0).asLong();
if (timeout > now) {
if (plugin.getConfig().getBoolean("protect-buildings", true)) {
bc.unprotect();
plugin.getDataStore().deleteChest(bc.getId());
}
}
player.removeMetadata("biab-permanent-timeout", plugin);
} else if (now - bc.getLastClicked() < plugin.getConfig().getInt("double-click-interval",2000)
&& bc.getLastClickType().equals(event.getAction())
&& player.getName().equals(bc.getLastClickedBy())) {
if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
// pick up
if (!bc.isLocked()) {
if (player.hasPermission("biab.pickup." + bc.getPlan().getName().toLowerCase())) {
bc.pickup(player);
} else {
player.sendMessage(BuildInABox.getErrorMsg("no-permission"));
}
}
} else if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
// lock/unlock
if (plugin.getConfig().getBoolean("allow-locking", true)) {
if (bc.isLocked()) {
if (bc.getLockedBy().equals(player.getName())) {
if (player.hasPermission("biab.unlock." + bc.getPlan().getName().toLowerCase())) {
bc.unlock(player);
} else {
player.sendMessage(BuildInABox.getErrorMsg("no-permission"));
}
} else if (plugin.getConfig().getBoolean("allow-unlocking-others")) {
if (player.hasPermission("biab.unlock.others")) {
bc.unlock(player);
} else {
player.sendMessage(BuildInABox.getErrorMsg("no-permission"));
}
}
} else {
if (player.hasPermission("biab.lock." + bc.getPlan().getName().toLowerCase())) {
bc.lock(player);
} else {
player.sendMessage(BuildInABox.getErrorMsg("no-permission"));
}
}
}
}
bc.setLastClicked(-1);
bc.setLastClickType(null);
bc.setLastClickedBy(null);
} else {
bc.setLastClicked(now);
bc.setLastClickType(event.getAction());
bc.setLastClickedBy(event.getPlayer().getName());
player.sendMessage(bc.getDescription());
}
}
event.setCancelled(true);
event.setUseInteractedBlock(Result.DENY);
event.setUseItemInHand(Result.DENY);
}
}
}
| public void onPlayerInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
Block block = event.getClickedBlock();
if (block == null) {
return;
}
if (block.getTypeId() == plugin.cfg.getChestBlockId()) {
if (block.hasMetadata("buildInABox")) {
BuildChest bc = (BuildChest) block.getMetadata("buildInABox").get(0).value();
if (!bc.canInteract()) {
event.setCancelled(true);
event.setUseInteractedBlock(Result.DENY);
event.setUseItemInHand(Result.DENY);
return;
}
bc.updateActivity();
if (bc.isPreviewing() && bc.getPreviewingPlayer().equals(player.getName())) {
if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
// Cancel
bc.endPreview(player);
} else if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
// build
bc.build(player);
}
} else {
long now = System.currentTimeMillis();
if (bc.isLocking()) {
if (!bc.getLockingTask().lockingPlayer.equals(player.getName())) {
if (plugin.getConfig().getBoolean("allow-unlocking-others", true)) {
if (player.hasPermission("biab.unlock.others")) {
BIABLockEvent le = new BIABLockEvent(player, bc, (bc.getLockingTask() instanceof UnlockingTask) ? BIABLockEvent.Type.UNLOCK_CANCEL : BIABLockEvent.Type.LOCK_CANCEL);
plugin.getServer().getPluginManager().callEvent(le);
if (le.isCancelled()) {
return;
}
String msgKey = "lock-attempt-cancelled";
if (bc.getLockingTask() instanceof UnlockingTask) {
msgKey = "un" + msgKey;
}
player.sendMessage(BuildInABox.getNormalMsg(msgKey, bc.getLockingTask().lockingPlayer));
bc.getLockingTask().cancel();
} else {
player.sendMessage(BuildInABox.getErrorMsg("no-permission"));
}
}
} else {
bc.getLockingTask().cancel();
}
} else if (player.hasMetadata("biab-permanent-timeout")) {
long timeout = player.getMetadata("biab-permanent-timeout").get(0).asLong();
if (timeout > now) {
if (plugin.getConfig().getBoolean("protect-buildings", true)) {
bc.unprotect();
plugin.getDataStore().deleteChest(bc.getId());
}
}
player.removeMetadata("biab-permanent-timeout", plugin);
} else if (now - bc.getLastClicked() < plugin.getConfig().getInt("double-click-interval",2000)
&& bc.getLastClickType().equals(event.getAction())
&& player.getName().equals(bc.getLastClickedBy())) {
if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
// pick up
if (!bc.isLocked()) {
if (player.hasPermission("biab.pickup." + bc.getPlan().getName().toLowerCase())) {
bc.pickup(player);
} else {
player.sendMessage(BuildInABox.getErrorMsg("no-permission"));
}
}
} else if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
// lock/unlock
if (plugin.getConfig().getBoolean("allow-locking", true)) {
if (bc.isLocked()) {
if (bc.getLockedBy().equals(player.getName())) {
if (player.hasPermission("biab.unlock." + bc.getPlan().getName().toLowerCase())) {
bc.unlock(player);
} else {
player.sendMessage(BuildInABox.getErrorMsg("no-permission"));
}
} else if (plugin.getConfig().getBoolean("allow-unlocking-others")) {
if (player.hasPermission("biab.unlock.others")) {
bc.unlock(player);
} else {
player.sendMessage(BuildInABox.getErrorMsg("no-permission"));
}
}
} else {
if (player.hasPermission("biab.lock." + bc.getPlan().getName().toLowerCase())) {
bc.lock(player);
} else {
player.sendMessage(BuildInABox.getErrorMsg("no-permission"));
}
}
}
}
bc.setLastClicked(-1);
bc.setLastClickType(null);
bc.setLastClickedBy(null);
} else {
bc.setLastClicked(now);
bc.setLastClickType(event.getAction());
bc.setLastClickedBy(event.getPlayer().getName());
player.sendMessage(bc.getDescription());
}
}
event.setCancelled(true);
event.setUseInteractedBlock(Result.DENY);
event.setUseItemInHand(Result.DENY);
}
}
}
|
diff --git a/src/net/java/sip/communicator/impl/gui/main/login/LoginManager.java b/src/net/java/sip/communicator/impl/gui/main/login/LoginManager.java
index e9225cd0e..35bce41d8 100644
--- a/src/net/java/sip/communicator/impl/gui/main/login/LoginManager.java
+++ b/src/net/java/sip/communicator/impl/gui/main/login/LoginManager.java
@@ -1,572 +1,572 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.gui.main.login;
import net.java.sip.communicator.impl.gui.*;
import net.java.sip.communicator.impl.gui.customcontrols.*;
import net.java.sip.communicator.impl.gui.main.*;
import net.java.sip.communicator.impl.gui.main.authorization.*;
import net.java.sip.communicator.impl.gui.utils.Constants;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;
import org.osgi.framework.*;
/**
* The <tt>LoginManager</tt> manages the login operation. Here we obtain the
* <tt>ProtocolProviderFactory</tt>, we make the account installation and we
* handle all events related to the registration state.
* <p>
* The <tt>LoginManager</tt> is the one that opens one or more
* <tt>LoginWindow</tt>s for each <tt>ProtocolProviderFactory</tt>. The
* <tt>LoginWindow</tt> is where user could enter an identifier and password.
* <p>
* Note that the behavior of this class will be changed when the Configuration
* Service is ready.
*
* @author Yana Stamcheva
*/
public class LoginManager
implements ServiceListener,
RegistrationStateChangeListener
{
private Logger logger = Logger.getLogger(LoginManager.class.getName());
private MainFrame mainFrame;
private boolean manuallyDisconnected = false;
/**
* Creates an instance of the <tt>LoginManager</tt>, by specifying the main
* application window.
*
* @param mainFrame the main application window
*/
public LoginManager(MainFrame mainFrame)
{
this.mainFrame = mainFrame;
GuiActivator.bundleContext.addServiceListener(this);
}
/**
* Registers the given protocol provider.
*
* @param protocolProvider the ProtocolProviderService to register.
*/
public void login(ProtocolProviderService protocolProvider)
{
SecurityAuthorityImpl secAuth = new SecurityAuthorityImpl(mainFrame,
protocolProvider);
new RegisterProvider(protocolProvider, secAuth).start();
}
/**
* Unregisters the given protocol provider.
*
* @param protocolProvider the ProtocolProviderService to unregister
*/
public void logoff(ProtocolProviderService protocolProvider)
{
new UnregisterProvider(protocolProvider).start();
}
/**
* Shows login window for each registered account.
*
* @param parent The parent MainFrame window.
*/
public void runLogin(MainFrame parent)
{
for (ProtocolProviderFactory providerFactory : GuiActivator
.getProtocolProviderFactories().values())
{
ServiceReference serRef;
ProtocolProviderService protocolProvider;
for (AccountID accountID : providerFactory.getRegisteredAccounts())
{
serRef = providerFactory.getProviderForAccount(accountID);
protocolProvider =
(ProtocolProviderService) GuiActivator.bundleContext
.getService(serRef);
protocolProvider.addRegistrationStateChangeListener(this);
this.mainFrame.addProtocolProvider(protocolProvider);
Object status =
this.mainFrame
.getProtocolProviderLastStatus(protocolProvider);
if (status == null
|| status.equals(Constants.ONLINE_STATUS)
|| ((status instanceof PresenceStatus) && (((PresenceStatus) status)
.getStatus() >= PresenceStatus.ONLINE_THRESHOLD)))
{
this.login(protocolProvider);
}
}
}
}
/**
* The method is called by a ProtocolProvider implementation whenever a
* change in the registration state of the corresponding provider had
* occurred.
*
* @param evt ProviderStatusChangeEvent the event describing the status
* change.
*/
public void registrationStateChanged(RegistrationStateChangeEvent evt)
{
ProtocolProviderService protocolProvider = evt.getProvider();
AccountID accountID = protocolProvider.getAccountID();
logger.trace("Protocol provider: " + protocolProvider
+ " changed its state to: " + evt.getNewState().getStateName());
OperationSetPresence presence = mainFrame
.getProtocolPresenceOpSet(protocolProvider);
OperationSetMultiUserChat multiUserChat = mainFrame
.getMultiUserChatOpSet(protocolProvider);
if (evt.getNewState().equals(RegistrationState.REGISTERED))
{
if (presence != null)
{
presence.setAuthorizationHandler(new AuthorizationHandlerImpl(
mainFrame));
}
if(multiUserChat != null)
{
GuiActivator.getUIService().getConferenceChatManager()
.getChatRoomList().synchronizeOpSetWithLocalContactList(
protocolProvider, multiUserChat);
}
}
else if (evt.getNewState().equals(
RegistrationState.AUTHENTICATION_FAILED))
{
if (evt.getReasonCode() == RegistrationStateChangeEvent
.REASON_RECONNECTION_RATE_LIMIT_EXCEEDED)
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.RECONNECTION_LIMIT_EXCEEDED", new String[]
{ accountID.getUserID(), accountID.getService() });
new ErrorDialog(
null,
GuiActivator.getResources()
.getI18NString("service.gui.ERROR"),
msgText).showDialog();
}
else if (evt.getReasonCode() == RegistrationStateChangeEvent
.REASON_NON_EXISTING_USER_ID)
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.NON_EXISTING_USER_ID",
new String[]
{ protocolProvider.getProtocolDisplayName() });
new ErrorDialog(
null,
GuiActivator.getResources().getI18NString("service.gui.ERROR"),
msgText).showDialog();
}
- logger.error(evt.getReason());
+ logger.trace(evt.getReason());
}
else if (evt.getNewState().equals(RegistrationState.CONNECTION_FAILED))
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.CONNECTION_FAILED_MSG",
new String[]
{ accountID.getUserID(),
accountID.getService() });
int result = new MessageDialog(
null,
GuiActivator.getResources().getI18NString("service.gui.ERROR"),
msgText,
GuiActivator.getResources().getI18NString("service.gui.RETRY"),
false).showDialog();
if (result == MessageDialog.OK_RETURN_CODE)
{
this.login(protocolProvider);
}
- logger.error(evt.getReason());
+ logger.trace(evt.getReason());
}
else if (evt.getNewState().equals(RegistrationState.EXPIRED))
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.CONNECTION_EXPIRED_MSG",
new String[]
{ protocolProvider.getProtocolDisplayName() });
new ErrorDialog(null,
GuiActivator.getResources().getI18NString("service.gui.ERROR"),
msgText).showDialog();
logger.error(evt.getReason());
}
else if (evt.getNewState().equals(RegistrationState.UNREGISTERED))
{
if (!manuallyDisconnected)
{
if (evt.getReasonCode() == RegistrationStateChangeEvent
.REASON_MULTIPLE_LOGINS)
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.MULTIPLE_LOGINS",
new String[]
{ accountID.getUserID(), accountID.getService() });
new ErrorDialog(null,
GuiActivator.getResources()
.getI18NString("service.gui.ERROR"),
msgText).showDialog();
}
else if (evt.getReasonCode() == RegistrationStateChangeEvent
.REASON_CLIENT_LIMIT_REACHED_FOR_IP)
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.LIMIT_REACHED_FOR_IP", new String[]
{ protocolProvider.getProtocolDisplayName() });
new ErrorDialog(null,
GuiActivator.getResources()
.getI18NString("service.gui.ERROR"),
msgText).showDialog();
}
else if (evt.getReasonCode() == RegistrationStateChangeEvent
.REASON_USER_REQUEST)
{
// do nothing
}
else
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.UNREGISTERED_MESSAGE", new String[]
{ accountID.getUserID(), accountID.getService() });
new ErrorDialog(null,
GuiActivator.getResources()
.getI18NString("service.gui.ERROR"),
msgText).showDialog();
}
- logger.error(evt.getReason());
+ logger.trace(evt.getReason());
}
}
}
/**
* Returns the MainFrame.
*
* @return The MainFrame.
*/
public MainFrame getMainFrame()
{
return mainFrame;
}
/**
* Sets the MainFrame.
*
* @param mainFrame The main frame.
*/
public void setMainFrame(MainFrame mainFrame)
{
this.mainFrame = mainFrame;
}
/**
* Implements the <tt>ServiceListener</tt> method. Verifies whether the
* passed event concerns a <tt>ProtocolProviderService</tt> and adds the
* corresponding UI controls.
*
* @param event The <tt>ServiceEvent</tt> object.
*/
public void serviceChanged(ServiceEvent event)
{
// if the event is caused by a bundle being stopped, we don't want to
// know
if (event.getServiceReference().getBundle().getState()
== Bundle.STOPPING)
{
return;
}
Object service = GuiActivator.bundleContext.getService(event
.getServiceReference());
// we don't care if the source service is not a protocol provider
if (!(service instanceof ProtocolProviderService))
{
return;
}
if (event.getType() == ServiceEvent.REGISTERED)
{
this.handleProviderAdded((ProtocolProviderService) service);
}
else if (event.getType() == ServiceEvent.UNREGISTERING)
{
this.handleProviderRemoved((ProtocolProviderService) service);
}
}
/**
* Adds all UI components (status selector box, etc) related to the given
* protocol provider.
*
* @param protocolProvider the <tt>ProtocolProviderService</tt>
*/
private void handleProviderAdded(ProtocolProviderService protocolProvider)
{
logger.trace("The following protocol provider was just added: "
+ protocolProvider.getAccountID().getAccountAddress());
protocolProvider.addRegistrationStateChangeListener(this);
this.mainFrame.addProtocolProvider(protocolProvider);
Object status = this.mainFrame
.getProtocolProviderLastStatus(protocolProvider);
if (status == null
|| status.equals(Constants.ONLINE_STATUS)
|| ((status instanceof PresenceStatus) && (((PresenceStatus) status)
.getStatus() >= PresenceStatus.ONLINE_THRESHOLD)))
{
this.login(protocolProvider);
}
}
/**
* Removes all UI components related to the given protocol provider.
*
* @param protocolProvider the <tt>ProtocolProviderService</tt>
*/
private void handleProviderRemoved(ProtocolProviderService protocolProvider)
{
this.mainFrame.removeProtocolProvider(protocolProvider);
}
public boolean isManuallyDisconnected()
{
return manuallyDisconnected;
}
public void setManuallyDisconnected(boolean manuallyDisconnected)
{
this.manuallyDisconnected = manuallyDisconnected;
}
/**
* Registers a protocol provider in a separate thread.
*/
private class RegisterProvider
extends Thread
{
private final ProtocolProviderService protocolProvider;
private final SecurityAuthority secAuth;
RegisterProvider(ProtocolProviderService protocolProvider,
SecurityAuthority secAuth)
{
this.protocolProvider = protocolProvider;
this.secAuth = secAuth;
}
/**
* Registers the contained protocol provider and process all possible
* errors that may occur during the registration process.
*/
public void run()
{
try
{
protocolProvider.register(secAuth);
}
catch (OperationFailedException ex)
{
handleOperationFailedException(ex);
}
catch (Throwable ex)
{
logger.error("Failed to register protocol provider. ", ex);
AccountID accountID = protocolProvider.getAccountID();
new ErrorDialog(
mainFrame,
GuiActivator.getResources()
.getI18NString("service.gui.ERROR"),
GuiActivator.getResources()
.getI18NString("service.gui.LOGIN_GENERAL_ERROR",
new String[]
{ accountID.getUserID(), accountID.getService() }))
.showDialog();
}
}
private void handleOperationFailedException(OperationFailedException ex)
{
String errorMessage = "";
switch (ex.getErrorCode())
{
case OperationFailedException.GENERAL_ERROR:
{
logger.error("Provider could not be registered"
+ " due to the following general error: ", ex);
AccountID accountID = protocolProvider.getAccountID();
errorMessage =
GuiActivator.getResources().getI18NString(
"service.gui.LOGIN_GENERAL_ERROR",
new String[]
{ accountID.getUserID(), accountID.getService() });
new ErrorDialog(mainFrame,
GuiActivator.getResources()
.getI18NString("service.gui.ERROR"), errorMessage, ex)
.showDialog();
}
break;
case OperationFailedException.INTERNAL_ERROR:
{
logger.error("Provider could not be registered"
+ " due to the following internal error: ", ex);
AccountID accountID = protocolProvider.getAccountID();
errorMessage =
GuiActivator.getResources().getI18NString(
"service.gui.LOGIN_INTERNAL_ERROR",
new String[]
{ accountID.getUserID(), accountID.getService() });
new ErrorDialog(mainFrame,
GuiActivator.getResources().getI18NString(
"service.gui.ERROR"), errorMessage, ex).showDialog();
}
break;
case OperationFailedException.NETWORK_FAILURE:
{
logger.error("Provider could not be registered"
+ " due to a network failure: " + ex);
AccountID accountID = protocolProvider.getAccountID();
errorMessage = GuiActivator.getResources().getI18NString(
"service.gui.LOGIN_NETWORK_ERROR",
new String[]
{ accountID.getUserID(), accountID.getService() });
int result =
new MessageDialog(
null,
GuiActivator.getResources()
.getI18NString("service.gui.ERROR"),
errorMessage,
GuiActivator.getResources()
.getI18NString("service.gui.RETRY"), false)
.showDialog();
if (result == MessageDialog.OK_RETURN_CODE)
{
login(protocolProvider);
}
}
break;
case OperationFailedException.INVALID_ACCOUNT_PROPERTIES:
{
logger.error("Provider could not be registered"
+ " due to an invalid account property: ", ex);
AccountID accountID = protocolProvider.getAccountID();
errorMessage =
GuiActivator.getResources().getI18NString(
"service.gui.LOGIN_INVALID_PROPERTIES_ERROR",
new String[]
{ accountID.getUserID(), accountID.getService() });
new ErrorDialog(mainFrame,
GuiActivator.getResources().getI18NString("service.gui.ERROR"),
errorMessage, ex).showDialog();
}
break;
default:
logger.error("Provider could not be registered.", ex);
}
}
}
/**
* Unregisters a protocol provider in a separate thread.
*/
private class UnregisterProvider
extends Thread
{
ProtocolProviderService protocolProvider;
UnregisterProvider(ProtocolProviderService protocolProvider)
{
this.protocolProvider = protocolProvider;
}
/**
* Unregisters the contained protocol provider and process all possible
* errors that may occur during the un-registration process.
*/
public void run()
{
try
{
protocolProvider.unregister();
}
catch (OperationFailedException ex)
{
int errorCode = ex.getErrorCode();
if (errorCode == OperationFailedException.GENERAL_ERROR)
{
logger.error("Provider could not be unregistered"
+ " due to the following general error: " + ex);
}
else if (errorCode == OperationFailedException.INTERNAL_ERROR)
{
logger.error("Provider could not be unregistered"
+ " due to the following internal error: " + ex);
}
else if (errorCode == OperationFailedException.NETWORK_FAILURE)
{
logger.error("Provider could not be unregistered"
+ " due to a network failure: " + ex);
}
new ErrorDialog(mainFrame,
GuiActivator.getResources()
.getI18NString("service.gui.ERROR"),
GuiActivator.getResources()
.getI18NString("service.gui.LOGOFF_NOT_SUCCEEDED",
new String[]
{ protocolProvider.getAccountID().getUserID(),
protocolProvider.getAccountID().getService() }))
.showDialog();
}
}
}
}
| false | true | public void registrationStateChanged(RegistrationStateChangeEvent evt)
{
ProtocolProviderService protocolProvider = evt.getProvider();
AccountID accountID = protocolProvider.getAccountID();
logger.trace("Protocol provider: " + protocolProvider
+ " changed its state to: " + evt.getNewState().getStateName());
OperationSetPresence presence = mainFrame
.getProtocolPresenceOpSet(protocolProvider);
OperationSetMultiUserChat multiUserChat = mainFrame
.getMultiUserChatOpSet(protocolProvider);
if (evt.getNewState().equals(RegistrationState.REGISTERED))
{
if (presence != null)
{
presence.setAuthorizationHandler(new AuthorizationHandlerImpl(
mainFrame));
}
if(multiUserChat != null)
{
GuiActivator.getUIService().getConferenceChatManager()
.getChatRoomList().synchronizeOpSetWithLocalContactList(
protocolProvider, multiUserChat);
}
}
else if (evt.getNewState().equals(
RegistrationState.AUTHENTICATION_FAILED))
{
if (evt.getReasonCode() == RegistrationStateChangeEvent
.REASON_RECONNECTION_RATE_LIMIT_EXCEEDED)
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.RECONNECTION_LIMIT_EXCEEDED", new String[]
{ accountID.getUserID(), accountID.getService() });
new ErrorDialog(
null,
GuiActivator.getResources()
.getI18NString("service.gui.ERROR"),
msgText).showDialog();
}
else if (evt.getReasonCode() == RegistrationStateChangeEvent
.REASON_NON_EXISTING_USER_ID)
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.NON_EXISTING_USER_ID",
new String[]
{ protocolProvider.getProtocolDisplayName() });
new ErrorDialog(
null,
GuiActivator.getResources().getI18NString("service.gui.ERROR"),
msgText).showDialog();
}
logger.error(evt.getReason());
}
else if (evt.getNewState().equals(RegistrationState.CONNECTION_FAILED))
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.CONNECTION_FAILED_MSG",
new String[]
{ accountID.getUserID(),
accountID.getService() });
int result = new MessageDialog(
null,
GuiActivator.getResources().getI18NString("service.gui.ERROR"),
msgText,
GuiActivator.getResources().getI18NString("service.gui.RETRY"),
false).showDialog();
if (result == MessageDialog.OK_RETURN_CODE)
{
this.login(protocolProvider);
}
logger.error(evt.getReason());
}
else if (evt.getNewState().equals(RegistrationState.EXPIRED))
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.CONNECTION_EXPIRED_MSG",
new String[]
{ protocolProvider.getProtocolDisplayName() });
new ErrorDialog(null,
GuiActivator.getResources().getI18NString("service.gui.ERROR"),
msgText).showDialog();
logger.error(evt.getReason());
}
else if (evt.getNewState().equals(RegistrationState.UNREGISTERED))
{
if (!manuallyDisconnected)
{
if (evt.getReasonCode() == RegistrationStateChangeEvent
.REASON_MULTIPLE_LOGINS)
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.MULTIPLE_LOGINS",
new String[]
{ accountID.getUserID(), accountID.getService() });
new ErrorDialog(null,
GuiActivator.getResources()
.getI18NString("service.gui.ERROR"),
msgText).showDialog();
}
else if (evt.getReasonCode() == RegistrationStateChangeEvent
.REASON_CLIENT_LIMIT_REACHED_FOR_IP)
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.LIMIT_REACHED_FOR_IP", new String[]
{ protocolProvider.getProtocolDisplayName() });
new ErrorDialog(null,
GuiActivator.getResources()
.getI18NString("service.gui.ERROR"),
msgText).showDialog();
}
else if (evt.getReasonCode() == RegistrationStateChangeEvent
.REASON_USER_REQUEST)
{
// do nothing
}
else
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.UNREGISTERED_MESSAGE", new String[]
{ accountID.getUserID(), accountID.getService() });
new ErrorDialog(null,
GuiActivator.getResources()
.getI18NString("service.gui.ERROR"),
msgText).showDialog();
}
logger.error(evt.getReason());
}
}
}
| public void registrationStateChanged(RegistrationStateChangeEvent evt)
{
ProtocolProviderService protocolProvider = evt.getProvider();
AccountID accountID = protocolProvider.getAccountID();
logger.trace("Protocol provider: " + protocolProvider
+ " changed its state to: " + evt.getNewState().getStateName());
OperationSetPresence presence = mainFrame
.getProtocolPresenceOpSet(protocolProvider);
OperationSetMultiUserChat multiUserChat = mainFrame
.getMultiUserChatOpSet(protocolProvider);
if (evt.getNewState().equals(RegistrationState.REGISTERED))
{
if (presence != null)
{
presence.setAuthorizationHandler(new AuthorizationHandlerImpl(
mainFrame));
}
if(multiUserChat != null)
{
GuiActivator.getUIService().getConferenceChatManager()
.getChatRoomList().synchronizeOpSetWithLocalContactList(
protocolProvider, multiUserChat);
}
}
else if (evt.getNewState().equals(
RegistrationState.AUTHENTICATION_FAILED))
{
if (evt.getReasonCode() == RegistrationStateChangeEvent
.REASON_RECONNECTION_RATE_LIMIT_EXCEEDED)
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.RECONNECTION_LIMIT_EXCEEDED", new String[]
{ accountID.getUserID(), accountID.getService() });
new ErrorDialog(
null,
GuiActivator.getResources()
.getI18NString("service.gui.ERROR"),
msgText).showDialog();
}
else if (evt.getReasonCode() == RegistrationStateChangeEvent
.REASON_NON_EXISTING_USER_ID)
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.NON_EXISTING_USER_ID",
new String[]
{ protocolProvider.getProtocolDisplayName() });
new ErrorDialog(
null,
GuiActivator.getResources().getI18NString("service.gui.ERROR"),
msgText).showDialog();
}
logger.trace(evt.getReason());
}
else if (evt.getNewState().equals(RegistrationState.CONNECTION_FAILED))
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.CONNECTION_FAILED_MSG",
new String[]
{ accountID.getUserID(),
accountID.getService() });
int result = new MessageDialog(
null,
GuiActivator.getResources().getI18NString("service.gui.ERROR"),
msgText,
GuiActivator.getResources().getI18NString("service.gui.RETRY"),
false).showDialog();
if (result == MessageDialog.OK_RETURN_CODE)
{
this.login(protocolProvider);
}
logger.trace(evt.getReason());
}
else if (evt.getNewState().equals(RegistrationState.EXPIRED))
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.CONNECTION_EXPIRED_MSG",
new String[]
{ protocolProvider.getProtocolDisplayName() });
new ErrorDialog(null,
GuiActivator.getResources().getI18NString("service.gui.ERROR"),
msgText).showDialog();
logger.error(evt.getReason());
}
else if (evt.getNewState().equals(RegistrationState.UNREGISTERED))
{
if (!manuallyDisconnected)
{
if (evt.getReasonCode() == RegistrationStateChangeEvent
.REASON_MULTIPLE_LOGINS)
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.MULTIPLE_LOGINS",
new String[]
{ accountID.getUserID(), accountID.getService() });
new ErrorDialog(null,
GuiActivator.getResources()
.getI18NString("service.gui.ERROR"),
msgText).showDialog();
}
else if (evt.getReasonCode() == RegistrationStateChangeEvent
.REASON_CLIENT_LIMIT_REACHED_FOR_IP)
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.LIMIT_REACHED_FOR_IP", new String[]
{ protocolProvider.getProtocolDisplayName() });
new ErrorDialog(null,
GuiActivator.getResources()
.getI18NString("service.gui.ERROR"),
msgText).showDialog();
}
else if (evt.getReasonCode() == RegistrationStateChangeEvent
.REASON_USER_REQUEST)
{
// do nothing
}
else
{
String msgText = GuiActivator.getResources().getI18NString(
"service.gui.UNREGISTERED_MESSAGE", new String[]
{ accountID.getUserID(), accountID.getService() });
new ErrorDialog(null,
GuiActivator.getResources()
.getI18NString("service.gui.ERROR"),
msgText).showDialog();
}
logger.trace(evt.getReason());
}
}
}
|
diff --git a/src/com/cg/trashman/object/Car.java b/src/com/cg/trashman/object/Car.java
index 4bc8b38..ed02085 100644
--- a/src/com/cg/trashman/object/Car.java
+++ b/src/com/cg/trashman/object/Car.java
@@ -1,249 +1,249 @@
package com.cg.trashman.object;
import static javax.media.opengl.GL2.GL_QUADS;
import java.awt.event.KeyEvent;
import javax.media.opengl.GL2;
import com.cg.trashman.ISimpleObject;
import com.jogamp.opengl.util.texture.Texture;
import com.jogamp.opengl.util.texture.TextureCoords;
public class Car implements ISimpleObject {
private float pX;
private float pZ;
private float desX;
private float desZ;
private float pSpeed = 0.1f;
private float pDefaultSpeed = 0.1f;
private Direction direction;
private boolean[][] mazeGrid;
private int gridX;
private int gridZ;
private Texture[] textures;
private float textureTop;
private float textureBottom;
private float textureLeft;
private float textureRight;
enum Direction {
Stop, Up, Down, Left, Right
}
private static final float size = 3f;
public Car(boolean[][] mazeGrid, Texture[] textures) {
pX = 0f;
pZ = 0f;
desX = pX;
desZ = pZ;
direction = Direction.Stop;
this.mazeGrid = mazeGrid;
gridX = 0;
gridZ = 0;
this.textures = textures;
TextureCoords textureCoords = textures[0].getImageTexCoords();
textureTop = textureCoords.top();
textureBottom = textureCoords.bottom();
textureLeft = textureCoords.left();
textureRight = textureCoords.right();
}
public void updateMazePosition(int row, int col) {
desX = row * 2f;
desZ = col * 2f;
}
public void addMazePositionX(int dX) {
// out of range
if (gridX + dX >= mazeGrid.length || gridX + dX < 0) {
direction = Direction.Stop;
return;
}
if (mazeGrid[gridX + dX][gridZ]) {
direction = Direction.Stop;
} else {
gridX += dX;
desX += dX * 2f;
}
}
public void addMazePositionZ(int dZ) {
// out of range
if (gridZ + dZ >= mazeGrid[0].length || gridZ + dZ < 0) {
direction = Direction.Stop;
return;
}
if (mazeGrid[gridX][gridZ + dZ]) {
direction = Direction.Stop;
} else {
gridZ += dZ;
desZ += dZ * 2f;
}
}
@Override
public void update(GL2 gl, Object arg) {
render(gl);
if (isStable()) {
pSpeed = 0;
// next move
if (direction == Direction.Left) {
addMazePositionX(-1);
} else if (direction == Direction.Right) {
addMazePositionX(1);
} else if (direction == Direction.Up) {
addMazePositionZ(1);
} else if (direction == Direction.Down) {
addMazePositionZ(-1);
}
return;
}
this.pX += Math.signum(desX - pX) * pSpeed;
if (Math.abs((this.pX - this.desX) * 1000f) / 1000f < pSpeed) {
this.pX = this.desX;
}
this.pZ += Math.signum(desZ - pZ) * pSpeed;
if (Math.abs((this.pZ - this.desZ) * 1000f) / 1000f < pSpeed) {
this.pZ = this.desZ;
}
pSpeed = pDefaultSpeed;
}
public float getX() {
return pX;
}
public float getZ() {
return pZ;
}
private void render(GL2 gl) {
// ----- Render the Color Cube -----
gl.glLoadIdentity(); // reset the current model-view matrix
// gl.glTranslatef(pX, 0, 0); // translate right and into the
// screen
gl.glTranslatef(0, 0, -pZ);
gl.glTranslatef(pX, 0, 0);
if (direction == Direction.Up)
gl.glRotatef(90f, 0f, 1f, 0f);
else if (direction == Direction.Down)
gl.glRotatef(-90f, 0f, 1f, 0f);
else if (direction == Direction.Left)
- gl.glRotatef(90f, 1f, 0f, 0f);
+ gl.glRotatef(0f, 0f, 1f, 0f);
else if (direction == Direction.Right)
- gl.glRotated(-90, 1f, 0f, 0f);
+ gl.glRotated(180, 0f, 1f, 0f);
// side car (for front face)
textures[11].enable(gl);
textures[11].bind(gl);
gl.glBegin(GL_QUADS);
// Front Face
gl.glTexCoord2f(textureLeft, textureBottom);
gl.glVertex3f(-size, -0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureRight, textureBottom);
gl.glVertex3f(size, -0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureRight, textureTop);
gl.glVertex3f(size, 0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureLeft, textureTop);
gl.glVertex3f(-size, 0.5f * size, 0.5f * size);
gl.glEnd();
// side car (inverse front face)
textures[11].enable(gl);
textures[11].bind(gl);
gl.glBegin(GL_QUADS);
// Back Face
gl.glTexCoord2f(textureRight, textureBottom);
gl.glVertex3f(-size, -0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureRight, textureTop);
gl.glVertex3f(-size, 0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureLeft, textureTop);
gl.glVertex3f(size, 0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureLeft, textureBottom);
gl.glVertex3f(size, -0.5f * size, -0.5f * size);
gl.glEnd();
// back car (for Top face)
textures[13].enable(gl);
textures[13].bind(gl);
gl.glBegin(GL_QUADS);
// Top Face
gl.glTexCoord2f(textureLeft, textureTop);
gl.glVertex3f(-size, 0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureLeft, textureBottom);
gl.glVertex3f(-size, 0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureRight, textureBottom);
gl.glVertex3f(size, 0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureRight, textureTop);
gl.glVertex3f(size, 0.5f * size, -0.5f * size);
gl.glEnd();
// go back to building (0,4)
textures[11].enable(gl);
textures[11].bind(gl);
gl.glBegin(GL_QUADS);
// Bottom Face
gl.glTexCoord2f(textureRight, textureTop);
gl.glVertex3f(-size, -0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureLeft, textureTop);
gl.glVertex3f(size, -0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureLeft, textureBottom);
gl.glVertex3f(size, -0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureRight, textureBottom);
gl.glVertex3f(-size, -0.5f * size, 0.5f * size);
// Right face
gl.glTexCoord2f(textureRight, textureBottom);
gl.glVertex3f(size, -0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureRight, textureTop);
gl.glVertex3f(size, 0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureLeft, textureTop);
gl.glVertex3f(size, 0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureLeft, textureBottom);
gl.glVertex3f(size, -0.5f * size, 0.5f * size);
// Left Face
gl.glTexCoord2f(textureLeft, textureBottom);
gl.glVertex3f(-size, -0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureRight, textureBottom);
gl.glVertex3f(-size, -0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureRight, textureTop);
gl.glVertex3f(-size, 0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureLeft, textureTop);
gl.glVertex3f(-size, 0.5f * size, -0.5f * size);
gl.glEnd();
}
public boolean isStable() {
return pX == desX && pZ == desZ;
}
public void keyPressed(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.VK_I) {
direction = Direction.Up;
}
if (event.getKeyCode() == KeyEvent.VK_K) {
direction = Direction.Down;
}
if (event.getKeyCode() == KeyEvent.VK_J) {
direction = Direction.Left;
}
if (event.getKeyCode() == KeyEvent.VK_L) {
direction = Direction.Right;
}
}
public void keyReleased(KeyEvent event) {
}
public void keyTyped(KeyEvent event) {
}
}
| false | true | private void render(GL2 gl) {
// ----- Render the Color Cube -----
gl.glLoadIdentity(); // reset the current model-view matrix
// gl.glTranslatef(pX, 0, 0); // translate right and into the
// screen
gl.glTranslatef(0, 0, -pZ);
gl.glTranslatef(pX, 0, 0);
if (direction == Direction.Up)
gl.glRotatef(90f, 0f, 1f, 0f);
else if (direction == Direction.Down)
gl.glRotatef(-90f, 0f, 1f, 0f);
else if (direction == Direction.Left)
gl.glRotatef(90f, 1f, 0f, 0f);
else if (direction == Direction.Right)
gl.glRotated(-90, 1f, 0f, 0f);
// side car (for front face)
textures[11].enable(gl);
textures[11].bind(gl);
gl.glBegin(GL_QUADS);
// Front Face
gl.glTexCoord2f(textureLeft, textureBottom);
gl.glVertex3f(-size, -0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureRight, textureBottom);
gl.glVertex3f(size, -0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureRight, textureTop);
gl.glVertex3f(size, 0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureLeft, textureTop);
gl.glVertex3f(-size, 0.5f * size, 0.5f * size);
gl.glEnd();
// side car (inverse front face)
textures[11].enable(gl);
textures[11].bind(gl);
gl.glBegin(GL_QUADS);
// Back Face
gl.glTexCoord2f(textureRight, textureBottom);
gl.glVertex3f(-size, -0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureRight, textureTop);
gl.glVertex3f(-size, 0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureLeft, textureTop);
gl.glVertex3f(size, 0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureLeft, textureBottom);
gl.glVertex3f(size, -0.5f * size, -0.5f * size);
gl.glEnd();
// back car (for Top face)
textures[13].enable(gl);
textures[13].bind(gl);
gl.glBegin(GL_QUADS);
// Top Face
gl.glTexCoord2f(textureLeft, textureTop);
gl.glVertex3f(-size, 0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureLeft, textureBottom);
gl.glVertex3f(-size, 0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureRight, textureBottom);
gl.glVertex3f(size, 0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureRight, textureTop);
gl.glVertex3f(size, 0.5f * size, -0.5f * size);
gl.glEnd();
// go back to building (0,4)
textures[11].enable(gl);
textures[11].bind(gl);
gl.glBegin(GL_QUADS);
// Bottom Face
gl.glTexCoord2f(textureRight, textureTop);
gl.glVertex3f(-size, -0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureLeft, textureTop);
gl.glVertex3f(size, -0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureLeft, textureBottom);
gl.glVertex3f(size, -0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureRight, textureBottom);
gl.glVertex3f(-size, -0.5f * size, 0.5f * size);
// Right face
gl.glTexCoord2f(textureRight, textureBottom);
gl.glVertex3f(size, -0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureRight, textureTop);
gl.glVertex3f(size, 0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureLeft, textureTop);
gl.glVertex3f(size, 0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureLeft, textureBottom);
gl.glVertex3f(size, -0.5f * size, 0.5f * size);
// Left Face
gl.glTexCoord2f(textureLeft, textureBottom);
gl.glVertex3f(-size, -0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureRight, textureBottom);
gl.glVertex3f(-size, -0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureRight, textureTop);
gl.glVertex3f(-size, 0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureLeft, textureTop);
gl.glVertex3f(-size, 0.5f * size, -0.5f * size);
gl.glEnd();
}
| private void render(GL2 gl) {
// ----- Render the Color Cube -----
gl.glLoadIdentity(); // reset the current model-view matrix
// gl.glTranslatef(pX, 0, 0); // translate right and into the
// screen
gl.glTranslatef(0, 0, -pZ);
gl.glTranslatef(pX, 0, 0);
if (direction == Direction.Up)
gl.glRotatef(90f, 0f, 1f, 0f);
else if (direction == Direction.Down)
gl.glRotatef(-90f, 0f, 1f, 0f);
else if (direction == Direction.Left)
gl.glRotatef(0f, 0f, 1f, 0f);
else if (direction == Direction.Right)
gl.glRotated(180, 0f, 1f, 0f);
// side car (for front face)
textures[11].enable(gl);
textures[11].bind(gl);
gl.glBegin(GL_QUADS);
// Front Face
gl.glTexCoord2f(textureLeft, textureBottom);
gl.glVertex3f(-size, -0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureRight, textureBottom);
gl.glVertex3f(size, -0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureRight, textureTop);
gl.glVertex3f(size, 0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureLeft, textureTop);
gl.glVertex3f(-size, 0.5f * size, 0.5f * size);
gl.glEnd();
// side car (inverse front face)
textures[11].enable(gl);
textures[11].bind(gl);
gl.glBegin(GL_QUADS);
// Back Face
gl.glTexCoord2f(textureRight, textureBottom);
gl.glVertex3f(-size, -0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureRight, textureTop);
gl.glVertex3f(-size, 0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureLeft, textureTop);
gl.glVertex3f(size, 0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureLeft, textureBottom);
gl.glVertex3f(size, -0.5f * size, -0.5f * size);
gl.glEnd();
// back car (for Top face)
textures[13].enable(gl);
textures[13].bind(gl);
gl.glBegin(GL_QUADS);
// Top Face
gl.glTexCoord2f(textureLeft, textureTop);
gl.glVertex3f(-size, 0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureLeft, textureBottom);
gl.glVertex3f(-size, 0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureRight, textureBottom);
gl.glVertex3f(size, 0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureRight, textureTop);
gl.glVertex3f(size, 0.5f * size, -0.5f * size);
gl.glEnd();
// go back to building (0,4)
textures[11].enable(gl);
textures[11].bind(gl);
gl.glBegin(GL_QUADS);
// Bottom Face
gl.glTexCoord2f(textureRight, textureTop);
gl.glVertex3f(-size, -0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureLeft, textureTop);
gl.glVertex3f(size, -0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureLeft, textureBottom);
gl.glVertex3f(size, -0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureRight, textureBottom);
gl.glVertex3f(-size, -0.5f * size, 0.5f * size);
// Right face
gl.glTexCoord2f(textureRight, textureBottom);
gl.glVertex3f(size, -0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureRight, textureTop);
gl.glVertex3f(size, 0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureLeft, textureTop);
gl.glVertex3f(size, 0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureLeft, textureBottom);
gl.glVertex3f(size, -0.5f * size, 0.5f * size);
// Left Face
gl.glTexCoord2f(textureLeft, textureBottom);
gl.glVertex3f(-size, -0.5f * size, -0.5f * size);
gl.glTexCoord2f(textureRight, textureBottom);
gl.glVertex3f(-size, -0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureRight, textureTop);
gl.glVertex3f(-size, 0.5f * size, 0.5f * size);
gl.glTexCoord2f(textureLeft, textureTop);
gl.glVertex3f(-size, 0.5f * size, -0.5f * size);
gl.glEnd();
}
|
diff --git a/Arena/src/game/Actor.java b/Arena/src/game/Actor.java
index 82f497e..363057b 100644
--- a/Arena/src/game/Actor.java
+++ b/Arena/src/game/Actor.java
@@ -1,331 +1,331 @@
package game;
/**
* Class for the player's characters
*
* @author Jacob Charles
*
*/
public class Actor extends GameObject {
private static final int CROUCH = 1;
private static final int LEAN = 2;
private static final int SLIDE = 4;
private static final int USE = 8;
private static final int GRAB = 16;
private static final int PIPE = 32;
private static final int MAX = 64-1;
//current data
private int id; //used in place of references
private int at = 1; //air time
private int dt; //dead time
private int r; //reload
private int dir = 1; //direction
private int cr = 0; //crouch and other unique stuff
private int p = 0; //power up
private int pv = 0; //power up variable (extra data)
private int lid = -1, lm = -1; //id and map id of the current land
private int s = 0; //score
private int l; //lives
private int m; //selected RoleModel from the Warehouse
/**
* Spawn a player with a given archetype and location
*
* @param x
* start x
* @param y
* start y
* @param character
* which player the character is using
*/
public Actor (int x, int y, int character) {
super(x, y);
//bind to their RoleModel
setModel(character);
//initialize some basic values
dt = getSpawnTime();
}
/**
* @return true if the actor is under spawn armor
*/
public boolean isArmored() {
if (getPowerup() == Item.HYPER) return true; //hypermode armor
return (!isDead() && dt < getSpawnTime()+getSpawnInv());
}
@Override
public int getSkin() {
if (p == Item.CHANGE) {
return Warehouse.getCharacters()[pv].getSkin();
}
else return super.getSkin();
}
/*getters and setters for attributes*/
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAirTime() {
return at;
}
public void setAirTime(int airTime) {
this.at = airTime;
}
public int getDeadTime() {
return dt;
}
public void setDeadTime(int deadTime) {
this.dt = deadTime;
}
public int getReload() {
return r;
}
public void setReload(int reload) {
this.r = reload;
}
public int getDir() {
return dir;
}
public void setDir(int dir) {
this.dir = dir;
}
public boolean isCrouch() {
return (cr&CROUCH) != 0;
}
public void setCrouch(boolean b) {
if (b) cr |= CROUCH;
else cr &= MAX-CROUCH;
}
public boolean isLean() {
return (cr&LEAN) != 0;
}
public void setLean(boolean b) {
if (b) cr |= LEAN;
else cr &= MAX-LEAN;
}
public boolean isSlide() {
return (cr&SLIDE) != 0;
}
public void setSlide(boolean b) {
if (b) cr |= SLIDE;
else cr &= MAX-SLIDE;
}
public boolean isUse() {
return (cr&USE) != 0;
}
public void setUse(boolean b) {
if (b) cr |= USE;
else cr &= MAX-USE;
}
public boolean isGrab() {
return (cr&GRAB) != 0;
}
public void setGrab(boolean b) {
if (b) cr |= GRAB;
else cr &= MAX-GRAB;
}
public boolean isPipe() {
return (cr&PIPE) != 0;
}
public void setPipe(boolean b) {
if (b) cr |= PIPE;
else cr &= MAX-PIPE;
}
public int getPowerup() {
return p;
}
public void setPowerup(int powerup) {
//grab a 1up (doesn't replace other powerups)
if (powerup == Item.LIFE) {
powerup = 0;
gainLife();
return;
}
//exit big mode (reset size)
if (this.p == Item.BIG && powerup != Item.BIG) {
float cx = getHCenter(), cy = getVCenter();
setW(Warehouse.getCharacters()[m].getW());
setH(Warehouse.getCharacters()[m].getH());
setCenter(cx, cy);
setOnLand(null); //off the ground
setAirTime(1);
}
//exit mini mode (reset size)
if (this.p == Item.MINI && powerup != Item.MINI) {
- setY(getY()-getH());
+ setY(getY()-getH()-2);
setX(getX()-getW());
setW(Warehouse.getCharacters()[m].getW());
setH(Warehouse.getCharacters()[m].getH());
setOnLand(null); //off the ground
setAirTime(1);
}
//enter big mode (get huge)
if (this.p != Item.BIG && powerup == Item.BIG) {
- setY(getY()-getH());
+ setY(getY()-getH()-2);
setX(getX()-getW()/2);
setW(getW()*2);
setH(getH()*2);
}
//enter mini mode (get tiny)
if (this.p != Item.MINI && powerup == Item.MINI) {
float cx = getHCenter(), cy = getVCenter();
setW(getW()/2);
setH(getH()/2);
setCenter(cx, cy);
setOnLand(null); //off the ground
setAirTime(1);
}
//don't morph into yourself
if (powerup == Item.CHANGE && pv == m) {
pv++;
}
this.p = powerup;
}
public int getPowerupVar() {
return pv;
}
public void setPowerupVar(int powerupVar) {
//don't morph into yourself
if (p == Item.CHANGE && powerupVar == m) {
powerupVar++;
}
this.pv = powerupVar;
}
public Land getOnLand() {
if (lm == -1 || lid == -1) {
return null;
}
return Warehouse.getMaps()[lm].getPieces().get(lid);
}
public void setOnLand(Land onLand) {
if (onLand == null) {
lm = -1;
lid = -1;
}
else {
lm = onLand.getMap();
lid = onLand.getId();
}
}
public int getScore() {
return s;
}
public void setScore(int score) {
this.s = score;
}
public void gainPoint() {
this.s++;
}
public void losePoint() {
this.s--;
}
public int getLives() {
return l;
}
public void setLives(int lives) {
this.l = lives;
}
public void loseLife() {
this.l--;
}
public void gainLife() {
this.l++;
}
/*getters to the RoleModel's properties*/
public float getRunSpeed() {
if (getOnLand() != null && getOnLand().isSlip()) { //slippery floor
return getRoleModel().getRunSpeed()/5;
}
return getRoleModel().getRunSpeed();
}
public float getAirSpeed() {
return getRoleModel().getAirSpeed();
}
public float getRunSlip() {
if (getOnLand() != null && getOnLand().isSlip()) { //slippery floor
return 1-getRoleModel().getRunFrict()/5;
}
return getRoleModel().getRunSlip();
}
public float getRunFrict() {
if (getOnLand() != null && getOnLand().isSlip()) { //slippery floor
return getRoleModel().getRunFrict()/5;
}
return getRoleModel().getRunFrict();
}
public float getAirSlip() {
return getRoleModel().getAirSlip();
}
public float getAirFrict() {
return getRoleModel().getAirFrict();
}
public float getMaxSpeed() {
return getRoleModel().getMaxSpeed();
}
public float getJumpPower() {
return getRoleModel().getJumpPower();
}
public int getJumpHold() {
return getRoleModel().getJumpHold();
}
public float getTermVel() {
if (isCrouch()) return getRoleModel().getTermVel()*getSink();
return getRoleModel().getTermVel();
}
public float getWallTermVel() {
return getRoleModel().getWallTermVel();
}
public float getGrav() {
if (isCrouch()) return getRoleModel().getGrav()*getSink();
return getRoleModel().getGrav();
}
public float getSink() {
return getRoleModel().getSink();
}
public int getSpawnTime() {
return getRoleModel().getSpawnTime();
}
public int getSpawnInv() {
return getRoleModel().getSpawnInv();
}
public int getShotDelay() {
return getRoleModel().getShotDelay();
}
public ShotModel getShot() {
return getRoleModel().getShotType();
}
//getter and setter for basic player type
public int getModel() {
return m;
}
//also sets derived fields
public void setModel(int model) {
this.m = model;
RoleModel rm = Warehouse.getCharacters()[model];
setSkin(rm.getSkin());
setW(rm.getW());
setH(rm.getH());
}
/**
* Get the RoleModel object referenced by m (model).
* @return the actual RoleModel from the warehouse
*/
private RoleModel getRoleModel() {
//Change powerup intercepts your model
if (p == Item.CHANGE) {
return Warehouse.getCharacters()[pv];
}
return Warehouse.getCharacters()[m];
}
}
| false | true | public void setPowerup(int powerup) {
//grab a 1up (doesn't replace other powerups)
if (powerup == Item.LIFE) {
powerup = 0;
gainLife();
return;
}
//exit big mode (reset size)
if (this.p == Item.BIG && powerup != Item.BIG) {
float cx = getHCenter(), cy = getVCenter();
setW(Warehouse.getCharacters()[m].getW());
setH(Warehouse.getCharacters()[m].getH());
setCenter(cx, cy);
setOnLand(null); //off the ground
setAirTime(1);
}
//exit mini mode (reset size)
if (this.p == Item.MINI && powerup != Item.MINI) {
setY(getY()-getH());
setX(getX()-getW());
setW(Warehouse.getCharacters()[m].getW());
setH(Warehouse.getCharacters()[m].getH());
setOnLand(null); //off the ground
setAirTime(1);
}
//enter big mode (get huge)
if (this.p != Item.BIG && powerup == Item.BIG) {
setY(getY()-getH());
setX(getX()-getW()/2);
setW(getW()*2);
setH(getH()*2);
}
//enter mini mode (get tiny)
if (this.p != Item.MINI && powerup == Item.MINI) {
float cx = getHCenter(), cy = getVCenter();
setW(getW()/2);
setH(getH()/2);
setCenter(cx, cy);
setOnLand(null); //off the ground
setAirTime(1);
}
//don't morph into yourself
if (powerup == Item.CHANGE && pv == m) {
pv++;
}
this.p = powerup;
}
| public void setPowerup(int powerup) {
//grab a 1up (doesn't replace other powerups)
if (powerup == Item.LIFE) {
powerup = 0;
gainLife();
return;
}
//exit big mode (reset size)
if (this.p == Item.BIG && powerup != Item.BIG) {
float cx = getHCenter(), cy = getVCenter();
setW(Warehouse.getCharacters()[m].getW());
setH(Warehouse.getCharacters()[m].getH());
setCenter(cx, cy);
setOnLand(null); //off the ground
setAirTime(1);
}
//exit mini mode (reset size)
if (this.p == Item.MINI && powerup != Item.MINI) {
setY(getY()-getH()-2);
setX(getX()-getW());
setW(Warehouse.getCharacters()[m].getW());
setH(Warehouse.getCharacters()[m].getH());
setOnLand(null); //off the ground
setAirTime(1);
}
//enter big mode (get huge)
if (this.p != Item.BIG && powerup == Item.BIG) {
setY(getY()-getH()-2);
setX(getX()-getW()/2);
setW(getW()*2);
setH(getH()*2);
}
//enter mini mode (get tiny)
if (this.p != Item.MINI && powerup == Item.MINI) {
float cx = getHCenter(), cy = getVCenter();
setW(getW()/2);
setH(getH()/2);
setCenter(cx, cy);
setOnLand(null); //off the ground
setAirTime(1);
}
//don't morph into yourself
if (powerup == Item.CHANGE && pv == m) {
pv++;
}
this.p = powerup;
}
|
diff --git a/src/main/java/org/elasticsearch/index/query/FilteredQueryParser.java b/src/main/java/org/elasticsearch/index/query/FilteredQueryParser.java
index ff42a0e708c..dbfe928b591 100644
--- a/src/main/java/org/elasticsearch/index/query/FilteredQueryParser.java
+++ b/src/main/java/org/elasticsearch/index/query/FilteredQueryParser.java
@@ -1,153 +1,153 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.index.query;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.FilteredQuery;
import org.apache.lucene.search.Query;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.lucene.search.Queries;
import org.elasticsearch.common.lucene.search.XConstantScoreQuery;
import org.elasticsearch.common.lucene.search.XFilteredQuery;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.cache.filter.support.CacheKeyFilter;
import java.io.IOException;
/**
*
*/
public class FilteredQueryParser implements QueryParser {
public static final String NAME = "filtered";
@Inject
public FilteredQueryParser() {
}
@Override
public String[] names() {
return new String[]{NAME};
}
@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
XContentParser parser = parseContext.parser();
Query query = Queries.newMatchAllQuery();
Filter filter = null;
boolean filterFound = false;
float boost = 1.0f;
boolean cache = false;
CacheKeyFilter.Key cacheKey = null;
String queryName = null;
String currentFieldName = null;
XContentParser.Token token;
FilteredQuery.FilterStrategy filterStrategy = XFilteredQuery.CUSTOM_FILTER_STRATEGY;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if ("query".equals(currentFieldName)) {
query = parseContext.parseInnerQuery();
} else if ("filter".equals(currentFieldName)) {
filterFound = true;
filter = parseContext.parseInnerFilter();
} else {
throw new QueryParsingException(parseContext.index(), "[filtered] query does not support [" + currentFieldName + "]");
}
} else if (token.isValue()) {
if ("strategy".equals(currentFieldName)) {
String value = parser.text();
if ("query_first".equals(value) || "queryFirst".equals(value)) {
filterStrategy = FilteredQuery.QUERY_FIRST_FILTER_STRATEGY;
} else if ("random_access_always".equals(value) || "randomAccessAlways".equals(value)) {
filterStrategy = XFilteredQuery.ALWAYS_RANDOM_ACCESS_FILTER_STRATEGY;
} else if ("leap_frog".equals(value) || "leapFrog".equals(value)) {
filterStrategy = FilteredQuery.LEAP_FROG_QUERY_FIRST_STRATEGY;
} else if (value.startsWith("random_access_")) {
int threshold = Integer.parseInt(value.substring("random_access_".length()));
filterStrategy = new XFilteredQuery.CustomRandomAccessFilterStrategy(threshold);
} else if (value.startsWith("randomAccess")) {
int threshold = Integer.parseInt(value.substring("randomAccess".length()));
filterStrategy = new XFilteredQuery.CustomRandomAccessFilterStrategy(threshold);
} else if ("leap_frog_query_first".equals(value) || "leapFrogQueryFirst".equals(value)) {
filterStrategy = FilteredQuery.LEAP_FROG_QUERY_FIRST_STRATEGY;
} else if ("leap_frog_filter_first".equals(value) || "leapFrogFilterFirst".equals(value)) {
filterStrategy = FilteredQuery.LEAP_FROG_FILTER_FIRST_STRATEGY;
- } else if ("_name".equals(currentFieldName)) {
- queryName = parser.text();
} else {
throw new QueryParsingException(parseContext.index(), "[filtered] strategy value not supported [" + value + "]");
}
+ } else if ("_name".equals(currentFieldName)) {
+ queryName = parser.text();
} else if ("boost".equals(currentFieldName)) {
boost = parser.floatValue();
} else if ("_cache".equals(currentFieldName)) {
cache = parser.booleanValue();
} else if ("_cache_key".equals(currentFieldName) || "_cacheKey".equals(currentFieldName)) {
cacheKey = new CacheKeyFilter.Key(parser.text());
} else {
throw new QueryParsingException(parseContext.index(), "[filtered] query does not support [" + currentFieldName + "]");
}
}
}
// parsed internally, but returned null during parsing...
if (query == null) {
return null;
}
if (filter == null) {
if (!filterFound) {
// we allow for null filter, so it makes compositions on the client side to be simpler
return query;
} else {
// even if the filter is not found, and its null, we should simply ignore it, and go
// by the query
return query;
}
}
if (filter == Queries.MATCH_ALL_FILTER) {
// this is an instance of match all filter, just execute the query
return query;
}
// cache if required
if (cache) {
filter = parseContext.cacheFilter(filter, cacheKey);
}
// if its a match_all query, use constant_score
if (Queries.isConstantMatchAllQuery(query)) {
Query q = new XConstantScoreQuery(filter);
q.setBoost(boost);
return q;
}
XFilteredQuery filteredQuery = new XFilteredQuery(query, filter, filterStrategy);
filteredQuery.setBoost(boost);
if (queryName != null) {
parseContext.addNamedQuery(queryName, filteredQuery);
}
return filteredQuery;
}
}
| false | true | public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
XContentParser parser = parseContext.parser();
Query query = Queries.newMatchAllQuery();
Filter filter = null;
boolean filterFound = false;
float boost = 1.0f;
boolean cache = false;
CacheKeyFilter.Key cacheKey = null;
String queryName = null;
String currentFieldName = null;
XContentParser.Token token;
FilteredQuery.FilterStrategy filterStrategy = XFilteredQuery.CUSTOM_FILTER_STRATEGY;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if ("query".equals(currentFieldName)) {
query = parseContext.parseInnerQuery();
} else if ("filter".equals(currentFieldName)) {
filterFound = true;
filter = parseContext.parseInnerFilter();
} else {
throw new QueryParsingException(parseContext.index(), "[filtered] query does not support [" + currentFieldName + "]");
}
} else if (token.isValue()) {
if ("strategy".equals(currentFieldName)) {
String value = parser.text();
if ("query_first".equals(value) || "queryFirst".equals(value)) {
filterStrategy = FilteredQuery.QUERY_FIRST_FILTER_STRATEGY;
} else if ("random_access_always".equals(value) || "randomAccessAlways".equals(value)) {
filterStrategy = XFilteredQuery.ALWAYS_RANDOM_ACCESS_FILTER_STRATEGY;
} else if ("leap_frog".equals(value) || "leapFrog".equals(value)) {
filterStrategy = FilteredQuery.LEAP_FROG_QUERY_FIRST_STRATEGY;
} else if (value.startsWith("random_access_")) {
int threshold = Integer.parseInt(value.substring("random_access_".length()));
filterStrategy = new XFilteredQuery.CustomRandomAccessFilterStrategy(threshold);
} else if (value.startsWith("randomAccess")) {
int threshold = Integer.parseInt(value.substring("randomAccess".length()));
filterStrategy = new XFilteredQuery.CustomRandomAccessFilterStrategy(threshold);
} else if ("leap_frog_query_first".equals(value) || "leapFrogQueryFirst".equals(value)) {
filterStrategy = FilteredQuery.LEAP_FROG_QUERY_FIRST_STRATEGY;
} else if ("leap_frog_filter_first".equals(value) || "leapFrogFilterFirst".equals(value)) {
filterStrategy = FilteredQuery.LEAP_FROG_FILTER_FIRST_STRATEGY;
} else if ("_name".equals(currentFieldName)) {
queryName = parser.text();
} else {
throw new QueryParsingException(parseContext.index(), "[filtered] strategy value not supported [" + value + "]");
}
} else if ("boost".equals(currentFieldName)) {
boost = parser.floatValue();
} else if ("_cache".equals(currentFieldName)) {
cache = parser.booleanValue();
} else if ("_cache_key".equals(currentFieldName) || "_cacheKey".equals(currentFieldName)) {
cacheKey = new CacheKeyFilter.Key(parser.text());
} else {
throw new QueryParsingException(parseContext.index(), "[filtered] query does not support [" + currentFieldName + "]");
}
}
}
// parsed internally, but returned null during parsing...
if (query == null) {
return null;
}
if (filter == null) {
if (!filterFound) {
// we allow for null filter, so it makes compositions on the client side to be simpler
return query;
} else {
// even if the filter is not found, and its null, we should simply ignore it, and go
// by the query
return query;
}
}
if (filter == Queries.MATCH_ALL_FILTER) {
// this is an instance of match all filter, just execute the query
return query;
}
// cache if required
if (cache) {
filter = parseContext.cacheFilter(filter, cacheKey);
}
// if its a match_all query, use constant_score
if (Queries.isConstantMatchAllQuery(query)) {
Query q = new XConstantScoreQuery(filter);
q.setBoost(boost);
return q;
}
XFilteredQuery filteredQuery = new XFilteredQuery(query, filter, filterStrategy);
filteredQuery.setBoost(boost);
if (queryName != null) {
parseContext.addNamedQuery(queryName, filteredQuery);
}
return filteredQuery;
}
| public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
XContentParser parser = parseContext.parser();
Query query = Queries.newMatchAllQuery();
Filter filter = null;
boolean filterFound = false;
float boost = 1.0f;
boolean cache = false;
CacheKeyFilter.Key cacheKey = null;
String queryName = null;
String currentFieldName = null;
XContentParser.Token token;
FilteredQuery.FilterStrategy filterStrategy = XFilteredQuery.CUSTOM_FILTER_STRATEGY;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if ("query".equals(currentFieldName)) {
query = parseContext.parseInnerQuery();
} else if ("filter".equals(currentFieldName)) {
filterFound = true;
filter = parseContext.parseInnerFilter();
} else {
throw new QueryParsingException(parseContext.index(), "[filtered] query does not support [" + currentFieldName + "]");
}
} else if (token.isValue()) {
if ("strategy".equals(currentFieldName)) {
String value = parser.text();
if ("query_first".equals(value) || "queryFirst".equals(value)) {
filterStrategy = FilteredQuery.QUERY_FIRST_FILTER_STRATEGY;
} else if ("random_access_always".equals(value) || "randomAccessAlways".equals(value)) {
filterStrategy = XFilteredQuery.ALWAYS_RANDOM_ACCESS_FILTER_STRATEGY;
} else if ("leap_frog".equals(value) || "leapFrog".equals(value)) {
filterStrategy = FilteredQuery.LEAP_FROG_QUERY_FIRST_STRATEGY;
} else if (value.startsWith("random_access_")) {
int threshold = Integer.parseInt(value.substring("random_access_".length()));
filterStrategy = new XFilteredQuery.CustomRandomAccessFilterStrategy(threshold);
} else if (value.startsWith("randomAccess")) {
int threshold = Integer.parseInt(value.substring("randomAccess".length()));
filterStrategy = new XFilteredQuery.CustomRandomAccessFilterStrategy(threshold);
} else if ("leap_frog_query_first".equals(value) || "leapFrogQueryFirst".equals(value)) {
filterStrategy = FilteredQuery.LEAP_FROG_QUERY_FIRST_STRATEGY;
} else if ("leap_frog_filter_first".equals(value) || "leapFrogFilterFirst".equals(value)) {
filterStrategy = FilteredQuery.LEAP_FROG_FILTER_FIRST_STRATEGY;
} else {
throw new QueryParsingException(parseContext.index(), "[filtered] strategy value not supported [" + value + "]");
}
} else if ("_name".equals(currentFieldName)) {
queryName = parser.text();
} else if ("boost".equals(currentFieldName)) {
boost = parser.floatValue();
} else if ("_cache".equals(currentFieldName)) {
cache = parser.booleanValue();
} else if ("_cache_key".equals(currentFieldName) || "_cacheKey".equals(currentFieldName)) {
cacheKey = new CacheKeyFilter.Key(parser.text());
} else {
throw new QueryParsingException(parseContext.index(), "[filtered] query does not support [" + currentFieldName + "]");
}
}
}
// parsed internally, but returned null during parsing...
if (query == null) {
return null;
}
if (filter == null) {
if (!filterFound) {
// we allow for null filter, so it makes compositions on the client side to be simpler
return query;
} else {
// even if the filter is not found, and its null, we should simply ignore it, and go
// by the query
return query;
}
}
if (filter == Queries.MATCH_ALL_FILTER) {
// this is an instance of match all filter, just execute the query
return query;
}
// cache if required
if (cache) {
filter = parseContext.cacheFilter(filter, cacheKey);
}
// if its a match_all query, use constant_score
if (Queries.isConstantMatchAllQuery(query)) {
Query q = new XConstantScoreQuery(filter);
q.setBoost(boost);
return q;
}
XFilteredQuery filteredQuery = new XFilteredQuery(query, filter, filterStrategy);
filteredQuery.setBoost(boost);
if (queryName != null) {
parseContext.addNamedQuery(queryName, filteredQuery);
}
return filteredQuery;
}
|
diff --git a/src/main/java/fi/csc/microarray/MicroarrayMain.java b/src/main/java/fi/csc/microarray/MicroarrayMain.java
index af51f0192..19e61dc5c 100644
--- a/src/main/java/fi/csc/microarray/MicroarrayMain.java
+++ b/src/main/java/fi/csc/microarray/MicroarrayMain.java
@@ -1,178 +1,178 @@
package fi.csc.microarray;
import java.io.FileInputStream;
import fi.csc.microarray.analyser.AnalyserServer;
import fi.csc.microarray.analyser.SADLTool;
import fi.csc.microarray.auth.Authenticator;
import fi.csc.microarray.client.SwingClientApplication;
import fi.csc.microarray.config.DirectoryLayout;
import fi.csc.microarray.constants.ApplicationConstants;
import fi.csc.microarray.filebroker.FileServer;
import fi.csc.microarray.manager.Manager;
import fi.csc.microarray.messaging.AdminAPI;
import fi.csc.microarray.messaging.MessagingEndpoint;
import fi.csc.microarray.messaging.NodeBase;
import fi.csc.microarray.messaging.Topics;
import fi.csc.microarray.messaging.MessagingTopic.AccessMode;
import fi.csc.microarray.module.chipster.ChipsterSADLParser.Validator;
import fi.csc.microarray.util.CommandLineParser;
import fi.csc.microarray.util.CommandLineParser.CommandLineException;
import fi.csc.microarray.webstart.WebstartJettyServer;
/**
* The main program of Chipster system, actually just a loader for the
* actual components.
*
* @author Aleksi Kallio, Taavi Hupponen
*/
public class MicroarrayMain {
public static void main(String[] args) {
try {
// create args descriptions
CommandLineParser cmdParser = new CommandLineParser();
cmdParser.addParameter("client", false, false, null, "start client (default)");
cmdParser.addParameter("standalone", false, false, null, "start standalone client");
cmdParser.addParameter("authenticator", false, false, null, "start authenticator");
cmdParser.addParameter("fileserver", false, false, null, "start fileserver");
cmdParser.addParameter("analyser", false, false, null, "start analyser");
cmdParser.addParameter("webstart", false, false, null, "start webstart service");
cmdParser.addParameter("manager", false, false, null, "start manager service");
cmdParser.addParameter("tests", false, false, null, "run tests");
cmdParser.addParameter("nagios-check", false, false, null, "do nagios-compatitible system availability check");
cmdParser.addParameter("system-status", false, false, null, "query and print system status");
cmdParser.addParameter("broker-check", false, false, null, "check broker availability");
cmdParser.addParameter("rcheck", false, true, null, "check R script syntax");
cmdParser.addParameter("-config", false, true, null, "configuration file URL (chipster-config.xml)");
cmdParser.addParameter("-required-analyser-count", false, true, "1", "required comp service count for nagios check");
- cmdParser.addParameter("-module", false, true, "microarray", "client module (e.g. microarray-module)");
+ cmdParser.addParameter("-module", false, true, "fi.csc.microarray.module.chipster.MicroarrayModule", "client module (e.g. microarray-module)");
// parse commandline
cmdParser.parse(args);
// configuration file path
String configURL = cmdParser.getValue("-config");
// give help, if needed
if (cmdParser.userAskedHelp()) {
System.out.println("Chipster " + ApplicationConstants.VERSION);
System.out.println("Parameters:");
System.out.println(cmdParser.getDescription());
System.exit(0);
}
// start application
if (cmdParser.hasValue("authenticator")) {
new Authenticator(configURL);
} else if (cmdParser.hasValue("analyser")) {
new AnalyserServer(configURL);
} else if (cmdParser.hasValue("fileserver")) {
new FileServer(configURL);
} else if (cmdParser.hasValue("webstart")) {
new WebstartJettyServer().start();
} else if (cmdParser.hasValue("manager")) {
new Manager(configURL);
} else if (cmdParser.hasValue("nagios-check") || cmdParser.hasValue("system-status")) {
// query status
int requiredAnalyserCount = Integer.parseInt(cmdParser.getValue("-required-analyser-count"));
boolean ok;
String error = "";
String status = "";
try {
NodeBase nodeSupport = new NodeBase() {
public String getName() {
return "nagios-check";
}
};
DirectoryLayout.initialiseSimpleLayout(configURL).getConfiguration();
MessagingEndpoint endpoint = new MessagingEndpoint(nodeSupport);
AdminAPI api = new AdminAPI(endpoint.createTopic(Topics.Name.ADMIN_TOPIC, AccessMode.READ_WRITE), null);
api.setRequiredCountFor("analyser", requiredAnalyserCount);
boolean fastCheck = cmdParser.hasValue("nagios-check");
ok = api.areAllServicesUp(fastCheck);
error = api.getErrorStatus();
status = api.generateStatusReport();
endpoint.close();
} catch (Exception e) {
ok = false;
error = e.getMessage();
}
// print results
if (cmdParser.hasValue("nagios-check")) {
if (ok) {
System.out.println("CHIPSTER OK");
System.exit(0);
} else {
System.out.println("CHIPSTER FAILED: " + error);
System.exit(2);
}
} else {
if (ok) {
System.out.println("Chipster OK.");
} else {
System.out.println("Chipster failed: " + error);
}
System.out.println(status);
}
} else if (cmdParser.hasValue("broker-check")) {
String error = "";
try {
NodeBase nodeSupport = new NodeBase() {
public String getName() {
return "nagios-check";
}
};
MessagingEndpoint endpoint = new MessagingEndpoint(nodeSupport);
endpoint.close();
} catch (Exception e) {
System.out.println("BROKER NOT AVAILABLE: " + error);
System.exit(1);
}
System.out.println("broker available");
System.exit(0);
} else if (cmdParser.hasValue("rcheck")) {
boolean fails = false;
try {
SADLTool.ParsedScript res = new SADLTool("#").parseScript(new FileInputStream(cmdParser.getValue("rcheck")));
new Validator().validate(cmdParser.getValue("rcheck"), res.SADL);
} catch (Exception e) {
System.out.println(e.getMessage());
fails = true;
}
System.out.println("parse succeeded: " + !fails);
} else if (cmdParser.hasValue("standalone")) {
SwingClientApplication.startStandalone(cmdParser.getValue("-module"));
} else {
SwingClientApplication.start(configURL, cmdParser.getValue("-module"));
}
} catch (CommandLineException e) {
System.out.println("Illegal parameters");
System.out.println(" " + e.getMessage());
System.exit(1);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
}
| true | true | public static void main(String[] args) {
try {
// create args descriptions
CommandLineParser cmdParser = new CommandLineParser();
cmdParser.addParameter("client", false, false, null, "start client (default)");
cmdParser.addParameter("standalone", false, false, null, "start standalone client");
cmdParser.addParameter("authenticator", false, false, null, "start authenticator");
cmdParser.addParameter("fileserver", false, false, null, "start fileserver");
cmdParser.addParameter("analyser", false, false, null, "start analyser");
cmdParser.addParameter("webstart", false, false, null, "start webstart service");
cmdParser.addParameter("manager", false, false, null, "start manager service");
cmdParser.addParameter("tests", false, false, null, "run tests");
cmdParser.addParameter("nagios-check", false, false, null, "do nagios-compatitible system availability check");
cmdParser.addParameter("system-status", false, false, null, "query and print system status");
cmdParser.addParameter("broker-check", false, false, null, "check broker availability");
cmdParser.addParameter("rcheck", false, true, null, "check R script syntax");
cmdParser.addParameter("-config", false, true, null, "configuration file URL (chipster-config.xml)");
cmdParser.addParameter("-required-analyser-count", false, true, "1", "required comp service count for nagios check");
cmdParser.addParameter("-module", false, true, "microarray", "client module (e.g. microarray-module)");
// parse commandline
cmdParser.parse(args);
// configuration file path
String configURL = cmdParser.getValue("-config");
// give help, if needed
if (cmdParser.userAskedHelp()) {
System.out.println("Chipster " + ApplicationConstants.VERSION);
System.out.println("Parameters:");
System.out.println(cmdParser.getDescription());
System.exit(0);
}
// start application
if (cmdParser.hasValue("authenticator")) {
new Authenticator(configURL);
} else if (cmdParser.hasValue("analyser")) {
new AnalyserServer(configURL);
} else if (cmdParser.hasValue("fileserver")) {
new FileServer(configURL);
} else if (cmdParser.hasValue("webstart")) {
new WebstartJettyServer().start();
} else if (cmdParser.hasValue("manager")) {
new Manager(configURL);
} else if (cmdParser.hasValue("nagios-check") || cmdParser.hasValue("system-status")) {
// query status
int requiredAnalyserCount = Integer.parseInt(cmdParser.getValue("-required-analyser-count"));
boolean ok;
String error = "";
String status = "";
try {
NodeBase nodeSupport = new NodeBase() {
public String getName() {
return "nagios-check";
}
};
DirectoryLayout.initialiseSimpleLayout(configURL).getConfiguration();
MessagingEndpoint endpoint = new MessagingEndpoint(nodeSupport);
AdminAPI api = new AdminAPI(endpoint.createTopic(Topics.Name.ADMIN_TOPIC, AccessMode.READ_WRITE), null);
api.setRequiredCountFor("analyser", requiredAnalyserCount);
boolean fastCheck = cmdParser.hasValue("nagios-check");
ok = api.areAllServicesUp(fastCheck);
error = api.getErrorStatus();
status = api.generateStatusReport();
endpoint.close();
} catch (Exception e) {
ok = false;
error = e.getMessage();
}
// print results
if (cmdParser.hasValue("nagios-check")) {
if (ok) {
System.out.println("CHIPSTER OK");
System.exit(0);
} else {
System.out.println("CHIPSTER FAILED: " + error);
System.exit(2);
}
} else {
if (ok) {
System.out.println("Chipster OK.");
} else {
System.out.println("Chipster failed: " + error);
}
System.out.println(status);
}
} else if (cmdParser.hasValue("broker-check")) {
String error = "";
try {
NodeBase nodeSupport = new NodeBase() {
public String getName() {
return "nagios-check";
}
};
MessagingEndpoint endpoint = new MessagingEndpoint(nodeSupport);
endpoint.close();
} catch (Exception e) {
System.out.println("BROKER NOT AVAILABLE: " + error);
System.exit(1);
}
System.out.println("broker available");
System.exit(0);
} else if (cmdParser.hasValue("rcheck")) {
boolean fails = false;
try {
SADLTool.ParsedScript res = new SADLTool("#").parseScript(new FileInputStream(cmdParser.getValue("rcheck")));
new Validator().validate(cmdParser.getValue("rcheck"), res.SADL);
} catch (Exception e) {
System.out.println(e.getMessage());
fails = true;
}
System.out.println("parse succeeded: " + !fails);
} else if (cmdParser.hasValue("standalone")) {
SwingClientApplication.startStandalone(cmdParser.getValue("-module"));
} else {
SwingClientApplication.start(configURL, cmdParser.getValue("-module"));
}
} catch (CommandLineException e) {
System.out.println("Illegal parameters");
System.out.println(" " + e.getMessage());
System.exit(1);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
| public static void main(String[] args) {
try {
// create args descriptions
CommandLineParser cmdParser = new CommandLineParser();
cmdParser.addParameter("client", false, false, null, "start client (default)");
cmdParser.addParameter("standalone", false, false, null, "start standalone client");
cmdParser.addParameter("authenticator", false, false, null, "start authenticator");
cmdParser.addParameter("fileserver", false, false, null, "start fileserver");
cmdParser.addParameter("analyser", false, false, null, "start analyser");
cmdParser.addParameter("webstart", false, false, null, "start webstart service");
cmdParser.addParameter("manager", false, false, null, "start manager service");
cmdParser.addParameter("tests", false, false, null, "run tests");
cmdParser.addParameter("nagios-check", false, false, null, "do nagios-compatitible system availability check");
cmdParser.addParameter("system-status", false, false, null, "query and print system status");
cmdParser.addParameter("broker-check", false, false, null, "check broker availability");
cmdParser.addParameter("rcheck", false, true, null, "check R script syntax");
cmdParser.addParameter("-config", false, true, null, "configuration file URL (chipster-config.xml)");
cmdParser.addParameter("-required-analyser-count", false, true, "1", "required comp service count for nagios check");
cmdParser.addParameter("-module", false, true, "fi.csc.microarray.module.chipster.MicroarrayModule", "client module (e.g. microarray-module)");
// parse commandline
cmdParser.parse(args);
// configuration file path
String configURL = cmdParser.getValue("-config");
// give help, if needed
if (cmdParser.userAskedHelp()) {
System.out.println("Chipster " + ApplicationConstants.VERSION);
System.out.println("Parameters:");
System.out.println(cmdParser.getDescription());
System.exit(0);
}
// start application
if (cmdParser.hasValue("authenticator")) {
new Authenticator(configURL);
} else if (cmdParser.hasValue("analyser")) {
new AnalyserServer(configURL);
} else if (cmdParser.hasValue("fileserver")) {
new FileServer(configURL);
} else if (cmdParser.hasValue("webstart")) {
new WebstartJettyServer().start();
} else if (cmdParser.hasValue("manager")) {
new Manager(configURL);
} else if (cmdParser.hasValue("nagios-check") || cmdParser.hasValue("system-status")) {
// query status
int requiredAnalyserCount = Integer.parseInt(cmdParser.getValue("-required-analyser-count"));
boolean ok;
String error = "";
String status = "";
try {
NodeBase nodeSupport = new NodeBase() {
public String getName() {
return "nagios-check";
}
};
DirectoryLayout.initialiseSimpleLayout(configURL).getConfiguration();
MessagingEndpoint endpoint = new MessagingEndpoint(nodeSupport);
AdminAPI api = new AdminAPI(endpoint.createTopic(Topics.Name.ADMIN_TOPIC, AccessMode.READ_WRITE), null);
api.setRequiredCountFor("analyser", requiredAnalyserCount);
boolean fastCheck = cmdParser.hasValue("nagios-check");
ok = api.areAllServicesUp(fastCheck);
error = api.getErrorStatus();
status = api.generateStatusReport();
endpoint.close();
} catch (Exception e) {
ok = false;
error = e.getMessage();
}
// print results
if (cmdParser.hasValue("nagios-check")) {
if (ok) {
System.out.println("CHIPSTER OK");
System.exit(0);
} else {
System.out.println("CHIPSTER FAILED: " + error);
System.exit(2);
}
} else {
if (ok) {
System.out.println("Chipster OK.");
} else {
System.out.println("Chipster failed: " + error);
}
System.out.println(status);
}
} else if (cmdParser.hasValue("broker-check")) {
String error = "";
try {
NodeBase nodeSupport = new NodeBase() {
public String getName() {
return "nagios-check";
}
};
MessagingEndpoint endpoint = new MessagingEndpoint(nodeSupport);
endpoint.close();
} catch (Exception e) {
System.out.println("BROKER NOT AVAILABLE: " + error);
System.exit(1);
}
System.out.println("broker available");
System.exit(0);
} else if (cmdParser.hasValue("rcheck")) {
boolean fails = false;
try {
SADLTool.ParsedScript res = new SADLTool("#").parseScript(new FileInputStream(cmdParser.getValue("rcheck")));
new Validator().validate(cmdParser.getValue("rcheck"), res.SADL);
} catch (Exception e) {
System.out.println(e.getMessage());
fails = true;
}
System.out.println("parse succeeded: " + !fails);
} else if (cmdParser.hasValue("standalone")) {
SwingClientApplication.startStandalone(cmdParser.getValue("-module"));
} else {
SwingClientApplication.start(configURL, cmdParser.getValue("-module"));
}
} catch (CommandLineException e) {
System.out.println("Illegal parameters");
System.out.println(" " + e.getMessage());
System.exit(1);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
|
diff --git a/src/com/android/email/activity/MailboxListItem.java b/src/com/android/email/activity/MailboxListItem.java
index df656507..83c41db7 100644
--- a/src/com/android/email/activity/MailboxListItem.java
+++ b/src/com/android/email/activity/MailboxListItem.java
@@ -1,93 +1,95 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.email.activity;
import com.android.email.R;
import com.android.email.provider.EmailContent.Mailbox;
import com.android.internal.util.ArrayUtils;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MailboxListItem extends RelativeLayout {
// Colors used for drop targets
private static Integer sDropUnavailableFgColor;
private static Integer sDropAvailableBgColor;
private static Integer sTextPrimaryColor;
private static Integer sTextSecondaryColor;
public long mMailboxId;
public Integer mMailboxType;
public MailboxesAdapter mAdapter;
private Drawable mBackground;
private TextView mLabelName;
private TextView mLabelCount;
public MailboxListItem(Context context) {
super(context);
}
public MailboxListItem(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MailboxListItem(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mBackground = getBackground();
if (sDropAvailableBgColor == null) {
Resources res = getResources();
sDropAvailableBgColor = res.getColor(R.color.mailbox_drop_available_bg_color);
sDropUnavailableFgColor = res.getColor(R.color.mailbox_drop_unavailable_fg_color);
sTextPrimaryColor = res.getColor(R.color.text_primary_color);
sTextSecondaryColor = res.getColor(R.color.text_secondary_color);
}
mLabelName = (TextView)findViewById(R.id.mailbox_name);
mLabelCount = (TextView)findViewById(R.id.message_count);
}
public boolean isDropTarget(long itemMailbox) {
if ((mMailboxId < 0) || (itemMailbox == mMailboxId)) {
return false;
}
return !ArrayUtils.contains(Mailbox.INVALID_DROP_TARGETS, mMailboxType);
}
public void setDropTargetBackground(boolean dragInProgress, long itemMailbox) {
+ int labelNameColor = sTextPrimaryColor;
+ int labelCountColor = sTextSecondaryColor;
if (dragInProgress) {
if (isDropTarget(itemMailbox)) {
setBackgroundColor(sDropAvailableBgColor);
} else {
- mLabelName.setTextColor(sDropUnavailableFgColor);
- mLabelCount.setTextColor(sDropUnavailableFgColor);
+ labelNameColor = sDropUnavailableFgColor;
+ labelCountColor = sDropUnavailableFgColor;
}
} else {
- mLabelName.setTextColor(sTextPrimaryColor);
- mLabelCount.setTextColor(sTextSecondaryColor);
setBackgroundDrawable(mBackground);
}
+ mLabelName.setTextColor(labelNameColor);
+ mLabelCount.setTextColor(labelCountColor);
}
}
| false | true | public void setDropTargetBackground(boolean dragInProgress, long itemMailbox) {
if (dragInProgress) {
if (isDropTarget(itemMailbox)) {
setBackgroundColor(sDropAvailableBgColor);
} else {
mLabelName.setTextColor(sDropUnavailableFgColor);
mLabelCount.setTextColor(sDropUnavailableFgColor);
}
} else {
mLabelName.setTextColor(sTextPrimaryColor);
mLabelCount.setTextColor(sTextSecondaryColor);
setBackgroundDrawable(mBackground);
}
}
| public void setDropTargetBackground(boolean dragInProgress, long itemMailbox) {
int labelNameColor = sTextPrimaryColor;
int labelCountColor = sTextSecondaryColor;
if (dragInProgress) {
if (isDropTarget(itemMailbox)) {
setBackgroundColor(sDropAvailableBgColor);
} else {
labelNameColor = sDropUnavailableFgColor;
labelCountColor = sDropUnavailableFgColor;
}
} else {
setBackgroundDrawable(mBackground);
}
mLabelName.setTextColor(labelNameColor);
mLabelCount.setTextColor(labelCountColor);
}
|
diff --git a/app/src/processing/app/syntax/PdeKeywords.java b/app/src/processing/app/syntax/PdeKeywords.java
index 9b5ea6838..e9b29f1ff 100644
--- a/app/src/processing/app/syntax/PdeKeywords.java
+++ b/app/src/processing/app/syntax/PdeKeywords.java
@@ -1,257 +1,258 @@
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
PdeKeywords - handles text coloring and links to html reference
Part of the Processing project - http://processing.org
Copyright (c) 2004-12 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package processing.app.syntax;
import javax.swing.text.Segment;
import processing.app.Editor;
/**
* This class reads a keywords.txt file to get coloring put links to reference
* locations for the set of keywords.
*/
public class PdeKeywords extends TokenMarker {
private KeywordMap keywordColoring;
private int lastOffset;
private int lastKeyword;
/**
* Add a keyword, and the associated coloring. KEYWORD2 and KEYWORD3
* should only be used with functions (where parens are present).
* This is done for the extra paren handling.
* @param coloring one of KEYWORD1, KEYWORD2, LITERAL1, etc.
*/
public void addColoring(String keyword, String coloring) {
if (keywordColoring == null) {
keywordColoring = new KeywordMap(false);
}
// KEYWORD1 -> 0, KEYWORD2 -> 1, etc
int num = coloring.charAt(coloring.length() - 1) - '1';
// byte id = (byte) ((isKey ? Token.KEYWORD1 : Token.LITERAL1) + num);
int id = 0;
boolean paren = false;
switch (coloring.charAt(0)) {
case 'K': id = Token.KEYWORD1 + num; break;
case 'L': id = Token.LITERAL1 + num; break;
case 'F': id = Token.FUNCTION1 + num; paren = true; break;
}
keywordColoring.add(keyword, (byte) id, paren);
}
public byte markTokensImpl(byte token, Segment line, int lineIndex) {
char[] array = line.array;
int offset = line.offset;
lastOffset = offset;
lastKeyword = offset;
int mlength = offset + line.count;
boolean backslash = false;
loop: for (int i = offset; i < mlength; i++) {
int i1 = (i + 1);
char c = array[i];
if (c == '\\') {
backslash = !backslash;
continue;
}
switch (token) {
case Token.NULL:
switch (c) {
case '#':
if (backslash)
backslash = false;
break;
case '"':
doKeyword(line, i, c);
if (backslash)
backslash = false;
else {
addToken(i - lastOffset, token);
token = Token.LITERAL1;
lastOffset = lastKeyword = i;
}
break;
case '\'':
doKeyword(line, i, c);
if (backslash)
backslash = false;
else {
addToken(i - lastOffset, token);
token = Token.LITERAL2;
lastOffset = lastKeyword = i;
}
break;
case ':':
if (lastKeyword == offset) {
if (doKeyword(line, i, c))
break;
backslash = false;
addToken(i1 - lastOffset, Token.LABEL);
lastOffset = lastKeyword = i1;
} else if (doKeyword(line, i, c))
break;
break;
case '/':
backslash = false;
doKeyword(line, i, c);
if (mlength - i > 1) {
switch (array[i1]) {
case '*':
addToken(i - lastOffset, token);
lastOffset = lastKeyword = i;
if (mlength - i > 2 && array[i + 2] == '*')
token = Token.COMMENT2;
else
token = Token.COMMENT1;
break;
case '/':
addToken(i - lastOffset, token);
addToken(mlength - i, Token.COMMENT1);
lastOffset = lastKeyword = mlength;
break loop;
}
- i++; // http://processing.org/bugs/bugzilla/609.html [jdf]
+ if(array[i1]!=' ')
+ i++; // http://processing.org/bugs/bugzilla/609.html [jdf]
}
break;
default:
backslash = false;
if (!Character.isLetterOrDigit(c) && c != '_') {
// if (i1 < mlength && array[i1]
// boolean paren = false;
// int stepper = i + 1;
// while (stepper < mlength) {
// if (array[stepper] == '(') {
// paren = true;
// break;
// }
// stepper++;
// }
doKeyword(line, i, c);
// doKeyword(line, i, checkParen(array, i1, mlength));
}
break;
}
break;
case Token.COMMENT1:
case Token.COMMENT2:
backslash = false;
if (c == '*' && mlength - i > 1) {
if (array[i1] == '/') {
i++;
addToken((i + 1) - lastOffset, token);
token = Token.NULL;
lastOffset = lastKeyword = i + 1;
}
}
break;
case Token.LITERAL1:
if (backslash)
backslash = false;
else if (c == '"') {
addToken(i1 - lastOffset, token);
token = Token.NULL;
lastOffset = lastKeyword = i1;
}
break;
case Token.LITERAL2:
if (backslash)
backslash = false;
else if (c == '\'') {
addToken(i1 - lastOffset, Token.LITERAL1);
token = Token.NULL;
lastOffset = lastKeyword = i1;
}
break;
default:
throw new InternalError("Invalid state: " + token);
}
}
if (token == Token.NULL) {
doKeyword(line, mlength, '\0');
}
switch (token) {
case Token.LITERAL1:
case Token.LITERAL2:
addToken(mlength - lastOffset, Token.INVALID);
token = Token.NULL;
break;
case Token.KEYWORD2:
addToken(mlength - lastOffset, token);
if (!backslash)
token = Token.NULL;
addToken(mlength - lastOffset, token);
break;
default:
addToken(mlength - lastOffset, token);
break;
}
return token;
}
private boolean doKeyword(Segment line, int i, char c) {
// return doKeyword(line, i, false);
// }
//
//
// //private boolean doKeyword(Segment line, int i, char c) {
// private boolean doKeyword(Segment line, int i, boolean paren) {
int i1 = i + 1;
int len = i - lastKeyword;
boolean paren = Editor.checkParen(line.array, i, line.array.length);
// String s = new String(line.array, lastKeyword, len);
// if (s.equals("mousePressed")) {
// System.out.println("found mousePressed" + (paren ? "()" : ""));
// //new Exception().printStackTrace(System.out);
//// System.out.println(" " + i + " " + line.count + " " +
//// //new String(line.array, line.offset + i, line.offset + line.count - i));
//// new String(line.array, i, line.array.length - i));
// }
byte id = keywordColoring.lookup(line, lastKeyword, len, paren);
if (id != Token.NULL) {
if (lastKeyword != lastOffset) {
addToken(lastKeyword - lastOffset, Token.NULL);
}
// if (paren && id == Token.LITERAL2) {
// id = Token.KEYWORD2;
// } else if (!paren && id == Token.KEYWORD2) {
// id = Token.LITERAL2;
// }
addToken(len, id);
lastOffset = i;
}
lastKeyword = i1;
return false;
}
}
| true | true | public byte markTokensImpl(byte token, Segment line, int lineIndex) {
char[] array = line.array;
int offset = line.offset;
lastOffset = offset;
lastKeyword = offset;
int mlength = offset + line.count;
boolean backslash = false;
loop: for (int i = offset; i < mlength; i++) {
int i1 = (i + 1);
char c = array[i];
if (c == '\\') {
backslash = !backslash;
continue;
}
switch (token) {
case Token.NULL:
switch (c) {
case '#':
if (backslash)
backslash = false;
break;
case '"':
doKeyword(line, i, c);
if (backslash)
backslash = false;
else {
addToken(i - lastOffset, token);
token = Token.LITERAL1;
lastOffset = lastKeyword = i;
}
break;
case '\'':
doKeyword(line, i, c);
if (backslash)
backslash = false;
else {
addToken(i - lastOffset, token);
token = Token.LITERAL2;
lastOffset = lastKeyword = i;
}
break;
case ':':
if (lastKeyword == offset) {
if (doKeyword(line, i, c))
break;
backslash = false;
addToken(i1 - lastOffset, Token.LABEL);
lastOffset = lastKeyword = i1;
} else if (doKeyword(line, i, c))
break;
break;
case '/':
backslash = false;
doKeyword(line, i, c);
if (mlength - i > 1) {
switch (array[i1]) {
case '*':
addToken(i - lastOffset, token);
lastOffset = lastKeyword = i;
if (mlength - i > 2 && array[i + 2] == '*')
token = Token.COMMENT2;
else
token = Token.COMMENT1;
break;
case '/':
addToken(i - lastOffset, token);
addToken(mlength - i, Token.COMMENT1);
lastOffset = lastKeyword = mlength;
break loop;
}
i++; // http://processing.org/bugs/bugzilla/609.html [jdf]
}
break;
default:
backslash = false;
if (!Character.isLetterOrDigit(c) && c != '_') {
// if (i1 < mlength && array[i1]
// boolean paren = false;
// int stepper = i + 1;
// while (stepper < mlength) {
// if (array[stepper] == '(') {
// paren = true;
// break;
// }
// stepper++;
// }
doKeyword(line, i, c);
// doKeyword(line, i, checkParen(array, i1, mlength));
}
break;
}
break;
case Token.COMMENT1:
case Token.COMMENT2:
backslash = false;
if (c == '*' && mlength - i > 1) {
if (array[i1] == '/') {
i++;
addToken((i + 1) - lastOffset, token);
token = Token.NULL;
lastOffset = lastKeyword = i + 1;
}
}
break;
case Token.LITERAL1:
if (backslash)
backslash = false;
else if (c == '"') {
addToken(i1 - lastOffset, token);
token = Token.NULL;
lastOffset = lastKeyword = i1;
}
break;
case Token.LITERAL2:
if (backslash)
backslash = false;
else if (c == '\'') {
addToken(i1 - lastOffset, Token.LITERAL1);
token = Token.NULL;
lastOffset = lastKeyword = i1;
}
break;
default:
throw new InternalError("Invalid state: " + token);
}
}
if (token == Token.NULL) {
doKeyword(line, mlength, '\0');
}
switch (token) {
case Token.LITERAL1:
case Token.LITERAL2:
addToken(mlength - lastOffset, Token.INVALID);
token = Token.NULL;
break;
case Token.KEYWORD2:
addToken(mlength - lastOffset, token);
if (!backslash)
token = Token.NULL;
addToken(mlength - lastOffset, token);
break;
default:
addToken(mlength - lastOffset, token);
break;
}
return token;
}
| public byte markTokensImpl(byte token, Segment line, int lineIndex) {
char[] array = line.array;
int offset = line.offset;
lastOffset = offset;
lastKeyword = offset;
int mlength = offset + line.count;
boolean backslash = false;
loop: for (int i = offset; i < mlength; i++) {
int i1 = (i + 1);
char c = array[i];
if (c == '\\') {
backslash = !backslash;
continue;
}
switch (token) {
case Token.NULL:
switch (c) {
case '#':
if (backslash)
backslash = false;
break;
case '"':
doKeyword(line, i, c);
if (backslash)
backslash = false;
else {
addToken(i - lastOffset, token);
token = Token.LITERAL1;
lastOffset = lastKeyword = i;
}
break;
case '\'':
doKeyword(line, i, c);
if (backslash)
backslash = false;
else {
addToken(i - lastOffset, token);
token = Token.LITERAL2;
lastOffset = lastKeyword = i;
}
break;
case ':':
if (lastKeyword == offset) {
if (doKeyword(line, i, c))
break;
backslash = false;
addToken(i1 - lastOffset, Token.LABEL);
lastOffset = lastKeyword = i1;
} else if (doKeyword(line, i, c))
break;
break;
case '/':
backslash = false;
doKeyword(line, i, c);
if (mlength - i > 1) {
switch (array[i1]) {
case '*':
addToken(i - lastOffset, token);
lastOffset = lastKeyword = i;
if (mlength - i > 2 && array[i + 2] == '*')
token = Token.COMMENT2;
else
token = Token.COMMENT1;
break;
case '/':
addToken(i - lastOffset, token);
addToken(mlength - i, Token.COMMENT1);
lastOffset = lastKeyword = mlength;
break loop;
}
if(array[i1]!=' ')
i++; // http://processing.org/bugs/bugzilla/609.html [jdf]
}
break;
default:
backslash = false;
if (!Character.isLetterOrDigit(c) && c != '_') {
// if (i1 < mlength && array[i1]
// boolean paren = false;
// int stepper = i + 1;
// while (stepper < mlength) {
// if (array[stepper] == '(') {
// paren = true;
// break;
// }
// stepper++;
// }
doKeyword(line, i, c);
// doKeyword(line, i, checkParen(array, i1, mlength));
}
break;
}
break;
case Token.COMMENT1:
case Token.COMMENT2:
backslash = false;
if (c == '*' && mlength - i > 1) {
if (array[i1] == '/') {
i++;
addToken((i + 1) - lastOffset, token);
token = Token.NULL;
lastOffset = lastKeyword = i + 1;
}
}
break;
case Token.LITERAL1:
if (backslash)
backslash = false;
else if (c == '"') {
addToken(i1 - lastOffset, token);
token = Token.NULL;
lastOffset = lastKeyword = i1;
}
break;
case Token.LITERAL2:
if (backslash)
backslash = false;
else if (c == '\'') {
addToken(i1 - lastOffset, Token.LITERAL1);
token = Token.NULL;
lastOffset = lastKeyword = i1;
}
break;
default:
throw new InternalError("Invalid state: " + token);
}
}
if (token == Token.NULL) {
doKeyword(line, mlength, '\0');
}
switch (token) {
case Token.LITERAL1:
case Token.LITERAL2:
addToken(mlength - lastOffset, Token.INVALID);
token = Token.NULL;
break;
case Token.KEYWORD2:
addToken(mlength - lastOffset, token);
if (!backslash)
token = Token.NULL;
addToken(mlength - lastOffset, token);
break;
default:
addToken(mlength - lastOffset, token);
break;
}
return token;
}
|
diff --git a/src/main/java/org/noisemap/core/PropagationProcess.java b/src/main/java/org/noisemap/core/PropagationProcess.java
index c1d6882..4ca5c89 100644
--- a/src/main/java/org/noisemap/core/PropagationProcess.java
+++ b/src/main/java/org/noisemap/core/PropagationProcess.java
@@ -1,947 +1,947 @@
/**
* NoiseMap is a scientific computation plugin for OrbisGIS developed in order to
* evaluate the noise impact on urban mobility plans. This model is
* based on the French standard method NMPB2008. It includes traffic-to-noise
* sources evaluation and sound propagation processing.
*
* This version is developed at French IRSTV Institute and at IFSTTAR
* (http://www.ifsttar.fr/) as part of the Eval-PDU project, funded by the
* French Agence Nationale de la Recherche (ANR) under contract ANR-08-VILL-0005-01.
*
* Noisemap is distributed under GPL 3 license. Its reference contact is Judicaël
* Picaut <[email protected]>. It is maintained by Nicolas Fortin
* as part of the "Atelier SIG" team of the IRSTV Institute <http://www.irstv.fr/>.
*
* Copyright (C) 2011 IFSTTAR
* Copyright (C) 2011-2012 IRSTV (FR CNRS 2488)
*
* Noisemap 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.
*
* Noisemap 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
* Noisemap. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, please consult: <http://www.orbisgis.org/>
* or contact directly:
* info_at_ orbisgis.org
*/
package org.noisemap.core;
import java.util.ArrayList;
import java.util.List;
import com.vividsolutions.jts.algorithm.NonRobustLineIntersector;
import com.vividsolutions.jts.algorithm.CGAlgorithms;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineSegment;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.index.quadtree.Quadtree;
import java.util.*;
/**
*
* @author Nicolas Fortin
*/
public class PropagationProcess implements Runnable {
private final static double BASE_LVL=1.; // 0dB lvl
private final static double ONETHIRD=1./3.;
private final static double MERGE_SRC_DIST=1.;
private final static double DBA_FORGET_SOURCE=0.03;
private final static double FIRST_STEP_RANGE=90;
private final static double W_RANGE=Math.pow(10,94./10.); //94 dB(A) range search. Max iso level is >75 dB(a).
private final static double CEL = 344.23935;
private final static int LIMITATION_RECEIVER_MIRROR = 1000;
private final static int LIMITATION_DIFFRACTION_PATH = 1000;
private Thread thread;
private PropagationProcessData data;
private PropagationProcessOut dataOut;
private Quadtree cornersQuad;
private int nbfreq;
private long diffractionPathCount=0;
private long refpathcount=0;
private double[] alpha_atmo;
private double[] freq_lambda;
private static double GetGlobalLevel(int nbfreq,double energeticSum[]) {
double globlvl = 0;
for (int idfreq = 0; idfreq < nbfreq; idfreq++) {
globlvl += energeticSum[idfreq];
}
return globlvl;
}
/**
* Occlusion test on two walls. Segments are CCW oriented.
* @param wall1
* @param wall2
* @return True if the walls are face to face
*/
static public boolean wallWallTest(LineSegment wall1,LineSegment wall2) {
return ((CGAlgorithms.isCCW(new Coordinate[] {wall1.getCoordinate(0),wall1.getCoordinate(1),wall2.getCoordinate(0),wall1.getCoordinate(0)}) || CGAlgorithms.isCCW(new Coordinate[] {wall1.getCoordinate(0),wall1.getCoordinate(1),wall2.getCoordinate(1),wall1.getCoordinate(0)})) && (CGAlgorithms.isCCW(new Coordinate[] {wall2.getCoordinate(0),wall2.getCoordinate(1),wall1.getCoordinate(0),wall2.getCoordinate(0)}) || CGAlgorithms.isCCW(new Coordinate[] {wall2.getCoordinate(0),wall2.getCoordinate(1),wall1.getCoordinate(1),wall2.getCoordinate(0)})));
}
/**
* Occlusion test on two walls. Segments are CCW oriented.
* @param wall1
* @param pt
* @return True if the wall is oriented to the point
*/
static public boolean wallPointTest(LineSegment wall1,Coordinate pt) {
return CGAlgorithms.isCCW(new Coordinate[] {wall1.getCoordinate(0),wall1.getCoordinate(1),pt,wall1.getCoordinate(0)});
}
/**
* Recursive method to feed mirrored receiver position on walls. No
* obstruction test is done.
*
* @param receiversImage
* Add receiver image here
* @param receiverCoord
* Receiver coordinate or precedent mirrored coordinate
* @param lastResult
* Last row index. -1 if first reflexion
* @param nearBuildingsWalls
* Walls to be reflected on
* @param depth
* Depth of reflection TODO Use segment orientation to filter
* wall list
*/
static private void feedMirroredReceiverResults(
List<MirrorReceiverResult> receiversImage,
Coordinate receiverCoord, int lastResult,
List<LineSegment> nearBuildingsWalls, int depth,
double distanceLimitation) {
// For each wall (except parent wall) compute the mirrored coordinate
int exceptionWallId = -1;
if (lastResult != -1) {
exceptionWallId = receiversImage.get(lastResult).getWallId();
}
int wallId = 0;
for (LineSegment wall : nearBuildingsWalls) {
if (wallId != exceptionWallId) {
//Counter ClockWise test. Walls vertices are CCW oriented.
//This help to test if a wall could see a point or another wall
//If the triangle formed by two point of the wall + the receiver is CCW then the wall is oriented toward the point.
boolean isCCW=false;
if (lastResult == -1) { //If the receiverCoord is not an image
isCCW=wallPointTest(wall,receiverCoord);
} else {
//Call wall visibility test
isCCW=wallWallTest(nearBuildingsWalls.get(exceptionWallId),wall);
}
if(isCCW) {
Coordinate intersectionPt = wall.project(receiverCoord);
if (wall.distance(receiverCoord) < distanceLimitation) // Test
// maximum
// distance
// constraint
{
Coordinate mirrored = new Coordinate(2 * intersectionPt.x
- receiverCoord.x, 2 * intersectionPt.y
- receiverCoord.y);
receiversImage.add(new MirrorReceiverResult(mirrored,
lastResult, wallId));
if (depth > 0) {
feedMirroredReceiverResults(receiversImage, mirrored,
receiversImage.size() - 1, nearBuildingsWalls,
depth - 1, distanceLimitation);
}
}
}
}
wallId++;
if(receiversImage.size()>LIMITATION_RECEIVER_MIRROR) {
break;
}
}
}
/**
* Compute all receiver position mirrored by specified segments
*
* @param receiverCoord
* Position of the original receiver
* @param nearBuildingsWalls
* Segments to mirror to
* @param order
* Order of reflections 1 to a limited number
* @param distanceLimitation Limitation of searching mirrored receivers
* @return List of possible reflections
*/
static public List<MirrorReceiverResult> getMirroredReceiverResults(
Coordinate receiverCoord, List<LineSegment> nearBuildingsWalls,
int order, double distanceLimitation) {
List<MirrorReceiverResult> receiversImage = new ArrayList<MirrorReceiverResult>();
feedMirroredReceiverResults(receiversImage, receiverCoord, -1,
nearBuildingsWalls, order - 1, distanceLimitation);
return receiversImage;
}
public PropagationProcess(PropagationProcessData data,
PropagationProcessOut dataOut) {
thread = new Thread(this);
this.dataOut = dataOut;
this.data = data;
}
public void start() {
thread.start();
}
public void join() {
try {
thread.join();
} catch (Exception e) {
return;
}
}
public static double dbaToW(double dBA) {
return Math.pow(10., dBA / 10.);
}
public static double wToDba(double w) {
return 10 * Math.log10(w);
}
/**
* @param startPt
* Compute the closest point on lineString with this coordinate,
* use it as one of the splitted points
* @return computed delta
*/
private double splitLineStringIntoPoints(Geometry geom, Coordinate startPt,
List<Coordinate> pts, double minRecDist) {
// Find the position of the closest point
Coordinate[] points = geom.getCoordinates();
// For each segments
Double closestPtDist = Double.MAX_VALUE;
Coordinate closestPt = null;
double roadLength = 0.;
for (int i = 1; i < points.length; i++) {
LineSegment seg = new LineSegment(points[i - 1], points[i]);
roadLength += seg.getLength();
Coordinate SegClosest = seg.closestPoint(startPt);
double segcdist = SegClosest.distance(startPt);
if (segcdist < closestPtDist) {
closestPtDist = segcdist;
closestPt = SegClosest;
}
}
if (closestPt == null) {
return 1.;
}
double delta = 20.;
// If the minimum effective distance between the line source and the
// receiver is smaller than the minimum distance constraint then the
// discretisation parameter is changed
// Delta must not not too small to avoid memory overhead.
if (closestPtDist < minRecDist) {
closestPtDist = minRecDist;
}
if (closestPtDist / 2 < delta) {
delta = closestPtDist / 2;
}
pts.add(closestPt);
Coordinate[] splitedPts = ST_SplitLineInPoints
.splitMultiPointsInRegularPoints(points, delta);
for (Coordinate pt : splitedPts) {
if (pt.distance(closestPt) > delta) {
pts.add(pt);
}
}
if (delta < roadLength) {
return delta;
} else {
return roadLength;
}
}
/**
* ISO-9613 p1 - At 15°C 70% humidity
*
* @param freq
* Third octave frequency
* @return Attenuation coefficient dB/KM
*/
private static double getAlpha(int freq) {
switch (freq) {
case 100:
return 0.25;
case 125:
return 0.38;
case 160:
return 0.57;
case 200:
return 0.82;
case 250:
return 1.13;
case 315:
return 1.51;
case 400:
return 1.92;
case 500:
return 2.36;
case 630:
return 2.84;
case 800:
return 3.38;
case 1000:
return 4.08;
case 1250:
return 5.05;
case 1600:
return 6.51;
case 2000:
return 8.75;
case 2500:
return 12.2;
case 3150:
return 17.7;
case 4000:
return 26.4;
case 5000:
return 39.9;
default:
return 0.;
}
}
private int nextFreeFieldNode(List<Coordinate> nodes, Coordinate startPt,
List<Integer> NodeExceptions, int firstTestNode,
FastObstructionTest freeFieldFinder) {
int validNode = firstTestNode;
while (NodeExceptions.contains(validNode)
|| (validNode < nodes.size() && !freeFieldFinder.isFreeField(
startPt, nodes.get(validNode)))) {
validNode++;
}
if (validNode >= nodes.size()) {
return -1;
}
return validNode;
}
/**
* Compute attenuation of sound energy by distance. Minimum distance is one
* meter.
*
* @param Wj
* Source level
* @param distance
* Distance in meter
* @return Attenuated sound level. Take only account of geometric dispersion
* of sound wave.
*/
public static double attDistW(double Wj, double distance) {
if (distance < 1.) // No infinite sound level
{
return Wj / (4 * Math.PI);
} else {
return Wj / (4 * Math.PI * distance * distance);
}
}
/**
* Source-Receiver Direct+Reflection+Diffraction computation
*
* @param[in] srcCoord Coordinate of source
* @param[in] receiverCoord Coordinate of receiver
* @param[out] energeticSum Energy by frequency band
* @param[in] alpha_atmo Atmospheric absorption by frequency band
* @param[in] wj Source sound pressure level dB(A) by frequency band
* @param[in] li Coefficient, distance between source discretization
* @param[in] mirroredReceiver Receivers mirrored by walls (for reflection)
* @param[in] nearBuildingsWalls Walls within maxsrcdist
* @param[in] regionCorners Corners within maxsrcdist
* @param[in] regionCornersFreeToReceiver List of index of corners visible
* from receiver
* @param[in] freq_lambda Array of sound wave lambda value by frequency band
*/
private void receiverSourcePropa(Coordinate srcCoord,
Coordinate receiverCoord, double energeticSum[],
double[] alpha_atmo, List<Double> wj,
List<MirrorReceiverResult> mirroredReceiver,
List<LineSegment> nearBuildingsWalls,
List<Coordinate> regionCorners,
List<Integer> regionCornersFreeToReceiver, double[] freq_lambda)
{
// GeometryFactory factory=new GeometryFactory();
int freqcount = data.freq_lvl.size();
double SrcReceiverDistance = srcCoord.distance(receiverCoord);
if (SrcReceiverDistance < data.maxSrcDist) {
// Then, check if the source is visible from the receiver (not
// hidden by a building)
// Create the direct Line
boolean somethingHideReceiver = false;
somethingHideReceiver = !data.freeFieldFinder.isFreeField(
receiverCoord, srcCoord);
if (!somethingHideReceiver) {
// Evaluation of energy at receiver
// add=wj/(4*pi*distance²)
for (int idfreq = 0; idfreq < freqcount; idfreq++) {
double AttenuatedWj = attDistW(wj.get(idfreq),
SrcReceiverDistance);
AttenuatedWj = attAtmW(AttenuatedWj,
SrcReceiverDistance,
alpha_atmo[idfreq]);
energeticSum[idfreq] += AttenuatedWj;
}
}
//
// Process specular reflection
if (data.reflexionOrder > 0) {
NonRobustLineIntersector linters = new NonRobustLineIntersector();
for (MirrorReceiverResult receiverReflection : mirroredReceiver) {
double ReflectedSrcReceiverDistance = receiverReflection
.getReceiverPos().distance(srcCoord);
if (ReflectedSrcReceiverDistance < data.maxSrcDist ) {
boolean validReflection = false;
int reflectionOrderCounter = 0;
MirrorReceiverResult receiverReflectionCursor = receiverReflection;
// Test whether intersection point is on the wall
// segment or not
Coordinate destinationPt = new Coordinate(srcCoord);
LineSegment seg = nearBuildingsWalls
.get(receiverReflection.getWallId());
linters.computeIntersection(seg.p0, seg.p1,
receiverReflection.getReceiverPos(),
destinationPt);
while (linters.hasIntersection() && PropagationProcess.wallPointTest(seg, destinationPt)) // While there is a
// reflection point
// on another wall
{
reflectionOrderCounter++;
// There are a probable reflection point on the
// segment
Coordinate reflectionPt = new Coordinate(
linters.getIntersection(0));
// Translate reflection point by epsilon value to
// increase computation robustness
Coordinate vec_epsilon = new Coordinate(
reflectionPt.x - destinationPt.x,
reflectionPt.y - destinationPt.y);
double length = vec_epsilon
.distance(new Coordinate(0., 0., 0.));
// Normalize vector
vec_epsilon.x /= length;
vec_epsilon.y /= length;
// Multiply by epsilon in meter
vec_epsilon.x *= 0.01;
vec_epsilon.y *= 0.01;
// Translate reflection pt by epsilon to get outside
// the wall
reflectionPt.x -= vec_epsilon.x;
reflectionPt.y -= vec_epsilon.y;
// Test if there is no obstacles between the
// reflection point and old reflection pt (or source
// position)
validReflection = data.freeFieldFinder.isFreeField(
reflectionPt, destinationPt);
if (validReflection) // Reflection point can see
// source or its image
{
if (receiverReflectionCursor
.getMirrorResultId() == -1) { // Direct
// to
// the
// receiver
validReflection = data.freeFieldFinder
.isFreeField(reflectionPt,
receiverCoord);
break; // That was the last reflection
} else {
// There is another reflection
destinationPt.setCoordinate(reflectionPt);
// Move reflection information cursor to a
// reflection closer
receiverReflectionCursor = mirroredReceiver
.get(receiverReflectionCursor
.getMirrorResultId());
// Update intersection data
seg = nearBuildingsWalls
.get(receiverReflectionCursor
.getWallId());
linters.computeIntersection(seg.p0, seg.p1,
receiverReflectionCursor
.getReceiverPos(),
destinationPt);
validReflection = false;
}
} else {
break;
}
}
if (validReflection) {
//NTODO remove output
/*
System.out.print("("+srcCoord+")Path : ");
receiverReflectionCursor = receiverReflection;
while(receiverReflectionCursor != null) {
System.out.print(receiverReflectionCursor.getWallId()+" ");
if(receiverReflectionCursor
.getMirrorResultId()!=-1) {
receiverReflectionCursor = mirroredReceiver
.get(receiverReflectionCursor
.getMirrorResultId());
}else{
receiverReflectionCursor=null;
}
}
System.out.println();
*/
// A path has been found
refpathcount+=1;
for (int idfreq = 0; idfreq < freqcount; idfreq++) {
// Geometric dispersion
double AttenuatedWj = attDistW(wj.get(idfreq),
ReflectedSrcReceiverDistance);
// Apply wall material attenuation
AttenuatedWj *= Math.pow((1 - data.wallAlpha),
reflectionOrderCounter);
// Apply atmospheric absorption and ground
AttenuatedWj = attAtmW(
AttenuatedWj,
ReflectedSrcReceiverDistance,
alpha_atmo[idfreq]);
energeticSum[idfreq] += AttenuatedWj;
}
}
}
}
} // End reflexion
// ///////////
// Process diffraction paths
if (somethingHideReceiver && data.diffractionOrder > 0
&& !regionCornersFreeToReceiver.isEmpty()) {
// Get the first valid receiver->corner
int receiverFreeCornerIndex = 0;
int firstCorner = regionCornersFreeToReceiver
.get(receiverFreeCornerIndex);
if (firstCorner != -1) {
// History of propagation through corners
List<Integer> curCorner = new ArrayList<Integer>();
curCorner.add(firstCorner);
while (!curCorner.isEmpty()) {
Coordinate lastCorner = regionCorners.get(curCorner
.get(curCorner.size() - 1));
// Test Path is free to the source
if (data.freeFieldFinder.isFreeField(lastCorner,
srcCoord)) {
// True then the path is clear
// Compute attenuation level
double elength = 0;
//Compute distance of the corner path
for (int ie = 1; ie < curCorner.size(); ie++) {
elength += regionCorners.get(
curCorner.get(ie - 1)).distance(
regionCorners.get(curCorner.get(ie)));
}
// delta=SO^1+O^nO^(n+1)+O^nnR
double diffractionFullDistance = receiverCoord
.distance(regionCorners.get(curCorner //Receiver to first corner distance
.get(0)))
+ elength //Corner to corner distance
+ srcCoord
.distance(regionCorners.get(curCorner //Last corner to source distance
.get(curCorner.size() - 1)));
if (diffractionFullDistance < data.maxSrcDist) {
diffractionPathCount++;
double delta = diffractionFullDistance
- SrcReceiverDistance;
for (int idfreq = 0; idfreq < freqcount; idfreq++) {
double cprime;
//C" NMPB 2008 P.33
if (curCorner.size() == 1) {
cprime = 1; //Single diffraction cprime=1
} else {
//Multiple diffraction
//CPRIME=( 1+(5*gamma)^2)/((1/3)+(5*gamma)^2)
- double gammapart=Math.pow((5*freq_lambda[idfreq])/diffractionFullDistance, 2);
+ double gammapart=Math.pow((5*freq_lambda[idfreq])/elength, 2);
cprime=(1.+gammapart)/(ONETHIRD+gammapart);
}
//(7.11) NMP2008 P.32
double testForm = (40 / freq_lambda[idfreq])
* cprime * delta;
double DiffractionAttenuation = 0.;
if (testForm >= -2.) {
DiffractionAttenuation = 10 * Math
.log10(3 + testForm);
}else{
}
// Limit to 0<=DiffractionAttenuation
DiffractionAttenuation = Math.max(0,
DiffractionAttenuation);
double AttenuatedWj = wj.get(idfreq);
// Geometric dispersion
AttenuatedWj=attDistW(AttenuatedWj, SrcReceiverDistance);
// Apply diffraction attenuation
AttenuatedWj = dbaToW(wToDba(AttenuatedWj)
- DiffractionAttenuation);
// Apply atmospheric absorption and ground
AttenuatedWj = attAtmW(
AttenuatedWj,
diffractionFullDistance,
alpha_atmo[idfreq]);
energeticSum[idfreq] += AttenuatedWj;
}
if(diffractionPathCount>LIMITATION_DIFFRACTION_PATH) {
break; //exit diffraction search
}
// TODO removing
/*
* if(somethingHideReceiver) { Coordinate[]
* coordinates=new
* Coordinate[2+curCorner.size()];
* coordinates[0]=receiverCoord; int idvertex=1;
* for(int idcorner : curCorner) {
* coordinates[idvertex
* ]=regionCorners.get(idcorner); idvertex++; }
* coordinates[coordinates.length-1]=srcCoord;
* Value[] row=new Value[3];
* row[0]=ValueFactory.
* createValue(factory.createLineString
* (coordinates));
* row[1]=ValueFactory.createValue(idReceiver);
* row
* [2]=ValueFactory.createValue(WToDba(largeAtt
* )); try { driver.addValues(row); } catch
* (DriverException e) { // TODO Auto-generated
* catch block e.printStackTrace(); return; } }
* //END REMOVING
*/
}
}
// Process to the next corner
int nextCorner = -1;
if (data.diffractionOrder > curCorner.size()) {
// Continue to next order valid corner
nextCorner = nextFreeFieldNode(regionCorners,
lastCorner, curCorner, 0,
data.freeFieldFinder);
if (nextCorner != -1) {
curCorner.add(nextCorner);
}
}
while (nextCorner == -1 && !curCorner.isEmpty()) {
if (curCorner.size() > 1) {
// Next free field corner
nextCorner = nextFreeFieldNode(regionCorners,
regionCorners.get(curCorner
.get(curCorner.size() - 2)),
curCorner, curCorner.get(curCorner
.size() - 1),
data.freeFieldFinder);
} else {
// Next receiver-corner tuple
receiverFreeCornerIndex++;
if (receiverFreeCornerIndex < regionCornersFreeToReceiver
.size()) {
nextCorner = regionCornersFreeToReceiver
.get(receiverFreeCornerIndex);
} else {
nextCorner = -1;
}
}
if (nextCorner != -1) {
curCorner.set(curCorner.size() - 1, nextCorner);
} else {
curCorner.remove(curCorner.size() - 1);
}
}
}
}
}
}
}
private static void insertPtSource(Coordinate receiverPos,Coordinate ptpos,List<Double> wj,double li,List<Coordinate> srcPos,List<ArrayList<Double>> srcWj,PointsMerge sourcesMerger,List<Integer> srcSortedIndex,List<Double> srcDistSorted) {
int mergedSrcIndex=sourcesMerger.getOrAppendVertex(ptpos);
if(mergedSrcIndex<srcPos.size()) {
ArrayList<Double> mergedWj=srcWj.get(mergedSrcIndex);
//A source already exist and is close enough to merge
for(int fb=0;fb<wj.size();fb++) {
mergedWj.set(fb, mergedWj.get(fb)+wj.get(fb)*li);
}
} else {
//New source
ArrayList<Double> liWj=new ArrayList<Double>(wj.size());
for(Double lvl : wj) {
liWj.add(lvl*li);
}
srcPos.add(ptpos);
srcWj.add(liWj);
double distanceSrcPt=ptpos.distance(receiverPos);
int index = Collections.binarySearch(srcDistSorted, distanceSrcPt);
if(index >=0) {
srcSortedIndex.add(index,mergedSrcIndex);
srcDistSorted.add(index,distanceSrcPt);
} else {
srcSortedIndex.add(-index-1, mergedSrcIndex);
srcDistSorted.add(-index-1, distanceSrcPt);
}
}
}
/**
* Compute the attenuation of atmospheric absorption
*
* @param Wj
* Source energy
* @param dist
* Propagation distance
* @param alpha_atmo
* Atmospheric alpha (dB/km)
* @return
*/
private Double attAtmW(double Wj, double dist, double alpha_atmo) {
return dbaToW(wToDba(Wj) - (alpha_atmo * dist) / 1000.);
}
/**
* Compute sound level by frequency band at this receiver position
* @param receiverCoord
* @param energeticSum
*/
public void computeSoundLevelAtPosition(Coordinate receiverCoord,double energeticSum[]) {
// List of walls within maxReceiverSource distance
double srcEnergeticSum=BASE_LVL; //Global energetic sum of all sources processed
List<LineSegment> nearBuildingsWalls = null;
List<MirrorReceiverResult> mirroredReceiver = null;
if (data.reflexionOrder > 0) {
nearBuildingsWalls = new ArrayList<LineSegment>(
data.freeFieldFinder.getLimitsInRange(
data.maxRefDist , receiverCoord));
// Build mirrored receiver list from wall list
mirroredReceiver = getMirroredReceiverResults(receiverCoord,
nearBuildingsWalls, data.reflexionOrder,
data.maxRefDist*2);
this.dataOut.appendImageReceiver(mirroredReceiver.size());
}
List<Coordinate> regionCorners = new ArrayList<Coordinate>();
List<Integer> regionCornersFreeToReceiver = new ArrayList<Integer>(); // Corners
// free
// field
// with
// receiver
if (data.diffractionOrder > 0) {
// Query corners in the current zone
ArrayCoordinateListVisitor cornerQuery = new ArrayCoordinateListVisitor(
receiverCoord, data.maxRefDist);
cornersQuad.query(new Envelope(receiverCoord.x
- data.maxRefDist, receiverCoord.x + data.maxRefDist,
receiverCoord.y - data.maxRefDist, receiverCoord.y
+ data.maxRefDist), cornerQuery);
regionCorners = cornerQuery.getItems();
// regionCornersFreeToReceiver.ensureCapacity(regionCorners.size());
for (int icorner = 0; icorner < regionCorners.size(); icorner++) {
if (data.freeFieldFinder.isFreeField(receiverCoord,
regionCorners.get(icorner))) {
regionCornersFreeToReceiver.add(icorner);
}
}
}
// Source search by multiple range query
HashSet<Integer> processedLineSources = new HashSet<Integer>(); //Already processed Raw source (line and/or points)
double[] ranges=new double[] {FIRST_STEP_RANGE,data.maxSrcDist/5,data.maxSrcDist/4,data.maxSrcDist/2,data.maxSrcDist};
long sourceCount=0;
for(double searchSourceDistance : ranges) {
Envelope receiverSourceRegion = new Envelope(receiverCoord.x
- searchSourceDistance, receiverCoord.x + searchSourceDistance,
receiverCoord.y - searchSourceDistance, receiverCoord.y
+ searchSourceDistance);
Iterator<Integer> regionSourcesLst = data.sourcesIndex
.query(receiverSourceRegion);
PointsMerge sourcesMerger=new PointsMerge(MERGE_SRC_DIST);
List<Integer> srcSortByDist = new ArrayList<Integer>();
List<Double> srcDist = new ArrayList<Double>();
List<Coordinate> srcPos = new ArrayList<Coordinate>();
List<ArrayList<Double>> srcWj= new ArrayList<ArrayList<Double>>();
while (regionSourcesLst.hasNext()) {
Integer srcIndex = regionSourcesLst.next();
if(!processedLineSources.contains(srcIndex)) {
processedLineSources.add(srcIndex);
Geometry source = data.sourceGeometries.get(srcIndex);
List<Double> wj = data.wj_sources.get(srcIndex); // DbaToW(sdsSources.getDouble(srcIndex,dbField
if (source instanceof Point) {
Coordinate ptpos = ((Point) source).getCoordinate();
insertPtSource(receiverCoord,ptpos, wj, 1., srcPos, srcWj, sourcesMerger,srcSortByDist,srcDist);
// Compute li to equation 4.1 NMPB 2008 (June 2009)
} else {
// Discretization of line into multiple point
// First point is the closest point of the LineString from
// the receiver
ArrayList<Coordinate> pts=new ArrayList<Coordinate>() ;
double li = splitLineStringIntoPoints(source, receiverCoord,
pts, data.minRecDist);
for(Coordinate pt : pts) {
insertPtSource(receiverCoord,pt, wj, li, srcPos, srcWj, sourcesMerger,srcSortByDist,srcDist);
}
// Compute li to equation 4.1 NMPB 2008 (June 2009)
}
}
}
//Iterate over source point sorted by their distance from the receiver
for (int mergedSrcId : srcSortByDist) {
// For each Pt Source - Pt Receiver
Coordinate srcCoord=srcPos.get(mergedSrcId);
ArrayList<Double> wj= srcWj.get(mergedSrcId);
double allreceiverfreqlvl = GetGlobalLevel(nbfreq,energeticSum);
double allsourcefreqlvl = 0;
for (int idfreq = 0; idfreq < nbfreq; idfreq++) {
allsourcefreqlvl += wj.get(idfreq);
}
double wAttDistSource=attDistW(allsourcefreqlvl,srcCoord.distance(receiverCoord));
srcEnergeticSum+=wAttDistSource;
if(Math.abs(wToDba(wAttDistSource+allreceiverfreqlvl)-wToDba(allreceiverfreqlvl))>DBA_FORGET_SOURCE) {
sourceCount++;
receiverSourcePropa(srcCoord, receiverCoord, energeticSum,
alpha_atmo, wj, mirroredReceiver,
nearBuildingsWalls, regionCorners,
regionCornersFreeToReceiver, freq_lambda);
}
}
//srcEnergeticSum=GetGlobalLevel(nbfreq,energeticSum);
if(Math.abs(wToDba(attDistW(W_RANGE,searchSourceDistance)+srcEnergeticSum)-wToDba(srcEnergeticSum))<DBA_FORGET_SOURCE) {
break; //Stop search for fartest sources
}
}
dataOut.appendSourceCount(sourceCount);
}
/**
* Must be called before computeSoundLevelAtPosition
*/
public void initStructures() {
nbfreq = data.freq_lvl.size();
// Init wave length for each frequency
freq_lambda = new double[nbfreq];
for (int idf = 0; idf < nbfreq; idf++) {
if (data.freq_lvl.get(idf) > 0) {
freq_lambda[idf] = CEL / data.freq_lvl.get(idf);
} else {
freq_lambda[idf] = 1;
}
}
// Compute atmospheric alpha value by specified frequency band
alpha_atmo = new double[data.freq_lvl.size()];
for (int idfreq = 0; idfreq < nbfreq; idfreq++) {
alpha_atmo[idfreq] = getAlpha(data.freq_lvl.get(idfreq));
}
// /////////////////////////////////////////////
// Search diffraction corners
cornersQuad = new Quadtree();
if (data.diffractionOrder > 0) {
List<Coordinate> corners = data.freeFieldFinder.getWideAnglePoints(
Math.PI * (1 + 1 / 16.0), Math.PI * (2 - (1 / 16.)));
// Build Quadtree
for (Coordinate corner : corners) {
cornersQuad.insert(new Envelope(corner), corner);
}
}
}
@Override
public void run() {
initStructures();
GeometryFactory factory = new GeometryFactory();
// TODO comment debugging code
/*
* Type
* meta_type[]={TypeFactory.createType(Type.GEOMETRY),TypeFactory.createType
* (Type.INT),TypeFactory.createType(Type.DOUBLE)}; String
* meta_name[]={"the_geom","difid","largebandatt"}; DefaultMetadata
* metadata = new DefaultMetadata(meta_type,meta_name); DiskBufferDriver
* driver; try { driver = new DiskBufferDriver(data.dsf,metadata ); }
* catch (DriverException e) { e.printStackTrace(); return; }
*/
double verticesSoundLevel[] = new double[data.vertices.size()]; // Computed
// sound
// level
// of
// vertices
// For each vertices, find sources where the distance is within
// maxSrcDist meters
ProgressionProcess propaProcessProgression = data.cellProg;
int idReceiver = 0;
long min_compute_time=Long.MAX_VALUE;
long max_compute_time=0;
long sum_compute=0;
for (Coordinate receiverCoord : data.vertices) {
long debReceiverTime = System.nanoTime();
propaProcessProgression.nextSubProcessEnd();
double energeticSum[] = new double[data.freq_lvl.size()];
for (int idfreq = 0; idfreq < nbfreq; idfreq++) {
energeticSum[idfreq] = 0.0;
}
computeSoundLevelAtPosition(receiverCoord, energeticSum);
// Save the sound level at this receiver
// Do the sum of all frequency bands
double allfreqlvl = 0;
for (int idfreq = 0; idfreq < nbfreq; idfreq++) {
allfreqlvl += energeticSum[idfreq];
}
allfreqlvl= Math.max(allfreqlvl,BASE_LVL);
verticesSoundLevel[idReceiver] = allfreqlvl;
long computeTime=System.nanoTime()-debReceiverTime;
min_compute_time=Math.min(computeTime, min_compute_time);
max_compute_time=Math.max(computeTime, max_compute_time);
sum_compute+=computeTime;
idReceiver++;
}
if(data.triangles!=null) { //Triangle output type
// Subdivide each triangle, and apply BiCubic interpolation.
/*
* ArrayList<Triangle> bicubictri=new ArrayList<Triangle>();
* bicubictri.ensureCapacity(data.triangles.size()); for(Triangle tri :
* data.triangles) { //////////////////////// //Find the fourth vertex }
*/
// Now export all triangles with the sound level at each vertices
int tri_id = 0;
for (Triangle tri : data.triangles) {
Coordinate pverts[] = { data.vertices.get(tri.getA()),
data.vertices.get(tri.getB()),
data.vertices.get(tri.getC()),
data.vertices.get(tri.getA()) };
dataOut.addValues(new PropagationResultTriRecord(
factory.createPolygon(factory.createLinearRing(pverts), null),
verticesSoundLevel[tri.getA()],
verticesSoundLevel[tri.getB()],
verticesSoundLevel[tri.getC()],
data.cellId,
tri_id));
tri_id++;
}
} else {
//Vertices output type
for(int receiverId=0;receiverId<data.vertices.size();receiverId++) {
dataOut.addValues(new PropagationResultPtRecord(data.receiverRowId.get(receiverId), data.cellId,verticesSoundLevel[receiverId] ));
}
}
dataOut.appendFreeFieldTestCount(data.freeFieldFinder.getNbObstructionTest());
dataOut.appendCellComputed();
dataOut.updateMaximalReceiverComputationTime(max_compute_time);
dataOut.updateMinimalReceiverComputationTime(min_compute_time);
dataOut.addSumReceiverComputationTime(sum_compute);
dataOut.appendDiffractionPath(diffractionPathCount);
dataOut.appendReflexionPath(refpathcount);
}
}
| true | true | private void receiverSourcePropa(Coordinate srcCoord,
Coordinate receiverCoord, double energeticSum[],
double[] alpha_atmo, List<Double> wj,
List<MirrorReceiverResult> mirroredReceiver,
List<LineSegment> nearBuildingsWalls,
List<Coordinate> regionCorners,
List<Integer> regionCornersFreeToReceiver, double[] freq_lambda)
{
// GeometryFactory factory=new GeometryFactory();
int freqcount = data.freq_lvl.size();
double SrcReceiverDistance = srcCoord.distance(receiverCoord);
if (SrcReceiverDistance < data.maxSrcDist) {
// Then, check if the source is visible from the receiver (not
// hidden by a building)
// Create the direct Line
boolean somethingHideReceiver = false;
somethingHideReceiver = !data.freeFieldFinder.isFreeField(
receiverCoord, srcCoord);
if (!somethingHideReceiver) {
// Evaluation of energy at receiver
// add=wj/(4*pi*distance²)
for (int idfreq = 0; idfreq < freqcount; idfreq++) {
double AttenuatedWj = attDistW(wj.get(idfreq),
SrcReceiverDistance);
AttenuatedWj = attAtmW(AttenuatedWj,
SrcReceiverDistance,
alpha_atmo[idfreq]);
energeticSum[idfreq] += AttenuatedWj;
}
}
//
// Process specular reflection
if (data.reflexionOrder > 0) {
NonRobustLineIntersector linters = new NonRobustLineIntersector();
for (MirrorReceiverResult receiverReflection : mirroredReceiver) {
double ReflectedSrcReceiverDistance = receiverReflection
.getReceiverPos().distance(srcCoord);
if (ReflectedSrcReceiverDistance < data.maxSrcDist ) {
boolean validReflection = false;
int reflectionOrderCounter = 0;
MirrorReceiverResult receiverReflectionCursor = receiverReflection;
// Test whether intersection point is on the wall
// segment or not
Coordinate destinationPt = new Coordinate(srcCoord);
LineSegment seg = nearBuildingsWalls
.get(receiverReflection.getWallId());
linters.computeIntersection(seg.p0, seg.p1,
receiverReflection.getReceiverPos(),
destinationPt);
while (linters.hasIntersection() && PropagationProcess.wallPointTest(seg, destinationPt)) // While there is a
// reflection point
// on another wall
{
reflectionOrderCounter++;
// There are a probable reflection point on the
// segment
Coordinate reflectionPt = new Coordinate(
linters.getIntersection(0));
// Translate reflection point by epsilon value to
// increase computation robustness
Coordinate vec_epsilon = new Coordinate(
reflectionPt.x - destinationPt.x,
reflectionPt.y - destinationPt.y);
double length = vec_epsilon
.distance(new Coordinate(0., 0., 0.));
// Normalize vector
vec_epsilon.x /= length;
vec_epsilon.y /= length;
// Multiply by epsilon in meter
vec_epsilon.x *= 0.01;
vec_epsilon.y *= 0.01;
// Translate reflection pt by epsilon to get outside
// the wall
reflectionPt.x -= vec_epsilon.x;
reflectionPt.y -= vec_epsilon.y;
// Test if there is no obstacles between the
// reflection point and old reflection pt (or source
// position)
validReflection = data.freeFieldFinder.isFreeField(
reflectionPt, destinationPt);
if (validReflection) // Reflection point can see
// source or its image
{
if (receiverReflectionCursor
.getMirrorResultId() == -1) { // Direct
// to
// the
// receiver
validReflection = data.freeFieldFinder
.isFreeField(reflectionPt,
receiverCoord);
break; // That was the last reflection
} else {
// There is another reflection
destinationPt.setCoordinate(reflectionPt);
// Move reflection information cursor to a
// reflection closer
receiverReflectionCursor = mirroredReceiver
.get(receiverReflectionCursor
.getMirrorResultId());
// Update intersection data
seg = nearBuildingsWalls
.get(receiverReflectionCursor
.getWallId());
linters.computeIntersection(seg.p0, seg.p1,
receiverReflectionCursor
.getReceiverPos(),
destinationPt);
validReflection = false;
}
} else {
break;
}
}
if (validReflection) {
//NTODO remove output
/*
System.out.print("("+srcCoord+")Path : ");
receiverReflectionCursor = receiverReflection;
while(receiverReflectionCursor != null) {
System.out.print(receiverReflectionCursor.getWallId()+" ");
if(receiverReflectionCursor
.getMirrorResultId()!=-1) {
receiverReflectionCursor = mirroredReceiver
.get(receiverReflectionCursor
.getMirrorResultId());
}else{
receiverReflectionCursor=null;
}
}
System.out.println();
*/
// A path has been found
refpathcount+=1;
for (int idfreq = 0; idfreq < freqcount; idfreq++) {
// Geometric dispersion
double AttenuatedWj = attDistW(wj.get(idfreq),
ReflectedSrcReceiverDistance);
// Apply wall material attenuation
AttenuatedWj *= Math.pow((1 - data.wallAlpha),
reflectionOrderCounter);
// Apply atmospheric absorption and ground
AttenuatedWj = attAtmW(
AttenuatedWj,
ReflectedSrcReceiverDistance,
alpha_atmo[idfreq]);
energeticSum[idfreq] += AttenuatedWj;
}
}
}
}
} // End reflexion
// ///////////
// Process diffraction paths
if (somethingHideReceiver && data.diffractionOrder > 0
&& !regionCornersFreeToReceiver.isEmpty()) {
// Get the first valid receiver->corner
int receiverFreeCornerIndex = 0;
int firstCorner = regionCornersFreeToReceiver
.get(receiverFreeCornerIndex);
if (firstCorner != -1) {
// History of propagation through corners
List<Integer> curCorner = new ArrayList<Integer>();
curCorner.add(firstCorner);
while (!curCorner.isEmpty()) {
Coordinate lastCorner = regionCorners.get(curCorner
.get(curCorner.size() - 1));
// Test Path is free to the source
if (data.freeFieldFinder.isFreeField(lastCorner,
srcCoord)) {
// True then the path is clear
// Compute attenuation level
double elength = 0;
//Compute distance of the corner path
for (int ie = 1; ie < curCorner.size(); ie++) {
elength += regionCorners.get(
curCorner.get(ie - 1)).distance(
regionCorners.get(curCorner.get(ie)));
}
// delta=SO^1+O^nO^(n+1)+O^nnR
double diffractionFullDistance = receiverCoord
.distance(regionCorners.get(curCorner //Receiver to first corner distance
.get(0)))
+ elength //Corner to corner distance
+ srcCoord
.distance(regionCorners.get(curCorner //Last corner to source distance
.get(curCorner.size() - 1)));
if (diffractionFullDistance < data.maxSrcDist) {
diffractionPathCount++;
double delta = diffractionFullDistance
- SrcReceiverDistance;
for (int idfreq = 0; idfreq < freqcount; idfreq++) {
double cprime;
//C" NMPB 2008 P.33
if (curCorner.size() == 1) {
cprime = 1; //Single diffraction cprime=1
} else {
//Multiple diffraction
//CPRIME=( 1+(5*gamma)^2)/((1/3)+(5*gamma)^2)
double gammapart=Math.pow((5*freq_lambda[idfreq])/diffractionFullDistance, 2);
cprime=(1.+gammapart)/(ONETHIRD+gammapart);
}
//(7.11) NMP2008 P.32
double testForm = (40 / freq_lambda[idfreq])
* cprime * delta;
double DiffractionAttenuation = 0.;
if (testForm >= -2.) {
DiffractionAttenuation = 10 * Math
.log10(3 + testForm);
}else{
}
// Limit to 0<=DiffractionAttenuation
DiffractionAttenuation = Math.max(0,
DiffractionAttenuation);
double AttenuatedWj = wj.get(idfreq);
// Geometric dispersion
AttenuatedWj=attDistW(AttenuatedWj, SrcReceiverDistance);
// Apply diffraction attenuation
AttenuatedWj = dbaToW(wToDba(AttenuatedWj)
- DiffractionAttenuation);
// Apply atmospheric absorption and ground
AttenuatedWj = attAtmW(
AttenuatedWj,
diffractionFullDistance,
alpha_atmo[idfreq]);
energeticSum[idfreq] += AttenuatedWj;
}
if(diffractionPathCount>LIMITATION_DIFFRACTION_PATH) {
break; //exit diffraction search
}
// TODO removing
/*
* if(somethingHideReceiver) { Coordinate[]
* coordinates=new
* Coordinate[2+curCorner.size()];
* coordinates[0]=receiverCoord; int idvertex=1;
* for(int idcorner : curCorner) {
* coordinates[idvertex
* ]=regionCorners.get(idcorner); idvertex++; }
* coordinates[coordinates.length-1]=srcCoord;
* Value[] row=new Value[3];
* row[0]=ValueFactory.
* createValue(factory.createLineString
* (coordinates));
* row[1]=ValueFactory.createValue(idReceiver);
* row
* [2]=ValueFactory.createValue(WToDba(largeAtt
* )); try { driver.addValues(row); } catch
* (DriverException e) { // TODO Auto-generated
* catch block e.printStackTrace(); return; } }
* //END REMOVING
*/
}
}
// Process to the next corner
int nextCorner = -1;
if (data.diffractionOrder > curCorner.size()) {
// Continue to next order valid corner
nextCorner = nextFreeFieldNode(regionCorners,
lastCorner, curCorner, 0,
data.freeFieldFinder);
if (nextCorner != -1) {
curCorner.add(nextCorner);
}
}
while (nextCorner == -1 && !curCorner.isEmpty()) {
if (curCorner.size() > 1) {
// Next free field corner
nextCorner = nextFreeFieldNode(regionCorners,
regionCorners.get(curCorner
.get(curCorner.size() - 2)),
curCorner, curCorner.get(curCorner
.size() - 1),
data.freeFieldFinder);
} else {
// Next receiver-corner tuple
receiverFreeCornerIndex++;
if (receiverFreeCornerIndex < regionCornersFreeToReceiver
.size()) {
nextCorner = regionCornersFreeToReceiver
.get(receiverFreeCornerIndex);
} else {
nextCorner = -1;
}
}
if (nextCorner != -1) {
curCorner.set(curCorner.size() - 1, nextCorner);
} else {
curCorner.remove(curCorner.size() - 1);
}
}
}
}
}
}
}
| private void receiverSourcePropa(Coordinate srcCoord,
Coordinate receiverCoord, double energeticSum[],
double[] alpha_atmo, List<Double> wj,
List<MirrorReceiverResult> mirroredReceiver,
List<LineSegment> nearBuildingsWalls,
List<Coordinate> regionCorners,
List<Integer> regionCornersFreeToReceiver, double[] freq_lambda)
{
// GeometryFactory factory=new GeometryFactory();
int freqcount = data.freq_lvl.size();
double SrcReceiverDistance = srcCoord.distance(receiverCoord);
if (SrcReceiverDistance < data.maxSrcDist) {
// Then, check if the source is visible from the receiver (not
// hidden by a building)
// Create the direct Line
boolean somethingHideReceiver = false;
somethingHideReceiver = !data.freeFieldFinder.isFreeField(
receiverCoord, srcCoord);
if (!somethingHideReceiver) {
// Evaluation of energy at receiver
// add=wj/(4*pi*distance²)
for (int idfreq = 0; idfreq < freqcount; idfreq++) {
double AttenuatedWj = attDistW(wj.get(idfreq),
SrcReceiverDistance);
AttenuatedWj = attAtmW(AttenuatedWj,
SrcReceiverDistance,
alpha_atmo[idfreq]);
energeticSum[idfreq] += AttenuatedWj;
}
}
//
// Process specular reflection
if (data.reflexionOrder > 0) {
NonRobustLineIntersector linters = new NonRobustLineIntersector();
for (MirrorReceiverResult receiverReflection : mirroredReceiver) {
double ReflectedSrcReceiverDistance = receiverReflection
.getReceiverPos().distance(srcCoord);
if (ReflectedSrcReceiverDistance < data.maxSrcDist ) {
boolean validReflection = false;
int reflectionOrderCounter = 0;
MirrorReceiverResult receiverReflectionCursor = receiverReflection;
// Test whether intersection point is on the wall
// segment or not
Coordinate destinationPt = new Coordinate(srcCoord);
LineSegment seg = nearBuildingsWalls
.get(receiverReflection.getWallId());
linters.computeIntersection(seg.p0, seg.p1,
receiverReflection.getReceiverPos(),
destinationPt);
while (linters.hasIntersection() && PropagationProcess.wallPointTest(seg, destinationPt)) // While there is a
// reflection point
// on another wall
{
reflectionOrderCounter++;
// There are a probable reflection point on the
// segment
Coordinate reflectionPt = new Coordinate(
linters.getIntersection(0));
// Translate reflection point by epsilon value to
// increase computation robustness
Coordinate vec_epsilon = new Coordinate(
reflectionPt.x - destinationPt.x,
reflectionPt.y - destinationPt.y);
double length = vec_epsilon
.distance(new Coordinate(0., 0., 0.));
// Normalize vector
vec_epsilon.x /= length;
vec_epsilon.y /= length;
// Multiply by epsilon in meter
vec_epsilon.x *= 0.01;
vec_epsilon.y *= 0.01;
// Translate reflection pt by epsilon to get outside
// the wall
reflectionPt.x -= vec_epsilon.x;
reflectionPt.y -= vec_epsilon.y;
// Test if there is no obstacles between the
// reflection point and old reflection pt (or source
// position)
validReflection = data.freeFieldFinder.isFreeField(
reflectionPt, destinationPt);
if (validReflection) // Reflection point can see
// source or its image
{
if (receiverReflectionCursor
.getMirrorResultId() == -1) { // Direct
// to
// the
// receiver
validReflection = data.freeFieldFinder
.isFreeField(reflectionPt,
receiverCoord);
break; // That was the last reflection
} else {
// There is another reflection
destinationPt.setCoordinate(reflectionPt);
// Move reflection information cursor to a
// reflection closer
receiverReflectionCursor = mirroredReceiver
.get(receiverReflectionCursor
.getMirrorResultId());
// Update intersection data
seg = nearBuildingsWalls
.get(receiverReflectionCursor
.getWallId());
linters.computeIntersection(seg.p0, seg.p1,
receiverReflectionCursor
.getReceiverPos(),
destinationPt);
validReflection = false;
}
} else {
break;
}
}
if (validReflection) {
//NTODO remove output
/*
System.out.print("("+srcCoord+")Path : ");
receiverReflectionCursor = receiverReflection;
while(receiverReflectionCursor != null) {
System.out.print(receiverReflectionCursor.getWallId()+" ");
if(receiverReflectionCursor
.getMirrorResultId()!=-1) {
receiverReflectionCursor = mirroredReceiver
.get(receiverReflectionCursor
.getMirrorResultId());
}else{
receiverReflectionCursor=null;
}
}
System.out.println();
*/
// A path has been found
refpathcount+=1;
for (int idfreq = 0; idfreq < freqcount; idfreq++) {
// Geometric dispersion
double AttenuatedWj = attDistW(wj.get(idfreq),
ReflectedSrcReceiverDistance);
// Apply wall material attenuation
AttenuatedWj *= Math.pow((1 - data.wallAlpha),
reflectionOrderCounter);
// Apply atmospheric absorption and ground
AttenuatedWj = attAtmW(
AttenuatedWj,
ReflectedSrcReceiverDistance,
alpha_atmo[idfreq]);
energeticSum[idfreq] += AttenuatedWj;
}
}
}
}
} // End reflexion
// ///////////
// Process diffraction paths
if (somethingHideReceiver && data.diffractionOrder > 0
&& !regionCornersFreeToReceiver.isEmpty()) {
// Get the first valid receiver->corner
int receiverFreeCornerIndex = 0;
int firstCorner = regionCornersFreeToReceiver
.get(receiverFreeCornerIndex);
if (firstCorner != -1) {
// History of propagation through corners
List<Integer> curCorner = new ArrayList<Integer>();
curCorner.add(firstCorner);
while (!curCorner.isEmpty()) {
Coordinate lastCorner = regionCorners.get(curCorner
.get(curCorner.size() - 1));
// Test Path is free to the source
if (data.freeFieldFinder.isFreeField(lastCorner,
srcCoord)) {
// True then the path is clear
// Compute attenuation level
double elength = 0;
//Compute distance of the corner path
for (int ie = 1; ie < curCorner.size(); ie++) {
elength += regionCorners.get(
curCorner.get(ie - 1)).distance(
regionCorners.get(curCorner.get(ie)));
}
// delta=SO^1+O^nO^(n+1)+O^nnR
double diffractionFullDistance = receiverCoord
.distance(regionCorners.get(curCorner //Receiver to first corner distance
.get(0)))
+ elength //Corner to corner distance
+ srcCoord
.distance(regionCorners.get(curCorner //Last corner to source distance
.get(curCorner.size() - 1)));
if (diffractionFullDistance < data.maxSrcDist) {
diffractionPathCount++;
double delta = diffractionFullDistance
- SrcReceiverDistance;
for (int idfreq = 0; idfreq < freqcount; idfreq++) {
double cprime;
//C" NMPB 2008 P.33
if (curCorner.size() == 1) {
cprime = 1; //Single diffraction cprime=1
} else {
//Multiple diffraction
//CPRIME=( 1+(5*gamma)^2)/((1/3)+(5*gamma)^2)
double gammapart=Math.pow((5*freq_lambda[idfreq])/elength, 2);
cprime=(1.+gammapart)/(ONETHIRD+gammapart);
}
//(7.11) NMP2008 P.32
double testForm = (40 / freq_lambda[idfreq])
* cprime * delta;
double DiffractionAttenuation = 0.;
if (testForm >= -2.) {
DiffractionAttenuation = 10 * Math
.log10(3 + testForm);
}else{
}
// Limit to 0<=DiffractionAttenuation
DiffractionAttenuation = Math.max(0,
DiffractionAttenuation);
double AttenuatedWj = wj.get(idfreq);
// Geometric dispersion
AttenuatedWj=attDistW(AttenuatedWj, SrcReceiverDistance);
// Apply diffraction attenuation
AttenuatedWj = dbaToW(wToDba(AttenuatedWj)
- DiffractionAttenuation);
// Apply atmospheric absorption and ground
AttenuatedWj = attAtmW(
AttenuatedWj,
diffractionFullDistance,
alpha_atmo[idfreq]);
energeticSum[idfreq] += AttenuatedWj;
}
if(diffractionPathCount>LIMITATION_DIFFRACTION_PATH) {
break; //exit diffraction search
}
// TODO removing
/*
* if(somethingHideReceiver) { Coordinate[]
* coordinates=new
* Coordinate[2+curCorner.size()];
* coordinates[0]=receiverCoord; int idvertex=1;
* for(int idcorner : curCorner) {
* coordinates[idvertex
* ]=regionCorners.get(idcorner); idvertex++; }
* coordinates[coordinates.length-1]=srcCoord;
* Value[] row=new Value[3];
* row[0]=ValueFactory.
* createValue(factory.createLineString
* (coordinates));
* row[1]=ValueFactory.createValue(idReceiver);
* row
* [2]=ValueFactory.createValue(WToDba(largeAtt
* )); try { driver.addValues(row); } catch
* (DriverException e) { // TODO Auto-generated
* catch block e.printStackTrace(); return; } }
* //END REMOVING
*/
}
}
// Process to the next corner
int nextCorner = -1;
if (data.diffractionOrder > curCorner.size()) {
// Continue to next order valid corner
nextCorner = nextFreeFieldNode(regionCorners,
lastCorner, curCorner, 0,
data.freeFieldFinder);
if (nextCorner != -1) {
curCorner.add(nextCorner);
}
}
while (nextCorner == -1 && !curCorner.isEmpty()) {
if (curCorner.size() > 1) {
// Next free field corner
nextCorner = nextFreeFieldNode(regionCorners,
regionCorners.get(curCorner
.get(curCorner.size() - 2)),
curCorner, curCorner.get(curCorner
.size() - 1),
data.freeFieldFinder);
} else {
// Next receiver-corner tuple
receiverFreeCornerIndex++;
if (receiverFreeCornerIndex < regionCornersFreeToReceiver
.size()) {
nextCorner = regionCornersFreeToReceiver
.get(receiverFreeCornerIndex);
} else {
nextCorner = -1;
}
}
if (nextCorner != -1) {
curCorner.set(curCorner.size() - 1, nextCorner);
} else {
curCorner.remove(curCorner.size() - 1);
}
}
}
}
}
}
}
|
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/validator/XpathValidator.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/validator/XpathValidator.java
index e984310fc..ea5e97e0a 100644
--- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/validator/XpathValidator.java
+++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/validator/XpathValidator.java
@@ -1,123 +1,123 @@
/*
* Copyright (c) 2013, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.validator;
import java.util.ArrayList;
import java.util.Map;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import org.wso2.developerstudio.eclipse.platform.ui.validator.CommonFieldValidator;
public class XpathValidator {
public static boolean isValidNamespace(Shell activeShell, Map<String, String> namespaceMap, String prefix, String uri) {
if (StringUtils.isBlank(prefix) || StringUtils.isBlank(uri)) {
return false;
}
if (!isValidUrl(uri)) {
showMessage(activeShell, "Invalid URI \n\n" + uri);
return false;
}
if (namespaceMap.containsKey(prefix)) {
showMessage(activeShell, "Namespace with the given prefix (" + prefix + ") is already exists");
return false;
}
return true;
}
public static boolean isValidUrl(String uri) {
/*
* http://org.apache.synapse/xsd url is valid. But following logic doesn't recognize it.
* Hence following logic is commented out by reopening TOOLS-1814.
*/
/* boolean result = true;
try {
CommonFieldValidator.isValidUrl(uri, "URI: ");
}
catch (Exception e){
result = false;
}
return result;*/
return true;
}
public static boolean isValidConfiguration(Shell activeShell, String xpath, Map<String, String> namespaceMap) {
if (!isValidXpathSyntax(xpath)) {
showMessage(activeShell, "Invalid Xpath Expression.\n\n" + xpath);
return false;
}
- boolean result = true;
+/* boolean result = true;
if (xpath.contains(":")) {
String[] splitedParts = xpath.split("/");
ArrayList<String> prefixList = new ArrayList<String>();
for (String part: splitedParts) {
if (part.length() > 1 && part.contains(":")) {
String prefix = part.substring(0, part.indexOf(":"));
prefixList.add(prefix);
}
}
for (String prefix : prefixList) {
if (!namespaceMap.keySet().contains(prefix)) {
showMessage(activeShell, "The prefix '" + prefix + "' is not contain in the prefix list.");
result = false;
break;
}
}
- }
- return result;
+ }*/
+ return true;
}
public static boolean isValidXpathSyntax(String string) {
/*
* get-property('GET_PROXY_PROPERTIES_RETURN_SEQ') xpath expression is valid. But following logic doesn't recognize it.
* Hence following logic is commented out by reopening TOOLS-1814.
*/
/* boolean result = true;
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
try {
@SuppressWarnings("unused")
XPathExpression expr = xpath.compile(string);
} catch (XPathExpressionException e) {
result = false;
}
return result;*/
return true;
}
private static void showMessage(Shell activeShell, String message){
if (activeShell != null) {
MessageDialog.openWarning(activeShell, "Error", message);
}
}
}
| false | true | public static boolean isValidConfiguration(Shell activeShell, String xpath, Map<String, String> namespaceMap) {
if (!isValidXpathSyntax(xpath)) {
showMessage(activeShell, "Invalid Xpath Expression.\n\n" + xpath);
return false;
}
boolean result = true;
if (xpath.contains(":")) {
String[] splitedParts = xpath.split("/");
ArrayList<String> prefixList = new ArrayList<String>();
for (String part: splitedParts) {
if (part.length() > 1 && part.contains(":")) {
String prefix = part.substring(0, part.indexOf(":"));
prefixList.add(prefix);
}
}
for (String prefix : prefixList) {
if (!namespaceMap.keySet().contains(prefix)) {
showMessage(activeShell, "The prefix '" + prefix + "' is not contain in the prefix list.");
result = false;
break;
}
}
}
return result;
}
| public static boolean isValidConfiguration(Shell activeShell, String xpath, Map<String, String> namespaceMap) {
if (!isValidXpathSyntax(xpath)) {
showMessage(activeShell, "Invalid Xpath Expression.\n\n" + xpath);
return false;
}
/* boolean result = true;
if (xpath.contains(":")) {
String[] splitedParts = xpath.split("/");
ArrayList<String> prefixList = new ArrayList<String>();
for (String part: splitedParts) {
if (part.length() > 1 && part.contains(":")) {
String prefix = part.substring(0, part.indexOf(":"));
prefixList.add(prefix);
}
}
for (String prefix : prefixList) {
if (!namespaceMap.keySet().contains(prefix)) {
showMessage(activeShell, "The prefix '" + prefix + "' is not contain in the prefix list.");
result = false;
break;
}
}
}*/
return true;
}
|
diff --git a/src/java/org/codehaus/groovy/grails/support/MockFileResource.java b/src/java/org/codehaus/groovy/grails/support/MockFileResource.java
index 1c06bd380..8da64151f 100644
--- a/src/java/org/codehaus/groovy/grails/support/MockFileResource.java
+++ b/src/java/org/codehaus/groovy/grails/support/MockFileResource.java
@@ -1,46 +1,46 @@
/* Copyright 2004-2005 Graeme Rocher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.support;
import org.springframework.core.io.ByteArrayResource;
import java.io.UnsupportedEncodingException;
/**
* A resource that mocks the behavior of a FileResource
*
* @author Graeme Rocher
* @since 1.1
* <p/>
* Created: Feb 6, 2009
*/
public class MockFileResource extends ByteArrayResource{
private String fileName;
public MockFileResource(String fileName, String contents) {
- super(contents.getBytes());
+ super(contents.getBytes("UTF-8"));
this.fileName = fileName;
}
public MockFileResource(String fileName, String contents, String encoding) throws UnsupportedEncodingException {
super(contents.getBytes(encoding));
this.fileName = fileName;
}
@Override
public String getFilename() throws IllegalStateException {
return this.fileName;
}
}
| true | true | public MockFileResource(String fileName, String contents) {
super(contents.getBytes());
this.fileName = fileName;
}
| public MockFileResource(String fileName, String contents) {
super(contents.getBytes("UTF-8"));
this.fileName = fileName;
}
|
diff --git a/search/src/java/cz/incad/Kramerius/views/item/ItemViewObject.java b/search/src/java/cz/incad/Kramerius/views/item/ItemViewObject.java
index 46e1edc5a..3f19ca64a 100644
--- a/search/src/java/cz/incad/Kramerius/views/item/ItemViewObject.java
+++ b/search/src/java/cz/incad/Kramerius/views/item/ItemViewObject.java
@@ -1,273 +1,274 @@
package cz.incad.Kramerius.views.item;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.antlr.stringtemplate.StringTemplate;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.name.Named;
import com.qbizm.kramerius.imp.jaxb.PageNumber;
import cz.incad.Kramerius.views.item.menu.ItemMenuViewObject;
import cz.incad.kramerius.FedoraAccess;
import cz.incad.kramerius.MostDesirable;
import cz.incad.kramerius.ProcessSubtreeException;
import cz.incad.kramerius.TreeNodeProcessor;
import cz.incad.kramerius.impl.AbstractTreeNodeProcessorAdapter;
import cz.incad.kramerius.security.IsUserInRoleDecision;
import cz.incad.kramerius.service.ResourceBundleService;
import cz.incad.kramerius.utils.FedoraUtils;
import cz.incad.kramerius.utils.conf.KConfiguration;
import cz.incad.kramerius.utils.pid.LexerException;
import cz.incad.kramerius.utils.pid.PIDParser;
public class ItemViewObject {
public static final java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(ItemViewObject.class.getName());
@Inject
ServletContext servletContext;
@Inject
MostDesirable mostDesirable;
@Inject
HttpServletRequest request;
@Inject
Provider<Locale> localeProvider;
@Inject
ResourceBundleService resourceBundleService;
@Inject
@Named("securedFedoraAccess")
FedoraAccess fedoraAccess;
protected List<String> uuidPath;
protected List<String> models;
protected String pdfPage;
public ItemViewObject() {
super();
}
public void saveMostDesirable() {
String pidPath = request.getParameter("pid_path");
StringTokenizer tokenizer = new StringTokenizer(pidPath, "/");
if (tokenizer.hasMoreTokens()) {
this.mostDesirable.saveAccess(tokenizer.nextToken(), new Date());
}
}
public String getFirstPageImageUrl() {
if(pdfPage==null){
return "fullThumb?uuid=" + getLastUUID();
}else{
return "djvu?uuid=" + getLastUUID() + "&scaledWidth=512&page="+(Integer.parseInt(pdfPage)-1);
}
}
public String getThumbImageUrl() {
if(pdfPage==null){
return "thumb?uuid=" + getLastUUID() + "&scaledWidth=650";
}else{
return "thumb?uuid=" + getLastUUID() + "&scaledWidth=650&page="+(Integer.parseInt(pdfPage)-1);
}
}
public String getPage(){
return pdfPage;
}
public String getImagePid() {
return getLastUUID();
}
public String getFirstUUID() {
return (getPids().isEmpty() ? null : getPids().get(0));
}
public String getParentUUID() {
List<String> pids = getPids();
if (pids.size() >= 2) {
return pids.get(pids.size() - 2);
} else {
return null;
}
}
public String getLastUUID() {
if(pdfPage==null)
return (getPids().isEmpty() ? null : getPids().get(getPids().size() - 1));
else
return (getPids().isEmpty() ? null : getPids().get(getPids().size() - 2));
}
public String[] getModelsFromRequest() {
String[] models = request.getParameter("path").split("/");
return models;
}
public String[] getUUIDPathFromRequest() {
String[] pids = request.getParameter("pid_path").split("/");
return pids;
}
public List<String> getPids() {
LOGGER.fine("uuid path is "+this.uuidPath);
return uuidPath;
}
public void init() {
try {
final String[]pathFromRequests = getUUIDPathFromRequest();
final String[] modelsFromRequest = getModelsFromRequest();
String lastUuid = pathFromRequests[pathFromRequests.length -1];
if (isPageUUID(lastUuid)) {
pdfPage = getPageUUID(lastUuid);
+ lastUuid = pathFromRequests[pathFromRequests.length -2];
}
// find everything
final FindRestUUIDs fru = new FindRestUUIDs(this.fedoraAccess, lastUuid);
fedoraAccess.processSubtree("uuid:"+lastUuid, fru);
List<String> uuidsPathList = new ArrayList<String>(){{
addAll(Arrays.asList(pathFromRequests));
addAll(fru.getPathFromRoot());
}};
List<String> modelsPathList = new ArrayList<String>(){{
addAll(Arrays.asList(modelsFromRequest));
addAll(fru.getModelsFromRoot());
}};
this.uuidPath = uuidsPathList;
this.models = modelsPathList;
} catch (IOException e) {
// co s tim ?
throw new RuntimeException(e);
} catch (ProcessSubtreeException e) {
// co s tim ?
throw new RuntimeException(e);
}
}
public boolean isPageUUID(String uuid) {
return uuid.indexOf("@")>-1;
}
public String getPageUUID(String pageUuid) {
return pageUuid.substring(1);
}
public List<String> getModels() {
return this.models;
}
public List<ItemMenuViewObject> getMenus() {
try {
List<String> pids = getPids();
List<String> models = getModels();
List<ItemMenuViewObject> menus = new ArrayList<ItemMenuViewObject>();
for (int i = 0; i < pids.size(); i++) {
menus.add(new ItemMenuViewObject(this.request, this.servletContext, this.fedoraAccess, this.resourceBundleService.getResourceBundle("labels", localeProvider.get()), KConfiguration.getInstance(), this, localeProvider.get(),pids.get(i), models.get(i), i));
}
return menus;
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return new ArrayList<ItemMenuViewObject>();
}
}
public String getDeepZoomURL() {
return null;
}
/** Finds lists represents uuid path and model path from given root */
private class FindRestUUIDs extends AbstractTreeNodeProcessorAdapter {
private List<String> pathFromRoot = new ArrayList<String>();
private List<String> modelsFromRoot = new ArrayList<String>();
private String rootUUID;
private FedoraAccess fedoraAccess;
private int previousLevel = 0;
private boolean broken = false;
public FindRestUUIDs(FedoraAccess fedoraAccess,String rootUUID) {
super();
this.rootUUID = rootUUID;
this.fedoraAccess = fedoraAccess;
}
@Override
public void processUuid(String pageUuid, int level) throws ProcessSubtreeException {
try {
// dolu
if (previousLevel < level || level == 0) {
if (!pageUuid.equals(rootUUID)) {
pathFromRoot.add(pageUuid);
modelsFromRoot.add(fedoraAccess.getKrameriusModelName(pageUuid));
}
//nahoru
} else if (previousLevel > level) {
broken = true;
// stejny level ale ne ten prvni
} else if ((previousLevel == level) && (previousLevel != 0)){
broken = true;
}
previousLevel = level;
} catch (IOException e) {
throw new ProcessSubtreeException(e);
}
}
public List<String> getPathFromRoot() {
LOGGER.fine("Path from root :"+this.pathFromRoot);
return pathFromRoot;
}
public List<String> getModelsFromRoot() {
LOGGER.fine("Models from root :"+this.pathFromRoot);
return modelsFromRoot;
}
@Override
public boolean breakProcessing(String pid, int level) {
try {
if (!broken) {
String uuid = ensureUUID(pid);
return fedoraAccess.isStreamAvailable(uuid, FedoraUtils.IMG_FULL_STREAM);
} else return true;
} catch (LexerException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
| true | true | public void init() {
try {
final String[]pathFromRequests = getUUIDPathFromRequest();
final String[] modelsFromRequest = getModelsFromRequest();
String lastUuid = pathFromRequests[pathFromRequests.length -1];
if (isPageUUID(lastUuid)) {
pdfPage = getPageUUID(lastUuid);
}
// find everything
final FindRestUUIDs fru = new FindRestUUIDs(this.fedoraAccess, lastUuid);
fedoraAccess.processSubtree("uuid:"+lastUuid, fru);
List<String> uuidsPathList = new ArrayList<String>(){{
addAll(Arrays.asList(pathFromRequests));
addAll(fru.getPathFromRoot());
}};
List<String> modelsPathList = new ArrayList<String>(){{
addAll(Arrays.asList(modelsFromRequest));
addAll(fru.getModelsFromRoot());
}};
this.uuidPath = uuidsPathList;
this.models = modelsPathList;
} catch (IOException e) {
// co s tim ?
throw new RuntimeException(e);
} catch (ProcessSubtreeException e) {
// co s tim ?
throw new RuntimeException(e);
}
}
| public void init() {
try {
final String[]pathFromRequests = getUUIDPathFromRequest();
final String[] modelsFromRequest = getModelsFromRequest();
String lastUuid = pathFromRequests[pathFromRequests.length -1];
if (isPageUUID(lastUuid)) {
pdfPage = getPageUUID(lastUuid);
lastUuid = pathFromRequests[pathFromRequests.length -2];
}
// find everything
final FindRestUUIDs fru = new FindRestUUIDs(this.fedoraAccess, lastUuid);
fedoraAccess.processSubtree("uuid:"+lastUuid, fru);
List<String> uuidsPathList = new ArrayList<String>(){{
addAll(Arrays.asList(pathFromRequests));
addAll(fru.getPathFromRoot());
}};
List<String> modelsPathList = new ArrayList<String>(){{
addAll(Arrays.asList(modelsFromRequest));
addAll(fru.getModelsFromRoot());
}};
this.uuidPath = uuidsPathList;
this.models = modelsPathList;
} catch (IOException e) {
// co s tim ?
throw new RuntimeException(e);
} catch (ProcessSubtreeException e) {
// co s tim ?
throw new RuntimeException(e);
}
}
|
diff --git a/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/DynamicEventAction.java b/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/DynamicEventAction.java
index 77517a9dd..5397557b0 100644
--- a/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/DynamicEventAction.java
+++ b/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/DynamicEventAction.java
@@ -1,409 +1,417 @@
package edu.wustl.catissuecore.action;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.common.dynamicextensions.exception.DynamicExtensionsCacheException;
import edu.wustl.cab2b.common.util.Utility;
import edu.wustl.catissuecore.actionForm.DynamicEventForm;
import edu.wustl.catissuecore.bizlogic.CatissueDefaultBizLogic;
import edu.wustl.catissuecore.bizlogic.SPPBizLogic;
import edu.wustl.catissuecore.bizlogic.UserBizLogic;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.domain.processingprocedure.Action;
import edu.wustl.catissuecore.domain.processingprocedure.ActionApplication;
import edu.wustl.catissuecore.domain.processingprocedure.DefaultAction;
import edu.wustl.catissuecore.processor.SPPEventProcessor;
import edu.wustl.catissuecore.util.global.AppUtility;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.global.SpecimenEventsUtility;
import edu.wustl.common.action.BaseAction;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.bizlogic.IBizLogic;
import edu.wustl.common.factory.AbstractFactoryConfig;
import edu.wustl.common.factory.IFactory;
import edu.wustl.common.util.global.CommonServiceLocator;
import edu.wustl.common.util.global.CommonUtilities;
public class DynamicEventAction extends BaseAction
{
/**
* Overrides the executeSecureAction method of SecureAction class.
* @param mapping
* object of ActionMapping
* @param form
* object of ActionForm
* @param request
* object of HttpServletRequest
* @param response : HttpServletResponse
* @throws Exception
* generic exception
* @return ActionForward : ActionForward
*/
@Override
protected ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
if (request.getParameter(Constants.REFRESH_EVENT_GRID) != null)
{
request.setAttribute(Constants.REFRESH_EVENT_GRID, request
.getParameter(Constants.REFRESH_EVENT_GRID));
}
//this.setCommonRequestParameters(request);
DynamicEventForm dynamicEventForm = (DynamicEventForm) form;
resetFormParameters(request, dynamicEventForm);
// if operation is add
if (dynamicEventForm.isAddOperation())
{
if (dynamicEventForm.getUserId() == 0)
{
final SessionDataBean sessionData = this.getSessionData(request);
if (sessionData != null && sessionData.getUserId() != null)
{
final long userId = sessionData.getUserId().longValue();
dynamicEventForm.setUserId(userId);
}
}
// set the current Date and Time for the event.
final Calendar cal = Calendar.getInstance();
if (dynamicEventForm.getDateOfEvent() == null)
{
dynamicEventForm.setDateOfEvent(CommonUtilities.parseDateToString(cal.getTime(),
CommonServiceLocator.getInstance().getDatePattern()));
}
if (dynamicEventForm.getTimeInHours() == null)
{
dynamicEventForm.setTimeInHours(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)));
}
if (dynamicEventForm.getTimeInMinutes() == null)
{
dynamicEventForm.setTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE)));
}
}
else
{
String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID);
if (specimenId == null)
{
request.setAttribute(Constants.SPECIMEN_ID, specimenId);
}
}
String reasonDeviation = "";
reasonDeviation = dynamicEventForm.getReasonDeviation();
if (reasonDeviation == null)
{
reasonDeviation = "";
}
String currentEventParametersDate = "";
currentEventParametersDate = dynamicEventForm.getDateOfEvent();
if (currentEventParametersDate == null)
{
currentEventParametersDate = "";
}
final Integer dynamicEventParametersYear = new Integer(AppUtility
.getYear(currentEventParametersDate));
final Integer dynamicEventParametersMonth = new Integer(AppUtility
.getMonth(currentEventParametersDate));
final Integer dynamicEventParametersDay = new Integer(AppUtility
.getDay(currentEventParametersDate));
request.setAttribute("minutesList", Constants.MINUTES_ARRAY);
// Sets the hourList attribute to be used in the Add/Edit
// FrozenEventParameters Page.
request.setAttribute("hourList", Constants.HOUR_ARRAY);
request.setAttribute("dynamicEventParametersYear", dynamicEventParametersYear);
request.setAttribute("dynamicEventParametersDay", dynamicEventParametersDay);
request.setAttribute("dynamicEventParametersMonth", dynamicEventParametersMonth);
request.setAttribute("formName", Constants.DYNAMIC_EVENT_ACTION);
request.setAttribute("addForJSP", Constants.ADD);
request.setAttribute("editForJSP", Constants.EDIT);
request.setAttribute("reasonDeviation", reasonDeviation);
request.setAttribute("userListforJSP", Constants.USERLIST);
request.setAttribute("currentEventParametersDate", currentEventParametersDate);
request.setAttribute(Constants.PAGE_OF, "pageOfDynamicEvent");
request.setAttribute(Constants.SPECIMEN_ID, request.getSession().getAttribute(
Constants.SPECIMEN_ID));
//request.setAttribute(Constants.SPECIMEN_ID, request.getAttribute(Constants.SPECIMEN_ID));
//request.setAttribute(Constants.PAGE_OF, request.getParameter(Constants.PAGE_OF));
//request.setAttribute("changeAction", Constants.CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION);
final String operation = request.getParameter(Constants.OPERATION);
final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory();
final UserBizLogic userBizLogic = (UserBizLogic) factory
.getBizLogic(Constants.USER_FORM_ID);
final Collection userCollection = userBizLogic.getUsers(operation);
request.setAttribute(Constants.USERLIST, userCollection);
HashMap dynamicEventMap = (HashMap) request.getSession().getAttribute("dynamicEventMap");
String iframeURL="";
long recordIdentifier=0;
Long eventId=null;
if(dynamicEventForm.getOperation().equals(Constants.ADD))
{
String eventName = request.getParameter("eventName");
if(eventName == null)
{
eventName = (String)request.getSession().getAttribute("eventName");
}
request.getSession().setAttribute("eventName", eventName);
dynamicEventForm.setEventName(eventName);
eventId=(Long) dynamicEventMap.get(eventName);
checkIsCaCoreGenerated(request, factory, eventId);
if (Boolean.parseBoolean(request.getParameter("showDefaultValues")))
{
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
List<Action> actionList = defaultBizLogic.retrieve(Action.class.getName(),
Constants.ID, request.getParameter("formContextId"));
if (actionList != null && !actionList.isEmpty())
{
Action action = (Action) actionList.get(0);
if (action.getApplicationDefaultValue() != null)
{
recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(action
.getApplicationDefaultValue().getId(), action.getContainerId());
}
}
}
else
{
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
List<DefaultAction> actionList = defaultBizLogic.retrieve(DefaultAction.class
.getName(), Constants.CONTAINER_ID, eventId);
DefaultAction action =null;
if (actionList != null && !actionList.isEmpty())
{
action = (DefaultAction) actionList.get(0);
}
else
{
action=new DefaultAction();
action.setContainerId(eventId);
defaultBizLogic.insert(action);
}
request.setAttribute("formContextId",action.getId());
}
if(eventName != null)
{
request.setAttribute("formDisplayName", Utility.getFormattedString(eventName));
}
if(eventId != null)
{
request.getSession().setAttribute("OverrideCaption", "_" + eventId.toString());
iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=insertParentData&useApplicationStylesheet=true&showInDiv=false&overrideCSS=true&overrideScroll=true"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=")
+ eventId.toString() + "&OverrideCaption=" + "_" + eventId.toString();
if (recordIdentifier != 0)
{
iframeURL = iframeURL + "&recordIdentifier=" + recordIdentifier;
}
}
}
else
{
String actionApplicationId = request.getParameter("id");
if(actionApplicationId ==null)
{
actionApplicationId = (String) request.getAttribute("id");
}
if(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))
&& request.getSession().getAttribute("dynamicEventsForm") != null)
{
dynamicEventForm = (DynamicEventForm) request.getSession().getAttribute("dynamicEventsForm");
actionApplicationId = String.valueOf(dynamicEventForm.getId());
}
recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(dynamicEventForm
.getRecordEntry(), dynamicEventForm.getContId());
Long containerId = dynamicEventForm.getContId();
checkIsCaCoreGenerated(request, factory, containerId);
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID);
boolean isDefaultAction = true;
if(specimenId!=null && !"".equals(specimenId))
{
List<Specimen> specimentList = defaultBizLogic.retrieve(
Specimen.class.getName(), Constants.ID, specimenId);
if (specimentList != null && !specimentList.isEmpty())
{
Specimen specimen = (Specimen) specimentList.get(0);
if(specimen.getProcessingSPPApplication() != null)
{
for(ActionApplication actionApplication : new SPPEventProcessor().getFilteredActionApplication(specimen.getProcessingSPPApplication().getSppActionApplicationCollection()))
{
if(actionApplication.getId().toString().equals(actionApplicationId))
{
for(Action action : specimen.getSpecimenRequirement().getProcessingSPP().getActionCollection())
{
if(action.getContainerId().equals(containerId))
{
request.setAttribute("formContextId", action.getId());
break;
}
}
isDefaultAction = false;
break;
}
}
}
}
}
if(isDefaultAction)
{
List<DefaultAction> actionList = defaultBizLogic.retrieve(
DefaultAction.class.getName(), Constants.CONTAINER_ID, dynamicEventForm
.getContId());
+ DefaultAction action=null;
if (actionList != null && !actionList.isEmpty())
{
- DefaultAction action = (DefaultAction) actionList.get(0);
+ action = (DefaultAction) actionList.get(0);
request.setAttribute("formContextId", action.getId());
}
+ else
+ {
+ action=new DefaultAction();
+ action.setContainerId(dynamicEventForm.getContId());
+ defaultBizLogic.insert(action);
+ }
+ request.setAttribute("formContextId",action.getId());
}
dynamicEventForm.setRecordIdentifier(recordIdentifier);
iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=edit&useApplicationStylesheet=true&showInDiv=false"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=")
+ dynamicEventForm.getContId()
+ "&recordIdentifier="
+ recordIdentifier
+ "&OverrideCaption=" + "_" + dynamicEventForm.getContId();
List contList = AppUtility
.executeSQLQuery("select caption from dyextn_container where identifier="
+ dynamicEventForm.getContId());
String eventName = (String) ((List) contList.get(0)).get(0);
request.setAttribute("formDisplayName", Utility.getFormattedString(eventName));
}
if (request.getSession().getAttribute("specimenId") == null)
{
request.getSession().setAttribute("specimenId", request.getParameter("specimenId"));
}
request.setAttribute("recordIdentifier", recordIdentifier);
request.getSession().setAttribute("recordIdentifier", recordIdentifier);
request.getSession().setAttribute("containerId", dynamicEventForm.getContId());
request.getSession().setAttribute("mandatory_Message", "false");
String formContxtId = getFormContextFromRequest(request);
if(!"".equals(iframeURL))
{
iframeURL = iframeURL + "&FormContextIdentifier=" + formContxtId;
}
populateStaticAttributes(request, dynamicEventForm);
request.setAttribute("iframeURL", iframeURL+"&showCalculateDefaultValue=false");
return mapping.findForward((String) request.getAttribute(Constants.PAGE_OF));
}
private void checkIsCaCoreGenerated(HttpServletRequest request, final IFactory factory,
Long containerId)
{
final SPPBizLogic sppBizLogic = (SPPBizLogic) factory
.getBizLogic(Constants.SPP_ID);
try
{
Boolean isCaCoreGenerated=sppBizLogic.isCaCoreGenerated(containerId);
if(!isCaCoreGenerated)
{
request.setAttribute("isCaCoreGenerated", true);
}
}
catch(DynamicExtensionsCacheException e)
{
request.setAttribute("isCaCoreGenerated", true);
}
}
/**
* @param request
* @param dynamicEventForm
*/
private void resetFormParameters(HttpServletRequest request, DynamicEventForm dynamicEventForm)
{
if("edit".equals(request.getParameter(Constants.OPERATION)) && request.getSession().getAttribute(Constants.DYN_EVENT_FORM)!= null)
{
DynamicEventForm originalForm = (DynamicEventForm) request.getSession().getAttribute(Constants.DYN_EVENT_FORM);
dynamicEventForm.setContId(originalForm.getContId());
dynamicEventForm.setReasonDeviation(originalForm.getReasonDeviation());
dynamicEventForm.setRecordEntry(originalForm.getRecordEntry());
dynamicEventForm.setRecordIdentifier(originalForm.getRecordIdentifier());
dynamicEventForm.setUserId(originalForm.getUserId());
dynamicEventForm.setTimeInHours(originalForm.getTimeInHours());
dynamicEventForm.setTimeInMinutes(originalForm.getTimeInMinutes());
dynamicEventForm.setId(originalForm.getId());
}
}
/**
* @param request
* @param dynamicEventForm
*/
private void populateStaticAttributes(HttpServletRequest request,
final DynamicEventForm dynamicEventForm)
{
String sessionMapName = "formContextParameterMap"+ getFormContextFromRequest(request);
Map<String, Object> formContextParameterMap = (Map<String, Object>) request.getSession().getAttribute(sessionMapName);
if(formContextParameterMap !=null && Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR)))
{
setDateParameters(request, formContextParameterMap);
dynamicEventForm.setTimeInMinutes((String) formContextParameterMap.get("timeInMinutes"));
dynamicEventForm.setTimeInHours((String) formContextParameterMap.get("timeInHours"));
dynamicEventForm.setUserId(Long.valueOf((String)formContextParameterMap.get(Constants.USER_ID)));
dynamicEventForm.setDateOfEvent((String) formContextParameterMap.get(Constants.DATE_OF_EVENT));
dynamicEventForm.setReasonDeviation((String) formContextParameterMap.get(Constants.REASON_DEVIATION));
dynamicEventForm.setReasonDeviation((String) formContextParameterMap.get(Constants.COMMENTS));
request.getSession().removeAttribute(sessionMapName);
request.getSession().removeAttribute(Constants.DYN_EVENT_FORM);
}
}
/**
* @param request
* @param formContextParameterMap
*/
private void setDateParameters(HttpServletRequest request,
Map<String, Object> formContextParameterMap)
{
if(formContextParameterMap.get(Constants.DATE_OF_EVENT)!= null)
{
String currentEventParametersDate = (String) formContextParameterMap.get(Constants.DATE_OF_EVENT);
request.setAttribute("currentEventParametersDate", currentEventParametersDate);
request.setAttribute("dynamicEventParametersYear", AppUtility
.getYear(currentEventParametersDate));
request.setAttribute("dynamicEventParametersDay", AppUtility
.getDay(currentEventParametersDate));
request.setAttribute("dynamicEventParametersMonth", AppUtility
.getMonth(currentEventParametersDate));
}
}
/**
* @param request
* @return
*/
private String getFormContextFromRequest(HttpServletRequest request)
{
String formContxtId = request.getParameter("formContextId");
if(formContxtId == null)
{
formContxtId = String.valueOf(request.getAttribute("formContextId"));
}
return formContxtId;
}
}
| false | true | protected ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
if (request.getParameter(Constants.REFRESH_EVENT_GRID) != null)
{
request.setAttribute(Constants.REFRESH_EVENT_GRID, request
.getParameter(Constants.REFRESH_EVENT_GRID));
}
//this.setCommonRequestParameters(request);
DynamicEventForm dynamicEventForm = (DynamicEventForm) form;
resetFormParameters(request, dynamicEventForm);
// if operation is add
if (dynamicEventForm.isAddOperation())
{
if (dynamicEventForm.getUserId() == 0)
{
final SessionDataBean sessionData = this.getSessionData(request);
if (sessionData != null && sessionData.getUserId() != null)
{
final long userId = sessionData.getUserId().longValue();
dynamicEventForm.setUserId(userId);
}
}
// set the current Date and Time for the event.
final Calendar cal = Calendar.getInstance();
if (dynamicEventForm.getDateOfEvent() == null)
{
dynamicEventForm.setDateOfEvent(CommonUtilities.parseDateToString(cal.getTime(),
CommonServiceLocator.getInstance().getDatePattern()));
}
if (dynamicEventForm.getTimeInHours() == null)
{
dynamicEventForm.setTimeInHours(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)));
}
if (dynamicEventForm.getTimeInMinutes() == null)
{
dynamicEventForm.setTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE)));
}
}
else
{
String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID);
if (specimenId == null)
{
request.setAttribute(Constants.SPECIMEN_ID, specimenId);
}
}
String reasonDeviation = "";
reasonDeviation = dynamicEventForm.getReasonDeviation();
if (reasonDeviation == null)
{
reasonDeviation = "";
}
String currentEventParametersDate = "";
currentEventParametersDate = dynamicEventForm.getDateOfEvent();
if (currentEventParametersDate == null)
{
currentEventParametersDate = "";
}
final Integer dynamicEventParametersYear = new Integer(AppUtility
.getYear(currentEventParametersDate));
final Integer dynamicEventParametersMonth = new Integer(AppUtility
.getMonth(currentEventParametersDate));
final Integer dynamicEventParametersDay = new Integer(AppUtility
.getDay(currentEventParametersDate));
request.setAttribute("minutesList", Constants.MINUTES_ARRAY);
// Sets the hourList attribute to be used in the Add/Edit
// FrozenEventParameters Page.
request.setAttribute("hourList", Constants.HOUR_ARRAY);
request.setAttribute("dynamicEventParametersYear", dynamicEventParametersYear);
request.setAttribute("dynamicEventParametersDay", dynamicEventParametersDay);
request.setAttribute("dynamicEventParametersMonth", dynamicEventParametersMonth);
request.setAttribute("formName", Constants.DYNAMIC_EVENT_ACTION);
request.setAttribute("addForJSP", Constants.ADD);
request.setAttribute("editForJSP", Constants.EDIT);
request.setAttribute("reasonDeviation", reasonDeviation);
request.setAttribute("userListforJSP", Constants.USERLIST);
request.setAttribute("currentEventParametersDate", currentEventParametersDate);
request.setAttribute(Constants.PAGE_OF, "pageOfDynamicEvent");
request.setAttribute(Constants.SPECIMEN_ID, request.getSession().getAttribute(
Constants.SPECIMEN_ID));
//request.setAttribute(Constants.SPECIMEN_ID, request.getAttribute(Constants.SPECIMEN_ID));
//request.setAttribute(Constants.PAGE_OF, request.getParameter(Constants.PAGE_OF));
//request.setAttribute("changeAction", Constants.CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION);
final String operation = request.getParameter(Constants.OPERATION);
final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory();
final UserBizLogic userBizLogic = (UserBizLogic) factory
.getBizLogic(Constants.USER_FORM_ID);
final Collection userCollection = userBizLogic.getUsers(operation);
request.setAttribute(Constants.USERLIST, userCollection);
HashMap dynamicEventMap = (HashMap) request.getSession().getAttribute("dynamicEventMap");
String iframeURL="";
long recordIdentifier=0;
Long eventId=null;
if(dynamicEventForm.getOperation().equals(Constants.ADD))
{
String eventName = request.getParameter("eventName");
if(eventName == null)
{
eventName = (String)request.getSession().getAttribute("eventName");
}
request.getSession().setAttribute("eventName", eventName);
dynamicEventForm.setEventName(eventName);
eventId=(Long) dynamicEventMap.get(eventName);
checkIsCaCoreGenerated(request, factory, eventId);
if (Boolean.parseBoolean(request.getParameter("showDefaultValues")))
{
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
List<Action> actionList = defaultBizLogic.retrieve(Action.class.getName(),
Constants.ID, request.getParameter("formContextId"));
if (actionList != null && !actionList.isEmpty())
{
Action action = (Action) actionList.get(0);
if (action.getApplicationDefaultValue() != null)
{
recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(action
.getApplicationDefaultValue().getId(), action.getContainerId());
}
}
}
else
{
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
List<DefaultAction> actionList = defaultBizLogic.retrieve(DefaultAction.class
.getName(), Constants.CONTAINER_ID, eventId);
DefaultAction action =null;
if (actionList != null && !actionList.isEmpty())
{
action = (DefaultAction) actionList.get(0);
}
else
{
action=new DefaultAction();
action.setContainerId(eventId);
defaultBizLogic.insert(action);
}
request.setAttribute("formContextId",action.getId());
}
if(eventName != null)
{
request.setAttribute("formDisplayName", Utility.getFormattedString(eventName));
}
if(eventId != null)
{
request.getSession().setAttribute("OverrideCaption", "_" + eventId.toString());
iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=insertParentData&useApplicationStylesheet=true&showInDiv=false&overrideCSS=true&overrideScroll=true"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=")
+ eventId.toString() + "&OverrideCaption=" + "_" + eventId.toString();
if (recordIdentifier != 0)
{
iframeURL = iframeURL + "&recordIdentifier=" + recordIdentifier;
}
}
}
else
{
String actionApplicationId = request.getParameter("id");
if(actionApplicationId ==null)
{
actionApplicationId = (String) request.getAttribute("id");
}
if(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))
&& request.getSession().getAttribute("dynamicEventsForm") != null)
{
dynamicEventForm = (DynamicEventForm) request.getSession().getAttribute("dynamicEventsForm");
actionApplicationId = String.valueOf(dynamicEventForm.getId());
}
recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(dynamicEventForm
.getRecordEntry(), dynamicEventForm.getContId());
Long containerId = dynamicEventForm.getContId();
checkIsCaCoreGenerated(request, factory, containerId);
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID);
boolean isDefaultAction = true;
if(specimenId!=null && !"".equals(specimenId))
{
List<Specimen> specimentList = defaultBizLogic.retrieve(
Specimen.class.getName(), Constants.ID, specimenId);
if (specimentList != null && !specimentList.isEmpty())
{
Specimen specimen = (Specimen) specimentList.get(0);
if(specimen.getProcessingSPPApplication() != null)
{
for(ActionApplication actionApplication : new SPPEventProcessor().getFilteredActionApplication(specimen.getProcessingSPPApplication().getSppActionApplicationCollection()))
{
if(actionApplication.getId().toString().equals(actionApplicationId))
{
for(Action action : specimen.getSpecimenRequirement().getProcessingSPP().getActionCollection())
{
if(action.getContainerId().equals(containerId))
{
request.setAttribute("formContextId", action.getId());
break;
}
}
isDefaultAction = false;
break;
}
}
}
}
}
if(isDefaultAction)
{
List<DefaultAction> actionList = defaultBizLogic.retrieve(
DefaultAction.class.getName(), Constants.CONTAINER_ID, dynamicEventForm
.getContId());
if (actionList != null && !actionList.isEmpty())
{
DefaultAction action = (DefaultAction) actionList.get(0);
request.setAttribute("formContextId", action.getId());
}
}
dynamicEventForm.setRecordIdentifier(recordIdentifier);
iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=edit&useApplicationStylesheet=true&showInDiv=false"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=")
+ dynamicEventForm.getContId()
+ "&recordIdentifier="
+ recordIdentifier
+ "&OverrideCaption=" + "_" + dynamicEventForm.getContId();
List contList = AppUtility
.executeSQLQuery("select caption from dyextn_container where identifier="
+ dynamicEventForm.getContId());
String eventName = (String) ((List) contList.get(0)).get(0);
request.setAttribute("formDisplayName", Utility.getFormattedString(eventName));
}
if (request.getSession().getAttribute("specimenId") == null)
{
request.getSession().setAttribute("specimenId", request.getParameter("specimenId"));
}
request.setAttribute("recordIdentifier", recordIdentifier);
request.getSession().setAttribute("recordIdentifier", recordIdentifier);
request.getSession().setAttribute("containerId", dynamicEventForm.getContId());
request.getSession().setAttribute("mandatory_Message", "false");
String formContxtId = getFormContextFromRequest(request);
if(!"".equals(iframeURL))
{
iframeURL = iframeURL + "&FormContextIdentifier=" + formContxtId;
}
populateStaticAttributes(request, dynamicEventForm);
request.setAttribute("iframeURL", iframeURL+"&showCalculateDefaultValue=false");
return mapping.findForward((String) request.getAttribute(Constants.PAGE_OF));
}
| protected ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
if (request.getParameter(Constants.REFRESH_EVENT_GRID) != null)
{
request.setAttribute(Constants.REFRESH_EVENT_GRID, request
.getParameter(Constants.REFRESH_EVENT_GRID));
}
//this.setCommonRequestParameters(request);
DynamicEventForm dynamicEventForm = (DynamicEventForm) form;
resetFormParameters(request, dynamicEventForm);
// if operation is add
if (dynamicEventForm.isAddOperation())
{
if (dynamicEventForm.getUserId() == 0)
{
final SessionDataBean sessionData = this.getSessionData(request);
if (sessionData != null && sessionData.getUserId() != null)
{
final long userId = sessionData.getUserId().longValue();
dynamicEventForm.setUserId(userId);
}
}
// set the current Date and Time for the event.
final Calendar cal = Calendar.getInstance();
if (dynamicEventForm.getDateOfEvent() == null)
{
dynamicEventForm.setDateOfEvent(CommonUtilities.parseDateToString(cal.getTime(),
CommonServiceLocator.getInstance().getDatePattern()));
}
if (dynamicEventForm.getTimeInHours() == null)
{
dynamicEventForm.setTimeInHours(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)));
}
if (dynamicEventForm.getTimeInMinutes() == null)
{
dynamicEventForm.setTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE)));
}
}
else
{
String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID);
if (specimenId == null)
{
request.setAttribute(Constants.SPECIMEN_ID, specimenId);
}
}
String reasonDeviation = "";
reasonDeviation = dynamicEventForm.getReasonDeviation();
if (reasonDeviation == null)
{
reasonDeviation = "";
}
String currentEventParametersDate = "";
currentEventParametersDate = dynamicEventForm.getDateOfEvent();
if (currentEventParametersDate == null)
{
currentEventParametersDate = "";
}
final Integer dynamicEventParametersYear = new Integer(AppUtility
.getYear(currentEventParametersDate));
final Integer dynamicEventParametersMonth = new Integer(AppUtility
.getMonth(currentEventParametersDate));
final Integer dynamicEventParametersDay = new Integer(AppUtility
.getDay(currentEventParametersDate));
request.setAttribute("minutesList", Constants.MINUTES_ARRAY);
// Sets the hourList attribute to be used in the Add/Edit
// FrozenEventParameters Page.
request.setAttribute("hourList", Constants.HOUR_ARRAY);
request.setAttribute("dynamicEventParametersYear", dynamicEventParametersYear);
request.setAttribute("dynamicEventParametersDay", dynamicEventParametersDay);
request.setAttribute("dynamicEventParametersMonth", dynamicEventParametersMonth);
request.setAttribute("formName", Constants.DYNAMIC_EVENT_ACTION);
request.setAttribute("addForJSP", Constants.ADD);
request.setAttribute("editForJSP", Constants.EDIT);
request.setAttribute("reasonDeviation", reasonDeviation);
request.setAttribute("userListforJSP", Constants.USERLIST);
request.setAttribute("currentEventParametersDate", currentEventParametersDate);
request.setAttribute(Constants.PAGE_OF, "pageOfDynamicEvent");
request.setAttribute(Constants.SPECIMEN_ID, request.getSession().getAttribute(
Constants.SPECIMEN_ID));
//request.setAttribute(Constants.SPECIMEN_ID, request.getAttribute(Constants.SPECIMEN_ID));
//request.setAttribute(Constants.PAGE_OF, request.getParameter(Constants.PAGE_OF));
//request.setAttribute("changeAction", Constants.CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION);
final String operation = request.getParameter(Constants.OPERATION);
final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory();
final UserBizLogic userBizLogic = (UserBizLogic) factory
.getBizLogic(Constants.USER_FORM_ID);
final Collection userCollection = userBizLogic.getUsers(operation);
request.setAttribute(Constants.USERLIST, userCollection);
HashMap dynamicEventMap = (HashMap) request.getSession().getAttribute("dynamicEventMap");
String iframeURL="";
long recordIdentifier=0;
Long eventId=null;
if(dynamicEventForm.getOperation().equals(Constants.ADD))
{
String eventName = request.getParameter("eventName");
if(eventName == null)
{
eventName = (String)request.getSession().getAttribute("eventName");
}
request.getSession().setAttribute("eventName", eventName);
dynamicEventForm.setEventName(eventName);
eventId=(Long) dynamicEventMap.get(eventName);
checkIsCaCoreGenerated(request, factory, eventId);
if (Boolean.parseBoolean(request.getParameter("showDefaultValues")))
{
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
List<Action> actionList = defaultBizLogic.retrieve(Action.class.getName(),
Constants.ID, request.getParameter("formContextId"));
if (actionList != null && !actionList.isEmpty())
{
Action action = (Action) actionList.get(0);
if (action.getApplicationDefaultValue() != null)
{
recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(action
.getApplicationDefaultValue().getId(), action.getContainerId());
}
}
}
else
{
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
List<DefaultAction> actionList = defaultBizLogic.retrieve(DefaultAction.class
.getName(), Constants.CONTAINER_ID, eventId);
DefaultAction action =null;
if (actionList != null && !actionList.isEmpty())
{
action = (DefaultAction) actionList.get(0);
}
else
{
action=new DefaultAction();
action.setContainerId(eventId);
defaultBizLogic.insert(action);
}
request.setAttribute("formContextId",action.getId());
}
if(eventName != null)
{
request.setAttribute("formDisplayName", Utility.getFormattedString(eventName));
}
if(eventId != null)
{
request.getSession().setAttribute("OverrideCaption", "_" + eventId.toString());
iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=insertParentData&useApplicationStylesheet=true&showInDiv=false&overrideCSS=true&overrideScroll=true"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=")
+ eventId.toString() + "&OverrideCaption=" + "_" + eventId.toString();
if (recordIdentifier != 0)
{
iframeURL = iframeURL + "&recordIdentifier=" + recordIdentifier;
}
}
}
else
{
String actionApplicationId = request.getParameter("id");
if(actionApplicationId ==null)
{
actionApplicationId = (String) request.getAttribute("id");
}
if(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))
&& request.getSession().getAttribute("dynamicEventsForm") != null)
{
dynamicEventForm = (DynamicEventForm) request.getSession().getAttribute("dynamicEventsForm");
actionApplicationId = String.valueOf(dynamicEventForm.getId());
}
recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(dynamicEventForm
.getRecordEntry(), dynamicEventForm.getContId());
Long containerId = dynamicEventForm.getContId();
checkIsCaCoreGenerated(request, factory, containerId);
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID);
boolean isDefaultAction = true;
if(specimenId!=null && !"".equals(specimenId))
{
List<Specimen> specimentList = defaultBizLogic.retrieve(
Specimen.class.getName(), Constants.ID, specimenId);
if (specimentList != null && !specimentList.isEmpty())
{
Specimen specimen = (Specimen) specimentList.get(0);
if(specimen.getProcessingSPPApplication() != null)
{
for(ActionApplication actionApplication : new SPPEventProcessor().getFilteredActionApplication(specimen.getProcessingSPPApplication().getSppActionApplicationCollection()))
{
if(actionApplication.getId().toString().equals(actionApplicationId))
{
for(Action action : specimen.getSpecimenRequirement().getProcessingSPP().getActionCollection())
{
if(action.getContainerId().equals(containerId))
{
request.setAttribute("formContextId", action.getId());
break;
}
}
isDefaultAction = false;
break;
}
}
}
}
}
if(isDefaultAction)
{
List<DefaultAction> actionList = defaultBizLogic.retrieve(
DefaultAction.class.getName(), Constants.CONTAINER_ID, dynamicEventForm
.getContId());
DefaultAction action=null;
if (actionList != null && !actionList.isEmpty())
{
action = (DefaultAction) actionList.get(0);
request.setAttribute("formContextId", action.getId());
}
else
{
action=new DefaultAction();
action.setContainerId(dynamicEventForm.getContId());
defaultBizLogic.insert(action);
}
request.setAttribute("formContextId",action.getId());
}
dynamicEventForm.setRecordIdentifier(recordIdentifier);
iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=edit&useApplicationStylesheet=true&showInDiv=false"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=")
+ dynamicEventForm.getContId()
+ "&recordIdentifier="
+ recordIdentifier
+ "&OverrideCaption=" + "_" + dynamicEventForm.getContId();
List contList = AppUtility
.executeSQLQuery("select caption from dyextn_container where identifier="
+ dynamicEventForm.getContId());
String eventName = (String) ((List) contList.get(0)).get(0);
request.setAttribute("formDisplayName", Utility.getFormattedString(eventName));
}
if (request.getSession().getAttribute("specimenId") == null)
{
request.getSession().setAttribute("specimenId", request.getParameter("specimenId"));
}
request.setAttribute("recordIdentifier", recordIdentifier);
request.getSession().setAttribute("recordIdentifier", recordIdentifier);
request.getSession().setAttribute("containerId", dynamicEventForm.getContId());
request.getSession().setAttribute("mandatory_Message", "false");
String formContxtId = getFormContextFromRequest(request);
if(!"".equals(iframeURL))
{
iframeURL = iframeURL + "&FormContextIdentifier=" + formContxtId;
}
populateStaticAttributes(request, dynamicEventForm);
request.setAttribute("iframeURL", iframeURL+"&showCalculateDefaultValue=false");
return mapping.findForward((String) request.getAttribute(Constants.PAGE_OF));
}
|
diff --git a/jsonrpc4j/src/main/java/com/googlecode/jsonrpc4j/JsonRpcClient.java b/jsonrpc4j/src/main/java/com/googlecode/jsonrpc4j/JsonRpcClient.java
index 7178cd6..7719ba6 100644
--- a/jsonrpc4j/src/main/java/com/googlecode/jsonrpc4j/JsonRpcClient.java
+++ b/jsonrpc4j/src/main/java/com/googlecode/jsonrpc4j/JsonRpcClient.java
@@ -1,167 +1,169 @@
package com.googlecode.jsonrpc4j;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.util.Random;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
import org.codehaus.jackson.node.ObjectNode;
/**
* A JSON-RPC client.
*/
public class JsonRpcClient {
private static final String JSON_RPC_VERSION = "2.0";
private ObjectMapper mapper;
private Random random;
/**
* Creates the {@link JsonRpcHttpClient} bound to the given {@code serviceUrl}.
* The headers provided in the {@code headers} map are added to every request
* made to the {@code serviceUrl}.
*
* @param serviceUrl the URL
*/
public JsonRpcClient(ObjectMapper mapper) {
this.mapper = mapper;
this.random = new Random(System.currentTimeMillis());
}
/**
* Creates the {@link JsonRpcHttpClient} bound to the given {@code serviceUrl}.
* The headers provided in the {@code headers} map are added to every request
* made to the {@code serviceUrl}.
*
* @param serviceUrl the URL
*/
public JsonRpcClient() {
this(new ObjectMapper());
}
/**
* Invokes the given method with the given arguments and returns
* an object of the given type, or null if void.
*
* @param methodName the name of the method to invoke
* @param arguments the arguments to the method
* @param returnType the return type
* @param extraHeaders extra headers to add to the request
* @return the return value
* @throws Exception on error
*/
public Object invokeAndReadResponse(
String methodName, Object[] arguments, Type returnType,
OutputStream ops, InputStream ips)
throws Exception {
// invoke it
invoke(methodName, arguments, ops);
// read it
return readResponse(returnType, ips);
}
/**
* Invokes the given method with the given arguments and returns
* an object of the given type, or null if void.
*
* @param methodName the name of the method to invoke
* @param arguments the arguments to the method
* @param returnType the return type
* @throws Exception on error
*/
public void invoke(
String methodName, Object[] arguments, OutputStream ops)
throws Exception {
writeRequest(methodName, arguments, ops, random.nextLong()+"");
ops.flush();
}
/**
* Reads the response from the server.
*
* @param returnType the expected return type
* @param ips the {@link InnputStream} to read the response from
* @return the object
* @throws IOException
* @throws JsonProcessingException
* @throws Exception
* @throws JsonParseException
* @throws JsonMappingException
*/
public Object readResponse(Type returnType, InputStream ips)
throws IOException,
JsonProcessingException,
Exception,
JsonParseException,
JsonMappingException {
// read the response
JsonNode response = mapper.readTree(ips);
// bail on invalid response
if (!response.isObject()) {
throw new Exception("Invalid JSON-RPC response");
}
ObjectNode jsonObject = ObjectNode.class.cast(response);
// detect errors
if (jsonObject.has("error")
&& jsonObject.get("error")!=null
&& !jsonObject.get("error").isNull()) {
ObjectNode errorObject = ObjectNode.class.cast(jsonObject.get("error"));
throw new Exception(
"JSON-RPC Error "+errorObject.get("code")+": "+errorObject.get("message"));
}
// convert it to a return object
- if (jsonObject.has("result")) {
+ if (jsonObject.has("result")
+ && !jsonObject.get("result").isNull()
+ && jsonObject.get("result")!=null) {
return mapper.readValue(
jsonObject.get("result"), TypeFactory.type(returnType));
}
// no return type
return null;
}
/**
* Writes a request to the server.
*
* @param methodName the method to invoke
* @param arguments the method arguments
* @param ops the {@link OutputStream}
* @param id the id
* @throws IOException
* @throws JsonGenerationException
* @throws JsonMappingException
*/
public void writeRequest(
String methodName, Object[] arguments, OutputStream ops, String id)
throws IOException,
JsonGenerationException,
JsonMappingException {
// create the request
ObjectNode request = mapper.createObjectNode();
request.put("id", id);
request.put("jsonrpc", JSON_RPC_VERSION);
request.put("method", methodName);
request.put("params", mapper.valueToTree(arguments));
// post the json data;
mapper.writeValue(ops, request);
}
}
| true | true | public Object readResponse(Type returnType, InputStream ips)
throws IOException,
JsonProcessingException,
Exception,
JsonParseException,
JsonMappingException {
// read the response
JsonNode response = mapper.readTree(ips);
// bail on invalid response
if (!response.isObject()) {
throw new Exception("Invalid JSON-RPC response");
}
ObjectNode jsonObject = ObjectNode.class.cast(response);
// detect errors
if (jsonObject.has("error")
&& jsonObject.get("error")!=null
&& !jsonObject.get("error").isNull()) {
ObjectNode errorObject = ObjectNode.class.cast(jsonObject.get("error"));
throw new Exception(
"JSON-RPC Error "+errorObject.get("code")+": "+errorObject.get("message"));
}
// convert it to a return object
if (jsonObject.has("result")) {
return mapper.readValue(
jsonObject.get("result"), TypeFactory.type(returnType));
}
// no return type
return null;
}
| public Object readResponse(Type returnType, InputStream ips)
throws IOException,
JsonProcessingException,
Exception,
JsonParseException,
JsonMappingException {
// read the response
JsonNode response = mapper.readTree(ips);
// bail on invalid response
if (!response.isObject()) {
throw new Exception("Invalid JSON-RPC response");
}
ObjectNode jsonObject = ObjectNode.class.cast(response);
// detect errors
if (jsonObject.has("error")
&& jsonObject.get("error")!=null
&& !jsonObject.get("error").isNull()) {
ObjectNode errorObject = ObjectNode.class.cast(jsonObject.get("error"));
throw new Exception(
"JSON-RPC Error "+errorObject.get("code")+": "+errorObject.get("message"));
}
// convert it to a return object
if (jsonObject.has("result")
&& !jsonObject.get("result").isNull()
&& jsonObject.get("result")!=null) {
return mapper.readValue(
jsonObject.get("result"), TypeFactory.type(returnType));
}
// no return type
return null;
}
|
diff --git a/org/jruby/KernelModule.java b/org/jruby/KernelModule.java
index decaaf21a..986813f4b 100644
--- a/org/jruby/KernelModule.java
+++ b/org/jruby/KernelModule.java
@@ -1,490 +1,490 @@
/*
* RubyKernel.java
* Created on May 2, 2002
*
* Copyright (C) 2001, 2002 Jan Arne Petersen, Alan Moore, Benoit Cerrina,
* Chad Fowler, Anders Bengtsson
* Jan Arne Petersen <[email protected]>
* Alan Moore <[email protected]>
* Benoit Cerrina <[email protected]>
* Chad Fowler <[email protected]>
* Anders Bengtsson <[email protected]>
*
* JRuby - http://jruby.sourceforge.net
*
* This file is part of JRuby
*
* JRuby is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* JRuby is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JRuby; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package org.jruby;
import java.util.*;
import java.io.*;
import org.jruby.internal.runtime.builtin.definitions.Kernel;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.exceptions.EOFError;
import org.jruby.exceptions.TypeError;
import org.jruby.exceptions.ArgumentError;
import org.jruby.exceptions.RaiseException;
import org.jruby.exceptions.ThrowJump;
import org.jruby.exceptions.NotImplementedError;
/**
*
* @author jpetersen
* @version $Revision$
*/
public class KernelModule {
public static RubyModule createKernelModule(Ruby runtime) {
return new Kernel(runtime).getModule();
}
public static IRubyObject open(IRubyObject recv, IRubyObject[] args) {
if (args[0].toString().startsWith("|")) {
// +++
return recv.getRuntime().getNil();
// ---
}
return RubyFile.open(recv.getRuntime().getClasses().getFileClass(), args);
}
public static RubyString gets(IRubyObject recv, IRubyObject[] args) {
RubyArgsFile argsFile = (RubyArgsFile) recv.getRuntime().getGlobalVar("$<");
RubyString line = argsFile.internalGets(args);
recv.getRuntime().setLastline(line);
return line;
}
public static IRubyObject p(IRubyObject recv, IRubyObject args[]) {
IRubyObject defout = recv.getRuntime().getGlobalVar("$>");
for (int i = 0; i < args.length; i++) {
if (args[i] != null) {
defout.callMethod("write", args[i].callMethod("inspect"));
defout.callMethod("write", RubyString.newString(recv.getRuntime(), "\n"));
}
}
return recv.getRuntime().getNil();
}
public static IRubyObject puts(IRubyObject recv, IRubyObject args[]) {
IRubyObject defout = recv.getRuntime().getGlobalVar("$>");
RubyIO.puts(defout, args);
return recv.getRuntime().getNil();
}
public static IRubyObject print(IRubyObject recv, IRubyObject args[]) {
IRubyObject defout = recv.getRuntime().getGlobalVar("$>");
RubyIO.print(defout, args);
return recv.getRuntime().getNil();
}
public static IRubyObject printf(IRubyObject recv, IRubyObject args[]) {
if (args.length != 0) {
IRubyObject defout = recv.getRuntime().getGlobalVar("$>");
if (!(args[0] instanceof RubyString)) {
defout = args[0];
IRubyObject[] newArgs = new IRubyObject[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, args.length - 1);
args = newArgs;
}
RubyIO.printf(defout, args);
}
return recv.getRuntime().getNil();
}
public static RubyString readline(IRubyObject recv, IRubyObject[] args) {
RubyString line = gets(recv, args);
if (line.isNil()) {
throw new EOFError(recv.getRuntime());
}
return line;
}
public static RubyArray readlines(IRubyObject recv, IRubyObject[] args) {
RubyArgsFile argsFile = (RubyArgsFile) recv.getRuntime().getGlobalVar("$<");
RubyArray lines = RubyArray.newArray(recv.getRuntime());
RubyString line = argsFile.internalGets(args);
while (!line.isNil()) {
lines.append(line);
line = argsFile.internalGets(args);
}
return lines;
}
/** Returns value of $_.
*
* @throws TypeError if $_ is not a String or nil.
* @return value of $_ as String.
*/
private static RubyString getLastlineString(Ruby ruby) {
IRubyObject line = ruby.getLastline();
if (line.isNil()) {
throw new TypeError(ruby, "$_ value need to be String (nil given).");
} else if (!(line instanceof RubyString)) {
throw new TypeError(ruby, "$_ value need to be String (" + line.getInternalClass().toName() + " given).");
} else {
return (RubyString) line;
}
}
public static IRubyObject sub_bang(IRubyObject recv, IRubyObject args[]) {
return getLastlineString(recv.getRuntime()).sub_bang(args);
}
public static IRubyObject sub(IRubyObject recv, IRubyObject args[]) {
RubyString str = (RubyString) getLastlineString(recv.getRuntime()).dup();
if (!str.sub_bang(args).isNil()) {
recv.getRuntime().setLastline(str);
}
return str;
}
public static IRubyObject gsub_bang(IRubyObject recv, IRubyObject args[]) {
return getLastlineString(recv.getRuntime()).gsub_bang(args);
}
public static IRubyObject gsub(IRubyObject recv, IRubyObject args[]) {
RubyString str = (RubyString) getLastlineString(recv.getRuntime()).dup();
if (!str.gsub_bang(args).isNil()) {
recv.getRuntime().setLastline(str);
}
return str;
}
public static IRubyObject chop_bang(IRubyObject recv) {
return getLastlineString(recv.getRuntime()).chop_bang();
}
public static IRubyObject chop(IRubyObject recv) {
RubyString str = getLastlineString(recv.getRuntime());
if (str.getValue().length() > 0) {
str = (RubyString) str.dup();
str.chop_bang();
recv.getRuntime().setLastline(str);
}
return str;
}
public static IRubyObject chomp_bang(IRubyObject recv, IRubyObject[] args) {
return getLastlineString(recv.getRuntime()).chomp_bang(args);
}
public static IRubyObject chomp(IRubyObject recv, IRubyObject[] args) {
RubyString str = getLastlineString(recv.getRuntime());
RubyString dup = (RubyString) str.dup();
if (dup.chomp_bang(args).isNil()) {
return str;
} else {
recv.getRuntime().setLastline(dup);
return str;
}
}
public static IRubyObject split(IRubyObject recv, IRubyObject[] args) {
return getLastlineString(recv.getRuntime()).split(args);
}
public static IRubyObject scan(IRubyObject recv, IRubyObject pattern) {
return getLastlineString(recv.getRuntime()).scan(pattern);
}
public static IRubyObject sleep(IRubyObject recv, IRubyObject seconds) {
try {
Thread.sleep((long) (RubyNumeric.numericValue(seconds).getDoubleValue() * 1000.0));
} catch (InterruptedException iExcptn) {
}
return recv;
}
public static IRubyObject exit(IRubyObject recv, IRubyObject args[]) {
int status = 0;
if (args.length > 0) {
status = RubyNumeric.fix2int(args[0]);
}
System.exit(status);
return recv.getRuntime().getNil();
}
/** Returns an Array with the names of all global variables.
*
*/
public static RubyArray global_variables(IRubyObject recv) {
RubyArray globalVariables = RubyArray.newArray(recv.getRuntime());
Iterator iter = recv.getRuntime().globalVariableNames();
while (iter.hasNext()) {
String globalVariableName = (String) iter.next();
globalVariables.append(RubyString.newString(recv.getRuntime(), globalVariableName));
}
return globalVariables;
}
/** Returns an Array with the names of all local variables.
*
*/
public static RubyArray local_variables(IRubyObject recv) {
RubyArray localVariables = RubyArray.newArray(recv.getRuntime());
if (recv.getRuntime().getScope().getLocalNames() != null) {
for (int i = 2; i < recv.getRuntime().getScope().getLocalNames().size(); i++) {
if (recv.getRuntime().getScope().getLocalNames().get(i) != null) {
localVariables.append(RubyString.newString(recv.getRuntime(), (String) recv.getRuntime().getScope().getLocalNames().get(i)));
}
}
}
Iterator dynamicNames = recv.getRuntime().getDynamicNames().iterator();
while (dynamicNames.hasNext()) {
String name = (String) dynamicNames.next();
localVariables.append(RubyString.newString(recv.getRuntime(), name));
}
return localVariables;
}
public static RubyBoolean block_given(IRubyObject recv) {
return RubyBoolean.newBoolean(recv.getRuntime(), recv.getRuntime().isFBlockGiven());
}
public static IRubyObject sprintf(IRubyObject recv, IRubyObject args[]) {
if (args.length == 0) {
throw new ArgumentError(recv.getRuntime(), "sprintf must have at least one argument");
}
RubyString str = RubyString.stringValue(args[0]);
RubyArray newArgs = RubyArray.newArray(recv.getRuntime(), args);
newArgs.shift();
return str.format(newArgs);
}
public static IRubyObject raise(IRubyObject recv, IRubyObject args[]) {
switch (args.length) {
case 0 :
case 1 :
if (args[0] instanceof RubyException) {
throw new RaiseException((RubyException) args[0]);
} else {
throw new RaiseException(RubyException.newInstance(recv.getRuntime().getExceptions().getRuntimeError(), args));
}
case 2 :
RubyException excptn = (RubyException) args[0].callMethod("exception", args[1]);
throw new RaiseException(excptn);
default :
throw new ArgumentError(recv.getRuntime(), "wrong # of arguments");
}
}
/**
* Require.
* MRI allows to require ever .rb files or ruby extension dll (.so or .dll depending on system).
* we allow requiring either .rb files or jars.
* @param recv ruby object used to call require (any object will do and it won't be used anyway).
* @param file the name of the file to require
**/
public static IRubyObject require(IRubyObject recv, IRubyObject file) {
if (recv.getRuntime().getLoadService().require(file.toString())) {
return recv.getRuntime().getTrue();
}
return recv.getRuntime().getFalse();
}
public static IRubyObject load(IRubyObject recv, IRubyObject[] args) {
RubyString file = (RubyString)args[0];
if (recv.getRuntime().getLoadService().load(file.toString())) {
return recv.getRuntime().getTrue();
}
return recv.getRuntime().getFalse();
}
public static IRubyObject eval(IRubyObject recv, IRubyObject[] args) {
RubyString src = (RubyString)args[0];
- IRubyObject scope = args.length > 0 ? args[1] : recv.getRuntime().getNil();
+ IRubyObject scope = args.length > 1 ? args[1] : recv.getRuntime().getNil();
String file = "(eval)";
int line = 1;
if (args.length > 2) {
// +++
file = args[2].toString();
// ---
}
if (args.length > 3) {
line = RubyFixnum.fix2int(args[3]);
}
// +++
src.checkSafeString();
// ---
if (scope.isNil() && recv.getRuntime().getFrameStack().getPrevious() != null) {
try {
// XXX
recv.getRuntime().getFrameStack().push(recv.getRuntime().getFrameStack().getPrevious());
return recv.eval(src, scope, file, line);
} finally {
recv.getRuntime().getFrameStack().pop();
}
}
return recv.eval(src, scope, file, line);
}
public static IRubyObject caller(IRubyObject recv, IRubyObject[] args) {
int level = args.length > 0 ? RubyFixnum.fix2int(args[0]) : 1;
if (level < 0) {
throw new ArgumentError(recv.getRuntime(), "negative level(" + level + ')');
}
return RaiseException.createBacktrace(recv.getRuntime(), level);
}
public static IRubyObject rbCatch(IRubyObject recv, IRubyObject tag) {
try {
return recv.getRuntime().yield(tag);
} catch (ThrowJump throwJump) {
if (throwJump.getTag().equals(tag.toId())) {
return throwJump.getValue();
} else {
throw throwJump;
}
}
}
public static IRubyObject rbThrow(IRubyObject recv, IRubyObject[] args) {
throw new ThrowJump(args[0].toId(), args.length > 1 ? args[1] : recv.getRuntime().getNil());
}
public static IRubyObject set_trace_func(IRubyObject recv, IRubyObject trace_func) {
if (trace_func.isNil()) {
recv.getRuntime().getRuntime().setTraceFunction(null);
} else if (!(trace_func instanceof RubyProc)) {
throw new TypeError(recv.getRuntime(), "trace_func needs to be Proc.");
}
recv.getRuntime().getRuntime().setTraceFunction((RubyProc) trace_func);
return trace_func;
}
public static RubyProc proc(IRubyObject recv) {
return RubyProc.newProc(recv.getRuntime(), recv.getRuntime().getClasses().getProcClass());
}
public static IRubyObject loop(IRubyObject recv) {
while (true) {
recv.getRuntime().yield(recv.getRuntime().getNil());
Thread.yield();
}
}
public static IRubyObject backquote(IRubyObject recv, IRubyObject aString) {
// FIXME clean this up.
try {
String lShellProp = System.getProperty("jruby.shell");
Process aProcess;
String lCommand = aString.toString();
String lSwitch = "-c";
if (lShellProp != null) {
if (!lShellProp.endsWith("sh")) { //case windowslike
lSwitch = "/c";
}
aProcess = Runtime.getRuntime().exec(new String[] { lShellProp, lSwitch, lCommand });
} else {
aProcess = Runtime.getRuntime().exec(lCommand);
}
final StringBuffer sb = new StringBuffer();
final BufferedReader reader = new BufferedReader(new InputStreamReader(aProcess.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
aProcess.waitFor();
return RubyString.newString(recv.getRuntime(), sb.toString());
} catch (Exception excptn) {
excptn.printStackTrace();
return RubyString.newString(recv.getRuntime(), "");
}
}
public static RubyInteger srand(IRubyObject recv, IRubyObject[] args) {
long oldRandomSeed = recv.getRuntime().randomSeed;
if (args.length > 0) {
RubyInteger integerSeed = (RubyInteger) args[0].convertToType("Integer", "to_int", true);
recv.getRuntime().randomSeed = integerSeed.getLongValue();
} else {
recv.getRuntime().randomSeed = System.currentTimeMillis(); // FIXME
}
recv.getRuntime().random.setSeed(recv.getRuntime().randomSeed);
return RubyFixnum.newFixnum(recv.getRuntime(), oldRandomSeed);
}
public static RubyNumeric rand(IRubyObject recv, IRubyObject args[]) {
if (args.length == 0) {
double result = recv.getRuntime().random.nextDouble();
return RubyFloat.newFloat(recv.getRuntime(), result);
} else if (args.length == 1) {
RubyInteger integerCeil = (RubyInteger) args[0].convertToType("Integer", "to_int", true);
long ceil = integerCeil.getLongValue();
if (ceil > Integer.MAX_VALUE) {
throw new NotImplementedError("Random values larger than Integer.MAX_VALUE not supported");
}
return RubyFixnum.newFixnum(recv.getRuntime(), recv.getRuntime().random.nextInt((int) ceil));
} else {
throw new ArgumentError(recv.getRuntime(), "wrong # of arguments(" + args.length + " for 1)");
}
}
}
| true | true | public static IRubyObject eval(IRubyObject recv, IRubyObject[] args) {
RubyString src = (RubyString)args[0];
IRubyObject scope = args.length > 0 ? args[1] : recv.getRuntime().getNil();
String file = "(eval)";
int line = 1;
if (args.length > 2) {
// +++
file = args[2].toString();
// ---
}
if (args.length > 3) {
line = RubyFixnum.fix2int(args[3]);
}
// +++
src.checkSafeString();
// ---
if (scope.isNil() && recv.getRuntime().getFrameStack().getPrevious() != null) {
try {
// XXX
recv.getRuntime().getFrameStack().push(recv.getRuntime().getFrameStack().getPrevious());
return recv.eval(src, scope, file, line);
} finally {
recv.getRuntime().getFrameStack().pop();
}
}
return recv.eval(src, scope, file, line);
}
| public static IRubyObject eval(IRubyObject recv, IRubyObject[] args) {
RubyString src = (RubyString)args[0];
IRubyObject scope = args.length > 1 ? args[1] : recv.getRuntime().getNil();
String file = "(eval)";
int line = 1;
if (args.length > 2) {
// +++
file = args[2].toString();
// ---
}
if (args.length > 3) {
line = RubyFixnum.fix2int(args[3]);
}
// +++
src.checkSafeString();
// ---
if (scope.isNil() && recv.getRuntime().getFrameStack().getPrevious() != null) {
try {
// XXX
recv.getRuntime().getFrameStack().push(recv.getRuntime().getFrameStack().getPrevious());
return recv.eval(src, scope, file, line);
} finally {
recv.getRuntime().getFrameStack().pop();
}
}
return recv.eval(src, scope, file, line);
}
|
diff --git a/LambTracker_V2/src/com/weyr_associates/lambtracker/TestInterfaceDesigns.java b/LambTracker_V2/src/com/weyr_associates/lambtracker/TestInterfaceDesigns.java
index 903cff3f..35e28936 100644
--- a/LambTracker_V2/src/com/weyr_associates/lambtracker/TestInterfaceDesigns.java
+++ b/LambTracker_V2/src/com/weyr_associates/lambtracker/TestInterfaceDesigns.java
@@ -1,338 +1,340 @@
package com.weyr_associates.lambtracker;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import java.util.ArrayList;
import java.util.List;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
import android.util.Log;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class TestInterfaceDesigns extends Activity{
private DatabaseHandler dbh;
private Cursor cursor, cursor2;
public RadioGroup radioGroup;
public Spinner test_dynamic_spinner, trait_spinner;
List<String> tag_colors, evaluation_traits;
List<Float> rating_scores;
ArrayAdapter<String> dataAdapter;
List<String> scored_evaluation_traits, data_evaluation_traits;
private RatingBar ratingBar01 ;
private RatingBar ratingBar02 ;
private int nRecs, tempTraitNumber;
String[] radioBtnText = {"Engorgement", "Mucus","Both"};
Object crsr, crsr2;
List <Integer> scored_trait_numbers;
ArrayList<Item> data = new ArrayList<Item>();
GridView gridview;
TextView TV;
GridViewAdapter gridviewAdapter;
String cmd;
String tempLabel;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_interface_designs);
String dbname = getString(R.string.real_database_file);
dbh = new DatabaseHandler( this, dbname );
scored_evaluation_traits = new ArrayList<String>();
scored_trait_numbers = new ArrayList<Integer>();
// cmd = "select * from last_eval_table";
cmd = String.format("select evaluation_trait_table.trait_name, evaluation_trait_table.id_traitid " +
"from evaluation_trait_table inner join last_eval_table where " +
" evaluation_trait_table.id_traitid = last_eval_table.id_traitid and evaluation_trait_table.trait_type = 1 ") ;
Log.i("test designs", " cmd is " + cmd);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
nRecs = cursor.getCount();
dbh.moveToFirstRecord();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
scored_trait_numbers.add(cursor.getInt(1));
// tempTraitNumber = cursor.getInt(1);
Log.i("test designs", " trait number is " + String.valueOf(cursor.getInt(1)));
// cmd = String.format("select evaluation_trait_table.trait_name, evaluation_trait_table.id_traitid " +
// "from evaluation_trait_table inner join last_eval_table where " +
// " evaluation_trait_table.id_traitid = last_eval_table.id_traitid") ;
// Log.i("test designs", " cmd is " + cmd);
// crsr2 = dbh.exec( cmd );
// cursor2 = ( Cursor ) crsr2;
scored_evaluation_traits.add(cursor.getString(0));
Log.i("test designs", " trait name is " + cursor.getString(0));
}
cursor.close();
// cursor2.close();
Log.i("test designs", "number of records in cursor is " + String.valueOf(nRecs));
LayoutInflater inflater = getLayoutInflater();
Log.i ("test designs", scored_evaluation_traits.get(0));
for( int ii = 0; ii < nRecs; ii++ )
{
Log.i("in for loop" , " ii is " + String.valueOf(ii));
Log.i ("in for loop", " trait name is " + scored_evaluation_traits.get(ii));
TableLayout table = (TableLayout) findViewById(R.id.TableLayout01);
Log.i("in for loop", " after TableLayout");
TableRow row = (TableRow)inflater.inflate(R.layout.eval_item_entry, table, false);
Log.i("in for loop", " after TableRow");
// TV = (TextView) findViewById (R.id.rb1_lbl);
Log.i("in for loop", " after get textview");
tempLabel = scored_evaluation_traits.get(ii);
Log.i("in for loop", " tempLabel is " + tempLabel);
- TV = (TextView) findViewById (R.id.rb1_lbl);
- Log.i("in for loop", " after got TV location rb1_lbl");
- TV.setText (tempLabel);
+ ((TextView)row.findViewById(R.id.rb1_lbl)).setText(tempLabel);
+// ((TextView)row.findViewById(R.id.attrib_value)).setText(b.VALUE);
+// TV = (TextView) findViewById (R.id.rb1_lbl);
+// Log.i("in for loop", " after got TV location rb1_lbl");
+// TV.setText (tempLabel);
Log.i("in for loop", " after set text view");
Log.i ("test designs", scored_evaluation_traits.get(ii));
table.addView(row);
// }
}
// TableLayout table = (TableLayout) findViewById(R.id.TableLayout01);
// LayoutInflater inflater = getLayoutInflater();
// TableRow row = (TableRow)inflater.inflate(R.layout.eval_item_entry, table, false);
// table.addView(row);
// TextView myLabel = (TextView) findViewById (R.id.rb1_lbl);
// myLabel.setText ("Set a characteristic Here");
// gridview = (GridView) findViewById(R.id.grid1);
// data.add(new Item("First Characteristic", ratingBar01));
// data.add(new Item("First Characteristic", ratingBar02));
// gridviewAdapter = new GridViewAdapter(getApplicationContext(), R.layout.eval_item_entry, data);
// gridview.setAdapter(gridviewAdapter);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
addRadioButtons(3, radioBtnText);
// scored_evaluation_traits = new ArrayList<String>();
test_dynamic_spinner = (Spinner) findViewById(R.id.test_dynamic_spinner);
// Log.i("testinterface", "in onCreate below test spinner");
tag_colors = new ArrayList<String>();
// Select All fields from tag colors to build the spinner
cmd = "select * from tag_colors_table";
Object crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
tag_colors.add("Select a Color");
// Log.i("testinterface", "in onCreate below got tag color table");
// looping through all rows and adding to list
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
tag_colors.add(cursor.getString(2));
}
cursor.close();
Log.i("testinterface", "below if loop");
// Creating adapter for spinner
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, tag_colors);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
test_dynamic_spinner.setAdapter (dataAdapter);
test_dynamic_spinner.setSelection(0);
// Log.i("Activity", "In Spinner");
test_dynamic_spinner.setOnItemSelectedListener(new SpinnerActivity());
// Select All fields from trait table that are score type and get set to fill the spinners
cmd = "select * from evaluation_trait_table where trait_type = 1";
crsr = dbh.exec( cmd ); ;
// Log.i("testing", "executed command " + cmd);
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
scored_evaluation_traits.add("Select a Trait");
// Log.i("testinterface", "in onCreate below got evaluation straits table");
// looping through all rows and adding to list
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
scored_evaluation_traits.add(cursor.getString(1));
}
cursor.close();
//// Log.i("createEval ", "below for loop");
//
// trait_spinner = (Spinner) findViewById(R.id.trait_spinner);
// dataAdapter = new ArrayAdapter<String>(this,
// android.R.layout.simple_spinner_item, scored_evaluation_traits);
// dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// trait_spinner.setAdapter (dataAdapter);
// trait_spinner.setSelection(0);
// trait_spinner.setOnItemSelectedListener(new SpinnerActivity());
//
// cmd = "select * from evaluation_trait_table where id_traitid = 2";
// crsr = dbh.exec( cmd );
// cursor = ( Cursor ) crsr;
// dbh.moveToFirstRecord();
// TextView TV = (TextView) findViewById(R.id.rb2_lbl);
// TV.setText( cursor.getString(1) );
// cursor.close();
}
// user clicked the 'saveScores' button
public void saveScores( View v )
{
// rating_scores = new ArrayList<Float>();
// ratingBar01 = (RatingBar) findViewById(R.id.ratingBar);
// rating_scores.add(ratingBar01.getRating());
// Log.i("RatingBar01 ", String.valueOf(ratingBar01.getRating()));
//
// ratingBar02 = (RatingBar) findViewById(R.id.ratingBar02);
// rating_scores.add(ratingBar02.getRating());
// Log.i("RatingBar02 ", String.valueOf(ratingBar02.getRating()));
}
private void addRadioButtons(int numButtons, String[] radioBtnText) {
int i;
// String[] radioBtnText = {"Engorgement", "Mucus","Both"};
for(i = 0; i < numButtons; i++){
//instantiate...
RadioButton radioBtn = new RadioButton(this);
//set the values that you would otherwise hardcode in the xml...
radioBtn.setLayoutParams
(new LayoutParams
(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
//label the button...
radioBtn.setText(radioBtnText[i]);
radioBtn.setId(i);
//add it to the group.
radioGroup.addView(radioBtn, i);
}
}
private class SpinnerActivity extends Activity implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Log.i("Activity", "In Spinner activity before the case statement");
String teststring;
teststring = String.valueOf (parent.getSelectedItemPosition());
// Log.i("Spinner", "Position = "+teststring);
switch (parent.getSelectedItemPosition()){
case 0:
// Don't want to do anything until something is selected so just break at position zero
break;
case 1:
teststring = String.valueOf (parent.getSelectedItemPosition());
teststring = test_dynamic_spinner.getSelectedItem().toString();
break;
case 2:
teststring = String.valueOf (parent.getSelectedItemPosition());
teststring = test_dynamic_spinner.getSelectedItem().toString();
break;
case 3:
teststring = String.valueOf (parent.getSelectedItemPosition());
teststring = test_dynamic_spinner.getSelectedItem().toString();
break;
case 4:
teststring = String.valueOf (parent.getSelectedItemPosition());
teststring = test_dynamic_spinner.getSelectedItem().toString();
break;
case 5:
teststring = String.valueOf (parent.getSelectedItemPosition());
teststring = test_dynamic_spinner.getSelectedItem().toString();
break;
case 6:
teststring = String.valueOf (parent.getSelectedItemPosition());
teststring = test_dynamic_spinner.getSelectedItem().toString();
break;
case 7:
teststring = String.valueOf (parent.getSelectedItemPosition());
teststring = test_dynamic_spinner.getSelectedItem().toString();
break;
case 8:
teststring = String.valueOf (parent.getSelectedItemPosition());
teststring = test_dynamic_spinner.getSelectedItem().toString();
break;
case 9:
teststring = String.valueOf (parent.getSelectedItemPosition());
teststring = test_dynamic_spinner.getSelectedItem().toString();
break;
case 10:
teststring = String.valueOf (parent.getSelectedItemPosition());
teststring = test_dynamic_spinner.getSelectedItem().toString();
break;
case 11:
teststring = String.valueOf (parent.getSelectedItemPosition());
teststring = test_dynamic_spinner.getSelectedItem().toString();
break;
case 12:
teststring = String.valueOf (parent.getSelectedItemPosition());
teststring = test_dynamic_spinner.getSelectedItem().toString();
break;
case 13:
teststring = String.valueOf (parent.getSelectedItemPosition());
teststring = test_dynamic_spinner.getSelectedItem().toString();
break;
case 14:
teststring = String.valueOf (parent.getSelectedItemPosition());
teststring = test_dynamic_spinner.getSelectedItem().toString();
break;
case 15:
teststring = String.valueOf (parent.getSelectedItemPosition());
teststring = test_dynamic_spinner.getSelectedItem().toString();
break;
case 16:
teststring = String.valueOf (parent.getSelectedItemPosition());
teststring = test_dynamic_spinner.getSelectedItem().toString();
break;
case 17:
teststring = String.valueOf (parent.getSelectedItemPosition());
teststring = test_dynamic_spinner.getSelectedItem().toString();
break;
case 18:
teststring = String.valueOf (parent.getSelectedItemPosition());
teststring = test_dynamic_spinner.getSelectedItem().toString();
break;
case 19:
teststring = String.valueOf (parent.getSelectedItemPosition());
teststring = test_dynamic_spinner.getSelectedItem().toString();
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
// user clicked the 'back' button
public void backBtn( View v )
{
dbh.closeDB();
finish();
}
// Set the Data Adapter
private void setDataAdapter()
{
gridviewAdapter = new GridViewAdapter(getApplicationContext(), R.layout.eval_item_entry, data);
gridview.setAdapter(gridviewAdapter);
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_interface_designs);
String dbname = getString(R.string.real_database_file);
dbh = new DatabaseHandler( this, dbname );
scored_evaluation_traits = new ArrayList<String>();
scored_trait_numbers = new ArrayList<Integer>();
// cmd = "select * from last_eval_table";
cmd = String.format("select evaluation_trait_table.trait_name, evaluation_trait_table.id_traitid " +
"from evaluation_trait_table inner join last_eval_table where " +
" evaluation_trait_table.id_traitid = last_eval_table.id_traitid and evaluation_trait_table.trait_type = 1 ") ;
Log.i("test designs", " cmd is " + cmd);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
nRecs = cursor.getCount();
dbh.moveToFirstRecord();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
scored_trait_numbers.add(cursor.getInt(1));
// tempTraitNumber = cursor.getInt(1);
Log.i("test designs", " trait number is " + String.valueOf(cursor.getInt(1)));
// cmd = String.format("select evaluation_trait_table.trait_name, evaluation_trait_table.id_traitid " +
// "from evaluation_trait_table inner join last_eval_table where " +
// " evaluation_trait_table.id_traitid = last_eval_table.id_traitid") ;
// Log.i("test designs", " cmd is " + cmd);
// crsr2 = dbh.exec( cmd );
// cursor2 = ( Cursor ) crsr2;
scored_evaluation_traits.add(cursor.getString(0));
Log.i("test designs", " trait name is " + cursor.getString(0));
}
cursor.close();
// cursor2.close();
Log.i("test designs", "number of records in cursor is " + String.valueOf(nRecs));
LayoutInflater inflater = getLayoutInflater();
Log.i ("test designs", scored_evaluation_traits.get(0));
for( int ii = 0; ii < nRecs; ii++ )
{
Log.i("in for loop" , " ii is " + String.valueOf(ii));
Log.i ("in for loop", " trait name is " + scored_evaluation_traits.get(ii));
TableLayout table = (TableLayout) findViewById(R.id.TableLayout01);
Log.i("in for loop", " after TableLayout");
TableRow row = (TableRow)inflater.inflate(R.layout.eval_item_entry, table, false);
Log.i("in for loop", " after TableRow");
// TV = (TextView) findViewById (R.id.rb1_lbl);
Log.i("in for loop", " after get textview");
tempLabel = scored_evaluation_traits.get(ii);
Log.i("in for loop", " tempLabel is " + tempLabel);
TV = (TextView) findViewById (R.id.rb1_lbl);
Log.i("in for loop", " after got TV location rb1_lbl");
TV.setText (tempLabel);
Log.i("in for loop", " after set text view");
Log.i ("test designs", scored_evaluation_traits.get(ii));
table.addView(row);
// }
}
// TableLayout table = (TableLayout) findViewById(R.id.TableLayout01);
// LayoutInflater inflater = getLayoutInflater();
// TableRow row = (TableRow)inflater.inflate(R.layout.eval_item_entry, table, false);
// table.addView(row);
// TextView myLabel = (TextView) findViewById (R.id.rb1_lbl);
// myLabel.setText ("Set a characteristic Here");
// gridview = (GridView) findViewById(R.id.grid1);
// data.add(new Item("First Characteristic", ratingBar01));
// data.add(new Item("First Characteristic", ratingBar02));
// gridviewAdapter = new GridViewAdapter(getApplicationContext(), R.layout.eval_item_entry, data);
// gridview.setAdapter(gridviewAdapter);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
addRadioButtons(3, radioBtnText);
// scored_evaluation_traits = new ArrayList<String>();
test_dynamic_spinner = (Spinner) findViewById(R.id.test_dynamic_spinner);
// Log.i("testinterface", "in onCreate below test spinner");
tag_colors = new ArrayList<String>();
// Select All fields from tag colors to build the spinner
cmd = "select * from tag_colors_table";
Object crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
tag_colors.add("Select a Color");
// Log.i("testinterface", "in onCreate below got tag color table");
// looping through all rows and adding to list
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
tag_colors.add(cursor.getString(2));
}
cursor.close();
Log.i("testinterface", "below if loop");
// Creating adapter for spinner
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, tag_colors);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
test_dynamic_spinner.setAdapter (dataAdapter);
test_dynamic_spinner.setSelection(0);
// Log.i("Activity", "In Spinner");
test_dynamic_spinner.setOnItemSelectedListener(new SpinnerActivity());
// Select All fields from trait table that are score type and get set to fill the spinners
cmd = "select * from evaluation_trait_table where trait_type = 1";
crsr = dbh.exec( cmd ); ;
// Log.i("testing", "executed command " + cmd);
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
scored_evaluation_traits.add("Select a Trait");
// Log.i("testinterface", "in onCreate below got evaluation straits table");
// looping through all rows and adding to list
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
scored_evaluation_traits.add(cursor.getString(1));
}
cursor.close();
//// Log.i("createEval ", "below for loop");
//
// trait_spinner = (Spinner) findViewById(R.id.trait_spinner);
// dataAdapter = new ArrayAdapter<String>(this,
// android.R.layout.simple_spinner_item, scored_evaluation_traits);
// dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// trait_spinner.setAdapter (dataAdapter);
// trait_spinner.setSelection(0);
// trait_spinner.setOnItemSelectedListener(new SpinnerActivity());
//
// cmd = "select * from evaluation_trait_table where id_traitid = 2";
// crsr = dbh.exec( cmd );
// cursor = ( Cursor ) crsr;
// dbh.moveToFirstRecord();
// TextView TV = (TextView) findViewById(R.id.rb2_lbl);
// TV.setText( cursor.getString(1) );
// cursor.close();
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_interface_designs);
String dbname = getString(R.string.real_database_file);
dbh = new DatabaseHandler( this, dbname );
scored_evaluation_traits = new ArrayList<String>();
scored_trait_numbers = new ArrayList<Integer>();
// cmd = "select * from last_eval_table";
cmd = String.format("select evaluation_trait_table.trait_name, evaluation_trait_table.id_traitid " +
"from evaluation_trait_table inner join last_eval_table where " +
" evaluation_trait_table.id_traitid = last_eval_table.id_traitid and evaluation_trait_table.trait_type = 1 ") ;
Log.i("test designs", " cmd is " + cmd);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
nRecs = cursor.getCount();
dbh.moveToFirstRecord();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
scored_trait_numbers.add(cursor.getInt(1));
// tempTraitNumber = cursor.getInt(1);
Log.i("test designs", " trait number is " + String.valueOf(cursor.getInt(1)));
// cmd = String.format("select evaluation_trait_table.trait_name, evaluation_trait_table.id_traitid " +
// "from evaluation_trait_table inner join last_eval_table where " +
// " evaluation_trait_table.id_traitid = last_eval_table.id_traitid") ;
// Log.i("test designs", " cmd is " + cmd);
// crsr2 = dbh.exec( cmd );
// cursor2 = ( Cursor ) crsr2;
scored_evaluation_traits.add(cursor.getString(0));
Log.i("test designs", " trait name is " + cursor.getString(0));
}
cursor.close();
// cursor2.close();
Log.i("test designs", "number of records in cursor is " + String.valueOf(nRecs));
LayoutInflater inflater = getLayoutInflater();
Log.i ("test designs", scored_evaluation_traits.get(0));
for( int ii = 0; ii < nRecs; ii++ )
{
Log.i("in for loop" , " ii is " + String.valueOf(ii));
Log.i ("in for loop", " trait name is " + scored_evaluation_traits.get(ii));
TableLayout table = (TableLayout) findViewById(R.id.TableLayout01);
Log.i("in for loop", " after TableLayout");
TableRow row = (TableRow)inflater.inflate(R.layout.eval_item_entry, table, false);
Log.i("in for loop", " after TableRow");
// TV = (TextView) findViewById (R.id.rb1_lbl);
Log.i("in for loop", " after get textview");
tempLabel = scored_evaluation_traits.get(ii);
Log.i("in for loop", " tempLabel is " + tempLabel);
((TextView)row.findViewById(R.id.rb1_lbl)).setText(tempLabel);
// ((TextView)row.findViewById(R.id.attrib_value)).setText(b.VALUE);
// TV = (TextView) findViewById (R.id.rb1_lbl);
// Log.i("in for loop", " after got TV location rb1_lbl");
// TV.setText (tempLabel);
Log.i("in for loop", " after set text view");
Log.i ("test designs", scored_evaluation_traits.get(ii));
table.addView(row);
// }
}
// TableLayout table = (TableLayout) findViewById(R.id.TableLayout01);
// LayoutInflater inflater = getLayoutInflater();
// TableRow row = (TableRow)inflater.inflate(R.layout.eval_item_entry, table, false);
// table.addView(row);
// TextView myLabel = (TextView) findViewById (R.id.rb1_lbl);
// myLabel.setText ("Set a characteristic Here");
// gridview = (GridView) findViewById(R.id.grid1);
// data.add(new Item("First Characteristic", ratingBar01));
// data.add(new Item("First Characteristic", ratingBar02));
// gridviewAdapter = new GridViewAdapter(getApplicationContext(), R.layout.eval_item_entry, data);
// gridview.setAdapter(gridviewAdapter);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
addRadioButtons(3, radioBtnText);
// scored_evaluation_traits = new ArrayList<String>();
test_dynamic_spinner = (Spinner) findViewById(R.id.test_dynamic_spinner);
// Log.i("testinterface", "in onCreate below test spinner");
tag_colors = new ArrayList<String>();
// Select All fields from tag colors to build the spinner
cmd = "select * from tag_colors_table";
Object crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
tag_colors.add("Select a Color");
// Log.i("testinterface", "in onCreate below got tag color table");
// looping through all rows and adding to list
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
tag_colors.add(cursor.getString(2));
}
cursor.close();
Log.i("testinterface", "below if loop");
// Creating adapter for spinner
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, tag_colors);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
test_dynamic_spinner.setAdapter (dataAdapter);
test_dynamic_spinner.setSelection(0);
// Log.i("Activity", "In Spinner");
test_dynamic_spinner.setOnItemSelectedListener(new SpinnerActivity());
// Select All fields from trait table that are score type and get set to fill the spinners
cmd = "select * from evaluation_trait_table where trait_type = 1";
crsr = dbh.exec( cmd ); ;
// Log.i("testing", "executed command " + cmd);
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
scored_evaluation_traits.add("Select a Trait");
// Log.i("testinterface", "in onCreate below got evaluation straits table");
// looping through all rows and adding to list
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
scored_evaluation_traits.add(cursor.getString(1));
}
cursor.close();
//// Log.i("createEval ", "below for loop");
//
// trait_spinner = (Spinner) findViewById(R.id.trait_spinner);
// dataAdapter = new ArrayAdapter<String>(this,
// android.R.layout.simple_spinner_item, scored_evaluation_traits);
// dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// trait_spinner.setAdapter (dataAdapter);
// trait_spinner.setSelection(0);
// trait_spinner.setOnItemSelectedListener(new SpinnerActivity());
//
// cmd = "select * from evaluation_trait_table where id_traitid = 2";
// crsr = dbh.exec( cmd );
// cursor = ( Cursor ) crsr;
// dbh.moveToFirstRecord();
// TextView TV = (TextView) findViewById(R.id.rb2_lbl);
// TV.setText( cursor.getString(1) );
// cursor.close();
}
|
diff --git a/java/src/test/java/de/weltraumschaf/ebnf/gfx/shapes/RuleTest.java b/java/src/test/java/de/weltraumschaf/ebnf/gfx/shapes/RuleTest.java
index 60fc9eaa..dd47abb8 100644
--- a/java/src/test/java/de/weltraumschaf/ebnf/gfx/shapes/RuleTest.java
+++ b/java/src/test/java/de/weltraumschaf/ebnf/gfx/shapes/RuleTest.java
@@ -1,84 +1,84 @@
/*
* LICENSE
*
* "THE BEER-WARE LICENSE" (Revision 42):
* "Sven Strittmatter" <[email protected]> wrote this file.
* As long as you retain this notice you can do whatever you want with
* this stuff. If we meet some day, and you think this stuff is worth it,
* you can buy me a beer in return.
*
*/
package de.weltraumschaf.ebnf.gfx.shapes;
import de.weltraumschaf.ebnf.gfx.StringPainter;
import static de.weltraumschaf.ebnf.gfx.shapes.ShapeFactory.rule;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import static org.mockito.Mockito.*;
/**
*
* @author Sven Strittmatter <[email protected]>
*/
public class RuleTest {
static class RuleStub extends Rule {
Dimension calcTextSize = new Dimension();
public RuleStub(final String text) {
super(text);
}
@Override
protected Dimension calculateTextSize(final Graphics2D graphic) {
return calcTextSize;
}
void setCalculatedTextSize(final Dimension calcTextSize) {
this.calcTextSize = calcTextSize;
}
}
@Test public void font() {
final String name = "foobar";
final AbstractTextShape rule = rule(name);
assertEquals(name, rule.getText());
assertEquals(StringPainter.SANSERIF, rule.getFont());
}
@Test public void adjust() {
final RuleStub rule = new RuleStub("foobar");
rule.adjust(null);
assertEquals(new Dimension(31, 31), rule.getSize());
rule.setCalculatedTextSize(new Dimension(100, 16));
rule.adjust(null);
assertEquals(new Dimension(124, 31), rule.getSize());
}
@Test public void paint() {
final String name = "foobar";
final FontMetrics metrics = mock(FontMetrics.class);
when(metrics.stringWidth(name)).thenReturn(80);
when(metrics.getAscent()).thenReturn(12);
when(metrics.getDescent()).thenReturn(4);
- final Graphics2D graphic = mock(Graphics2D.class);
- when(graphic.getFontMetrics()).thenReturn(metrics);
+ final Graphics2D graphics = mock(Graphics2D.class);
+ when(graphics.getFontMetrics()).thenReturn(metrics);
final RuleStub rule = new RuleStub(name);
rule.setCalculatedTextSize(new Dimension(100, 16));
- rule.paint(graphic);
+ rule.paint(graphics);
- verify(graphic, times(1)).setColor(Color.BLACK);
- verify(graphic, times(1)).setFont(StringPainter.SANSERIF);
- verify(graphic, times(1)).drawString(name, 15, 19);
+ verify(graphics, times(1)).setColor(Color.BLACK);
+ verify(graphics, times(1)).setFont(StringPainter.SANSERIF);
+ verify(graphics, times(1)).drawString(name, 15, 19);
}
}
| false | true | @Test public void paint() {
final String name = "foobar";
final FontMetrics metrics = mock(FontMetrics.class);
when(metrics.stringWidth(name)).thenReturn(80);
when(metrics.getAscent()).thenReturn(12);
when(metrics.getDescent()).thenReturn(4);
final Graphics2D graphic = mock(Graphics2D.class);
when(graphic.getFontMetrics()).thenReturn(metrics);
final RuleStub rule = new RuleStub(name);
rule.setCalculatedTextSize(new Dimension(100, 16));
rule.paint(graphic);
verify(graphic, times(1)).setColor(Color.BLACK);
verify(graphic, times(1)).setFont(StringPainter.SANSERIF);
verify(graphic, times(1)).drawString(name, 15, 19);
}
| @Test public void paint() {
final String name = "foobar";
final FontMetrics metrics = mock(FontMetrics.class);
when(metrics.stringWidth(name)).thenReturn(80);
when(metrics.getAscent()).thenReturn(12);
when(metrics.getDescent()).thenReturn(4);
final Graphics2D graphics = mock(Graphics2D.class);
when(graphics.getFontMetrics()).thenReturn(metrics);
final RuleStub rule = new RuleStub(name);
rule.setCalculatedTextSize(new Dimension(100, 16));
rule.paint(graphics);
verify(graphics, times(1)).setColor(Color.BLACK);
verify(graphics, times(1)).setFont(StringPainter.SANSERIF);
verify(graphics, times(1)).drawString(name, 15, 19);
}
|
diff --git a/src/main/java/hudson/plugins/scm_sync_configuration/ScmSyncConfigurationBusiness.java b/src/main/java/hudson/plugins/scm_sync_configuration/ScmSyncConfigurationBusiness.java
index 0fff6af..00244e1 100644
--- a/src/main/java/hudson/plugins/scm_sync_configuration/ScmSyncConfigurationBusiness.java
+++ b/src/main/java/hudson/plugins/scm_sync_configuration/ScmSyncConfigurationBusiness.java
@@ -1,343 +1,343 @@
package hudson.plugins.scm_sync_configuration;
import com.google.common.io.Files;
import hudson.model.Hudson;
import hudson.model.User;
import hudson.plugins.scm_sync_configuration.exceptions.LoggableException;
import hudson.plugins.scm_sync_configuration.model.*;
import hudson.plugins.scm_sync_configuration.strategies.ScmSyncStrategy;
import hudson.plugins.scm_sync_configuration.utils.Checksums;
import hudson.util.DaemonThreadFactory;
import org.apache.commons.io.FileUtils;
import org.apache.maven.scm.ScmException;
import org.apache.maven.scm.manager.ScmManager;
import org.codehaus.plexus.PlexusContainerException;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Logger;
public class ScmSyncConfigurationBusiness {
private static final String WORKING_DIRECTORY_PATH = "/scm-sync-configuration/";
private static final String CHECKOUT_SCM_DIRECTORY = "checkoutConfiguration";
private static final Logger LOGGER = Logger.getLogger(ScmSyncConfigurationBusiness.class.getName());
private boolean checkoutSucceeded;
private SCMManipulator scmManipulator;
private File checkoutScmDirectory = null;
private ScmSyncConfigurationStatusManager scmSyncConfigurationStatusManager = null;
/**
* Use of a size 1 thread pool frees us from worrying about accidental thread death and
* changeset commit concurrency
*/
/*package*/ final ExecutorService writer = Executors.newFixedThreadPool(1, new DaemonThreadFactory());
// TODO: Refactor this into the plugin object ???
private List<Commit> commitsQueue = Collections.synchronizedList(new ArrayList<Commit>());
public ScmSyncConfigurationBusiness(){
}
public ScmSyncConfigurationStatusManager getScmSyncConfigurationStatusManager() {
if (scmSyncConfigurationStatusManager == null) {
scmSyncConfigurationStatusManager = new ScmSyncConfigurationStatusManager();
}
return scmSyncConfigurationStatusManager;
}
public void init(ScmContext scmContext) throws ComponentLookupException, PlexusContainerException {
ScmManager scmManager = SCMManagerFactory.getInstance().createScmManager();
this.scmManipulator = new SCMManipulator(scmManager);
this.checkoutScmDirectory = new File(getCheckoutScmDirectoryAbsolutePath());
this.checkoutSucceeded = false;
initializeRepository(scmContext, false);
}
public void initializeRepository(ScmContext scmContext, boolean deleteCheckoutScmDir){
// Let's check if everything is available to checkout sources
if(scmManipulator != null && scmManipulator.scmConfigurationSettledUp(scmContext, true)){
LOGGER.info("Initializing SCM repository for scm-sync-configuration plugin ...");
// If checkoutScmDirectory was not empty and deleteCheckoutScmDir is asked, reinitialize it !
if(deleteCheckoutScmDir){
cleanChekoutScmDirectory();
}
// Creating checkout scm directory
if(!checkoutScmDirectory.exists()){
try {
FileUtils.forceMkdir(checkoutScmDirectory);
LOGGER.info("Directory ["+ checkoutScmDirectory.getAbsolutePath() +"] created !");
} catch (IOException e) {
LOGGER.warning("Directory ["+ checkoutScmDirectory.getAbsolutePath() +"] cannot be created !");
}
}
this.checkoutSucceeded = this.scmManipulator.checkout(this.checkoutScmDirectory);
if(this.checkoutSucceeded){
LOGGER.info("SCM repository initialization done.");
}
signal("Checkout " + this.checkoutScmDirectory, this.checkoutSucceeded);
}
}
public void cleanChekoutScmDirectory(){
if(checkoutScmDirectory != null && checkoutScmDirectory.exists()){
LOGGER.info("Deleting old checkout SCM directory ...");
try {
FileUtils.forceDelete(checkoutScmDirectory);
} catch (IOException e) {
LOGGER.throwing(FileUtils.class.getName(), "forceDelete", e);
LOGGER.severe("Error while deleting ["+checkoutScmDirectory.getAbsolutePath()+"] : "+e.getMessage());
}
this.checkoutSucceeded = false;
}
}
public List<File> deleteHierarchy(ScmContext scmContext, String hierarchyPath){
if(scmManipulator == null || !scmManipulator.scmConfigurationSettledUp(scmContext, false)){
return null;
}
File rootHierarchyTranslatedInScm = new File(getCheckoutScmDirectoryAbsolutePath()+File.separator+hierarchyPath);
List<File> filesToCommit = scmManipulator.deleteHierarchy(rootHierarchyTranslatedInScm);
signal("Delete " + hierarchyPath, filesToCommit != null);
return filesToCommit;
}
public Future<Void> queueChangeSet(final ScmContext scmContext, ChangeSet changeset, User user, String userMessage) {
if(scmManipulator == null || !scmManipulator.scmConfigurationSettledUp(scmContext, false)){
LOGGER.info("Queue of changeset "+changeset.toString()+" aborted (scm manipulator not settled !)");
return null;
}
Commit commit = new Commit(changeset, user, userMessage, scmContext);
LOGGER.info("Queuing commit "+commit.toString()+" to SCM ...");
commitsQueue.add(commit);
return writer.submit(new Callable<Void>() {
public Void call() throws Exception {
processCommitsQueue();
return null;
}
});
}
private void processCommitsQueue() {
File scmRoot = new File(getCheckoutScmDirectoryAbsolutePath());
// Copying shared commitQueue in order to allow conccurrent modification
List<Commit> currentCommitQueue = new ArrayList<Commit>(commitsQueue);
List<Commit> checkedInCommits = new ArrayList<Commit>();
try {
// Reading commit queue and commiting changeset
for(Commit commit: currentCommitQueue){
String logMessage = "Processing commit : " + commit.toString();
LOGGER.info(logMessage);
// Preparing files to add / delete
List<File> updatedFiles = new ArrayList<File>();
for(Map.Entry<Path,byte[]> pathContent : commit.getChangeset().getPathContents().entrySet()){
Path pathRelativeToJenkinsRoot = pathContent.getKey();
byte[] content = pathContent.getValue();
File fileTranslatedInScm = pathRelativeToJenkinsRoot.getScmFile();
if(pathRelativeToJenkinsRoot.isDirectory()) {
if(!fileTranslatedInScm.exists()){
// Retrieving non existing parent scm path *before* copying it from jenkins directory
- String firstExistingParentScmPath = pathRelativeToJenkinsRoot.getFirstNonExistingParentScmPath();
+ String firstNonExistingParentScmPath = pathRelativeToJenkinsRoot.getFirstNonExistingParentScmPath();
try {
FileUtils.copyDirectory(JenkinsFilesHelper.buildFileFromPathRelativeToHudsonRoot(pathRelativeToJenkinsRoot.getPath()),
fileTranslatedInScm);
} catch (IOException e) {
throw new LoggableException("Error while copying file hierarchy to SCM checkouted directory", FileUtils.class, "copyDirectory", e);
}
- updatedFiles.addAll(scmManipulator.addFile(scmRoot, firstExistingParentScmPath));
+ updatedFiles.addAll(scmManipulator.addFile(scmRoot, firstNonExistingParentScmPath));
}
} else {
// We should remember if file in scm existed or not before any manipulation,
// especially writing content
boolean fileTranslatedInScmInitiallyExists = fileTranslatedInScm.exists();
boolean fileContentModified = writeScmContentOnlyIfItDiffers(pathRelativeToJenkinsRoot, content, fileTranslatedInScm);
if(fileTranslatedInScmInitiallyExists){
if(fileContentModified){
// No need to call scmManipulator.addFile() if fileTranslatedInScm already existed
updatedFiles.add(fileTranslatedInScm);
}
} else {
updatedFiles.addAll(scmManipulator.addFile(scmRoot, pathRelativeToJenkinsRoot.getPath()));
}
}
}
for(Path path : commit.getChangeset().getPathsToDelete()){
List<File> deletedFiles = deleteHierarchy(commit.getScmContext(), path.getPath());
updatedFiles.addAll(deletedFiles);
}
if(updatedFiles.isEmpty()){
LOGGER.info("Empty changeset to commit (no changes found on files) => commit skipped !");
} else {
// Commiting files...
boolean result = scmManipulator.checkinFiles(scmRoot, commit.getMessage());
if(result){
LOGGER.info("Commit "+commit.toString()+" pushed to SCM !");
checkedInCommits.add(commit);
} else {
throw new LoggableException("Error while checking in file to scm repository", SCMManipulator.class, "checkinFiles");
}
signal(logMessage, true);
}
}
// As soon as a commit doesn't goes well, we should abort commit queue processing...
}catch(LoggableException e){
LOGGER.throwing(e.getClazz().getName(), e.getMethodName(), e);
LOGGER.severe("Error while processing commit queue : "+e.getMessage());
signal(e.getMessage(), false);
} finally {
// We should remove every checkedInCommits
commitsQueue.removeAll(checkedInCommits);
}
}
private boolean writeScmContentOnlyIfItDiffers(Path pathRelativeToJenkinsRoot, byte[] content, File fileTranslatedInScm)
throws LoggableException {
boolean scmContentUpdated = false;
boolean contentDiffer = false;
try {
contentDiffer = !Checksums.fileAndByteArrayContentAreEqual(fileTranslatedInScm, content);
} catch (IOException e) {
throw new LoggableException("Error while checking content checksum", Checksums.class, "fileAndByteArrayContentAreEqual", e);
}
if(contentDiffer){
createScmContent(pathRelativeToJenkinsRoot, content, fileTranslatedInScm);
scmContentUpdated = true;
} else {
// Don't do anything
}
return scmContentUpdated;
}
private void createScmContent(Path pathRelativeToJenkinsRoot, byte[] content, File fileTranslatedInScm)
throws LoggableException {
Stack<File> directoriesToCreate = new Stack<File>();
File directory = fileTranslatedInScm.getParentFile();
// Eventually, creating non existing enclosing directories
while(!directory.exists()){
directoriesToCreate.push(directory);
directory = directory.getParentFile();
}
while(!directoriesToCreate.empty()){
directory = directoriesToCreate.pop();
if(!directory.mkdir()){
throw new LoggableException("Error while creating directory "+directory.getAbsolutePath(), File.class, "mkdir");
}
}
try {
// Copying content if pathRelativeToJenkinsRoot is a file, or creating the directory if it is a directory
if(pathRelativeToJenkinsRoot.isDirectory()){
if(!fileTranslatedInScm.mkdir()){
throw new LoggableException("Error while creating directory "+fileTranslatedInScm.getAbsolutePath(), File.class, "mkdir");
}
} else {
Files.write(content, fileTranslatedInScm);
}
} catch (IOException e) {
throw new LoggableException("Error while creating file in checkouted directory", Files.class, "write", e);
}
}
public void synchronizeAllConfigs(ScmSyncStrategy[] availableStrategies){
List<File> filesToSync = new ArrayList<File>();
// Building synced files from strategies
for(ScmSyncStrategy strategy : availableStrategies){
filesToSync.addAll(strategy.createInitializationSynchronizedFileset());
}
ScmSyncConfigurationPlugin plugin = ScmSyncConfigurationPlugin.getInstance();
plugin.startThreadedTransaction();
try {
for(File fileToSync : filesToSync){
String hudsonConfigPathRelativeToHudsonRoot = JenkinsFilesHelper.buildPathRelativeToHudsonRoot(fileToSync);
plugin.getTransaction().defineCommitMessage(new WeightedMessage("Repository initialization", MessageWeight.IMPORTANT));
plugin.getTransaction().registerPath(hudsonConfigPathRelativeToHudsonRoot);
}
} finally {
plugin.getTransaction().commit();
}
}
public boolean scmCheckoutDirectorySettledUp(ScmContext scmContext){
return scmManipulator != null && this.scmManipulator.scmConfigurationSettledUp(scmContext, false) && this.checkoutSucceeded;
}
public List<File> reloadAllFilesFromScm() throws IOException, ScmException {
this.scmManipulator.update(new File(getCheckoutScmDirectoryAbsolutePath()));
return syncDirectories(new File(getCheckoutScmDirectoryAbsolutePath() + File.separator), "");
}
private List<File> syncDirectories(File from, String relative) throws IOException {
List<File> l = new ArrayList<File>();
for(File f : from.listFiles()) {
String newRelative = relative + File.separator + f.getName();
File jenkinsFile = new File(Hudson.getInstance().getRootDir() + newRelative);
if (f.getName().equals(scmManipulator.getScmSpecificFilename())) {
// nothing to do
}
else if (f.isDirectory()) {
if (!jenkinsFile.exists()) {
FileUtils.copyDirectory(f, jenkinsFile, new FileFilter() {
public boolean accept(File f) {
return !f.getName().equals(scmManipulator.getScmSpecificFilename());
}
});
l.add(jenkinsFile);
}
else {
l.addAll(syncDirectories(f, newRelative));
}
}
else {
if (!jenkinsFile.exists() || !FileUtils.contentEquals(f, jenkinsFile)) {
FileUtils.copyFile(f, jenkinsFile);
l.add(jenkinsFile);
}
}
}
return l;
}
private void signal(String operation, boolean result) {
if (result) {
getScmSyncConfigurationStatusManager().signalSuccess();
}
else {
getScmSyncConfigurationStatusManager().signalFailed(operation);
}
}
public static String getCheckoutScmDirectoryAbsolutePath(){
return Hudson.getInstance().getRootDir().getAbsolutePath()+WORKING_DIRECTORY_PATH+CHECKOUT_SCM_DIRECTORY;
}
}
| false | true | private void processCommitsQueue() {
File scmRoot = new File(getCheckoutScmDirectoryAbsolutePath());
// Copying shared commitQueue in order to allow conccurrent modification
List<Commit> currentCommitQueue = new ArrayList<Commit>(commitsQueue);
List<Commit> checkedInCommits = new ArrayList<Commit>();
try {
// Reading commit queue and commiting changeset
for(Commit commit: currentCommitQueue){
String logMessage = "Processing commit : " + commit.toString();
LOGGER.info(logMessage);
// Preparing files to add / delete
List<File> updatedFiles = new ArrayList<File>();
for(Map.Entry<Path,byte[]> pathContent : commit.getChangeset().getPathContents().entrySet()){
Path pathRelativeToJenkinsRoot = pathContent.getKey();
byte[] content = pathContent.getValue();
File fileTranslatedInScm = pathRelativeToJenkinsRoot.getScmFile();
if(pathRelativeToJenkinsRoot.isDirectory()) {
if(!fileTranslatedInScm.exists()){
// Retrieving non existing parent scm path *before* copying it from jenkins directory
String firstExistingParentScmPath = pathRelativeToJenkinsRoot.getFirstNonExistingParentScmPath();
try {
FileUtils.copyDirectory(JenkinsFilesHelper.buildFileFromPathRelativeToHudsonRoot(pathRelativeToJenkinsRoot.getPath()),
fileTranslatedInScm);
} catch (IOException e) {
throw new LoggableException("Error while copying file hierarchy to SCM checkouted directory", FileUtils.class, "copyDirectory", e);
}
updatedFiles.addAll(scmManipulator.addFile(scmRoot, firstExistingParentScmPath));
}
} else {
// We should remember if file in scm existed or not before any manipulation,
// especially writing content
boolean fileTranslatedInScmInitiallyExists = fileTranslatedInScm.exists();
boolean fileContentModified = writeScmContentOnlyIfItDiffers(pathRelativeToJenkinsRoot, content, fileTranslatedInScm);
if(fileTranslatedInScmInitiallyExists){
if(fileContentModified){
// No need to call scmManipulator.addFile() if fileTranslatedInScm already existed
updatedFiles.add(fileTranslatedInScm);
}
} else {
updatedFiles.addAll(scmManipulator.addFile(scmRoot, pathRelativeToJenkinsRoot.getPath()));
}
}
}
for(Path path : commit.getChangeset().getPathsToDelete()){
List<File> deletedFiles = deleteHierarchy(commit.getScmContext(), path.getPath());
updatedFiles.addAll(deletedFiles);
}
if(updatedFiles.isEmpty()){
LOGGER.info("Empty changeset to commit (no changes found on files) => commit skipped !");
} else {
// Commiting files...
boolean result = scmManipulator.checkinFiles(scmRoot, commit.getMessage());
if(result){
LOGGER.info("Commit "+commit.toString()+" pushed to SCM !");
checkedInCommits.add(commit);
} else {
throw new LoggableException("Error while checking in file to scm repository", SCMManipulator.class, "checkinFiles");
}
signal(logMessage, true);
}
}
// As soon as a commit doesn't goes well, we should abort commit queue processing...
}catch(LoggableException e){
LOGGER.throwing(e.getClazz().getName(), e.getMethodName(), e);
LOGGER.severe("Error while processing commit queue : "+e.getMessage());
signal(e.getMessage(), false);
} finally {
// We should remove every checkedInCommits
commitsQueue.removeAll(checkedInCommits);
}
}
| private void processCommitsQueue() {
File scmRoot = new File(getCheckoutScmDirectoryAbsolutePath());
// Copying shared commitQueue in order to allow conccurrent modification
List<Commit> currentCommitQueue = new ArrayList<Commit>(commitsQueue);
List<Commit> checkedInCommits = new ArrayList<Commit>();
try {
// Reading commit queue and commiting changeset
for(Commit commit: currentCommitQueue){
String logMessage = "Processing commit : " + commit.toString();
LOGGER.info(logMessage);
// Preparing files to add / delete
List<File> updatedFiles = new ArrayList<File>();
for(Map.Entry<Path,byte[]> pathContent : commit.getChangeset().getPathContents().entrySet()){
Path pathRelativeToJenkinsRoot = pathContent.getKey();
byte[] content = pathContent.getValue();
File fileTranslatedInScm = pathRelativeToJenkinsRoot.getScmFile();
if(pathRelativeToJenkinsRoot.isDirectory()) {
if(!fileTranslatedInScm.exists()){
// Retrieving non existing parent scm path *before* copying it from jenkins directory
String firstNonExistingParentScmPath = pathRelativeToJenkinsRoot.getFirstNonExistingParentScmPath();
try {
FileUtils.copyDirectory(JenkinsFilesHelper.buildFileFromPathRelativeToHudsonRoot(pathRelativeToJenkinsRoot.getPath()),
fileTranslatedInScm);
} catch (IOException e) {
throw new LoggableException("Error while copying file hierarchy to SCM checkouted directory", FileUtils.class, "copyDirectory", e);
}
updatedFiles.addAll(scmManipulator.addFile(scmRoot, firstNonExistingParentScmPath));
}
} else {
// We should remember if file in scm existed or not before any manipulation,
// especially writing content
boolean fileTranslatedInScmInitiallyExists = fileTranslatedInScm.exists();
boolean fileContentModified = writeScmContentOnlyIfItDiffers(pathRelativeToJenkinsRoot, content, fileTranslatedInScm);
if(fileTranslatedInScmInitiallyExists){
if(fileContentModified){
// No need to call scmManipulator.addFile() if fileTranslatedInScm already existed
updatedFiles.add(fileTranslatedInScm);
}
} else {
updatedFiles.addAll(scmManipulator.addFile(scmRoot, pathRelativeToJenkinsRoot.getPath()));
}
}
}
for(Path path : commit.getChangeset().getPathsToDelete()){
List<File> deletedFiles = deleteHierarchy(commit.getScmContext(), path.getPath());
updatedFiles.addAll(deletedFiles);
}
if(updatedFiles.isEmpty()){
LOGGER.info("Empty changeset to commit (no changes found on files) => commit skipped !");
} else {
// Commiting files...
boolean result = scmManipulator.checkinFiles(scmRoot, commit.getMessage());
if(result){
LOGGER.info("Commit "+commit.toString()+" pushed to SCM !");
checkedInCommits.add(commit);
} else {
throw new LoggableException("Error while checking in file to scm repository", SCMManipulator.class, "checkinFiles");
}
signal(logMessage, true);
}
}
// As soon as a commit doesn't goes well, we should abort commit queue processing...
}catch(LoggableException e){
LOGGER.throwing(e.getClazz().getName(), e.getMethodName(), e);
LOGGER.severe("Error while processing commit queue : "+e.getMessage());
signal(e.getMessage(), false);
} finally {
// We should remove every checkedInCommits
commitsQueue.removeAll(checkedInCommits);
}
}
|
diff --git a/src/main/java/com/sparsity/dex/etl/config/bean/DatabaseConfiguration.java b/src/main/java/com/sparsity/dex/etl/config/bean/DatabaseConfiguration.java
index 1684433..aa5afbf 100644
--- a/src/main/java/com/sparsity/dex/etl/config/bean/DatabaseConfiguration.java
+++ b/src/main/java/com/sparsity/dex/etl/config/bean/DatabaseConfiguration.java
@@ -1,521 +1,521 @@
/*
* Copyright (c) 2012 Sparsity Technologies www.sparsity-technologies.com
*
* This file is part of 'dexjava-etl'.
*
* Licensed under the GNU Lesser General Public License (LGPL) v3, (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.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.sparsity.dex.etl.config.bean;
import java.io.File;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.sparsity.dex.etl.DexUtilsException;
import com.sparsity.dex.gdb.Attribute;
import com.sparsity.dex.gdb.AttributeList;
import com.sparsity.dex.gdb.AttributeListIterator;
import com.sparsity.dex.gdb.Database;
import com.sparsity.dex.gdb.Dex;
import com.sparsity.dex.gdb.DexConfig;
import com.sparsity.dex.gdb.DexProperties;
import com.sparsity.dex.gdb.Graph;
import com.sparsity.dex.gdb.Session;
import com.sparsity.dex.gdb.Type;
import com.sparsity.dex.gdb.TypeList;
import com.sparsity.dex.gdb.TypeListIterator;
/**
* Allows for opening and closing a Dex database.
* <p>
* It also automatically manages a per-thread "working" {@link Session}. The
* user just gets a Session ({@link #getSession()}) and this automatically
* creates one if required or returns its {@link Session}. Moreover, this
* provides an exclusive per-thread {@link Session}.
*
* @author Sparsity Technologies
*
*/
public class DatabaseConfiguration {
/**
* {@link Log} instance.
*/
private static Log log = LogFactory.getLog(DatabaseConfiguration.class);
/**
* Unique name for the {@link DatabaseConfiguration}.
*/
private String name = null;
/**
* Alias database.
*/
private String alias = null;
/**
* Path database.
*/
private String path = null;
/**
* Dex configuration file.
*/
private String dexConf = null;
/**
* Manages a Dex {@link Session} as well as its {@link Graph} instance.
*
* @author Sparsity Technologies
*
*/
private class SessionManager {
/**
* {@link Graph} instance.
*/
private Graph graph = null;
/**
* {@link Session} instance.
*/
private Session session = null;
/**
* Thread identifier.
*/
long thId = Thread.currentThread().getId();
/**
* Creates a new instance.
*/
public SessionManager() {
}
/**
* Closes the {@link Session}.
*/
public void closeSession() {
if (session != null && !session.isClosed()) {
session.close();
session = null;
graph = null;
log.debug("Dex Session was closed for thread " + thId);
}
}
/**
* Gets if the {@link Session} is closed.
*
* @return
*/
public boolean isClosed() {
return session == null || session.isClosed();
}
/**
* Gets the {@link Session}.
* <p>
* It creates a new one {@link Session} if there was no {@link Session}
* or if it was already closed.
*
* @return The {@link Session}.
*/
public Session getSession() {
if (isClosed()) {
session = DatabaseConfiguration.this.db.newSession();
graph = session.getGraph();
log.debug("Dex Session was created for thread " + thId);
}
return session;
}
/**
* Gets the {@link Graph}.
* <p>
* It creates a new one {@link Session} if there was no {@link Session}
* or if it was already closed.
*
* @return The {@link Graph} of the {@link Session}.
*/
public Graph getGraph() {
if (isClosed()) {
getSession();
}
return graph;
}
}
/**
* Manages a per-thread local {@link SessionManager} instance.
* <p>
* Therefore, each thread will just access its {@link SessionManager}
* instance.
*/
private ThreadLocal<SessionManager> sessMngr = new ThreadLocal<SessionManager>() {
@Override
protected SessionManager initialValue() {
return new SessionManager();
}
};
/**
* {@link DexConfig} instance.
*/
private DexConfig dexCfg = null;
/**
* {@link Dex} instance.
*/
private Dex dex = null;
/**
* {@link Database} instance.
*/
private Database db = null;
/**
* Parent {@link Configuration} instance.
*/
private Configuration configuration;
/**
* Gets the unique name.
*
* @return The unique name.
*/
public String getName() {
return name;
}
/**
* Sets the unique name.
*
* @param n
* The unique name. It cannot be <code>null</code> or a blank
* string.
*/
public void setName(String n) {
if (n == null || n.matches("[\\s]++")) {
log.error("Name cannot be null or a blank string.");
throw new IllegalArgumentException(
"Name cannot be null or a blank string.");
}
name = n;
}
/**
* Gets the alias.
*
* @return The alias.
*/
public String getAlias() {
return alias;
}
/**
* Sets the alias.
*
* @param a
* The alias. It cannot be <code>null</code> or a blank string.
*/
public void setAlias(String a) {
if (a == null || a.matches("[\\s]++")) {
log.error("Alias cannot be null or a blank string.");
throw new IllegalArgumentException(
"Alias cannot be null or a blank string.");
}
alias = a;
}
/**
* Gets the path.
*
* @return The path.
*/
public String getPath() {
return path;
}
/**
* Sets the path.
*
* @param p
* The path. It cannot be <code>null</code> or a blank string.
*/
public void setPath(String p) {
if (p == null || p.matches("[\\s]++")) {
String msg = new String("Path cannot be null or a blank string.");
log.error(msg);
throw new IllegalArgumentException(msg);
}
path = p;
}
/**
* Gets the Dex runtime configuration file path.
*
* @return The Dex runtime configuration file path.
*/
public String getDexConfiguration() {
return dexConf;
}
/**
* Sets the Dex runtime configuration file path.
*
* @param c
* The Dex runtime configuration file path.
*/
public void setDexConfiguration(String c) {
if (c == null || c.matches("[\\s]++")) {
String msg = new String(
"Dex runtime configuration file path cannot be null or a blank string.");
log.error(msg);
throw new IllegalArgumentException(msg);
}
dexConf = c;
}
/**
* Gets the parent {@link Configuration} instance.
*
* @return The parent {@link Configuration} instance.
*/
public Configuration getConfiguration() {
return configuration;
}
/**
* Sets the parent {@link Configuration} instance.
*
* @param c
* The parent {@link Configuration} instance.
*/
public void setConfiguration(Configuration c) {
configuration = c;
}
@Override
public boolean equals(Object o) {
boolean result = false;
if (o instanceof DatabaseConfiguration) {
DatabaseConfiguration aux = (DatabaseConfiguration) o;
String n = getName();
if (n == null) {
result = (aux.getName() == null);
} else {
result = n.equals(aux.getName());
}
if (result) {
String a = getAlias();
if (a == null) {
result = (aux.getAlias() == null);
} else {
result = a.equals(aux.getAlias());
}
}
if (result) {
String p = getPath();
if (p == null) {
result = (aux.getPath() == null);
} else {
result = p.equals(aux.getPath());
}
}
}
return result;
}
/**
* Gets if the Database has been already closed or not.
*
* @return <code>true</code> if closed, <code>false</code> otherwise.
*/
public boolean isClosed() {
return (dex == null && db == null);
}
/**
* Opens the Database and sets the working {@link Session} for the calling
* thread.
* <p>
* The Database is open once, so this opens the Database just if it has not
* been opened before.
* <p>
* In any case, it starts the working {@link Session} for the calling thread
* if necessary.
*/
public void openDatabase() {
if (isClosed()) {
File f = new File(getPath());
if (dexConf != null) {
DexProperties.load(dexConf);
}
dexCfg = new DexConfig();
dex = new Dex(dexCfg);
db = null;
try {
if (f.exists()) {
- db = dex.open(f.getAbsolutePath(), true);
+ db = dex.open(f.getAbsolutePath(), false);
if (db.getAlias().compareTo(getAlias()) != 0) {
throw new DexUtilsException(
"Database with an unexpected name/alias");
}
} else {
db = dex.create(f.getAbsolutePath(), alias);
}
} catch (Exception e) {
String msg = new String("DexUtils cannot open/create the "
+ getAlias() + " database " + "located at "
+ f.getAbsolutePath());
log.error(msg, e);
throw new DexUtilsException(msg, e);
}
log.info("Database " + getAlias() + "[" + f.getAbsolutePath()
+ "] was opened");
}
this.sessMngr.get().getSession();
}
/**
* Closes and opens the Database.
* <p>
* Closing the database closes the working {@link Session}.
*/
public void restartDatabase() {
closeDatabase();
openDatabase();
}
/**
* Closes the Database.
* <p>
* Therefore it also closes the working {@link Session}.
*/
public void closeDatabase() {
//
// FIXME This just closes the Session of the calling thread, others may
// remain
// open!
//
if (!sessMngr.get().isClosed()) {
sessMngr.get().closeSession();
}
if (!isClosed()) {
db.close();
db = null;
dex.close();
dex = null;
log.info("Database " + getAlias() + " was closed");
}
}
/**
* Gets the working {@link Session} for the calling thread.
* <p>
* If necessary, it creates a new {@link Session}.
*
* @return The working {@link Session} for the calling thread.
*/
public Session getSession() {
return sessMngr.get().getSession();
}
/**
* Gets the {@link Graph} of the working {@link Session} for the calling
* thread.
* <p>
* If necessary, it creates a new {@link Session}.
*
* @return The working {@link Graph} for the calling thread.
*/
public Graph getGraph() {
return sessMngr.get().getGraph();
}
/**
* Drops all attributes and node and edge types.
*/
public void dropSchema() {
if (isClosed()) {
openDatabase();
}
Graph graph = sessMngr.get().getGraph();
TypeList types = graph.findEdgeTypes();
TypeListIterator typeIt = types.iterator();
while (typeIt.hasNext()) {
Integer type = typeIt.next();
AttributeList alist = graph.findAttributes(type);
AttributeListIterator attrIt = alist.iterator();
while (attrIt.hasNext()) {
graph.removeAttribute(attrIt.next());
}
graph.removeType(type);
}
types = graph.findNodeTypes();
typeIt = types.iterator();
while (typeIt.hasNext()) {
Integer type = typeIt.next();
AttributeList alist = graph.findAttributes(type);
AttributeListIterator attrIt = alist.iterator();
while (attrIt.hasNext()) {
graph.removeAttribute(attrIt.next());
}
graph.removeType(type);
}
log.info("Schema for the Database " + getAlias() + " was droped");
}
/**
* Gets the Dex attribute identifier for the given attribute.
*
* @param typename
* Node or edge type name.
* @param name
* Attribute name.
* @return The Dex attribute identifier or
* {@link Attribute#InvalidAttribute} if if does not exist.
*/
public Integer getAttributeIdentifier(String typename, String name) {
if (isClosed()) {
openDatabase();
}
int type = getTypeIdentifier(typename);
if (type != Type.InvalidType) {
return sessMngr.get().getGraph().findAttribute(type, name);
} else {
return Attribute.InvalidAttribute;
}
}
/**
* Gets the Dex type identifier for the given type.
*
* @param name
* Node or edge type name.
* @return The Dex node or edge type identifier or {@link Type#InvalidType}
* if it does not exist.
*/
public Integer getTypeIdentifier(String name) {
if (isClosed()) {
openDatabase();
}
return sessMngr.get().getGraph().findType(name);
}
}
| true | true | public void openDatabase() {
if (isClosed()) {
File f = new File(getPath());
if (dexConf != null) {
DexProperties.load(dexConf);
}
dexCfg = new DexConfig();
dex = new Dex(dexCfg);
db = null;
try {
if (f.exists()) {
db = dex.open(f.getAbsolutePath(), true);
if (db.getAlias().compareTo(getAlias()) != 0) {
throw new DexUtilsException(
"Database with an unexpected name/alias");
}
} else {
db = dex.create(f.getAbsolutePath(), alias);
}
} catch (Exception e) {
String msg = new String("DexUtils cannot open/create the "
+ getAlias() + " database " + "located at "
+ f.getAbsolutePath());
log.error(msg, e);
throw new DexUtilsException(msg, e);
}
log.info("Database " + getAlias() + "[" + f.getAbsolutePath()
+ "] was opened");
}
this.sessMngr.get().getSession();
}
| public void openDatabase() {
if (isClosed()) {
File f = new File(getPath());
if (dexConf != null) {
DexProperties.load(dexConf);
}
dexCfg = new DexConfig();
dex = new Dex(dexCfg);
db = null;
try {
if (f.exists()) {
db = dex.open(f.getAbsolutePath(), false);
if (db.getAlias().compareTo(getAlias()) != 0) {
throw new DexUtilsException(
"Database with an unexpected name/alias");
}
} else {
db = dex.create(f.getAbsolutePath(), alias);
}
} catch (Exception e) {
String msg = new String("DexUtils cannot open/create the "
+ getAlias() + " database " + "located at "
+ f.getAbsolutePath());
log.error(msg, e);
throw new DexUtilsException(msg, e);
}
log.info("Database " + getAlias() + "[" + f.getAbsolutePath()
+ "] was opened");
}
this.sessMngr.get().getSession();
}
|
diff --git a/core/src/main/java/org/acegisecurity/intercept/web/FilterInvocationDefinitionSourceEditor.java b/core/src/main/java/org/acegisecurity/intercept/web/FilterInvocationDefinitionSourceEditor.java
index 7b8450bbc..133e586d6 100644
--- a/core/src/main/java/org/acegisecurity/intercept/web/FilterInvocationDefinitionSourceEditor.java
+++ b/core/src/main/java/org/acegisecurity/intercept/web/FilterInvocationDefinitionSourceEditor.java
@@ -1,175 +1,175 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.acegisecurity.intercept.web;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.beans.PropertyEditorSupport;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
/**
* Property editor to assist with the setup of a {@link FilterInvocationDefinitionSource}.<p>The class creates and
* populates a {@link RegExpBasedFilterInvocationDefinitionMap} or {@link PathBasedFilterInvocationDefinitionMap}
* (depending on the type of patterns presented).</p>
* <p>By default the class treats presented patterns as regular expressions. If the keyword
* <code>PATTERN_TYPE_APACHE_ANT</code> is present (case sensitive), patterns will be treated as Apache Ant paths
* rather than regular expressions.</p>
*
* @author Ben Alex
* @version $Id$
*/
public class FilterInvocationDefinitionSourceEditor extends PropertyEditorSupport {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(FilterInvocationDefinitionSourceEditor.class);
public static final String DIRECTIVE_CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON = "CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON";
public static final String DIRECTIVE_PATTERN_TYPE_APACHE_ANT = "PATTERN_TYPE_APACHE_ANT";
//~ Methods ========================================================================================================
public void setAsText(String s) throws IllegalArgumentException {
FilterInvocationDefinitionDecorator source = new FilterInvocationDefinitionDecorator();
source.setDecorated(new RegExpBasedFilterInvocationDefinitionMap());
if ((s == null) || "".equals(s)) {
// Leave target object empty
} else {
// Check if we need to override the default definition map
if (s.lastIndexOf(DIRECTIVE_PATTERN_TYPE_APACHE_ANT) != -1) {
source.setDecorated(new PathBasedFilterInvocationDefinitionMap());
if (logger.isDebugEnabled()) {
logger.debug(("Detected " + DIRECTIVE_PATTERN_TYPE_APACHE_ANT
+ " directive; using Apache Ant style path expressions"));
}
}
if (s.lastIndexOf(DIRECTIVE_CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON) != -1) {
if (logger.isDebugEnabled()) {
logger.debug("Detected " + DIRECTIVE_CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
+ " directive; Instructing mapper to convert URLs to lowercase before comparison");
}
source.setConvertUrlToLowercaseBeforeComparison(true);
}
BufferedReader br = new BufferedReader(new StringReader(s));
int counter = 0;
String line;
List mappings = new ArrayList();
while (true) {
counter++;
try {
line = br.readLine();
} catch (IOException ioe) {
throw new IllegalArgumentException(ioe.getMessage());
}
if (line == null) {
break;
}
line = line.trim();
if (logger.isDebugEnabled()) {
logger.debug("Line " + counter + ": " + line);
}
if (line.startsWith("//")) {
continue;
}
// Attempt to detect malformed lines (as per SEC-204)
if (line.lastIndexOf(DIRECTIVE_CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON) != -1) {
// Directive found; check for second directive or name=value
if ((line.lastIndexOf(DIRECTIVE_PATTERN_TYPE_APACHE_ANT) != -1) || (line.lastIndexOf("=") != -1)) {
throw new IllegalArgumentException("Line appears to be malformed: " + line);
}
}
// Attempt to detect malformed lines (as per SEC-204)
if (line.lastIndexOf(DIRECTIVE_PATTERN_TYPE_APACHE_ANT) != -1) {
// Directive found; check for second directive or name=value
if ((line.lastIndexOf(DIRECTIVE_CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON) != -1)
|| (line.lastIndexOf("=") != -1)) {
throw new IllegalArgumentException("Line appears to be malformed: " + line);
}
}
// Skip lines that are not directives
if (line.lastIndexOf('=') == -1) {
continue;
}
if (line.lastIndexOf("==") != -1) {
throw new IllegalArgumentException("Only single equals should be used in line " + line);
}
// Tokenize the line into its name/value tokens
// As per SEC-219, use the LAST equals as the delimiter between LHS and RHS
String name = StringUtils.substringBeforeLast(line, "=");
String value = StringUtils.substringAfterLast(line, "=");
if (StringUtils.isBlank(name) || StringUtils.isBlank(value)) {
throw new IllegalArgumentException("Failed to parse a valid name/value pair from " + line);
}
// Attempt to detect malformed lines (as per SEC-204)
if (source.isConvertUrlToLowercaseBeforeComparison()
&& source.getDecorated() instanceof PathBasedFilterInvocationDefinitionMap) {
// Should all be lowercase; check each character
// We only do this for Ant (regexp have control chars)
for (int i = 0; i < name.length(); i++) {
String character = name.substring(i, i + 1);
if (!character.toLowerCase().equals(character)) {
throw new IllegalArgumentException("You are using the "
+ DIRECTIVE_CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
+ " with Ant Paths, yet you have specified an uppercase character in line: " + line
+ " (character '" + character + "')");
}
}
}
FilterInvocationDefinitionSourceMapping mapping = new FilterInvocationDefinitionSourceMapping();
mapping.setUrl(name);
String[] tokens = org.springframework.util.StringUtils
.commaDelimitedListToStringArray(value);
for (int i = 0; i < tokens.length; i++) {
mapping.addConfigAttribute(tokens[i].trim());
}
mappings.add(mapping);
}
source.setMappings(mappings);
}
- setValue(source);
+ setValue(source.getDecorated());
}
}
| true | true | public void setAsText(String s) throws IllegalArgumentException {
FilterInvocationDefinitionDecorator source = new FilterInvocationDefinitionDecorator();
source.setDecorated(new RegExpBasedFilterInvocationDefinitionMap());
if ((s == null) || "".equals(s)) {
// Leave target object empty
} else {
// Check if we need to override the default definition map
if (s.lastIndexOf(DIRECTIVE_PATTERN_TYPE_APACHE_ANT) != -1) {
source.setDecorated(new PathBasedFilterInvocationDefinitionMap());
if (logger.isDebugEnabled()) {
logger.debug(("Detected " + DIRECTIVE_PATTERN_TYPE_APACHE_ANT
+ " directive; using Apache Ant style path expressions"));
}
}
if (s.lastIndexOf(DIRECTIVE_CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON) != -1) {
if (logger.isDebugEnabled()) {
logger.debug("Detected " + DIRECTIVE_CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
+ " directive; Instructing mapper to convert URLs to lowercase before comparison");
}
source.setConvertUrlToLowercaseBeforeComparison(true);
}
BufferedReader br = new BufferedReader(new StringReader(s));
int counter = 0;
String line;
List mappings = new ArrayList();
while (true) {
counter++;
try {
line = br.readLine();
} catch (IOException ioe) {
throw new IllegalArgumentException(ioe.getMessage());
}
if (line == null) {
break;
}
line = line.trim();
if (logger.isDebugEnabled()) {
logger.debug("Line " + counter + ": " + line);
}
if (line.startsWith("//")) {
continue;
}
// Attempt to detect malformed lines (as per SEC-204)
if (line.lastIndexOf(DIRECTIVE_CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON) != -1) {
// Directive found; check for second directive or name=value
if ((line.lastIndexOf(DIRECTIVE_PATTERN_TYPE_APACHE_ANT) != -1) || (line.lastIndexOf("=") != -1)) {
throw new IllegalArgumentException("Line appears to be malformed: " + line);
}
}
// Attempt to detect malformed lines (as per SEC-204)
if (line.lastIndexOf(DIRECTIVE_PATTERN_TYPE_APACHE_ANT) != -1) {
// Directive found; check for second directive or name=value
if ((line.lastIndexOf(DIRECTIVE_CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON) != -1)
|| (line.lastIndexOf("=") != -1)) {
throw new IllegalArgumentException("Line appears to be malformed: " + line);
}
}
// Skip lines that are not directives
if (line.lastIndexOf('=') == -1) {
continue;
}
if (line.lastIndexOf("==") != -1) {
throw new IllegalArgumentException("Only single equals should be used in line " + line);
}
// Tokenize the line into its name/value tokens
// As per SEC-219, use the LAST equals as the delimiter between LHS and RHS
String name = StringUtils.substringBeforeLast(line, "=");
String value = StringUtils.substringAfterLast(line, "=");
if (StringUtils.isBlank(name) || StringUtils.isBlank(value)) {
throw new IllegalArgumentException("Failed to parse a valid name/value pair from " + line);
}
// Attempt to detect malformed lines (as per SEC-204)
if (source.isConvertUrlToLowercaseBeforeComparison()
&& source.getDecorated() instanceof PathBasedFilterInvocationDefinitionMap) {
// Should all be lowercase; check each character
// We only do this for Ant (regexp have control chars)
for (int i = 0; i < name.length(); i++) {
String character = name.substring(i, i + 1);
if (!character.toLowerCase().equals(character)) {
throw new IllegalArgumentException("You are using the "
+ DIRECTIVE_CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
+ " with Ant Paths, yet you have specified an uppercase character in line: " + line
+ " (character '" + character + "')");
}
}
}
FilterInvocationDefinitionSourceMapping mapping = new FilterInvocationDefinitionSourceMapping();
mapping.setUrl(name);
String[] tokens = org.springframework.util.StringUtils
.commaDelimitedListToStringArray(value);
for (int i = 0; i < tokens.length; i++) {
mapping.addConfigAttribute(tokens[i].trim());
}
mappings.add(mapping);
}
source.setMappings(mappings);
}
setValue(source);
}
| public void setAsText(String s) throws IllegalArgumentException {
FilterInvocationDefinitionDecorator source = new FilterInvocationDefinitionDecorator();
source.setDecorated(new RegExpBasedFilterInvocationDefinitionMap());
if ((s == null) || "".equals(s)) {
// Leave target object empty
} else {
// Check if we need to override the default definition map
if (s.lastIndexOf(DIRECTIVE_PATTERN_TYPE_APACHE_ANT) != -1) {
source.setDecorated(new PathBasedFilterInvocationDefinitionMap());
if (logger.isDebugEnabled()) {
logger.debug(("Detected " + DIRECTIVE_PATTERN_TYPE_APACHE_ANT
+ " directive; using Apache Ant style path expressions"));
}
}
if (s.lastIndexOf(DIRECTIVE_CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON) != -1) {
if (logger.isDebugEnabled()) {
logger.debug("Detected " + DIRECTIVE_CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
+ " directive; Instructing mapper to convert URLs to lowercase before comparison");
}
source.setConvertUrlToLowercaseBeforeComparison(true);
}
BufferedReader br = new BufferedReader(new StringReader(s));
int counter = 0;
String line;
List mappings = new ArrayList();
while (true) {
counter++;
try {
line = br.readLine();
} catch (IOException ioe) {
throw new IllegalArgumentException(ioe.getMessage());
}
if (line == null) {
break;
}
line = line.trim();
if (logger.isDebugEnabled()) {
logger.debug("Line " + counter + ": " + line);
}
if (line.startsWith("//")) {
continue;
}
// Attempt to detect malformed lines (as per SEC-204)
if (line.lastIndexOf(DIRECTIVE_CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON) != -1) {
// Directive found; check for second directive or name=value
if ((line.lastIndexOf(DIRECTIVE_PATTERN_TYPE_APACHE_ANT) != -1) || (line.lastIndexOf("=") != -1)) {
throw new IllegalArgumentException("Line appears to be malformed: " + line);
}
}
// Attempt to detect malformed lines (as per SEC-204)
if (line.lastIndexOf(DIRECTIVE_PATTERN_TYPE_APACHE_ANT) != -1) {
// Directive found; check for second directive or name=value
if ((line.lastIndexOf(DIRECTIVE_CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON) != -1)
|| (line.lastIndexOf("=") != -1)) {
throw new IllegalArgumentException("Line appears to be malformed: " + line);
}
}
// Skip lines that are not directives
if (line.lastIndexOf('=') == -1) {
continue;
}
if (line.lastIndexOf("==") != -1) {
throw new IllegalArgumentException("Only single equals should be used in line " + line);
}
// Tokenize the line into its name/value tokens
// As per SEC-219, use the LAST equals as the delimiter between LHS and RHS
String name = StringUtils.substringBeforeLast(line, "=");
String value = StringUtils.substringAfterLast(line, "=");
if (StringUtils.isBlank(name) || StringUtils.isBlank(value)) {
throw new IllegalArgumentException("Failed to parse a valid name/value pair from " + line);
}
// Attempt to detect malformed lines (as per SEC-204)
if (source.isConvertUrlToLowercaseBeforeComparison()
&& source.getDecorated() instanceof PathBasedFilterInvocationDefinitionMap) {
// Should all be lowercase; check each character
// We only do this for Ant (regexp have control chars)
for (int i = 0; i < name.length(); i++) {
String character = name.substring(i, i + 1);
if (!character.toLowerCase().equals(character)) {
throw new IllegalArgumentException("You are using the "
+ DIRECTIVE_CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
+ " with Ant Paths, yet you have specified an uppercase character in line: " + line
+ " (character '" + character + "')");
}
}
}
FilterInvocationDefinitionSourceMapping mapping = new FilterInvocationDefinitionSourceMapping();
mapping.setUrl(name);
String[] tokens = org.springframework.util.StringUtils
.commaDelimitedListToStringArray(value);
for (int i = 0; i < tokens.length; i++) {
mapping.addConfigAttribute(tokens[i].trim());
}
mappings.add(mapping);
}
source.setMappings(mappings);
}
setValue(source.getDecorated());
}
|
diff --git a/src-tools/org/seasr/meandre/components/tools/basic/PushText.java b/src-tools/org/seasr/meandre/components/tools/basic/PushText.java
index 9536b529..72a2c922 100644
--- a/src-tools/org/seasr/meandre/components/tools/basic/PushText.java
+++ b/src-tools/org/seasr/meandre/components/tools/basic/PushText.java
@@ -1,128 +1,129 @@
/**
*
* University of Illinois/NCSA
* Open Source License
*
* Copyright (c) 2008, NCSA. All rights reserved.
*
* Developed by:
* The Automated Learning Group
* University of Illinois at Urbana-Champaign
* http://www.seasr.org
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal with the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimers.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimers in
* the documentation and/or other materials provided with the distribution.
*
* Neither the names of The Automated Learning Group, University of
* Illinois at Urbana-Champaign, nor the names of its contributors may
* be used to endorse or promote products derived from this Software
* without specific prior written permission.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE SOFTWARE.
*
*/
package org.seasr.meandre.components.tools.basic;
import org.meandre.annotations.Component;
import org.meandre.annotations.Component.FiringPolicy;
import org.meandre.annotations.Component.Licenses;
import org.meandre.annotations.Component.Mode;
import org.meandre.annotations.ComponentOutput;
import org.meandre.annotations.ComponentProperty;
import org.meandre.core.ComponentContext;
import org.meandre.core.ComponentContextProperties;
import org.seasr.datatypes.core.BasicDataTypesTools;
import org.seasr.datatypes.core.Names;
import org.seasr.meandre.components.abstracts.AbstractExecutableComponent;
/**
* Pushes text from a property to the output
*
* @author Boris Capitanu
*
*/
@Component(
name = "Push Text",
creator = "Boris Capitanu",
baseURL = "meandre://seasr.org/components/foundry/",
firingPolicy = FiringPolicy.all,
mode = Mode.compute,
rights = Licenses.UofINCSA,
tags = "#INPUT, io, string, text",
description = "Pushes the value of the text message property to the output.",
dependency = {"protobuf-java-2.2.0.jar"}
)
public class PushText extends AbstractExecutableComponent {
//------------------------------ OUTPUTS -----------------------------------------------------
@ComponentOutput(
name = Names.PORT_TEXT,
description = "The text message being pushed" +
"<br>TYPE: org.seasr.datatypes.BasicDataTypes.Strings"
)
protected static final String OUT_TEXT = Names.PORT_TEXT;
//------------------------------ PROPERTIES --------------------------------------------------
@ComponentProperty(
name = Names.PROP_MESSAGE,
description = "The text message to push. ",
defaultValue = ""
)
protected static final String PROP_MESSAGE = Names.PROP_MESSAGE;
@ComponentProperty(
name = "parse_newlines",
description = "Should the string '\\n' in a replacement expression be interpreted as a newline?",
defaultValue = "true"
)
protected static final String PROP_PARSE_NEWLINES = "parse_newlines";
//--------------------------------------------------------------------------------------------
private String _text;
private boolean bParseNewlines;
//--------------------------------------------------------------------------------------------
@Override
public void initializeCallBack(ComponentContextProperties ccp) throws Exception {
_text = getPropertyOrDieTrying(PROP_MESSAGE, false, false, ccp);
+ bParseNewlines = Boolean.parseBoolean(ccp.getProperty(PROP_PARSE_NEWLINES));
if (bParseNewlines)
_text = _text.replaceAll("\\\\n", "\n");
if (_text.length() == 0)
console.warning("Pushing the empty string");
}
@Override
public void executeCallBack(ComponentContext cc) throws Exception {
console.fine("Pushing:\n"+_text+"\n");
cc.pushDataComponentToOutput(OUT_TEXT, BasicDataTypesTools.stringToStrings(_text));
}
@Override
public void disposeCallBack(ComponentContextProperties ccp) throws Exception {
}
}
| true | true | public void initializeCallBack(ComponentContextProperties ccp) throws Exception {
_text = getPropertyOrDieTrying(PROP_MESSAGE, false, false, ccp);
if (bParseNewlines)
_text = _text.replaceAll("\\\\n", "\n");
if (_text.length() == 0)
console.warning("Pushing the empty string");
}
| public void initializeCallBack(ComponentContextProperties ccp) throws Exception {
_text = getPropertyOrDieTrying(PROP_MESSAGE, false, false, ccp);
bParseNewlines = Boolean.parseBoolean(ccp.getProperty(PROP_PARSE_NEWLINES));
if (bParseNewlines)
_text = _text.replaceAll("\\\\n", "\n");
if (_text.length() == 0)
console.warning("Pushing the empty string");
}
|
diff --git a/blobstore/src/main/java/org/jboss/capedwarf/blobstore/CapedwarfBlobstoreService.java b/blobstore/src/main/java/org/jboss/capedwarf/blobstore/CapedwarfBlobstoreService.java
index 2b2a3194..977b279d 100644
--- a/blobstore/src/main/java/org/jboss/capedwarf/blobstore/CapedwarfBlobstoreService.java
+++ b/blobstore/src/main/java/org/jboss/capedwarf/blobstore/CapedwarfBlobstoreService.java
@@ -1,309 +1,309 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.capedwarf.blobstore;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreFailureException;
import com.google.appengine.api.blobstore.ByteRange;
import com.google.appengine.api.blobstore.FileInfo;
import com.google.appengine.api.blobstore.RangeFormatException;
import com.google.appengine.api.blobstore.UnsupportedRangeFormatException;
import com.google.appengine.api.blobstore.UploadOptions;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.jboss.capedwarf.common.io.IOUtils;
import org.jboss.capedwarf.common.servlet.ServletUtils;
import org.jboss.capedwarf.files.ExposedFileService;
/**
* @author <a href="mailto:[email protected]">Ales Justin</a>
* @author <a href="mailto:[email protected]">Marko Luksa</a>
*/
public class CapedwarfBlobstoreService implements ExposedBlobstoreService {
private static final String UPLOADED_BLOBKEY_ATTR = "com.google.appengine.api.blobstore.upload.blobkeys";
private static final String UPLOADED_BLOBKEY_LIST_ATTR = "com.google.appengine.api.blobstore.upload.blobkeylists";
private Function<List<BlobKey>, List<BlobInfo>> BLOB_LIST_KEY_TO_INFO_FN = new Function<List<BlobKey>, List<BlobInfo>>() {
public List<BlobInfo> apply(List<BlobKey> input) {
return Lists.transform(input, BLOB_KEY_TO_INFO_FN);
}
};
private Function<BlobKey, BlobInfo> BLOB_KEY_TO_INFO_FN = new Function<BlobKey, BlobInfo>() {
public BlobInfo apply(BlobKey input) {
return getBlobInfo(input);
}
};
private Function<List<BlobKey>, List<FileInfo>> FILE_LIST_KEY_TO_INFO_FN = new Function<List<BlobKey>, List<FileInfo>>() {
public List<FileInfo> apply(List<BlobKey> input) {
return Lists.transform(input, FILE_KEY_TO_INFO_FN);
}
};
private Function<BlobKey, FileInfo> FILE_KEY_TO_INFO_FN = new Function<BlobKey, FileInfo>() {
public FileInfo apply(BlobKey input) {
return getFileService().getFileInfo(input);
}
};
private ExposedFileService fileService;
private synchronized ExposedFileService getFileService() {
if (fileService == null) {
fileService = (ExposedFileService) FileServiceFactory.getFileService();
}
return fileService;
}
public String createUploadUrl(String successPath) {
return createUploadUrl(successPath, UploadOptions.Builder.withDefaults());
}
public String createUploadUrl(String successPath, UploadOptions uploadOptions) {
return UploadServlet.createUploadUrl(successPath, uploadOptions);
}
public void delete(BlobKey... blobKeys) {
getFileService().delete(blobKeys);
}
public void serve(BlobKey blobKey, HttpServletResponse response) throws IOException {
serve(blobKey, (ByteRange) null, response);
}
public void serve(BlobKey blobKey, String rangeHeader, HttpServletResponse response) throws IOException {
serve(blobKey, ByteRange.parse(rangeHeader), response);
}
public void serve(BlobKey blobKey, ByteRange byteRange, HttpServletResponse response) throws IOException {
assertNotCommited(response);
response.setStatus(HttpServletResponse.SC_OK);
response.setHeader(BLOB_KEY_HEADER, blobKey.getKeyString());
if (byteRange != null) {
response.setHeader(BLOB_RANGE_HEADER, byteRange.toString());
}
}
public void serveBlob(BlobKey blobKey, String byteRangeStr, HttpServletResponse response) throws IOException {
assertNotCommited(response);
BlobInfo blobInfo = getBlobInfo(blobKey);
+ if (blobInfo == null) {
+ throw new IOException(String.format("No such blob for key: %s", blobKey));
+ }
response.setContentType(blobInfo.getContentType());
ByteRange byteRange = null;
if (byteRangeStr == null) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
try {
byteRange = ByteRange.parse(byteRangeStr);
} catch (RangeFormatException e) {
response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return;
}
if (byteRange.getStart() >= blobInfo.getSize()) {
response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return;
}
- if (byteRange.hasEnd() && byteRange.getEnd() >= blobInfo.getSize()) {
- byteRange = new ByteRange(byteRange.getStart(), blobInfo.getSize()-1);
+ if ((byteRange.hasEnd() == false) || (byteRange.getEnd() >= blobInfo.getSize())) {
+ byteRange = new ByteRange(byteRange.getStart(), blobInfo.getSize() - 1);
}
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
response.setHeader("Content-Range", "bytes " + byteRange.getStart() + "-" + byteRange.getEnd() + "/" + blobInfo.getSize());
}
try {
- InputStream in = getStream(blobKey);
- try {
+ try (InputStream in = getStream(blobKey)) {
copyStream(in, response.getOutputStream(), byteRange);
- } finally {
- in.close();
}
} catch (FileNotFoundException e) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
private BlobInfo getBlobInfo(BlobKey blobKey) {
return getFileService().getBlobInfo(blobKey);
}
private void assertNotCommited(HttpServletResponse response) {
if (response.isCommitted()) {
throw new IllegalStateException("Response was already committed.");
}
}
private void copyStream(InputStream in, OutputStream out, ByteRange range) throws IOException {
if (range == null) {
IOUtils.copyStream(in, out);
} else {
if (range.hasEnd()) {
long length = range.getEnd() + 1 - range.getStart(); // end is inclusive, hence +1
IOUtils.copyStream(in, out, range.getStart(), length);
} else {
IOUtils.copyStream(in, out, range.getStart());
}
}
}
public byte[] fetchData(BlobKey blobKey, long startIndex, long endIndex) {
if (startIndex < 0) {
throw new IllegalArgumentException("startIndex must be >= 0");
}
if (endIndex < startIndex) {
throw new IllegalArgumentException("endIndex must be >= startIndex");
}
long fetchSize = endIndex - startIndex + 1;
if (fetchSize > MAX_BLOB_FETCH_SIZE) {
throw new IllegalArgumentException("Blob fetch size " + fetchSize + " is larger than MAX_BLOB_FETCH_SIZE (" + MAX_BLOB_FETCH_SIZE + ")");
}
try {
InputStream stream = getStream(blobKey);
return IOUtils.toBytes(stream, startIndex, endIndex, true);
} catch (FileNotFoundException e) {
throw new IllegalArgumentException("Blob does not exist");
} catch (IOException e) {
throw new BlobstoreFailureException("An unexpected error occured", e);
}
}
@SuppressWarnings("unchecked")
public ByteRange getByteRange(HttpServletRequest request) {
Enumeration<String> rangeHeaders = request.getHeaders("range");
if (!rangeHeaders.hasMoreElements()) {
return null;
}
String rangeHeader = rangeHeaders.nextElement();
if (rangeHeaders.hasMoreElements()) {
throw new UnsupportedRangeFormatException("Cannot accept multiple range headers.");
}
return ByteRange.parse(rangeHeader);
}
public void storeUploadedBlobs(HttpServletRequest request) throws IOException, ServletException {
Map<String, BlobKey> map = new HashMap<String, BlobKey>();
Map<String, List<BlobKey>> map2 = new HashMap<String, List<BlobKey>>();
for (Part part : request.getParts()) {
if (ServletUtils.isFile(part)) {
BlobKey blobKey = storeUploadedBlob(part);
String name = part.getName();
map.put(name, blobKey);
List<BlobKey> list = map2.get(name);
if (list == null) {
list = new LinkedList<BlobKey>();
map2.put(name, list);
}
list.add(blobKey);
}
}
request.setAttribute(UPLOADED_BLOBKEY_ATTR, map);
request.setAttribute(UPLOADED_BLOBKEY_LIST_ATTR, map2);
}
private BlobKey storeUploadedBlob(Part part) throws IOException {
ExposedFileService fileService = getFileService();
AppEngineFile file = fileService.createNewBlobFile(part.getContentType(), ServletUtils.getFileName(part));
ReadableByteChannel in = Channels.newChannel(part.getInputStream());
try {
FileWriteChannel out = fileService.openWriteChannel(file, true);
try {
IOUtils.copy(in, out);
} finally {
out.closeFinally();
}
} finally {
in.close();
}
return fileService.getBlobKey(file);
}
@SuppressWarnings("unchecked")
public Map<String, BlobKey> getUploadedBlobs(HttpServletRequest request) {
Map<String, BlobKey> map = (Map<String, BlobKey>) request.getAttribute(UPLOADED_BLOBKEY_ATTR);
if (map == null) {
throw new IllegalStateException("Must be called from a blob upload callback request.");
}
return map;
}
@SuppressWarnings("unchecked")
public Map<String, List<BlobKey>> getUploads(HttpServletRequest request) {
Map<String, List<BlobKey>> map = (Map<String, List<BlobKey>>) request.getAttribute(UPLOADED_BLOBKEY_LIST_ATTR);
if (map == null) {
throw new IllegalStateException("Must be called from a blob upload callback request.");
}
return map;
}
public InputStream getStream(BlobKey blobKey) throws FileNotFoundException {
return getFileService().getStream(blobKey);
}
public BlobKey createGsBlobKey(String name) {
return null; // TODO
}
public Map<String, List<BlobInfo>> getBlobInfos(HttpServletRequest httpServletRequest) {
return Maps.transformValues(getUploads(httpServletRequest), BLOB_LIST_KEY_TO_INFO_FN);
}
public Map<String, List<FileInfo>> getFileInfos(HttpServletRequest httpServletRequest) {
return Maps.transformValues(getUploads(httpServletRequest), FILE_LIST_KEY_TO_INFO_FN);
}
}
| false | true | public void serveBlob(BlobKey blobKey, String byteRangeStr, HttpServletResponse response) throws IOException {
assertNotCommited(response);
BlobInfo blobInfo = getBlobInfo(blobKey);
response.setContentType(blobInfo.getContentType());
ByteRange byteRange = null;
if (byteRangeStr == null) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
try {
byteRange = ByteRange.parse(byteRangeStr);
} catch (RangeFormatException e) {
response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return;
}
if (byteRange.getStart() >= blobInfo.getSize()) {
response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return;
}
if (byteRange.hasEnd() && byteRange.getEnd() >= blobInfo.getSize()) {
byteRange = new ByteRange(byteRange.getStart(), blobInfo.getSize()-1);
}
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
response.setHeader("Content-Range", "bytes " + byteRange.getStart() + "-" + byteRange.getEnd() + "/" + blobInfo.getSize());
}
try {
InputStream in = getStream(blobKey);
try {
copyStream(in, response.getOutputStream(), byteRange);
} finally {
in.close();
}
} catch (FileNotFoundException e) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
| public void serveBlob(BlobKey blobKey, String byteRangeStr, HttpServletResponse response) throws IOException {
assertNotCommited(response);
BlobInfo blobInfo = getBlobInfo(blobKey);
if (blobInfo == null) {
throw new IOException(String.format("No such blob for key: %s", blobKey));
}
response.setContentType(blobInfo.getContentType());
ByteRange byteRange = null;
if (byteRangeStr == null) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
try {
byteRange = ByteRange.parse(byteRangeStr);
} catch (RangeFormatException e) {
response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return;
}
if (byteRange.getStart() >= blobInfo.getSize()) {
response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return;
}
if ((byteRange.hasEnd() == false) || (byteRange.getEnd() >= blobInfo.getSize())) {
byteRange = new ByteRange(byteRange.getStart(), blobInfo.getSize() - 1);
}
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
response.setHeader("Content-Range", "bytes " + byteRange.getStart() + "-" + byteRange.getEnd() + "/" + blobInfo.getSize());
}
try {
try (InputStream in = getStream(blobKey)) {
copyStream(in, response.getOutputStream(), byteRange);
}
} catch (FileNotFoundException e) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
|
diff --git a/src/com/android/calendar/DismissAllAlarmsService.java b/src/com/android/calendar/DismissAllAlarmsService.java
index 8541c6e1..fee76e0b 100644
--- a/src/com/android/calendar/DismissAllAlarmsService.java
+++ b/src/com/android/calendar/DismissAllAlarmsService.java
@@ -1,60 +1,60 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.android.calendar;
import android.app.IntentService;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.provider.Calendar.CalendarAlerts;
/**
* Service for asynchronously marking all fired alarms as dismissed.
*/
public class DismissAllAlarmsService extends IntentService {
private static final String[] PROJECTION = new String[] {
CalendarAlerts.STATE,
};
private static final int COLUMN_INDEX_STATE = 0;
public DismissAllAlarmsService() {
super("DismissAllAlarmsService");
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@SuppressWarnings("deprecation")
@Override
public void onHandleIntent(Intent intent) {
// Mark all fired alarms as dismissed
- Uri uri = CalendarAlerts.CONTENT_URI_BY_INSTANCE;
+ Uri uri = CalendarAlerts.CONTENT_URI;
String selection = CalendarAlerts.STATE + "=" + CalendarAlerts.FIRED;
ContentResolver resolver = getContentResolver();
ContentValues values = new ContentValues();
values.put(PROJECTION[COLUMN_INDEX_STATE], CalendarAlerts.DISMISSED);
resolver.update(uri, values, selection, null);
// Stop this service
stopSelf();
}
}
| true | true | public void onHandleIntent(Intent intent) {
// Mark all fired alarms as dismissed
Uri uri = CalendarAlerts.CONTENT_URI_BY_INSTANCE;
String selection = CalendarAlerts.STATE + "=" + CalendarAlerts.FIRED;
ContentResolver resolver = getContentResolver();
ContentValues values = new ContentValues();
values.put(PROJECTION[COLUMN_INDEX_STATE], CalendarAlerts.DISMISSED);
resolver.update(uri, values, selection, null);
// Stop this service
stopSelf();
}
| public void onHandleIntent(Intent intent) {
// Mark all fired alarms as dismissed
Uri uri = CalendarAlerts.CONTENT_URI;
String selection = CalendarAlerts.STATE + "=" + CalendarAlerts.FIRED;
ContentResolver resolver = getContentResolver();
ContentValues values = new ContentValues();
values.put(PROJECTION[COLUMN_INDEX_STATE], CalendarAlerts.DISMISSED);
resolver.update(uri, values, selection, null);
// Stop this service
stopSelf();
}
|
diff --git a/trunk/src/edu/umich/lsa/cscs/gridsweeper/GridSweeperRunner.java b/trunk/src/edu/umich/lsa/cscs/gridsweeper/GridSweeperRunner.java
index ef5a1b5..5835107 100644
--- a/trunk/src/edu/umich/lsa/cscs/gridsweeper/GridSweeperRunner.java
+++ b/trunk/src/edu/umich/lsa/cscs/gridsweeper/GridSweeperRunner.java
@@ -1,127 +1,137 @@
package edu.umich.lsa.cscs.gridsweeper;
import java.io.*;
import static edu.umich.lsa.cscs.gridsweeper.StringUtils.*;
import edu.umich.lsa.cscs.gridsweeper.parameters.ParameterMap;
/**
* The GridSweeperRunner command-line tool to actually run the model
* on the execution host.
* @author Ed Baskerville
*
*/
public class GridSweeperRunner
{
/**
* Runs the model. First, reads the {@link RunSetup} object from standard input,
* and extracts settings for the run. If file transfer is on, input files
* are then downloaded from the file transfer system. Then an adapter object
* is created as specified in the run setup and used to actually run the model.
* Finally, if necessary, files are staged back to the file transfer system
* to be retrieved at the submission host.
*/
public static void main(String[] args)
{
RunResults results;
try
{
// Load RunSetup object
- ObjectInputStream stdinStream = new ObjectInputStream(System.in);
- RunSetup setup = (RunSetup)stdinStream.readObject();
+ RunSetup setup;
+ try
+ {
+ ObjectInputStream stdinStream = new ObjectInputStream(System.in);
+ setup = (RunSetup)stdinStream.readObject();
+ }
+ catch(Exception e)
+ {
+ ObjectInputStream stdinFileStream =
+ new ObjectInputStream(new FileInputStream(".gsweep_in.0"));
+ setup = (RunSetup)stdinFileStream.readObject();
+ }
// Get GridSweeper settings
Settings settings = setup.getSettings();
// Download input files
boolean useFileTransfer = settings.getBooleanProperty("UseFileTransfer");
FileTransferSystem fts = null;
if(useFileTransfer)
{
String className = settings.getSetting("FileTransferSystemClassName");
Settings ftsSettings = settings.getSettingsForClass(className);
fts = FileTransferSystemFactory.getFactory().getFileTransferSystem(className, ftsSettings);
fts.connect();
StringMap inputFiles = setup.getInputFiles();
for(String key : inputFiles.keySet())
{
String path = inputFiles.get(key);
String fileTransferSubpath = appendPathComponent(setup.getFileTransferSubpath(), "input");
String remotePath = appendPathComponent(fileTransferSubpath, path);
String localPath = path;
fts.downloadFile(remotePath, localPath);
}
fts.disconnect();
}
String adapterClassName = settings.getSetting("AdapterClass");
Settings adapterSettings = settings.getSettingsForClass(adapterClassName);
Adapter adapter = AdapterFactory.createAdapter(adapterClassName, adapterSettings);
// Run!
ParameterMap parameters = setup.getParameters();
int runNumber = setup.getRunNumber();
int rngSeed = setup.getRngSeed();
results = adapter.run(parameters, runNumber, rngSeed);
// Stage files listed in run properties back to server (if asked for)
if(useFileTransfer)
{
fts.connect();
StringList outputFiles = setup.getOutputFiles();
for(String outputFile : outputFiles)
{
String fileTransferSubpath = setup.getFileTransferSubpath();
String remotePath = appendPathComponent(fileTransferSubpath, outputFile);
fts.uploadFile(outputFile, remotePath);
}
fts.disconnect();
}
// If file transfer is off, write standard output and standard error
// to local files.
// If file transfer is on, this will happen at the client end of things
if(!useFileTransfer)
{
String stdoutFilename = "stdout." + runNumber;
byte[] stdoutData = results.getStdoutData();
writeData(stdoutFilename, stdoutData);
String stderrFilename = "stderr." + runNumber;
byte[] stderrData = results.getStderrData();
writeData(stderrFilename, stderrData);
}
}
catch(Exception e)
{
e.printStackTrace();
results = new RunResults(e);
}
// Write results to stdout
// Set up ObjectOutputStream to write RunResults object
try
{
ObjectOutputStream stdoutStream = new ObjectOutputStream(System.out);
stdoutStream.writeObject(results);
}
catch(Exception e) {}
}
private static void writeData(String filename, byte[] data) throws IOException
{
OutputStream os = new BufferedOutputStream(new FileOutputStream(filename));
os.write(data);
os.close();
}
}
| true | true | public static void main(String[] args)
{
RunResults results;
try
{
// Load RunSetup object
ObjectInputStream stdinStream = new ObjectInputStream(System.in);
RunSetup setup = (RunSetup)stdinStream.readObject();
// Get GridSweeper settings
Settings settings = setup.getSettings();
// Download input files
boolean useFileTransfer = settings.getBooleanProperty("UseFileTransfer");
FileTransferSystem fts = null;
if(useFileTransfer)
{
String className = settings.getSetting("FileTransferSystemClassName");
Settings ftsSettings = settings.getSettingsForClass(className);
fts = FileTransferSystemFactory.getFactory().getFileTransferSystem(className, ftsSettings);
fts.connect();
StringMap inputFiles = setup.getInputFiles();
for(String key : inputFiles.keySet())
{
String path = inputFiles.get(key);
String fileTransferSubpath = appendPathComponent(setup.getFileTransferSubpath(), "input");
String remotePath = appendPathComponent(fileTransferSubpath, path);
String localPath = path;
fts.downloadFile(remotePath, localPath);
}
fts.disconnect();
}
String adapterClassName = settings.getSetting("AdapterClass");
Settings adapterSettings = settings.getSettingsForClass(adapterClassName);
Adapter adapter = AdapterFactory.createAdapter(adapterClassName, adapterSettings);
// Run!
ParameterMap parameters = setup.getParameters();
int runNumber = setup.getRunNumber();
int rngSeed = setup.getRngSeed();
results = adapter.run(parameters, runNumber, rngSeed);
// Stage files listed in run properties back to server (if asked for)
if(useFileTransfer)
{
fts.connect();
StringList outputFiles = setup.getOutputFiles();
for(String outputFile : outputFiles)
{
String fileTransferSubpath = setup.getFileTransferSubpath();
String remotePath = appendPathComponent(fileTransferSubpath, outputFile);
fts.uploadFile(outputFile, remotePath);
}
fts.disconnect();
}
// If file transfer is off, write standard output and standard error
// to local files.
// If file transfer is on, this will happen at the client end of things
if(!useFileTransfer)
{
String stdoutFilename = "stdout." + runNumber;
byte[] stdoutData = results.getStdoutData();
writeData(stdoutFilename, stdoutData);
String stderrFilename = "stderr." + runNumber;
byte[] stderrData = results.getStderrData();
writeData(stderrFilename, stderrData);
}
}
catch(Exception e)
{
e.printStackTrace();
results = new RunResults(e);
}
// Write results to stdout
// Set up ObjectOutputStream to write RunResults object
try
{
ObjectOutputStream stdoutStream = new ObjectOutputStream(System.out);
stdoutStream.writeObject(results);
}
catch(Exception e) {}
}
| public static void main(String[] args)
{
RunResults results;
try
{
// Load RunSetup object
RunSetup setup;
try
{
ObjectInputStream stdinStream = new ObjectInputStream(System.in);
setup = (RunSetup)stdinStream.readObject();
}
catch(Exception e)
{
ObjectInputStream stdinFileStream =
new ObjectInputStream(new FileInputStream(".gsweep_in.0"));
setup = (RunSetup)stdinFileStream.readObject();
}
// Get GridSweeper settings
Settings settings = setup.getSettings();
// Download input files
boolean useFileTransfer = settings.getBooleanProperty("UseFileTransfer");
FileTransferSystem fts = null;
if(useFileTransfer)
{
String className = settings.getSetting("FileTransferSystemClassName");
Settings ftsSettings = settings.getSettingsForClass(className);
fts = FileTransferSystemFactory.getFactory().getFileTransferSystem(className, ftsSettings);
fts.connect();
StringMap inputFiles = setup.getInputFiles();
for(String key : inputFiles.keySet())
{
String path = inputFiles.get(key);
String fileTransferSubpath = appendPathComponent(setup.getFileTransferSubpath(), "input");
String remotePath = appendPathComponent(fileTransferSubpath, path);
String localPath = path;
fts.downloadFile(remotePath, localPath);
}
fts.disconnect();
}
String adapterClassName = settings.getSetting("AdapterClass");
Settings adapterSettings = settings.getSettingsForClass(adapterClassName);
Adapter adapter = AdapterFactory.createAdapter(adapterClassName, adapterSettings);
// Run!
ParameterMap parameters = setup.getParameters();
int runNumber = setup.getRunNumber();
int rngSeed = setup.getRngSeed();
results = adapter.run(parameters, runNumber, rngSeed);
// Stage files listed in run properties back to server (if asked for)
if(useFileTransfer)
{
fts.connect();
StringList outputFiles = setup.getOutputFiles();
for(String outputFile : outputFiles)
{
String fileTransferSubpath = setup.getFileTransferSubpath();
String remotePath = appendPathComponent(fileTransferSubpath, outputFile);
fts.uploadFile(outputFile, remotePath);
}
fts.disconnect();
}
// If file transfer is off, write standard output and standard error
// to local files.
// If file transfer is on, this will happen at the client end of things
if(!useFileTransfer)
{
String stdoutFilename = "stdout." + runNumber;
byte[] stdoutData = results.getStdoutData();
writeData(stdoutFilename, stdoutData);
String stderrFilename = "stderr." + runNumber;
byte[] stderrData = results.getStderrData();
writeData(stderrFilename, stderrData);
}
}
catch(Exception e)
{
e.printStackTrace();
results = new RunResults(e);
}
// Write results to stdout
// Set up ObjectOutputStream to write RunResults object
try
{
ObjectOutputStream stdoutStream = new ObjectOutputStream(System.out);
stdoutStream.writeObject(results);
}
catch(Exception e) {}
}
|
diff --git a/common/logisticspipes/routing/PathFinder.java b/common/logisticspipes/routing/PathFinder.java
index 97e8bc65..608e2084 100644
--- a/common/logisticspipes/routing/PathFinder.java
+++ b/common/logisticspipes/routing/PathFinder.java
@@ -1,271 +1,271 @@
/**
* Copyright (c) Krapht, 2011
*
* "LogisticsPipes" is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package logisticspipes.routing;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import logisticspipes.api.ILogisticsPowerProvider;
import logisticspipes.interfaces.routing.IDirectRoutingConnection;
import logisticspipes.pipes.basic.CoreRoutedPipe;
import logisticspipes.pipes.basic.fluid.LogisticsFluidConnectorPipe;
import logisticspipes.proxy.SimpleServiceLocator;
import logisticspipes.utils.Pair;
import net.minecraft.inventory.IInventory;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.ForgeDirection;
import buildcraft.api.core.Position;
import buildcraft.transport.TileGenericPipe;
import buildcraft.transport.pipes.PipeItemsDiamond;
import buildcraft.transport.pipes.PipeItemsIron;
import buildcraft.transport.pipes.PipeItemsObsidian;
import buildcraft.transport.pipes.PipeStructureCobblestone;
/**
* Examines all pipe connections and their forks to locate all connected routers
*/
public class PathFinder {
/**
* Recurse through all exists of a pipe to find instances of PipeItemsRouting. maxVisited and maxLength are safeguards for
* recursion runaways.
*
* @param startPipe - The TileGenericPipe to start the search from
* @param maxVisited - The maximum number of pipes to visit, regardless of recursion level
* @param maxLength - The maximum recurse depth, i.e. the maximum length pipe that is supported
* @return
*/
public static HashMap<CoreRoutedPipe, ExitRoute> paintAndgetConnectedRoutingPipes(TileGenericPipe startPipe, ForgeDirection startOrientation, int maxVisited, int maxLength, IPaintPath pathPainter, EnumSet<PipeRoutingConnectionType> connectionType) {
PathFinder newSearch = new PathFinder(maxVisited, maxLength, pathPainter);
newSearch.setVisited.add(startPipe);
Position p = new Position(startPipe.xCoord, startPipe.yCoord, startPipe.zCoord, startOrientation);
p.moveForwards(1);
TileEntity entity = startPipe.getWorld().getBlockTileEntity((int)p.x, (int)p.y, (int)p.z);
if (!(entity instanceof TileGenericPipe && ((TileGenericPipe)entity).pipe.canPipeConnect(startPipe, startOrientation))){
return new HashMap<CoreRoutedPipe, ExitRoute>();
}
return newSearch.getConnectedRoutingPipes((TileGenericPipe) entity, connectionType, startOrientation);
}
public HashMap<CoreRoutedPipe, ExitRoute> result;
public PathFinder(TileGenericPipe startPipe, int maxVisited, int maxLength) {
this(maxVisited, maxLength, null);
result = this.getConnectedRoutingPipes(startPipe, EnumSet.allOf(PipeRoutingConnectionType.class), ForgeDirection.UNKNOWN);
}
public PathFinder(TileGenericPipe startPipe, int maxVisited, int maxLength, ForgeDirection side) {
this(maxVisited, maxLength, null);
result=this.getConnectedRoutingPipes(startPipe, EnumSet.allOf(PipeRoutingConnectionType.class), side);
}
private PathFinder(int maxVisited, int maxLength, IPaintPath pathPainter) {
this.maxVisited = maxVisited;
this.maxLength = maxLength;
this.setVisited = new HashSet<TileGenericPipe>();
this.pathPainter = pathPainter;
}
private final int maxVisited;
private final int maxLength;
private final HashSet<TileGenericPipe> setVisited;
private final IPaintPath pathPainter;
private int pipesVisited;
public List<ILogisticsPowerProvider> powerNodes;
private HashMap<CoreRoutedPipe, ExitRoute> getConnectedRoutingPipes(TileGenericPipe startPipe, EnumSet<PipeRoutingConnectionType> connectionFlags, ForgeDirection side) {
HashMap<CoreRoutedPipe, ExitRoute> foundPipes = new HashMap<CoreRoutedPipe, ExitRoute>();
boolean root = setVisited.size() == 0;
//Reset visited count at top level
if (setVisited.size() == 1) {
pipesVisited = 0;
}
//Break recursion if we have visited a set number of pipes, to prevent client hang if pipes are weirdly configured
if (++pipesVisited > maxVisited) {
return foundPipes;
}
//Break recursion after certain amount of nodes visited
if (setVisited.size() > maxLength) {
return foundPipes;
}
if (!startPipe.initialized) {
return foundPipes;
}
//Break recursion if we end up on a routing pipe, unless its the first one. Will break if matches the first call
if (startPipe.pipe instanceof CoreRoutedPipe && setVisited.size() != 0) {
CoreRoutedPipe rp = (CoreRoutedPipe) startPipe.pipe;
if(rp.stillNeedReplace()) {
return foundPipes;
}
foundPipes.put(rp, new ExitRoute(null,rp.getRouter(), ForgeDirection.UNKNOWN, side.getOpposite(), setVisited.size(), connectionFlags));
return foundPipes;
}
//Iron, obsidean and liquid pipes will separate networks
if (startPipe.pipe instanceof LogisticsFluidConnectorPipe) {
return foundPipes;
}
//Visited is checked after, so we can reach the same target twice to allow to keep the shortest path
setVisited.add(startPipe);
// first check specialPipeConnections (tesseracts, teleports, other connectors)
if(startPipe.pipe != null) {
List<TileGenericPipe> pipez = SimpleServiceLocator.specialpipeconnection.getConnectedPipes(startPipe);
for (TileGenericPipe specialpipe : pipez){
if (setVisited.contains(specialpipe)) {
//Don't go where we have been before
continue;
}
HashMap<CoreRoutedPipe, ExitRoute> result = getConnectedRoutingPipes(specialpipe,connectionFlags, side);
for (Entry<CoreRoutedPipe, ExitRoute> pipe : result.entrySet()) {
pipe.getValue().exitOrientation = ForgeDirection.UNKNOWN;
ExitRoute foundPipe=foundPipes.get(pipe.getKey());
if (foundPipe==null || (pipe.getValue().distanceToDestination < foundPipe.distanceToDestination)) {
// New path OR If new path is better, replace old path
foundPipes.put(pipe.getKey(), pipe.getValue());
}
}
}
}
ArrayDeque<Pair<TileEntity,ForgeDirection>> connections = new ArrayDeque<Pair<TileEntity,ForgeDirection>>();
//Recurse in all directions
for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS) {
if(root && !ForgeDirection.UNKNOWN.equals(side) && !direction.equals(side)) continue;
// tile may be up to 1 second old, but any neighbour pipe change will cause an immidiate update here, so we know that if it has changed, it isn't a pipe that has done so.
TileEntity tile = startPipe.getTile(direction);
if (tile == null) continue;
if (root && tile instanceof ILogisticsPowerProvider) {
if(this.powerNodes==null) {
powerNodes = new ArrayList<ILogisticsPowerProvider>();
}
powerNodes.add((ILogisticsPowerProvider) tile);
}
connections.add(new Pair<TileEntity, ForgeDirection>(tile, direction));
}
while(!connections.isEmpty()) {
Pair<TileEntity,ForgeDirection> pair = connections.pollFirst();
TileEntity tile = pair.getValue1();
ForgeDirection direction = pair.getValue2();
EnumSet<PipeRoutingConnectionType> nextConnectionFlags = EnumSet.copyOf(connectionFlags);
boolean isDirectConnection = false;
int resistance = 0;
if(root) {
List<TileGenericPipe> list = SimpleServiceLocator.specialtileconnection.getConnectedPipes(tile);
if(!list.isEmpty()) {
for(TileGenericPipe pipe:list) {
connections.add(new Pair<TileEntity,ForgeDirection>(pipe, direction));
}
continue;
}
}
if(tile instanceof IInventory) {
if(startPipe.pipe instanceof IDirectRoutingConnection) {
if(SimpleServiceLocator.connectionManager.hasDirectConnection(((CoreRoutedPipe)startPipe.pipe).getRouter())) {
CoreRoutedPipe CRP = SimpleServiceLocator.connectionManager.getConnectedPipe(((CoreRoutedPipe)startPipe.pipe).getRouter());
if(CRP != null) {
tile = CRP.container;
isDirectConnection = true;
resistance = ((IDirectRoutingConnection)startPipe.pipe).getConnectionResistance();
}
}
}
}
if (tile == null) continue;
- if (tile instanceof TileGenericPipe && (isDirectConnection || SimpleServiceLocator.buildCraftProxy.checkPipesConnections(startPipe, tile, direction, true))) {
+ if (tile instanceof TileGenericPipe && ((TileGenericPipe)tile).pipe != null && (isDirectConnection || SimpleServiceLocator.buildCraftProxy.checkPipesConnections(startPipe, tile, direction, true))) {
TileGenericPipe currentPipe = (TileGenericPipe) tile;
if (setVisited.contains(tile)) {
//Don't go where we have been before
continue;
}
if(isDirectConnection) { //ISC doesn't pass power
nextConnectionFlags.remove(PipeRoutingConnectionType.canPowerFrom);
}
if(currentPipe.pipe instanceof PipeItemsObsidian){ //Obsidian seperates networks
continue;
}
if(currentPipe.pipe instanceof PipeStructureCobblestone){ //don't recurse onto structure pipes.
continue;
}
if(currentPipe.pipe instanceof PipeItemsDiamond){ //Diamond only allows power through
nextConnectionFlags.remove(PipeRoutingConnectionType.canRouteTo);
nextConnectionFlags.remove(PipeRoutingConnectionType.canRequestFrom);
}
if(startPipe.pipe instanceof PipeItemsIron){ //Iron requests and power can come from closed sides
if(!startPipe.pipe.outputOpen(direction)){
nextConnectionFlags.remove(PipeRoutingConnectionType.canRouteTo);
}
}
if(currentPipe.pipe instanceof PipeItemsIron){ //and can only go to the open side
if(!currentPipe.pipe.outputOpen(direction.getOpposite())){
nextConnectionFlags.remove(PipeRoutingConnectionType.canRequestFrom);
nextConnectionFlags.remove(PipeRoutingConnectionType.canPowerFrom);
}
}
if(nextConnectionFlags.isEmpty()) { //don't bother going somewhere we can't do anything with
continue;
}
int beforeRecurseCount = foundPipes.size();
HashMap<CoreRoutedPipe, ExitRoute> result = getConnectedRoutingPipes(((TileGenericPipe)tile), nextConnectionFlags, direction);
for(Entry<CoreRoutedPipe, ExitRoute> pipeEntry : result.entrySet()) {
//Update Result with the direction we took
pipeEntry.getValue().exitOrientation = direction;
ExitRoute foundPipe = foundPipes.get(pipeEntry.getKey());
if (foundPipe==null) {
// New path
foundPipes.put(pipeEntry.getKey(), pipeEntry.getValue());
//Add resistance
pipeEntry.getValue().distanceToDestination += resistance;
}
else if (pipeEntry.getValue().distanceToDestination + resistance < foundPipe.distanceToDestination) {
//If new path is better, replace old path, otherwise do nothing
foundPipes.put(pipeEntry.getKey(), pipeEntry.getValue());
//Add resistance
pipeEntry.getValue().distanceToDestination += resistance;
}
}
if (foundPipes.size() > beforeRecurseCount && pathPainter != null) {
pathPainter.addLaser(startPipe.getWorld(), new LaserData(startPipe.xCoord, startPipe.yCoord, startPipe.zCoord, direction, connectionFlags));
}
}
}
setVisited.remove(startPipe);
if(startPipe.pipe instanceof CoreRoutedPipe){ // ie, has the recursion returned to the pipe it started from?
for(ExitRoute e:foundPipes.values())
e.root=((CoreRoutedPipe)startPipe.pipe).getRouter();
}
return foundPipes;
}
}
| true | true | private HashMap<CoreRoutedPipe, ExitRoute> getConnectedRoutingPipes(TileGenericPipe startPipe, EnumSet<PipeRoutingConnectionType> connectionFlags, ForgeDirection side) {
HashMap<CoreRoutedPipe, ExitRoute> foundPipes = new HashMap<CoreRoutedPipe, ExitRoute>();
boolean root = setVisited.size() == 0;
//Reset visited count at top level
if (setVisited.size() == 1) {
pipesVisited = 0;
}
//Break recursion if we have visited a set number of pipes, to prevent client hang if pipes are weirdly configured
if (++pipesVisited > maxVisited) {
return foundPipes;
}
//Break recursion after certain amount of nodes visited
if (setVisited.size() > maxLength) {
return foundPipes;
}
if (!startPipe.initialized) {
return foundPipes;
}
//Break recursion if we end up on a routing pipe, unless its the first one. Will break if matches the first call
if (startPipe.pipe instanceof CoreRoutedPipe && setVisited.size() != 0) {
CoreRoutedPipe rp = (CoreRoutedPipe) startPipe.pipe;
if(rp.stillNeedReplace()) {
return foundPipes;
}
foundPipes.put(rp, new ExitRoute(null,rp.getRouter(), ForgeDirection.UNKNOWN, side.getOpposite(), setVisited.size(), connectionFlags));
return foundPipes;
}
//Iron, obsidean and liquid pipes will separate networks
if (startPipe.pipe instanceof LogisticsFluidConnectorPipe) {
return foundPipes;
}
//Visited is checked after, so we can reach the same target twice to allow to keep the shortest path
setVisited.add(startPipe);
// first check specialPipeConnections (tesseracts, teleports, other connectors)
if(startPipe.pipe != null) {
List<TileGenericPipe> pipez = SimpleServiceLocator.specialpipeconnection.getConnectedPipes(startPipe);
for (TileGenericPipe specialpipe : pipez){
if (setVisited.contains(specialpipe)) {
//Don't go where we have been before
continue;
}
HashMap<CoreRoutedPipe, ExitRoute> result = getConnectedRoutingPipes(specialpipe,connectionFlags, side);
for (Entry<CoreRoutedPipe, ExitRoute> pipe : result.entrySet()) {
pipe.getValue().exitOrientation = ForgeDirection.UNKNOWN;
ExitRoute foundPipe=foundPipes.get(pipe.getKey());
if (foundPipe==null || (pipe.getValue().distanceToDestination < foundPipe.distanceToDestination)) {
// New path OR If new path is better, replace old path
foundPipes.put(pipe.getKey(), pipe.getValue());
}
}
}
}
ArrayDeque<Pair<TileEntity,ForgeDirection>> connections = new ArrayDeque<Pair<TileEntity,ForgeDirection>>();
//Recurse in all directions
for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS) {
if(root && !ForgeDirection.UNKNOWN.equals(side) && !direction.equals(side)) continue;
// tile may be up to 1 second old, but any neighbour pipe change will cause an immidiate update here, so we know that if it has changed, it isn't a pipe that has done so.
TileEntity tile = startPipe.getTile(direction);
if (tile == null) continue;
if (root && tile instanceof ILogisticsPowerProvider) {
if(this.powerNodes==null) {
powerNodes = new ArrayList<ILogisticsPowerProvider>();
}
powerNodes.add((ILogisticsPowerProvider) tile);
}
connections.add(new Pair<TileEntity, ForgeDirection>(tile, direction));
}
while(!connections.isEmpty()) {
Pair<TileEntity,ForgeDirection> pair = connections.pollFirst();
TileEntity tile = pair.getValue1();
ForgeDirection direction = pair.getValue2();
EnumSet<PipeRoutingConnectionType> nextConnectionFlags = EnumSet.copyOf(connectionFlags);
boolean isDirectConnection = false;
int resistance = 0;
if(root) {
List<TileGenericPipe> list = SimpleServiceLocator.specialtileconnection.getConnectedPipes(tile);
if(!list.isEmpty()) {
for(TileGenericPipe pipe:list) {
connections.add(new Pair<TileEntity,ForgeDirection>(pipe, direction));
}
continue;
}
}
if(tile instanceof IInventory) {
if(startPipe.pipe instanceof IDirectRoutingConnection) {
if(SimpleServiceLocator.connectionManager.hasDirectConnection(((CoreRoutedPipe)startPipe.pipe).getRouter())) {
CoreRoutedPipe CRP = SimpleServiceLocator.connectionManager.getConnectedPipe(((CoreRoutedPipe)startPipe.pipe).getRouter());
if(CRP != null) {
tile = CRP.container;
isDirectConnection = true;
resistance = ((IDirectRoutingConnection)startPipe.pipe).getConnectionResistance();
}
}
}
}
if (tile == null) continue;
if (tile instanceof TileGenericPipe && (isDirectConnection || SimpleServiceLocator.buildCraftProxy.checkPipesConnections(startPipe, tile, direction, true))) {
TileGenericPipe currentPipe = (TileGenericPipe) tile;
if (setVisited.contains(tile)) {
//Don't go where we have been before
continue;
}
if(isDirectConnection) { //ISC doesn't pass power
nextConnectionFlags.remove(PipeRoutingConnectionType.canPowerFrom);
}
if(currentPipe.pipe instanceof PipeItemsObsidian){ //Obsidian seperates networks
continue;
}
if(currentPipe.pipe instanceof PipeStructureCobblestone){ //don't recurse onto structure pipes.
continue;
}
if(currentPipe.pipe instanceof PipeItemsDiamond){ //Diamond only allows power through
nextConnectionFlags.remove(PipeRoutingConnectionType.canRouteTo);
nextConnectionFlags.remove(PipeRoutingConnectionType.canRequestFrom);
}
if(startPipe.pipe instanceof PipeItemsIron){ //Iron requests and power can come from closed sides
if(!startPipe.pipe.outputOpen(direction)){
nextConnectionFlags.remove(PipeRoutingConnectionType.canRouteTo);
}
}
if(currentPipe.pipe instanceof PipeItemsIron){ //and can only go to the open side
if(!currentPipe.pipe.outputOpen(direction.getOpposite())){
nextConnectionFlags.remove(PipeRoutingConnectionType.canRequestFrom);
nextConnectionFlags.remove(PipeRoutingConnectionType.canPowerFrom);
}
}
if(nextConnectionFlags.isEmpty()) { //don't bother going somewhere we can't do anything with
continue;
}
int beforeRecurseCount = foundPipes.size();
HashMap<CoreRoutedPipe, ExitRoute> result = getConnectedRoutingPipes(((TileGenericPipe)tile), nextConnectionFlags, direction);
for(Entry<CoreRoutedPipe, ExitRoute> pipeEntry : result.entrySet()) {
//Update Result with the direction we took
pipeEntry.getValue().exitOrientation = direction;
ExitRoute foundPipe = foundPipes.get(pipeEntry.getKey());
if (foundPipe==null) {
// New path
foundPipes.put(pipeEntry.getKey(), pipeEntry.getValue());
//Add resistance
pipeEntry.getValue().distanceToDestination += resistance;
}
else if (pipeEntry.getValue().distanceToDestination + resistance < foundPipe.distanceToDestination) {
//If new path is better, replace old path, otherwise do nothing
foundPipes.put(pipeEntry.getKey(), pipeEntry.getValue());
//Add resistance
pipeEntry.getValue().distanceToDestination += resistance;
}
}
if (foundPipes.size() > beforeRecurseCount && pathPainter != null) {
pathPainter.addLaser(startPipe.getWorld(), new LaserData(startPipe.xCoord, startPipe.yCoord, startPipe.zCoord, direction, connectionFlags));
}
}
}
setVisited.remove(startPipe);
if(startPipe.pipe instanceof CoreRoutedPipe){ // ie, has the recursion returned to the pipe it started from?
for(ExitRoute e:foundPipes.values())
e.root=((CoreRoutedPipe)startPipe.pipe).getRouter();
}
return foundPipes;
}
| private HashMap<CoreRoutedPipe, ExitRoute> getConnectedRoutingPipes(TileGenericPipe startPipe, EnumSet<PipeRoutingConnectionType> connectionFlags, ForgeDirection side) {
HashMap<CoreRoutedPipe, ExitRoute> foundPipes = new HashMap<CoreRoutedPipe, ExitRoute>();
boolean root = setVisited.size() == 0;
//Reset visited count at top level
if (setVisited.size() == 1) {
pipesVisited = 0;
}
//Break recursion if we have visited a set number of pipes, to prevent client hang if pipes are weirdly configured
if (++pipesVisited > maxVisited) {
return foundPipes;
}
//Break recursion after certain amount of nodes visited
if (setVisited.size() > maxLength) {
return foundPipes;
}
if (!startPipe.initialized) {
return foundPipes;
}
//Break recursion if we end up on a routing pipe, unless its the first one. Will break if matches the first call
if (startPipe.pipe instanceof CoreRoutedPipe && setVisited.size() != 0) {
CoreRoutedPipe rp = (CoreRoutedPipe) startPipe.pipe;
if(rp.stillNeedReplace()) {
return foundPipes;
}
foundPipes.put(rp, new ExitRoute(null,rp.getRouter(), ForgeDirection.UNKNOWN, side.getOpposite(), setVisited.size(), connectionFlags));
return foundPipes;
}
//Iron, obsidean and liquid pipes will separate networks
if (startPipe.pipe instanceof LogisticsFluidConnectorPipe) {
return foundPipes;
}
//Visited is checked after, so we can reach the same target twice to allow to keep the shortest path
setVisited.add(startPipe);
// first check specialPipeConnections (tesseracts, teleports, other connectors)
if(startPipe.pipe != null) {
List<TileGenericPipe> pipez = SimpleServiceLocator.specialpipeconnection.getConnectedPipes(startPipe);
for (TileGenericPipe specialpipe : pipez){
if (setVisited.contains(specialpipe)) {
//Don't go where we have been before
continue;
}
HashMap<CoreRoutedPipe, ExitRoute> result = getConnectedRoutingPipes(specialpipe,connectionFlags, side);
for (Entry<CoreRoutedPipe, ExitRoute> pipe : result.entrySet()) {
pipe.getValue().exitOrientation = ForgeDirection.UNKNOWN;
ExitRoute foundPipe=foundPipes.get(pipe.getKey());
if (foundPipe==null || (pipe.getValue().distanceToDestination < foundPipe.distanceToDestination)) {
// New path OR If new path is better, replace old path
foundPipes.put(pipe.getKey(), pipe.getValue());
}
}
}
}
ArrayDeque<Pair<TileEntity,ForgeDirection>> connections = new ArrayDeque<Pair<TileEntity,ForgeDirection>>();
//Recurse in all directions
for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS) {
if(root && !ForgeDirection.UNKNOWN.equals(side) && !direction.equals(side)) continue;
// tile may be up to 1 second old, but any neighbour pipe change will cause an immidiate update here, so we know that if it has changed, it isn't a pipe that has done so.
TileEntity tile = startPipe.getTile(direction);
if (tile == null) continue;
if (root && tile instanceof ILogisticsPowerProvider) {
if(this.powerNodes==null) {
powerNodes = new ArrayList<ILogisticsPowerProvider>();
}
powerNodes.add((ILogisticsPowerProvider) tile);
}
connections.add(new Pair<TileEntity, ForgeDirection>(tile, direction));
}
while(!connections.isEmpty()) {
Pair<TileEntity,ForgeDirection> pair = connections.pollFirst();
TileEntity tile = pair.getValue1();
ForgeDirection direction = pair.getValue2();
EnumSet<PipeRoutingConnectionType> nextConnectionFlags = EnumSet.copyOf(connectionFlags);
boolean isDirectConnection = false;
int resistance = 0;
if(root) {
List<TileGenericPipe> list = SimpleServiceLocator.specialtileconnection.getConnectedPipes(tile);
if(!list.isEmpty()) {
for(TileGenericPipe pipe:list) {
connections.add(new Pair<TileEntity,ForgeDirection>(pipe, direction));
}
continue;
}
}
if(tile instanceof IInventory) {
if(startPipe.pipe instanceof IDirectRoutingConnection) {
if(SimpleServiceLocator.connectionManager.hasDirectConnection(((CoreRoutedPipe)startPipe.pipe).getRouter())) {
CoreRoutedPipe CRP = SimpleServiceLocator.connectionManager.getConnectedPipe(((CoreRoutedPipe)startPipe.pipe).getRouter());
if(CRP != null) {
tile = CRP.container;
isDirectConnection = true;
resistance = ((IDirectRoutingConnection)startPipe.pipe).getConnectionResistance();
}
}
}
}
if (tile == null) continue;
if (tile instanceof TileGenericPipe && ((TileGenericPipe)tile).pipe != null && (isDirectConnection || SimpleServiceLocator.buildCraftProxy.checkPipesConnections(startPipe, tile, direction, true))) {
TileGenericPipe currentPipe = (TileGenericPipe) tile;
if (setVisited.contains(tile)) {
//Don't go where we have been before
continue;
}
if(isDirectConnection) { //ISC doesn't pass power
nextConnectionFlags.remove(PipeRoutingConnectionType.canPowerFrom);
}
if(currentPipe.pipe instanceof PipeItemsObsidian){ //Obsidian seperates networks
continue;
}
if(currentPipe.pipe instanceof PipeStructureCobblestone){ //don't recurse onto structure pipes.
continue;
}
if(currentPipe.pipe instanceof PipeItemsDiamond){ //Diamond only allows power through
nextConnectionFlags.remove(PipeRoutingConnectionType.canRouteTo);
nextConnectionFlags.remove(PipeRoutingConnectionType.canRequestFrom);
}
if(startPipe.pipe instanceof PipeItemsIron){ //Iron requests and power can come from closed sides
if(!startPipe.pipe.outputOpen(direction)){
nextConnectionFlags.remove(PipeRoutingConnectionType.canRouteTo);
}
}
if(currentPipe.pipe instanceof PipeItemsIron){ //and can only go to the open side
if(!currentPipe.pipe.outputOpen(direction.getOpposite())){
nextConnectionFlags.remove(PipeRoutingConnectionType.canRequestFrom);
nextConnectionFlags.remove(PipeRoutingConnectionType.canPowerFrom);
}
}
if(nextConnectionFlags.isEmpty()) { //don't bother going somewhere we can't do anything with
continue;
}
int beforeRecurseCount = foundPipes.size();
HashMap<CoreRoutedPipe, ExitRoute> result = getConnectedRoutingPipes(((TileGenericPipe)tile), nextConnectionFlags, direction);
for(Entry<CoreRoutedPipe, ExitRoute> pipeEntry : result.entrySet()) {
//Update Result with the direction we took
pipeEntry.getValue().exitOrientation = direction;
ExitRoute foundPipe = foundPipes.get(pipeEntry.getKey());
if (foundPipe==null) {
// New path
foundPipes.put(pipeEntry.getKey(), pipeEntry.getValue());
//Add resistance
pipeEntry.getValue().distanceToDestination += resistance;
}
else if (pipeEntry.getValue().distanceToDestination + resistance < foundPipe.distanceToDestination) {
//If new path is better, replace old path, otherwise do nothing
foundPipes.put(pipeEntry.getKey(), pipeEntry.getValue());
//Add resistance
pipeEntry.getValue().distanceToDestination += resistance;
}
}
if (foundPipes.size() > beforeRecurseCount && pathPainter != null) {
pathPainter.addLaser(startPipe.getWorld(), new LaserData(startPipe.xCoord, startPipe.yCoord, startPipe.zCoord, direction, connectionFlags));
}
}
}
setVisited.remove(startPipe);
if(startPipe.pipe instanceof CoreRoutedPipe){ // ie, has the recursion returned to the pipe it started from?
for(ExitRoute e:foundPipes.values())
e.root=((CoreRoutedPipe)startPipe.pipe).getRouter();
}
return foundPipes;
}
|
diff --git a/test/src/com/redhat/ceylon/compiler/java/test/misc/MiscTest.java b/test/src/com/redhat/ceylon/compiler/java/test/misc/MiscTest.java
index ab4d3f522..fae6637c6 100755
--- a/test/src/com/redhat/ceylon/compiler/java/test/misc/MiscTest.java
+++ b/test/src/com/redhat/ceylon/compiler/java/test/misc/MiscTest.java
@@ -1,441 +1,441 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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 distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.java.test.misc;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.ProcessBuilder.Redirect;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.tools.JavaFileObject;
import junit.framework.Assert;
import org.junit.Ignore;
import org.junit.Test;
import com.redhat.ceylon.cmr.api.JDKUtils;
import com.redhat.ceylon.compiler.java.test.CompilerTest;
import com.redhat.ceylon.compiler.java.test.ErrorCollector;
import com.redhat.ceylon.compiler.java.tools.CeyloncFileManager;
import com.redhat.ceylon.compiler.java.tools.CeyloncTaskImpl;
import com.redhat.ceylon.compiler.java.tools.CeyloncTool;
public class MiscTest extends CompilerTest {
@Test
public void testDefaultedModel() throws Exception{
compile("defaultedmodel/DefineDefaulted.ceylon");
compile("defaultedmodel/UseDefaulted.ceylon");
}
@Test
public void testHelloWorld(){
compareWithJavaSource("helloworld/helloworld");
}
@Test
public void runHelloWorld() throws Exception{
compileAndRun("com.redhat.ceylon.compiler.java.test.misc.helloworld.helloworld", "helloworld/helloworld.ceylon");
}
@Test
public void testCompileTwoDepdendantClasses() throws Exception{
compile("twoclasses/Two.ceylon");
compile("twoclasses/One.ceylon");
}
@Test
public void testCompileTwoClasses() throws Exception{
compileAndRun("com.redhat.ceylon.compiler.java.test.misc.twoclasses.main", "twoclasses/One.ceylon", "twoclasses/Two.ceylon", "twoclasses/main.ceylon");
}
@Test
public void testEqualsHashOverriding(){
compareWithJavaSource("equalshashoverriding/EqualsHashOverriding");
}
@Test
public void compileRuntime(){
cleanCars("build/classes-runtime");
java.util.List<File> sourceFiles = new ArrayList<File>();
String ceylonSourcePath = "../ceylon.language/src";
String javaSourcePath = "../ceylon.language/runtime";
String[] ceylonPackages = {"ceylon.language", "ceylon.language.meta", "ceylon.language.impl", "ceylon.language.meta.declaration", "ceylon.language.meta.model"};
// Native files
FileFilter exceptions = new FileFilter() {
@Override
public boolean accept(File pathname) {
String filename = pathname.getName();
filename = filename.substring(0, filename.lastIndexOf('.'));
for (String s : new String[]{"Array", "ArraySequence", "Boolean", "Callable", "Character", "className",
"Exception", "flatten", "Float", "identityHash", "Integer", "internalSort",
- "language", "metamodel", "modules", "process", "integerRangeByIterable",
- "SequenceBuilder", "SequenceAppender", "String", "StringBuilder", "Tuple"}) {
+ "language", "metamodel", "modules", "operatingSystem", "process", "integerRangeByIterable",
+ "runtime", "SequenceBuilder", "SequenceAppender", "String", "StringBuilder", "system", "Tuple"}) {
if (s.equals(filename)) {
return true;
}
}
if (filename.equals("annotations")
&& pathname.getParentFile().getName().equals("meta")) {
return true;
}
return false;
}
};
String[] extras = new String[]{
"arrayOfSize", "false", "infinity",
"parseFloat", "true", "integerRangeByIterable", "unflatten"
};
String[] modelExtras = new String[]{
"annotations", "modules", "type", "typeLiteral"
};
for(String pkg : ceylonPackages){
File pkgDir = new File(ceylonSourcePath, pkg.replaceAll("\\.", "/"));
File javaPkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".ceylon")) {
String baseName = src.getName().substring(0, src.getName().length() - 7);
if (!exceptions.accept(src)) {
sourceFiles.add(src);
} else {
addJavaSourceFile(baseName, sourceFiles, javaPkgDir, false);
}
}
}
}
}
// add extra files that are in Java
File javaPkgDir = new File(javaSourcePath, "ceylon/language");
for(String extra : extras)
addJavaSourceFile(extra, sourceFiles, javaPkgDir, true);
File javaModelPkgDir = new File(javaSourcePath, "ceylon/language/meta");
for(String extra : modelExtras)
addJavaSourceFile(extra, sourceFiles, javaModelPkgDir, true);
String[] javaPackages = {
"com/redhat/ceylon/compiler/java",
"com/redhat/ceylon/compiler/java/language",
"com/redhat/ceylon/compiler/java/metadata",
"com/redhat/ceylon/compiler/java/runtime/ide",
"com/redhat/ceylon/compiler/java/runtime/metamodel",
"com/redhat/ceylon/compiler/java/runtime/model",
};
for(String pkg : javaPackages){
File pkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".java")) {
sourceFiles.add(src);
}
}
}
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjectsFromFiles(sourceFiles);
String compilerSourcePath = ceylonSourcePath + File.pathSeparator + javaSourcePath;
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, null,
Arrays.asList("-sourcepath", compilerSourcePath, "-d", "build/classes-runtime", "-Xbootstrapceylon"/*, "-verbose"*/),
null, compilationUnits1);
Boolean result = task.call();
Assert.assertEquals("Compilation failed", Boolean.TRUE, result);
}
private void addJavaSourceFile(String baseName, List<File> sourceFiles, File javaPkgDir, boolean required) {
if (Character.isLowerCase(baseName.charAt(0))) {
File file = new File(javaPkgDir, baseName + "_.java");
if(file.exists())
sourceFiles.add(file);
else if(required)
Assert.fail("Required file not found: "+file);
} else {
File file = new File(javaPkgDir, baseName + "_.java");
if(file.exists())
sourceFiles.add(file);
else if(required)
Assert.fail("Required file not found: "+file);
File impl = new File(javaPkgDir, baseName + "$impl.java");
if (impl.exists()) {
sourceFiles.add(impl);
}
}
}
/**
* This test is for when we need to debug an incremental compilation error from the IDE, to make
* sure it is indeed a bug and find which bug it is, do not enable it by default, it's only there
* for debugging purpose. Once the bug is found, add it where it belongs (not here).
*/
@Ignore
@Test
public void debugIncrementalCompilationBug(){
java.util.List<File> sourceFiles = new ArrayList<File>();
String sdkSourcePath = "../ceylon-sdk/source";
String testSourcePath = "../ceylon-sdk/test-source";
for(String s : new String[]{
"../ceylon-sdk/source/ceylon/json/StringPrinter.ceylon",
"../ceylon-sdk/test-source/test/ceylon/json/print.ceylon",
"../ceylon-sdk/source/ceylon/json/Array.ceylon",
"../ceylon-sdk/test-source/test/ceylon/json/use.ceylon",
"../ceylon-sdk/source/ceylon/net/uri/Path.ceylon",
"../ceylon-sdk/test-source/test/ceylon/net/run.ceylon",
"../ceylon-sdk/source/ceylon/json/Printer.ceylon",
"../ceylon-sdk/source/ceylon/json/Object.ceylon",
"../ceylon-sdk/source/ceylon/net/uri/Query.ceylon",
"../ceylon-sdk/test-source/test/ceylon/json/run.ceylon",
"../ceylon-sdk/test-source/test/ceylon/net/connection.ceylon",
"../ceylon-sdk/source/ceylon/json/parse.ceylon",
"../ceylon-sdk/test-source/test/ceylon/json/parse.ceylon",
"../ceylon-sdk/source/ceylon/net/uri/PathSegment.ceylon",
}){
sourceFiles.add(new File(s));
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjectsFromFiles(sourceFiles);
String compilerSourcePath = sdkSourcePath + File.pathSeparator + testSourcePath;
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, null,
Arrays.asList("-sourcepath", compilerSourcePath, "-d", "../ceylon-sdk/modules"/*, "-verbose"*/),
null, compilationUnits1);
Boolean result = task.call();
Assert.assertEquals("Compilation failed", Boolean.TRUE, result);
}
@Test
public void compileSDK(){
String[] modules = {
"collection",
"dbc",
"file",
"interop.java",
"io",
"json",
"math",
"net",
"process",
"test",
"time"
};
compileSDKOnly(modules);
compileSDKTests(modules);
}
private void compileSDKOnly(String[] modules){
String sourceDir = "../ceylon-sdk/source";
// don't run this if the SDK is not checked out
File sdkFile = new File(sourceDir);
if(!sdkFile.exists())
return;
java.util.List<String> moduleNames = new ArrayList<String>(modules.length);
for(String module : modules){
moduleNames.add("ceylon." + module);
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
ErrorCollector errorCollector = new ErrorCollector();
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, errorCollector,
Arrays.asList("-sourcepath", sourceDir, "-d", "build/classes-sdk"),
moduleNames, null);
Boolean result = task.call();
Assert.assertEquals("Compilation of SDK itself failed: " + errorCollector.getAssertionFailureMessage(), Boolean.TRUE, result);
}
private void compileSDKTests(String[] modules){
String sourceDir = "../ceylon-sdk/test-source";
String depsDir = "../ceylon-sdk/test-deps";
// don't run this if the SDK is not checked out
File sdkFile = new File(sourceDir);
if(!sdkFile.exists())
return;
java.util.List<String> moduleNames = new ArrayList<String>(modules.length);
for(String module : modules){
moduleNames.add("test.ceylon." + module);
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
ErrorCollector errorCollector = new ErrorCollector();
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, errorCollector,
Arrays.asList("-sourcepath", sourceDir, "-rep", depsDir, "-d", "build/classes-sdk"),
moduleNames, null);
Boolean result = task.call();
Assert.assertEquals("Compilation of SDK tests failed:" + errorCollector.getAssertionFailureMessage(), Boolean.TRUE, result);
}
//
// Java keyword avoidance
// Note class names and generic type arguments are not a problem because
// in Ceylon they must begin with an upper case latter, but the Java
// keywords are all lowercase
@Test
public void testKeywordVariable(){
compareWithJavaSource("keyword/Variable");
}
@Test
public void testKeywordAttribute(){
compareWithJavaSource("keyword/Attribute");
}
@Test
public void testKeywordMethod(){
compareWithJavaSource("keyword/Method");
}
@Test
public void testKeywordParameter(){
compareWithJavaSource("keyword/Parameter");
}
@Test
public void testJDKModules(){
Assert.assertTrue(JDKUtils.isJDKModule("java.base"));
Assert.assertTrue(JDKUtils.isJDKModule("java.desktop"));
Assert.assertTrue(JDKUtils.isJDKModule("java.compiler")); // last one
Assert.assertFalse(JDKUtils.isJDKModule("java.stef"));
}
@Test
public void testJDKPackages(){
Assert.assertTrue(JDKUtils.isJDKAnyPackage("java.awt"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("java.lang"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("java.util"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("javax.swing"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("org.w3c.dom"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("org.xml.sax.helpers"));// last one
Assert.assertFalse(JDKUtils.isJDKAnyPackage("fr.epardaud"));
}
@Test
public void testOracleJDKModules(){
Assert.assertTrue(JDKUtils.isOracleJDKModule("oracle.jdk.base"));
Assert.assertTrue(JDKUtils.isOracleJDKModule("oracle.jdk.desktop"));
Assert.assertTrue(JDKUtils.isOracleJDKModule("oracle.jdk.httpserver"));
Assert.assertTrue(JDKUtils.isOracleJDKModule("oracle.jdk.tools.base")); // last one
Assert.assertFalse(JDKUtils.isOracleJDKModule("oracle.jdk.stef"));
Assert.assertFalse(JDKUtils.isOracleJDKModule("jdk.base"));
}
@Test
public void testOracleJDKPackages(){
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.oracle.net"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.sun.awt"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.sun.imageio.plugins.bmp"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.sun.java.swing.plaf.gtk"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.sun.nio.sctp"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("sun.nio"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("sunw.util"));// last one
Assert.assertFalse(JDKUtils.isOracleJDKAnyPackage("fr.epardaud"));
}
@Test
public void testLaunchDistCeylon() throws IOException, InterruptedException {
String[] args1 = {
"../ceylon-dist/dist/bin/ceylon",
"compile",
"--src",
"../ceylon-dist/dist/samples/helloworld/source",
"--out",
"build/test-cars",
"com.example.helloworld"
};
launchCeylon(args1);
String[] args2 = {
"../ceylon-dist/dist/bin/ceylon",
"doc",
"--src",
"../ceylon-dist/dist/samples/helloworld/source",
"--out",
"build/test-cars",
"com.example.helloworld"
};
launchCeylon(args2);
String[] args3 = {
"../ceylon-dist/dist/bin/ceylon",
"run",
"--rep",
"build/test-cars",
"com.example.helloworld/1.0.0"
};
launchCeylon(args3);
}
public void launchCeylon(String[] args) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder(args);
pb.redirectInput(Redirect.INHERIT);
pb.redirectOutput(Redirect.INHERIT);
pb.redirectError(Redirect.INHERIT);
Process p = pb.start();
p.waitFor();
if (p.exitValue() > 0) {
Assert.fail("Ceylon script execution failed");
}
}
}
| true | true | public void compileRuntime(){
cleanCars("build/classes-runtime");
java.util.List<File> sourceFiles = new ArrayList<File>();
String ceylonSourcePath = "../ceylon.language/src";
String javaSourcePath = "../ceylon.language/runtime";
String[] ceylonPackages = {"ceylon.language", "ceylon.language.meta", "ceylon.language.impl", "ceylon.language.meta.declaration", "ceylon.language.meta.model"};
// Native files
FileFilter exceptions = new FileFilter() {
@Override
public boolean accept(File pathname) {
String filename = pathname.getName();
filename = filename.substring(0, filename.lastIndexOf('.'));
for (String s : new String[]{"Array", "ArraySequence", "Boolean", "Callable", "Character", "className",
"Exception", "flatten", "Float", "identityHash", "Integer", "internalSort",
"language", "metamodel", "modules", "process", "integerRangeByIterable",
"SequenceBuilder", "SequenceAppender", "String", "StringBuilder", "Tuple"}) {
if (s.equals(filename)) {
return true;
}
}
if (filename.equals("annotations")
&& pathname.getParentFile().getName().equals("meta")) {
return true;
}
return false;
}
};
String[] extras = new String[]{
"arrayOfSize", "false", "infinity",
"parseFloat", "true", "integerRangeByIterable", "unflatten"
};
String[] modelExtras = new String[]{
"annotations", "modules", "type", "typeLiteral"
};
for(String pkg : ceylonPackages){
File pkgDir = new File(ceylonSourcePath, pkg.replaceAll("\\.", "/"));
File javaPkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".ceylon")) {
String baseName = src.getName().substring(0, src.getName().length() - 7);
if (!exceptions.accept(src)) {
sourceFiles.add(src);
} else {
addJavaSourceFile(baseName, sourceFiles, javaPkgDir, false);
}
}
}
}
}
// add extra files that are in Java
File javaPkgDir = new File(javaSourcePath, "ceylon/language");
for(String extra : extras)
addJavaSourceFile(extra, sourceFiles, javaPkgDir, true);
File javaModelPkgDir = new File(javaSourcePath, "ceylon/language/meta");
for(String extra : modelExtras)
addJavaSourceFile(extra, sourceFiles, javaModelPkgDir, true);
String[] javaPackages = {
"com/redhat/ceylon/compiler/java",
"com/redhat/ceylon/compiler/java/language",
"com/redhat/ceylon/compiler/java/metadata",
"com/redhat/ceylon/compiler/java/runtime/ide",
"com/redhat/ceylon/compiler/java/runtime/metamodel",
"com/redhat/ceylon/compiler/java/runtime/model",
};
for(String pkg : javaPackages){
File pkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".java")) {
sourceFiles.add(src);
}
}
}
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjectsFromFiles(sourceFiles);
String compilerSourcePath = ceylonSourcePath + File.pathSeparator + javaSourcePath;
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, null,
Arrays.asList("-sourcepath", compilerSourcePath, "-d", "build/classes-runtime", "-Xbootstrapceylon"/*, "-verbose"*/),
null, compilationUnits1);
Boolean result = task.call();
Assert.assertEquals("Compilation failed", Boolean.TRUE, result);
}
| public void compileRuntime(){
cleanCars("build/classes-runtime");
java.util.List<File> sourceFiles = new ArrayList<File>();
String ceylonSourcePath = "../ceylon.language/src";
String javaSourcePath = "../ceylon.language/runtime";
String[] ceylonPackages = {"ceylon.language", "ceylon.language.meta", "ceylon.language.impl", "ceylon.language.meta.declaration", "ceylon.language.meta.model"};
// Native files
FileFilter exceptions = new FileFilter() {
@Override
public boolean accept(File pathname) {
String filename = pathname.getName();
filename = filename.substring(0, filename.lastIndexOf('.'));
for (String s : new String[]{"Array", "ArraySequence", "Boolean", "Callable", "Character", "className",
"Exception", "flatten", "Float", "identityHash", "Integer", "internalSort",
"language", "metamodel", "modules", "operatingSystem", "process", "integerRangeByIterable",
"runtime", "SequenceBuilder", "SequenceAppender", "String", "StringBuilder", "system", "Tuple"}) {
if (s.equals(filename)) {
return true;
}
}
if (filename.equals("annotations")
&& pathname.getParentFile().getName().equals("meta")) {
return true;
}
return false;
}
};
String[] extras = new String[]{
"arrayOfSize", "false", "infinity",
"parseFloat", "true", "integerRangeByIterable", "unflatten"
};
String[] modelExtras = new String[]{
"annotations", "modules", "type", "typeLiteral"
};
for(String pkg : ceylonPackages){
File pkgDir = new File(ceylonSourcePath, pkg.replaceAll("\\.", "/"));
File javaPkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".ceylon")) {
String baseName = src.getName().substring(0, src.getName().length() - 7);
if (!exceptions.accept(src)) {
sourceFiles.add(src);
} else {
addJavaSourceFile(baseName, sourceFiles, javaPkgDir, false);
}
}
}
}
}
// add extra files that are in Java
File javaPkgDir = new File(javaSourcePath, "ceylon/language");
for(String extra : extras)
addJavaSourceFile(extra, sourceFiles, javaPkgDir, true);
File javaModelPkgDir = new File(javaSourcePath, "ceylon/language/meta");
for(String extra : modelExtras)
addJavaSourceFile(extra, sourceFiles, javaModelPkgDir, true);
String[] javaPackages = {
"com/redhat/ceylon/compiler/java",
"com/redhat/ceylon/compiler/java/language",
"com/redhat/ceylon/compiler/java/metadata",
"com/redhat/ceylon/compiler/java/runtime/ide",
"com/redhat/ceylon/compiler/java/runtime/metamodel",
"com/redhat/ceylon/compiler/java/runtime/model",
};
for(String pkg : javaPackages){
File pkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".java")) {
sourceFiles.add(src);
}
}
}
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjectsFromFiles(sourceFiles);
String compilerSourcePath = ceylonSourcePath + File.pathSeparator + javaSourcePath;
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, null,
Arrays.asList("-sourcepath", compilerSourcePath, "-d", "build/classes-runtime", "-Xbootstrapceylon"/*, "-verbose"*/),
null, compilationUnits1);
Boolean result = task.call();
Assert.assertEquals("Compilation failed", Boolean.TRUE, result);
}
|
diff --git a/plug-ins/svn/src/main/java/eu/sqooss/plugins/tds/svn/SVNAccessorImpl.java b/plug-ins/svn/src/main/java/eu/sqooss/plugins/tds/svn/SVNAccessorImpl.java
index 8e06154e..a8411e36 100644
--- a/plug-ins/svn/src/main/java/eu/sqooss/plugins/tds/svn/SVNAccessorImpl.java
+++ b/plug-ins/svn/src/main/java/eu/sqooss/plugins/tds/svn/SVNAccessorImpl.java
@@ -1,921 +1,921 @@
/*
* This file is part of the Alitheia system, developed by the SQO-OSS
* consortium as part of the IST FP6 SQO-OSS project, number 033331.
*
* Copyright 2007 - 2010 - Organization for Free and Open Source Software,
* Athens, Greece.
*
* 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.
*
* 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 eu.sqooss.plugins.tds.svn;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.tmatesoft.svn.core.SVNDirEntry;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNLogEntry;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNProperty;
import org.tmatesoft.svn.core.SVNRevisionProperty;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
import org.tmatesoft.svn.core.io.ISVNEditor;
import org.tmatesoft.svn.core.io.ISVNReporterBaton;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.ISVNAnnotateHandler;
import org.tmatesoft.svn.core.wc.SVNDiffClient;
import org.tmatesoft.svn.core.wc.SVNLogClient;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNWCUtil;
import eu.sqooss.core.AlitheiaCore;
import eu.sqooss.service.logging.Logger;
import eu.sqooss.service.tds.AccessorException;
import eu.sqooss.service.tds.AnnotatedLine;
import eu.sqooss.service.tds.CommitLog;
import eu.sqooss.service.tds.Diff;
import eu.sqooss.service.tds.DiffFactory;
import eu.sqooss.service.tds.InvalidProjectRevisionException;
import eu.sqooss.service.tds.InvalidRepositoryException;
import eu.sqooss.service.tds.PathChangeType;
import eu.sqooss.service.tds.Revision;
import eu.sqooss.service.tds.SCMAccessor;
import eu.sqooss.service.tds.SCMNode;
import eu.sqooss.service.tds.SCMNodeType;
import eu.sqooss.service.util.FileUtils;
public class SVNAccessorImpl implements SCMAccessor {
private String url;
private String projectname;
private SVNRepository svnRepository = null;
private Logger logger = null;
private static List<URI> supportedSchemes;
static {
// Initialize access methods for all the repo types
DAVRepositoryFactory.setup();
SVNRepositoryFactoryImpl.setup();
FSRepositoryFactory.setup();
supportedSchemes = new ArrayList<URI>();
supportedSchemes.add(URI.create("svn-file://www.sqo-oss.org"));
supportedSchemes.add(URI.create("svn://www.sqo-oss.org"));
supportedSchemes.add(URI.create("svn-http://www.sqo-oss.org"));
}
public SVNAccessorImpl() {
//Default constructor
}
public List<URI> getSupportedURLSchemes() {
return supportedSchemes;
}
public void init(URI dataURL, String name) throws AccessorException {
this.url = convertURI(dataURL);
this.projectname = name;
logger = AlitheiaCore.getInstance().getLogManager().createLogger(Logger.NAME_SQOOSS_TDS);
if (logger != null) {
logger.info("Created SCMAccessor for " + url);
}
try {
connectToRepository();
} catch (InvalidRepositoryException e) {
throw new AccessorException(this.getClass(), e.getMessage());
}
}
/**Convert form Alitheia URL to SVN URL*/
private String convertURI(URI uri) {
String s = uri.toString();
s = s.replace("svn-file", "file");
s = s.replace("svn-http", "http");
return s;
}
/**
* Connect to the repository named in the constructor (the URL
* is stored in this.url); may set the repo to null on error.
*/
private void connectToRepository()
throws InvalidRepositoryException {
try {
svnRepository = SVNRepositoryFactory.create(SVNURL.parseURIDecoded(url));
// All access is assumed to be anonynmous, so no
// authentication manager is used.
} catch (SVNException e) {
logger.error("Could not create SVN repository connection for " + url +
e.getMessage());
svnRepository = null;
throw new InvalidRepositoryException(url,e.getMessage());
}
}
/**
* For a ProjectRevision which has only got a date associated
* with it (typically from things like revisions stated
* as a {YYYYMMDD} string) resolve the date to a SVN revision
* number. Throws SVNException on errors in the underlying
* library or InvalidProjectRevisionException if the
* ProjectRevision can't be used for resolution.
*/
private long resolveDatedProjectRevision( SVNProjectRevision r )
throws InvalidProjectRevisionException,
InvalidRepositoryException {
if ((r == null) || r.getDate() == null) {
throw new InvalidProjectRevisionException(
"Can only resolve revisions with a valid date", getClass());
}
long revno = -1;
try {
revno = svnRepository.getDatedRevision(r.getDate());
} catch (SVNException e) {
throw new InvalidRepositoryException(url,e.getMessage());
}
return revno;
}
/**
* Get the Date for a revision number
*/
private Date resolveRevisionDate(SVNProjectRevision r)
throws InvalidProjectRevisionException, InvalidRepositoryException {
if ((r == null) || r.getSVNRevision() == -1) {
throw new InvalidProjectRevisionException(
"Can only resolve revisions with a SVN version.", getClass());
}
Date d = null;
String date = "";
try {
date = svnRepository.getRevisionPropertyValue(r.getSVNRevision(),
SVNRevisionProperty.DATE).getString();
SimpleDateFormat dateParser = new SimpleDateFormat("y-M-d'T'H:m:s.S'Z'");
d = dateParser.parse(date);
} catch (SVNException e) {
throw new InvalidRepositoryException(url, e.getMessage());
} catch (ParseException pe) {
throw new InvalidProjectRevisionException("Cannot parse date "
+ date + " for revision " + r.getSVNRevision() + " "
+ pe.getMessage(), getClass());
}
if (d == null) {
logger.warn("Resolved date is null");
}
return d;
}
/**
* Get latest svn revision as long
*/
private long getHeadSVNRevision() throws InvalidRepositoryException {
long endRevision = -1;
if (svnRepository == null) {
connectToRepository();
}
try {
endRevision = svnRepository.getLatestRevision();
} catch (SVNException e) {
logger.warn("Could not get latest revision of " + url
+ e.getMessage());
throw new InvalidRepositoryException(url, e.getMessage());
}
return endRevision;
}
/**
* Dummy check to see if revision 1 is indeed the first revision.
*/
private long getFirstSVNRevision() throws InvalidRepositoryException {
if (svnRepository == null) {
connectToRepository();
}
try {
svnRepository.getRevisionPropertyValue(0, SVNProperty.REVISION);
} catch (SVNException e) {
logger.warn("Could not get revision 0 from repository " + url +
e.getMessage());
throw new InvalidRepositoryException(url, e.getMessage());
}
return 0;
}
/**
* Resolve all revision fields from the repo.
*/
private SVNProjectRevision resolveRevision(Revision r) {
if ((r == null)) {
logger.error(projectname + ": Revision to be resolved is null");
return null;
}
if (!(r instanceof SVNProjectRevision)) {
logger.error(projectname + ": " +
"Non SVN revision appearing in SVN project?");
return null;
}
SVNProjectRevision svnrev = (SVNProjectRevision)r;
if (svnrev.isResolved()) {
// No resolution necessary
return svnrev;
}
Date d = null;
long l = -1;
try {
if (svnrev.getSVNRevision() != -1) {
if (svnrev.getSVNRevision() > getHeadSVNRevision()) {
logger.error(String.valueOf(svnrev.getSVNRevision())
+ " > HEAD");
return null;
}
if (svnrev.getSVNRevision() < getFirstSVNRevision()) {
logger.error(String.valueOf(svnrev.getSVNRevision())
+ " < 0");
return null;
}
//Resolve date
d = resolveRevisionDate(svnrev);
if (d == null) {
return null;
}
} else {
//Resolve SVN revision number
l = resolveDatedProjectRevision(svnrev);
if (l < 0) {
return null;
}
}
if (svnrev.getSVNRevision() == 0) {
SVNLogEntry logEntry = new SVNLogEntry(Collections.EMPTY_MAP, 0,
"sqo-oss", d, "Repository Init");
SVNProjectRevision spr = new SVNProjectRevision(logEntry, "");
return spr;
}
- List<SVNLogEntry> log = getSVNLog("", svnrev.getSVNRevision(), -1);
+ List<SVNLogEntry> log = getSVNLog("", svnrev.getSVNRevision(), svnrev.getSVNRevision() + 1);
SVNLogEntry full = log.iterator().next();
return new SVNProjectRevision(full, "");
} catch (InvalidRepositoryException e) {
logger.error("Revision " + r + " of project " + projectname
+ "refers to invalid project " + "repository " + url, e);
} catch (InvalidProjectRevisionException e) {
logger.error("Revision " + r + " is invalid:" + e.getMessage(), e);
}
return null;
}
private List<SVNLogEntry> getSVNLog(String repoPath, long revstart,
long revend) throws InvalidRepositoryException {
ArrayList<SVNLogEntry> l = new ArrayList<SVNLogEntry>();
try {
svnRepository.log(new String[] { repoPath }, l, revstart, revend,
true, true);
} catch (SVNException e) {
throw new InvalidRepositoryException(url, e.getMessage());
}
return l;
}
// Interface methods
/** {@inheritDoc}} */
public boolean isValidRevision(Revision r) {
return (resolveRevision((SVNProjectRevision)r) != null?true:false);
}
/** {@inheritDoc}} */
public Revision getHeadRevision()
throws InvalidRepositoryException {
long head = getHeadSVNRevision();
Revision s = new SVNProjectRevision(head);
return resolveRevision(s);
}
/** {@inheritDoc} */
public Revision getFirstRevision() throws InvalidRepositoryException {
long first = getFirstSVNRevision();
SVNProjectRevision s = new SVNProjectRevision(first);
return resolveRevision(s);
}
/**{@inheritDoc}*/
public Revision getNextRevision(Revision r) throws InvalidProjectRevisionException {
SVNProjectRevision svnr = (SVNProjectRevision)r;
try {
if (svnr.getSVNRevision() + 1 > getHeadSVNRevision()) {
throw new InvalidProjectRevisionException(
"Cannot get next revision of HEAD",
getClass());
}
} catch (InvalidRepositoryException e) {
throw new InvalidProjectRevisionException(e.getMessage(), getClass());
}
SVNProjectRevision next = new SVNProjectRevision(svnr.getSVNRevision() + 1);
return resolveRevision(next);
}
/**{@inheritDoc}*/
public Revision getPreviousRevision(Revision r)
throws InvalidProjectRevisionException {
SVNProjectRevision svnr = (SVNProjectRevision)r;
try {
if (svnr.getSVNRevision() - 1 < getFirstSVNRevision()) {
throw new InvalidProjectRevisionException(
"Cannot get previous revision of revision 1",
getClass());
}
} catch (InvalidRepositoryException e) {
throw new InvalidProjectRevisionException(e.getMessage(), getClass());
}
SVNProjectRevision prev = new SVNProjectRevision(svnr.getSVNRevision() - 1);
return resolveRevision(prev);
}
/** {@inheritDoc} */
public Revision newRevision(Date d) {
if (d == null) {
logger.error("Cannot create new revision with null or empty"
+ " date");
return null;
}
SVNProjectRevision r = new SVNProjectRevision(d);
return resolveRevision(r);
}
/** {@inheritDoc} */
public Revision newRevision(String uniqueId) {
long revision = -1;
if (uniqueId == null || uniqueId.equals("")) {
logger.error("Cannot create new revision with null or empty"
+ " revisionid");
return null;
}
try {
revision = Long.parseLong(uniqueId);
} catch (NumberFormatException nfe) {
logger.error("Invalid SVN revision id" + uniqueId);
return null;
}
SVNProjectRevision r = new SVNProjectRevision(revision);
return resolveRevision(r);
}
/**{@inheritDoc}*/
public void getCheckout(String repoPath, Revision rev,
File localPath)
throws InvalidProjectRevisionException,
InvalidRepositoryException,
FileNotFoundException {
if (svnRepository == null) {
connectToRepository();
}
SVNCheckoutEditor.logger = logger;
SVNCheckoutBaton.logger = logger;
logger.debug("Checking out from repository " + url + " path <" +
repoPath + "> rev " + rev.getUniqueId() + " in <" +
localPath + ">");
SVNProjectRevision svnrev = resolveRevision(rev);
if (svnrev == null) {
throw new InvalidProjectRevisionException("Cannot resolve revision",
getClass());
}
SVNNodeKind nodeKind;
try {
nodeKind = svnRepository.checkPath(repoPath, svnrev.getSVNRevision());
} catch (SVNException e) {
throw new FileNotFoundException(repoPath);
}
// Handle the various kinds of nodes that repoPath may refer to
if ((SVNNodeKind.NONE == nodeKind) || (SVNNodeKind.UNKNOWN == nodeKind)) {
logger.warn("Requested path " + repoPath + " does not exist.");
throw new FileNotFoundException(repoPath);
}
if (SVNNodeKind.FILE == nodeKind) {
getFile(repoPath, rev, new File(localPath, repoPath));
return;
}
// It must be a directory now.
if (SVNNodeKind.DIR != nodeKind) {
logger.warn("Node " + repoPath + " has weird type.");
throw new FileNotFoundException(repoPath);
}
ISVNReporterBaton baton = new SVNCheckoutBaton(svnrev.getSVNRevision());
ISVNEditor editor = new SVNCheckoutEditor(svnrev.getSVNRevision(),localPath);
try {
svnRepository.update(svnrev.getSVNRevision(),repoPath,true,baton,editor);
} catch (SVNException e) {
throw new InvalidRepositoryException(url,e.getMessage());
}
}
/**{@inheritDoc}*/
public void updateCheckout(String repoPath, Revision src, Revision dst, File localPath)
throws InvalidProjectRevisionException,
InvalidRepositoryException,
FileNotFoundException {
if (svnRepository == null) {
connectToRepository();
}
SVNCheckoutEditor.logger = logger;
SVNCheckoutBaton.logger = logger;
logger.info("Updating path <" + repoPath + "> from " + src + " to "
+ dst + " in <" + localPath + ">");
SVNProjectRevision svndst = resolveRevision(dst);
SVNProjectRevision svnsrc = resolveRevision(src);
if (svndst == null) {
throw new InvalidProjectRevisionException("Cannot resolve revision",
getClass());
}
if (svnsrc == null) {
throw new InvalidProjectRevisionException("Cannot resolve revision",
getClass());
}
SVNNodeKind nodeKind;
try {
nodeKind = svnRepository.checkPath(repoPath, svndst.getSVNRevision());
} catch (SVNException e) {
throw new FileNotFoundException(repoPath);
}
// Handle the various kinds of nodes that repoPath may refer to
if ( (SVNNodeKind.NONE == nodeKind) ||
(SVNNodeKind.UNKNOWN == nodeKind) ) {
logger.info("Requested path " + repoPath + " does not exist.");
throw new FileNotFoundException(repoPath);
}
if (SVNNodeKind.FILE == nodeKind) {
getFile(repoPath, dst, new File(localPath, repoPath));
return;
}
// It must be a directory now.
if (SVNNodeKind.DIR != nodeKind) {
logger.warn("Node " + repoPath + " has weird type.");
throw new FileNotFoundException(repoPath);
}
ISVNReporterBaton baton = new SVNCheckoutBaton(svnsrc.getSVNRevision(),
svndst.getSVNRevision());
ISVNEditor editor = new SVNCheckoutEditor(svndst.getSVNRevision(),localPath);
try {
svnRepository.update(svndst.getSVNRevision(),repoPath,true,baton,editor);
} catch (SVNException e) {
e.printStackTrace();
throw new InvalidRepositoryException(url,e.getMessage());
}
}
/**{@inheritDoc}*/
public void getFile(String repoPath, Revision revision, OutputStream stream)
throws InvalidProjectRevisionException,
InvalidRepositoryException,
FileNotFoundException {
// Connect to the repository if a connection has not yet been created
if (svnRepository == null) {
connectToRepository();
}
SVNProjectRevision svnrev = resolveRevision(revision);
if (svnrev == null) {
throw new InvalidProjectRevisionException("Cannot resolve revision",
getClass());
}
long revno = svnrev.getSVNRevision();
try {
SVNNodeKind nodeKind = svnRepository.checkPath(repoPath, revno);
logger.debug(projectname + ": Requesting path " + repoPath
+ ", revision " + revno + ", nodeKind="
+ nodeKind.toString());
/* NOTE: Seems like checkPath() sometimes returns a node kind in
* small letter (i.e. "dir" instead of "DIR"). Converting it
* to upper case solves the "problem", although the actual
* reason for such a behavior is not clear.
*/
// TODO: aboves NOTE should not matter, actually it didn't worked :-/
//nodeKind = SVNNodeKind.parseKind(
// nodeKind.toString().toUpperCase());
if (SVNNodeKind.NONE == nodeKind) {
logger.warn(projectname + ": Requested path " + repoPath +
"@" + revision.getUniqueId() + " does not exist.");
throw new FileNotFoundException(repoPath);
}
if (SVNNodeKind.DIR == nodeKind) {
logger.warn(projectname + ": Requested path " + repoPath +
"@" + revision.getUniqueId() + " is a directory.");
throw new FileNotFoundException(repoPath + " (dir)");
}
if (SVNNodeKind.UNKNOWN == nodeKind) {
logger.warn(projectname + ": Requested path " + repoPath +
"@" + revision.getUniqueId() + " is of unknown type.");
throw new FileNotFoundException(repoPath + " (unknown)");
}
svnRepository.getFile(repoPath, revno, null, stream);
stream.close();
} catch (SVNException e) {
throw new FileNotFoundException(e.getMessage());
} catch (IOException e) {
logger.warn("Failed to close output stream on SVN request." + e
+ " Revision:" + revision);
// Swallow this exception.
}
}
/**{@inheritDoc}*/
public void getFile(String repoPath,
Revision revision, File localPath)
throws InvalidProjectRevisionException,
InvalidRepositoryException,
FileNotFoundException {
if (!localPath.exists()) {
try {
localPath.createNewFile();
} catch (IOException e) {
throw new FileNotFoundException(e.getMessage());
}
}
FileOutputStream stream = new FileOutputStream(localPath);
getFile(repoPath, revision, stream);
// Stream was closed by other getFile()
}
/**{@inheritDoc}*/
public CommitLog getCommitLog(String repoPath, Revision r1, Revision r2)
throws InvalidProjectRevisionException,
InvalidRepositoryException {
if (svnRepository == null) {
connectToRepository();
}
// Map the project revisions to SVN revision numbers
logger.debug("Start revision for log " + r1);
SVNProjectRevision revstart = resolveRevision(r1);
if ((r1 == null) || (revstart == null)) {
throw new InvalidProjectRevisionException("Invalid start revision", getClass());
}
SVNProjectRevision revend = null;
if (r2 == null) {
revend = revstart;
} else {
revend = resolveRevision(r2);
if (revend == null) {
throw new InvalidProjectRevisionException("Invalid end revision",getClass());
}
logger.debug("End revision for log " + r2);
}
List<SVNLogEntry> l = getSVNLog(repoPath, revstart.getSVNRevision(),
revend.getSVNRevision());
Iterator<SVNLogEntry> i = l.iterator();
SVNCommitLogImpl result = new SVNCommitLogImpl();
while (i.hasNext()) {
SVNLogEntry entry = i.next();
result.getEntries().add(new SVNProjectRevision(entry, ""));
}
return result;
}
/**{@inheritDoc}*/
public Diff getDiff(String repoPath, Revision r1, Revision r2 )
throws InvalidProjectRevisionException,
InvalidRepositoryException,
FileNotFoundException {
if (svnRepository == null) {
connectToRepository();
}
//Map the project revisions to SVN revision numbers
long revstart=-1, revend=-1;
if ((r1 == null) || (resolveRevision(r1) == null)) {
throw new InvalidProjectRevisionException("Invalid start revision", getClass());
}
revstart = ((SVNProjectRevision)r1).getSVNRevision();
if (r2 == null) {
if (revstart == getHeadSVNRevision()) {
revend = revstart;
} else {
revend = revstart + 1;
}
} else {
if (resolveRevision(r2) == null) {
throw new InvalidProjectRevisionException("Invalid end revision", getClass());
}
revend = ((SVNProjectRevision)r2).getSVNRevision();
}
logger.debug("Diffing versions " + r1.getUniqueId() + ":"
+ r2.getUniqueId() + " of path " + projectname + ":"
+ repoPath);
SVNNodeKind nodeKind;
try {
nodeKind = svnRepository.checkPath(repoPath, revstart);
} catch (SVNException e) {
throw new FileNotFoundException(repoPath);
}
// Handle the various kinds of nodes that repoPath may refer to
if ( (SVNNodeKind.NONE == nodeKind) ||
(SVNNodeKind.UNKNOWN == nodeKind) ) {
logger.info("Requested path " + repoPath + " does not exist.");
throw new FileNotFoundException(repoPath);
}
try {
SVNDiffClient d = new SVNDiffClient(svnRepository.getAuthenticationManager(),null);
ByteArrayOutputStream diff = new ByteArrayOutputStream();
SVNURL u = svnRepository.getLocation().appendPath(repoPath,true);
d.doDiff(u,
SVNRevision.create(revstart),
SVNRevision.create(revstart),
SVNRevision.create(revend),
true,
false,
diff);
// Store the diff
Diff theDiff = DiffFactory.getInstance().doUnifiedDiff((SVNProjectRevision)r1,
(SVNProjectRevision)r2, FileUtils.dirname(repoPath), diff.toString());
return theDiff;
} catch (SVNException e) {
logger.warn(e.getMessage());
throw new InvalidRepositoryException(url,e.getMessage());
}
}
/**{@inheritDoc}*/
public Diff getChange(String repoPath, Revision r)
throws InvalidProjectRevisionException,
InvalidRepositoryException,
FileNotFoundException {
return getDiff(repoPath, getPreviousRevision(r), r);
}
/**{@inheritDoc}*/
public SCMNodeType getNodeType(String repoPath, Revision r)
throws InvalidRepositoryException {
try {
SVNNodeKind k = svnRepository.checkPath(repoPath, ((SVNProjectRevision)r).getSVNRevision());
if (k == SVNNodeKind.DIR)
return SCMNodeType.DIR;
if (k == SVNNodeKind.FILE)
return SCMNodeType.FILE;
return SCMNodeType.UNKNOWN;
} catch (SVNException e) {
logger.warn(e.getMessage());
throw new InvalidRepositoryException(url,e.getMessage());
}
}
/**{@inheritDoc}*/
public String getSubProjectPath() throws InvalidRepositoryException {
if (svnRepository == null) {
connectToRepository();
}
try {
return svnRepository.getRepositoryPath("");
} catch (SVNException e) {
logger.warn(e.getMessage());
throw new InvalidRepositoryException( url, e.getMessage());
}
}
public String toString() {
return projectname.concat(":").concat(url);
}
public String getName() {
return "SVNAccessor";
}
/** {@inheritDoc}} */
public List<SCMNode> listDirectory(SCMNode dir)
throws InvalidRepositoryException {
ArrayList<SCMNode> contents = new ArrayList<SCMNode>();
if (svnRepository == null) {
connectToRepository();
}
if (!getNodeType(dir.getPath(), dir.getRevision()).equals(SCMNodeType.DIR)) {
contents.add(dir);
return contents;
}
Collection<SVNDirEntry> svnContents = new Vector<SVNDirEntry>();
try {
svnRepository.getDir(dir.getPath(),
Long.parseLong(dir.getRevision().getUniqueId()),
false, svnContents);
Iterator<SVNDirEntry> i = svnContents.iterator();
while (i.hasNext()) {
SVNDirEntry d = i.next();
SCMNode node = new SCMNode(
dir.getPath() + "/" + d.getName(),
(d.getKind() == SVNNodeKind.DIR)?SCMNodeType.DIR:SCMNodeType.FILE,
dir.getRevision());
contents.add(node);
}
} catch (NumberFormatException e) {
logger.warn("Not an SVN revision: " + dir.getRevision().getUniqueId());
} catch (SVNException e) {
logger.warn("Error getting dir contents for path " + dir.getPath());
}
return contents;
}
/** {@inheritDoc}} */
public SCMNode getNode(String path, Revision r)
throws InvalidRepositoryException {
if (svnRepository == null) {
connectToRepository();
}
SCMNodeType t = getNodeType(path, r);
if ( !t.equals(SCMNodeType.UNKNOWN)) {
return new SCMNode(path, t, r);
}
return null;
}
/** {@inheritDoc}} */
//TODO: Finish implementation
public PathChangeType getNodeChangeType(SCMNode s)
throws InvalidRepositoryException, InvalidProjectRevisionException {
CommitLog log = getCommitLog("", getPreviousRevision(s.getRevision()), s.getRevision());
Iterator<Revision> i = log.iterator();
while (i.hasNext()) {
Revision ce = i.next();
}
return null;
}
/** {@inheritDoc }*/
public List<AnnotatedLine> getNodeAnnotations(SCMNode s) {
if (!s.getType().equals(SCMNodeType.FILE))
return Collections.emptyList();
List<AnnotatedLine> annotations = new ArrayList<AnnotatedLine>();
SVNLogClient log = new SVNLogClient(SVNWCUtil.createDefaultAuthenticationManager(), null);
SVNAnnotator annotator = new SVNAnnotator();
try {
log.doAnnotate(SVNURL.parseURIDecoded(url+s.getPath()),
SVNRevision.create(Long.parseLong(s.getRevision().getUniqueId())),
null,
SVNRevision.create(Long.parseLong(s.getRevision().getUniqueId())),
annotator);
} catch (NumberFormatException e) {
logger.error("Number formating error " + e.getMessage());
return Collections.emptyList();
} catch (SVNException e) {
logger.error("Repository error " + e.getMessage());
return Collections.emptyList();
}
return annotator.getAnnotatedFile();
}
/** Used by the #getNodeAnnotations method to annotate a file */
private class SVNAnnotator implements ISVNAnnotateHandler {
private List<AnnotatedLine> annotate = new ArrayList<AnnotatedLine>();
public void handleEOF() {}
public void handleLine(Date date, long revision, String author,
String line) throws SVNException {
AnnotatedLine al = new AnnotatedLine();
al.developer = String.copyValueOf(author.toCharArray());
al.line = String.copyValueOf(line.toCharArray());
al.rev = newRevision(String.valueOf(revision));
annotate.add(al);
}
public void handleLine(Date date, long revision, String author,
String line, Date mergedDate, long mergedRevision,
String mergedAuthor, String mergedPath, int lineNumber)
throws SVNException {
handleLine(date, revision, author, line);
}
public boolean handleRevision(Date date, long revision, String author,
File contents) throws SVNException { return false;}
public List<AnnotatedLine> getAnnotatedFile() {
return annotate;
}
}
}
// vi: ai nosi sw=4 ts=4 expandtab
| true | true | private SVNProjectRevision resolveRevision(Revision r) {
if ((r == null)) {
logger.error(projectname + ": Revision to be resolved is null");
return null;
}
if (!(r instanceof SVNProjectRevision)) {
logger.error(projectname + ": " +
"Non SVN revision appearing in SVN project?");
return null;
}
SVNProjectRevision svnrev = (SVNProjectRevision)r;
if (svnrev.isResolved()) {
// No resolution necessary
return svnrev;
}
Date d = null;
long l = -1;
try {
if (svnrev.getSVNRevision() != -1) {
if (svnrev.getSVNRevision() > getHeadSVNRevision()) {
logger.error(String.valueOf(svnrev.getSVNRevision())
+ " > HEAD");
return null;
}
if (svnrev.getSVNRevision() < getFirstSVNRevision()) {
logger.error(String.valueOf(svnrev.getSVNRevision())
+ " < 0");
return null;
}
//Resolve date
d = resolveRevisionDate(svnrev);
if (d == null) {
return null;
}
} else {
//Resolve SVN revision number
l = resolveDatedProjectRevision(svnrev);
if (l < 0) {
return null;
}
}
if (svnrev.getSVNRevision() == 0) {
SVNLogEntry logEntry = new SVNLogEntry(Collections.EMPTY_MAP, 0,
"sqo-oss", d, "Repository Init");
SVNProjectRevision spr = new SVNProjectRevision(logEntry, "");
return spr;
}
List<SVNLogEntry> log = getSVNLog("", svnrev.getSVNRevision(), -1);
SVNLogEntry full = log.iterator().next();
return new SVNProjectRevision(full, "");
} catch (InvalidRepositoryException e) {
logger.error("Revision " + r + " of project " + projectname
+ "refers to invalid project " + "repository " + url, e);
} catch (InvalidProjectRevisionException e) {
logger.error("Revision " + r + " is invalid:" + e.getMessage(), e);
}
return null;
}
| private SVNProjectRevision resolveRevision(Revision r) {
if ((r == null)) {
logger.error(projectname + ": Revision to be resolved is null");
return null;
}
if (!(r instanceof SVNProjectRevision)) {
logger.error(projectname + ": " +
"Non SVN revision appearing in SVN project?");
return null;
}
SVNProjectRevision svnrev = (SVNProjectRevision)r;
if (svnrev.isResolved()) {
// No resolution necessary
return svnrev;
}
Date d = null;
long l = -1;
try {
if (svnrev.getSVNRevision() != -1) {
if (svnrev.getSVNRevision() > getHeadSVNRevision()) {
logger.error(String.valueOf(svnrev.getSVNRevision())
+ " > HEAD");
return null;
}
if (svnrev.getSVNRevision() < getFirstSVNRevision()) {
logger.error(String.valueOf(svnrev.getSVNRevision())
+ " < 0");
return null;
}
//Resolve date
d = resolveRevisionDate(svnrev);
if (d == null) {
return null;
}
} else {
//Resolve SVN revision number
l = resolveDatedProjectRevision(svnrev);
if (l < 0) {
return null;
}
}
if (svnrev.getSVNRevision() == 0) {
SVNLogEntry logEntry = new SVNLogEntry(Collections.EMPTY_MAP, 0,
"sqo-oss", d, "Repository Init");
SVNProjectRevision spr = new SVNProjectRevision(logEntry, "");
return spr;
}
List<SVNLogEntry> log = getSVNLog("", svnrev.getSVNRevision(), svnrev.getSVNRevision() + 1);
SVNLogEntry full = log.iterator().next();
return new SVNProjectRevision(full, "");
} catch (InvalidRepositoryException e) {
logger.error("Revision " + r + " of project " + projectname
+ "refers to invalid project " + "repository " + url, e);
} catch (InvalidProjectRevisionException e) {
logger.error("Revision " + r + " is invalid:" + e.getMessage(), e);
}
return null;
}
|
diff --git a/src/main/java/com/github/kpacha/jkata/tennis/Tennis.java b/src/main/java/com/github/kpacha/jkata/tennis/Tennis.java
index 0f7adbf..8162593 100644
--- a/src/main/java/com/github/kpacha/jkata/tennis/Tennis.java
+++ b/src/main/java/com/github/kpacha/jkata/tennis/Tennis.java
@@ -1,23 +1,27 @@
package com.github.kpacha.jkata.tennis;
public class Tennis {
private int playerOneScored = 0;
private int playerTwoScored = 0;
public String getScore() {
if (playerOneScored == 3 && playerTwoScored == 3)
return "Deuce";
- if (playerOneScored == 4)
- return "Player 1 wins";
+ if (playerOneScored == 4) {
+ if (playerTwoScored == 3)
+ return "Advantage Player 1";
+ else
+ return "Player 1 wins";
+ }
return (15 * playerOneScored) + " - " + (15 * playerTwoScored);
}
public void playerOneScores() {
playerOneScored++;
}
public void playerTwoScores() {
playerTwoScored++;
}
}
| true | true | public String getScore() {
if (playerOneScored == 3 && playerTwoScored == 3)
return "Deuce";
if (playerOneScored == 4)
return "Player 1 wins";
return (15 * playerOneScored) + " - " + (15 * playerTwoScored);
}
| public String getScore() {
if (playerOneScored == 3 && playerTwoScored == 3)
return "Deuce";
if (playerOneScored == 4) {
if (playerTwoScored == 3)
return "Advantage Player 1";
else
return "Player 1 wins";
}
return (15 * playerOneScored) + " - " + (15 * playerTwoScored);
}
|
diff --git a/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/servlet/AjaxServlet.java b/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/servlet/AjaxServlet.java
index 6ea9b99c..8796c958 100644
--- a/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/servlet/AjaxServlet.java
+++ b/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/servlet/AjaxServlet.java
@@ -1,4287 +1,4287 @@
package gov.nih.nci.evs.browser.servlet;
import org.json.*;
import gov.nih.nci.evs.browser.utils.*;
import gov.nih.nci.evs.browser.common.*;
import java.io.*;
import java.util.*;
import java.net.URI;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.log4j.*;
import gov.nih.nci.evs.browser.properties.*;
import static gov.nih.nci.evs.browser.common.Constants.*;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag;
import org.LexGrid.valueSets.ValueSetDefinition;
import org.LexGrid.LexBIG.DataModel.Collections.*;
import org.LexGrid.LexBIG.DataModel.Core.*;
import org.LexGrid.LexBIG.LexBIGService.*;
import org.LexGrid.LexBIG.Utility.*;
import org.LexGrid.codingSchemes.*;
import org.LexGrid.naming.*;
import org.LexGrid.LexBIG.Impl.Extensions.GenericExtensions.*;
import org.apache.log4j.*;
import javax.faces.event.ValueChangeEvent;
import org.LexGrid.LexBIG.caCore.interfaces.LexEVSDistributed;
import org.lexgrid.valuesets.LexEVSValueSetDefinitionServices;
import org.LexGrid.valueSets.ValueSetDefinition;
import org.LexGrid.commonTypes.Source;
import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference;
import org.lexgrid.valuesets.dto.ResolvedValueSetDefinition;
import org.LexGrid.LexBIG.Utility.Iterators.ResolvedConceptReferencesIterator;
import javax.servlet.ServletOutputStream;
import org.LexGrid.concepts.*;
import org.lexgrid.valuesets.dto.ResolvedValueSetCodedNodeSet;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.PropertyType;
import org.LexGrid.concepts.Definition;
import org.LexGrid.commonTypes.PropertyQualifier;
import org.LexGrid.commonTypes.Property;
/**
* <!-- LICENSE_TEXT_START -->
* Copyright 2008,2009 NGIT. This software was developed in conjunction
* with the National Cancer Institute, and so to the extent government
* employees are co-authors, any rights in such works shall be subject
* to Title 17 of the United States Code, section 105.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the disclaimer of Article 3,
* below. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* 2. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by NGIT and the National
* Cancer Institute." If no such end-user documentation is to be
* included, this acknowledgment shall appear in the software itself,
* wherever such third-party acknowledgments normally appear.
* 3. The names "The National Cancer Institute", "NCI" and "NGIT" must
* not be used to endorse or promote products derived from this software.
* 4. This license does not authorize the incorporation of this software
* into any third party proprietary programs. This license does not
* authorize the recipient to use any trademarks owned by either NCI
* or NGIT
* 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE
* DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE,
* NGIT, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* <!-- LICENSE_TEXT_END -->
*/
/**
* @author EVS Team
* @version 1.0
*
* Modification history
* Initial implementation [email protected]
*
*/
public final class AjaxServlet extends HttpServlet {
private static Logger _logger = Logger.getLogger(AjaxServlet.class);
/**
* local constants
*/
private static final long serialVersionUID = 1L;
//private static final int STANDARD_VIEW = 1;
//private static final int TERMINOLOGY_VIEW = 2;
/**
* Validates the Init and Context parameters, configures authentication URL
*
* @throws ServletException if the init parameters are invalid or any other
* problems occur during initialisation
*/
public void init() throws ServletException {
}
/**
* Route the user to the execute method
*
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
execute(request, response);
}
/**
* Route the user to the execute method
*
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a Servlet exception occurs
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
execute(request, response);
}
private static void debugJSONString(String msg, String jsonString) {
boolean debug = false; //DYEE_DEBUG (default: false)
if (! debug)
return;
_logger.debug(Utils.SEPARATOR);
if (msg != null && msg.length() > 0)
_logger.debug(msg);
_logger.debug("jsonString: " + jsonString);
_logger.debug("jsonString length: " + jsonString.length());
Utils.debugJSONString(jsonString);
}
public static void search_tree(HttpServletResponse response, String node_id,
String ontology_display_name, String ontology_version) {
try {
String jsonString = search_tree(node_id,
ontology_display_name, ontology_version);
if (jsonString == null)
return;
JSONObject json = new JSONObject();
JSONArray rootsArray = new JSONArray(jsonString);
json.put("root_nodes", rootsArray);
response.setContentType("text/html");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write(json.toString());
response.getWriter().flush();
} catch (Exception e) {
e.printStackTrace();
}
}
public static String search_tree(String node_id,
String ontology_display_name, String ontology_version) throws Exception {
if (node_id == null || ontology_display_name == null)
return null;
Utils.StopWatch stopWatch = new Utils.StopWatch();
// String max_tree_level_str =
// NCItBrowserProperties.getProperty(
// NCItBrowserProperties.MAXIMUM_TREE_LEVEL);
// int maxLevel = Integer.parseInt(max_tree_level_str);
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
if (ontology_version != null) versionOrTag.setVersion(ontology_version);
String jsonString =
CacheController.getTree(
ontology_display_name, versionOrTag, node_id);
debugJSONString("Section: search_tree", jsonString);
_logger.debug("search_tree: " + stopWatch.getResult());
return jsonString;
}
/**
* Process the specified HTTP request, and create the corresponding HTTP
* response (or forward to another web component that will create it).
*
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public void execute(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Determine request by attributes
String action = request.getParameter("action");// DataConstants.ACTION);
String node_id = request.getParameter("ontology_node_id");// DataConstants.ONTOLOGY_NODE_ID);
String ontology_display_name =
request.getParameter("ontology_display_name");// DataConstants.ONTOLOGY_DISPLAY_NAME);
String ontology_version = request.getParameter("version");
if (ontology_version == null) {
ontology_version = DataUtils.getVocabularyVersionByTag(ontology_display_name, "PRODUCTION");
}
long ms = System.currentTimeMillis();
if (action.equals("expand_tree")) {
if (node_id != null && ontology_display_name != null) {
System.out.println("(*) EXPAND TREE NODE: " + node_id);
response.setContentType("text/html");
response.setHeader("Cache-Control", "no-cache");
JSONObject json = new JSONObject();
JSONArray nodesArray = null;
try {
/*
// for HL7 (temporary fix)
ontology_display_name =
DataUtils.searchFormalName(ontology_display_name);
*/
nodesArray =
CacheController.getInstance().getSubconcepts(
ontology_display_name, ontology_version, node_id);
if (nodesArray != null) {
json.put("nodes", nodesArray);
}
} catch (Exception e) {
}
debugJSONString("Section: expand_tree", json.toString());
response.getWriter().write(json.toString());
/*
_logger.debug("Run time (milliseconds): "
+ (System.currentTimeMillis() - ms));
*/
}
}
/*
* else if (action.equals("search_tree")) {
*
*
* if (node_id != null && ontology_display_name != null) {
* response.setContentType("text/html");
* response.setHeader("Cache-Control", "no-cache"); JSONObject json =
* new JSONObject(); try { // testing // JSONArray rootsArray = //
* CacheController.getInstance().getPathsToRoots(ontology_display_name,
* // null, node_id, true);
*
* String max_tree_level_str = null; int maxLevel = -1; try {
* max_tree_level_str = NCItBrowserProperties .getInstance()
* .getProperty( NCItBrowserProperties.MAXIMUM_TREE_LEVEL); maxLevel =
* Integer.parseInt(max_tree_level_str);
*
* } catch (Exception ex) {
*
* }
*
* JSONArray rootsArray = CacheController.getInstance()
* .getPathsToRoots(ontology_display_name, null, node_id, true,
* maxLevel);
*
* if (rootsArray.length() == 0) { rootsArray =
* CacheController.getInstance() .getRootConcepts(ontology_display_name,
* null);
*
* boolean is_root = isRoot(rootsArray, node_id); if (!is_root) {
* //rootsArray = null; json.put("dummy_root_nodes", rootsArray);
* response.getWriter().write(json.toString());
* response.getWriter().flush();
*
* _logger.debug("Run time (milliseconds): " +
* (System.currentTimeMillis() - ms)); return; } }
* json.put("root_nodes", rootsArray); } catch (Exception e) {
* e.printStackTrace(); }
*
* response.getWriter().write(json.toString());
* response.getWriter().flush();
*
* _logger.debug("Run time (milliseconds): " +
* (System.currentTimeMillis() - ms)); return; } }
*/
if (action.equals("search_value_set")) {
search_value_set(request, response);
} else if (action.equals("create_src_vs_tree")) {
create_src_vs_tree(request, response);
} else if (action.equals("create_cs_vs_tree")) {
create_cs_vs_tree(request, response);
} else if (action.equals("search_hierarchy")) {
search_hierarchy(request, response, node_id, ontology_display_name, ontology_version);
} else if (action.equals("search_tree")) {
search_tree(response, node_id, ontology_display_name, ontology_version);
} else if (action.equals("build_tree")) {
if (ontology_display_name == null)
ontology_display_name = CODING_SCHEME_NAME;
response.setContentType("text/html");
response.setHeader("Cache-Control", "no-cache");
JSONObject json = new JSONObject();
JSONArray nodesArray = null;// new JSONArray();
try {
nodesArray =
CacheController.getInstance().getRootConcepts(
ontology_display_name, ontology_version);
if (nodesArray != null) {
json.put("root_nodes", nodesArray);
}
} catch (Exception e) {
e.printStackTrace();
}
debugJSONString("Section: build_tree", json.toString());
response.getWriter().write(json.toString());
// response.getWriter().flush();
_logger.debug("Run time (milliseconds): "
+ (System.currentTimeMillis() - ms));
return;
} else if (action.equals("build_vs_tree")) {
if (ontology_display_name == null)
ontology_display_name = CODING_SCHEME_NAME;
response.setContentType("text/html");
response.setHeader("Cache-Control", "no-cache");
JSONObject json = new JSONObject();
JSONArray nodesArray = null;// new JSONArray();
try {
//HashMap getRootValueSets(String codingSchemeURN)
String codingSchemeVersion = null;
nodesArray =
CacheController.getInstance().getRootValueSets(
ontology_display_name, codingSchemeVersion);
if (nodesArray != null) {
json.put("root_nodes", nodesArray);
}
} catch (Exception e) {
e.printStackTrace();
}
response.getWriter().write(json.toString());
//System.out.println(json.toString());
_logger.debug("Run time (milliseconds): "
+ (System.currentTimeMillis() - ms));
return;
} else if (action.equals("expand_vs_tree")) {
if (node_id != null && ontology_display_name != null) {
response.setContentType("text/html");
response.setHeader("Cache-Control", "no-cache");
JSONObject json = new JSONObject();
JSONArray nodesArray = null;
try {
nodesArray =
CacheController.getInstance().getSubValueSets(
ontology_display_name, ontology_version, node_id);
if (nodesArray != null) {
System.out.println("expand_vs_tree nodesArray != null");
json.put("nodes", nodesArray);
} else {
System.out.println("expand_vs_tree nodesArray == null???");
}
} catch (Exception e) {
}
response.getWriter().write(json.toString());
_logger.debug("Run time (milliseconds): "
+ (System.currentTimeMillis() - ms));
}
} else if (action.equals("expand_entire_vs_tree")) {
if (node_id != null && ontology_display_name != null) {
response.setContentType("text/html");
response.setHeader("Cache-Control", "no-cache");
JSONObject json = new JSONObject();
JSONArray nodesArray = null;
try {
nodesArray =
CacheController.getInstance().getSourceValueSetTree(
ontology_display_name, ontology_version, true);
if (nodesArray != null) {
System.out.println("expand_entire_vs_tree nodesArray != null");
json.put("root_nodes", nodesArray);
} else {
System.out.println("expand_entire_vs_tree nodesArray == null???");
}
} catch (Exception e) {
}
response.getWriter().write(json.toString());
_logger.debug("Run time (milliseconds): "
+ (System.currentTimeMillis() - ms));
}
} else if (action.equals("expand_entire_cs_vs_tree")) {
//if (node_id != null && ontology_display_name != null) {
response.setContentType("text/html");
response.setHeader("Cache-Control", "no-cache");
JSONObject json = new JSONObject();
JSONArray nodesArray = null;
try {
nodesArray =
CacheController.getInstance().getCodingSchemeValueSetTree(
ontology_display_name, ontology_version, true);
if (nodesArray != null) {
System.out.println("expand_entire_vs_tree nodesArray != null");
json.put("root_nodes", nodesArray);
} else {
System.out.println("expand_entire_vs_tree nodesArray == null???");
}
} catch (Exception e) {
}
response.getWriter().write(json.toString());
_logger.debug("Run time (milliseconds): "
+ (System.currentTimeMillis() - ms));
//}
} else if (action.equals("build_cs_vs_tree")) {
response.setContentType("text/html");
response.setHeader("Cache-Control", "no-cache");
JSONObject json = new JSONObject();
JSONArray nodesArray = null;// new JSONArray();
try {
//HashMap getRootValueSets(String codingSchemeURN)
String codingSchemeVersion = null;
nodesArray =
CacheController.getInstance().getRootValueSets(true);
if (nodesArray != null) {
json.put("root_nodes", nodesArray);
}
} catch (Exception e) {
e.printStackTrace();
}
response.getWriter().write(json.toString());
_logger.debug("Run time (milliseconds): "
+ (System.currentTimeMillis() - ms));
return;
} else if (action.equals("expand_cs_vs_tree")) {
response.setContentType("text/html");
response.setHeader("Cache-Control", "no-cache");
JSONObject json = new JSONObject();
JSONArray nodesArray = null;
String vsd_uri = ValueSetHierarchy.getValueSetURI(node_id);
node_id = ValueSetHierarchy.getCodingSchemeName(node_id);
//if (node_id != null && ontology_display_name != null) {
if (node_id != null) {
ValueSetDefinition vsd = ValueSetHierarchy.findValueSetDefinitionByURI(vsd_uri);
if (vsd == null) {
System.out.println("(****) coding scheme name: " + node_id);
try {
//
nodesArray = CacheController.getInstance().getRootValueSets(node_id, null);
//nodesArray = CacheController.getInstance().getRootValueSets(node_id, null); //find roots (by source)
if (nodesArray != null) {
json.put("nodes", nodesArray);
} else {
System.out.println("expand_vs_tree nodesArray == null???");
}
} catch (Exception e) {
}
} else {
try {
nodesArray =
CacheController.getInstance().getSubValueSets(
node_id, null, vsd_uri);
if (nodesArray != null) {
json.put("nodes", nodesArray);
}
} catch (Exception e) {
}
}
response.getWriter().write(json.toString());
_logger.debug("Run time (milliseconds): "
+ (System.currentTimeMillis() - ms));
}
} else if (action.equals("build_src_vs_tree")) {
response.setContentType("text/html");
response.setHeader("Cache-Control", "no-cache");
JSONObject json = new JSONObject();
JSONArray nodesArray = null;// new JSONArray();
try {
//HashMap getRootValueSets(String codingSchemeURN)
String codingSchemeVersion = null;
nodesArray =
//CacheController.getInstance().getRootValueSets(true, true);
CacheController.getInstance().build_src_vs_tree();
if (nodesArray != null) {
json.put("root_nodes", nodesArray);
}
} catch (Exception e) {
e.printStackTrace();
}
response.getWriter().write(json.toString());
//System.out.println(json.toString());
_logger.debug("Run time (milliseconds): "
+ (System.currentTimeMillis() - ms));
return;
} else if (action.equals("expand_src_vs_tree")) {
if (node_id != null && ontology_display_name != null) {
response.setContentType("text/html");
response.setHeader("Cache-Control", "no-cache");
JSONObject json = new JSONObject();
JSONArray nodesArray = null;
nodesArray = CacheController.getInstance().expand_src_vs_tree(node_id);
if (nodesArray == null) {
System.out.println("(*) CacheController returns nodesArray == null");
}
try {
if (nodesArray != null) {
System.out.println("expand_src_vs_tree nodesArray != null");
json.put("nodes", nodesArray);
} else {
System.out.println("expand_src_vs_tree nodesArray == null???");
}
} catch (Exception e) {
e.printStackTrace();
}
response.getWriter().write(json.toString());
_logger.debug("Run time (milliseconds): "
+ (System.currentTimeMillis() - ms));
}
}
}
private boolean isRoot(JSONArray rootsArray, String code) {
for (int i = 0; i < rootsArray.length(); i++) {
String node_id = null;
try {
JSONObject node = rootsArray.getJSONObject(i);
node_id = (String) node.get(CacheController.ONTOLOGY_NODE_ID);
if (node_id.compareTo(code) == 0)
return true;
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
private static boolean _debug = false; // DYEE_DEBUG (default: false)
private static StringBuffer _debugBuffer = null;
public static void println(PrintWriter out, String text) {
if (_debug) {
_logger.debug("DBG: " + text);
_debugBuffer.append(text + "\n");
}
out.println(text);
}
public static void search_hierarchy(HttpServletRequest request, HttpServletResponse response, String node_id,
String ontology_display_name, String ontology_version) {
Enumeration parameters = request.getParameterNames();
String param = null;
while (parameters.hasMoreElements())
{
param = (String) parameters.nextElement();
String paramValue = request.getParameter(param);
}
response.setContentType("text/html");
PrintWriter out = null;
try {
out = response.getWriter();
} catch (Exception ex) {
ex.printStackTrace();
return;
}
if (_debug) {
_debugBuffer = new StringBuffer();
}
String localName = DataUtils.getLocalName(ontology_display_name);
String formalName = DataUtils.getFormalName(localName);
String term_browser_version = DataUtils.getMetadataValue(formalName, ontology_version, "term_browser_version");
String display_name = DataUtils.getMetadataValue(formalName, ontology_version, "display_name");
println(out, "");
println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/yahoo-min.js\" ></script>");
println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/event-min.js\" ></script>");
println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/dom-min.js\" ></script>");
println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/animation-min.js\" ></script>");
println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/container-min.js\" ></script>");
println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/connection-min.js\" ></script>");
//println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/autocomplete-min.js\" ></script>");
println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/treeview-min.js\" ></script>");
println(out, "");
println(out, "");
println(out, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
println(out, "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">");
println(out, " <head>");
println(out, " <title>Vocabulary Hierarchy</title>");
println(out, " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">");
println(out, " <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/styleSheet.css\" />");
println(out, " <link rel=\"shortcut icon\" href=\"/ncitbrowser/favicon.ico\" type=\"image/x-icon\" />");
println(out, " <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/yui/fonts.css\" />");
println(out, " <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/yui/grids.css\" />");
println(out, " <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/yui/code.css\" />");
println(out, " <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/yui/tree.css\" />");
println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/script.js\"></script>");
println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/search.js\"></script>");
println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/dropdown.js\"></script>");
println(out, "");
println(out, " <script language=\"JavaScript\">");
println(out, "");
println(out, " var tree;");
println(out, " var nodeIndex;");
println(out, " var rootDescDiv;");
println(out, " var emptyRootDiv;");
println(out, " var treeStatusDiv;");
println(out, " var nodes = [];");
println(out, " var currOpener;");
println(out, "");
println(out, " function load(url,target) {");
println(out, " if (target != '')");
println(out, " target.window.location.href = url;");
println(out, " else");
println(out, " window.location.href = url;");
println(out, " }");
println(out, "");
println(out, " function init() {");
println(out, "");
println(out, " rootDescDiv = new YAHOO.widget.Module(\"rootDesc\", {visible:false} );");
println(out, " resetRootDesc();");
println(out, "");
println(out, " emptyRootDiv = new YAHOO.widget.Module(\"emptyRoot\", {visible:true} );");
println(out, " resetEmptyRoot();");
println(out, "");
println(out, " treeStatusDiv = new YAHOO.widget.Module(\"treeStatus\", {visible:true} );");
println(out, " resetTreeStatus();");
println(out, "");
println(out, " currOpener = opener;");
println(out, " initTree();");
println(out, " }");
println(out, "");
println(out, " function addTreeNode(rootNode, nodeInfo) {");
println(out, " var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";");
println(out, " var newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };");
println(out, " var newNode = new YAHOO.widget.TextNode(newNodeData, rootNode, false);");
println(out, " if (nodeInfo.ontology_node_child_count > 0) {");
println(out, " newNode.setDynamicLoad(loadNodeData);");
println(out, " }");
println(out, " }");
println(out, "");
println(out, " function buildTree(ontology_node_id, ontology_display_name) {");
println(out, " var handleBuildTreeSuccess = function(o) {");
println(out, " var respTxt = o.responseText;");
println(out, " var respObj = eval('(' + respTxt + ')');");
println(out, " if ( typeof(respObj) != \"undefined\") {");
println(out, " if ( typeof(respObj.root_nodes) != \"undefined\") {");
println(out, " var root = tree.getRoot();");
println(out, " if (respObj.root_nodes.length == 0) {");
println(out, " showEmptyRoot();");
println(out, " }");
println(out, " else {");
println(out, " for (var i=0; i < respObj.root_nodes.length; i++) {");
println(out, " var nodeInfo = respObj.root_nodes[i];");
println(out, " var expand = false;");
println(out, " addTreeNode(root, nodeInfo, expand);");
println(out, " }");
println(out, " }");
println(out, "");
println(out, " tree.draw();");
println(out, " }");
println(out, " }");
println(out, " resetTreeStatus();");
println(out, " }");
println(out, "");
println(out, " var handleBuildTreeFailure = function(o) {");
println(out, " resetTreeStatus();");
println(out, " resetEmptyRoot();");
println(out, " alert('responseFailure: ' + o.statusText);");
println(out, " }");
println(out, "");
println(out, " var buildTreeCallback =");
println(out, " {");
println(out, " success:handleBuildTreeSuccess,");
println(out, " failure:handleBuildTreeFailure");
println(out, " };");
println(out, "");
println(out, " if (ontology_display_name!='') {");
println(out, " resetEmptyRoot();");
println(out, "");
println(out, " showTreeLoadingStatus();");
println(out, " var ontology_source = null;");
println(out, " var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
println(out, " var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=build_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);");
println(out, " }");
println(out, " }");
println(out, "");
println(out, " function resetTree(ontology_node_id, ontology_display_name) {");
println(out, "");
println(out, " var handleResetTreeSuccess = function(o) {");
println(out, " var respTxt = o.responseText;");
println(out, " var respObj = eval('(' + respTxt + ')');");
println(out, " if ( typeof(respObj) != \"undefined\") {");
println(out, " if ( typeof(respObj.root_node) != \"undefined\") {");
println(out, " var root = tree.getRoot();");
println(out, " var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.root_node.ontology_node_id + \"');\";");
println(out, " var rootNodeData = { label:respObj.root_node.ontology_node_name, id:respObj.root_node.ontology_node_id, href:nodeDetails };");
println(out, " var expand = false;");
println(out, " if (respObj.root_node.ontology_node_child_count > 0) {");
println(out, " expand = true;");
println(out, " }");
println(out, " var ontRoot = new YAHOO.widget.TextNode(rootNodeData, root, expand);");
println(out, "");
println(out, " if ( typeof(respObj.child_nodes) != \"undefined\") {");
println(out, " for (var i=0; i < respObj.child_nodes.length; i++) {");
println(out, " var nodeInfo = respObj.child_nodes[i];");
println(out, " addTreeNode(ontRoot, nodeInfo);");
println(out, " }");
println(out, " }");
println(out, " tree.draw();");
println(out, " setRootDesc(respObj.root_node.ontology_node_name, ontology_display_name);");
println(out, " }");
println(out, " }");
println(out, " resetTreeStatus();");
println(out, " }");
println(out, "");
println(out, " var handleResetTreeFailure = function(o) {");
println(out, " resetTreeStatus();");
println(out, " alert('responseFailure: ' + o.statusText);");
println(out, " }");
println(out, "");
println(out, " var resetTreeCallback =");
println(out, " {");
println(out, " success:handleResetTreeSuccess,");
println(out, " failure:handleResetTreeFailure");
println(out, " };");
println(out, " if (ontology_node_id!= '') {");
println(out, " showTreeLoadingStatus();");
println(out, " var ontology_source = null;");
println(out, " var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
println(out, " var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=reset_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name + '&version='+ ontology_version +'&ontology_source='+ontology_source,resetTreeCallback);");
println(out, " }");
println(out, " }");
println(out, "");
println(out, " function onClickTreeNode(ontology_node_id) {");
out.println(" if (ontology_node_id.indexOf(\"_dot_\") != -1) return;");
println(out, " var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;");
println(out, " var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
println(out, " load('/ncitbrowser/ConceptReport.jsp?dictionary='+ ontology_display_name + '&version='+ ontology_version + '&code=' + ontology_node_id, currOpener);");
println(out, " }");
println(out, "");
println(out, " function onClickViewEntireOntology(ontology_display_name) {");
println(out, " var ontology_display_name = document.pg_form.ontology_display_name.value;");
println(out, " tree = new YAHOO.widget.TreeView(\"treecontainer\");");
println(out, " tree.draw();");
println(out, " resetRootDesc();");
println(out, " buildTree('', ontology_display_name);");
println(out, " }");
println(out, "");
println(out, " function initTree() {");
println(out, "");
println(out, " tree = new YAHOO.widget.TreeView(\"treecontainer\");");
println(out, " var ontology_node_id = document.forms[\"pg_form\"].ontology_node_id.value;");
println(out, " var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;");
println(out, "");
println(out, " if (ontology_node_id == null || ontology_node_id == \"null\")");
println(out, " {");
println(out, " buildTree(ontology_node_id, ontology_display_name);");
println(out, " }");
println(out, " else");
println(out, " {");
println(out, " searchTree(ontology_node_id, ontology_display_name);");
println(out, " }");
println(out, " }");
println(out, "");
println(out, " function initRootDesc() {");
println(out, " rootDescDiv.setBody('');");
println(out, " initRootDesc.show();");
println(out, " rootDescDiv.render();");
println(out, " }");
println(out, "");
println(out, " function resetRootDesc() {");
println(out, " rootDescDiv.hide();");
println(out, " rootDescDiv.setBody('');");
println(out, " rootDescDiv.render();");
println(out, " }");
println(out, "");
println(out, " function resetEmptyRoot() {");
println(out, " emptyRootDiv.hide();");
println(out, " emptyRootDiv.setBody('');");
println(out, " emptyRootDiv.render();");
println(out, " }");
println(out, "");
println(out, " function resetTreeStatus() {");
println(out, " treeStatusDiv.hide();");
println(out, " treeStatusDiv.setBody('');");
println(out, " treeStatusDiv.render();");
println(out, " }");
println(out, "");
println(out, " function showEmptyRoot() {");
println(out, " emptyRootDiv.setBody(\"<span class='instruction_text'>No root nodes available.</span>\");");
println(out, " emptyRootDiv.show();");
println(out, " emptyRootDiv.render();");
println(out, " }");
println(out, "");
println(out, " function showNodeNotFound(node_id) {");
println(out, " //emptyRootDiv.setBody(\"<span class='instruction_text'>Concept with code \" + node_id + \" not found in the hierarchy.</span>\");");
println(out, " emptyRootDiv.setBody(\"<span class='instruction_text'>Concept not part of the parent-child hierarchy in this source; check other relationships.</span>\");");
println(out, " emptyRootDiv.show();");
println(out, " emptyRootDiv.render();");
println(out, " }");
println(out, " ");
println(out, " function showPartialHierarchy() {");
println(out, " rootDescDiv.setBody(\"<span class='instruction_text'>(Note: This tree only shows partial hierarchy.)</span>\");");
println(out, " rootDescDiv.show();");
println(out, " rootDescDiv.render();");
println(out, " }");
println(out, "");
println(out, " function showTreeLoadingStatus() {");
println(out, " treeStatusDiv.setBody(\"<img src='/ncitbrowser/images/loading.gif'/> <span class='instruction_text'>Building tree ...</span>\");");
println(out, " treeStatusDiv.show();");
println(out, " treeStatusDiv.render();");
println(out, " }");
println(out, "");
println(out, " function showTreeDrawingStatus() {");
println(out, " treeStatusDiv.setBody(\"<img src='/ncitbrowser/images/loading.gif'/> <span class='instruction_text'>Drawing tree ...</span>\");");
println(out, " treeStatusDiv.show();");
println(out, " treeStatusDiv.render();");
println(out, " }");
println(out, "");
println(out, " function showSearchingTreeStatus() {");
println(out, " treeStatusDiv.setBody(\"<img src='/ncitbrowser/images/loading.gif'/> <span class='instruction_text'>Searching tree... Please wait.</span>\");");
println(out, " treeStatusDiv.show();");
println(out, " treeStatusDiv.render();");
println(out, " }");
println(out, "");
println(out, " function showConstructingTreeStatus() {");
println(out, " treeStatusDiv.setBody(\"<img src='/ncitbrowser/images/loading.gif'/> <span class='instruction_text'>Constructing tree... Please wait.</span>\");");
println(out, " treeStatusDiv.show();");
println(out, " treeStatusDiv.render();");
println(out, " }");
println(out, "");
/*
println(out, " function loadNodeData(node, fnLoadComplete) {");
println(out, " var id = node.data.id;");
println(out, "");
println(out, " var responseSuccess = function(o)");
println(out, " {");
println(out, " var path;");
println(out, " var dirs;");
println(out, " var files;");
println(out, " var respTxt = o.responseText;");
println(out, " var respObj = eval('(' + respTxt + ')');");
println(out, " var fileNum = 0;");
println(out, " var categoryNum = 0;");
println(out, " if ( typeof(respObj.nodes) != \"undefined\") {");
println(out, " for (var i=0; i < respObj.nodes.length; i++) {");
println(out, " var name = respObj.nodes[i].ontology_node_name;");
println(out, " var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";");
println(out, " var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };");
println(out, " var newNode = new YAHOO.widget.TextNode(newNodeData, node, false);");
println(out, " if (respObj.nodes[i].ontology_node_child_count > 0) {");
println(out, " newNode.setDynamicLoad(loadNodeData);");
println(out, " }");
println(out, " }");
println(out, " }");
println(out, " tree.draw();");
println(out, " fnLoadComplete();");
println(out, " }");
*/
out.println(" function loadNodeData(node, fnLoadComplete) {");
out.println(" var id = node.data.id;");
out.println("");
out.println(" var responseSuccess = function(o)");
out.println(" {");
out.println(" var path;");
out.println(" var dirs;");
out.println(" var files;");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" var fileNum = 0;");
out.println(" var categoryNum = 0;");
out.println(" var pos = id.indexOf(\"_dot_\");");
out.println(" if ( typeof(respObj.nodes) != \"undefined\") {");
out.println(" if (pos == -1) {");
out.println(" for (var i=0; i < respObj.nodes.length; i++) {");
out.println(" var name = respObj.nodes[i].ontology_node_name;");
out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";");
out.println(" var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };");
out.println(" var newNode = new YAHOO.widget.TextNode(newNodeData, node, false);");
out.println(" if (respObj.nodes[i].ontology_node_child_count > 0) {");
out.println(" newNode.setDynamicLoad(loadNodeData);");
out.println(" }");
out.println(" }");
out.println("");
out.println(" } else {");
out.println("");
out.println(" var parent = node.parent;");
out.println(" for (var i=0; i < respObj.nodes.length; i++) {");
out.println(" var name = respObj.nodes[i].ontology_node_name;");
out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";");
out.println(" var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };");
out.println("");
out.println(" var newNode = new YAHOO.widget.TextNode(newNodeData, parent, true);");
out.println(" if (respObj.nodes[i].ontology_node_child_count > 0) {");
out.println(" newNode.setDynamicLoad(loadNodeData);");
out.println(" }");
out.println(" }");
out.println(" tree.removeNode(node,true);");
out.println(" }");
out.println(" }");
out.println(" fnLoadComplete();");
out.println(" }");
println(out, "");
println(out, " var responseFailure = function(o){");
println(out, " alert('responseFailure: ' + o.statusText);");
println(out, " }");
println(out, "");
println(out, " var callback =");
println(out, " {");
println(out, " success:responseSuccess,");
println(out, " failure:responseFailure");
println(out, " };");
println(out, "");
println(out, " var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;");
println(out, " var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
//println(out, " var ontology_display_name = " + "\"" + ontology_display_name + "\";");
//println(out, " var ontology_version = " + "\"" + ontology_version + "\";");
println(out, " var cObj = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_tree&ontology_node_id=' +id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version,callback);");
println(out, " }");
println(out, "");
println(out, " function setRootDesc(rootNodeName, ontology_display_name) {");
println(out, " var newDesc = \"<span class='instruction_text'>Root set to <b>\" + rootNodeName + \"</b></span>\";");
println(out, " rootDescDiv.setBody(newDesc);");
println(out, " var footer = \"<a onClick='javascript:onClickViewEntireOntology();' href='#' class='link_text'>view full ontology}</a>\";");
println(out, " rootDescDiv.setFooter(footer);");
println(out, " rootDescDiv.show();");
println(out, " rootDescDiv.render();");
println(out, " }");
println(out, "");
println(out, "");
println(out, " function searchTree(ontology_node_id, ontology_display_name) {");
println(out, "");
println(out, " var root = tree.getRoot();");
//new ViewInHierarchyUtil().printTree(out, ontology_display_name, ontology_version, node_id);
new ViewInHierarchyUtils().printTree(out, ontology_display_name, ontology_version, node_id);
println(out, " showPartialHierarchy();");
println(out, " tree.draw();");
println(out, " }");
println(out, "");
println(out, "");
println(out, " function addTreeBranch(ontology_node_id, rootNode, nodeInfo) {");
println(out, " var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";");
println(out, " var newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };");
println(out, "");
println(out, " var expand = false;");
println(out, " var childNodes = nodeInfo.children_nodes;");
println(out, "");
println(out, " if (childNodes.length > 0) {");
println(out, " expand = true;");
println(out, " }");
println(out, " var newNode = new YAHOO.widget.TextNode(newNodeData, rootNode, expand);");
println(out, " if (nodeInfo.ontology_node_id == ontology_node_id) {");
println(out, " newNode.labelStyle = \"ygtvlabel_highlight\";");
println(out, " }");
println(out, "");
println(out, " if (nodeInfo.ontology_node_id == ontology_node_id) {");
println(out, " newNode.isLeaf = true;");
println(out, " if (nodeInfo.ontology_node_child_count > 0) {");
println(out, " newNode.isLeaf = false;");
println(out, " newNode.setDynamicLoad(loadNodeData);");
println(out, " } else {");
println(out, " tree.draw();");
println(out, " }");
println(out, "");
println(out, " } else {");
println(out, " if (nodeInfo.ontology_node_id != ontology_node_id) {");
println(out, " if (nodeInfo.ontology_node_child_count == 0 && nodeInfo.ontology_node_id != ontology_node_id) {");
println(out, " newNode.isLeaf = true;");
println(out, " } else if (childNodes.length == 0) {");
println(out, " newNode.setDynamicLoad(loadNodeData);");
println(out, " }");
println(out, " }");
println(out, " }");
println(out, "");
println(out, " tree.draw();");
println(out, " for (var i=0; i < childNodes.length; i++) {");
println(out, " var childnodeInfo = childNodes[i];");
println(out, " addTreeBranch(ontology_node_id, newNode, childnodeInfo);");
println(out, " }");
println(out, " }");
println(out, " YAHOO.util.Event.addListener(window, \"load\", init);");
println(out, "");
println(out, " </script>");
println(out, "</head>");
println(out, "<body>");
println(out, " ");
println(out, " <!-- Begin Skip Top Navigation -->");
println(out, " <a href=\"#evs-content\" class=\"hideLink\" accesskey=\"1\" title=\"Skip repetitive navigation links\">skip navigation links</A>");
println(out, " <!-- End Skip Top Navigation --> ");
println(out, " <div id=\"popupContainer\">");
println(out, " <!-- nci popup banner -->");
println(out, " <div class=\"ncipopupbanner\">");
println(out, " <a href=\"http://www.cancer.gov\" target=\"_blank\" alt=\"National Cancer Institute\"><img src=\"/ncitbrowser/images/nci-banner-1.gif\" width=\"440\" height=\"39\" border=\"0\" alt=\"National Cancer Institute\" /></a>");
println(out, " <a href=\"http://www.cancer.gov\" target=\"_blank\" alt=\"National Cancer Institute\"><img src=\"/ncitbrowser/images/spacer.gif\" width=\"48\" height=\"39\" border=\"0\" alt=\"National Cancer Institute\" class=\"print-header\" /></a>");
println(out, " </div>");
println(out, " <!-- end nci popup banner -->");
println(out, " <div id=\"popupMainArea\">");
println(out, " <a name=\"evs-content\" id=\"evs-content\"></a>");
println(out, " <table class=\"evsLogoBg\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">");
println(out, " <tr>");
println(out, " <td valign=\"top\">");
println(out, " <a href=\"http://evs.nci.nih.gov/\" target=\"_blank\" alt=\"Enterprise Vocabulary Services\">");
println(out, " <img src=\"/ncitbrowser/images/evs-popup-logo.gif\" width=\"213\" height=\"26\" alt=\"EVS: Enterprise Vocabulary Services\" title=\"EVS: Enterprise Vocabulary Services\" border=\"0\" />");
println(out, " </a>");
println(out, " </td>");
println(out, " <td valign=\"top\"><div id=\"closeWindow\"><a href=\"javascript:window.close();\"><img src=\"/ncitbrowser/images/thesaurus_close_icon.gif\" width=\"10\" height=\"10\" border=\"0\" alt=\"Close Window\" /> CLOSE WINDOW</a></div></td>");
println(out, " </tr>");
println(out, " </table>");
println(out, "");
println(out, "");
String release_date = DataUtils.getVersionReleaseDate(ontology_display_name, ontology_version);
if (ontology_display_name.compareTo("NCI Thesaurus") == 0 || ontology_display_name.compareTo("NCI_Thesaurus") == 0) {
println(out, " <div>");
println(out, " <img src=\"/ncitbrowser/images/thesaurus_popup_banner.gif\" width=\"612\" height=\"56\" alt=\"NCI Thesaurus\" title=\"\" border=\"0\" />");
println(out, " ");
println(out, " ");
println(out, " <span class=\"texttitle-blue-rightjust-2\">" + ontology_version + " (Release date: " + release_date + ")</span>");
println(out, " ");
println(out, "");
println(out, " </div>");
} else {
println(out, " <div>");
println(out, " <img src=\"/ncitbrowser/images/other_popup_banner.gif\" width=\"612\" height=\"56\" alt=\"" + display_name + "\" title=\"\" border=\"0\" />");
println(out, " <div class=\"vocabularynamepopupshort\">" + display_name );
println(out, " ");
println(out, " ");
println(out, " <span class=\"texttitle-blue-rightjust\">" + ontology_version + " (Release date: " + release_date + ")</span>");
println(out, " ");
println(out, " ");
println(out, " </div>");
println(out, " </div>");
}
println(out, "");
println(out, " <div id=\"popupContentArea\">");
println(out, " <table width=\"580px\" cellpadding=\"3\" cellspacing=\"0\" border=\"0\">");
println(out, " <tr class=\"textbody\">");
println(out, " <td class=\"pageTitle\" align=\"left\">");
println(out, " " + display_name + " Hierarchy");
println(out, " </td>");
println(out, " <td class=\"pageTitle\" align=\"right\">");
println(out, " <font size=\"1\" color=\"red\" align=\"right\">");
println(out, " <a href=\"javascript:printPage()\"><img src=\"/ncitbrowser/images/printer.bmp\" border=\"0\" alt=\"Send to Printer\"><i>Send to Printer</i></a>");
println(out, " </font>");
println(out, " </td>");
println(out, " </tr>");
println(out, " </table>");
if (! ServerMonitorThread.getInstance().isLexEVSRunning()) {
println(out, " <div class=\"textbodyredsmall\">" + ServerMonitorThread.getInstance().getMessage() + "</div>");
} else {
println(out, " <!-- Tree content -->");
println(out, " <div id=\"rootDesc\">");
println(out, " <div id=\"bd\"></div>");
println(out, " <div id=\"ft\"></div>");
println(out, " </div>");
println(out, " <div id=\"treeStatus\">");
println(out, " <div id=\"bd\"></div>");
println(out, " </div>");
println(out, " <div id=\"emptyRoot\">");
println(out, " <div id=\"bd\"></div>");
println(out, " </div>");
println(out, " <div id=\"treecontainer\"></div>");
}
println(out, "");
println(out, " <form id=\"pg_form\">");
println(out, " ");
String ontology_node_id_value = HTTPUtils.cleanXSS(node_id);
String ontology_display_name_value = HTTPUtils.cleanXSS(ontology_display_name);
String ontology_version_value = HTTPUtils.cleanXSS(ontology_version);
println(out, " <input type=\"hidden\" id=\"ontology_node_id\" name=\"ontology_node_id\" value=\"" + ontology_node_id_value + "\" />");
println(out, " <input type=\"hidden\" id=\"ontology_display_name\" name=\"ontology_display_name\" value=\"" + ontology_display_name_value + "\" />");
//println(out, " <input type=\"hidden\" id=\"schema\" name=\"schema\" value=\"" + scheme_value + "\" />");
println(out, " <input type=\"hidden\" id=\"ontology_version\" name=\"ontology_version\" value=\"" + ontology_version_value + "\" />");
println(out, "");
println(out, " </form>");
println(out, " <!-- End of Tree control content -->");
println(out, " </div>");
println(out, " </div>");
println(out, " </div>");
println(out, " ");
println(out, "</body>");
println(out, "</html>");
if (_debug) {
_logger.debug(Utils.SEPARATOR);
_logger.debug("VIH HTML:\n" + _debugBuffer);
_debugBuffer = null;
_logger.debug(Utils.SEPARATOR);
}
}
public static void create_src_vs_tree(HttpServletRequest request, HttpServletResponse response) {
create_vs_tree(request, response, Constants.STANDARD_VIEW);
}
public static void create_cs_vs_tree(HttpServletRequest request, HttpServletResponse response) {
String dictionary = (String) request.getParameter("dictionary");
if (!DataUtils.isNull(dictionary)) {
String version = (String) request.getParameter("version");
create_vs_tree(request, response, Constants.TERMINOLOGY_VIEW, dictionary, version);
} else {
create_vs_tree(request, response, Constants.TERMINOLOGY_VIEW);
}
}
public static void create_vs_tree(HttpServletRequest request, HttpServletResponse response, int view) {
request.getSession().removeAttribute("b");
request.getSession().removeAttribute("m");
response.setContentType("text/html");
PrintWriter out = null;
String checked_vocabularies = (String) request.getParameter("checked_vocabularies");
System.out.println("checked_vocabularies: " + checked_vocabularies);
String partial_checked_vocabularies = (String) request.getParameter("partial_checked_vocabularies");
System.out.println("partial_checked_vocabularies: " + partial_checked_vocabularies);
try {
out = response.getWriter();
} catch (Exception ex) {
ex.printStackTrace();
return;
}
String message = (String) request.getSession().getAttribute("message");
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
out.println("<html xmlns:c=\"http://java.sun.com/jsp/jstl/core\">");
out.println("<head>");
if (view == Constants.STANDARD_VIEW) {
out.println(" <title>NCI Term Browser - Value Set Source View</title>");
} else {
out.println(" <title>NCI Term Browser - Value Set Terminology View</title>");
}
//out.println(" <title>NCI Thesaurus</title>");
out.println(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">");
out.println("");
out.println("<style type=\"text/css\">");
out.println("/*margin and padding on body element");
out.println(" can introduce errors in determining");
out.println(" element position and are not recommended;");
out.println(" we turn them off as a foundation for YUI");
out.println(" CSS treatments. */");
out.println("body {");
out.println(" margin:0;");
out.println(" padding:0;");
out.println("}");
out.println("</style>");
out.println("");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/fonts/fonts-min.css\" />");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/treeview/assets/skins/sam/treeview.css\" />");
out.println("");
out.println("<script type=\"text/javascript\" src=\"http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js\"></script>");
//Before(GF31982): out.println("<script type=\"text/javascript\" src=\"http://yui.yahooapis.com/2.9.0/build/treeview/treeview-min.js\"></script>");
out.println("<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/treeview-min.js\" ></script>"); //GF31982
out.println("");
out.println("");
out.println("<!-- Dependency -->");
out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js\"></script>");
out.println("");
out.println("<!-- Source file -->");
out.println("<!--");
out.println(" If you require only basic HTTP transaction support, use the");
out.println(" connection_core.js file.");
out.println("-->");
out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection_core-min.js\"></script>");
out.println("");
out.println("<!--");
out.println(" Use the full connection.js if you require the following features:");
out.println(" - Form serialization.");
out.println(" - File Upload using the iframe transport.");
out.println(" - Cross-domain(XDR) transactions.");
out.println("-->");
out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection-min.js\"></script>");
out.println("");
out.println("");
out.println("");
out.println("<!--begin custom header content for this example-->");
out.println("<!--Additional custom style rules for this example:-->");
out.println("<style type=\"text/css\">");
out.println("");
out.println("");
out.println(".ygtvcheck0 { background: url(/ncitbrowser/images/yui/treeview/check0.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }");
out.println(".ygtvcheck1 { background: url(/ncitbrowser/images/yui/treeview/check1.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }");
out.println(".ygtvcheck2 { background: url(/ncitbrowser/images/yui/treeview/check2.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }");
out.println("");
out.println("");
out.println(".ygtv-edit-TaskNode { width: 190px;}");
out.println(".ygtv-edit-TaskNode .ygtvcancel, .ygtv-edit-TextNode .ygtvok { border:none;}");
out.println(".ygtv-edit-TaskNode .ygtv-button-container { float: right;}");
out.println(".ygtv-edit-TaskNode .ygtv-input input{ width: 140px;}");
out.println(".whitebg {");
out.println(" background-color:white;");
out.println("}");
out.println("</style>");
out.println("");
out.println(" <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/styleSheet.css\" />");
out.println(" <link rel=\"shortcut icon\" href=\"/ncitbrowser/favicon.ico\" type=\"image/x-icon\" />");
out.println("");
out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/script.js\"></script>");
out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tasknode.js\"></script>");
println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/search.js\"></script>");
println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/dropdown.js\"></script>");
out.println("");
out.println(" <script type=\"text/javascript\">");
out.println("");
out.println(" function refresh() {");
out.println("");
out.println(" var selectValueSetSearchOptionObj = document.forms[\"valueSetSearchForm\"].selectValueSetSearchOption;");
out.println("");
out.println(" for (var i=0; i<selectValueSetSearchOptionObj.length; i++) {");
out.println(" if (selectValueSetSearchOptionObj[i].checked) {");
out.println(" selectValueSetSearchOption = selectValueSetSearchOptionObj[i].value;");
out.println(" }");
out.println(" }");
out.println("");
out.println("");
out.println(" window.location.href=\"/ncitbrowser/pages/value_set_source_view.jsf?refresh=1\""); //Before(GF31982)
//GF31982(Not Sure): out.println(" window.location.href=\"/ncitbrowser/ajax?action=create_src_vs_tree?refresh=1\"");
out.println(" + \"&nav_type=valuesets\" + \"&opt=\"+ selectValueSetSearchOption;");
out.println("");
out.println(" }");
out.println(" </script>");
out.println("");
out.println(" <script language=\"JavaScript\">");
out.println("");
out.println(" var tree;");
out.println(" var nodeIndex;");
out.println(" var nodes = [];");
out.println("");
out.println(" function load(url,target) {");
out.println(" if (target != '')");
out.println(" target.window.location.href = url;");
out.println(" else");
out.println(" window.location.href = url;");
out.println(" }");
out.println("");
out.println(" function init() {");
out.println(" //initTree();");
out.println(" }");
out.println("");
out.println(" //handler for expanding all nodes");
out.println(" YAHOO.util.Event.on(\"expand_all\", \"click\", function(e) {");
out.println(" //expandEntireTree();");
out.println("");
out.println(" tree.expandAll();");
out.println(" //YAHOO.util.Event.preventDefault(e);");
out.println(" });");
out.println("");
out.println(" //handler for collapsing all nodes");
out.println(" YAHOO.util.Event.on(\"collapse_all\", \"click\", function(e) {");
out.println(" tree.collapseAll();");
out.println(" //YAHOO.util.Event.preventDefault(e);");
out.println(" });");
out.println("");
out.println(" //handler for checking all nodes");
out.println(" YAHOO.util.Event.on(\"check_all\", \"click\", function(e) {");
out.println(" check_all();");
out.println(" //YAHOO.util.Event.preventDefault(e);");
out.println(" });");
out.println("");
out.println(" //handler for unchecking all nodes");
out.println(" YAHOO.util.Event.on(\"uncheck_all\", \"click\", function(e) {");
out.println(" uncheck_all();");
out.println(" //YAHOO.util.Event.preventDefault(e);");
out.println(" });");
out.println("");
out.println("");
out.println("");
out.println(" YAHOO.util.Event.on(\"getchecked\", \"click\", function(e) {");
out.println(" //alert(\"Checked nodes: \" + YAHOO.lang.dump(getCheckedNodes()), \"info\", \"example\");");
out.println(" //YAHOO.util.Event.preventDefault(e);");
out.println("");
out.println(" });");
out.println("");
out.println("");
out.println(" function addTreeNode(rootNode, nodeInfo) {");
out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";");
out.println("");
out.println(" if (nodeInfo.ontology_node_id.indexOf(\"TVS_\") >= 0) {");
out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };");
out.println(" } else {");
out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };");
out.println(" }");
out.println("");
out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, false);");
out.println(" if (nodeInfo.ontology_node_child_count > 0) {");
out.println(" newNode.setDynamicLoad(loadNodeData);");
out.println(" }");
out.println(" }");
out.println("");
out.println(" function buildTree(ontology_node_id, ontology_display_name) {");
out.println(" var handleBuildTreeSuccess = function(o) {");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" if ( typeof(respObj) != \"undefined\") {");
out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {");
out.println(" var root = tree.getRoot();");
out.println(" if (respObj.root_nodes.length == 0) {");
out.println(" //showEmptyRoot();");
out.println(" }");
out.println(" else {");
out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {");
out.println(" var nodeInfo = respObj.root_nodes[i];");
out.println(" var expand = false;");
out.println(" //addTreeNode(root, nodeInfo, expand);");
out.println("");
out.println(" addTreeNode(root, nodeInfo);");
out.println(" }");
out.println(" }");
out.println("");
out.println(" tree.draw();");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
out.println(" var handleBuildTreeFailure = function(o) {");
out.println(" alert('responseFailure: ' + o.statusText);");
out.println(" }");
out.println("");
out.println(" var buildTreeCallback =");
out.println(" {");
out.println(" success:handleBuildTreeSuccess,");
out.println(" failure:handleBuildTreeFailure");
out.println(" };");
out.println("");
out.println(" if (ontology_display_name!='') {");
out.println(" var ontology_source = null;");
out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=build_src_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);");
out.println(" }");
out.println(" }");
out.println("");
out.println(" function resetTree(ontology_node_id, ontology_display_name) {");
out.println("");
out.println(" var handleResetTreeSuccess = function(o) {");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" if ( typeof(respObj) != \"undefined\") {");
out.println(" if ( typeof(respObj.root_node) != \"undefined\") {");
out.println(" var root = tree.getRoot();");
out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.root_node.ontology_node_id + \"');\";");
out.println(" var rootNodeData = { label:respObj.root_node.ontology_node_name, id:respObj.root_node.ontology_node_id, href:nodeDetails };");
out.println(" var expand = false;");
out.println(" if (respObj.root_node.ontology_node_child_count > 0) {");
out.println(" expand = true;");
out.println(" }");
out.println(" var ontRoot = new YAHOO.widget.TaskNode(rootNodeData, root, expand);");
out.println("");
out.println(" if ( typeof(respObj.child_nodes) != \"undefined\") {");
out.println(" for (var i=0; i < respObj.child_nodes.length; i++) {");
out.println(" var nodeInfo = respObj.child_nodes[i];");
out.println(" addTreeNode(ontRoot, nodeInfo);");
out.println(" }");
out.println(" }");
out.println(" tree.draw();");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
out.println(" var handleResetTreeFailure = function(o) {");
out.println(" alert('responseFailure: ' + o.statusText);");
out.println(" }");
out.println("");
out.println(" var resetTreeCallback =");
out.println(" {");
out.println(" success:handleResetTreeSuccess,");
out.println(" failure:handleResetTreeFailure");
out.println(" };");
out.println(" if (ontology_node_id!= '') {");
out.println(" var ontology_source = null;");
out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=reset_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name + '&version='+ ontology_version +'&ontology_source='+ontology_source,resetTreeCallback);");
out.println(" }");
out.println(" }");
out.println("");
out.println(" function onClickTreeNode(ontology_node_id) {");
out.println(" //alert(\"onClickTreeNode \" + ontology_node_id);");
out.println(" window.location = '/ncitbrowser/pages/value_set_treenode_redirect.jsf?ontology_node_id=' + ontology_node_id;");
out.println(" }");
out.println("");
out.println("");
out.println(" function onClickViewEntireOntology(ontology_display_name) {");
out.println(" var ontology_display_name = document.pg_form.ontology_display_name.value;");
out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");");
out.println(" tree.draw();");
// out.println(" buildTree('', ontology_display_name);");
out.println(" }");
out.println("");
out.println(" function initTree() {");
out.println("");
out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");");
out.println(" tree.setNodesProperty('propagateHighlightUp',true);");
out.println(" tree.setNodesProperty('propagateHighlightDown',true);");
out.println(" tree.subscribe('keydown',tree._onKeyDownEvent);");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" tree.subscribe(\"expand\", function(node) {");
out.println("");
out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 39 });");
out.println("");
out.println(" });");
out.println("");
out.println("");
out.println("");
out.println(" tree.subscribe(\"collapse\", function(node) {");
out.println(" //alert(\"Collapsing \" + node.label );");
out.println("");
out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 109 });");
out.println(" });");
out.println("");
out.println(" // By default, trees with TextNodes will fire an event for when the label is clicked:");
out.println(" tree.subscribe(\"checkClick\", function(node) {");
out.println(" //alert(node.data.myNodeId + \" label was checked\");");
out.println(" });");
out.println("");
out.println("");
println(out, " var root = tree.getRoot();");
HashMap value_set_tree_hmap = null;
if (view == Constants.STANDARD_VIEW) {
value_set_tree_hmap = DataUtils.getSourceValueSetTree();
} else {
value_set_tree_hmap = DataUtils.getCodingSchemeValueSetTree();
}
TreeItem root = (TreeItem) value_set_tree_hmap.get("<Root>");
//
//new ValueSetUtils().printTree(out, root);
new ValueSetUtils().printTree(out, root, view);
String contextPath = request.getContextPath();
String view_str = new Integer(view).toString();
//[#31914] Search option and algorithm in value set search box are not preserved in session.
//String option = (String) request.getSession().getAttribute("selectValueSetSearchOption");
//String algorithm = (String) request.getSession().getAttribute("valueset_search_algorithm");
String option = (String) request.getParameter("selectValueSetSearchOption");
if (DataUtils.isNull(option)) {
option = (String) request.getSession().getAttribute("selectValueSetSearchOption");
}
if (DataUtils.isNull(option)) {
option = "Code";
}
request.getSession().setAttribute("selectValueSetSearchOption", option);
String algorithm = (String) request.getParameter("valueset_search_algorithm");
if (DataUtils.isNull(algorithm)) {
algorithm = (String) request.getSession().getAttribute("valueset_search_algorithm");
}
if (DataUtils.isNull(algorithm)) {
algorithm = "exactMatch";
}
request.getSession().setAttribute("valueset_search_algorithm", algorithm);
String matchText = (String) request.getParameter("matchText");
if (DataUtils.isNull(matchText)) {
matchText = (String) request.getSession().getAttribute("matchText");
}
if (DataUtils.isNull(matchText)) {
matchText = "";
} else {
matchText = matchText.trim();
}
request.getSession().setAttribute("matchText", matchText);
String option_code = "";
String option_name = "";
if (DataUtils.isNull(option)) {
option_code = "checked";
} else {
if (option.compareToIgnoreCase("Code") == 0) {
option_code = "checked";
}
if (option.compareToIgnoreCase("Name") == 0) {
option_name = "checked";
}
}
String algorithm_exactMatch = "";
String algorithm_startsWith = "";
String algorithm_contains = "";
if (DataUtils.isNull(algorithm)) {
algorithm_exactMatch = "checked";
} else {
if (algorithm.compareToIgnoreCase("exactMatch") == 0) {
algorithm_exactMatch = "checked";
}
if (algorithm.compareToIgnoreCase("startsWith") == 0) {
algorithm_startsWith = "checked";
}
if (algorithm.compareToIgnoreCase("contains") == 0) {
algorithm_contains = "checked";
}
}
System.out.println("*** OPTION: " + option);
System.out.println("*** ALGORITHM: " + algorithm);
System.out.println("*** matchText: " + matchText);
System.out.println("AjaxServlet option_code: " + option_code);
System.out.println("AjaxServlet option_name: " + option_name);
System.out.println("AjaxServlet algorithm_exactMatch: " + algorithm_exactMatch);
System.out.println("AjaxServlet algorithm_startsWith: " + algorithm_startsWith);
System.out.println("AjaxServlet algorithm_contains: " + algorithm_contains);
out.println("");
if (message == null) {
out.println(" tree.collapseAll();");
}
//initializeNodeCheckState(out);
out.println(" initializeNodeCheckState();");
out.println(" tree.draw();");
out.println(" }");
out.println("");
out.println("");
out.println(" function onCheckClick(node) {");
out.println(" YAHOO.log(node.label + \" check was clicked, new state: \" + node.checkState, \"info\", \"example\");");
out.println(" }");
out.println("");
out.println(" function check_all() {");
out.println(" var topNodes = tree.getRoot().children;");
out.println(" for(var i=0; i<topNodes.length; ++i) {");
out.println(" topNodes[i].check();");
out.println(" }");
out.println(" }");
out.println("");
out.println(" function uncheck_all() {");
out.println(" var topNodes = tree.getRoot().children;");
out.println(" for(var i=0; i<topNodes.length; ++i) {");
out.println(" topNodes[i].uncheck();");
out.println(" }");
out.println(" }");
out.println("");
out.println("");
out.println("");
out.println(" function expand_all() {");
out.println(" //alert(\"expand_all\");");
out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;");
out.println(" onClickViewEntireOntology(ontology_display_name);");
out.println(" }");
out.println("");
out.println("");
// 0=unchecked, 1=some children checked, 2=all children checked
/*
out.println(" // Gets the labels of all of the fully checked nodes");
out.println(" // Could be updated to only return checked leaf nodes by evaluating");
out.println(" // the children collection first.");
out.println(" function getCheckedNodes(nodes) {");
out.println(" nodes = nodes || tree.getRoot().children;");
out.println(" checkedNodes = [];");
out.println(" for(var i=0, l=nodes.length; i<l; i=i+1) {");
out.println(" var n = nodes[i];");
out.println(" //if (n.checkState > 0) { // if we were interested in the nodes that have some but not all children checked");
out.println(" if (n.checkState == 2) {");
out.println(" checkedNodes.push(n.label); // just using label for simplicity");
out.println("");
out.println(" if (n.hasChildren()) {");
out.println(" checkedNodes = checkedNodes.concat(getCheckedNodes(n.children));");
out.println(" }");
out.println("");
out.println(" }");
out.println(" }");
out.println("");
out.println(" var checked_vocabularies = document.forms[\"valueSetSearchForm\"].checked_vocabularies;");
out.println(" checked_vocabularies.value = checkedNodes;");
out.println("");
out.println(" return checkedNodes;");
out.println(" }");
*/
out.println(" function getCheckedVocabularies(nodes) {");
out.println(" getCheckedNodes(nodes);");
out.println(" getPartialCheckedNodes(nodes);");
out.println(" }");
writeInitialize(out);
initializeNodeCheckState(out);
out.println(" // Gets the labels of all of the fully checked nodes");
out.println(" // Could be updated to only return checked leaf nodes by evaluating");
out.println(" // the children collection first.");
out.println(" function getCheckedNodes(nodes) {");
out.println(" nodes = nodes || tree.getRoot().children;");
out.println(" var checkedNodes = [];");
out.println(" for(var i=0, l=nodes.length; i<l; i=i+1) {");
out.println(" var n = nodes[i];");
out.println(" if (n.checkState == 2) {");
out.println(" checkedNodes.push(n.label); // just using label for simplicity");
out.println(" }");
out.println(" if (n.hasChildren()) {");
out.println(" checkedNodes = checkedNodes.concat(getCheckedNodes(n.children));");
out.println(" }");
out.println(" }");
//out.println(" checkedNodes = checkedNodes.concat(\",\");");
out.println(" var checked_vocabularies = document.forms[\"valueSetSearchForm\"].checked_vocabularies;");
out.println(" checked_vocabularies.value = checkedNodes;");
out.println(" return checkedNodes;");
out.println(" }");
out.println(" function getPartialCheckedNodes(nodes) {");
out.println(" nodes = nodes || tree.getRoot().children;");
out.println(" var checkedNodes = [];");
out.println(" for(var i=0, l=nodes.length; i<l; i=i+1) {");
out.println(" var n = nodes[i];");
out.println(" if (n.checkState == 1) {");
out.println(" checkedNodes.push(n.label); // just using label for simplicity");
out.println(" }");
out.println(" if (n.hasChildren()) {");
out.println(" checkedNodes = checkedNodes.concat(getPartialCheckedNodes(n.children));");
out.println(" }");
out.println(" }");
//out.println(" checkedNodes = checkedNodes.concat(\",\");");
out.println(" var partial_checked_vocabularies = document.forms[\"valueSetSearchForm\"].partial_checked_vocabularies;");
out.println(" partial_checked_vocabularies.value = checkedNodes;");
out.println(" return checkedNodes;");
out.println(" }");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" function loadNodeData(node, fnLoadComplete) {");
out.println(" var id = node.data.id;");
out.println("");
out.println(" var responseSuccess = function(o)");
out.println(" {");
out.println(" var path;");
out.println(" var dirs;");
out.println(" var files;");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" var fileNum = 0;");
out.println(" var categoryNum = 0;");
out.println(" if ( typeof(respObj.nodes) != \"undefined\") {");
out.println(" for (var i=0; i < respObj.nodes.length; i++) {");
out.println(" var name = respObj.nodes[i].ontology_node_name;");
out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";");
out.println(" var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };");
out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, node, false);");
out.println(" if (respObj.nodes[i].ontology_node_child_count > 0) {");
out.println(" newNode.setDynamicLoad(loadNodeData);");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" tree.draw();");
out.println(" fnLoadComplete();");
out.println(" }");
out.println("");
out.println(" var responseFailure = function(o){");
out.println(" alert('responseFailure: ' + o.statusText);");
out.println(" }");
out.println("");
out.println(" var callback =");
out.println(" {");
out.println(" success:responseSuccess,");
out.println(" failure:responseFailure");
out.println(" };");
out.println("");
out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;");
out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
out.println(" var cObj = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_src_vs_tree&ontology_node_id=' +id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version,callback);");
out.println(" }");
out.println("");
out.println("");
out.println(" function searchTree(ontology_node_id, ontology_display_name) {");
out.println("");
out.println(" var handleBuildTreeSuccess = function(o) {");
out.println("");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" if ( typeof(respObj) != \"undefined\") {");
out.println("");
out.println(" if ( typeof(respObj.dummy_root_nodes) != \"undefined\") {");
out.println(" showNodeNotFound(ontology_node_id);");
out.println(" }");
out.println("");
out.println(" else if ( typeof(respObj.root_nodes) != \"undefined\") {");
out.println(" var root = tree.getRoot();");
out.println(" if (respObj.root_nodes.length == 0) {");
out.println(" //showEmptyRoot();");
out.println(" }");
out.println(" else {");
out.println(" showPartialHierarchy();");
out.println(" showConstructingTreeStatus();");
out.println("");
out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {");
out.println(" var nodeInfo = respObj.root_nodes[i];");
out.println(" //var expand = false;");
out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
out.println(" var handleBuildTreeFailure = function(o) {");
out.println(" alert('responseFailure: ' + o.statusText);");
out.println(" }");
out.println("");
out.println(" var buildTreeCallback =");
out.println(" {");
out.println(" success:handleBuildTreeSuccess,");
out.println(" failure:handleBuildTreeFailure");
out.println(" };");
out.println("");
out.println(" if (ontology_display_name!='') {");
out.println(" var ontology_source = null;//document.pg_form.ontology_source.value;");
out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=search_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);");
out.println("");
out.println(" }");
out.println(" }");
out.println("");
out.println("");
out.println("");
out.println(" function expandEntireTree() {");
out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");");
out.println(" //tree.draw();");
out.println("");
out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;");
out.println(" var ontology_node_id = document.forms[\"pg_form\"].ontology_node_id.value;");
out.println("");
out.println(" var handleBuildTreeSuccess = function(o) {");
out.println("");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" if ( typeof(respObj) != \"undefined\") {");
out.println("");
out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {");
out.println("");
out.println(" //alert(respObj.root_nodes.length);");
out.println("");
out.println(" var root = tree.getRoot();");
out.println(" if (respObj.root_nodes.length == 0) {");
out.println(" //showEmptyRoot();");
out.println(" } else {");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {");
out.println(" var nodeInfo = respObj.root_nodes[i];");
out.println(" //alert(\"calling addTreeBranch \");");
out.println("");
out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
out.println(" var handleBuildTreeFailure = function(o) {");
out.println(" alert('responseFailure: ' + o.statusText);");
out.println(" }");
out.println("");
out.println(" var buildTreeCallback =");
out.println(" {");
out.println(" success:handleBuildTreeSuccess,");
out.println(" failure:handleBuildTreeFailure");
out.println(" };");
out.println("");
out.println(" if (ontology_display_name!='') {");
out.println(" var ontology_source = null;");
out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_entire_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);");
out.println("");
out.println(" }");
out.println(" }");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" function addTreeBranch(ontology_node_id, rootNode, nodeInfo) {");
out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";");
out.println("");
out.println(" var newNodeData;");
out.println(" if (ontology_node_id.indexOf(\"TVS_\") >= 0) {");
out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };");
out.println(" } else {");
out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };");
out.println(" }");
out.println("");
out.println(" var expand = false;");
out.println(" var childNodes = nodeInfo.children_nodes;");
out.println("");
out.println(" if (childNodes.length > 0) {");
out.println(" expand = true;");
out.println(" }");
out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, expand);");
out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {");
out.println(" newNode.labelStyle = \"ygtvlabel_highlight\";");
out.println(" }");
out.println("");
out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {");
out.println(" newNode.isLeaf = true;");
out.println(" if (nodeInfo.ontology_node_child_count > 0) {");
out.println(" newNode.isLeaf = false;");
out.println(" newNode.setDynamicLoad(loadNodeData);");
out.println(" } else {");
out.println(" tree.draw();");
out.println(" }");
out.println("");
out.println(" } else {");
out.println(" if (nodeInfo.ontology_node_id != ontology_node_id) {");
out.println(" if (nodeInfo.ontology_node_child_count == 0 && nodeInfo.ontology_node_id != ontology_node_id) {");
out.println(" newNode.isLeaf = true;");
out.println(" } else if (childNodes.length == 0) {");
out.println(" newNode.setDynamicLoad(loadNodeData);");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
out.println(" tree.draw();");
out.println(" for (var i=0; i < childNodes.length; i++) {");
out.println(" var childnodeInfo = childNodes[i];");
out.println(" addTreeBranch(ontology_node_id, newNode, childnodeInfo);");
out.println(" }");
out.println(" }");
out.println(" YAHOO.util.Event.addListener(window, \"load\", init);");
out.println("");
out.println(" YAHOO.util.Event.onDOMReady(initTree);");
out.println("");
out.println("");
out.println(" </script>");
out.println("");
out.println("</head>");
out.println("");
out.println("");
out.println("");
out.println("");
out.println("");
out.println("<body onLoad=\"document.forms.valueSetSearchForm.matchText.focus();\">");
//out.println("<body onLoad=\"initialize();\">");
out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/wz_tooltip.js\"></script>");
out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_centerwindow.js\"></script>");
out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_followscroll.js\"></script>");
out.println("");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" <!-- Begin Skip Top Navigation -->");
out.println(" <a href=\"#evs-content\" class=\"hideLink\" accesskey=\"1\" title=\"Skip repetitive navigation links\">skip navigation links</A>");
out.println(" <!-- End Skip Top Navigation -->");
out.println("");
out.println("<!-- nci banner -->");
out.println("<div class=\"ncibanner\">");
out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">");
out.println(" <img src=\"/ncitbrowser/images/logotype.gif\"");
out.println(" width=\"440\" height=\"39\" border=\"0\"");
out.println(" alt=\"National Cancer Institute\"/>");
out.println(" </a>");
out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">");
out.println(" <img src=\"/ncitbrowser/images/spacer.gif\"");
out.println(" width=\"48\" height=\"39\" border=\"0\"");
out.println(" alt=\"National Cancer Institute\" class=\"print-header\"/>");
out.println(" </a>");
out.println(" <a href=\"http://www.nih.gov\" target=\"_blank\" >");
out.println(" <img src=\"/ncitbrowser/images/tagline_nologo.gif\"");
out.println(" width=\"173\" height=\"39\" border=\"0\"");
out.println(" alt=\"U.S. National Institutes of Health\"/>");
out.println(" </a>");
out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">");
out.println(" <img src=\"/ncitbrowser/images/cancer-gov.gif\"");
out.println(" width=\"99\" height=\"39\" border=\"0\"");
out.println(" alt=\"www.cancer.gov\"/>");
out.println(" </a>");
out.println("</div>");
out.println("<!-- end nci banner -->");
out.println("");
out.println(" <div class=\"center-page\">");
out.println(" <!-- EVS Logo -->");
out.println("<div>");
out.println(" <img src=\"/ncitbrowser/images/evs-logo-swapped.gif\" alt=\"EVS Logo\"");
out.println(" width=\"745\" height=\"26\" border=\"0\"");
out.println(" usemap=\"#external-evs\" />");
out.println(" <map id=\"external-evs\" name=\"external-evs\">");
out.println(" <area shape=\"rect\" coords=\"0,0,140,26\"");
out.println(" href=\"/ncitbrowser/start.jsf\" target=\"_self\"");
out.println(" alt=\"NCI Term Browser\" />");
out.println(" <area shape=\"rect\" coords=\"520,0,745,26\"");
out.println(" href=\"http://evs.nci.nih.gov/\" target=\"_blank\"");
out.println(" alt=\"Enterprise Vocabulary Services\" />");
out.println(" </map>");
out.println("</div>");
out.println("");
out.println("");
out.println("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">");
out.println(" <tr>");
out.println(" <td width=\"5\"></td>");
out.println(" <td><a href=\"/ncitbrowser/pages/multiple_search.jsf?nav_type=terminologies\">");
out.println(" <img name=\"tab_terms\" src=\"/ncitbrowser/images/tab_terms.gif\"");
out.println(" border=\"0\" alt=\"Terminologies\" title=\"Terminologies\" /></a></td>");
//Before(GF31982): out.println(" <td><a href=\"/ncitbrowser/pages/value_set_source_view.jsf?nav_type=valuesets\">");
out.println(" <td><a href=\"/ncitbrowser/ajax?action=create_src_vs_tree\">"); //GF31982
out.println(" <img name=\"tab_valuesets\" src=\"/ncitbrowser/images/tab_valuesets_clicked.gif\"");
out.println(" border=\"0\" alt=\"Value Sets\" title=\"ValueSets\" /></a></td>");
out.println(" <td><a href=\"/ncitbrowser/pages/mapping_search.jsf?nav_type=mappings\">");
out.println(" <img name=\"tab_map\" src=\"/ncitbrowser/images/tab_map.gif\"");
out.println(" border=\"0\" alt=\"Mappings\" title=\"Mappings\" /></a></td>");
out.println(" </tr>");
out.println("</table>");
out.println("");
out.println("<div class=\"mainbox-top\"><img src=\"/ncitbrowser/images/mainbox-top.gif\" width=\"745\" height=\"5\" alt=\"\"/></div>");
out.println("<!-- end EVS Logo -->");
out.println(" <!-- Main box -->");
out.println(" <div id=\"main-area\">");
out.println("");
out.println(" <!-- Thesaurus, banner search area -->");
out.println(" <div class=\"bannerarea\">");
out.println(" <a href=\"/ncitbrowser/start.jsf\" style=\"text-decoration: none;\">");
out.println(" <div class=\"vocabularynamebanner_tb\">");
out.println(" <span class=\"vocabularynamelong_tb\">" + JSPUtils.getApplicationVersionDisplay() + "</span>");
out.println(" </div>");
out.println(" </a>");
out.println(" <div class=\"search-globalnav\">");
out.println(" <!-- Search box -->");
out.println(" <div class=\"searchbox-top\"><img src=\"/ncitbrowser/images/searchbox-top.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Top\" /></div>");
out.println(" <div class=\"searchbox\">");
out.println("");
out.println("");
//out.println("<form id=\"valueSetSearchForm\" name=\"valueSetSearchForm\" method=\"post\" action=\"" + contextPath + + "/ajax?action=saerch_value_set_tree\"> "/pages/value_set_source_view.jsf\" class=\"search-form-main-area\" enctype=\"application/x-www-form-urlencoded\">");
out.println("<form id=\"valueSetSearchForm\" name=\"valueSetSearchForm\" method=\"post\" action=\"" + contextPath + "/ajax?action=search_value_set\" class=\"search-form-main-area\" enctype=\"application/x-www-form-urlencoded\">");
out.println("<input type=\"hidden\" name=\"valueSetSearchForm\" value=\"valueSetSearchForm\" />");
out.println("<input type=\"hidden\" name=\"view\" value=\"" + view_str + "\" />");
out.println("");
out.println("");
out.println("");
out.println(" <input type=\"hidden\" id=\"checked_vocabularies\" name=\"checked_vocabularies\" value=\"\" />");
out.println(" <input type=\"hidden\" id=\"partial_checked_vocabularies\" name=\"partial_checked_vocabularies\" value=\"\" />");
out.println("");
out.println("");
out.println("");
out.println("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 2px\" >");
out.println(" <tr valign=\"top\" align=\"left\">");
out.println(" <td align=\"left\" class=\"textbody\">");
out.println("");
out.println(" <input CLASS=\"searchbox-input-2\"");
out.println(" name=\"matchText\"");
out.println(" value=\"" + matchText + "\"");
out.println(" onFocus=\"active = true\"");
out.println(" onBlur=\"active = false\"");
out.println(" onkeypress=\"return submitEnter('valueSetSearchForm:valueset_search',event)\"");
out.println(" tabindex=\"1\"/>");
out.println("");
out.println("");
out.println(" <input id=\"valueSetSearchForm:valueset_search\" type=\"image\" src=\"/ncitbrowser/images/search.gif\" name=\"valueSetSearchForm:valueset_search\" alt=\"Search Value Sets\" onclick=\"javascript:getCheckedVocabularies();\" tabindex=\"2\" class=\"searchbox-btn\" /><a href=\"/ncitbrowser/pages/help.jsf#searchhelp\" tabindex=\"3\"><img src=\"/ncitbrowser/images/search-help.gif\" alt=\"Search Help\" style=\"border-width:0;\" class=\"searchbox-btn\" /></a>");
out.println("");
out.println("");
out.println(" </td>");
out.println(" </tr>");
out.println("");
out.println(" <tr valign=\"top\" align=\"left\">");
out.println(" <td>");
out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 0px\">");
out.println("");
out.println(" <tr valign=\"top\" align=\"left\">");
out.println(" <td align=\"left\" class=\"textbody\">");
out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"exactMatch\" alt=\"Exact Match\" " + algorithm_exactMatch + " tabindex=\"3\">Exact Match ");
out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"startsWith\" alt=\"Begins With\" " + algorithm_startsWith + " tabindex=\"3\">Begins With ");
out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"contains\" alt=\"Contains\" " + algorithm_contains + " tabindex=\"3\">Contains");
out.println(" </td>");
out.println(" </tr>");
out.println("");
out.println(" <tr align=\"left\">");
out.println(" <td height=\"1px\" bgcolor=\"#2F2F5F\" align=\"left\"></td>");
out.println(" </tr>");
out.println(" <tr valign=\"top\" align=\"left\">");
out.println(" <td align=\"left\" class=\"textbody\">");
out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Code\" " + option_code + " alt=\"Code\" tabindex=\"1\" >Code ");
out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Name\" " + option_name + " alt=\"Name\" tabindex=\"1\" >Name");
out.println(" </td>");
out.println(" </tr>");
out.println(" </table>");
out.println(" </td>");
out.println(" </tr>");
out.println("</table>");
out.println(" <input type=\"hidden\" name=\"referer\" id=\"referer\" value=\"http%3A%2F%2Flocalhost%3A8080%2Fncitbrowser%2Fpages%2Fresolved_value_set_search_results.jsf\">");
out.println(" <input type=\"hidden\" id=\"nav_type\" name=\"nav_type\" value=\"valuesets\" />");
out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />");
out.println("");
out.println("<input type=\"hidden\" name=\"javax.faces.ViewState\" id=\"javax.faces.ViewState\" value=\"j_id22:j_id23\" />");
out.println("</form>");
addHiddenForm(out, checked_vocabularies, partial_checked_vocabularies);
out.println(" </div> <!-- searchbox -->");
out.println("");
out.println(" <div class=\"searchbox-bottom\"><img src=\"/ncitbrowser/images/searchbox-bottom.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Bottom\" /></div>");
out.println(" <!-- end Search box -->");
out.println(" <!-- Global Navigation -->");
out.println("");
out.println("<table class=\"global-nav\" border=\"0\" width=\"100%\" height=\"37px\" cellpadding=\"0\" cellspacing=\"0\">");
out.println(" <tr>");
out.println(" <td align=\"left\" valign=\"bottom\">");
out.println(" <a href=\"#\" onclick=\"javascript:window.open('/ncitbrowser/pages/source_help_info-termbrowser.jsf',");
out.println(" '_blank','top=100, left=100, height=740, width=780, status=no, menubar=no, resizable=yes, scrollbars=yes, toolbar=no, location=no, directories=no');\" tabindex=\"13\">");
out.println(" Sources</a>");
out.println("");
String cart_size = (String) request.getSession().getAttribute("cart_size");
if (!DataUtils.isNull(cart_size)) {
out.write("|");
out.write(" <a href=\"");
out.print(request.getContextPath());
out.write("/pages/cart.jsf\" tabindex=\"16\">Cart</a>\r\n");
}
//KLO, 022612
out.println(" \r\n");
out.println(" ");
out.print( VisitedConceptUtils.getDisplayLink(request, true) );
out.println(" \r\n");
// Visited concepts -- to be implemented.
// out.println(" | <A href=\"#\" onmouseover=\"Tip('<ul><li><a href=\'/ncitbrowser/ConceptReport.jsp?dictionary=NCI Thesaurus&version=11.09d&code=C44256\'>Ratio (NCI Thesaurus 11.09d)</a><br></li></ul>',WIDTH, 300, TITLE, 'Visited Concepts', SHADOW, true, FADEIN, 300, FADEOUT, 300, STICKY, 1, CLOSEBTN, true, CLICKCLOSE, true)\" onmouseout=UnTip() >Visited Concepts</A>");
out.println(" </td>");
out.println(" <td align=\"right\" valign=\"bottom\">");
out.println(" <a href=\"");
out.print( request.getContextPath() );
out.println("/pages/help.jsf\" tabindex=\"16\">Help</a>\r\n");
out.println(" </td>\r\n");
out.println(" <td width=\"7\"></td>\r\n");
out.println(" </tr>\r\n");
out.println("</table>");
/*
out.println(" <a href=\"/ncitbrowser/pages/help.jsf\" tabindex=\"16\">Help</a>");
out.println(" </td>");
out.println(" <td width=\"7\"></td>");
out.println(" </tr>");
out.println("</table>");
*/
out.println(" <!-- end Global Navigation -->");
out.println("");
out.println(" </div> <!-- search-globalnav -->");
out.println(" </div> <!-- bannerarea -->");
out.println("");
out.println(" <!-- end Thesaurus, banner search area -->");
out.println(" <!-- Quick links bar -->");
out.println("");
out.println("<div class=\"bluebar\">");
out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
out.println(" <tr>");
out.println(" <td><div class=\"quicklink-status\"> </div></td>");
out.println(" <td>");
out.println("");
/*
out.println(" <div id=\"quicklinksholder\">");
out.println(" <ul id=\"quicklinks\"");
out.println(" onmouseover=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-active.gif';\"");
out.println(" onmouseout=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-inactive.gif';\">");
out.println(" <li>");
out.println(" <a href=\"#\" tabindex=\"-1\"><img src=\"/ncitbrowser/images/quicklinks-inactive.gif\" width=\"162\"");
out.println(" height=\"18\" border=\"0\" name=\"quicklinksimg\" alt=\"Quick Links\" />");
out.println(" </a>");
out.println(" <ul>");
out.println(" <li><a href=\"http://evs.nci.nih.gov/\" tabindex=\"-1\" target=\"_blank\"");
out.println(" alt=\"Enterprise Vocabulary Services\">EVS Home</a></li>");
out.println(" <li><a href=\"http://localhost/ncimbrowserncimbrowser\" tabindex=\"-1\" target=\"_blank\"");
out.println(" alt=\"NCI Metathesaurus\">NCI Metathesaurus Browser</a></li>");
out.println("");
out.println(" <li><a href=\"/ncitbrowser/start.jsf\" tabindex=\"-1\"");
out.println(" alt=\"NCI Term Browser\">NCI Term Browser</a></li>");
out.println(" <li><a href=\"http://www.cancer.gov/cancertopics/terminologyresources\" tabindex=\"-1\" target=\"_blank\"");
out.println(" alt=\"NCI Terminology Resources\">NCI Terminology Resources</a></li>");
out.println("");
out.println(" <li><a href=\"http://ncitermform.nci.nih.gov/ncitermform/?dictionary=NCI%20Thesaurus\" tabindex=\"-1\" target=\"_blank\" alt=\"Term Suggestion\">Term Suggestion</a></li>");
out.println("");
out.println("");
out.println(" </ul>");
out.println(" </li>");
out.println(" </ul>");
out.println(" </div>");
*/
addQuickLink(request, out);
out.println("");
out.println(" </td>");
out.println(" </tr>");
out.println(" </table>");
out.println("");
out.println("</div>");
if (! ServerMonitorThread.getInstance().isLexEVSRunning()) {
out.println(" <div class=\"redbar\">");
out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
out.println(" <tr>");
out.println(" <td class=\"lexevs-status\">");
out.println(" " + ServerMonitorThread.getInstance().getMessage());
out.println(" </td>");
out.println(" </tr>");
out.println(" </table>");
out.println(" </div>");
}
out.println(" <!-- end Quick links bar -->");
out.println("");
out.println(" <!-- Page content -->");
out.println(" <div class=\"pagecontent\">");
out.println("");
if (message != null) {
out.println("\r\n");
out.println(" <p class=\"textbodyred\">");
out.print(message);
out.println("</p>\r\n");
out.println(" ");
request.getSession().removeAttribute("message");
}
out.println("<p class=\"textbody\">");
out.println("View value sets organized by standards category or source terminology.");
out.println("Standards categories group the value sets supporting them; all other labels lead to the home pages of actual value sets or source terminologies.");
out.println("Search or browse a value set from its home page, or search all value sets at once from this page (very slow) to find which ones contain a particular code or term.");
out.println("</p>");
out.println("");
out.println(" <div id=\"popupContentArea\">");
out.println(" <a name=\"evs-content\" id=\"evs-content\"></a>");
out.println("");
out.println(" <table width=\"580px\" cellpadding=\"3\" cellspacing=\"0\" border=\"0\">");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" <tr class=\"textbody\">");
out.println(" <td class=\"textbody\" align=\"left\">");
out.println("");
if (view == Constants.STANDARD_VIEW) {
out.println(" Standards View");
out.println(" |");
out.println(" <a href=\"" + contextPath + "/ajax?action=create_cs_vs_tree\">Terminology View</a>");
} else {
out.println(" <a href=\"" + contextPath + "/ajax?action=create_src_vs_tree\">Standards View</a>");
out.println(" |");
out.println(" Terminology View");
}
out.println(" </td>");
out.println("");
out.println(" <td align=\"right\">");
out.println(" <font size=\"1\" color=\"red\" align=\"right\">");
out.println(" <a href=\"javascript:printPage()\"><img src=\"/ncitbrowser/images/printer.bmp\" border=\"0\" alt=\"Send to Printer\"><i>Send to Printer</i></a>");
out.println(" </font>");
out.println(" </td>");
out.println(" </tr>");
out.println(" </table>");
out.println("");
out.println(" <hr/>");
out.println("");
out.println("");
out.println("");
out.println("<style>");
out.println("#expandcontractdiv {border:1px solid #336600; background-color:#FFFFCC; margin:0 0 .5em 0; padding:0.2em;}");
out.println("#treecontainer { background: #fff }");
out.println("</style>");
out.println("");
out.println("");
out.println("<div id=\"expandcontractdiv\">");
out.println(" <a id=\"expand_all\" href=\"#\">Expand all</a>");
out.println(" <a id=\"collapse_all\" href=\"#\">Collapse all</a>");
out.println(" <a id=\"check_all\" href=\"#\">Check all</a>");
out.println(" <a id=\"uncheck_all\" href=\"#\">Uncheck all</a>");
out.println("</div>");
out.println("");
out.println("");
out.println("");
out.println(" <!-- Tree content -->");
out.println("");
out.println(" <div id=\"treecontainer\" class=\"ygtv-checkbox\"></div>");
out.println("");
out.println(" <form id=\"pg_form\">");
out.println(" <input type=\"hidden\" id=\"ontology_node_id\" name=\"ontology_node_id\" value=\"null\" />");
out.println(" <input type=\"hidden\" id=\"schema\" name=\"schema\" value=\"null\" />");
out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />");
out.println(" </form>");
out.println("");
out.println("");
out.println(" </div> <!-- popupContentArea -->");
out.println("");
out.println("");
out.println("<div class=\"textbody\">");
out.println("<!-- footer -->");
out.println("<div class=\"footer\" style=\"width:720px\">");
out.println(" <ul>");
out.println(" <li><a href=\"http://www.cancer.gov\" target=\"_blank\" alt=\"National Cancer Institute\">NCI Home</a> |</li>");
out.println(" <li><a href=\"/ncitbrowser/pages/contact_us.jsf\">Contact Us</a> |</li>");
out.println(" <li><a href=\"http://www.cancer.gov/policies\" target=\"_blank\" alt=\"National Cancer Institute Policies\">Policies</a> |</li>");
out.println(" <li><a href=\"http://www.cancer.gov/policies/page3\" target=\"_blank\" alt=\"National Cancer Institute Accessibility\">Accessibility</a> |</li>");
out.println(" <li><a href=\"http://www.cancer.gov/policies/page6\" target=\"_blank\" alt=\"National Cancer Institute FOIA\">FOIA</a></li>");
out.println(" </ul>");
out.println(" <p>");
out.println(" A Service of the National Cancer Institute<br />");
out.println(" <img src=\"/ncitbrowser/images/external-footer-logos.gif\"");
out.println(" alt=\"External Footer Logos\" width=\"238\" height=\"34\" border=\"0\"");
out.println(" usemap=\"#external-footer\" />");
out.println(" </p>");
out.println(" <map id=\"external-footer\" name=\"external-footer\">");
out.println(" <area shape=\"rect\" coords=\"0,0,46,34\"");
out.println(" href=\"http://www.cancer.gov\" target=\"_blank\"");
out.println(" alt=\"National Cancer Institute\" />");
out.println(" <area shape=\"rect\" coords=\"55,1,99,32\"");
out.println(" href=\"http://www.hhs.gov/\" target=\"_blank\"");
out.println(" alt=\"U.S. Health & Human Services\" />");
out.println(" <area shape=\"rect\" coords=\"103,1,147,31\"");
out.println(" href=\"http://www.nih.gov/\" target=\"_blank\"");
out.println(" alt=\"National Institutes of Health\" />");
out.println(" <area shape=\"rect\" coords=\"148,1,235,33\"");
out.println(" href=\"http://www.usa.gov/\" target=\"_blank\"");
out.println(" alt=\"USA.gov\" />");
out.println(" </map>");
out.println("</div>");
out.println("<!-- end footer -->");
out.println("</div>");
out.println("");
out.println("");
out.println(" </div> <!-- pagecontent -->");
out.println(" </div> <!-- main-area -->");
out.println(" <div class=\"mainbox-bottom\"><img src=\"/ncitbrowser/images/mainbox-bottom.gif\" width=\"745\" height=\"5\" alt=\"Mainbox Bottom\" /></div>");
out.println("");
out.println(" </div> <!-- center-page -->");
out.println("");
out.println("</body>");
out.println("</html>");
out.println("");
}
public static void search_value_set(HttpServletRequest request, HttpServletResponse response) {
String selectValueSetSearchOption = (String) request.getParameter("selectValueSetSearchOption");
request.getSession().setAttribute("selectValueSetSearchOption", selectValueSetSearchOption);
String algorithm = (String) request.getParameter("valueset_search_algorithm");
request.getSession().setAttribute("valueset_search_algorithm", algorithm);
// check if any checkbox is checked.
String contextPath = request.getContextPath();
String view_str = (String) request.getParameter("view");
int view = Integer.parseInt(view_str);
String msg = null;
request.getSession().removeAttribute("checked_vocabularies");
String checked_vocabularies = (String) request.getParameter("checked_vocabularies");
System.out.println("checked_vocabularies: " + checked_vocabularies);
request.getSession().removeAttribute("partial_checked_vocabularies");
String partial_checked_vocabularies = (String) request.getParameter("partial_checked_vocabularies");
System.out.println("partial_checked_vocabularies: " + partial_checked_vocabularies);
String matchText = (String) request.getParameter("matchText");
if (DataUtils.isNull(matchText)) {
matchText = "";
} else {
matchText = matchText.trim();
}
request.getSession().setAttribute("matchText", matchText);
String ontology_display_name = (String) request.getParameter("ontology_display_name");
String ontology_version = (String) request.getParameter("ontology_version");
if (matchText.compareTo("") == 0) {
msg = "Please enter a search string.";
System.out.println(msg);
request.getSession().setAttribute("message", msg);
if (!DataUtils.isNull(ontology_display_name) && !DataUtils.isNull(ontology_version)) {
create_vs_tree(request, response, view, ontology_display_name, ontology_version);
} else {
create_vs_tree(request, response, view);
}
return;
}
if (checked_vocabularies == null || (checked_vocabularies != null && checked_vocabularies.compareTo("") == 0)) { //DYEE
msg = "No value set definition is selected.";
System.out.println(msg);
request.getSession().setAttribute("message", msg);
if (!DataUtils.isNull(ontology_display_name) && !DataUtils.isNull(ontology_version)) {
create_vs_tree(request, response, view, ontology_display_name, ontology_version);
} else {
create_vs_tree(request, response, view);
}
} else {
String destination = contextPath + "/pages/value_set_search_results.jsf";
try {
String retstr = valueSetSearchAction(request);
//KLO, 041312
if (retstr.compareTo("message") == 0) {
if (!DataUtils.isNull(ontology_display_name) && !DataUtils.isNull(ontology_version)) {
create_vs_tree(request, response, view, ontology_display_name, ontology_version);
} else {
create_vs_tree(request, response, view);
}
return;
}
System.out.println("(*) redirecting to: " + destination);
response.sendRedirect(response.encodeRedirectURL(destination));
request.getSession().setAttribute("checked_vocabularies", checked_vocabularies);
} catch (Exception ex) {
System.out.println("response.sendRedirect failed???");
}
}
}
public static String valueSetSearchAction(HttpServletRequest request) {
java.lang.String valueSetDefinitionRevisionId = null;
String msg = null;
String selectValueSetSearchOption = (String) request.getParameter("selectValueSetSearchOption");
if (DataUtils.isNull(selectValueSetSearchOption)) {
selectValueSetSearchOption = "Name";
}
request.getSession().setAttribute("selectValueSetSearchOption", selectValueSetSearchOption);
String algorithm = (String) request.getParameter("valueset_search_algorithm");
if (DataUtils.isNull(algorithm)) {
algorithm = "exactMatch";
}
request.getSession().setAttribute("valueset_search_algorithm", algorithm);
String checked_vocabularies = (String) request.getParameter("checked_vocabularies");
System.out.println("checked_vocabularies: " + checked_vocabularies);
if (checked_vocabularies != null && checked_vocabularies.compareTo("") == 0) {
msg = "No value set definition is selected.";
System.out.println(msg);
request.getSession().setAttribute("message", msg);
return "message";
}
Vector selected_vocabularies = new Vector();
selected_vocabularies = DataUtils.parseData(checked_vocabularies, ",");
System.out.println("selected_vocabularies count: " + selected_vocabularies.size());
String VSD_view = (String) request.getParameter("view");
request.getSession().setAttribute("view", VSD_view);
String matchText = (String) request.getParameter("matchText");
Vector v = new Vector();
LexEVSValueSetDefinitionServices vsd_service = null;
vsd_service = RemoteServerUtil.getLexEVSValueSetDefinitionServices();
if (matchText != null) matchText = matchText.trim();
if (selectValueSetSearchOption.compareTo("Code") == 0) {
String uri = null;
try {
String versionTag = null;//"PRODUCTION";
if (checked_vocabularies != null) {
for (int k=0; k<selected_vocabularies.size(); k++) {
String vsd_name = (String) selected_vocabularies.elementAt(k);
String vsd_uri = DataUtils.getValueSetDefinitionURIByName(vsd_name);
System.out.println("vsd_name: " + vsd_name + " (vsd_uri: " + vsd_uri + ")");
try {
//ValueSetDefinition vsd = vsd_service.getValueSetDefinition(new URI(vsd_uri), null);
if (vsd_uri != null) {
ValueSetDefinition vsd = vsd_service.getValueSetDefinition(new URI(vsd_uri), null);
AbsoluteCodingSchemeVersionReference acsvr = vsd_service.isEntityInValueSet(matchText,
new URI(vsd_uri),
null,
versionTag);
if (acsvr != null) {
String metadata = DataUtils.getValueSetDefinitionMetadata(vsd);
if (metadata != null) {
v.add(metadata);
}
}
} else {
System.out.println("WARNING: Unable to find vsd_uri for " + vsd_name);
}
} catch (Exception ex) {
System.out.println("WARNING: vsd_service.getValueSetDefinition threw exception: " + vsd_name);
}
}
} else {
AbsoluteCodingSchemeVersionReferenceList csVersionList = null;//ValueSetHierarchy.getAbsoluteCodingSchemeVersionReferenceList();
List list = vsd_service.listValueSetsWithEntityCode(matchText, null, csVersionList, versionTag);
if (list != null) {
for (int j=0; j<list.size(); j++) {
uri = (String) list.get(j);
String vsd_name = DataUtils.valueSetDefiniionURI2Name(uri);
if (selected_vocabularies.contains(vsd_name)) {
try {
ValueSetDefinition vsd = vsd_service.getValueSetDefinition(new URI(uri), null);
if (vsd == null) {
msg = "Unable to find any value set with URI " + uri + ".";
request.getSession().setAttribute("message", msg);
return "message";
}
String metadata = DataUtils.getValueSetDefinitionMetadata(vsd);
if (metadata != null) {
v.add(metadata);
}
} catch (Exception ex) {
ex.printStackTrace();
msg = "Unable to find any value set with URI " + uri + ".";
request.getSession().setAttribute("message", msg);
return "message";
}
}
}
}
}
request.getSession().setAttribute("matched_vsds", v);
if (v.size() == 0) {
msg = "No match found.";
request.getSession().setAttribute("message", msg);
return "message";
} else if (v.size() == 1) {
request.getSession().setAttribute("vsd_uri", uri);
}
return "value_set";
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("vsd_service.listValueSetsWithEntityCode throws exceptions???");
}
msg = "Unexpected errors encountered; search by code failed.";
request.getSession().setAttribute("message", msg);
return "message";
} else if (selectValueSetSearchOption.compareTo("Name") == 0) {
String uri = null;
try {
Vector uri_vec = DataUtils.getValueSetURIs();
for (int i=0; i<uri_vec.size(); i++) {
uri = (String) uri_vec.elementAt(i);
String vsd_name = DataUtils.valueSetDefiniionURI2Name(uri);
if (checked_vocabularies == null || selected_vocabularies.contains(vsd_name)) {
//System.out.println("Searching " + vsd_name + "...");
AbsoluteCodingSchemeVersionReferenceList csVersionList = null;
/*
Vector cs_ref_vec = DataUtils.getCodingSchemeReferencesInValueSetDefinition(uri, "PRODUCTION");
if (cs_ref_vec != null) {
csVersionList = DataUtils.vector2CodingSchemeVersionReferenceList(cs_ref_vec);
}
*/
ResolvedValueSetCodedNodeSet rvs_cns = null;
SortOptionList sortOptions = null;
LocalNameList propertyNames = null;
CodedNodeSet.PropertyType[] propertyTypes = null;
try {
System.out.println("URI: " + uri);
rvs_cns = vsd_service.getValueSetDefinitionEntitiesForTerm(matchText, algorithm, new URI(uri), csVersionList, null);
if (rvs_cns != null) {
CodedNodeSet cns = rvs_cns.getCodedNodeSet();
ResolvedConceptReferencesIterator itr = cns.resolve(sortOptions, propertyNames, propertyTypes);
if (itr != null && itr.numberRemaining() > 0) {
AbsoluteCodingSchemeVersionReferenceList ref_list = rvs_cns.getCodingSchemeVersionRefList();
if (ref_list.getAbsoluteCodingSchemeVersionReferenceCount() > 0) {
try {
ValueSetDefinition vsd = vsd_service.getValueSetDefinition(new URI(uri), null);
if (vsd == null) {
msg = "Unable to find any value set with name " + matchText + ".";
request.getSession().setAttribute("message", msg);
return "message";
}
String metadata = DataUtils.getValueSetDefinitionMetadata(vsd);
if (metadata != null) {
v.add(metadata);
}
} catch (Exception ex) {
ex.printStackTrace();
msg = "Unable to find any value set with name " + matchText + ".";
request.getSession().setAttribute("message", msg);
return "message";
}
}
}
}
} catch (Exception ex) {
//System.out.println("WARNING: getValueSetDefinitionEntitiesForTerm throws exception???");
msg = "getValueSetDefinitionEntitiesForTerm throws exception -- search by \"" + matchText + "\" failed. (VSD URI: " + uri + ")";
System.out.println(msg);
request.getSession().setAttribute("message", msg);
ex.printStackTrace();
return "message";
}
}
}
request.getSession().setAttribute("matched_vsds", v);
if (v.size() == 0) {
msg = "No match found.";
request.getSession().setAttribute("message", msg);
return "message";
} else if (v.size() == 1) {
request.getSession().setAttribute("vsd_uri", uri);
}
return "value_set";
} catch (Exception ex) {
//ex.printStackTrace();
System.out.println("vsd_service.getValueSetDefinitionEntitiesForTerm throws exceptions???");
}
msg = "Unexpected errors encountered; search by name failed.";
request.getSession().setAttribute("message", msg);
return "message";
}
return "value_set";
}
public static void create_vs_tree(HttpServletRequest request, HttpServletResponse response, int view, String dictionary, String version) {
request.getSession().removeAttribute("b");
request.getSession().removeAttribute("m");
response.setContentType("text/html");
PrintWriter out = null;
String checked_vocabularies = (String) request.getParameter("checked_vocabularies");
System.out.println("checked_vocabularies: " + checked_vocabularies);
String partial_checked_vocabularies = (String) request.getParameter("partial_checked_vocabularies");
System.out.println("partial_checked_vocabularies: " + partial_checked_vocabularies);
try {
out = response.getWriter();
} catch (Exception ex) {
ex.printStackTrace();
return;
}
String message = (String) request.getSession().getAttribute("message");
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
out.println("<html xmlns:c=\"http://java.sun.com/jsp/jstl/core\">");
out.println("<head>");
out.println(" <title>" + dictionary + " value set</title>");
//out.println(" <title>NCI Thesaurus</title>");
out.println(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">");
out.println("");
out.println("<style type=\"text/css\">");
out.println("/*margin and padding on body element");
out.println(" can introduce errors in determining");
out.println(" element position and are not recommended;");
out.println(" we turn them off as a foundation for YUI");
out.println(" CSS treatments. */");
out.println("body {");
out.println(" margin:0;");
out.println(" padding:0;");
out.println("}");
out.println("</style>");
out.println("");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/fonts/fonts-min.css\" />");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/treeview/assets/skins/sam/treeview.css\" />");
out.println("");
out.println("<script type=\"text/javascript\" src=\"http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js\"></script>");
out.println("<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/treeview-min.js\" ></script>");
out.println("");
out.println("");
out.println("<!-- Dependency -->");
out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js\"></script>");
out.println("");
out.println("<!-- Source file -->");
out.println("<!--");
out.println(" If you require only basic HTTP transaction support, use the");
out.println(" connection_core.js file.");
out.println("-->");
out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection_core-min.js\"></script>");
out.println("");
out.println("<!--");
out.println(" Use the full connection.js if you require the following features:");
out.println(" - Form serialization.");
out.println(" - File Upload using the iframe transport.");
out.println(" - Cross-domain(XDR) transactions.");
out.println("-->");
out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection-min.js\"></script>");
out.println("");
out.println("");
out.println("");
out.println("<!--begin custom header content for this example-->");
out.println("<!--Additional custom style rules for this example:-->");
out.println("<style type=\"text/css\">");
out.println("");
out.println("");
out.println(".ygtvcheck0 { background: url(/ncitbrowser/images/yui/treeview/check0.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }");
out.println(".ygtvcheck1 { background: url(/ncitbrowser/images/yui/treeview/check1.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }");
out.println(".ygtvcheck2 { background: url(/ncitbrowser/images/yui/treeview/check2.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }");
out.println("");
out.println("");
out.println(".ygtv-edit-TaskNode { width: 190px;}");
out.println(".ygtv-edit-TaskNode .ygtvcancel, .ygtv-edit-TextNode .ygtvok { border:none;}");
out.println(".ygtv-edit-TaskNode .ygtv-button-container { float: right;}");
out.println(".ygtv-edit-TaskNode .ygtv-input input{ width: 140px;}");
out.println(".whitebg {");
out.println(" background-color:white;");
out.println("}");
out.println("</style>");
out.println("");
out.println(" <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/styleSheet.css\" />");
out.println(" <link rel=\"shortcut icon\" href=\"/ncitbrowser/favicon.ico\" type=\"image/x-icon\" />");
out.println("");
out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/script.js\"></script>");
out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tasknode.js\"></script>");
println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/search.js\"></script>");
println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/dropdown.js\"></script>");
out.println("");
out.println(" <script type=\"text/javascript\">");
out.println("");
out.println(" function refresh() {");
out.println("");
out.println(" var selectValueSetSearchOptionObj = document.forms[\"valueSetSearchForm\"].selectValueSetSearchOption;");
out.println("");
out.println(" for (var i=0; i<selectValueSetSearchOptionObj.length; i++) {");
out.println(" if (selectValueSetSearchOptionObj[i].checked) {");
out.println(" selectValueSetSearchOption = selectValueSetSearchOptionObj[i].value;");
out.println(" }");
out.println(" }");
out.println("");
out.println("");
out.println(" window.location.href=\"/ncitbrowser/pages/value_set_source_view.jsf?refresh=1\"");
out.println(" + \"&nav_type=valuesets\" + \"&opt=\"+ selectValueSetSearchOption;");
out.println("");
out.println(" }");
out.println(" </script>");
out.println("");
out.println(" <script language=\"JavaScript\">");
out.println("");
out.println(" var tree;");
out.println(" var nodeIndex;");
out.println(" var nodes = [];");
out.println("");
out.println(" function load(url,target) {");
out.println(" if (target != '')");
out.println(" target.window.location.href = url;");
out.println(" else");
out.println(" window.location.href = url;");
out.println(" }");
out.println("");
out.println(" function init() {");
out.println(" //initTree();");
out.println(" }");
out.println("");
out.println(" //handler for expanding all nodes");
out.println(" YAHOO.util.Event.on(\"expand_all\", \"click\", function(e) {");
out.println(" //expandEntireTree();");
out.println("");
out.println(" tree.expandAll();");
out.println(" //YAHOO.util.Event.preventDefault(e);");
out.println(" });");
out.println("");
out.println(" //handler for collapsing all nodes");
out.println(" YAHOO.util.Event.on(\"collapse_all\", \"click\", function(e) {");
out.println(" tree.collapseAll();");
out.println(" //YAHOO.util.Event.preventDefault(e);");
out.println(" });");
out.println("");
out.println(" //handler for checking all nodes");
out.println(" YAHOO.util.Event.on(\"check_all\", \"click\", function(e) {");
out.println(" check_all();");
out.println(" //YAHOO.util.Event.preventDefault(e);");
out.println(" });");
out.println("");
out.println(" //handler for unchecking all nodes");
out.println(" YAHOO.util.Event.on(\"uncheck_all\", \"click\", function(e) {");
out.println(" uncheck_all();");
out.println(" //YAHOO.util.Event.preventDefault(e);");
out.println(" });");
out.println("");
out.println("");
out.println("");
out.println(" YAHOO.util.Event.on(\"getchecked\", \"click\", function(e) {");
out.println(" //alert(\"Checked nodes: \" + YAHOO.lang.dump(getCheckedNodes()), \"info\", \"example\");");
out.println(" //YAHOO.util.Event.preventDefault(e);");
out.println("");
out.println(" });");
out.println("");
out.println("");
out.println(" function addTreeNode(rootNode, nodeInfo) {");
out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";");
out.println("");
out.println(" if (nodeInfo.ontology_node_id.indexOf(\"TVS_\") >= 0) {");
out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };");
out.println(" } else {");
out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };");
out.println(" }");
out.println("");
out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, false);");
out.println(" if (nodeInfo.ontology_node_child_count > 0) {");
out.println(" newNode.setDynamicLoad(loadNodeData);");
out.println(" }");
out.println(" }");
out.println("");
out.println(" function buildTree(ontology_node_id, ontology_display_name) {");
out.println(" var handleBuildTreeSuccess = function(o) {");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" if ( typeof(respObj) != \"undefined\") {");
out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {");
out.println(" var root = tree.getRoot();");
out.println(" if (respObj.root_nodes.length == 0) {");
out.println(" //showEmptyRoot();");
out.println(" }");
out.println(" else {");
out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {");
out.println(" var nodeInfo = respObj.root_nodes[i];");
out.println(" var expand = false;");
out.println(" //addTreeNode(root, nodeInfo, expand);");
out.println("");
out.println(" addTreeNode(root, nodeInfo);");
out.println(" }");
out.println(" }");
out.println("");
out.println(" tree.draw();");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
out.println(" var handleBuildTreeFailure = function(o) {");
out.println(" alert('responseFailure: ' + o.statusText);");
out.println(" }");
out.println("");
out.println(" var buildTreeCallback =");
out.println(" {");
out.println(" success:handleBuildTreeSuccess,");
out.println(" failure:handleBuildTreeFailure");
out.println(" };");
out.println("");
out.println(" if (ontology_display_name!='') {");
out.println(" var ontology_source = null;");
out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=build_src_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);");
out.println(" }");
out.println(" }");
out.println("");
out.println(" function resetTree(ontology_node_id, ontology_display_name) {");
out.println("");
out.println(" var handleResetTreeSuccess = function(o) {");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" if ( typeof(respObj) != \"undefined\") {");
out.println(" if ( typeof(respObj.root_node) != \"undefined\") {");
out.println(" var root = tree.getRoot();");
out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.root_node.ontology_node_id + \"');\";");
out.println(" var rootNodeData = { label:respObj.root_node.ontology_node_name, id:respObj.root_node.ontology_node_id, href:nodeDetails };");
out.println(" var expand = false;");
out.println(" if (respObj.root_node.ontology_node_child_count > 0) {");
out.println(" expand = true;");
out.println(" }");
out.println(" var ontRoot = new YAHOO.widget.TaskNode(rootNodeData, root, expand);");
out.println("");
out.println(" if ( typeof(respObj.child_nodes) != \"undefined\") {");
out.println(" for (var i=0; i < respObj.child_nodes.length; i++) {");
out.println(" var nodeInfo = respObj.child_nodes[i];");
out.println(" addTreeNode(ontRoot, nodeInfo);");
out.println(" }");
out.println(" }");
out.println(" tree.draw();");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
out.println(" var handleResetTreeFailure = function(o) {");
out.println(" alert('responseFailure: ' + o.statusText);");
out.println(" }");
out.println("");
out.println(" var resetTreeCallback =");
out.println(" {");
out.println(" success:handleResetTreeSuccess,");
out.println(" failure:handleResetTreeFailure");
out.println(" };");
out.println(" if (ontology_node_id!= '') {");
out.println(" var ontology_source = null;");
out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=reset_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name + '&version='+ ontology_version +'&ontology_source='+ontology_source,resetTreeCallback);");
out.println(" }");
out.println(" }");
out.println("");
out.println(" function onClickTreeNode(ontology_node_id) {");
out.println(" //alert(\"onClickTreeNode \" + ontology_node_id);");
out.println(" window.location = '/ncitbrowser/pages/value_set_treenode_redirect.jsf?ontology_node_id=' + ontology_node_id;");
out.println(" }");
out.println("");
out.println("");
out.println(" function onClickViewEntireOntology(ontology_display_name) {");
out.println(" var ontology_display_name = document.pg_form.ontology_display_name.value;");
out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");");
out.println(" tree.draw();");
out.println(" }");
out.println("");
out.println(" function initTree() {");
out.println("");
out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");");
//out.println(" pre_check();");
out.println(" tree.setNodesProperty('propagateHighlightUp',true);");
out.println(" tree.setNodesProperty('propagateHighlightDown',true);");
out.println(" tree.subscribe('keydown',tree._onKeyDownEvent);");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" tree.subscribe(\"expand\", function(node) {");
out.println("");
out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 39 });");
out.println("");
out.println(" });");
out.println("");
out.println("");
out.println("");
out.println(" tree.subscribe(\"collapse\", function(node) {");
out.println(" //alert(\"Collapsing \" + node.label );");
out.println("");
out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 109 });");
out.println(" });");
out.println("");
out.println(" // By default, trees with TextNodes will fire an event for when the label is clicked:");
out.println(" tree.subscribe(\"checkClick\", function(node) {");
out.println(" //alert(node.data.myNodeId + \" label was checked\");");
out.println(" });");
out.println("");
out.println("");
println(out, " var root = tree.getRoot();");
HashMap value_set_tree_hmap = DataUtils.getCodingSchemeValueSetTree();
TreeItem root = (TreeItem) value_set_tree_hmap.get("<Root>");
new ValueSetUtils().printTree(out, root, Constants.TERMINOLOGY_VIEW, dictionary);
//new ValueSetUtils().printTree(out, root, Constants.TERMINOLOGY_VIEW);
String contextPath = request.getContextPath();
String view_str = new Integer(view).toString();
//String option = (String) request.getSession().getAttribute("selectValueSetSearchOption");
//String algorithm = (String) request.getSession().getAttribute("valueset_search_algorithm");
String option = (String) request.getParameter("selectValueSetSearchOption");
String algorithm = (String) request.getParameter("valueset_search_algorithm");
String option_code = "";
String option_name = "";
if (DataUtils.isNull(option)) {
option_code = "checked";
} else {
if (option.compareToIgnoreCase("Code") == 0) {
option_code = "checked";
}
if (option.compareToIgnoreCase("Name") == 0) {
option_name = "checked";
}
}
String algorithm_exactMatch = "";
String algorithm_startsWith = "";
String algorithm_contains = "";
if (DataUtils.isNull(algorithm)) {
algorithm_exactMatch = "checked";
} else {
if (algorithm.compareToIgnoreCase("exactMatch") == 0) {
algorithm_exactMatch = "checked";
}
if (algorithm.compareToIgnoreCase("startsWith") == 0) {
algorithm_startsWith = "checked";
}
if (algorithm.compareToIgnoreCase("contains") == 0) {
algorithm_contains = "checked";
}
}
out.println("");
if (message == null) {
out.println(" tree.collapseAll();");
}
out.println(" initializeNodeCheckState();");
out.println(" tree.draw();");
out.println(" }");
out.println("");
out.println("");
out.println(" function onCheckClick(node) {");
out.println(" YAHOO.log(node.label + \" check was clicked, new state: \" + node.checkState, \"info\", \"example\");");
out.println(" }");
out.println("");
out.println(" function check_all() {");
out.println(" var topNodes = tree.getRoot().children;");
out.println(" for(var i=0; i<topNodes.length; ++i) {");
out.println(" topNodes[i].check();");
out.println(" }");
out.println(" }");
out.println("");
out.println(" function uncheck_all() {");
out.println(" var topNodes = tree.getRoot().children;");
out.println(" for(var i=0; i<topNodes.length; ++i) {");
out.println(" topNodes[i].uncheck();");
out.println(" }");
out.println(" }");
out.println("");
out.println("");
out.println("");
out.println(" function expand_all() {");
out.println(" //alert(\"expand_all\");");
out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;");
out.println(" onClickViewEntireOntology(ontology_display_name);");
out.println(" }");
out.println("");
out.println(" function pre_check() {");
out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;");
//out.println(" alert(ontology_display_name);");
out.println(" var topNodes = tree.getRoot().children;");
out.println(" for(var i=0; i<topNodes.length; ++i) {");
out.println(" if (topNodes[i].label == ontology_display_name) {");
out.println(" topNodes[i].check();");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
// 0=unchecked, 1=some children checked, 2=all children checked
/*
function getCheckedNodes(nodes) {
nodes = nodes || tree.getRoot().children;
checkedNodes = [];
for(var i=0, l=nodes.length; i<l; i=i+1) {
var n = nodes[i];
//if (n.checkState > 0) { // if we were interested in the nodes that have some but not all children checked
if (n.checkState == 2) {
checkedNodes.push(n.label); // just using label for simplicity
}
if (n.hasChildren()) {
checkedNodes = checkedNodes.concat(getCheckedNodes(n.children));
}
}
//var checked_vocabularies = document.forms["valueSetSearchForm"].checked_vocabularies;
//checked_vocabularies.value = checkedNodes;
return checkedNodes;
}
*/
out.println(" function getCheckedVocabularies(nodes) {");
out.println(" getCheckedNodes(nodes);");
out.println(" getPartialCheckedNodes(nodes);");
out.println(" }");
writeInitialize(out);
initializeNodeCheckState(out);
out.println(" // Gets the labels of all of the fully checked nodes");
out.println(" // Could be updated to only return checked leaf nodes by evaluating");
out.println(" // the children collection first.");
out.println(" function getCheckedNodes(nodes) {");
out.println(" nodes = nodes || tree.getRoot().children;");
out.println(" var checkedNodes = [];");
out.println(" for(var i=0, l=nodes.length; i<l; i=i+1) {");
out.println(" var n = nodes[i];");
out.println(" if (n.checkState == 2) {");
out.println(" checkedNodes.push(n.label); // just using label for simplicity");
out.println(" }");
out.println(" if (n.hasChildren()) {");
out.println(" checkedNodes = checkedNodes.concat(getCheckedNodes(n.children));");
out.println(" }");
out.println(" }");
//out.println(" checkedNodes = checkedNodes.concat(\",\");");
out.println(" var checked_vocabularies = document.forms[\"valueSetSearchForm\"].checked_vocabularies;");
out.println(" checked_vocabularies.value = checkedNodes;");
out.println(" return checkedNodes;");
out.println(" }");
out.println(" function getPartialCheckedNodes(nodes) {");
out.println(" nodes = nodes || tree.getRoot().children;");
out.println(" var checkedNodes = [];");
out.println(" for(var i=0, l=nodes.length; i<l; i=i+1) {");
out.println(" var n = nodes[i];");
out.println(" if (n.checkState == 1) {");
out.println(" checkedNodes.push(n.label); // just using label for simplicity");
out.println(" }");
out.println(" if (n.hasChildren()) {");
out.println(" checkedNodes = checkedNodes.concat(getPartialCheckedNodes(n.children));");
out.println(" }");
out.println(" }");
//out.println(" checkedNodes = checkedNodes.concat(\",\");");
out.println(" var partial_checked_vocabularies = document.forms[\"valueSetSearchForm\"].partial_checked_vocabularies;");
out.println(" partial_checked_vocabularies.value = checkedNodes;");
out.println(" return checkedNodes;");
out.println(" }");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" function loadNodeData(node, fnLoadComplete) {");
out.println(" var id = node.data.id;");
out.println("");
out.println(" var responseSuccess = function(o)");
out.println(" {");
out.println(" var path;");
out.println(" var dirs;");
out.println(" var files;");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" var fileNum = 0;");
out.println(" var categoryNum = 0;");
out.println(" if ( typeof(respObj.nodes) != \"undefined\") {");
out.println(" for (var i=0; i < respObj.nodes.length; i++) {");
out.println(" var name = respObj.nodes[i].ontology_node_name;");
out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";");
out.println(" var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };");
out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, node, false);");
out.println(" if (respObj.nodes[i].ontology_node_child_count > 0) {");
out.println(" newNode.setDynamicLoad(loadNodeData);");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" tree.draw();");
out.println(" fnLoadComplete();");
out.println(" }");
out.println("");
out.println(" var responseFailure = function(o){");
out.println(" alert('responseFailure: ' + o.statusText);");
out.println(" }");
out.println("");
out.println(" var callback =");
out.println(" {");
out.println(" success:responseSuccess,");
out.println(" failure:responseFailure");
out.println(" };");
out.println("");
out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;");
out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
out.println(" var cObj = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_src_vs_tree&ontology_node_id=' +id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version,callback);");
out.println(" }");
out.println("");
out.println("");
out.println(" function searchTree(ontology_node_id, ontology_display_name) {");
out.println("");
out.println(" var handleBuildTreeSuccess = function(o) {");
out.println("");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" if ( typeof(respObj) != \"undefined\") {");
out.println("");
out.println(" if ( typeof(respObj.dummy_root_nodes) != \"undefined\") {");
out.println(" showNodeNotFound(ontology_node_id);");
out.println(" }");
out.println("");
out.println(" else if ( typeof(respObj.root_nodes) != \"undefined\") {");
out.println(" var root = tree.getRoot();");
out.println(" if (respObj.root_nodes.length == 0) {");
out.println(" //showEmptyRoot();");
out.println(" }");
out.println(" else {");
out.println(" showPartialHierarchy();");
out.println(" showConstructingTreeStatus();");
out.println("");
out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {");
out.println(" var nodeInfo = respObj.root_nodes[i];");
out.println(" //var expand = false;");
out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
out.println(" var handleBuildTreeFailure = function(o) {");
out.println(" alert('responseFailure: ' + o.statusText);");
out.println(" }");
out.println("");
out.println(" var buildTreeCallback =");
out.println(" {");
out.println(" success:handleBuildTreeSuccess,");
out.println(" failure:handleBuildTreeFailure");
out.println(" };");
out.println("");
out.println(" if (ontology_display_name!='') {");
out.println(" var ontology_source = null;//document.pg_form.ontology_source.value;");
out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=search_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);");
out.println("");
out.println(" }");
out.println(" }");
out.println("");
out.println("");
out.println("");
out.println(" function expandEntireTree() {");
out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");");
out.println(" //tree.draw();");
out.println("");
out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;");
out.println(" var ontology_node_id = document.forms[\"pg_form\"].ontology_node_id.value;");
out.println("");
out.println(" var handleBuildTreeSuccess = function(o) {");
out.println("");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" if ( typeof(respObj) != \"undefined\") {");
out.println("");
out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {");
out.println("");
out.println(" //alert(respObj.root_nodes.length);");
out.println("");
out.println(" var root = tree.getRoot();");
out.println(" if (respObj.root_nodes.length == 0) {");
out.println(" //showEmptyRoot();");
out.println(" } else {");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {");
out.println(" var nodeInfo = respObj.root_nodes[i];");
out.println(" //alert(\"calling addTreeBranch \");");
out.println("");
out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
out.println(" var handleBuildTreeFailure = function(o) {");
out.println(" alert('responseFailure: ' + o.statusText);");
out.println(" }");
out.println("");
out.println(" var buildTreeCallback =");
out.println(" {");
out.println(" success:handleBuildTreeSuccess,");
out.println(" failure:handleBuildTreeFailure");
out.println(" };");
out.println("");
out.println(" if (ontology_display_name!='') {");
out.println(" var ontology_source = null;");
out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_entire_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);");
out.println("");
out.println(" }");
out.println(" }");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" function addTreeBranch(ontology_node_id, rootNode, nodeInfo) {");
out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";");
out.println("");
out.println(" var newNodeData;");
out.println(" if (ontology_node_id.indexOf(\"TVS_\") >= 0) {");
out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };");
out.println(" } else {");
out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };");
out.println(" }");
out.println("");
out.println(" var expand = false;");
out.println(" var childNodes = nodeInfo.children_nodes;");
out.println("");
out.println(" if (childNodes.length > 0) {");
out.println(" expand = true;");
out.println(" }");
out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, expand);");
out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {");
out.println(" newNode.labelStyle = \"ygtvlabel_highlight\";");
out.println(" }");
out.println("");
out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {");
out.println(" newNode.isLeaf = true;");
out.println(" if (nodeInfo.ontology_node_child_count > 0) {");
out.println(" newNode.isLeaf = false;");
out.println(" newNode.setDynamicLoad(loadNodeData);");
out.println(" } else {");
out.println(" tree.draw();");
out.println(" }");
out.println("");
out.println(" } else {");
out.println(" if (nodeInfo.ontology_node_id != ontology_node_id) {");
out.println(" if (nodeInfo.ontology_node_child_count == 0 && nodeInfo.ontology_node_id != ontology_node_id) {");
out.println(" newNode.isLeaf = true;");
out.println(" } else if (childNodes.length == 0) {");
out.println(" newNode.setDynamicLoad(loadNodeData);");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
out.println(" tree.draw();");
out.println(" for (var i=0; i < childNodes.length; i++) {");
out.println(" var childnodeInfo = childNodes[i];");
out.println(" addTreeBranch(ontology_node_id, newNode, childnodeInfo);");
out.println(" }");
out.println(" }");
out.println(" YAHOO.util.Event.addListener(window, \"load\", init);");
out.println("");
out.println(" YAHOO.util.Event.onDOMReady(initTree);");
out.println("");
out.println("");
out.println(" </script>");
out.println("");
out.println("</head>");
out.println("");
out.println("");
out.println("");
out.println("");
out.println("");
//out.println("<body>");
out.println("<body onLoad=\"document.forms.valueSetSearchForm.matchText.focus();\">");
//out.println("<body onLoad=\"initialize();\">");
out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/wz_tooltip.js\"></script>");
out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_centerwindow.js\"></script>");
out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_followscroll.js\"></script>");
out.println("");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" <!-- Begin Skip Top Navigation -->");
out.println(" <a href=\"#evs-content\" class=\"hideLink\" accesskey=\"1\" title=\"Skip repetitive navigation links\">skip navigation links</A>");
out.println(" <!-- End Skip Top Navigation -->");
out.println("");
out.println("<!-- nci banner -->");
out.println("<div class=\"ncibanner\">");
out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">");
out.println(" <img src=\"/ncitbrowser/images/logotype.gif\"");
out.println(" width=\"440\" height=\"39\" border=\"0\"");
out.println(" alt=\"National Cancer Institute\"/>");
out.println(" </a>");
out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">");
out.println(" <img src=\"/ncitbrowser/images/spacer.gif\"");
out.println(" width=\"48\" height=\"39\" border=\"0\"");
out.println(" alt=\"National Cancer Institute\" class=\"print-header\"/>");
out.println(" </a>");
out.println(" <a href=\"http://www.nih.gov\" target=\"_blank\" >");
out.println(" <img src=\"/ncitbrowser/images/tagline_nologo.gif\"");
out.println(" width=\"173\" height=\"39\" border=\"0\"");
out.println(" alt=\"U.S. National Institutes of Health\"/>");
out.println(" </a>");
out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">");
out.println(" <img src=\"/ncitbrowser/images/cancer-gov.gif\"");
out.println(" width=\"99\" height=\"39\" border=\"0\"");
out.println(" alt=\"www.cancer.gov\"/>");
out.println(" </a>");
out.println("</div>");
out.println("<!-- end nci banner -->");
out.println("");
out.println(" <div class=\"center-page\">");
out.println(" <!-- EVS Logo -->");
out.println("<div>");
// to be modified
out.println(" <img src=\"/ncitbrowser/images/evs-logo-swapped.gif\" alt=\"EVS Logo\"");
out.println(" width=\"745\" height=\"26\" border=\"0\"");
out.println(" usemap=\"#external-evs\" />");
out.println(" <map id=\"external-evs\" name=\"external-evs\">");
out.println(" <area shape=\"rect\" coords=\"0,0,140,26\"");
out.println(" href=\"/ncitbrowser/start.jsf\" target=\"_self\"");
out.println(" alt=\"NCI Term Browser\" />");
out.println(" <area shape=\"rect\" coords=\"520,0,745,26\"");
out.println(" href=\"http://evs.nci.nih.gov/\" target=\"_blank\"");
out.println(" alt=\"Enterprise Vocabulary Services\" />");
out.println(" </map>");
out.println("</div>");
out.println("");
out.println("");
out.println("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">");
out.println(" <tr>");
out.println(" <td width=\"5\"></td>");
//to be modified
out.println(" <td><a href=\"/ncitbrowser/pages/multiple_search.jsf?nav_type=terminologies\">");
out.println(" <img name=\"tab_terms\" src=\"/ncitbrowser/images/tab_terms_clicked.gif\"");
out.println(" border=\"0\" alt=\"Terminologies\" title=\"Terminologies\" /></a></td>");
out.println(" <td><a href=\"/ncitbrowser/ajax?action=create_src_vs_tree\">");
out.println(" <img name=\"tab_valuesets\" src=\"/ncitbrowser/images/tab_valuesets.gif\"");
out.println(" border=\"0\" alt=\"Value Sets\" title=\"ValueSets\" /></a></td>");
out.println(" <td><a href=\"/ncitbrowser/pages/mapping_search.jsf?nav_type=mappings\">");
out.println(" <img name=\"tab_map\" src=\"/ncitbrowser/images/tab_map.gif\"");
out.println(" border=\"0\" alt=\"Mappings\" title=\"Mappings\" /></a></td>");
out.println(" </tr>");
out.println("</table>");
out.println("");
out.println("<div class=\"mainbox-top\"><img src=\"/ncitbrowser/images/mainbox-top.gif\" width=\"745\" height=\"5\" alt=\"\"/></div>");
out.println("<!-- end EVS Logo -->");
out.println(" <!-- Main box -->");
out.println(" <div id=\"main-area\">");
out.println("");
out.println(" <!-- Thesaurus, banner search area -->");
out.println(" <div class=\"bannerarea\">");
/*
out.println(" <a href=\"/ncitbrowser/start.jsf\" style=\"text-decoration: none;\">");
out.println(" <div class=\"vocabularynamebanner_tb\">");
out.println(" <span class=\"vocabularynamelong_tb\">" + JSPUtils.getApplicationVersionDisplay() + "</span>");
out.println(" </div>");
out.println(" </a>");
*/
JSPUtils.JSPHeaderInfoMore info = new JSPUtils.JSPHeaderInfoMore(request);
String scheme = info.dictionary;
String term_browser_version = info.term_browser_version;
String display_name = info.display_name;
String basePath = request.getContextPath();
/*
<a href="/ncitbrowser/pages/home.jsf?version=12.02d" style="text-decoration: none;">
<div class="vocabularynamebanner_ncit">
<span class="vocabularynamelong_ncit">Version: 12.02d (Release date: 2012-02-27-08:00)</span>
</div>
</a>
*/
String release_date = DataUtils.getVersionReleaseDate(scheme, version);
if (dictionary != null && dictionary.compareTo("NCI Thesaurus") == 0) {
out.println("<a href=\"/ncitbrowser/pages/home.jsf?version=" + version + "\" style=\"text-decoration: none;\">");
out.println(" <div class=\"vocabularynamebanner_ncit\">");
out.println(" <span class=\"vocabularynamelong_ncit\">Version: " + version + " (Release date: " + release_date + ")</span>");
out.println(" </div>");
out.println("</a>");
/*
out.write("\r\n");
out.write(" <div class=\"banner\"><a href=\"");
out.print(basePath);
out.write("\"><img src=\"");
out.print(basePath);
out.write("/images/thesaurus_browser_logo.jpg\" width=\"383\" height=\"117\" alt=\"Thesaurus Browser Logo\" border=\"0\"/></a></div>\r\n");
*/
} else {
out.write("\r\n");
out.write("\r\n");
out.write(" ");
if (version == null) {
out.write("\r\n");
out.write(" <a class=\"vocabularynamebanner\" href=\"");
out.print(request.getContextPath());
out.write("/pages/vocabulary.jsf?dictionary=");
out.print(HTTPUtils.cleanXSS(dictionary));
out.write("\">\r\n");
out.write(" ");
} else {
out.write("\r\n");
out.write(" <a class=\"vocabularynamebanner\" href=\"");
out.print(request.getContextPath());
out.write("/pages/vocabulary.jsf?dictionary=");
out.print(HTTPUtils.cleanXSS(dictionary));
out.write("&version=");
out.print(HTTPUtils.cleanXSS(version));
out.write("\">\r\n");
out.write(" ");
}
out.write("\r\n");
out.write(" <div class=\"vocabularynamebanner\">\r\n");
out.write(" <div class=\"vocabularynameshort\" STYLE=\"font-size: ");
out.print(HTTPUtils.maxFontSize(display_name));
out.write("px; font-family : Arial\">\r\n");
out.write(" ");
out.print(HTTPUtils.cleanXSS(display_name));
out.write("\r\n");
out.write(" </div>\r\n");
out.write(" \r\n");
boolean display_release_date = true;
if (release_date == null || release_date.compareTo("") == 0) {
display_release_date = false;
}
if (display_release_date) {
out.write("\r\n");
out.write(" <div class=\"vocabularynamelong\">Version: ");
out.print(HTTPUtils.cleanXSS(term_browser_version));
out.write(" (Release date: ");
out.print(release_date);
out.write(")</div>\r\n");
} else {
out.write("\r\n");
out.write(" <div class=\"vocabularynamelong\">Version: ");
out.print(HTTPUtils.cleanXSS(term_browser_version));
out.write("</div>\r\n");
}
out.write(" \r\n");
out.write(" \r\n");
out.write(" </div>\r\n");
out.write(" </a>\r\n");
}
out.println(" <div class=\"search-globalnav\">");
out.println(" <!-- Search box -->");
out.println(" <div class=\"searchbox-top\"><img src=\"/ncitbrowser/images/searchbox-top.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Top\" /></div>");
out.println(" <div class=\"searchbox\">");
out.println("");
out.println("");
out.println("<form id=\"valueSetSearchForm\" name=\"valueSetSearchForm\" method=\"post\" action=\"" + contextPath + "/ajax?action=search_value_set\" class=\"search-form-main-area\" enctype=\"application/x-www-form-urlencoded\">");
out.println("<input type=\"hidden\" name=\"valueSetSearchForm\" value=\"valueSetSearchForm\" />");
out.println("<input type=\"hidden\" name=\"view\" value=\"" + view_str + "\" />");
String matchText = (String) request.getSession().getAttribute("matchText");
if (DataUtils.isNull(matchText)) {
matchText = "";
}
out.println("");
out.println("");
out.println("");
out.println(" <input type=\"hidden\" id=\"checked_vocabularies\" name=\"checked_vocabularies\" value=\"\" />");
out.println(" <input type=\"hidden\" id=\"partial_checked_vocabularies\" name=\"partial_checked_vocabularies\" value=\"\" />");
out.println("");
out.println("");
out.println("");
out.println("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 2px\" >");
out.println(" <tr valign=\"top\" align=\"left\">");
out.println(" <td align=\"left\" class=\"textbody\">");
out.println("");
out.println(" <input CLASS=\"searchbox-input-2\"");
out.println(" name=\"matchText\"");
out.println(" value=\"" + matchText + "\"");
out.println(" onFocus=\"active = true\"");
out.println(" onBlur=\"active = false\"");
out.println(" onkeypress=\"return submitEnter('valueSetSearchForm:valueset_search',event)\"");
out.println(" tabindex=\"1\"/>");
out.println("");
out.println("");
out.println(" <input id=\"valueSetSearchForm:valueset_search\" type=\"image\" src=\"/ncitbrowser/images/search.gif\" name=\"valueSetSearchForm:valueset_search\" alt=\"Search Value Sets\" onclick=\"javascript:getCheckedVocabularies();\" tabindex=\"2\" class=\"searchbox-btn\" /><a href=\"/ncitbrowser/pages/help.jsf#searchhelp\" tabindex=\"3\"><img src=\"/ncitbrowser/images/search-help.gif\" alt=\"Search Help\" style=\"border-width:0;\" class=\"searchbox-btn\" /></a>");
out.println("");
out.println("");
out.println(" </td>");
out.println(" </tr>");
out.println("");
out.println(" <tr valign=\"top\" align=\"left\">");
out.println(" <td>");
out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 0px\">");
out.println("");
out.println(" <tr valign=\"top\" align=\"left\">");
out.println(" <td align=\"left\" class=\"textbody\">");
out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"exactMatch\" alt=\"Exact Match\" " + algorithm_exactMatch + " tabindex=\"3\">Exact Match ");
out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"startsWith\" alt=\"Begins With\" " + algorithm_startsWith + " tabindex=\"3\">Begins With ");
out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"contains\" alt=\"Contains\" " + algorithm_contains + " tabindex=\"3\">Contains");
out.println(" </td>");
out.println(" </tr>");
out.println("");
out.println(" <tr align=\"left\">");
out.println(" <td height=\"1px\" bgcolor=\"#2F2F5F\" align=\"left\"></td>");
out.println(" </tr>");
out.println(" <tr valign=\"top\" align=\"left\">");
out.println(" <td align=\"left\" class=\"textbody\">");
out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Code\" " + option_code + " alt=\"Code\" tabindex=\"1\" >Code ");
out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Name\" " + option_name + " alt=\"Name\" tabindex=\"1\" >Name");
out.println(" </td>");
out.println(" </tr>");
out.println(" </table>");
out.println(" </td>");
out.println(" </tr>");
out.println("</table>");
out.println(" <input type=\"hidden\" name=\"referer\" id=\"referer\" value=\"http%3A%2F%2Flocalhost%3A8080%2Fncitbrowser%2Fpages%2Fresolved_value_set_search_results.jsf\">");
out.println(" <input type=\"hidden\" id=\"nav_type\" name=\"nav_type\" value=\"valuesets\" />");
out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />");
out.println(" <input type=\"hidden\" id=\"ontology_display_name\" name=\"ontology_display_name\" value=\"" + dictionary + "\" />");
out.println(" <input type=\"hidden\" id=\"schema\" name=\"schema\" value=\"" + dictionary + "\" />");
out.println(" <input type=\"hidden\" id=\"ontology_version\" name=\"ontology_version\" value=\"" + version + "\" />");
out.println("");
out.println("<input type=\"hidden\" name=\"javax.faces.ViewState\" id=\"javax.faces.ViewState\" value=\"j_id22:j_id23\" />");
out.println("</form>");
addHiddenForm(out, checked_vocabularies, partial_checked_vocabularies);
out.println(" </div> <!-- searchbox -->");
out.println("");
out.println(" <div class=\"searchbox-bottom\"><img src=\"/ncitbrowser/images/searchbox-bottom.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Bottom\" /></div>");
out.println(" <!-- end Search box -->");
out.println(" <!-- Global Navigation -->");
out.println("");
/*
out.println("<table class=\"global-nav\" border=\"0\" width=\"100%\" height=\"37px\" cellpadding=\"0\" cellspacing=\"0\">");
out.println(" <tr>");
out.println(" <td align=\"left\" valign=\"bottom\">");
out.println(" <a href=\"#\" onclick=\"javascript:window.open('/ncitbrowser/pages/source_help_info-termbrowser.jsf',");
out.println(" '_blank','top=100, left=100, height=740, width=780, status=no, menubar=no, resizable=yes, scrollbars=yes, toolbar=no, location=no, directories=no');\" tabindex=\"13\">");
out.println(" Sources</a>");
out.println("");
out.println(" \r\n");
out.println(" ");
out.print( VisitedConceptUtils.getDisplayLink(request, true) );
out.println(" \r\n");
out.println(" </td>");
out.println(" <td align=\"right\" valign=\"bottom\">");
out.println(" <a href=\"");
out.print( request.getContextPath() );
out.println("/pages/help.jsf\" tabindex=\"16\">Help</a>\r\n");
out.println(" </td>\r\n");
out.println(" <td width=\"7\"></td>\r\n");
out.println(" </tr>\r\n");
out.println("</table>");
*/
boolean hasValueSet = ValueSetHierarchy.hasValueSet(scheme);
boolean hasMapping = DataUtils.hasMapping(scheme);
boolean tree_access_allowed = true;
if (DataUtils._vocabulariesWithoutTreeAccessHashSet.contains(scheme)) {
tree_access_allowed = false;
}
boolean vocabulary_isMapping = DataUtils.isMapping(scheme, null);
- out.write(" <table class=\"global-nav\" border=\"0\" width=\"100%\" height=\"37px\" cellpadding=\"0\" cellspacing=\"0\">\r\n");
+ out.write(" <table class=\"global-nav\" border=\"0\" width=\"100%\" height=\"30px\" cellpadding=\"0\" cellspacing=\"0\">\r\n");
out.write(" <tr>\r\n");
out.write(" <td valign=\"bottom\">\r\n");
out.write(" ");
Boolean[] isPipeDisplayed = new Boolean[] { Boolean.FALSE };
out.write("\r\n");
out.write(" ");
if (vocabulary_isMapping) {
out.write("\r\n");
out.write(" ");
out.print( JSPUtils.getPipeSeparator(isPipeDisplayed) );
out.write("\r\n");
out.write(" <a href=\"");
out.print(request.getContextPath() );
out.write("/pages/mapping.jsf?dictionary=");
out.print(HTTPUtils.cleanXSS(scheme));
out.write("&version=");
out.print(version);
out.write("\">\r\n");
out.write(" Mapping\r\n");
out.write(" </a>\r\n");
out.write(" ");
} else if (tree_access_allowed) {
out.write("\r\n");
out.write(" ");
out.print( JSPUtils.getPipeSeparator(isPipeDisplayed) );
out.write("\r\n");
out.write(" <a href=\"#\" onclick=\"javascript:window.open('");
out.print(request.getContextPath());
out.write("/pages/hierarchy.jsf?dictionary=");
out.print(HTTPUtils.cleanXSS(scheme));
out.write("&version=");
out.print(HTTPUtils.cleanXSS(version));
out.write("', '_blank','top=100, left=100, height=740, width=680, status=no, menubar=no, resizable=yes, scrollbars=yes, toolbar=no, location=no, directories=no');\" tabindex=\"12\">\r\n");
out.write(" Hierarchy </a>\r\n");
out.write(" ");
}
out.write(" \r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write(" ");
if (hasValueSet) {
out.write("\r\n");
out.write(" ");
out.print( JSPUtils.getPipeSeparator(isPipeDisplayed) );
out.write("\r\n");
out.write(" <!--\r\n");
out.write(" <a href=\"");
out.print( request.getContextPath() );
out.write("/pages/value_set_hierarchy.jsf?dictionary=");
out.print(HTTPUtils.cleanXSS(scheme));
out.write("&version=");
out.print(HTTPUtils.cleanXSS(version));
out.write("\" tabindex=\"15\">Value Sets</a>\r\n");
out.write(" -->\r\n");
out.write(" <a href=\"");
out.print( request.getContextPath() );
out.write("/ajax?action=create_cs_vs_tree&dictionary=");
out.print(HTTPUtils.cleanXSS(scheme));
out.write("&version=");
out.print(HTTPUtils.cleanXSS(version));
out.write("\" tabindex=\"15\">Value Sets</a>\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" ");
}
out.write("\r\n");
out.write(" \r\n");
out.write(" ");
if (hasMapping) {
out.write("\r\n");
out.write(" ");
out.print( JSPUtils.getPipeSeparator(isPipeDisplayed) );
out.write("\r\n");
out.write(" <a href=\"");
out.print( request.getContextPath() );
out.write("/pages/cs_mappings.jsf?dictionary=");
out.print(HTTPUtils.cleanXSS(scheme));
out.write("&version=");
out.print(HTTPUtils.cleanXSS(version));
out.write("\" tabindex=\"15\">Maps</a> \r\n");
out.write(" ");
}
String cart_size = (String) request.getSession().getAttribute("cart_size");
if (!DataUtils.isNull(cart_size)) {
out.write("|");
out.write(" <a href=\"");
out.print(request.getContextPath());
out.write("/pages/cart.jsf\" tabindex=\"16\">Cart</a>\r\n");
}
out.write(" ");
out.print( VisitedConceptUtils.getDisplayLink(request, isPipeDisplayed) );
out.write("\r\n");
out.write(" </td>\r\n");
out.write(" <td align=\"right\" valign=\"bottom\">\r\n");
out.write(" <a href=\"");
out.print(request.getContextPath());
out.write("/pages/help.jsf\" tabindex=\"16\">Help</a>\r\n");
out.write(" </td>\r\n");
out.write(" <td width=\"7\" valign=\"bottom\"></td>\r\n");
out.write(" </tr>\r\n");
out.write(" </table>\r\n");
out.println(" <!-- end Global Navigation -->");
out.println("");
out.println(" </div> <!-- search-globalnav -->");
out.println(" </div> <!-- bannerarea -->");
out.println("");
out.println(" <!-- end Thesaurus, banner search area -->");
out.println(" <!-- Quick links bar -->");
out.println("");
out.println("<div class=\"bluebar\">");
out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
out.println(" <tr>");
out.println(" <td><div class=\"quicklink-status\"> </div></td>");
out.println(" <td>");
out.println("");
/*
out.println(" <div id=\"quicklinksholder\">");
out.println(" <ul id=\"quicklinks\"");
out.println(" onmouseover=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-active.gif';\"");
out.println(" onmouseout=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-inactive.gif';\">");
out.println(" <li>");
out.println(" <a href=\"#\" tabindex=\"-1\"><img src=\"/ncitbrowser/images/quicklinks-inactive.gif\" width=\"162\"");
out.println(" height=\"18\" border=\"0\" name=\"quicklinksimg\" alt=\"Quick Links\" />");
out.println(" </a>");
out.println(" <ul>");
out.println(" <li><a href=\"http://evs.nci.nih.gov/\" tabindex=\"-1\" target=\"_blank\"");
out.println(" alt=\"Enterprise Vocabulary Services\">EVS Home</a></li>");
out.println(" <li><a href=\"http://localhost/ncimbrowserncimbrowser\" tabindex=\"-1\" target=\"_blank\"");
out.println(" alt=\"NCI Metathesaurus\">NCI Metathesaurus Browser</a></li>");
out.println("");
out.println(" <li><a href=\"/ncitbrowser/start.jsf\" tabindex=\"-1\"");
out.println(" alt=\"NCI Term Browser\">NCI Term Browser</a></li>");
out.println(" <li><a href=\"http://www.cancer.gov/cancertopics/terminologyresources\" tabindex=\"-1\" target=\"_blank\"");
out.println(" alt=\"NCI Terminology Resources\">NCI Terminology Resources</a></li>");
out.println("");
out.println(" <li><a href=\"http://ncitermform.nci.nih.gov/ncitermform/?dictionary=NCI%20Thesaurus\" tabindex=\"-1\" target=\"_blank\" alt=\"Term Suggestion\">Term Suggestion</a></li>");
out.println("");
out.println("");
out.println(" </ul>");
out.println(" </li>");
out.println(" </ul>");
out.println(" </div>");
*/
addQuickLink(request, out);
out.println("");
out.println(" </td>");
out.println(" </tr>");
out.println(" </table>");
out.println("");
out.println("</div>");
if (! ServerMonitorThread.getInstance().isLexEVSRunning()) {
out.println(" <div class=\"redbar\">");
out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
out.println(" <tr>");
out.println(" <td class=\"lexevs-status\">");
out.println(" " + ServerMonitorThread.getInstance().getMessage());
out.println(" </td>");
out.println(" </tr>");
out.println(" </table>");
out.println(" </div>");
}
out.println(" <!-- end Quick links bar -->");
out.println("");
out.println(" <!-- Page content -->");
out.println(" <div class=\"pagecontent\">");
out.println("");
if (message != null) {
out.println("\r\n");
out.println(" <p class=\"textbodyred\">");
out.print(message);
out.println("</p>\r\n");
out.println(" ");
request.getSession().removeAttribute("message");
}
// to be modified
/*
out.println("<p class=\"textbody\">");
out.println("View value sets organized by standards category or source terminology.");
out.println("Standards categories group the value sets supporting them; all other labels lead to the home pages of actual value sets or source terminologies.");
out.println("Search or browse a value set from its home page, or search all value sets at once from this page (very slow) to find which ones contain a particular code or term.");
out.println("</p>");
*/
out.println("");
out.println(" <div id=\"popupContentArea\">");
out.println(" <a name=\"evs-content\" id=\"evs-content\"></a>");
out.println("");
out.println(" <table width=\"580px\" cellpadding=\"3\" cellspacing=\"0\" border=\"0\">");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" <tr class=\"textbody\">");
out.println(" <td class=\"textbody\" align=\"left\">");
out.println("");
/*
if (view == Constants.STANDARD_VIEW) {
out.println(" Standards View");
out.println(" |");
out.println(" <a href=\"" + contextPath + "/ajax?action=create_cs_vs_tree\">Terminology View</a>");
} else {
out.println(" <a href=\"" + contextPath + "/ajax?action=create_src_vs_tree\">Standards View</a>");
out.println(" |");
out.println(" Terminology View");
}
*/
out.println(" </td>");
out.println("");
out.println(" <td align=\"right\">");
out.println(" <font size=\"1\" color=\"red\" align=\"right\">");
out.println(" <a href=\"javascript:printPage()\"><img src=\"/ncitbrowser/images/printer.bmp\" border=\"0\" alt=\"Send to Printer\"><i>Send to Printer</i></a>");
out.println(" </font>");
out.println(" </td>");
out.println(" </tr>");
out.println(" </table>");
out.println("");
out.println(" <hr/>");
out.println("");
out.println("");
out.println("");
out.println("<style>");
out.println("#expandcontractdiv {border:1px solid #336600; background-color:#FFFFCC; margin:0 0 .5em 0; padding:0.2em;}");
out.println("#treecontainer { background: #fff }");
out.println("</style>");
out.println("");
out.println("");
out.println("<div id=\"expandcontractdiv\">");
out.println(" <a id=\"expand_all\" href=\"#\">Expand all</a>");
out.println(" <a id=\"collapse_all\" href=\"#\">Collapse all</a>");
out.println(" <a id=\"check_all\" href=\"#\">Check all</a>");
out.println(" <a id=\"uncheck_all\" href=\"#\">Uncheck all</a>");
out.println("</div>");
out.println("");
out.println("");
out.println("");
out.println(" <!-- Tree content -->");
out.println("");
out.println(" <div id=\"treecontainer\" class=\"ygtv-checkbox\"></div>");
out.println("");
out.println(" <form id=\"pg_form\">");
out.println("");
out.println(" <input type=\"hidden\" id=\"ontology_node_id\" name=\"ontology_node_id\" value=\"null\" />");
out.println(" <input type=\"hidden\" id=\"ontology_display_name\" name=\"ontology_display_name\" value=\"" + dictionary + "\" />");
out.println(" <input type=\"hidden\" id=\"schema\" name=\"schema\" value=\"" + dictionary + "\" />");
out.println(" <input type=\"hidden\" id=\"ontology_version\" name=\"ontology_version\" value=\"" + version + "\" />");
out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />");
out.println(" </form>");
out.println("");
out.println("");
out.println(" </div> <!-- popupContentArea -->");
out.println("");
out.println("");
out.println("<div class=\"textbody\">");
out.println("<!-- footer -->");
out.println("<div class=\"footer\" style=\"width:720px\">");
out.println(" <ul>");
out.println(" <li><a href=\"http://www.cancer.gov\" target=\"_blank\" alt=\"National Cancer Institute\">NCI Home</a> |</li>");
out.println(" <li><a href=\"/ncitbrowser/pages/contact_us.jsf\">Contact Us</a> |</li>");
out.println(" <li><a href=\"http://www.cancer.gov/policies\" target=\"_blank\" alt=\"National Cancer Institute Policies\">Policies</a> |</li>");
out.println(" <li><a href=\"http://www.cancer.gov/policies/page3\" target=\"_blank\" alt=\"National Cancer Institute Accessibility\">Accessibility</a> |</li>");
out.println(" <li><a href=\"http://www.cancer.gov/policies/page6\" target=\"_blank\" alt=\"National Cancer Institute FOIA\">FOIA</a></li>");
out.println(" </ul>");
out.println(" <p>");
out.println(" A Service of the National Cancer Institute<br />");
out.println(" <img src=\"/ncitbrowser/images/external-footer-logos.gif\"");
out.println(" alt=\"External Footer Logos\" width=\"238\" height=\"34\" border=\"0\"");
out.println(" usemap=\"#external-footer\" />");
out.println(" </p>");
out.println(" <map id=\"external-footer\" name=\"external-footer\">");
out.println(" <area shape=\"rect\" coords=\"0,0,46,34\"");
out.println(" href=\"http://www.cancer.gov\" target=\"_blank\"");
out.println(" alt=\"National Cancer Institute\" />");
out.println(" <area shape=\"rect\" coords=\"55,1,99,32\"");
out.println(" href=\"http://www.hhs.gov/\" target=\"_blank\"");
out.println(" alt=\"U.S. Health & Human Services\" />");
out.println(" <area shape=\"rect\" coords=\"103,1,147,31\"");
out.println(" href=\"http://www.nih.gov/\" target=\"_blank\"");
out.println(" alt=\"National Institutes of Health\" />");
out.println(" <area shape=\"rect\" coords=\"148,1,235,33\"");
out.println(" href=\"http://www.usa.gov/\" target=\"_blank\"");
out.println(" alt=\"USA.gov\" />");
out.println(" </map>");
out.println("</div>");
out.println("<!-- end footer -->");
out.println("</div>");
out.println("");
out.println("");
out.println(" </div> <!-- pagecontent -->");
out.println(" </div> <!-- main-area -->");
out.println(" <div class=\"mainbox-bottom\"><img src=\"/ncitbrowser/images/mainbox-bottom.gif\" width=\"745\" height=\"5\" alt=\"Mainbox Bottom\" /></div>");
out.println("");
out.println(" </div> <!-- center-page -->");
out.println("");
out.println("</body>");
out.println("</html>");
out.println("");
}
public static void addHiddenForm(PrintWriter out, String checkedNodes, String partialCheckedNodes) {
out.println(" <form id=\"hidden_form\">");
out.println(" <input type=\"hidden\" id=\"checkedNodes\" name=\"checkedNodes\" value=\"" + checkedNodes + "\" />");
out.println(" <input type=\"hidden\" id=\"partialCheckedNodes\" name=\"partialCheckedNodes\" value=\"" + partialCheckedNodes + "\" />");
out.println(" </form>");
}
public static void writeInitialize(PrintWriter out) {
out.println(" function initialize() {");
out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");");
out.println(" initializeNodeCheckState();");
out.println(" tree.expandAll();");
out.println(" tree.draw();");
out.println(" }");
}
public static void initializeNodeCheckState(PrintWriter out) {
out.println(" function initializeNodeCheckState(nodes) {");
out.println(" nodes = nodes || tree.getRoot().children;");
out.println(" var checkedNodes = document.forms[\"hidden_form\"].checkedNodes.value;");
out.println(" var partialCheckedNodes = document.forms[\"hidden_form\"].partialCheckedNodes.value;");
out.println(" for(var i=0, l=nodes.length; i<l; i=i+1) {");
out.println(" var n = nodes[i];");
out.println("");
out.println(" if (checkedNodes.indexOf(n.label) != -1) {");
out.println(" n.setCheckState(2);");
out.println(" } else if (partialCheckedNodes.indexOf(n.label) != -1) {");
out.println(" n.setCheckState(1);");
out.println(" }");
out.println("");
out.println(" if (n.hasChildren()) {");
out.println(" initializeNodeCheckState(n.children);");
out.println(" }");
out.println(" }");
out.println(" }");
}
public static void addQuickLink(HttpServletRequest request, PrintWriter out) {
String basePath = request.getContextPath();
String ncim_url = new DataUtils().getNCImURL();
String quicklink_dictionary = (String) request.getSession().getAttribute("dictionary");
quicklink_dictionary = DataUtils.getFormalName(quicklink_dictionary);
String term_suggestion_application_url2 = "";
String dictionary_encoded2 = "";
if (quicklink_dictionary != null) {
term_suggestion_application_url2 = DataUtils.getMetadataValue(quicklink_dictionary, "term_suggestion_application_url");
dictionary_encoded2 = DataUtils.replaceAll(quicklink_dictionary, " ", "%20");
}
out.write(" <div id=\"quicklinksholder\">\r\n");
out.write(" <ul id=\"quicklinks\"\r\n");
out.write(" onmouseover=\"document.quicklinksimg.src='");
out.print(basePath);
out.write("/images/quicklinks-active.gif';\"\r\n");
out.write(" onmouseout=\"document.quicklinksimg.src='");
out.print(basePath);
out.write("/images/quicklinks-inactive.gif';\">\r\n");
out.write(" <li>\r\n");
out.write(" <a href=\"#\" tabindex=\"-1\"><img src=\"");
out.print(basePath);
out.write("/images/quicklinks-inactive.gif\" width=\"162\"\r\n");
out.write(" height=\"18\" border=\"0\" name=\"quicklinksimg\" alt=\"Quick Links\" />\r\n");
out.write(" </a>\r\n");
out.write(" <ul>\r\n");
out.write(" <li><a href=\"http://evs.nci.nih.gov/\" tabindex=\"-1\" target=\"_blank\"\r\n");
out.write(" alt=\"Enterprise Vocabulary Services\">EVS Home</a></li>\r\n");
out.write(" <li><a href=\"");
out.print(ncim_url);
out.write("\" tabindex=\"-1\" target=\"_blank\"\r\n");
out.write(" alt=\"NCI Metathesaurus\">NCI Metathesaurus Browser</a></li>\r\n");
out.write("\r\n");
out.write(" ");
if (quicklink_dictionary == null || quicklink_dictionary.compareTo("NCI Thesaurus") != 0) {
out.write("\r\n");
out.write("\r\n");
out.write(" <li><a href=\"");
out.print( request.getContextPath() );
out.write("/index.jsp\" tabindex=\"-1\"\r\n");
out.write(" alt=\"NCI Thesaurus Browser\">NCI Thesaurus Browser</a></li>\r\n");
out.write("\r\n");
out.write(" ");
}
out.write("\r\n");
out.write("\r\n");
out.write(" <li>\r\n");
out.write(" <a href=\"");
out.print( request.getContextPath() );
out.write("/termbrowser.jsf\" tabindex=\"-1\" alt=\"NCI Term Browser\">NCI Term Browser</a>\r\n");
out.write(" </li>\r\n");
out.write(" \r\n");
out.write(" <li><a href=\"http://www.cancer.gov/cancertopics/terminologyresources\" tabindex=\"-1\" target=\"_blank\"\r\n");
out.write(" alt=\"NCI Terminology Resources\">NCI Terminology Resources</a></li>\r\n");
out.write(" ");
if (term_suggestion_application_url2 != null && term_suggestion_application_url2.length() > 0) {
out.write("\r\n");
out.write(" <li><a href=\"");
out.print(term_suggestion_application_url2);
out.write("?dictionary=");
out.print(dictionary_encoded2);
out.write("\" tabindex=\"-1\" target=\"_blank\" alt=\"Term Suggestion\">Term Suggestion</a></li>\r\n");
out.write(" ");
}
out.write("\r\n");
out.write("\r\n");
out.write(" </ul>\r\n");
out.write(" </li>\r\n");
out.write(" </ul>\r\n");
out.write(" </div>\r\n");
}
}
| true | true | public static void create_vs_tree(HttpServletRequest request, HttpServletResponse response, int view, String dictionary, String version) {
request.getSession().removeAttribute("b");
request.getSession().removeAttribute("m");
response.setContentType("text/html");
PrintWriter out = null;
String checked_vocabularies = (String) request.getParameter("checked_vocabularies");
System.out.println("checked_vocabularies: " + checked_vocabularies);
String partial_checked_vocabularies = (String) request.getParameter("partial_checked_vocabularies");
System.out.println("partial_checked_vocabularies: " + partial_checked_vocabularies);
try {
out = response.getWriter();
} catch (Exception ex) {
ex.printStackTrace();
return;
}
String message = (String) request.getSession().getAttribute("message");
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
out.println("<html xmlns:c=\"http://java.sun.com/jsp/jstl/core\">");
out.println("<head>");
out.println(" <title>" + dictionary + " value set</title>");
//out.println(" <title>NCI Thesaurus</title>");
out.println(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">");
out.println("");
out.println("<style type=\"text/css\">");
out.println("/*margin and padding on body element");
out.println(" can introduce errors in determining");
out.println(" element position and are not recommended;");
out.println(" we turn them off as a foundation for YUI");
out.println(" CSS treatments. */");
out.println("body {");
out.println(" margin:0;");
out.println(" padding:0;");
out.println("}");
out.println("</style>");
out.println("");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/fonts/fonts-min.css\" />");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/treeview/assets/skins/sam/treeview.css\" />");
out.println("");
out.println("<script type=\"text/javascript\" src=\"http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js\"></script>");
out.println("<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/treeview-min.js\" ></script>");
out.println("");
out.println("");
out.println("<!-- Dependency -->");
out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js\"></script>");
out.println("");
out.println("<!-- Source file -->");
out.println("<!--");
out.println(" If you require only basic HTTP transaction support, use the");
out.println(" connection_core.js file.");
out.println("-->");
out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection_core-min.js\"></script>");
out.println("");
out.println("<!--");
out.println(" Use the full connection.js if you require the following features:");
out.println(" - Form serialization.");
out.println(" - File Upload using the iframe transport.");
out.println(" - Cross-domain(XDR) transactions.");
out.println("-->");
out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection-min.js\"></script>");
out.println("");
out.println("");
out.println("");
out.println("<!--begin custom header content for this example-->");
out.println("<!--Additional custom style rules for this example:-->");
out.println("<style type=\"text/css\">");
out.println("");
out.println("");
out.println(".ygtvcheck0 { background: url(/ncitbrowser/images/yui/treeview/check0.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }");
out.println(".ygtvcheck1 { background: url(/ncitbrowser/images/yui/treeview/check1.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }");
out.println(".ygtvcheck2 { background: url(/ncitbrowser/images/yui/treeview/check2.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }");
out.println("");
out.println("");
out.println(".ygtv-edit-TaskNode { width: 190px;}");
out.println(".ygtv-edit-TaskNode .ygtvcancel, .ygtv-edit-TextNode .ygtvok { border:none;}");
out.println(".ygtv-edit-TaskNode .ygtv-button-container { float: right;}");
out.println(".ygtv-edit-TaskNode .ygtv-input input{ width: 140px;}");
out.println(".whitebg {");
out.println(" background-color:white;");
out.println("}");
out.println("</style>");
out.println("");
out.println(" <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/styleSheet.css\" />");
out.println(" <link rel=\"shortcut icon\" href=\"/ncitbrowser/favicon.ico\" type=\"image/x-icon\" />");
out.println("");
out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/script.js\"></script>");
out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tasknode.js\"></script>");
println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/search.js\"></script>");
println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/dropdown.js\"></script>");
out.println("");
out.println(" <script type=\"text/javascript\">");
out.println("");
out.println(" function refresh() {");
out.println("");
out.println(" var selectValueSetSearchOptionObj = document.forms[\"valueSetSearchForm\"].selectValueSetSearchOption;");
out.println("");
out.println(" for (var i=0; i<selectValueSetSearchOptionObj.length; i++) {");
out.println(" if (selectValueSetSearchOptionObj[i].checked) {");
out.println(" selectValueSetSearchOption = selectValueSetSearchOptionObj[i].value;");
out.println(" }");
out.println(" }");
out.println("");
out.println("");
out.println(" window.location.href=\"/ncitbrowser/pages/value_set_source_view.jsf?refresh=1\"");
out.println(" + \"&nav_type=valuesets\" + \"&opt=\"+ selectValueSetSearchOption;");
out.println("");
out.println(" }");
out.println(" </script>");
out.println("");
out.println(" <script language=\"JavaScript\">");
out.println("");
out.println(" var tree;");
out.println(" var nodeIndex;");
out.println(" var nodes = [];");
out.println("");
out.println(" function load(url,target) {");
out.println(" if (target != '')");
out.println(" target.window.location.href = url;");
out.println(" else");
out.println(" window.location.href = url;");
out.println(" }");
out.println("");
out.println(" function init() {");
out.println(" //initTree();");
out.println(" }");
out.println("");
out.println(" //handler for expanding all nodes");
out.println(" YAHOO.util.Event.on(\"expand_all\", \"click\", function(e) {");
out.println(" //expandEntireTree();");
out.println("");
out.println(" tree.expandAll();");
out.println(" //YAHOO.util.Event.preventDefault(e);");
out.println(" });");
out.println("");
out.println(" //handler for collapsing all nodes");
out.println(" YAHOO.util.Event.on(\"collapse_all\", \"click\", function(e) {");
out.println(" tree.collapseAll();");
out.println(" //YAHOO.util.Event.preventDefault(e);");
out.println(" });");
out.println("");
out.println(" //handler for checking all nodes");
out.println(" YAHOO.util.Event.on(\"check_all\", \"click\", function(e) {");
out.println(" check_all();");
out.println(" //YAHOO.util.Event.preventDefault(e);");
out.println(" });");
out.println("");
out.println(" //handler for unchecking all nodes");
out.println(" YAHOO.util.Event.on(\"uncheck_all\", \"click\", function(e) {");
out.println(" uncheck_all();");
out.println(" //YAHOO.util.Event.preventDefault(e);");
out.println(" });");
out.println("");
out.println("");
out.println("");
out.println(" YAHOO.util.Event.on(\"getchecked\", \"click\", function(e) {");
out.println(" //alert(\"Checked nodes: \" + YAHOO.lang.dump(getCheckedNodes()), \"info\", \"example\");");
out.println(" //YAHOO.util.Event.preventDefault(e);");
out.println("");
out.println(" });");
out.println("");
out.println("");
out.println(" function addTreeNode(rootNode, nodeInfo) {");
out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";");
out.println("");
out.println(" if (nodeInfo.ontology_node_id.indexOf(\"TVS_\") >= 0) {");
out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };");
out.println(" } else {");
out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };");
out.println(" }");
out.println("");
out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, false);");
out.println(" if (nodeInfo.ontology_node_child_count > 0) {");
out.println(" newNode.setDynamicLoad(loadNodeData);");
out.println(" }");
out.println(" }");
out.println("");
out.println(" function buildTree(ontology_node_id, ontology_display_name) {");
out.println(" var handleBuildTreeSuccess = function(o) {");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" if ( typeof(respObj) != \"undefined\") {");
out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {");
out.println(" var root = tree.getRoot();");
out.println(" if (respObj.root_nodes.length == 0) {");
out.println(" //showEmptyRoot();");
out.println(" }");
out.println(" else {");
out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {");
out.println(" var nodeInfo = respObj.root_nodes[i];");
out.println(" var expand = false;");
out.println(" //addTreeNode(root, nodeInfo, expand);");
out.println("");
out.println(" addTreeNode(root, nodeInfo);");
out.println(" }");
out.println(" }");
out.println("");
out.println(" tree.draw();");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
out.println(" var handleBuildTreeFailure = function(o) {");
out.println(" alert('responseFailure: ' + o.statusText);");
out.println(" }");
out.println("");
out.println(" var buildTreeCallback =");
out.println(" {");
out.println(" success:handleBuildTreeSuccess,");
out.println(" failure:handleBuildTreeFailure");
out.println(" };");
out.println("");
out.println(" if (ontology_display_name!='') {");
out.println(" var ontology_source = null;");
out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=build_src_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);");
out.println(" }");
out.println(" }");
out.println("");
out.println(" function resetTree(ontology_node_id, ontology_display_name) {");
out.println("");
out.println(" var handleResetTreeSuccess = function(o) {");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" if ( typeof(respObj) != \"undefined\") {");
out.println(" if ( typeof(respObj.root_node) != \"undefined\") {");
out.println(" var root = tree.getRoot();");
out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.root_node.ontology_node_id + \"');\";");
out.println(" var rootNodeData = { label:respObj.root_node.ontology_node_name, id:respObj.root_node.ontology_node_id, href:nodeDetails };");
out.println(" var expand = false;");
out.println(" if (respObj.root_node.ontology_node_child_count > 0) {");
out.println(" expand = true;");
out.println(" }");
out.println(" var ontRoot = new YAHOO.widget.TaskNode(rootNodeData, root, expand);");
out.println("");
out.println(" if ( typeof(respObj.child_nodes) != \"undefined\") {");
out.println(" for (var i=0; i < respObj.child_nodes.length; i++) {");
out.println(" var nodeInfo = respObj.child_nodes[i];");
out.println(" addTreeNode(ontRoot, nodeInfo);");
out.println(" }");
out.println(" }");
out.println(" tree.draw();");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
out.println(" var handleResetTreeFailure = function(o) {");
out.println(" alert('responseFailure: ' + o.statusText);");
out.println(" }");
out.println("");
out.println(" var resetTreeCallback =");
out.println(" {");
out.println(" success:handleResetTreeSuccess,");
out.println(" failure:handleResetTreeFailure");
out.println(" };");
out.println(" if (ontology_node_id!= '') {");
out.println(" var ontology_source = null;");
out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=reset_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name + '&version='+ ontology_version +'&ontology_source='+ontology_source,resetTreeCallback);");
out.println(" }");
out.println(" }");
out.println("");
out.println(" function onClickTreeNode(ontology_node_id) {");
out.println(" //alert(\"onClickTreeNode \" + ontology_node_id);");
out.println(" window.location = '/ncitbrowser/pages/value_set_treenode_redirect.jsf?ontology_node_id=' + ontology_node_id;");
out.println(" }");
out.println("");
out.println("");
out.println(" function onClickViewEntireOntology(ontology_display_name) {");
out.println(" var ontology_display_name = document.pg_form.ontology_display_name.value;");
out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");");
out.println(" tree.draw();");
out.println(" }");
out.println("");
out.println(" function initTree() {");
out.println("");
out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");");
//out.println(" pre_check();");
out.println(" tree.setNodesProperty('propagateHighlightUp',true);");
out.println(" tree.setNodesProperty('propagateHighlightDown',true);");
out.println(" tree.subscribe('keydown',tree._onKeyDownEvent);");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" tree.subscribe(\"expand\", function(node) {");
out.println("");
out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 39 });");
out.println("");
out.println(" });");
out.println("");
out.println("");
out.println("");
out.println(" tree.subscribe(\"collapse\", function(node) {");
out.println(" //alert(\"Collapsing \" + node.label );");
out.println("");
out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 109 });");
out.println(" });");
out.println("");
out.println(" // By default, trees with TextNodes will fire an event for when the label is clicked:");
out.println(" tree.subscribe(\"checkClick\", function(node) {");
out.println(" //alert(node.data.myNodeId + \" label was checked\");");
out.println(" });");
out.println("");
out.println("");
println(out, " var root = tree.getRoot();");
HashMap value_set_tree_hmap = DataUtils.getCodingSchemeValueSetTree();
TreeItem root = (TreeItem) value_set_tree_hmap.get("<Root>");
new ValueSetUtils().printTree(out, root, Constants.TERMINOLOGY_VIEW, dictionary);
//new ValueSetUtils().printTree(out, root, Constants.TERMINOLOGY_VIEW);
String contextPath = request.getContextPath();
String view_str = new Integer(view).toString();
//String option = (String) request.getSession().getAttribute("selectValueSetSearchOption");
//String algorithm = (String) request.getSession().getAttribute("valueset_search_algorithm");
String option = (String) request.getParameter("selectValueSetSearchOption");
String algorithm = (String) request.getParameter("valueset_search_algorithm");
String option_code = "";
String option_name = "";
if (DataUtils.isNull(option)) {
option_code = "checked";
} else {
if (option.compareToIgnoreCase("Code") == 0) {
option_code = "checked";
}
if (option.compareToIgnoreCase("Name") == 0) {
option_name = "checked";
}
}
String algorithm_exactMatch = "";
String algorithm_startsWith = "";
String algorithm_contains = "";
if (DataUtils.isNull(algorithm)) {
algorithm_exactMatch = "checked";
} else {
if (algorithm.compareToIgnoreCase("exactMatch") == 0) {
algorithm_exactMatch = "checked";
}
if (algorithm.compareToIgnoreCase("startsWith") == 0) {
algorithm_startsWith = "checked";
}
if (algorithm.compareToIgnoreCase("contains") == 0) {
algorithm_contains = "checked";
}
}
out.println("");
if (message == null) {
out.println(" tree.collapseAll();");
}
out.println(" initializeNodeCheckState();");
out.println(" tree.draw();");
out.println(" }");
out.println("");
out.println("");
out.println(" function onCheckClick(node) {");
out.println(" YAHOO.log(node.label + \" check was clicked, new state: \" + node.checkState, \"info\", \"example\");");
out.println(" }");
out.println("");
out.println(" function check_all() {");
out.println(" var topNodes = tree.getRoot().children;");
out.println(" for(var i=0; i<topNodes.length; ++i) {");
out.println(" topNodes[i].check();");
out.println(" }");
out.println(" }");
out.println("");
out.println(" function uncheck_all() {");
out.println(" var topNodes = tree.getRoot().children;");
out.println(" for(var i=0; i<topNodes.length; ++i) {");
out.println(" topNodes[i].uncheck();");
out.println(" }");
out.println(" }");
out.println("");
out.println("");
out.println("");
out.println(" function expand_all() {");
out.println(" //alert(\"expand_all\");");
out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;");
out.println(" onClickViewEntireOntology(ontology_display_name);");
out.println(" }");
out.println("");
out.println(" function pre_check() {");
out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;");
//out.println(" alert(ontology_display_name);");
out.println(" var topNodes = tree.getRoot().children;");
out.println(" for(var i=0; i<topNodes.length; ++i) {");
out.println(" if (topNodes[i].label == ontology_display_name) {");
out.println(" topNodes[i].check();");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
// 0=unchecked, 1=some children checked, 2=all children checked
/*
function getCheckedNodes(nodes) {
nodes = nodes || tree.getRoot().children;
checkedNodes = [];
for(var i=0, l=nodes.length; i<l; i=i+1) {
var n = nodes[i];
//if (n.checkState > 0) { // if we were interested in the nodes that have some but not all children checked
if (n.checkState == 2) {
checkedNodes.push(n.label); // just using label for simplicity
}
if (n.hasChildren()) {
checkedNodes = checkedNodes.concat(getCheckedNodes(n.children));
}
}
//var checked_vocabularies = document.forms["valueSetSearchForm"].checked_vocabularies;
//checked_vocabularies.value = checkedNodes;
return checkedNodes;
}
*/
out.println(" function getCheckedVocabularies(nodes) {");
out.println(" getCheckedNodes(nodes);");
out.println(" getPartialCheckedNodes(nodes);");
out.println(" }");
writeInitialize(out);
initializeNodeCheckState(out);
out.println(" // Gets the labels of all of the fully checked nodes");
out.println(" // Could be updated to only return checked leaf nodes by evaluating");
out.println(" // the children collection first.");
out.println(" function getCheckedNodes(nodes) {");
out.println(" nodes = nodes || tree.getRoot().children;");
out.println(" var checkedNodes = [];");
out.println(" for(var i=0, l=nodes.length; i<l; i=i+1) {");
out.println(" var n = nodes[i];");
out.println(" if (n.checkState == 2) {");
out.println(" checkedNodes.push(n.label); // just using label for simplicity");
out.println(" }");
out.println(" if (n.hasChildren()) {");
out.println(" checkedNodes = checkedNodes.concat(getCheckedNodes(n.children));");
out.println(" }");
out.println(" }");
//out.println(" checkedNodes = checkedNodes.concat(\",\");");
out.println(" var checked_vocabularies = document.forms[\"valueSetSearchForm\"].checked_vocabularies;");
out.println(" checked_vocabularies.value = checkedNodes;");
out.println(" return checkedNodes;");
out.println(" }");
out.println(" function getPartialCheckedNodes(nodes) {");
out.println(" nodes = nodes || tree.getRoot().children;");
out.println(" var checkedNodes = [];");
out.println(" for(var i=0, l=nodes.length; i<l; i=i+1) {");
out.println(" var n = nodes[i];");
out.println(" if (n.checkState == 1) {");
out.println(" checkedNodes.push(n.label); // just using label for simplicity");
out.println(" }");
out.println(" if (n.hasChildren()) {");
out.println(" checkedNodes = checkedNodes.concat(getPartialCheckedNodes(n.children));");
out.println(" }");
out.println(" }");
//out.println(" checkedNodes = checkedNodes.concat(\",\");");
out.println(" var partial_checked_vocabularies = document.forms[\"valueSetSearchForm\"].partial_checked_vocabularies;");
out.println(" partial_checked_vocabularies.value = checkedNodes;");
out.println(" return checkedNodes;");
out.println(" }");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" function loadNodeData(node, fnLoadComplete) {");
out.println(" var id = node.data.id;");
out.println("");
out.println(" var responseSuccess = function(o)");
out.println(" {");
out.println(" var path;");
out.println(" var dirs;");
out.println(" var files;");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" var fileNum = 0;");
out.println(" var categoryNum = 0;");
out.println(" if ( typeof(respObj.nodes) != \"undefined\") {");
out.println(" for (var i=0; i < respObj.nodes.length; i++) {");
out.println(" var name = respObj.nodes[i].ontology_node_name;");
out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";");
out.println(" var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };");
out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, node, false);");
out.println(" if (respObj.nodes[i].ontology_node_child_count > 0) {");
out.println(" newNode.setDynamicLoad(loadNodeData);");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" tree.draw();");
out.println(" fnLoadComplete();");
out.println(" }");
out.println("");
out.println(" var responseFailure = function(o){");
out.println(" alert('responseFailure: ' + o.statusText);");
out.println(" }");
out.println("");
out.println(" var callback =");
out.println(" {");
out.println(" success:responseSuccess,");
out.println(" failure:responseFailure");
out.println(" };");
out.println("");
out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;");
out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
out.println(" var cObj = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_src_vs_tree&ontology_node_id=' +id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version,callback);");
out.println(" }");
out.println("");
out.println("");
out.println(" function searchTree(ontology_node_id, ontology_display_name) {");
out.println("");
out.println(" var handleBuildTreeSuccess = function(o) {");
out.println("");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" if ( typeof(respObj) != \"undefined\") {");
out.println("");
out.println(" if ( typeof(respObj.dummy_root_nodes) != \"undefined\") {");
out.println(" showNodeNotFound(ontology_node_id);");
out.println(" }");
out.println("");
out.println(" else if ( typeof(respObj.root_nodes) != \"undefined\") {");
out.println(" var root = tree.getRoot();");
out.println(" if (respObj.root_nodes.length == 0) {");
out.println(" //showEmptyRoot();");
out.println(" }");
out.println(" else {");
out.println(" showPartialHierarchy();");
out.println(" showConstructingTreeStatus();");
out.println("");
out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {");
out.println(" var nodeInfo = respObj.root_nodes[i];");
out.println(" //var expand = false;");
out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
out.println(" var handleBuildTreeFailure = function(o) {");
out.println(" alert('responseFailure: ' + o.statusText);");
out.println(" }");
out.println("");
out.println(" var buildTreeCallback =");
out.println(" {");
out.println(" success:handleBuildTreeSuccess,");
out.println(" failure:handleBuildTreeFailure");
out.println(" };");
out.println("");
out.println(" if (ontology_display_name!='') {");
out.println(" var ontology_source = null;//document.pg_form.ontology_source.value;");
out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=search_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);");
out.println("");
out.println(" }");
out.println(" }");
out.println("");
out.println("");
out.println("");
out.println(" function expandEntireTree() {");
out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");");
out.println(" //tree.draw();");
out.println("");
out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;");
out.println(" var ontology_node_id = document.forms[\"pg_form\"].ontology_node_id.value;");
out.println("");
out.println(" var handleBuildTreeSuccess = function(o) {");
out.println("");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" if ( typeof(respObj) != \"undefined\") {");
out.println("");
out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {");
out.println("");
out.println(" //alert(respObj.root_nodes.length);");
out.println("");
out.println(" var root = tree.getRoot();");
out.println(" if (respObj.root_nodes.length == 0) {");
out.println(" //showEmptyRoot();");
out.println(" } else {");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {");
out.println(" var nodeInfo = respObj.root_nodes[i];");
out.println(" //alert(\"calling addTreeBranch \");");
out.println("");
out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
out.println(" var handleBuildTreeFailure = function(o) {");
out.println(" alert('responseFailure: ' + o.statusText);");
out.println(" }");
out.println("");
out.println(" var buildTreeCallback =");
out.println(" {");
out.println(" success:handleBuildTreeSuccess,");
out.println(" failure:handleBuildTreeFailure");
out.println(" };");
out.println("");
out.println(" if (ontology_display_name!='') {");
out.println(" var ontology_source = null;");
out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_entire_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);");
out.println("");
out.println(" }");
out.println(" }");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" function addTreeBranch(ontology_node_id, rootNode, nodeInfo) {");
out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";");
out.println("");
out.println(" var newNodeData;");
out.println(" if (ontology_node_id.indexOf(\"TVS_\") >= 0) {");
out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };");
out.println(" } else {");
out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };");
out.println(" }");
out.println("");
out.println(" var expand = false;");
out.println(" var childNodes = nodeInfo.children_nodes;");
out.println("");
out.println(" if (childNodes.length > 0) {");
out.println(" expand = true;");
out.println(" }");
out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, expand);");
out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {");
out.println(" newNode.labelStyle = \"ygtvlabel_highlight\";");
out.println(" }");
out.println("");
out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {");
out.println(" newNode.isLeaf = true;");
out.println(" if (nodeInfo.ontology_node_child_count > 0) {");
out.println(" newNode.isLeaf = false;");
out.println(" newNode.setDynamicLoad(loadNodeData);");
out.println(" } else {");
out.println(" tree.draw();");
out.println(" }");
out.println("");
out.println(" } else {");
out.println(" if (nodeInfo.ontology_node_id != ontology_node_id) {");
out.println(" if (nodeInfo.ontology_node_child_count == 0 && nodeInfo.ontology_node_id != ontology_node_id) {");
out.println(" newNode.isLeaf = true;");
out.println(" } else if (childNodes.length == 0) {");
out.println(" newNode.setDynamicLoad(loadNodeData);");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
out.println(" tree.draw();");
out.println(" for (var i=0; i < childNodes.length; i++) {");
out.println(" var childnodeInfo = childNodes[i];");
out.println(" addTreeBranch(ontology_node_id, newNode, childnodeInfo);");
out.println(" }");
out.println(" }");
out.println(" YAHOO.util.Event.addListener(window, \"load\", init);");
out.println("");
out.println(" YAHOO.util.Event.onDOMReady(initTree);");
out.println("");
out.println("");
out.println(" </script>");
out.println("");
out.println("</head>");
out.println("");
out.println("");
out.println("");
out.println("");
out.println("");
//out.println("<body>");
out.println("<body onLoad=\"document.forms.valueSetSearchForm.matchText.focus();\">");
//out.println("<body onLoad=\"initialize();\">");
out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/wz_tooltip.js\"></script>");
out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_centerwindow.js\"></script>");
out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_followscroll.js\"></script>");
out.println("");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" <!-- Begin Skip Top Navigation -->");
out.println(" <a href=\"#evs-content\" class=\"hideLink\" accesskey=\"1\" title=\"Skip repetitive navigation links\">skip navigation links</A>");
out.println(" <!-- End Skip Top Navigation -->");
out.println("");
out.println("<!-- nci banner -->");
out.println("<div class=\"ncibanner\">");
out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">");
out.println(" <img src=\"/ncitbrowser/images/logotype.gif\"");
out.println(" width=\"440\" height=\"39\" border=\"0\"");
out.println(" alt=\"National Cancer Institute\"/>");
out.println(" </a>");
out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">");
out.println(" <img src=\"/ncitbrowser/images/spacer.gif\"");
out.println(" width=\"48\" height=\"39\" border=\"0\"");
out.println(" alt=\"National Cancer Institute\" class=\"print-header\"/>");
out.println(" </a>");
out.println(" <a href=\"http://www.nih.gov\" target=\"_blank\" >");
out.println(" <img src=\"/ncitbrowser/images/tagline_nologo.gif\"");
out.println(" width=\"173\" height=\"39\" border=\"0\"");
out.println(" alt=\"U.S. National Institutes of Health\"/>");
out.println(" </a>");
out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">");
out.println(" <img src=\"/ncitbrowser/images/cancer-gov.gif\"");
out.println(" width=\"99\" height=\"39\" border=\"0\"");
out.println(" alt=\"www.cancer.gov\"/>");
out.println(" </a>");
out.println("</div>");
out.println("<!-- end nci banner -->");
out.println("");
out.println(" <div class=\"center-page\">");
out.println(" <!-- EVS Logo -->");
out.println("<div>");
// to be modified
out.println(" <img src=\"/ncitbrowser/images/evs-logo-swapped.gif\" alt=\"EVS Logo\"");
out.println(" width=\"745\" height=\"26\" border=\"0\"");
out.println(" usemap=\"#external-evs\" />");
out.println(" <map id=\"external-evs\" name=\"external-evs\">");
out.println(" <area shape=\"rect\" coords=\"0,0,140,26\"");
out.println(" href=\"/ncitbrowser/start.jsf\" target=\"_self\"");
out.println(" alt=\"NCI Term Browser\" />");
out.println(" <area shape=\"rect\" coords=\"520,0,745,26\"");
out.println(" href=\"http://evs.nci.nih.gov/\" target=\"_blank\"");
out.println(" alt=\"Enterprise Vocabulary Services\" />");
out.println(" </map>");
out.println("</div>");
out.println("");
out.println("");
out.println("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">");
out.println(" <tr>");
out.println(" <td width=\"5\"></td>");
//to be modified
out.println(" <td><a href=\"/ncitbrowser/pages/multiple_search.jsf?nav_type=terminologies\">");
out.println(" <img name=\"tab_terms\" src=\"/ncitbrowser/images/tab_terms_clicked.gif\"");
out.println(" border=\"0\" alt=\"Terminologies\" title=\"Terminologies\" /></a></td>");
out.println(" <td><a href=\"/ncitbrowser/ajax?action=create_src_vs_tree\">");
out.println(" <img name=\"tab_valuesets\" src=\"/ncitbrowser/images/tab_valuesets.gif\"");
out.println(" border=\"0\" alt=\"Value Sets\" title=\"ValueSets\" /></a></td>");
out.println(" <td><a href=\"/ncitbrowser/pages/mapping_search.jsf?nav_type=mappings\">");
out.println(" <img name=\"tab_map\" src=\"/ncitbrowser/images/tab_map.gif\"");
out.println(" border=\"0\" alt=\"Mappings\" title=\"Mappings\" /></a></td>");
out.println(" </tr>");
out.println("</table>");
out.println("");
out.println("<div class=\"mainbox-top\"><img src=\"/ncitbrowser/images/mainbox-top.gif\" width=\"745\" height=\"5\" alt=\"\"/></div>");
out.println("<!-- end EVS Logo -->");
out.println(" <!-- Main box -->");
out.println(" <div id=\"main-area\">");
out.println("");
out.println(" <!-- Thesaurus, banner search area -->");
out.println(" <div class=\"bannerarea\">");
/*
out.println(" <a href=\"/ncitbrowser/start.jsf\" style=\"text-decoration: none;\">");
out.println(" <div class=\"vocabularynamebanner_tb\">");
out.println(" <span class=\"vocabularynamelong_tb\">" + JSPUtils.getApplicationVersionDisplay() + "</span>");
out.println(" </div>");
out.println(" </a>");
*/
JSPUtils.JSPHeaderInfoMore info = new JSPUtils.JSPHeaderInfoMore(request);
String scheme = info.dictionary;
String term_browser_version = info.term_browser_version;
String display_name = info.display_name;
String basePath = request.getContextPath();
/*
<a href="/ncitbrowser/pages/home.jsf?version=12.02d" style="text-decoration: none;">
<div class="vocabularynamebanner_ncit">
<span class="vocabularynamelong_ncit">Version: 12.02d (Release date: 2012-02-27-08:00)</span>
</div>
</a>
*/
String release_date = DataUtils.getVersionReleaseDate(scheme, version);
if (dictionary != null && dictionary.compareTo("NCI Thesaurus") == 0) {
out.println("<a href=\"/ncitbrowser/pages/home.jsf?version=" + version + "\" style=\"text-decoration: none;\">");
out.println(" <div class=\"vocabularynamebanner_ncit\">");
out.println(" <span class=\"vocabularynamelong_ncit\">Version: " + version + " (Release date: " + release_date + ")</span>");
out.println(" </div>");
out.println("</a>");
/*
out.write("\r\n");
out.write(" <div class=\"banner\"><a href=\"");
out.print(basePath);
out.write("\"><img src=\"");
out.print(basePath);
out.write("/images/thesaurus_browser_logo.jpg\" width=\"383\" height=\"117\" alt=\"Thesaurus Browser Logo\" border=\"0\"/></a></div>\r\n");
*/
} else {
out.write("\r\n");
out.write("\r\n");
out.write(" ");
if (version == null) {
out.write("\r\n");
out.write(" <a class=\"vocabularynamebanner\" href=\"");
out.print(request.getContextPath());
out.write("/pages/vocabulary.jsf?dictionary=");
out.print(HTTPUtils.cleanXSS(dictionary));
out.write("\">\r\n");
out.write(" ");
} else {
out.write("\r\n");
out.write(" <a class=\"vocabularynamebanner\" href=\"");
out.print(request.getContextPath());
out.write("/pages/vocabulary.jsf?dictionary=");
out.print(HTTPUtils.cleanXSS(dictionary));
out.write("&version=");
out.print(HTTPUtils.cleanXSS(version));
out.write("\">\r\n");
out.write(" ");
}
out.write("\r\n");
out.write(" <div class=\"vocabularynamebanner\">\r\n");
out.write(" <div class=\"vocabularynameshort\" STYLE=\"font-size: ");
out.print(HTTPUtils.maxFontSize(display_name));
out.write("px; font-family : Arial\">\r\n");
out.write(" ");
out.print(HTTPUtils.cleanXSS(display_name));
out.write("\r\n");
out.write(" </div>\r\n");
out.write(" \r\n");
boolean display_release_date = true;
if (release_date == null || release_date.compareTo("") == 0) {
display_release_date = false;
}
if (display_release_date) {
out.write("\r\n");
out.write(" <div class=\"vocabularynamelong\">Version: ");
out.print(HTTPUtils.cleanXSS(term_browser_version));
out.write(" (Release date: ");
out.print(release_date);
out.write(")</div>\r\n");
} else {
out.write("\r\n");
out.write(" <div class=\"vocabularynamelong\">Version: ");
out.print(HTTPUtils.cleanXSS(term_browser_version));
out.write("</div>\r\n");
}
out.write(" \r\n");
out.write(" \r\n");
out.write(" </div>\r\n");
out.write(" </a>\r\n");
}
out.println(" <div class=\"search-globalnav\">");
out.println(" <!-- Search box -->");
out.println(" <div class=\"searchbox-top\"><img src=\"/ncitbrowser/images/searchbox-top.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Top\" /></div>");
out.println(" <div class=\"searchbox\">");
out.println("");
out.println("");
out.println("<form id=\"valueSetSearchForm\" name=\"valueSetSearchForm\" method=\"post\" action=\"" + contextPath + "/ajax?action=search_value_set\" class=\"search-form-main-area\" enctype=\"application/x-www-form-urlencoded\">");
out.println("<input type=\"hidden\" name=\"valueSetSearchForm\" value=\"valueSetSearchForm\" />");
out.println("<input type=\"hidden\" name=\"view\" value=\"" + view_str + "\" />");
String matchText = (String) request.getSession().getAttribute("matchText");
if (DataUtils.isNull(matchText)) {
matchText = "";
}
out.println("");
out.println("");
out.println("");
out.println(" <input type=\"hidden\" id=\"checked_vocabularies\" name=\"checked_vocabularies\" value=\"\" />");
out.println(" <input type=\"hidden\" id=\"partial_checked_vocabularies\" name=\"partial_checked_vocabularies\" value=\"\" />");
out.println("");
out.println("");
out.println("");
out.println("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 2px\" >");
out.println(" <tr valign=\"top\" align=\"left\">");
out.println(" <td align=\"left\" class=\"textbody\">");
out.println("");
out.println(" <input CLASS=\"searchbox-input-2\"");
out.println(" name=\"matchText\"");
out.println(" value=\"" + matchText + "\"");
out.println(" onFocus=\"active = true\"");
out.println(" onBlur=\"active = false\"");
out.println(" onkeypress=\"return submitEnter('valueSetSearchForm:valueset_search',event)\"");
out.println(" tabindex=\"1\"/>");
out.println("");
out.println("");
out.println(" <input id=\"valueSetSearchForm:valueset_search\" type=\"image\" src=\"/ncitbrowser/images/search.gif\" name=\"valueSetSearchForm:valueset_search\" alt=\"Search Value Sets\" onclick=\"javascript:getCheckedVocabularies();\" tabindex=\"2\" class=\"searchbox-btn\" /><a href=\"/ncitbrowser/pages/help.jsf#searchhelp\" tabindex=\"3\"><img src=\"/ncitbrowser/images/search-help.gif\" alt=\"Search Help\" style=\"border-width:0;\" class=\"searchbox-btn\" /></a>");
out.println("");
out.println("");
out.println(" </td>");
out.println(" </tr>");
out.println("");
out.println(" <tr valign=\"top\" align=\"left\">");
out.println(" <td>");
out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 0px\">");
out.println("");
out.println(" <tr valign=\"top\" align=\"left\">");
out.println(" <td align=\"left\" class=\"textbody\">");
out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"exactMatch\" alt=\"Exact Match\" " + algorithm_exactMatch + " tabindex=\"3\">Exact Match ");
out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"startsWith\" alt=\"Begins With\" " + algorithm_startsWith + " tabindex=\"3\">Begins With ");
out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"contains\" alt=\"Contains\" " + algorithm_contains + " tabindex=\"3\">Contains");
out.println(" </td>");
out.println(" </tr>");
out.println("");
out.println(" <tr align=\"left\">");
out.println(" <td height=\"1px\" bgcolor=\"#2F2F5F\" align=\"left\"></td>");
out.println(" </tr>");
out.println(" <tr valign=\"top\" align=\"left\">");
out.println(" <td align=\"left\" class=\"textbody\">");
out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Code\" " + option_code + " alt=\"Code\" tabindex=\"1\" >Code ");
out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Name\" " + option_name + " alt=\"Name\" tabindex=\"1\" >Name");
out.println(" </td>");
out.println(" </tr>");
out.println(" </table>");
out.println(" </td>");
out.println(" </tr>");
out.println("</table>");
out.println(" <input type=\"hidden\" name=\"referer\" id=\"referer\" value=\"http%3A%2F%2Flocalhost%3A8080%2Fncitbrowser%2Fpages%2Fresolved_value_set_search_results.jsf\">");
out.println(" <input type=\"hidden\" id=\"nav_type\" name=\"nav_type\" value=\"valuesets\" />");
out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />");
out.println(" <input type=\"hidden\" id=\"ontology_display_name\" name=\"ontology_display_name\" value=\"" + dictionary + "\" />");
out.println(" <input type=\"hidden\" id=\"schema\" name=\"schema\" value=\"" + dictionary + "\" />");
out.println(" <input type=\"hidden\" id=\"ontology_version\" name=\"ontology_version\" value=\"" + version + "\" />");
out.println("");
out.println("<input type=\"hidden\" name=\"javax.faces.ViewState\" id=\"javax.faces.ViewState\" value=\"j_id22:j_id23\" />");
out.println("</form>");
addHiddenForm(out, checked_vocabularies, partial_checked_vocabularies);
out.println(" </div> <!-- searchbox -->");
out.println("");
out.println(" <div class=\"searchbox-bottom\"><img src=\"/ncitbrowser/images/searchbox-bottom.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Bottom\" /></div>");
out.println(" <!-- end Search box -->");
out.println(" <!-- Global Navigation -->");
out.println("");
/*
out.println("<table class=\"global-nav\" border=\"0\" width=\"100%\" height=\"37px\" cellpadding=\"0\" cellspacing=\"0\">");
out.println(" <tr>");
out.println(" <td align=\"left\" valign=\"bottom\">");
out.println(" <a href=\"#\" onclick=\"javascript:window.open('/ncitbrowser/pages/source_help_info-termbrowser.jsf',");
out.println(" '_blank','top=100, left=100, height=740, width=780, status=no, menubar=no, resizable=yes, scrollbars=yes, toolbar=no, location=no, directories=no');\" tabindex=\"13\">");
out.println(" Sources</a>");
out.println("");
out.println(" \r\n");
out.println(" ");
out.print( VisitedConceptUtils.getDisplayLink(request, true) );
out.println(" \r\n");
out.println(" </td>");
out.println(" <td align=\"right\" valign=\"bottom\">");
out.println(" <a href=\"");
out.print( request.getContextPath() );
out.println("/pages/help.jsf\" tabindex=\"16\">Help</a>\r\n");
out.println(" </td>\r\n");
out.println(" <td width=\"7\"></td>\r\n");
out.println(" </tr>\r\n");
out.println("</table>");
*/
boolean hasValueSet = ValueSetHierarchy.hasValueSet(scheme);
boolean hasMapping = DataUtils.hasMapping(scheme);
boolean tree_access_allowed = true;
if (DataUtils._vocabulariesWithoutTreeAccessHashSet.contains(scheme)) {
tree_access_allowed = false;
}
boolean vocabulary_isMapping = DataUtils.isMapping(scheme, null);
out.write(" <table class=\"global-nav\" border=\"0\" width=\"100%\" height=\"37px\" cellpadding=\"0\" cellspacing=\"0\">\r\n");
out.write(" <tr>\r\n");
out.write(" <td valign=\"bottom\">\r\n");
out.write(" ");
Boolean[] isPipeDisplayed = new Boolean[] { Boolean.FALSE };
out.write("\r\n");
out.write(" ");
if (vocabulary_isMapping) {
out.write("\r\n");
out.write(" ");
out.print( JSPUtils.getPipeSeparator(isPipeDisplayed) );
out.write("\r\n");
out.write(" <a href=\"");
out.print(request.getContextPath() );
out.write("/pages/mapping.jsf?dictionary=");
out.print(HTTPUtils.cleanXSS(scheme));
out.write("&version=");
out.print(version);
out.write("\">\r\n");
out.write(" Mapping\r\n");
out.write(" </a>\r\n");
out.write(" ");
} else if (tree_access_allowed) {
out.write("\r\n");
out.write(" ");
out.print( JSPUtils.getPipeSeparator(isPipeDisplayed) );
out.write("\r\n");
out.write(" <a href=\"#\" onclick=\"javascript:window.open('");
out.print(request.getContextPath());
out.write("/pages/hierarchy.jsf?dictionary=");
out.print(HTTPUtils.cleanXSS(scheme));
out.write("&version=");
out.print(HTTPUtils.cleanXSS(version));
out.write("', '_blank','top=100, left=100, height=740, width=680, status=no, menubar=no, resizable=yes, scrollbars=yes, toolbar=no, location=no, directories=no');\" tabindex=\"12\">\r\n");
out.write(" Hierarchy </a>\r\n");
out.write(" ");
}
out.write(" \r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write(" ");
if (hasValueSet) {
out.write("\r\n");
out.write(" ");
out.print( JSPUtils.getPipeSeparator(isPipeDisplayed) );
out.write("\r\n");
out.write(" <!--\r\n");
out.write(" <a href=\"");
out.print( request.getContextPath() );
out.write("/pages/value_set_hierarchy.jsf?dictionary=");
out.print(HTTPUtils.cleanXSS(scheme));
out.write("&version=");
out.print(HTTPUtils.cleanXSS(version));
out.write("\" tabindex=\"15\">Value Sets</a>\r\n");
out.write(" -->\r\n");
out.write(" <a href=\"");
out.print( request.getContextPath() );
out.write("/ajax?action=create_cs_vs_tree&dictionary=");
out.print(HTTPUtils.cleanXSS(scheme));
out.write("&version=");
out.print(HTTPUtils.cleanXSS(version));
out.write("\" tabindex=\"15\">Value Sets</a>\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" ");
}
out.write("\r\n");
out.write(" \r\n");
out.write(" ");
if (hasMapping) {
out.write("\r\n");
out.write(" ");
out.print( JSPUtils.getPipeSeparator(isPipeDisplayed) );
out.write("\r\n");
out.write(" <a href=\"");
out.print( request.getContextPath() );
out.write("/pages/cs_mappings.jsf?dictionary=");
out.print(HTTPUtils.cleanXSS(scheme));
out.write("&version=");
out.print(HTTPUtils.cleanXSS(version));
out.write("\" tabindex=\"15\">Maps</a> \r\n");
out.write(" ");
}
String cart_size = (String) request.getSession().getAttribute("cart_size");
if (!DataUtils.isNull(cart_size)) {
out.write("|");
out.write(" <a href=\"");
out.print(request.getContextPath());
out.write("/pages/cart.jsf\" tabindex=\"16\">Cart</a>\r\n");
}
out.write(" ");
out.print( VisitedConceptUtils.getDisplayLink(request, isPipeDisplayed) );
out.write("\r\n");
out.write(" </td>\r\n");
out.write(" <td align=\"right\" valign=\"bottom\">\r\n");
out.write(" <a href=\"");
out.print(request.getContextPath());
out.write("/pages/help.jsf\" tabindex=\"16\">Help</a>\r\n");
out.write(" </td>\r\n");
out.write(" <td width=\"7\" valign=\"bottom\"></td>\r\n");
out.write(" </tr>\r\n");
out.write(" </table>\r\n");
out.println(" <!-- end Global Navigation -->");
out.println("");
out.println(" </div> <!-- search-globalnav -->");
out.println(" </div> <!-- bannerarea -->");
out.println("");
out.println(" <!-- end Thesaurus, banner search area -->");
out.println(" <!-- Quick links bar -->");
out.println("");
out.println("<div class=\"bluebar\">");
out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
out.println(" <tr>");
out.println(" <td><div class=\"quicklink-status\"> </div></td>");
out.println(" <td>");
out.println("");
/*
out.println(" <div id=\"quicklinksholder\">");
out.println(" <ul id=\"quicklinks\"");
out.println(" onmouseover=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-active.gif';\"");
out.println(" onmouseout=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-inactive.gif';\">");
out.println(" <li>");
out.println(" <a href=\"#\" tabindex=\"-1\"><img src=\"/ncitbrowser/images/quicklinks-inactive.gif\" width=\"162\"");
out.println(" height=\"18\" border=\"0\" name=\"quicklinksimg\" alt=\"Quick Links\" />");
out.println(" </a>");
out.println(" <ul>");
out.println(" <li><a href=\"http://evs.nci.nih.gov/\" tabindex=\"-1\" target=\"_blank\"");
out.println(" alt=\"Enterprise Vocabulary Services\">EVS Home</a></li>");
out.println(" <li><a href=\"http://localhost/ncimbrowserncimbrowser\" tabindex=\"-1\" target=\"_blank\"");
out.println(" alt=\"NCI Metathesaurus\">NCI Metathesaurus Browser</a></li>");
out.println("");
out.println(" <li><a href=\"/ncitbrowser/start.jsf\" tabindex=\"-1\"");
out.println(" alt=\"NCI Term Browser\">NCI Term Browser</a></li>");
out.println(" <li><a href=\"http://www.cancer.gov/cancertopics/terminologyresources\" tabindex=\"-1\" target=\"_blank\"");
out.println(" alt=\"NCI Terminology Resources\">NCI Terminology Resources</a></li>");
out.println("");
out.println(" <li><a href=\"http://ncitermform.nci.nih.gov/ncitermform/?dictionary=NCI%20Thesaurus\" tabindex=\"-1\" target=\"_blank\" alt=\"Term Suggestion\">Term Suggestion</a></li>");
out.println("");
out.println("");
out.println(" </ul>");
out.println(" </li>");
out.println(" </ul>");
out.println(" </div>");
*/
addQuickLink(request, out);
out.println("");
out.println(" </td>");
out.println(" </tr>");
out.println(" </table>");
out.println("");
out.println("</div>");
if (! ServerMonitorThread.getInstance().isLexEVSRunning()) {
out.println(" <div class=\"redbar\">");
out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
out.println(" <tr>");
out.println(" <td class=\"lexevs-status\">");
out.println(" " + ServerMonitorThread.getInstance().getMessage());
out.println(" </td>");
out.println(" </tr>");
out.println(" </table>");
out.println(" </div>");
}
out.println(" <!-- end Quick links bar -->");
out.println("");
out.println(" <!-- Page content -->");
out.println(" <div class=\"pagecontent\">");
out.println("");
if (message != null) {
out.println("\r\n");
out.println(" <p class=\"textbodyred\">");
out.print(message);
out.println("</p>\r\n");
out.println(" ");
request.getSession().removeAttribute("message");
}
// to be modified
/*
out.println("<p class=\"textbody\">");
out.println("View value sets organized by standards category or source terminology.");
out.println("Standards categories group the value sets supporting them; all other labels lead to the home pages of actual value sets or source terminologies.");
out.println("Search or browse a value set from its home page, or search all value sets at once from this page (very slow) to find which ones contain a particular code or term.");
out.println("</p>");
*/
out.println("");
out.println(" <div id=\"popupContentArea\">");
out.println(" <a name=\"evs-content\" id=\"evs-content\"></a>");
out.println("");
out.println(" <table width=\"580px\" cellpadding=\"3\" cellspacing=\"0\" border=\"0\">");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" <tr class=\"textbody\">");
out.println(" <td class=\"textbody\" align=\"left\">");
out.println("");
/*
if (view == Constants.STANDARD_VIEW) {
out.println(" Standards View");
out.println(" |");
out.println(" <a href=\"" + contextPath + "/ajax?action=create_cs_vs_tree\">Terminology View</a>");
} else {
out.println(" <a href=\"" + contextPath + "/ajax?action=create_src_vs_tree\">Standards View</a>");
out.println(" |");
out.println(" Terminology View");
}
*/
out.println(" </td>");
out.println("");
out.println(" <td align=\"right\">");
out.println(" <font size=\"1\" color=\"red\" align=\"right\">");
out.println(" <a href=\"javascript:printPage()\"><img src=\"/ncitbrowser/images/printer.bmp\" border=\"0\" alt=\"Send to Printer\"><i>Send to Printer</i></a>");
out.println(" </font>");
out.println(" </td>");
out.println(" </tr>");
out.println(" </table>");
out.println("");
out.println(" <hr/>");
out.println("");
out.println("");
out.println("");
out.println("<style>");
out.println("#expandcontractdiv {border:1px solid #336600; background-color:#FFFFCC; margin:0 0 .5em 0; padding:0.2em;}");
out.println("#treecontainer { background: #fff }");
out.println("</style>");
out.println("");
out.println("");
out.println("<div id=\"expandcontractdiv\">");
out.println(" <a id=\"expand_all\" href=\"#\">Expand all</a>");
out.println(" <a id=\"collapse_all\" href=\"#\">Collapse all</a>");
out.println(" <a id=\"check_all\" href=\"#\">Check all</a>");
out.println(" <a id=\"uncheck_all\" href=\"#\">Uncheck all</a>");
out.println("</div>");
out.println("");
out.println("");
out.println("");
out.println(" <!-- Tree content -->");
out.println("");
out.println(" <div id=\"treecontainer\" class=\"ygtv-checkbox\"></div>");
out.println("");
out.println(" <form id=\"pg_form\">");
out.println("");
out.println(" <input type=\"hidden\" id=\"ontology_node_id\" name=\"ontology_node_id\" value=\"null\" />");
out.println(" <input type=\"hidden\" id=\"ontology_display_name\" name=\"ontology_display_name\" value=\"" + dictionary + "\" />");
out.println(" <input type=\"hidden\" id=\"schema\" name=\"schema\" value=\"" + dictionary + "\" />");
out.println(" <input type=\"hidden\" id=\"ontology_version\" name=\"ontology_version\" value=\"" + version + "\" />");
out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />");
out.println(" </form>");
out.println("");
out.println("");
out.println(" </div> <!-- popupContentArea -->");
out.println("");
out.println("");
out.println("<div class=\"textbody\">");
out.println("<!-- footer -->");
out.println("<div class=\"footer\" style=\"width:720px\">");
out.println(" <ul>");
out.println(" <li><a href=\"http://www.cancer.gov\" target=\"_blank\" alt=\"National Cancer Institute\">NCI Home</a> |</li>");
out.println(" <li><a href=\"/ncitbrowser/pages/contact_us.jsf\">Contact Us</a> |</li>");
out.println(" <li><a href=\"http://www.cancer.gov/policies\" target=\"_blank\" alt=\"National Cancer Institute Policies\">Policies</a> |</li>");
out.println(" <li><a href=\"http://www.cancer.gov/policies/page3\" target=\"_blank\" alt=\"National Cancer Institute Accessibility\">Accessibility</a> |</li>");
out.println(" <li><a href=\"http://www.cancer.gov/policies/page6\" target=\"_blank\" alt=\"National Cancer Institute FOIA\">FOIA</a></li>");
out.println(" </ul>");
out.println(" <p>");
out.println(" A Service of the National Cancer Institute<br />");
out.println(" <img src=\"/ncitbrowser/images/external-footer-logos.gif\"");
out.println(" alt=\"External Footer Logos\" width=\"238\" height=\"34\" border=\"0\"");
out.println(" usemap=\"#external-footer\" />");
out.println(" </p>");
out.println(" <map id=\"external-footer\" name=\"external-footer\">");
out.println(" <area shape=\"rect\" coords=\"0,0,46,34\"");
out.println(" href=\"http://www.cancer.gov\" target=\"_blank\"");
out.println(" alt=\"National Cancer Institute\" />");
out.println(" <area shape=\"rect\" coords=\"55,1,99,32\"");
out.println(" href=\"http://www.hhs.gov/\" target=\"_blank\"");
out.println(" alt=\"U.S. Health & Human Services\" />");
out.println(" <area shape=\"rect\" coords=\"103,1,147,31\"");
out.println(" href=\"http://www.nih.gov/\" target=\"_blank\"");
out.println(" alt=\"National Institutes of Health\" />");
out.println(" <area shape=\"rect\" coords=\"148,1,235,33\"");
out.println(" href=\"http://www.usa.gov/\" target=\"_blank\"");
out.println(" alt=\"USA.gov\" />");
out.println(" </map>");
out.println("</div>");
out.println("<!-- end footer -->");
out.println("</div>");
out.println("");
out.println("");
out.println(" </div> <!-- pagecontent -->");
out.println(" </div> <!-- main-area -->");
out.println(" <div class=\"mainbox-bottom\"><img src=\"/ncitbrowser/images/mainbox-bottom.gif\" width=\"745\" height=\"5\" alt=\"Mainbox Bottom\" /></div>");
out.println("");
out.println(" </div> <!-- center-page -->");
out.println("");
out.println("</body>");
out.println("</html>");
out.println("");
}
| public static void create_vs_tree(HttpServletRequest request, HttpServletResponse response, int view, String dictionary, String version) {
request.getSession().removeAttribute("b");
request.getSession().removeAttribute("m");
response.setContentType("text/html");
PrintWriter out = null;
String checked_vocabularies = (String) request.getParameter("checked_vocabularies");
System.out.println("checked_vocabularies: " + checked_vocabularies);
String partial_checked_vocabularies = (String) request.getParameter("partial_checked_vocabularies");
System.out.println("partial_checked_vocabularies: " + partial_checked_vocabularies);
try {
out = response.getWriter();
} catch (Exception ex) {
ex.printStackTrace();
return;
}
String message = (String) request.getSession().getAttribute("message");
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
out.println("<html xmlns:c=\"http://java.sun.com/jsp/jstl/core\">");
out.println("<head>");
out.println(" <title>" + dictionary + " value set</title>");
//out.println(" <title>NCI Thesaurus</title>");
out.println(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">");
out.println("");
out.println("<style type=\"text/css\">");
out.println("/*margin and padding on body element");
out.println(" can introduce errors in determining");
out.println(" element position and are not recommended;");
out.println(" we turn them off as a foundation for YUI");
out.println(" CSS treatments. */");
out.println("body {");
out.println(" margin:0;");
out.println(" padding:0;");
out.println("}");
out.println("</style>");
out.println("");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/fonts/fonts-min.css\" />");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/treeview/assets/skins/sam/treeview.css\" />");
out.println("");
out.println("<script type=\"text/javascript\" src=\"http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js\"></script>");
out.println("<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/treeview-min.js\" ></script>");
out.println("");
out.println("");
out.println("<!-- Dependency -->");
out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js\"></script>");
out.println("");
out.println("<!-- Source file -->");
out.println("<!--");
out.println(" If you require only basic HTTP transaction support, use the");
out.println(" connection_core.js file.");
out.println("-->");
out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection_core-min.js\"></script>");
out.println("");
out.println("<!--");
out.println(" Use the full connection.js if you require the following features:");
out.println(" - Form serialization.");
out.println(" - File Upload using the iframe transport.");
out.println(" - Cross-domain(XDR) transactions.");
out.println("-->");
out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection-min.js\"></script>");
out.println("");
out.println("");
out.println("");
out.println("<!--begin custom header content for this example-->");
out.println("<!--Additional custom style rules for this example:-->");
out.println("<style type=\"text/css\">");
out.println("");
out.println("");
out.println(".ygtvcheck0 { background: url(/ncitbrowser/images/yui/treeview/check0.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }");
out.println(".ygtvcheck1 { background: url(/ncitbrowser/images/yui/treeview/check1.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }");
out.println(".ygtvcheck2 { background: url(/ncitbrowser/images/yui/treeview/check2.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }");
out.println("");
out.println("");
out.println(".ygtv-edit-TaskNode { width: 190px;}");
out.println(".ygtv-edit-TaskNode .ygtvcancel, .ygtv-edit-TextNode .ygtvok { border:none;}");
out.println(".ygtv-edit-TaskNode .ygtv-button-container { float: right;}");
out.println(".ygtv-edit-TaskNode .ygtv-input input{ width: 140px;}");
out.println(".whitebg {");
out.println(" background-color:white;");
out.println("}");
out.println("</style>");
out.println("");
out.println(" <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/styleSheet.css\" />");
out.println(" <link rel=\"shortcut icon\" href=\"/ncitbrowser/favicon.ico\" type=\"image/x-icon\" />");
out.println("");
out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/script.js\"></script>");
out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tasknode.js\"></script>");
println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/search.js\"></script>");
println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/dropdown.js\"></script>");
out.println("");
out.println(" <script type=\"text/javascript\">");
out.println("");
out.println(" function refresh() {");
out.println("");
out.println(" var selectValueSetSearchOptionObj = document.forms[\"valueSetSearchForm\"].selectValueSetSearchOption;");
out.println("");
out.println(" for (var i=0; i<selectValueSetSearchOptionObj.length; i++) {");
out.println(" if (selectValueSetSearchOptionObj[i].checked) {");
out.println(" selectValueSetSearchOption = selectValueSetSearchOptionObj[i].value;");
out.println(" }");
out.println(" }");
out.println("");
out.println("");
out.println(" window.location.href=\"/ncitbrowser/pages/value_set_source_view.jsf?refresh=1\"");
out.println(" + \"&nav_type=valuesets\" + \"&opt=\"+ selectValueSetSearchOption;");
out.println("");
out.println(" }");
out.println(" </script>");
out.println("");
out.println(" <script language=\"JavaScript\">");
out.println("");
out.println(" var tree;");
out.println(" var nodeIndex;");
out.println(" var nodes = [];");
out.println("");
out.println(" function load(url,target) {");
out.println(" if (target != '')");
out.println(" target.window.location.href = url;");
out.println(" else");
out.println(" window.location.href = url;");
out.println(" }");
out.println("");
out.println(" function init() {");
out.println(" //initTree();");
out.println(" }");
out.println("");
out.println(" //handler for expanding all nodes");
out.println(" YAHOO.util.Event.on(\"expand_all\", \"click\", function(e) {");
out.println(" //expandEntireTree();");
out.println("");
out.println(" tree.expandAll();");
out.println(" //YAHOO.util.Event.preventDefault(e);");
out.println(" });");
out.println("");
out.println(" //handler for collapsing all nodes");
out.println(" YAHOO.util.Event.on(\"collapse_all\", \"click\", function(e) {");
out.println(" tree.collapseAll();");
out.println(" //YAHOO.util.Event.preventDefault(e);");
out.println(" });");
out.println("");
out.println(" //handler for checking all nodes");
out.println(" YAHOO.util.Event.on(\"check_all\", \"click\", function(e) {");
out.println(" check_all();");
out.println(" //YAHOO.util.Event.preventDefault(e);");
out.println(" });");
out.println("");
out.println(" //handler for unchecking all nodes");
out.println(" YAHOO.util.Event.on(\"uncheck_all\", \"click\", function(e) {");
out.println(" uncheck_all();");
out.println(" //YAHOO.util.Event.preventDefault(e);");
out.println(" });");
out.println("");
out.println("");
out.println("");
out.println(" YAHOO.util.Event.on(\"getchecked\", \"click\", function(e) {");
out.println(" //alert(\"Checked nodes: \" + YAHOO.lang.dump(getCheckedNodes()), \"info\", \"example\");");
out.println(" //YAHOO.util.Event.preventDefault(e);");
out.println("");
out.println(" });");
out.println("");
out.println("");
out.println(" function addTreeNode(rootNode, nodeInfo) {");
out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";");
out.println("");
out.println(" if (nodeInfo.ontology_node_id.indexOf(\"TVS_\") >= 0) {");
out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };");
out.println(" } else {");
out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };");
out.println(" }");
out.println("");
out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, false);");
out.println(" if (nodeInfo.ontology_node_child_count > 0) {");
out.println(" newNode.setDynamicLoad(loadNodeData);");
out.println(" }");
out.println(" }");
out.println("");
out.println(" function buildTree(ontology_node_id, ontology_display_name) {");
out.println(" var handleBuildTreeSuccess = function(o) {");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" if ( typeof(respObj) != \"undefined\") {");
out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {");
out.println(" var root = tree.getRoot();");
out.println(" if (respObj.root_nodes.length == 0) {");
out.println(" //showEmptyRoot();");
out.println(" }");
out.println(" else {");
out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {");
out.println(" var nodeInfo = respObj.root_nodes[i];");
out.println(" var expand = false;");
out.println(" //addTreeNode(root, nodeInfo, expand);");
out.println("");
out.println(" addTreeNode(root, nodeInfo);");
out.println(" }");
out.println(" }");
out.println("");
out.println(" tree.draw();");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
out.println(" var handleBuildTreeFailure = function(o) {");
out.println(" alert('responseFailure: ' + o.statusText);");
out.println(" }");
out.println("");
out.println(" var buildTreeCallback =");
out.println(" {");
out.println(" success:handleBuildTreeSuccess,");
out.println(" failure:handleBuildTreeFailure");
out.println(" };");
out.println("");
out.println(" if (ontology_display_name!='') {");
out.println(" var ontology_source = null;");
out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=build_src_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);");
out.println(" }");
out.println(" }");
out.println("");
out.println(" function resetTree(ontology_node_id, ontology_display_name) {");
out.println("");
out.println(" var handleResetTreeSuccess = function(o) {");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" if ( typeof(respObj) != \"undefined\") {");
out.println(" if ( typeof(respObj.root_node) != \"undefined\") {");
out.println(" var root = tree.getRoot();");
out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.root_node.ontology_node_id + \"');\";");
out.println(" var rootNodeData = { label:respObj.root_node.ontology_node_name, id:respObj.root_node.ontology_node_id, href:nodeDetails };");
out.println(" var expand = false;");
out.println(" if (respObj.root_node.ontology_node_child_count > 0) {");
out.println(" expand = true;");
out.println(" }");
out.println(" var ontRoot = new YAHOO.widget.TaskNode(rootNodeData, root, expand);");
out.println("");
out.println(" if ( typeof(respObj.child_nodes) != \"undefined\") {");
out.println(" for (var i=0; i < respObj.child_nodes.length; i++) {");
out.println(" var nodeInfo = respObj.child_nodes[i];");
out.println(" addTreeNode(ontRoot, nodeInfo);");
out.println(" }");
out.println(" }");
out.println(" tree.draw();");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
out.println(" var handleResetTreeFailure = function(o) {");
out.println(" alert('responseFailure: ' + o.statusText);");
out.println(" }");
out.println("");
out.println(" var resetTreeCallback =");
out.println(" {");
out.println(" success:handleResetTreeSuccess,");
out.println(" failure:handleResetTreeFailure");
out.println(" };");
out.println(" if (ontology_node_id!= '') {");
out.println(" var ontology_source = null;");
out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=reset_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name + '&version='+ ontology_version +'&ontology_source='+ontology_source,resetTreeCallback);");
out.println(" }");
out.println(" }");
out.println("");
out.println(" function onClickTreeNode(ontology_node_id) {");
out.println(" //alert(\"onClickTreeNode \" + ontology_node_id);");
out.println(" window.location = '/ncitbrowser/pages/value_set_treenode_redirect.jsf?ontology_node_id=' + ontology_node_id;");
out.println(" }");
out.println("");
out.println("");
out.println(" function onClickViewEntireOntology(ontology_display_name) {");
out.println(" var ontology_display_name = document.pg_form.ontology_display_name.value;");
out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");");
out.println(" tree.draw();");
out.println(" }");
out.println("");
out.println(" function initTree() {");
out.println("");
out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");");
//out.println(" pre_check();");
out.println(" tree.setNodesProperty('propagateHighlightUp',true);");
out.println(" tree.setNodesProperty('propagateHighlightDown',true);");
out.println(" tree.subscribe('keydown',tree._onKeyDownEvent);");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" tree.subscribe(\"expand\", function(node) {");
out.println("");
out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 39 });");
out.println("");
out.println(" });");
out.println("");
out.println("");
out.println("");
out.println(" tree.subscribe(\"collapse\", function(node) {");
out.println(" //alert(\"Collapsing \" + node.label );");
out.println("");
out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 109 });");
out.println(" });");
out.println("");
out.println(" // By default, trees with TextNodes will fire an event for when the label is clicked:");
out.println(" tree.subscribe(\"checkClick\", function(node) {");
out.println(" //alert(node.data.myNodeId + \" label was checked\");");
out.println(" });");
out.println("");
out.println("");
println(out, " var root = tree.getRoot();");
HashMap value_set_tree_hmap = DataUtils.getCodingSchemeValueSetTree();
TreeItem root = (TreeItem) value_set_tree_hmap.get("<Root>");
new ValueSetUtils().printTree(out, root, Constants.TERMINOLOGY_VIEW, dictionary);
//new ValueSetUtils().printTree(out, root, Constants.TERMINOLOGY_VIEW);
String contextPath = request.getContextPath();
String view_str = new Integer(view).toString();
//String option = (String) request.getSession().getAttribute("selectValueSetSearchOption");
//String algorithm = (String) request.getSession().getAttribute("valueset_search_algorithm");
String option = (String) request.getParameter("selectValueSetSearchOption");
String algorithm = (String) request.getParameter("valueset_search_algorithm");
String option_code = "";
String option_name = "";
if (DataUtils.isNull(option)) {
option_code = "checked";
} else {
if (option.compareToIgnoreCase("Code") == 0) {
option_code = "checked";
}
if (option.compareToIgnoreCase("Name") == 0) {
option_name = "checked";
}
}
String algorithm_exactMatch = "";
String algorithm_startsWith = "";
String algorithm_contains = "";
if (DataUtils.isNull(algorithm)) {
algorithm_exactMatch = "checked";
} else {
if (algorithm.compareToIgnoreCase("exactMatch") == 0) {
algorithm_exactMatch = "checked";
}
if (algorithm.compareToIgnoreCase("startsWith") == 0) {
algorithm_startsWith = "checked";
}
if (algorithm.compareToIgnoreCase("contains") == 0) {
algorithm_contains = "checked";
}
}
out.println("");
if (message == null) {
out.println(" tree.collapseAll();");
}
out.println(" initializeNodeCheckState();");
out.println(" tree.draw();");
out.println(" }");
out.println("");
out.println("");
out.println(" function onCheckClick(node) {");
out.println(" YAHOO.log(node.label + \" check was clicked, new state: \" + node.checkState, \"info\", \"example\");");
out.println(" }");
out.println("");
out.println(" function check_all() {");
out.println(" var topNodes = tree.getRoot().children;");
out.println(" for(var i=0; i<topNodes.length; ++i) {");
out.println(" topNodes[i].check();");
out.println(" }");
out.println(" }");
out.println("");
out.println(" function uncheck_all() {");
out.println(" var topNodes = tree.getRoot().children;");
out.println(" for(var i=0; i<topNodes.length; ++i) {");
out.println(" topNodes[i].uncheck();");
out.println(" }");
out.println(" }");
out.println("");
out.println("");
out.println("");
out.println(" function expand_all() {");
out.println(" //alert(\"expand_all\");");
out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;");
out.println(" onClickViewEntireOntology(ontology_display_name);");
out.println(" }");
out.println("");
out.println(" function pre_check() {");
out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;");
//out.println(" alert(ontology_display_name);");
out.println(" var topNodes = tree.getRoot().children;");
out.println(" for(var i=0; i<topNodes.length; ++i) {");
out.println(" if (topNodes[i].label == ontology_display_name) {");
out.println(" topNodes[i].check();");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
// 0=unchecked, 1=some children checked, 2=all children checked
/*
function getCheckedNodes(nodes) {
nodes = nodes || tree.getRoot().children;
checkedNodes = [];
for(var i=0, l=nodes.length; i<l; i=i+1) {
var n = nodes[i];
//if (n.checkState > 0) { // if we were interested in the nodes that have some but not all children checked
if (n.checkState == 2) {
checkedNodes.push(n.label); // just using label for simplicity
}
if (n.hasChildren()) {
checkedNodes = checkedNodes.concat(getCheckedNodes(n.children));
}
}
//var checked_vocabularies = document.forms["valueSetSearchForm"].checked_vocabularies;
//checked_vocabularies.value = checkedNodes;
return checkedNodes;
}
*/
out.println(" function getCheckedVocabularies(nodes) {");
out.println(" getCheckedNodes(nodes);");
out.println(" getPartialCheckedNodes(nodes);");
out.println(" }");
writeInitialize(out);
initializeNodeCheckState(out);
out.println(" // Gets the labels of all of the fully checked nodes");
out.println(" // Could be updated to only return checked leaf nodes by evaluating");
out.println(" // the children collection first.");
out.println(" function getCheckedNodes(nodes) {");
out.println(" nodes = nodes || tree.getRoot().children;");
out.println(" var checkedNodes = [];");
out.println(" for(var i=0, l=nodes.length; i<l; i=i+1) {");
out.println(" var n = nodes[i];");
out.println(" if (n.checkState == 2) {");
out.println(" checkedNodes.push(n.label); // just using label for simplicity");
out.println(" }");
out.println(" if (n.hasChildren()) {");
out.println(" checkedNodes = checkedNodes.concat(getCheckedNodes(n.children));");
out.println(" }");
out.println(" }");
//out.println(" checkedNodes = checkedNodes.concat(\",\");");
out.println(" var checked_vocabularies = document.forms[\"valueSetSearchForm\"].checked_vocabularies;");
out.println(" checked_vocabularies.value = checkedNodes;");
out.println(" return checkedNodes;");
out.println(" }");
out.println(" function getPartialCheckedNodes(nodes) {");
out.println(" nodes = nodes || tree.getRoot().children;");
out.println(" var checkedNodes = [];");
out.println(" for(var i=0, l=nodes.length; i<l; i=i+1) {");
out.println(" var n = nodes[i];");
out.println(" if (n.checkState == 1) {");
out.println(" checkedNodes.push(n.label); // just using label for simplicity");
out.println(" }");
out.println(" if (n.hasChildren()) {");
out.println(" checkedNodes = checkedNodes.concat(getPartialCheckedNodes(n.children));");
out.println(" }");
out.println(" }");
//out.println(" checkedNodes = checkedNodes.concat(\",\");");
out.println(" var partial_checked_vocabularies = document.forms[\"valueSetSearchForm\"].partial_checked_vocabularies;");
out.println(" partial_checked_vocabularies.value = checkedNodes;");
out.println(" return checkedNodes;");
out.println(" }");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" function loadNodeData(node, fnLoadComplete) {");
out.println(" var id = node.data.id;");
out.println("");
out.println(" var responseSuccess = function(o)");
out.println(" {");
out.println(" var path;");
out.println(" var dirs;");
out.println(" var files;");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" var fileNum = 0;");
out.println(" var categoryNum = 0;");
out.println(" if ( typeof(respObj.nodes) != \"undefined\") {");
out.println(" for (var i=0; i < respObj.nodes.length; i++) {");
out.println(" var name = respObj.nodes[i].ontology_node_name;");
out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";");
out.println(" var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };");
out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, node, false);");
out.println(" if (respObj.nodes[i].ontology_node_child_count > 0) {");
out.println(" newNode.setDynamicLoad(loadNodeData);");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" tree.draw();");
out.println(" fnLoadComplete();");
out.println(" }");
out.println("");
out.println(" var responseFailure = function(o){");
out.println(" alert('responseFailure: ' + o.statusText);");
out.println(" }");
out.println("");
out.println(" var callback =");
out.println(" {");
out.println(" success:responseSuccess,");
out.println(" failure:responseFailure");
out.println(" };");
out.println("");
out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;");
out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
out.println(" var cObj = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_src_vs_tree&ontology_node_id=' +id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version,callback);");
out.println(" }");
out.println("");
out.println("");
out.println(" function searchTree(ontology_node_id, ontology_display_name) {");
out.println("");
out.println(" var handleBuildTreeSuccess = function(o) {");
out.println("");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" if ( typeof(respObj) != \"undefined\") {");
out.println("");
out.println(" if ( typeof(respObj.dummy_root_nodes) != \"undefined\") {");
out.println(" showNodeNotFound(ontology_node_id);");
out.println(" }");
out.println("");
out.println(" else if ( typeof(respObj.root_nodes) != \"undefined\") {");
out.println(" var root = tree.getRoot();");
out.println(" if (respObj.root_nodes.length == 0) {");
out.println(" //showEmptyRoot();");
out.println(" }");
out.println(" else {");
out.println(" showPartialHierarchy();");
out.println(" showConstructingTreeStatus();");
out.println("");
out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {");
out.println(" var nodeInfo = respObj.root_nodes[i];");
out.println(" //var expand = false;");
out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
out.println(" var handleBuildTreeFailure = function(o) {");
out.println(" alert('responseFailure: ' + o.statusText);");
out.println(" }");
out.println("");
out.println(" var buildTreeCallback =");
out.println(" {");
out.println(" success:handleBuildTreeSuccess,");
out.println(" failure:handleBuildTreeFailure");
out.println(" };");
out.println("");
out.println(" if (ontology_display_name!='') {");
out.println(" var ontology_source = null;//document.pg_form.ontology_source.value;");
out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=search_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);");
out.println("");
out.println(" }");
out.println(" }");
out.println("");
out.println("");
out.println("");
out.println(" function expandEntireTree() {");
out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");");
out.println(" //tree.draw();");
out.println("");
out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;");
out.println(" var ontology_node_id = document.forms[\"pg_form\"].ontology_node_id.value;");
out.println("");
out.println(" var handleBuildTreeSuccess = function(o) {");
out.println("");
out.println(" var respTxt = o.responseText;");
out.println(" var respObj = eval('(' + respTxt + ')');");
out.println(" if ( typeof(respObj) != \"undefined\") {");
out.println("");
out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {");
out.println("");
out.println(" //alert(respObj.root_nodes.length);");
out.println("");
out.println(" var root = tree.getRoot();");
out.println(" if (respObj.root_nodes.length == 0) {");
out.println(" //showEmptyRoot();");
out.println(" } else {");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {");
out.println(" var nodeInfo = respObj.root_nodes[i];");
out.println(" //alert(\"calling addTreeBranch \");");
out.println("");
out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
out.println(" var handleBuildTreeFailure = function(o) {");
out.println(" alert('responseFailure: ' + o.statusText);");
out.println(" }");
out.println("");
out.println(" var buildTreeCallback =");
out.println(" {");
out.println(" success:handleBuildTreeSuccess,");
out.println(" failure:handleBuildTreeFailure");
out.println(" };");
out.println("");
out.println(" if (ontology_display_name!='') {");
out.println(" var ontology_source = null;");
out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;");
out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_entire_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);");
out.println("");
out.println(" }");
out.println(" }");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" function addTreeBranch(ontology_node_id, rootNode, nodeInfo) {");
out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";");
out.println("");
out.println(" var newNodeData;");
out.println(" if (ontology_node_id.indexOf(\"TVS_\") >= 0) {");
out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };");
out.println(" } else {");
out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };");
out.println(" }");
out.println("");
out.println(" var expand = false;");
out.println(" var childNodes = nodeInfo.children_nodes;");
out.println("");
out.println(" if (childNodes.length > 0) {");
out.println(" expand = true;");
out.println(" }");
out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, expand);");
out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {");
out.println(" newNode.labelStyle = \"ygtvlabel_highlight\";");
out.println(" }");
out.println("");
out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {");
out.println(" newNode.isLeaf = true;");
out.println(" if (nodeInfo.ontology_node_child_count > 0) {");
out.println(" newNode.isLeaf = false;");
out.println(" newNode.setDynamicLoad(loadNodeData);");
out.println(" } else {");
out.println(" tree.draw();");
out.println(" }");
out.println("");
out.println(" } else {");
out.println(" if (nodeInfo.ontology_node_id != ontology_node_id) {");
out.println(" if (nodeInfo.ontology_node_child_count == 0 && nodeInfo.ontology_node_id != ontology_node_id) {");
out.println(" newNode.isLeaf = true;");
out.println(" } else if (childNodes.length == 0) {");
out.println(" newNode.setDynamicLoad(loadNodeData);");
out.println(" }");
out.println(" }");
out.println(" }");
out.println("");
out.println(" tree.draw();");
out.println(" for (var i=0; i < childNodes.length; i++) {");
out.println(" var childnodeInfo = childNodes[i];");
out.println(" addTreeBranch(ontology_node_id, newNode, childnodeInfo);");
out.println(" }");
out.println(" }");
out.println(" YAHOO.util.Event.addListener(window, \"load\", init);");
out.println("");
out.println(" YAHOO.util.Event.onDOMReady(initTree);");
out.println("");
out.println("");
out.println(" </script>");
out.println("");
out.println("</head>");
out.println("");
out.println("");
out.println("");
out.println("");
out.println("");
//out.println("<body>");
out.println("<body onLoad=\"document.forms.valueSetSearchForm.matchText.focus();\">");
//out.println("<body onLoad=\"initialize();\">");
out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/wz_tooltip.js\"></script>");
out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_centerwindow.js\"></script>");
out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_followscroll.js\"></script>");
out.println("");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" <!-- Begin Skip Top Navigation -->");
out.println(" <a href=\"#evs-content\" class=\"hideLink\" accesskey=\"1\" title=\"Skip repetitive navigation links\">skip navigation links</A>");
out.println(" <!-- End Skip Top Navigation -->");
out.println("");
out.println("<!-- nci banner -->");
out.println("<div class=\"ncibanner\">");
out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">");
out.println(" <img src=\"/ncitbrowser/images/logotype.gif\"");
out.println(" width=\"440\" height=\"39\" border=\"0\"");
out.println(" alt=\"National Cancer Institute\"/>");
out.println(" </a>");
out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">");
out.println(" <img src=\"/ncitbrowser/images/spacer.gif\"");
out.println(" width=\"48\" height=\"39\" border=\"0\"");
out.println(" alt=\"National Cancer Institute\" class=\"print-header\"/>");
out.println(" </a>");
out.println(" <a href=\"http://www.nih.gov\" target=\"_blank\" >");
out.println(" <img src=\"/ncitbrowser/images/tagline_nologo.gif\"");
out.println(" width=\"173\" height=\"39\" border=\"0\"");
out.println(" alt=\"U.S. National Institutes of Health\"/>");
out.println(" </a>");
out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">");
out.println(" <img src=\"/ncitbrowser/images/cancer-gov.gif\"");
out.println(" width=\"99\" height=\"39\" border=\"0\"");
out.println(" alt=\"www.cancer.gov\"/>");
out.println(" </a>");
out.println("</div>");
out.println("<!-- end nci banner -->");
out.println("");
out.println(" <div class=\"center-page\">");
out.println(" <!-- EVS Logo -->");
out.println("<div>");
// to be modified
out.println(" <img src=\"/ncitbrowser/images/evs-logo-swapped.gif\" alt=\"EVS Logo\"");
out.println(" width=\"745\" height=\"26\" border=\"0\"");
out.println(" usemap=\"#external-evs\" />");
out.println(" <map id=\"external-evs\" name=\"external-evs\">");
out.println(" <area shape=\"rect\" coords=\"0,0,140,26\"");
out.println(" href=\"/ncitbrowser/start.jsf\" target=\"_self\"");
out.println(" alt=\"NCI Term Browser\" />");
out.println(" <area shape=\"rect\" coords=\"520,0,745,26\"");
out.println(" href=\"http://evs.nci.nih.gov/\" target=\"_blank\"");
out.println(" alt=\"Enterprise Vocabulary Services\" />");
out.println(" </map>");
out.println("</div>");
out.println("");
out.println("");
out.println("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">");
out.println(" <tr>");
out.println(" <td width=\"5\"></td>");
//to be modified
out.println(" <td><a href=\"/ncitbrowser/pages/multiple_search.jsf?nav_type=terminologies\">");
out.println(" <img name=\"tab_terms\" src=\"/ncitbrowser/images/tab_terms_clicked.gif\"");
out.println(" border=\"0\" alt=\"Terminologies\" title=\"Terminologies\" /></a></td>");
out.println(" <td><a href=\"/ncitbrowser/ajax?action=create_src_vs_tree\">");
out.println(" <img name=\"tab_valuesets\" src=\"/ncitbrowser/images/tab_valuesets.gif\"");
out.println(" border=\"0\" alt=\"Value Sets\" title=\"ValueSets\" /></a></td>");
out.println(" <td><a href=\"/ncitbrowser/pages/mapping_search.jsf?nav_type=mappings\">");
out.println(" <img name=\"tab_map\" src=\"/ncitbrowser/images/tab_map.gif\"");
out.println(" border=\"0\" alt=\"Mappings\" title=\"Mappings\" /></a></td>");
out.println(" </tr>");
out.println("</table>");
out.println("");
out.println("<div class=\"mainbox-top\"><img src=\"/ncitbrowser/images/mainbox-top.gif\" width=\"745\" height=\"5\" alt=\"\"/></div>");
out.println("<!-- end EVS Logo -->");
out.println(" <!-- Main box -->");
out.println(" <div id=\"main-area\">");
out.println("");
out.println(" <!-- Thesaurus, banner search area -->");
out.println(" <div class=\"bannerarea\">");
/*
out.println(" <a href=\"/ncitbrowser/start.jsf\" style=\"text-decoration: none;\">");
out.println(" <div class=\"vocabularynamebanner_tb\">");
out.println(" <span class=\"vocabularynamelong_tb\">" + JSPUtils.getApplicationVersionDisplay() + "</span>");
out.println(" </div>");
out.println(" </a>");
*/
JSPUtils.JSPHeaderInfoMore info = new JSPUtils.JSPHeaderInfoMore(request);
String scheme = info.dictionary;
String term_browser_version = info.term_browser_version;
String display_name = info.display_name;
String basePath = request.getContextPath();
/*
<a href="/ncitbrowser/pages/home.jsf?version=12.02d" style="text-decoration: none;">
<div class="vocabularynamebanner_ncit">
<span class="vocabularynamelong_ncit">Version: 12.02d (Release date: 2012-02-27-08:00)</span>
</div>
</a>
*/
String release_date = DataUtils.getVersionReleaseDate(scheme, version);
if (dictionary != null && dictionary.compareTo("NCI Thesaurus") == 0) {
out.println("<a href=\"/ncitbrowser/pages/home.jsf?version=" + version + "\" style=\"text-decoration: none;\">");
out.println(" <div class=\"vocabularynamebanner_ncit\">");
out.println(" <span class=\"vocabularynamelong_ncit\">Version: " + version + " (Release date: " + release_date + ")</span>");
out.println(" </div>");
out.println("</a>");
/*
out.write("\r\n");
out.write(" <div class=\"banner\"><a href=\"");
out.print(basePath);
out.write("\"><img src=\"");
out.print(basePath);
out.write("/images/thesaurus_browser_logo.jpg\" width=\"383\" height=\"117\" alt=\"Thesaurus Browser Logo\" border=\"0\"/></a></div>\r\n");
*/
} else {
out.write("\r\n");
out.write("\r\n");
out.write(" ");
if (version == null) {
out.write("\r\n");
out.write(" <a class=\"vocabularynamebanner\" href=\"");
out.print(request.getContextPath());
out.write("/pages/vocabulary.jsf?dictionary=");
out.print(HTTPUtils.cleanXSS(dictionary));
out.write("\">\r\n");
out.write(" ");
} else {
out.write("\r\n");
out.write(" <a class=\"vocabularynamebanner\" href=\"");
out.print(request.getContextPath());
out.write("/pages/vocabulary.jsf?dictionary=");
out.print(HTTPUtils.cleanXSS(dictionary));
out.write("&version=");
out.print(HTTPUtils.cleanXSS(version));
out.write("\">\r\n");
out.write(" ");
}
out.write("\r\n");
out.write(" <div class=\"vocabularynamebanner\">\r\n");
out.write(" <div class=\"vocabularynameshort\" STYLE=\"font-size: ");
out.print(HTTPUtils.maxFontSize(display_name));
out.write("px; font-family : Arial\">\r\n");
out.write(" ");
out.print(HTTPUtils.cleanXSS(display_name));
out.write("\r\n");
out.write(" </div>\r\n");
out.write(" \r\n");
boolean display_release_date = true;
if (release_date == null || release_date.compareTo("") == 0) {
display_release_date = false;
}
if (display_release_date) {
out.write("\r\n");
out.write(" <div class=\"vocabularynamelong\">Version: ");
out.print(HTTPUtils.cleanXSS(term_browser_version));
out.write(" (Release date: ");
out.print(release_date);
out.write(")</div>\r\n");
} else {
out.write("\r\n");
out.write(" <div class=\"vocabularynamelong\">Version: ");
out.print(HTTPUtils.cleanXSS(term_browser_version));
out.write("</div>\r\n");
}
out.write(" \r\n");
out.write(" \r\n");
out.write(" </div>\r\n");
out.write(" </a>\r\n");
}
out.println(" <div class=\"search-globalnav\">");
out.println(" <!-- Search box -->");
out.println(" <div class=\"searchbox-top\"><img src=\"/ncitbrowser/images/searchbox-top.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Top\" /></div>");
out.println(" <div class=\"searchbox\">");
out.println("");
out.println("");
out.println("<form id=\"valueSetSearchForm\" name=\"valueSetSearchForm\" method=\"post\" action=\"" + contextPath + "/ajax?action=search_value_set\" class=\"search-form-main-area\" enctype=\"application/x-www-form-urlencoded\">");
out.println("<input type=\"hidden\" name=\"valueSetSearchForm\" value=\"valueSetSearchForm\" />");
out.println("<input type=\"hidden\" name=\"view\" value=\"" + view_str + "\" />");
String matchText = (String) request.getSession().getAttribute("matchText");
if (DataUtils.isNull(matchText)) {
matchText = "";
}
out.println("");
out.println("");
out.println("");
out.println(" <input type=\"hidden\" id=\"checked_vocabularies\" name=\"checked_vocabularies\" value=\"\" />");
out.println(" <input type=\"hidden\" id=\"partial_checked_vocabularies\" name=\"partial_checked_vocabularies\" value=\"\" />");
out.println("");
out.println("");
out.println("");
out.println("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 2px\" >");
out.println(" <tr valign=\"top\" align=\"left\">");
out.println(" <td align=\"left\" class=\"textbody\">");
out.println("");
out.println(" <input CLASS=\"searchbox-input-2\"");
out.println(" name=\"matchText\"");
out.println(" value=\"" + matchText + "\"");
out.println(" onFocus=\"active = true\"");
out.println(" onBlur=\"active = false\"");
out.println(" onkeypress=\"return submitEnter('valueSetSearchForm:valueset_search',event)\"");
out.println(" tabindex=\"1\"/>");
out.println("");
out.println("");
out.println(" <input id=\"valueSetSearchForm:valueset_search\" type=\"image\" src=\"/ncitbrowser/images/search.gif\" name=\"valueSetSearchForm:valueset_search\" alt=\"Search Value Sets\" onclick=\"javascript:getCheckedVocabularies();\" tabindex=\"2\" class=\"searchbox-btn\" /><a href=\"/ncitbrowser/pages/help.jsf#searchhelp\" tabindex=\"3\"><img src=\"/ncitbrowser/images/search-help.gif\" alt=\"Search Help\" style=\"border-width:0;\" class=\"searchbox-btn\" /></a>");
out.println("");
out.println("");
out.println(" </td>");
out.println(" </tr>");
out.println("");
out.println(" <tr valign=\"top\" align=\"left\">");
out.println(" <td>");
out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 0px\">");
out.println("");
out.println(" <tr valign=\"top\" align=\"left\">");
out.println(" <td align=\"left\" class=\"textbody\">");
out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"exactMatch\" alt=\"Exact Match\" " + algorithm_exactMatch + " tabindex=\"3\">Exact Match ");
out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"startsWith\" alt=\"Begins With\" " + algorithm_startsWith + " tabindex=\"3\">Begins With ");
out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"contains\" alt=\"Contains\" " + algorithm_contains + " tabindex=\"3\">Contains");
out.println(" </td>");
out.println(" </tr>");
out.println("");
out.println(" <tr align=\"left\">");
out.println(" <td height=\"1px\" bgcolor=\"#2F2F5F\" align=\"left\"></td>");
out.println(" </tr>");
out.println(" <tr valign=\"top\" align=\"left\">");
out.println(" <td align=\"left\" class=\"textbody\">");
out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Code\" " + option_code + " alt=\"Code\" tabindex=\"1\" >Code ");
out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Name\" " + option_name + " alt=\"Name\" tabindex=\"1\" >Name");
out.println(" </td>");
out.println(" </tr>");
out.println(" </table>");
out.println(" </td>");
out.println(" </tr>");
out.println("</table>");
out.println(" <input type=\"hidden\" name=\"referer\" id=\"referer\" value=\"http%3A%2F%2Flocalhost%3A8080%2Fncitbrowser%2Fpages%2Fresolved_value_set_search_results.jsf\">");
out.println(" <input type=\"hidden\" id=\"nav_type\" name=\"nav_type\" value=\"valuesets\" />");
out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />");
out.println(" <input type=\"hidden\" id=\"ontology_display_name\" name=\"ontology_display_name\" value=\"" + dictionary + "\" />");
out.println(" <input type=\"hidden\" id=\"schema\" name=\"schema\" value=\"" + dictionary + "\" />");
out.println(" <input type=\"hidden\" id=\"ontology_version\" name=\"ontology_version\" value=\"" + version + "\" />");
out.println("");
out.println("<input type=\"hidden\" name=\"javax.faces.ViewState\" id=\"javax.faces.ViewState\" value=\"j_id22:j_id23\" />");
out.println("</form>");
addHiddenForm(out, checked_vocabularies, partial_checked_vocabularies);
out.println(" </div> <!-- searchbox -->");
out.println("");
out.println(" <div class=\"searchbox-bottom\"><img src=\"/ncitbrowser/images/searchbox-bottom.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Bottom\" /></div>");
out.println(" <!-- end Search box -->");
out.println(" <!-- Global Navigation -->");
out.println("");
/*
out.println("<table class=\"global-nav\" border=\"0\" width=\"100%\" height=\"37px\" cellpadding=\"0\" cellspacing=\"0\">");
out.println(" <tr>");
out.println(" <td align=\"left\" valign=\"bottom\">");
out.println(" <a href=\"#\" onclick=\"javascript:window.open('/ncitbrowser/pages/source_help_info-termbrowser.jsf',");
out.println(" '_blank','top=100, left=100, height=740, width=780, status=no, menubar=no, resizable=yes, scrollbars=yes, toolbar=no, location=no, directories=no');\" tabindex=\"13\">");
out.println(" Sources</a>");
out.println("");
out.println(" \r\n");
out.println(" ");
out.print( VisitedConceptUtils.getDisplayLink(request, true) );
out.println(" \r\n");
out.println(" </td>");
out.println(" <td align=\"right\" valign=\"bottom\">");
out.println(" <a href=\"");
out.print( request.getContextPath() );
out.println("/pages/help.jsf\" tabindex=\"16\">Help</a>\r\n");
out.println(" </td>\r\n");
out.println(" <td width=\"7\"></td>\r\n");
out.println(" </tr>\r\n");
out.println("</table>");
*/
boolean hasValueSet = ValueSetHierarchy.hasValueSet(scheme);
boolean hasMapping = DataUtils.hasMapping(scheme);
boolean tree_access_allowed = true;
if (DataUtils._vocabulariesWithoutTreeAccessHashSet.contains(scheme)) {
tree_access_allowed = false;
}
boolean vocabulary_isMapping = DataUtils.isMapping(scheme, null);
out.write(" <table class=\"global-nav\" border=\"0\" width=\"100%\" height=\"30px\" cellpadding=\"0\" cellspacing=\"0\">\r\n");
out.write(" <tr>\r\n");
out.write(" <td valign=\"bottom\">\r\n");
out.write(" ");
Boolean[] isPipeDisplayed = new Boolean[] { Boolean.FALSE };
out.write("\r\n");
out.write(" ");
if (vocabulary_isMapping) {
out.write("\r\n");
out.write(" ");
out.print( JSPUtils.getPipeSeparator(isPipeDisplayed) );
out.write("\r\n");
out.write(" <a href=\"");
out.print(request.getContextPath() );
out.write("/pages/mapping.jsf?dictionary=");
out.print(HTTPUtils.cleanXSS(scheme));
out.write("&version=");
out.print(version);
out.write("\">\r\n");
out.write(" Mapping\r\n");
out.write(" </a>\r\n");
out.write(" ");
} else if (tree_access_allowed) {
out.write("\r\n");
out.write(" ");
out.print( JSPUtils.getPipeSeparator(isPipeDisplayed) );
out.write("\r\n");
out.write(" <a href=\"#\" onclick=\"javascript:window.open('");
out.print(request.getContextPath());
out.write("/pages/hierarchy.jsf?dictionary=");
out.print(HTTPUtils.cleanXSS(scheme));
out.write("&version=");
out.print(HTTPUtils.cleanXSS(version));
out.write("', '_blank','top=100, left=100, height=740, width=680, status=no, menubar=no, resizable=yes, scrollbars=yes, toolbar=no, location=no, directories=no');\" tabindex=\"12\">\r\n");
out.write(" Hierarchy </a>\r\n");
out.write(" ");
}
out.write(" \r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write(" ");
if (hasValueSet) {
out.write("\r\n");
out.write(" ");
out.print( JSPUtils.getPipeSeparator(isPipeDisplayed) );
out.write("\r\n");
out.write(" <!--\r\n");
out.write(" <a href=\"");
out.print( request.getContextPath() );
out.write("/pages/value_set_hierarchy.jsf?dictionary=");
out.print(HTTPUtils.cleanXSS(scheme));
out.write("&version=");
out.print(HTTPUtils.cleanXSS(version));
out.write("\" tabindex=\"15\">Value Sets</a>\r\n");
out.write(" -->\r\n");
out.write(" <a href=\"");
out.print( request.getContextPath() );
out.write("/ajax?action=create_cs_vs_tree&dictionary=");
out.print(HTTPUtils.cleanXSS(scheme));
out.write("&version=");
out.print(HTTPUtils.cleanXSS(version));
out.write("\" tabindex=\"15\">Value Sets</a>\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" ");
}
out.write("\r\n");
out.write(" \r\n");
out.write(" ");
if (hasMapping) {
out.write("\r\n");
out.write(" ");
out.print( JSPUtils.getPipeSeparator(isPipeDisplayed) );
out.write("\r\n");
out.write(" <a href=\"");
out.print( request.getContextPath() );
out.write("/pages/cs_mappings.jsf?dictionary=");
out.print(HTTPUtils.cleanXSS(scheme));
out.write("&version=");
out.print(HTTPUtils.cleanXSS(version));
out.write("\" tabindex=\"15\">Maps</a> \r\n");
out.write(" ");
}
String cart_size = (String) request.getSession().getAttribute("cart_size");
if (!DataUtils.isNull(cart_size)) {
out.write("|");
out.write(" <a href=\"");
out.print(request.getContextPath());
out.write("/pages/cart.jsf\" tabindex=\"16\">Cart</a>\r\n");
}
out.write(" ");
out.print( VisitedConceptUtils.getDisplayLink(request, isPipeDisplayed) );
out.write("\r\n");
out.write(" </td>\r\n");
out.write(" <td align=\"right\" valign=\"bottom\">\r\n");
out.write(" <a href=\"");
out.print(request.getContextPath());
out.write("/pages/help.jsf\" tabindex=\"16\">Help</a>\r\n");
out.write(" </td>\r\n");
out.write(" <td width=\"7\" valign=\"bottom\"></td>\r\n");
out.write(" </tr>\r\n");
out.write(" </table>\r\n");
out.println(" <!-- end Global Navigation -->");
out.println("");
out.println(" </div> <!-- search-globalnav -->");
out.println(" </div> <!-- bannerarea -->");
out.println("");
out.println(" <!-- end Thesaurus, banner search area -->");
out.println(" <!-- Quick links bar -->");
out.println("");
out.println("<div class=\"bluebar\">");
out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
out.println(" <tr>");
out.println(" <td><div class=\"quicklink-status\"> </div></td>");
out.println(" <td>");
out.println("");
/*
out.println(" <div id=\"quicklinksholder\">");
out.println(" <ul id=\"quicklinks\"");
out.println(" onmouseover=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-active.gif';\"");
out.println(" onmouseout=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-inactive.gif';\">");
out.println(" <li>");
out.println(" <a href=\"#\" tabindex=\"-1\"><img src=\"/ncitbrowser/images/quicklinks-inactive.gif\" width=\"162\"");
out.println(" height=\"18\" border=\"0\" name=\"quicklinksimg\" alt=\"Quick Links\" />");
out.println(" </a>");
out.println(" <ul>");
out.println(" <li><a href=\"http://evs.nci.nih.gov/\" tabindex=\"-1\" target=\"_blank\"");
out.println(" alt=\"Enterprise Vocabulary Services\">EVS Home</a></li>");
out.println(" <li><a href=\"http://localhost/ncimbrowserncimbrowser\" tabindex=\"-1\" target=\"_blank\"");
out.println(" alt=\"NCI Metathesaurus\">NCI Metathesaurus Browser</a></li>");
out.println("");
out.println(" <li><a href=\"/ncitbrowser/start.jsf\" tabindex=\"-1\"");
out.println(" alt=\"NCI Term Browser\">NCI Term Browser</a></li>");
out.println(" <li><a href=\"http://www.cancer.gov/cancertopics/terminologyresources\" tabindex=\"-1\" target=\"_blank\"");
out.println(" alt=\"NCI Terminology Resources\">NCI Terminology Resources</a></li>");
out.println("");
out.println(" <li><a href=\"http://ncitermform.nci.nih.gov/ncitermform/?dictionary=NCI%20Thesaurus\" tabindex=\"-1\" target=\"_blank\" alt=\"Term Suggestion\">Term Suggestion</a></li>");
out.println("");
out.println("");
out.println(" </ul>");
out.println(" </li>");
out.println(" </ul>");
out.println(" </div>");
*/
addQuickLink(request, out);
out.println("");
out.println(" </td>");
out.println(" </tr>");
out.println(" </table>");
out.println("");
out.println("</div>");
if (! ServerMonitorThread.getInstance().isLexEVSRunning()) {
out.println(" <div class=\"redbar\">");
out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
out.println(" <tr>");
out.println(" <td class=\"lexevs-status\">");
out.println(" " + ServerMonitorThread.getInstance().getMessage());
out.println(" </td>");
out.println(" </tr>");
out.println(" </table>");
out.println(" </div>");
}
out.println(" <!-- end Quick links bar -->");
out.println("");
out.println(" <!-- Page content -->");
out.println(" <div class=\"pagecontent\">");
out.println("");
if (message != null) {
out.println("\r\n");
out.println(" <p class=\"textbodyred\">");
out.print(message);
out.println("</p>\r\n");
out.println(" ");
request.getSession().removeAttribute("message");
}
// to be modified
/*
out.println("<p class=\"textbody\">");
out.println("View value sets organized by standards category or source terminology.");
out.println("Standards categories group the value sets supporting them; all other labels lead to the home pages of actual value sets or source terminologies.");
out.println("Search or browse a value set from its home page, or search all value sets at once from this page (very slow) to find which ones contain a particular code or term.");
out.println("</p>");
*/
out.println("");
out.println(" <div id=\"popupContentArea\">");
out.println(" <a name=\"evs-content\" id=\"evs-content\"></a>");
out.println("");
out.println(" <table width=\"580px\" cellpadding=\"3\" cellspacing=\"0\" border=\"0\">");
out.println("");
out.println("");
out.println("");
out.println("");
out.println(" <tr class=\"textbody\">");
out.println(" <td class=\"textbody\" align=\"left\">");
out.println("");
/*
if (view == Constants.STANDARD_VIEW) {
out.println(" Standards View");
out.println(" |");
out.println(" <a href=\"" + contextPath + "/ajax?action=create_cs_vs_tree\">Terminology View</a>");
} else {
out.println(" <a href=\"" + contextPath + "/ajax?action=create_src_vs_tree\">Standards View</a>");
out.println(" |");
out.println(" Terminology View");
}
*/
out.println(" </td>");
out.println("");
out.println(" <td align=\"right\">");
out.println(" <font size=\"1\" color=\"red\" align=\"right\">");
out.println(" <a href=\"javascript:printPage()\"><img src=\"/ncitbrowser/images/printer.bmp\" border=\"0\" alt=\"Send to Printer\"><i>Send to Printer</i></a>");
out.println(" </font>");
out.println(" </td>");
out.println(" </tr>");
out.println(" </table>");
out.println("");
out.println(" <hr/>");
out.println("");
out.println("");
out.println("");
out.println("<style>");
out.println("#expandcontractdiv {border:1px solid #336600; background-color:#FFFFCC; margin:0 0 .5em 0; padding:0.2em;}");
out.println("#treecontainer { background: #fff }");
out.println("</style>");
out.println("");
out.println("");
out.println("<div id=\"expandcontractdiv\">");
out.println(" <a id=\"expand_all\" href=\"#\">Expand all</a>");
out.println(" <a id=\"collapse_all\" href=\"#\">Collapse all</a>");
out.println(" <a id=\"check_all\" href=\"#\">Check all</a>");
out.println(" <a id=\"uncheck_all\" href=\"#\">Uncheck all</a>");
out.println("</div>");
out.println("");
out.println("");
out.println("");
out.println(" <!-- Tree content -->");
out.println("");
out.println(" <div id=\"treecontainer\" class=\"ygtv-checkbox\"></div>");
out.println("");
out.println(" <form id=\"pg_form\">");
out.println("");
out.println(" <input type=\"hidden\" id=\"ontology_node_id\" name=\"ontology_node_id\" value=\"null\" />");
out.println(" <input type=\"hidden\" id=\"ontology_display_name\" name=\"ontology_display_name\" value=\"" + dictionary + "\" />");
out.println(" <input type=\"hidden\" id=\"schema\" name=\"schema\" value=\"" + dictionary + "\" />");
out.println(" <input type=\"hidden\" id=\"ontology_version\" name=\"ontology_version\" value=\"" + version + "\" />");
out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />");
out.println(" </form>");
out.println("");
out.println("");
out.println(" </div> <!-- popupContentArea -->");
out.println("");
out.println("");
out.println("<div class=\"textbody\">");
out.println("<!-- footer -->");
out.println("<div class=\"footer\" style=\"width:720px\">");
out.println(" <ul>");
out.println(" <li><a href=\"http://www.cancer.gov\" target=\"_blank\" alt=\"National Cancer Institute\">NCI Home</a> |</li>");
out.println(" <li><a href=\"/ncitbrowser/pages/contact_us.jsf\">Contact Us</a> |</li>");
out.println(" <li><a href=\"http://www.cancer.gov/policies\" target=\"_blank\" alt=\"National Cancer Institute Policies\">Policies</a> |</li>");
out.println(" <li><a href=\"http://www.cancer.gov/policies/page3\" target=\"_blank\" alt=\"National Cancer Institute Accessibility\">Accessibility</a> |</li>");
out.println(" <li><a href=\"http://www.cancer.gov/policies/page6\" target=\"_blank\" alt=\"National Cancer Institute FOIA\">FOIA</a></li>");
out.println(" </ul>");
out.println(" <p>");
out.println(" A Service of the National Cancer Institute<br />");
out.println(" <img src=\"/ncitbrowser/images/external-footer-logos.gif\"");
out.println(" alt=\"External Footer Logos\" width=\"238\" height=\"34\" border=\"0\"");
out.println(" usemap=\"#external-footer\" />");
out.println(" </p>");
out.println(" <map id=\"external-footer\" name=\"external-footer\">");
out.println(" <area shape=\"rect\" coords=\"0,0,46,34\"");
out.println(" href=\"http://www.cancer.gov\" target=\"_blank\"");
out.println(" alt=\"National Cancer Institute\" />");
out.println(" <area shape=\"rect\" coords=\"55,1,99,32\"");
out.println(" href=\"http://www.hhs.gov/\" target=\"_blank\"");
out.println(" alt=\"U.S. Health & Human Services\" />");
out.println(" <area shape=\"rect\" coords=\"103,1,147,31\"");
out.println(" href=\"http://www.nih.gov/\" target=\"_blank\"");
out.println(" alt=\"National Institutes of Health\" />");
out.println(" <area shape=\"rect\" coords=\"148,1,235,33\"");
out.println(" href=\"http://www.usa.gov/\" target=\"_blank\"");
out.println(" alt=\"USA.gov\" />");
out.println(" </map>");
out.println("</div>");
out.println("<!-- end footer -->");
out.println("</div>");
out.println("");
out.println("");
out.println(" </div> <!-- pagecontent -->");
out.println(" </div> <!-- main-area -->");
out.println(" <div class=\"mainbox-bottom\"><img src=\"/ncitbrowser/images/mainbox-bottom.gif\" width=\"745\" height=\"5\" alt=\"Mainbox Bottom\" /></div>");
out.println("");
out.println(" </div> <!-- center-page -->");
out.println("");
out.println("</body>");
out.println("</html>");
out.println("");
}
|
diff --git a/src/com/android/timezonepicker/TimeZoneFilterTypeAdapter.java b/src/com/android/timezonepicker/TimeZoneFilterTypeAdapter.java
index 5d0e881..cadd4f2 100644
--- a/src/com/android/timezonepicker/TimeZoneFilterTypeAdapter.java
+++ b/src/com/android/timezonepicker/TimeZoneFilterTypeAdapter.java
@@ -1,535 +1,530 @@
/*
* Copyright (C) 2013 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.timezonepicker;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import java.util.ArrayList;
public class TimeZoneFilterTypeAdapter extends BaseAdapter implements Filterable, OnClickListener {
public static final String TAG = "TimeZoneFilterTypeAdapter";
public static final int FILTER_TYPE_EMPTY = -1;
public static final int FILTER_TYPE_NONE = 0;
public static final int FILTER_TYPE_TIME = 1;
public static final int FILTER_TYPE_TIME_ZONE = 2;
public static final int FILTER_TYPE_COUNTRY = 3;
public static final int FILTER_TYPE_STATE = 4;
public static final int FILTER_TYPE_GMT = 5;
public interface OnSetFilterListener {
void onSetFilter(int filterType, String str, int time);
}
static class ViewHolder {
int filterType;
String str;
int time;
TextView typeTextView;
TextView strTextView;
static void setupViewHolder(View v) {
ViewHolder vh = new ViewHolder();
vh.typeTextView = (TextView) v.findViewById(R.id.type);
vh.strTextView = (TextView) v.findViewById(R.id.value);
v.setTag(vh);
}
}
class FilterTypeResult {
boolean showLabel;
int type;
String constraint;
public int time;
public FilterTypeResult(boolean showLabel, int type, String constraint, int time) {
this.showLabel = showLabel;
this.type = type;
this.constraint = constraint;
this.time = time;
}
@Override
public String toString() {
return constraint;
}
}
private ArrayList<FilterTypeResult> mLiveResults = new ArrayList<FilterTypeResult>();
private int mLiveResultsCount = 0;
private ArrayFilter mFilter;
private LayoutInflater mInflater;
private TimeZoneData mTimeZoneData;
private OnSetFilterListener mListener;
public TimeZoneFilterTypeAdapter(Context context, TimeZoneData tzd, OnSetFilterListener l) {
mTimeZoneData = tzd;
mListener = l;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public boolean areAllItemsEnabled() {
return false;
}
@Override
public boolean isEnabled(int position) {
return !mLiveResults.get(position).showLabel;
}
@Override
public int getCount() {
return mLiveResultsCount;
}
@Override
public FilterTypeResult getItem(int position) {
return mLiveResults.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v;
if (convertView != null) {
v = convertView;
} else {
v = mInflater.inflate(R.layout.time_zone_filter_item, null);
ViewHolder.setupViewHolder(v);
}
ViewHolder vh = (ViewHolder) v.getTag();
if (position >= mLiveResults.size()) {
Log.e(TAG, "getView: " + position + " of " + mLiveResults.size());
}
FilterTypeResult filter = mLiveResults.get(position);
vh.filterType = filter.type;
vh.str = filter.constraint;
vh.time = filter.time;
if (filter.showLabel) {
int resId;
switch (filter.type) {
case FILTER_TYPE_GMT:
resId = R.string.gmt_offset;
break;
case FILTER_TYPE_TIME:
resId = R.string.local_time;
break;
case FILTER_TYPE_TIME_ZONE:
resId = R.string.time_zone;
break;
case FILTER_TYPE_COUNTRY:
resId = R.string.country;
break;
default:
throw new IllegalArgumentException();
}
vh.typeTextView.setText(resId);
vh.typeTextView.setVisibility(View.VISIBLE);
vh.strTextView.setVisibility(View.GONE);
} else {
vh.typeTextView.setVisibility(View.GONE);
vh.strTextView.setVisibility(View.VISIBLE);
}
vh.strTextView.setText(filter.constraint);
return v;
}
OnClickListener mDummyListener = new OnClickListener() {
@Override
public void onClick(View v) {
}
};
// Implements OnClickListener
// This onClickListener is actually called from the AutoCompleteTextView's
// onItemClickListener. Trying to update the text in AutoCompleteTextView
// is causing an infinite loop.
@Override
public void onClick(View v) {
if (mListener != null && v != null) {
ViewHolder vh = (ViewHolder) v.getTag();
mListener.onSetFilter(vh.filterType, vh.str, vh.time);
}
notifyDataSetInvalidated();
}
// Implements Filterable
@Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ArrayFilter();
}
return mFilter;
}
private class ArrayFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence prefix) {
Log.e(TAG, "performFiltering >>>> [" + prefix + "]");
FilterResults results = new FilterResults();
String prefixString = null;
if (prefix != null) {
prefixString = prefix.toString().trim().toLowerCase();
}
if (TextUtils.isEmpty(prefixString)) {
results.values = null;
results.count = 0;
return results;
}
// TODO Perf - we can loop through the filtered list if the new
// search string starts with the old search string
ArrayList<FilterTypeResult> filtered = new ArrayList<FilterTypeResult>();
// ////////////////////////////////////////
// Search by local time and GMT offset
// ////////////////////////////////////////
boolean gmtOnly = false;
int startParsePosition = 0;
if (prefixString.charAt(0) == '+' || prefixString.charAt(0) == '-') {
gmtOnly = true;
}
if (prefixString.startsWith("gmt")) {
startParsePosition = 3;
gmtOnly = true;
}
int num = parseNum(prefixString, startParsePosition);
if (num != Integer.MIN_VALUE) {
boolean positiveOnly = prefixString.length() > startParsePosition
&& prefixString.charAt(startParsePosition) == '+';
handleSearchByGmt(filtered, num, positiveOnly);
// Search by time
if (!gmtOnly) {
handleSearchByTime(filtered, num);
}
}
// ////////////////////////////////////////
// Search by country
// ////////////////////////////////////////
boolean first = true;
for (String country : mTimeZoneData.mTimeZonesByCountry.keySet()) {
// TODO Perf - cache toLowerCase()?
if (!TextUtils.isEmpty(country)) {
final String lowerCaseCountry = country.toLowerCase();
if (lowerCaseCountry.startsWith(prefixString)
|| (lowerCaseCountry.charAt(0) == prefixString.charAt(0) &&
isStartingInitialsFor(prefixString, lowerCaseCountry))) {
FilterTypeResult r;
- if (first) {
- r = new FilterTypeResult(true, FILTER_TYPE_COUNTRY, null, 0);
- filtered.add(r);
- first = false;
- }
r = new FilterTypeResult(false, FILTER_TYPE_COUNTRY, country, 0);
filtered.add(r);
}
}
}
// ////////////////////////////////////////
// Search by time zone name
// ////////////////////////////////////////
// first = true;
// for (String timeZoneName : mTimeZoneData.mTimeZoneNames) {
// // TODO Perf - cache toLowerCase()?
// if (timeZoneName.toLowerCase().startsWith(prefixString)) {
// FilterTypeResult r;
// if (first) {
// r = new FilterTypeResult(true, FILTER_TYPE_TIME_ZONE, null, 0);
// filtered.add(r);
// first = false;
// }
// r = new FilterTypeResult(false, FILTER_TYPE_TIME_ZONE, timeZoneName, 0);
// filtered.add(r);
// }
// }
// ////////////////////////////////////////
// TODO Search by state
// ////////////////////////////////////////
Log.e(TAG, "performFiltering <<<< " + filtered.size() + "[" + prefix + "]");
results.values = filtered;
results.count = filtered.size();
return results;
}
/**
* Returns true if the prefixString is an initial for string. Note that
* this method will return true even if prefixString does not cover all
* the words. Words are separated by non-letters which includes spaces
* and symbols).
*
* For example:
* isStartingInitialsFor("UA", "United Arb Emirates") would return true
* isStartingInitialsFor("US", "U.S. Virgin Island") would return true
* @param prefixString
* @param string
* @return
*/
private boolean isStartingInitialsFor(String prefixString, String string) {
final int initialLen = prefixString.length();
final int strLen = string.length();
int initialIdx = 0;
boolean wasWordBreak = true;
for (int i = 0; i < strLen; i++) {
if (!Character.isLetter(string.charAt(i))) {
wasWordBreak = true;
continue;
}
if (wasWordBreak) {
if (prefixString.charAt(initialIdx++) != string.charAt(i)) {
return false;
}
if (initialIdx == initialLen) {
return true;
}
wasWordBreak = false;
}
}
return false;
}
/**
* @param filtered
* @param num
*/
private void handleSearchByTime(ArrayList<FilterTypeResult> filtered, int num) {
int originalResultCount = filtered.size();
// Separator
FilterTypeResult r = new FilterTypeResult(true, FILTER_TYPE_TIME, null, 0);
filtered.add(r);
long now = System.currentTimeMillis();
boolean[] hasTz = new boolean[24];
// TODO make this faster
for (TimeZoneInfo tzi : mTimeZoneData.mTimeZones) {
int localHr = tzi.getLocalHr(now);
hasTz[localHr] = true;
}
if (hasTz[num]) {
r = new FilterTypeResult(false, FILTER_TYPE_TIME,
Integer.toString(num), num);
filtered.add(r);
}
int start = Integer.MAX_VALUE;
int end = Integer.MIN_VALUE;
if (TimeZoneData.is24HourFormat) {
switch (num) {
case 1:
start = 10;
end = 23;
break;
case 2:
start = 20;
end = 23;
break;
}
} else if (num == 1) {
start = 10;
end = 12;
}
for (int i = start; i < end; i++) {
if (hasTz[i]) {
r = new FilterTypeResult(false, FILTER_TYPE_TIME,
Integer.toString(i), i);
filtered.add(r);
}
}
// Nothing was added except for the separator. Let's remove it.
if (filtered.size() == originalResultCount + 1) {
filtered.remove(originalResultCount);
}
}
private void handleSearchByGmt(ArrayList<FilterTypeResult> filtered, int num,
boolean positiveOnly) {
FilterTypeResult r;
int originalResultCount = filtered.size();
// Separator
r = new FilterTypeResult(true, FILTER_TYPE_GMT, null, 0);
filtered.add(r);
if (num >= 0) {
if (num == 1) {
for (int i = 19; i >= 10; i--) {
if (mTimeZoneData.hasTimeZonesInHrOffset(i)) {
r = new FilterTypeResult(false, FILTER_TYPE_GMT, "GMT+" + i, i);
filtered.add(r);
}
}
}
if (mTimeZoneData.hasTimeZonesInHrOffset(num)) {
r = new FilterTypeResult(false, FILTER_TYPE_GMT, "GMT+" + num, num);
filtered.add(r);
}
num *= -1;
}
if (!positiveOnly && num != 0) {
if (mTimeZoneData.hasTimeZonesInHrOffset(num)) {
r = new FilterTypeResult(false, FILTER_TYPE_GMT, "GMT" + num, num);
filtered.add(r);
}
if (num == -1) {
for (int i = -10; i >= -19; i--) {
if (mTimeZoneData.hasTimeZonesInHrOffset(i)) {
r = new FilterTypeResult(false, FILTER_TYPE_GMT, "GMT" + i, i);
filtered.add(r);
}
}
}
}
// Nothing was added except for the separator. Let's remove it.
if (filtered.size() == originalResultCount + 1) {
filtered.remove(originalResultCount);
}
return;
}
/**
* Acceptable strings are in the following format: [+-]?[0-9]?[0-9]
*
* @param str
* @param startIndex
* @return Integer.MIN_VALUE as invalid
*/
public int parseNum(String str, int startIndex) {
int idx = startIndex;
int num = Integer.MIN_VALUE;
int negativeMultiplier = 1;
// First char - check for + and -
char ch = str.charAt(idx++);
switch (ch) {
case '-':
negativeMultiplier = -1;
// fall through
case '+':
if (idx >= str.length()) {
// No more digits
return Integer.MIN_VALUE;
}
ch = str.charAt(idx++);
break;
}
if (!Character.isDigit(ch)) {
// No digit
return Integer.MIN_VALUE;
}
// Got first digit
num = Character.digit(ch, 10);
// Check next char
if (idx < str.length()) {
ch = str.charAt(idx++);
if (Character.isDigit(ch)) {
// Got second digit
num = 10 * num + Character.digit(ch, 10);
} else {
return Integer.MIN_VALUE;
}
}
if (idx != str.length()) {
// Invalid
return Integer.MIN_VALUE;
}
Log.e(TAG, "Parsing " + str + " -> " + negativeMultiplier * num);
return negativeMultiplier * num;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults
results) {
if (results.values == null || results.count == 0) {
if (mListener != null) {
int filterType;
if (TextUtils.isEmpty(constraint)) {
filterType = FILTER_TYPE_NONE;
} else {
filterType = FILTER_TYPE_EMPTY;
}
mListener.onSetFilter(filterType, null, 0);
}
Log.e(TAG, "publishResults: " + results.count + " of null [" + constraint);
} else {
mLiveResults = (ArrayList<FilterTypeResult>) results.values;
Log.e(TAG, "publishResults: " + results.count + " of " + mLiveResults.size() + " ["
+ constraint);
}
mLiveResultsCount = results.count;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
| true | true | protected FilterResults performFiltering(CharSequence prefix) {
Log.e(TAG, "performFiltering >>>> [" + prefix + "]");
FilterResults results = new FilterResults();
String prefixString = null;
if (prefix != null) {
prefixString = prefix.toString().trim().toLowerCase();
}
if (TextUtils.isEmpty(prefixString)) {
results.values = null;
results.count = 0;
return results;
}
// TODO Perf - we can loop through the filtered list if the new
// search string starts with the old search string
ArrayList<FilterTypeResult> filtered = new ArrayList<FilterTypeResult>();
// ////////////////////////////////////////
// Search by local time and GMT offset
// ////////////////////////////////////////
boolean gmtOnly = false;
int startParsePosition = 0;
if (prefixString.charAt(0) == '+' || prefixString.charAt(0) == '-') {
gmtOnly = true;
}
if (prefixString.startsWith("gmt")) {
startParsePosition = 3;
gmtOnly = true;
}
int num = parseNum(prefixString, startParsePosition);
if (num != Integer.MIN_VALUE) {
boolean positiveOnly = prefixString.length() > startParsePosition
&& prefixString.charAt(startParsePosition) == '+';
handleSearchByGmt(filtered, num, positiveOnly);
// Search by time
if (!gmtOnly) {
handleSearchByTime(filtered, num);
}
}
// ////////////////////////////////////////
// Search by country
// ////////////////////////////////////////
boolean first = true;
for (String country : mTimeZoneData.mTimeZonesByCountry.keySet()) {
// TODO Perf - cache toLowerCase()?
if (!TextUtils.isEmpty(country)) {
final String lowerCaseCountry = country.toLowerCase();
if (lowerCaseCountry.startsWith(prefixString)
|| (lowerCaseCountry.charAt(0) == prefixString.charAt(0) &&
isStartingInitialsFor(prefixString, lowerCaseCountry))) {
FilterTypeResult r;
if (first) {
r = new FilterTypeResult(true, FILTER_TYPE_COUNTRY, null, 0);
filtered.add(r);
first = false;
}
r = new FilterTypeResult(false, FILTER_TYPE_COUNTRY, country, 0);
filtered.add(r);
}
}
}
// ////////////////////////////////////////
// Search by time zone name
// ////////////////////////////////////////
// first = true;
// for (String timeZoneName : mTimeZoneData.mTimeZoneNames) {
// // TODO Perf - cache toLowerCase()?
// if (timeZoneName.toLowerCase().startsWith(prefixString)) {
// FilterTypeResult r;
// if (first) {
// r = new FilterTypeResult(true, FILTER_TYPE_TIME_ZONE, null, 0);
// filtered.add(r);
// first = false;
// }
// r = new FilterTypeResult(false, FILTER_TYPE_TIME_ZONE, timeZoneName, 0);
// filtered.add(r);
// }
// }
// ////////////////////////////////////////
// TODO Search by state
// ////////////////////////////////////////
Log.e(TAG, "performFiltering <<<< " + filtered.size() + "[" + prefix + "]");
results.values = filtered;
results.count = filtered.size();
return results;
}
| protected FilterResults performFiltering(CharSequence prefix) {
Log.e(TAG, "performFiltering >>>> [" + prefix + "]");
FilterResults results = new FilterResults();
String prefixString = null;
if (prefix != null) {
prefixString = prefix.toString().trim().toLowerCase();
}
if (TextUtils.isEmpty(prefixString)) {
results.values = null;
results.count = 0;
return results;
}
// TODO Perf - we can loop through the filtered list if the new
// search string starts with the old search string
ArrayList<FilterTypeResult> filtered = new ArrayList<FilterTypeResult>();
// ////////////////////////////////////////
// Search by local time and GMT offset
// ////////////////////////////////////////
boolean gmtOnly = false;
int startParsePosition = 0;
if (prefixString.charAt(0) == '+' || prefixString.charAt(0) == '-') {
gmtOnly = true;
}
if (prefixString.startsWith("gmt")) {
startParsePosition = 3;
gmtOnly = true;
}
int num = parseNum(prefixString, startParsePosition);
if (num != Integer.MIN_VALUE) {
boolean positiveOnly = prefixString.length() > startParsePosition
&& prefixString.charAt(startParsePosition) == '+';
handleSearchByGmt(filtered, num, positiveOnly);
// Search by time
if (!gmtOnly) {
handleSearchByTime(filtered, num);
}
}
// ////////////////////////////////////////
// Search by country
// ////////////////////////////////////////
boolean first = true;
for (String country : mTimeZoneData.mTimeZonesByCountry.keySet()) {
// TODO Perf - cache toLowerCase()?
if (!TextUtils.isEmpty(country)) {
final String lowerCaseCountry = country.toLowerCase();
if (lowerCaseCountry.startsWith(prefixString)
|| (lowerCaseCountry.charAt(0) == prefixString.charAt(0) &&
isStartingInitialsFor(prefixString, lowerCaseCountry))) {
FilterTypeResult r;
r = new FilterTypeResult(false, FILTER_TYPE_COUNTRY, country, 0);
filtered.add(r);
}
}
}
// ////////////////////////////////////////
// Search by time zone name
// ////////////////////////////////////////
// first = true;
// for (String timeZoneName : mTimeZoneData.mTimeZoneNames) {
// // TODO Perf - cache toLowerCase()?
// if (timeZoneName.toLowerCase().startsWith(prefixString)) {
// FilterTypeResult r;
// if (first) {
// r = new FilterTypeResult(true, FILTER_TYPE_TIME_ZONE, null, 0);
// filtered.add(r);
// first = false;
// }
// r = new FilterTypeResult(false, FILTER_TYPE_TIME_ZONE, timeZoneName, 0);
// filtered.add(r);
// }
// }
// ////////////////////////////////////////
// TODO Search by state
// ////////////////////////////////////////
Log.e(TAG, "performFiltering <<<< " + filtered.size() + "[" + prefix + "]");
results.values = filtered;
results.count = filtered.size();
return results;
}
|
diff --git a/src/de/raptor2101/GalDroid/Activities/Listeners/ImageViewImageLoaderTaskListener.java b/src/de/raptor2101/GalDroid/Activities/Listeners/ImageViewImageLoaderTaskListener.java
index 0865958..75ea12c 100644
--- a/src/de/raptor2101/GalDroid/Activities/Listeners/ImageViewImageLoaderTaskListener.java
+++ b/src/de/raptor2101/GalDroid/Activities/Listeners/ImageViewImageLoaderTaskListener.java
@@ -1,45 +1,45 @@
package de.raptor2101.GalDroid.Activities.Listeners;
import android.graphics.Bitmap;
import android.widget.Gallery;
import android.widget.ImageView;
import de.raptor2101.GalDroid.Activities.Helpers.ImageInformationExtractor;
import de.raptor2101.GalDroid.WebGallery.GalleryImageView;
import de.raptor2101.GalDroid.WebGallery.Tasks.ImageLoaderTaskListener;
public class ImageViewImageLoaderTaskListener implements ImageLoaderTaskListener {
private final ImageInformationExtractor mInformationExtractor;
private final Gallery mGallery;
public ImageViewImageLoaderTaskListener(Gallery gallery, ImageInformationExtractor informationExtractor) {
mInformationExtractor = informationExtractor;
mGallery = gallery;
}
public void onLoadingStarted(String uniqueId) {
// Nothing todo
}
public void onLoadingProgress(String uniqueId, int currentValue,
int maxValue) {
// Nothing todo
}
public void onLoadingCompleted(String uniqueId, Bitmap bitmap) {
// if a Download is completed it could be the current diplayed image.
// so start decoding of its embeded informations
GalleryImageView imageView = (GalleryImageView) mGallery.getSelectedView();
- if(imageView.getGalleryObject().getImage().getUniqueId() == uniqueId) {
+ if(imageView != null && imageView.getGalleryObject().getImage().getUniqueId() == uniqueId) {
mInformationExtractor.extractImageInformations(imageView);
}
}
public void onLoadingCancelled(String uniqueId) {
// TODO Auto-generated method stub
}
}
| true | true | public void onLoadingCompleted(String uniqueId, Bitmap bitmap) {
// if a Download is completed it could be the current diplayed image.
// so start decoding of its embeded informations
GalleryImageView imageView = (GalleryImageView) mGallery.getSelectedView();
if(imageView.getGalleryObject().getImage().getUniqueId() == uniqueId) {
mInformationExtractor.extractImageInformations(imageView);
}
}
| public void onLoadingCompleted(String uniqueId, Bitmap bitmap) {
// if a Download is completed it could be the current diplayed image.
// so start decoding of its embeded informations
GalleryImageView imageView = (GalleryImageView) mGallery.getSelectedView();
if(imageView != null && imageView.getGalleryObject().getImage().getUniqueId() == uniqueId) {
mInformationExtractor.extractImageInformations(imageView);
}
}
|
diff --git a/server/cluster-mgmt/src/main/java/com/vmware/bdd/service/sp/ScaleVMSP.java b/server/cluster-mgmt/src/main/java/com/vmware/bdd/service/sp/ScaleVMSP.java
index 6d5250d1..c9c0abc9 100644
--- a/server/cluster-mgmt/src/main/java/com/vmware/bdd/service/sp/ScaleVMSP.java
+++ b/server/cluster-mgmt/src/main/java/com/vmware/bdd/service/sp/ScaleVMSP.java
@@ -1,135 +1,135 @@
/***************************************************************************
* Copyright (c) 2012 VMware, Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
package com.vmware.bdd.service.sp;
import java.util.concurrent.Callable;
import org.apache.log4j.Logger;
import com.vmware.aurora.global.DiskSize;
import com.vmware.aurora.vc.DeviceId;
import com.vmware.aurora.vc.DiskSpec.AllocationType;
import com.vmware.aurora.vc.VcCache;
import com.vmware.aurora.vc.VcDatastore;
import com.vmware.aurora.vc.VcVirtualMachine;
import com.vmware.aurora.vc.VcVirtualMachine.DiskCreateSpec;
import com.vmware.aurora.vc.VmConfigUtil;
import com.vmware.aurora.vc.vcservice.VcContext;
import com.vmware.aurora.vc.vcservice.VcSession;
import com.vmware.bdd.entity.DiskEntity;
import com.vmware.bdd.utils.VcVmUtil;
import com.vmware.vim.binding.impl.vim.vm.ConfigSpecImpl;
import com.vmware.vim.binding.impl.vim.vm.device.VirtualDeviceSpecImpl;
import com.vmware.vim.binding.vim.vm.device.VirtualDeviceSpec;
import com.vmware.vim.binding.vim.vm.device.VirtualDisk;
import com.vmware.vim.binding.vim.vm.device.VirtualDiskOption.DiskMode;
/**
* @author Jarred Li
* @version 0.9
* @since 0.9
*
*/
public class ScaleVMSP implements Callable<Void> {
private static final Logger logger = Logger.getLogger(ScaleVMSP.class);
private String vmId;
private int cpuNumber;
private long memory;
private VcDatastore targetDs;
private DiskEntity swapDisk;
private long newSwapSizeInMB;
public ScaleVMSP(String vmId, int cpuNumber, long memory,
VcDatastore targetDs, DiskEntity swapDisk, long newSwapSizeInMB) {
this.vmId = vmId;
this.cpuNumber = cpuNumber;
this.memory = memory;
this.targetDs = targetDs;
this.swapDisk = swapDisk;
this.newSwapSizeInMB = newSwapSizeInMB;
}
/* (non-Javadoc)
* @see java.util.concurrent.Callable#call()
*/
@Override
public Void call() throws Exception {
final VcVirtualMachine vcVm = VcCache.getIgnoreMissing(vmId);
if (vcVm == null) {
logger.info("vm: " + vmId + " is not found.");
return null;
}
if (vcVm.isPoweredOn()) {
logger.info("vm " + vcVm.getName()
+ " must be powered off before scaling");
return null;
}
logger.info("scale vm,vmId:" + vmId + ",cpuNumber:" + cpuNumber
+ ",memory:" + memory);
return VcContext.inVcSessionDo(new VcSession<Void>() {
@Override
protected Void body() throws Exception {
//start config vm if max configuration check is passed
ConfigSpecImpl newConfigSpec = new ConfigSpecImpl();
if (cpuNumber > 0) {
newConfigSpec.setNumCPUs(cpuNumber);
}
if (memory > 0) {
VmConfigUtil.setMemoryAndBalloon(newConfigSpec, memory);
if (targetDs != null) {
VirtualDisk vmSwapDisk =
VcVmUtil.findVirtualDisk(vmId,
swapDisk.getExternalAddress());
logger.info("current ds swap disk placed: "
+ swapDisk.getDatastoreName());
logger.info("target ds to place swap disk: "
+ targetDs.getName());
- if (swapDisk.getDatastoreMoId() == targetDs.getId()) {
+ if (swapDisk.getDatastoreMoId().equals(targetDs.getId())) {
VirtualDeviceSpec devSpec = new VirtualDeviceSpecImpl();
devSpec.setOperation(VirtualDeviceSpec.Operation.edit);
vmSwapDisk.setCapacityInKB(newSwapSizeInMB * 1024);
devSpec.setDevice(vmSwapDisk);
VirtualDeviceSpec[] changes = { devSpec };
newConfigSpec.setDeviceChange(changes);
logger.info("finished resize swap disk size");
} else {
vcVm.detachVirtualDisk(
new DeviceId(swapDisk.getExternalAddress()), true);
AllocationType allocType =
swapDisk.getAllocType() == null ? null : AllocationType
.valueOf(swapDisk.getAllocType());
DiskCreateSpec[] addDisks =
{ new DiskCreateSpec(new DeviceId(swapDisk
.getExternalAddress()), targetDs, swapDisk
.getName(), DiskMode.independent_persistent,
DiskSize.sizeFromMB(newSwapSizeInMB), allocType) };
// changeDisks() will run vcVm.reconfigure() itself
vcVm.changeDisks(null, addDisks);
}
}
}
vcVm.reconfigure(newConfigSpec);
return null;
}
protected boolean isTaskSession() {
return true;
}
});
}
}
| true | true | public Void call() throws Exception {
final VcVirtualMachine vcVm = VcCache.getIgnoreMissing(vmId);
if (vcVm == null) {
logger.info("vm: " + vmId + " is not found.");
return null;
}
if (vcVm.isPoweredOn()) {
logger.info("vm " + vcVm.getName()
+ " must be powered off before scaling");
return null;
}
logger.info("scale vm,vmId:" + vmId + ",cpuNumber:" + cpuNumber
+ ",memory:" + memory);
return VcContext.inVcSessionDo(new VcSession<Void>() {
@Override
protected Void body() throws Exception {
//start config vm if max configuration check is passed
ConfigSpecImpl newConfigSpec = new ConfigSpecImpl();
if (cpuNumber > 0) {
newConfigSpec.setNumCPUs(cpuNumber);
}
if (memory > 0) {
VmConfigUtil.setMemoryAndBalloon(newConfigSpec, memory);
if (targetDs != null) {
VirtualDisk vmSwapDisk =
VcVmUtil.findVirtualDisk(vmId,
swapDisk.getExternalAddress());
logger.info("current ds swap disk placed: "
+ swapDisk.getDatastoreName());
logger.info("target ds to place swap disk: "
+ targetDs.getName());
if (swapDisk.getDatastoreMoId() == targetDs.getId()) {
VirtualDeviceSpec devSpec = new VirtualDeviceSpecImpl();
devSpec.setOperation(VirtualDeviceSpec.Operation.edit);
vmSwapDisk.setCapacityInKB(newSwapSizeInMB * 1024);
devSpec.setDevice(vmSwapDisk);
VirtualDeviceSpec[] changes = { devSpec };
newConfigSpec.setDeviceChange(changes);
logger.info("finished resize swap disk size");
} else {
vcVm.detachVirtualDisk(
new DeviceId(swapDisk.getExternalAddress()), true);
AllocationType allocType =
swapDisk.getAllocType() == null ? null : AllocationType
.valueOf(swapDisk.getAllocType());
DiskCreateSpec[] addDisks =
{ new DiskCreateSpec(new DeviceId(swapDisk
.getExternalAddress()), targetDs, swapDisk
.getName(), DiskMode.independent_persistent,
DiskSize.sizeFromMB(newSwapSizeInMB), allocType) };
// changeDisks() will run vcVm.reconfigure() itself
vcVm.changeDisks(null, addDisks);
}
}
}
vcVm.reconfigure(newConfigSpec);
return null;
}
protected boolean isTaskSession() {
return true;
}
});
}
| public Void call() throws Exception {
final VcVirtualMachine vcVm = VcCache.getIgnoreMissing(vmId);
if (vcVm == null) {
logger.info("vm: " + vmId + " is not found.");
return null;
}
if (vcVm.isPoweredOn()) {
logger.info("vm " + vcVm.getName()
+ " must be powered off before scaling");
return null;
}
logger.info("scale vm,vmId:" + vmId + ",cpuNumber:" + cpuNumber
+ ",memory:" + memory);
return VcContext.inVcSessionDo(new VcSession<Void>() {
@Override
protected Void body() throws Exception {
//start config vm if max configuration check is passed
ConfigSpecImpl newConfigSpec = new ConfigSpecImpl();
if (cpuNumber > 0) {
newConfigSpec.setNumCPUs(cpuNumber);
}
if (memory > 0) {
VmConfigUtil.setMemoryAndBalloon(newConfigSpec, memory);
if (targetDs != null) {
VirtualDisk vmSwapDisk =
VcVmUtil.findVirtualDisk(vmId,
swapDisk.getExternalAddress());
logger.info("current ds swap disk placed: "
+ swapDisk.getDatastoreName());
logger.info("target ds to place swap disk: "
+ targetDs.getName());
if (swapDisk.getDatastoreMoId().equals(targetDs.getId())) {
VirtualDeviceSpec devSpec = new VirtualDeviceSpecImpl();
devSpec.setOperation(VirtualDeviceSpec.Operation.edit);
vmSwapDisk.setCapacityInKB(newSwapSizeInMB * 1024);
devSpec.setDevice(vmSwapDisk);
VirtualDeviceSpec[] changes = { devSpec };
newConfigSpec.setDeviceChange(changes);
logger.info("finished resize swap disk size");
} else {
vcVm.detachVirtualDisk(
new DeviceId(swapDisk.getExternalAddress()), true);
AllocationType allocType =
swapDisk.getAllocType() == null ? null : AllocationType
.valueOf(swapDisk.getAllocType());
DiskCreateSpec[] addDisks =
{ new DiskCreateSpec(new DeviceId(swapDisk
.getExternalAddress()), targetDs, swapDisk
.getName(), DiskMode.independent_persistent,
DiskSize.sizeFromMB(newSwapSizeInMB), allocType) };
// changeDisks() will run vcVm.reconfigure() itself
vcVm.changeDisks(null, addDisks);
}
}
}
vcVm.reconfigure(newConfigSpec);
return null;
}
protected boolean isTaskSession() {
return true;
}
});
}
|
diff --git a/btm/src/main/java/bitronix/tm/resource/common/XAPool.java b/btm/src/main/java/bitronix/tm/resource/common/XAPool.java
index 5cb2d7c..c5eba30 100644
--- a/btm/src/main/java/bitronix/tm/resource/common/XAPool.java
+++ b/btm/src/main/java/bitronix/tm/resource/common/XAPool.java
@@ -1,668 +1,668 @@
/*
* Bitronix Transaction Manager
*
* Copyright (c) 2010, Bitronix Software.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package bitronix.tm.resource.common;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.transaction.Synchronization;
import org.slf4j.*;
import bitronix.tm.*;
import bitronix.tm.internal.*;
import bitronix.tm.recovery.*;
import bitronix.tm.utils.*;
import bitronix.tm.utils.CryptoEngine;
/**
* Generic XA pool. {@link XAStatefulHolder} instances are created by the {@link XAPool} out of a
* {@link XAResourceProducer}. Those objects are then pooled and can be retrieved and/or recycled by the pool
* depending on the running XA transaction's and the {@link XAStatefulHolder}'s states.
*
* @author lorban
*/
public class XAPool implements StateChangeListener {
private final static Logger log = LoggerFactory.getLogger(XAPool.class);
private final static String PASSWORD_PROPERTY_NAME = "password";
private final Map<Uid, StatefulHolderThreadLocal> statefulHolderTransactionMap = new ConcurrentHashMap<Uid, StatefulHolderThreadLocal>();
private final BlockingQueue<XAStatefulHolder> availablePool = new LinkedBlockingQueue<XAStatefulHolder>();
private final Queue<XAStatefulHolder> accessiblePool = new ConcurrentLinkedQueue<XAStatefulHolder>();
private final Queue<XAStatefulHolder> inaccessiblePool = new ConcurrentLinkedQueue<XAStatefulHolder>();
/**
* The stateTransitionLock makes sure that transitions of XAStatefulHolders from one state to another
* are atomic. A ReentrantReadWriteLock allows any number of readers to access and iterate the
* accessiblePool and inaccessiblePool without blocking. Readers are blocked only for the instant
* when a connection is moving between pools. We use a lock, in addition to the collections being
* concurrent, because concurrent collections only guarantee atomic reads and writes, but not consistent
* iteration. Iterating over a concurrent collection while it is modified can lead to the same element
* being seen twice or some elements never being seen at all.
*/
private final ReentrantReadWriteLock stateTransitionLock = new ReentrantReadWriteLock();
private final ResourceBean bean;
private final XAResourceProducer xaResourceProducer;
private final Object xaFactory;
private final AtomicBoolean failed = new AtomicBoolean();
public XAPool(XAResourceProducer xaResourceProducer, ResourceBean bean) throws Exception {
this.xaResourceProducer = xaResourceProducer;
this.bean = bean;
if (bean.getMaxPoolSize() < 1 || bean.getMinPoolSize() > bean.getMaxPoolSize())
throw new IllegalArgumentException("cannot create a pool with min " + bean.getMinPoolSize() + " connection(s) and max " + bean.getMaxPoolSize() + " connection(s)");
if (bean.getAcquireIncrement() < 1)
throw new IllegalArgumentException("cannot create a pool with a connection acquisition increment less than 1, configured value is " + bean.getAcquireIncrement());
xaFactory = createXAFactory(bean);
init();
if (bean.getIgnoreRecoveryFailures())
log.warn("resource '" + bean.getUniqueName() + "' is configured to ignore recovery failures, make sure this setting is not enabled on a production system!");
}
/**
* Get the XAFactory (XADataSource) that produces objects for this pool.
*
* @return the factory (XADataSource) object
*/
public Object getXAFactory() {
return xaFactory;
}
/**
* Sets this XAPool as failed or unfailed, requiring recovery.
*
* @param failed true if this XAPool has failed and requires recovery, false if it is ok
*/
public void setFailed(boolean failed) {
this.failed.set(failed);
}
/**
* Is the XAPool in a failed state?
*
* @return true if this XAPool has failed, false otherwise
*/
public boolean isFailed() {
return failed.get();
}
/**
* Get a connection handle from this pool.
*
* @return a connection handle
* @throws Exception throw in the pool is unrecoverable or a timeout occurs getting a connection
*/
public Object getConnectionHandle() throws Exception {
return getConnectionHandle(true);
}
/**
* Get a connection handle from this pool.
*
* @param recycle true if we should try to get a connection in the NON_ACCESSIBLE pool in the same transaction
* @return a connection handle
* @throws Exception throw in the pool is unrecoverable or a timeout occurs getting a connection
*/
public Object getConnectionHandle(boolean recycle) throws Exception {
if (isFailed()) {
synchronized (this) {
try {
if (isFailed()) {
if (log.isDebugEnabled()) { log.debug("resource '" + bean.getUniqueName() + "' is marked as failed, resetting and recovering it before trying connection acquisition"); }
close();
init();
IncrementalRecoverer.recover(xaResourceProducer);
}
}
catch (RecoveryException ex) {
throw new BitronixRuntimeException("incremental recovery failed when trying to acquire a connection from failed resource '" + bean.getUniqueName() + "'", ex);
}
catch (Exception ex) {
throw new BitronixRuntimeException("pool reset failed when trying to acquire a connection from failed resource '" + bean.getUniqueName() + "'", ex);
}
}
}
- long before = MonotonicClock.currentTimeMillis();
long remainingTimeMs = bean.getAcquisitionTimeout() * 1000L;
while (true) {
+ long before = MonotonicClock.currentTimeMillis();
XAStatefulHolder xaStatefulHolder = null;
if (recycle) {
if (bean.getShareTransactionConnections()) {
xaStatefulHolder = getSharedXAStatefulHolder();
}
else {
xaStatefulHolder = getNotAccessible();
}
}
if (xaStatefulHolder == null) {
xaStatefulHolder = getInPool(remainingTimeMs);
}
if (log.isDebugEnabled()) { log.debug("found " + Decoder.decodeXAStatefulHolderState(xaStatefulHolder.getState()) + " connection " + xaStatefulHolder + " from " + this); }
try {
// getConnectionHandle() here could throw an exception, if it doesn't the connection is
// still alive and we can share it (if sharing is enabled)
Object connectionHandle = xaStatefulHolder.getConnectionHandle();
if (bean.getShareTransactionConnections()) {
putSharedXAStatefulHolder(xaStatefulHolder);
}
growUntilMinPoolSize();
return connectionHandle;
} catch (Exception ex) {
try {
if (log.isDebugEnabled()) { log.debug("connection is invalid, trying to close it", ex); }
xaStatefulHolder.close();
} catch (Exception ex2) {
if (log.isDebugEnabled()) { log.debug("exception while trying to close invalid connection, ignoring it", ex2); }
}
finally {
if (xaStatefulHolder.getState() != XAStatefulHolder.STATE_CLOSED) {
stateChanged(xaStatefulHolder, xaStatefulHolder.getState(), XAStatefulHolder.STATE_CLOSED);
}
if (log.isDebugEnabled()) { log.debug("removed invalid connection " + xaStatefulHolder + " from " + this); }
if (log.isDebugEnabled()) log.debug("waiting " + bean.getAcquisitionInterval() + "s before trying to acquire a connection again from " + this);
long waitTime = bean.getAcquisitionInterval() * 1000L;
if (waitTime > 0) {
try {
wait(waitTime);
} catch (InterruptedException ex2) {
// ignore
}
}
}
// check for timeout
long now = MonotonicClock.currentTimeMillis();
remainingTimeMs -= (now - before);
before = now;
if (remainingTimeMs <= 0) {
throw new BitronixRuntimeException("cannot get valid connection from " + this + " after trying for " + bean.getAcquisitionTimeout() + "s", ex);
}
Thread.sleep(bean.getAcquisitionInterval() * 1000L);
}
} // while true
}
/**
* Close down and cleanup this XAPool instance.
*/
public synchronized void close() {
if (log.isDebugEnabled()) { log.debug("closing all connections of " + this); }
for (XAStatefulHolder xaStatefulHolder : getXAResourceHolders()) {
try {
xaStatefulHolder.close();
} catch (Exception ex) {
if (log.isDebugEnabled()) { log.debug("ignoring exception while closing connection " + xaStatefulHolder, ex); }
}
}
if (TransactionManagerServices.isTaskSchedulerRunning())
TransactionManagerServices.getTaskScheduler().cancelPoolShrinking(this);
availablePool.clear();
accessiblePool.clear();
inaccessiblePool.clear();
failed.set(false);
}
/**
* Get the total size of this pool.
*
* @return the total size of this pool
*/
public long totalPoolSize() {
return availablePool.size() + accessiblePool.size() + inaccessiblePool.size();
}
public long inPoolSize() {
return availablePool.size();
}
public List<XAStatefulHolder> getXAResourceHolders() {
List<XAStatefulHolder> holders = new ArrayList<XAStatefulHolder>();
holders.addAll(availablePool);
holders.addAll(accessiblePool);
holders.addAll(inaccessiblePool);
return holders;
}
public Date getNextShrinkDate() {
return new Date(MonotonicClock.currentTimeMillis() + bean.getMaxIdleTime() * 1000);
}
/**
* This method is called to initialize the pool.
*
* @throws Exception
*/
private void init() throws Exception {
growUntilMinPoolSize();
if (bean.getMaxIdleTime() > 0) {
TransactionManagerServices.getTaskScheduler().schedulePoolShrinking(this);
}
}
public void shrink() throws Exception {
if (log.isDebugEnabled()) { log.debug("shrinking " + this); }
expireOrCloseStatefulHolders(false);
if (log.isDebugEnabled()) { log.debug("shrunk " + this); }
}
public void reset() throws Exception {
if (log.isDebugEnabled()) { log.debug("resetting " + this); }
expireOrCloseStatefulHolders(true);
if (log.isDebugEnabled()) { log.debug("reset " + this); }
}
private synchronized void expireOrCloseStatefulHolders(boolean forceClose) throws Exception {
int closed = 0;
final long now = MonotonicClock.currentTimeMillis();
final int availableSize = availablePool.size();
for (int i = 0; i < availableSize; i++) {
XAStatefulHolder xaStatefulHolder = availablePool.poll();
if (xaStatefulHolder == null) {
break;
}
long expirationTime = (xaStatefulHolder.getLastReleaseDate().getTime() + (bean.getMaxIdleTime() * 1000));
if (bean.getMaxLifeTime() > 0)
{
long endOfLife = xaStatefulHolder.getCreationDate().getTime() + (bean.getMaxLifeTime() * 1000);
expirationTime = Math.min(expirationTime, endOfLife);
}
if (!forceClose && log.isDebugEnabled()) { log.debug("checking if connection can be closed: " + xaStatefulHolder + " - closing time: " + expirationTime + ", now time: " + now); }
if (expirationTime <= now || forceClose) {
try {
closed++;
xaStatefulHolder.close();
} catch (Exception ex) {
log.warn("error closing " + xaStatefulHolder, ex);
}
} else {
availablePool.add(xaStatefulHolder);
}
} // for
if (log.isDebugEnabled()) { log.debug("closed " + closed + (forceClose ? " " : " idle ") + "connection(s)"); }
growUntilMinPoolSize();
}
public void stateChanged(XAStatefulHolder source, int oldState, int newState) {
stateTransitionLock.writeLock().lock();
try {
switch (newState) {
case XAStatefulHolder.STATE_IN_POOL:
if (log.isDebugEnabled()) { log.debug("added " + source + " to the available pool"); }
availablePool.add(source);
break;
case XAStatefulHolder.STATE_ACCESSIBLE:
if (log.isDebugEnabled()) { log.debug("added " + source + " to the accessible pool"); }
accessiblePool.add(source);
break;
case XAStatefulHolder.STATE_NOT_ACCESSIBLE:
if (log.isDebugEnabled()) { log.debug("added " + source + " to the inaccessible pool"); }
inaccessiblePool.add(source);
break;
case XAStatefulHolder.STATE_CLOSED:
source.removeStateChangeEventListener(this);
break;
}
}
finally {
stateTransitionLock.writeLock().unlock();
}
}
public void stateChanging(XAStatefulHolder source, int currentState, int futureState) {
stateTransitionLock.writeLock().lock();
try {
switch (currentState) {
case XAStatefulHolder.STATE_IN_POOL:
if (log.isDebugEnabled()) { log.debug("removed " + source + " from the available pool"); }
availablePool.remove(source);
break;
case XAStatefulHolder.STATE_ACCESSIBLE:
if (log.isDebugEnabled()) { log.debug("removed " + source + " from the accessible pool"); }
accessiblePool.remove(source);
break;
case XAStatefulHolder.STATE_NOT_ACCESSIBLE:
if (log.isDebugEnabled()) { log.debug("removed " + source + " from the inaccessible pool"); }
inaccessiblePool.remove(source);
break;
case XAStatefulHolder.STATE_CLOSED:
source.removeStateChangeEventListener(this);
break;
}
}
finally {
stateTransitionLock.writeLock().unlock();
}
}
public String toString() {
return "an XAPool of resource " + bean.getUniqueName() + " with " + totalPoolSize() + " connection(s) (" + inPoolSize() + " still available)" + (isFailed() ? " -failed-" : "");
}
private void createPooledObject(Object xaFactory) throws Exception {
XAStatefulHolder xaStatefulHolder = xaResourceProducer.createPooledConnection(xaFactory, bean);
xaStatefulHolder.addStateChangeEventListener(this);
availablePool.add(xaStatefulHolder);
}
private static Object createXAFactory(ResourceBean bean) throws Exception {
String className = bean.getClassName();
if (className == null)
throw new IllegalArgumentException("className cannot be null");
Class<?> xaFactoryClass = ClassLoaderUtils.loadClass(className);
Object xaFactory = xaFactoryClass.newInstance();
for (Map.Entry<Object, Object> entry : bean.getDriverProperties().entrySet()) {
String name = (String) entry.getKey();
Object value = entry.getValue();
if (name.endsWith(PASSWORD_PROPERTY_NAME)) {
value = decrypt(value.toString());
}
if (log.isDebugEnabled()) { log.debug("setting vendor property '" + name + "' to '" + value + "'"); }
PropertyUtils.setProperty(xaFactory, name, value);
}
return xaFactory;
}
private static String decrypt(String resourcePassword) throws Exception {
int startIdx = resourcePassword.indexOf("{");
int endIdx = resourcePassword.indexOf("}");
if (startIdx != 0 || endIdx == -1)
return resourcePassword;
String cipher = resourcePassword.substring(1, endIdx);
if (log.isDebugEnabled()) { log.debug("resource password is encrypted, decrypting " + resourcePassword); }
return CryptoEngine.decrypt(cipher, resourcePassword.substring(endIdx + 1));
}
/**
* Get a XAStatefulHolder (connection) from the NOT_ACCESSIBLE pool.
*
* @return a connection, or null if there are no connections in the inaccessible pool for the current transaction
*/
private XAStatefulHolder getNotAccessible() {
if (log.isDebugEnabled()) { log.debug("trying to recycle a NOT_ACCESSIBLE connection of " + this); }
BitronixTransaction transaction = TransactionContextHelper.currentTransaction();
if (transaction == null) {
if (log.isDebugEnabled()) { log.debug("no current transaction, no connection can be in state NOT_ACCESSIBLE when there is no global transaction context"); }
return null;
}
Uid currentTxGtrid = transaction.getResourceManager().getGtrid();
if (log.isDebugEnabled()) { log.debug("current transaction GTRID is [" + currentTxGtrid + "]"); }
stateTransitionLock.readLock().lock();
try {
for (XAStatefulHolder xaStatefulHolder : inaccessiblePool) {
if (log.isDebugEnabled()) { log.debug("found a connection in NOT_ACCESSIBLE state: " + xaStatefulHolder); }
if (containsXAResourceHolderMatchingGtrid(xaStatefulHolder, currentTxGtrid))
return xaStatefulHolder;
} // for
if (log.isDebugEnabled()) { log.debug("no NOT_ACCESSIBLE connection enlisted in this transaction"); }
return null;
}
finally {
stateTransitionLock.readLock().unlock();
}
}
private boolean containsXAResourceHolderMatchingGtrid(XAStatefulHolder xaStatefulHolder, final Uid currentTxGtrid) {
List<XAResourceHolder> xaResourceHolders = xaStatefulHolder.getXAResourceHolders();
if (log.isDebugEnabled()) { log.debug(xaResourceHolders.size() + " xa resource(s) created by connection in NOT_ACCESSIBLE state: " + xaStatefulHolder); }
for (XAResourceHolder xaResourceHolder : xaResourceHolders) {
class LocalVisitor implements XAResourceHolderStateVisitor {
private boolean found;
public boolean visit(XAResourceHolderState xaResourceHolderState) {
// compare GTRIDs
BitronixXid bitronixXid = xaResourceHolderState.getXid();
Uid resourceGtrid = bitronixXid.getGlobalTransactionIdUid();
if (log.isDebugEnabled()) { log.debug("NOT_ACCESSIBLE xa resource GTRID: " + resourceGtrid); }
if (currentTxGtrid.equals(resourceGtrid)) {
if (log.isDebugEnabled()) { log.debug("NOT_ACCESSIBLE xa resource's GTRID matched this transaction's GTRID, recycling it"); }
found = true;
}
return !found; // continue visitation if not found, stop visitation if found
}
}
LocalVisitor xaResourceHolderStateVisitor = new LocalVisitor();
xaResourceHolder.acceptVisitorForXAResourceHolderStates(currentTxGtrid, xaResourceHolderStateVisitor);
return xaResourceHolderStateVisitor.found;
}
return false;
}
/**
* Get an IN_POOL connection. This method blocks for up to remainingTimeMs milliseconds
* for someone to return or create a connection in the available pool. If remainingTimeMs
* expires, an exception is thrown.
*
* @param remainingTimeMs the maximum time to wait for a connection
* @return a connection from the available (IN_POOL) pool
* @throws Exception thrown in no connection is available before the remainingTimeMs time expires
*/
private XAStatefulHolder getInPool(long remainingTimeMs) throws Exception {
if (log.isDebugEnabled()) { log.debug("getting a IN_POOL connection from " + this); }
if (inPoolSize() == 0) {
if (log.isDebugEnabled()) { log.debug("no more free connection in " + this + ", trying to grow it"); }
grow();
}
if (log.isDebugEnabled()) { log.debug("getting IN_POOL connection, waiting if necessary, current size is " + inPoolSize()); }
try {
XAStatefulHolder xaStatefulHolder = availablePool.poll(remainingTimeMs, TimeUnit.MILLISECONDS);
if (xaStatefulHolder != null) {
return xaStatefulHolder;
}
throw new BitronixRuntimeException("XA pool of resource " + bean.getUniqueName() + " still empty after " + bean.getAcquisitionTimeout() + "s wait time");
} catch (InterruptedException e) {
throw new BitronixRuntimeException("Interrupted while waiting for IN_POOL connection.");
}
}
/**
* Grow the pool by "acquire increment" amount up to the max pool size.
*
* @throws Exception thrown if creating a pooled objects fails
*/
private synchronized void grow() throws Exception {
if (totalPoolSize() < bean.getMaxPoolSize()) {
long increment = bean.getAcquireIncrement();
if (totalPoolSize() + increment > bean.getMaxPoolSize()) {
increment = bean.getMaxPoolSize() - totalPoolSize();
}
if (log.isDebugEnabled()) { log.debug("incrementing " + bean.getUniqueName() + " pool size by " + increment + " unit(s) to reach " + (totalPoolSize() + increment) + " connection(s)"); }
for (int i=0; i < increment ;i++) {
createPooledObject(xaFactory);
}
}
else {
if (log.isDebugEnabled()) { log.debug("pool " + bean.getUniqueName() + " already at max size of " + totalPoolSize() + " connection(s), not growing it"); }
}
}
private synchronized void growUntilMinPoolSize() throws Exception {
if (log.isDebugEnabled()) { log.debug("growing " + this + " to minimum pool size " + bean.getMinPoolSize()); }
for (int i = (int)totalPoolSize(); i < bean.getMinPoolSize() ;i++) {
createPooledObject(xaFactory);
}
}
private synchronized void waitForConnectionInPool() {
long remainingTime = bean.getAcquisitionTimeout() * 1000L;
if (log.isDebugEnabled()) log.debug("waiting for IN_POOL connections count to be > 0, currently is " + inPoolSize());
while (inPoolSize() == 0) {
long before = MonotonicClock.currentTimeMillis();
try {
if (log.isDebugEnabled()) log.debug("waiting " + remainingTime + "ms");
wait(remainingTime);
if (log.isDebugEnabled()) log.debug("waiting over, IN_POOL connections count is now " + inPoolSize());
} catch (InterruptedException ex) {
// ignore
}
long now = MonotonicClock.currentTimeMillis();
remainingTime -= (now - before);
if (remainingTime <= 0 && inPoolSize() == 0) {
if (log.isDebugEnabled()) log.debug("connection pool dequeue timed out");
if (TransactionManagerServices.isTransactionManagerRunning())
TransactionManagerServices.getTransactionManager().dumpTransactionContexts();
throw new BitronixRuntimeException("XA pool of resource " + bean.getUniqueName() + " still empty after " + bean.getAcquisitionTimeout() + "s wait time");
}
} // while
}
/**
* Shared Connection Handling
*/
/**
* Try to get a shared XAStatefulHolder. This method will either return
* a shared XAStatefulHolder or <code>null</code>. If there is no current
* transaction, XAStatefulHolder's are not shared. If there is a transaction
* <i>and</i> there is a XAStatefulHolder associated with this thread already,
* we return that XAStatefulHolder (provided it is ACCESSIBLE or NOT_ACCESSIBLE).
*
* @return a shared XAStatefulHolder or <code>null</code>
*/
private XAStatefulHolder getSharedXAStatefulHolder() {
BitronixTransaction transaction = TransactionContextHelper.currentTransaction();
if (transaction == null) {
if (log.isDebugEnabled()) { log.debug("no current transaction, shared connection map will not be used"); }
return null;
}
Uid currentTxGtrid = transaction.getResourceManager().getGtrid();
StatefulHolderThreadLocal threadLocal = statefulHolderTransactionMap.get(currentTxGtrid);
if (threadLocal != null) {
XAStatefulHolder xaStatefulHolder = (XAStatefulHolder) threadLocal.get();
// Additional sanity checks...
if (xaStatefulHolder != null &&
xaStatefulHolder.getState() != XAStatefulHolder.STATE_IN_POOL &&
xaStatefulHolder.getState() != XAStatefulHolder.STATE_CLOSED) {
if (log.isDebugEnabled()) { log.debug("sharing connection " + xaStatefulHolder + " in transaction " + currentTxGtrid); }
return xaStatefulHolder;
}
}
return null;
}
/**
* Try to share a XAStatefulHolder with other callers on this thread. If
* there is no current transaction, the XAStatefulHolder is not put into the
* ThreadLocal. If there is a transaction, and it is the first time we're
* attempting to share a XAStatefulHolder on this thread, then we register
* a Synchronization so we can pull the ThreadLocals out of the shared map
* when the transaction completes (either commit() or rollback()). Without
* the Synchronization we would "leak".
*
* @param xaStatefulHolder a XAStatefulHolder to share with other callers
* on this thread.
*/
private void putSharedXAStatefulHolder(final XAStatefulHolder xaStatefulHolder) {
BitronixTransaction transaction = TransactionContextHelper.currentTransaction();
if (transaction == null) {
if (log.isDebugEnabled()) { log.debug("no current transaction, not adding " + xaStatefulHolder + " to shared connection map"); }
return;
}
final Uid currentTxGtrid = transaction.getResourceManager().getGtrid();
StatefulHolderThreadLocal threadLocal = statefulHolderTransactionMap.get(currentTxGtrid);
if (threadLocal == null) {
// This is the first time this TxGtrid/ThreadLocal is going into the map,
// register interest in synchronization so we can remove it at commit/rollback
try {
transaction.registerSynchronization(new SharedStatefulHolderCleanupSynchronization(currentTxGtrid));
} catch (Exception e) {
// OK, forget it. The transaction is either rollback only or already finished.
return;
}
threadLocal = new StatefulHolderThreadLocal();
statefulHolderTransactionMap.put(currentTxGtrid, threadLocal);
if (log.isDebugEnabled()) { log.debug("added shared connection mapping for " + currentTxGtrid + " holder " + xaStatefulHolder); }
}
// Set the XAStatefulHolder on the ThreadLocal. Even if we've already set it before,
// it's safe -- checking would be more expensive than just setting it again.
threadLocal.set(xaStatefulHolder);
}
private final class SharedStatefulHolderCleanupSynchronization implements Synchronization {
private final Uid gtrid;
private SharedStatefulHolderCleanupSynchronization(Uid gtrid) {
this.gtrid = gtrid;
}
public void beforeCompletion() {
}
public void afterCompletion(int status) {
statefulHolderTransactionMap.remove(gtrid);
if (log.isDebugEnabled()) { log.debug("deleted shared connection mappings for " + gtrid); }
}
public String toString() {
return "a SharedStatefulHolderCleanupSynchronization with GTRID [" + gtrid + "]";
}
}
private final class StatefulHolderThreadLocal extends ThreadLocal<XAStatefulHolder>
{
@Override
public XAStatefulHolder get() {
return super.get();
}
@Override
public void set(XAStatefulHolder value) {
super.set(value);
}
}
}
| false | true | public Object getConnectionHandle(boolean recycle) throws Exception {
if (isFailed()) {
synchronized (this) {
try {
if (isFailed()) {
if (log.isDebugEnabled()) { log.debug("resource '" + bean.getUniqueName() + "' is marked as failed, resetting and recovering it before trying connection acquisition"); }
close();
init();
IncrementalRecoverer.recover(xaResourceProducer);
}
}
catch (RecoveryException ex) {
throw new BitronixRuntimeException("incremental recovery failed when trying to acquire a connection from failed resource '" + bean.getUniqueName() + "'", ex);
}
catch (Exception ex) {
throw new BitronixRuntimeException("pool reset failed when trying to acquire a connection from failed resource '" + bean.getUniqueName() + "'", ex);
}
}
}
long before = MonotonicClock.currentTimeMillis();
long remainingTimeMs = bean.getAcquisitionTimeout() * 1000L;
while (true) {
XAStatefulHolder xaStatefulHolder = null;
if (recycle) {
if (bean.getShareTransactionConnections()) {
xaStatefulHolder = getSharedXAStatefulHolder();
}
else {
xaStatefulHolder = getNotAccessible();
}
}
if (xaStatefulHolder == null) {
xaStatefulHolder = getInPool(remainingTimeMs);
}
if (log.isDebugEnabled()) { log.debug("found " + Decoder.decodeXAStatefulHolderState(xaStatefulHolder.getState()) + " connection " + xaStatefulHolder + " from " + this); }
try {
// getConnectionHandle() here could throw an exception, if it doesn't the connection is
// still alive and we can share it (if sharing is enabled)
Object connectionHandle = xaStatefulHolder.getConnectionHandle();
if (bean.getShareTransactionConnections()) {
putSharedXAStatefulHolder(xaStatefulHolder);
}
growUntilMinPoolSize();
return connectionHandle;
} catch (Exception ex) {
try {
if (log.isDebugEnabled()) { log.debug("connection is invalid, trying to close it", ex); }
xaStatefulHolder.close();
} catch (Exception ex2) {
if (log.isDebugEnabled()) { log.debug("exception while trying to close invalid connection, ignoring it", ex2); }
}
finally {
if (xaStatefulHolder.getState() != XAStatefulHolder.STATE_CLOSED) {
stateChanged(xaStatefulHolder, xaStatefulHolder.getState(), XAStatefulHolder.STATE_CLOSED);
}
if (log.isDebugEnabled()) { log.debug("removed invalid connection " + xaStatefulHolder + " from " + this); }
if (log.isDebugEnabled()) log.debug("waiting " + bean.getAcquisitionInterval() + "s before trying to acquire a connection again from " + this);
long waitTime = bean.getAcquisitionInterval() * 1000L;
if (waitTime > 0) {
try {
wait(waitTime);
} catch (InterruptedException ex2) {
// ignore
}
}
}
// check for timeout
long now = MonotonicClock.currentTimeMillis();
remainingTimeMs -= (now - before);
before = now;
if (remainingTimeMs <= 0) {
throw new BitronixRuntimeException("cannot get valid connection from " + this + " after trying for " + bean.getAcquisitionTimeout() + "s", ex);
}
Thread.sleep(bean.getAcquisitionInterval() * 1000L);
}
} // while true
}
| public Object getConnectionHandle(boolean recycle) throws Exception {
if (isFailed()) {
synchronized (this) {
try {
if (isFailed()) {
if (log.isDebugEnabled()) { log.debug("resource '" + bean.getUniqueName() + "' is marked as failed, resetting and recovering it before trying connection acquisition"); }
close();
init();
IncrementalRecoverer.recover(xaResourceProducer);
}
}
catch (RecoveryException ex) {
throw new BitronixRuntimeException("incremental recovery failed when trying to acquire a connection from failed resource '" + bean.getUniqueName() + "'", ex);
}
catch (Exception ex) {
throw new BitronixRuntimeException("pool reset failed when trying to acquire a connection from failed resource '" + bean.getUniqueName() + "'", ex);
}
}
}
long remainingTimeMs = bean.getAcquisitionTimeout() * 1000L;
while (true) {
long before = MonotonicClock.currentTimeMillis();
XAStatefulHolder xaStatefulHolder = null;
if (recycle) {
if (bean.getShareTransactionConnections()) {
xaStatefulHolder = getSharedXAStatefulHolder();
}
else {
xaStatefulHolder = getNotAccessible();
}
}
if (xaStatefulHolder == null) {
xaStatefulHolder = getInPool(remainingTimeMs);
}
if (log.isDebugEnabled()) { log.debug("found " + Decoder.decodeXAStatefulHolderState(xaStatefulHolder.getState()) + " connection " + xaStatefulHolder + " from " + this); }
try {
// getConnectionHandle() here could throw an exception, if it doesn't the connection is
// still alive and we can share it (if sharing is enabled)
Object connectionHandle = xaStatefulHolder.getConnectionHandle();
if (bean.getShareTransactionConnections()) {
putSharedXAStatefulHolder(xaStatefulHolder);
}
growUntilMinPoolSize();
return connectionHandle;
} catch (Exception ex) {
try {
if (log.isDebugEnabled()) { log.debug("connection is invalid, trying to close it", ex); }
xaStatefulHolder.close();
} catch (Exception ex2) {
if (log.isDebugEnabled()) { log.debug("exception while trying to close invalid connection, ignoring it", ex2); }
}
finally {
if (xaStatefulHolder.getState() != XAStatefulHolder.STATE_CLOSED) {
stateChanged(xaStatefulHolder, xaStatefulHolder.getState(), XAStatefulHolder.STATE_CLOSED);
}
if (log.isDebugEnabled()) { log.debug("removed invalid connection " + xaStatefulHolder + " from " + this); }
if (log.isDebugEnabled()) log.debug("waiting " + bean.getAcquisitionInterval() + "s before trying to acquire a connection again from " + this);
long waitTime = bean.getAcquisitionInterval() * 1000L;
if (waitTime > 0) {
try {
wait(waitTime);
} catch (InterruptedException ex2) {
// ignore
}
}
}
// check for timeout
long now = MonotonicClock.currentTimeMillis();
remainingTimeMs -= (now - before);
before = now;
if (remainingTimeMs <= 0) {
throw new BitronixRuntimeException("cannot get valid connection from " + this + " after trying for " + bean.getAcquisitionTimeout() + "s", ex);
}
Thread.sleep(bean.getAcquisitionInterval() * 1000L);
}
} // while true
}
|
diff --git a/jasper-reports/008-06-script-filling-parameters/src/JasperApp.java b/jasper-reports/008-06-script-filling-parameters/src/JasperApp.java
index 1d91da0..8a19aaa 100644
--- a/jasper-reports/008-06-script-filling-parameters/src/JasperApp.java
+++ b/jasper-reports/008-06-script-filling-parameters/src/JasperApp.java
@@ -1,203 +1,203 @@
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Panel;
import java.awt.Toolkit;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperPrintManager;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.export.JExcelApiExporter;
import net.sf.jasperreports.engine.export.JExcelApiMetadataExporter;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRCsvMetadataExporter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRPdfExporterParameter;
import net.sf.jasperreports.engine.export.JRRtfExporter;
import net.sf.jasperreports.engine.export.JRXhtmlExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.export.oasis.JROdsExporter;
import net.sf.jasperreports.engine.export.oasis.JROdtExporter;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter;
import net.sf.jasperreports.engine.export.ooxml.JRPptxExporter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.engine.util.AbstractSampleApp;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.util.AbstractSampleApp;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.util.JRSaver;
import mutil.base.ExceptionAdapter;
import mutil.base.Holder;
import mutil.base.FileUtil;
import org.python.core.PyCode;
import org.python.core.PyException;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang3.StringEscapeUtils;
public class JasperApp
{
private static final Logger l = LoggerFactory.getLogger(JasperApp.class);
public static void main(String[] args) throws JRException, IOException {
switch (args[0]) {
case "pdf": pdf(args[1]);
break;
default:
throw new RuntimeException("unrecognized case");
}
System.err.println("exiting "+JasperApp.class.getName()+"#main");
}
private static String className () { return JasperApp.class.getName() ; }
private static String reportCoreName () { return "groups" ; }
private static String compiledReportName() { return reportCoreName()+".jasper"; }
private static String pdfReportName () { return reportCoreName()+".pdf" ; }
private static Connection getHsqlConnection() throws JRException {
Connection conn;
try {
String driver = "org.hsqldb.jdbcDriver";
String connectString = "jdbc:hsqldb:hsql://localhost";
String user = "sa";
String password = "";
Class.forName(driver);
conn = DriverManager.getConnection(connectString, user, password);
System.out.println("Connection obtained: "+((conn==null)?"null":"not null"));
}
catch (ClassNotFoundException e) {
throw new JRException(e);
}
catch (SQLException e) {
throw new JRException(e);
}
return conn;
}
private static File fill() throws JRException, IOException {
long start = System.currentTimeMillis();
String sourceFileLocation = "reports/"+compiledReportName();
System.err.println(" sourceFileLocation : " + sourceFileLocation);
JasperReport jasperReport = (JasperReport)JRLoader.loadObjectFromLocation(sourceFileLocation);
String script = FileUtil.readFileAsSingleString(new File("script.py"), "\n");
System.out.println("script file read as follows:\n");
System.out.println(script);
- /*
- "q1 = sql.q('SELECT ORDERID FROM PUBLIC.ORDERS')\n" +
- "STR_1 = 'Pi One'\n" +
- "I_2=3**2\nI_3=2\n" +
- "I_4=I_2**I_3\n" +
- "I_5=q1[1]\n" +
- "q2 = sql.q('SELECT SHIPCOUNTRY FROM PUBLIC.ORDERS WHERE ORDERID=%d'%I_5)\n" +
- "STR_b=q2[1]" ;*/
System.out.println("\\---------------- end of script file ------------/");
- Map<String, Object> parameters = processParameters(getHsqlConnection(), script);
+ String escapedScript = StringEscapeUtils.escapeJava(script);
+ System.out.println("escaped script file read as follows:\n");
+ System.out.println(escapedScript);
+ System.out.println("\\---------------- end of escaped script file ------------/");
+ String escapedScriptNewLinesCorrected = escapedScript.replaceAll("\\\\n", "\n");
+ System.out.println("escaped script new lines corrected file read as follows:\n");
+ System.out.println(escapedScriptNewLinesCorrected);
+ System.out.println("\\---------------- end of escaped script new lines corrected file ------------/");
+ Map<String, Object> parameters = processParameters(getHsqlConnection(), escapedScriptNewLinesCorrected); // script) ;// escapedScript);
printParameters(parameters);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, getHsqlConnection());
File destTempFile = null;
try {
destTempFile = File.createTempFile("jasper-"+className(), ".jrprint");
} catch (IOException e) {
throw new ExceptionAdapter(e);
}
JRSaver.saveObject(jasperPrint, destTempFile);
System.err.println("Filling time : " + (System.currentTimeMillis() - start));
return destTempFile;
}
private static void printParameters(Map<String, Object> params) {
System.out.println("----------- έλεγχος -----------");
String s = StringEscapeUtils.unescapeJava("\u00ce\u00a0\u00ce\u00b9 \u00ce\u00ad\u00ce\u00bd\u00ce\u00b1");
System.out.println(s);
String test = "\u03a0\u03b9 \u03ad\u03bd\u03b1";
System.out.println("test = " +test);
for (String key : params.keySet()) {
if (!key.startsWith("STR_"))
System.out.println(key+" --> "+params.get(key));
else {
System.out.println(key+" --> "+StringEscapeUtils.unescapeJava((String)params.get(key)));
params.put(key, StringEscapeUtils.unescapeJava((String)params.get(key)));
}
}
}
public static Map<String, Object> processParameters(Connection conn, String script) throws JRException {
Map<String, Object> params = new HashMap<String, Object>();
{
PythonInterpreter pi = new PythonInterpreter();
QueryJythonHolder sql = new QueryJythonHolder(conn);
pi.set("params", params);
pi.set("sql", sql);
PyObject result = null;
try {
PyCode code = pi.compile(adorn(script, "params"));
result = pi.eval(code);
l.info("evalution result = "+result);
} catch (PyException pyException) {
throw new ExceptionAdapter(pyException);
}
}
return params;
}
private static List<String> paramNames(String script, String paramRegExp) {
List<String> retValue = new ArrayList<String>();
Pattern p0 = Pattern.compile(paramRegExp);
Matcher m = p0.matcher(script);
while (m.find()) {
retValue.add(m.group(0));
}
return retValue;
}
public static void mmain(String args[]) {
System.out.println(paramNames("STR_1=sdf I_3=I_2+I_3;BD_234\nBD_3; dfasdfsdfasdfasdfasdf", "(STR|BD|I|D)_\\w*"));
}
private static final String adorn(String script, String paramsVar) {
List<String> paramNames = paramNames(script, "(STR|BD|I|D)_\\w*");
StringBuilder sb = new StringBuilder();
sb.append("\n");
for (String paramName : paramNames)
sb.append(String.format("%s.put('%s', %s)\n", paramsVar, paramName, paramName));
return script+sb.toString();
}
public static void pdf(String whereToProducePDF) throws JRException, IOException {
File jrprintFile = fill();
long start = System.currentTimeMillis();
JasperExportManager.exportReportToPdfFile(jrprintFile.getAbsolutePath(), whereToProducePDF+"/"+pdfReportName());
System.err.println("PDF creation time : " + (System.currentTimeMillis() - start));
}
}
| false | true | private static File fill() throws JRException, IOException {
long start = System.currentTimeMillis();
String sourceFileLocation = "reports/"+compiledReportName();
System.err.println(" sourceFileLocation : " + sourceFileLocation);
JasperReport jasperReport = (JasperReport)JRLoader.loadObjectFromLocation(sourceFileLocation);
String script = FileUtil.readFileAsSingleString(new File("script.py"), "\n");
System.out.println("script file read as follows:\n");
System.out.println(script);
/*
"q1 = sql.q('SELECT ORDERID FROM PUBLIC.ORDERS')\n" +
"STR_1 = 'Pi One'\n" +
"I_2=3**2\nI_3=2\n" +
"I_4=I_2**I_3\n" +
"I_5=q1[1]\n" +
"q2 = sql.q('SELECT SHIPCOUNTRY FROM PUBLIC.ORDERS WHERE ORDERID=%d'%I_5)\n" +
"STR_b=q2[1]" ;*/
System.out.println("\\---------------- end of script file ------------/");
Map<String, Object> parameters = processParameters(getHsqlConnection(), script);
printParameters(parameters);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, getHsqlConnection());
File destTempFile = null;
try {
destTempFile = File.createTempFile("jasper-"+className(), ".jrprint");
} catch (IOException e) {
throw new ExceptionAdapter(e);
}
JRSaver.saveObject(jasperPrint, destTempFile);
System.err.println("Filling time : " + (System.currentTimeMillis() - start));
return destTempFile;
}
| private static File fill() throws JRException, IOException {
long start = System.currentTimeMillis();
String sourceFileLocation = "reports/"+compiledReportName();
System.err.println(" sourceFileLocation : " + sourceFileLocation);
JasperReport jasperReport = (JasperReport)JRLoader.loadObjectFromLocation(sourceFileLocation);
String script = FileUtil.readFileAsSingleString(new File("script.py"), "\n");
System.out.println("script file read as follows:\n");
System.out.println(script);
System.out.println("\\---------------- end of script file ------------/");
String escapedScript = StringEscapeUtils.escapeJava(script);
System.out.println("escaped script file read as follows:\n");
System.out.println(escapedScript);
System.out.println("\\---------------- end of escaped script file ------------/");
String escapedScriptNewLinesCorrected = escapedScript.replaceAll("\\\\n", "\n");
System.out.println("escaped script new lines corrected file read as follows:\n");
System.out.println(escapedScriptNewLinesCorrected);
System.out.println("\\---------------- end of escaped script new lines corrected file ------------/");
Map<String, Object> parameters = processParameters(getHsqlConnection(), escapedScriptNewLinesCorrected); // script) ;// escapedScript);
printParameters(parameters);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, getHsqlConnection());
File destTempFile = null;
try {
destTempFile = File.createTempFile("jasper-"+className(), ".jrprint");
} catch (IOException e) {
throw new ExceptionAdapter(e);
}
JRSaver.saveObject(jasperPrint, destTempFile);
System.err.println("Filling time : " + (System.currentTimeMillis() - start));
return destTempFile;
}
|
diff --git a/stripes/src/net/sourceforge/stripes/controller/DispatcherServlet.java b/stripes/src/net/sourceforge/stripes/controller/DispatcherServlet.java
index 496f464c..77180cd3 100644
--- a/stripes/src/net/sourceforge/stripes/controller/DispatcherServlet.java
+++ b/stripes/src/net/sourceforge/stripes/controller/DispatcherServlet.java
@@ -1,178 +1,178 @@
/* Copyright (C) 2005 Tim Fennell
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the license with this software. If not,
* it can be found online at http://www.fsf.org/licensing/licenses/lgpl.html
*/
package net.sourceforge.stripes.controller;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.DontValidate;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.exception.StripesServletException;
import net.sourceforge.stripes.util.Log;
import net.sourceforge.stripes.validation.Validatable;
import net.sourceforge.stripes.validation.ValidationError;
import net.sourceforge.stripes.validation.ValidationErrorHandler;
import net.sourceforge.stripes.validation.ValidationErrors;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
/**
* Servlet that controls how requests to the Stripes framework are processed. Uses an instance of
* the ActionResolver interface to locate the bean and method used to handle the current request and
* then delegates processing to the bean.
*
* @author Tim Fennell
*/
public class DispatcherServlet extends HttpServlet {
/** Log used throughout the class. */
private static Log log = Log.getInstance(DispatcherServlet.class);
/** Implemented as a simple call to doPost(request, response). */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* Uses the configured actionResolver to locate the appropriate ActionBean type and method to handle
* the current request. Instantiates the ActionBean, provides it references to the request and
* response and then invokes the handler method.
*
* @param request the HttpServletRequest handed to the class by the container
* @param response the HttpServletResponse paired to the request
* @throws ServletException thrown when the system fails to process the request in any way
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
try {
// Lookup the bean, handler method and hook everything together
ActionBeanContext context = StripesFilter.getConfiguration()
.getActionBeanContextFactory().getContextInstance(request, response);
Resolution resolution = null;
ActionResolver actionResolver = StripesFilter.getConfiguration().getActionResolver();
ActionBean bean = actionResolver.getActionBean(context);
String eventName = actionResolver.getEventName(bean.getClass(), context);
context.setEventName(eventName);
Method handler = null;
if (eventName != null) {
handler = actionResolver.getHandler(bean.getClass(), eventName);
}
else {
handler = actionResolver.getDefaultHandler(bean.getClass());
}
// Insist that we have a handler
if (handler == null) {
throw new StripesServletException("No handler method found for request with " +
"ActionBean [" + bean.getClass().getName() + "] and eventName [ " + eventName + "]");
}
bean.setContext(context);
request.setAttribute((String) request.getAttribute(ActionResolver.RESOLVED_ACTION), bean);
request.setAttribute(StripesConstants.REQ_ATTR_ACTION_BEAN, bean);
// Find out if we're validating for this event or not
boolean doValidate = (handler.getAnnotation(DontValidate.class) == null);
// Bind the value to the bean - this includes performing field level validation
ValidationErrors errors = bindValues(bean, context, doValidate);
bean.getContext().setValidationErrors(errors);
// If blah blah blah, run the bean's validate method, or maybe handleErrors
if (errors.size() == 0 && bean instanceof Validatable && doValidate) {
((Validatable) bean).validate(errors);
}
// If we have errors, add the action path to them
if (errors.size() > 0) {
String formAction = (String) request.getAttribute(ActionResolver.RESOLVED_ACTION);
/** Since we don't pass form action down the stack, we add it to the errors here. */
for (List<ValidationError> listOfErrors : errors.values()) {
for (ValidationError error : listOfErrors) {
error.setActionPath(formAction);
}
}
}
// Now if we have errors and the bean wants to handle them...
if (errors.size() > 0 && bean instanceof ValidationErrorHandler) {
resolution = ((ValidationErrorHandler) bean).handleValidationErrors(errors);
}
// If there are still errors see if we need to lookup the resolution
if (errors.size() > 0 && resolution == null) {
resolution = context.getSourcePageResolution();
}
else if (errors.size() == 0) {
Object returnValue = handler.invoke(bean);
if (returnValue != null && returnValue instanceof Resolution) {
resolution = (Resolution) returnValue;
}
else {
log.warn("Expected handler method ", handler.getName(), " on class ",
bean.getClass().getSimpleName(), " to return a Resolution. Instead it ",
"returned: ", returnValue);
}
}
// Finally, execute the resolution
- resolution.execute(request, response);
+ if (resolution != null) resolution.execute(request, response);
}
catch (ServletException se) { throw se; }
catch (RuntimeException re) { throw re; }
catch (InvocationTargetException ite) {
if (ite.getTargetException() instanceof ServletException) {
throw (ServletException) ite.getTargetException();
}
else if (ite.getTargetException() instanceof RuntimeException) {
throw (RuntimeException) ite.getTargetException();
}
else {
throw new StripesServletException
("ActionBean execution threw an exception.", ite.getTargetException());
}
}
catch (Exception e) {
throw new StripesServletException("Exception encountered processing request.", e);
}
}
/**
* Invokes the configured property binder in order to populate the bean's properties from the
* values contained in the request.
*
* @param bean the bean to be populated
* @param context the ActionBeanContext containing the request and other information
*/
protected ValidationErrors bindValues(ActionBean bean,
ActionBeanContext context,
boolean validate) throws StripesServletException {
return StripesFilter.getConfiguration()
.getActionBeanPropertyBinder().bind(bean, context, validate);
}
}
| true | true | protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
try {
// Lookup the bean, handler method and hook everything together
ActionBeanContext context = StripesFilter.getConfiguration()
.getActionBeanContextFactory().getContextInstance(request, response);
Resolution resolution = null;
ActionResolver actionResolver = StripesFilter.getConfiguration().getActionResolver();
ActionBean bean = actionResolver.getActionBean(context);
String eventName = actionResolver.getEventName(bean.getClass(), context);
context.setEventName(eventName);
Method handler = null;
if (eventName != null) {
handler = actionResolver.getHandler(bean.getClass(), eventName);
}
else {
handler = actionResolver.getDefaultHandler(bean.getClass());
}
// Insist that we have a handler
if (handler == null) {
throw new StripesServletException("No handler method found for request with " +
"ActionBean [" + bean.getClass().getName() + "] and eventName [ " + eventName + "]");
}
bean.setContext(context);
request.setAttribute((String) request.getAttribute(ActionResolver.RESOLVED_ACTION), bean);
request.setAttribute(StripesConstants.REQ_ATTR_ACTION_BEAN, bean);
// Find out if we're validating for this event or not
boolean doValidate = (handler.getAnnotation(DontValidate.class) == null);
// Bind the value to the bean - this includes performing field level validation
ValidationErrors errors = bindValues(bean, context, doValidate);
bean.getContext().setValidationErrors(errors);
// If blah blah blah, run the bean's validate method, or maybe handleErrors
if (errors.size() == 0 && bean instanceof Validatable && doValidate) {
((Validatable) bean).validate(errors);
}
// If we have errors, add the action path to them
if (errors.size() > 0) {
String formAction = (String) request.getAttribute(ActionResolver.RESOLVED_ACTION);
/** Since we don't pass form action down the stack, we add it to the errors here. */
for (List<ValidationError> listOfErrors : errors.values()) {
for (ValidationError error : listOfErrors) {
error.setActionPath(formAction);
}
}
}
// Now if we have errors and the bean wants to handle them...
if (errors.size() > 0 && bean instanceof ValidationErrorHandler) {
resolution = ((ValidationErrorHandler) bean).handleValidationErrors(errors);
}
// If there are still errors see if we need to lookup the resolution
if (errors.size() > 0 && resolution == null) {
resolution = context.getSourcePageResolution();
}
else if (errors.size() == 0) {
Object returnValue = handler.invoke(bean);
if (returnValue != null && returnValue instanceof Resolution) {
resolution = (Resolution) returnValue;
}
else {
log.warn("Expected handler method ", handler.getName(), " on class ",
bean.getClass().getSimpleName(), " to return a Resolution. Instead it ",
"returned: ", returnValue);
}
}
// Finally, execute the resolution
resolution.execute(request, response);
}
catch (ServletException se) { throw se; }
catch (RuntimeException re) { throw re; }
catch (InvocationTargetException ite) {
if (ite.getTargetException() instanceof ServletException) {
throw (ServletException) ite.getTargetException();
}
else if (ite.getTargetException() instanceof RuntimeException) {
throw (RuntimeException) ite.getTargetException();
}
else {
throw new StripesServletException
("ActionBean execution threw an exception.", ite.getTargetException());
}
}
catch (Exception e) {
throw new StripesServletException("Exception encountered processing request.", e);
}
}
| protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
try {
// Lookup the bean, handler method and hook everything together
ActionBeanContext context = StripesFilter.getConfiguration()
.getActionBeanContextFactory().getContextInstance(request, response);
Resolution resolution = null;
ActionResolver actionResolver = StripesFilter.getConfiguration().getActionResolver();
ActionBean bean = actionResolver.getActionBean(context);
String eventName = actionResolver.getEventName(bean.getClass(), context);
context.setEventName(eventName);
Method handler = null;
if (eventName != null) {
handler = actionResolver.getHandler(bean.getClass(), eventName);
}
else {
handler = actionResolver.getDefaultHandler(bean.getClass());
}
// Insist that we have a handler
if (handler == null) {
throw new StripesServletException("No handler method found for request with " +
"ActionBean [" + bean.getClass().getName() + "] and eventName [ " + eventName + "]");
}
bean.setContext(context);
request.setAttribute((String) request.getAttribute(ActionResolver.RESOLVED_ACTION), bean);
request.setAttribute(StripesConstants.REQ_ATTR_ACTION_BEAN, bean);
// Find out if we're validating for this event or not
boolean doValidate = (handler.getAnnotation(DontValidate.class) == null);
// Bind the value to the bean - this includes performing field level validation
ValidationErrors errors = bindValues(bean, context, doValidate);
bean.getContext().setValidationErrors(errors);
// If blah blah blah, run the bean's validate method, or maybe handleErrors
if (errors.size() == 0 && bean instanceof Validatable && doValidate) {
((Validatable) bean).validate(errors);
}
// If we have errors, add the action path to them
if (errors.size() > 0) {
String formAction = (String) request.getAttribute(ActionResolver.RESOLVED_ACTION);
/** Since we don't pass form action down the stack, we add it to the errors here. */
for (List<ValidationError> listOfErrors : errors.values()) {
for (ValidationError error : listOfErrors) {
error.setActionPath(formAction);
}
}
}
// Now if we have errors and the bean wants to handle them...
if (errors.size() > 0 && bean instanceof ValidationErrorHandler) {
resolution = ((ValidationErrorHandler) bean).handleValidationErrors(errors);
}
// If there are still errors see if we need to lookup the resolution
if (errors.size() > 0 && resolution == null) {
resolution = context.getSourcePageResolution();
}
else if (errors.size() == 0) {
Object returnValue = handler.invoke(bean);
if (returnValue != null && returnValue instanceof Resolution) {
resolution = (Resolution) returnValue;
}
else {
log.warn("Expected handler method ", handler.getName(), " on class ",
bean.getClass().getSimpleName(), " to return a Resolution. Instead it ",
"returned: ", returnValue);
}
}
// Finally, execute the resolution
if (resolution != null) resolution.execute(request, response);
}
catch (ServletException se) { throw se; }
catch (RuntimeException re) { throw re; }
catch (InvocationTargetException ite) {
if (ite.getTargetException() instanceof ServletException) {
throw (ServletException) ite.getTargetException();
}
else if (ite.getTargetException() instanceof RuntimeException) {
throw (RuntimeException) ite.getTargetException();
}
else {
throw new StripesServletException
("ActionBean execution threw an exception.", ite.getTargetException());
}
}
catch (Exception e) {
throw new StripesServletException("Exception encountered processing request.", e);
}
}
|
diff --git a/src/com/undeadscythes/udsplugin/eventhandlers/EntityDamage.java b/src/com/undeadscythes/udsplugin/eventhandlers/EntityDamage.java
index 6537342..4710730 100644
--- a/src/com/undeadscythes/udsplugin/eventhandlers/EntityDamage.java
+++ b/src/com/undeadscythes/udsplugin/eventhandlers/EntityDamage.java
@@ -1,48 +1,48 @@
package com.undeadscythes.udsplugin.eventhandlers;
import com.undeadscythes.udsplugin.*;
import org.bukkit.entity.*;
import org.bukkit.event.*;
import org.bukkit.event.entity.*;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
/**
* When an entity is damaged.
* @author UndeadScythes
*/
public class EntityDamage extends ListenerWrapper implements Listener {
@EventHandler
public final void onEvent(final EntityDamageEvent event) {
if((event.getEntity() instanceof Player)) {
final SaveablePlayer player = UDSPlugin.getOnlinePlayers().get(((Player)event.getEntity()).getName());
if(player.hasGodMode() || player.isAfk() || (event.getCause().equals(DamageCause.DROWNING) && player.hasScuba())) {
event.setCancelled(true);
}
- if(((Damageable)player).getHealth() < event.getDamage()) {
+ if(((Damageable)event.getEntity()).getHealth() < event.getDamage()) {
for(Region arena : UDSPlugin.getRegions(RegionType.ARENA).values()) {
if(arena.contains(player.getLocation())) {
event.setCancelled(true);
player.teleport(arena.getWarp());
player.setHealth(player.getMaxHealth());
}
}
if(player.isDuelling()) {
challengeLoss(player);
}
}
} else if(UDSPlugin.getPassiveMobs().contains(event.getEntity().getType()) && !hasFlag(event.getEntity().getLocation(), RegionFlag.PVE)) {
event.setCancelled(true);
}
}
private void challengeLoss(final SaveablePlayer loser) {
final SaveablePlayer winner = loser.getChallenger();
winner.credit(2 * winner.getWager());
winner.endChallenge();
winner.sendMessage(Color.MESSAGE + "You won the challenge.");
winner.setHealth(winner.getMaxHealth());
loser.endChallenge();
loser.sendMessage(Color.MESSAGE + "You lost the challenge.");
loser.setHealth(loser.getMaxHealth());
}
}
| true | true | public final void onEvent(final EntityDamageEvent event) {
if((event.getEntity() instanceof Player)) {
final SaveablePlayer player = UDSPlugin.getOnlinePlayers().get(((Player)event.getEntity()).getName());
if(player.hasGodMode() || player.isAfk() || (event.getCause().equals(DamageCause.DROWNING) && player.hasScuba())) {
event.setCancelled(true);
}
if(((Damageable)player).getHealth() < event.getDamage()) {
for(Region arena : UDSPlugin.getRegions(RegionType.ARENA).values()) {
if(arena.contains(player.getLocation())) {
event.setCancelled(true);
player.teleport(arena.getWarp());
player.setHealth(player.getMaxHealth());
}
}
if(player.isDuelling()) {
challengeLoss(player);
}
}
} else if(UDSPlugin.getPassiveMobs().contains(event.getEntity().getType()) && !hasFlag(event.getEntity().getLocation(), RegionFlag.PVE)) {
event.setCancelled(true);
}
}
| public final void onEvent(final EntityDamageEvent event) {
if((event.getEntity() instanceof Player)) {
final SaveablePlayer player = UDSPlugin.getOnlinePlayers().get(((Player)event.getEntity()).getName());
if(player.hasGodMode() || player.isAfk() || (event.getCause().equals(DamageCause.DROWNING) && player.hasScuba())) {
event.setCancelled(true);
}
if(((Damageable)event.getEntity()).getHealth() < event.getDamage()) {
for(Region arena : UDSPlugin.getRegions(RegionType.ARENA).values()) {
if(arena.contains(player.getLocation())) {
event.setCancelled(true);
player.teleport(arena.getWarp());
player.setHealth(player.getMaxHealth());
}
}
if(player.isDuelling()) {
challengeLoss(player);
}
}
} else if(UDSPlugin.getPassiveMobs().contains(event.getEntity().getType()) && !hasFlag(event.getEntity().getLocation(), RegionFlag.PVE)) {
event.setCancelled(true);
}
}
|
diff --git a/server/src/org/bedework/caldav/server/CaldavCalNode.java b/server/src/org/bedework/caldav/server/CaldavCalNode.java
index f215459..d7a42be 100644
--- a/server/src/org/bedework/caldav/server/CaldavCalNode.java
+++ b/server/src/org/bedework/caldav/server/CaldavCalNode.java
@@ -1,1558 +1,1558 @@
/* ********************************************************************
Licensed to Jasig under one or more contributor license
agreements. See the NOTICE file distributed with this work
for additional information regarding copyright ownership.
Jasig 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.bedework.caldav.server;
import org.bedework.caldav.server.sysinterface.CalPrincipalInfo;
import org.bedework.caldav.server.sysinterface.SysIntf;
import org.bedework.caldav.server.sysinterface.SysIntf.MethodEmitted;
import edu.rpi.cct.webdav.servlet.shared.WdEntity;
import edu.rpi.cct.webdav.servlet.shared.WebdavBadRequest;
import edu.rpi.cct.webdav.servlet.shared.WebdavException;
import edu.rpi.cct.webdav.servlet.shared.WebdavForbidden;
import edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf;
import edu.rpi.cct.webdav.servlet.shared.WebdavNsNode;
import edu.rpi.cmt.access.AccessPrincipal;
import edu.rpi.cmt.access.Acl.CurrentAccess;
import edu.rpi.cmt.access.PrivilegeDefs;
import edu.rpi.cmt.calendar.XcalUtil;
import edu.rpi.sss.util.DateTimeUtil;
import edu.rpi.sss.util.xml.XmlEmit;
import edu.rpi.sss.util.xml.XmlUtil;
import edu.rpi.sss.util.xml.tagdefs.AppleIcalTags;
import edu.rpi.sss.util.xml.tagdefs.AppleServerTags;
import edu.rpi.sss.util.xml.tagdefs.CalWSSoapTags;
import edu.rpi.sss.util.xml.tagdefs.CalWSXrdDefs;
import edu.rpi.sss.util.xml.tagdefs.CaldavTags;
import edu.rpi.sss.util.xml.tagdefs.WebdavTags;
import org.oasis_open.docs.ws_calendar.ns.soap.CalendarCollectionType;
import org.oasis_open.docs.ws_calendar.ns.soap.ChildCollectionType;
import org.oasis_open.docs.ws_calendar.ns.soap.CollectionType;
import org.oasis_open.docs.ws_calendar.ns.soap.GetPropertiesBasePropertyType;
import org.oasis_open.docs.ws_calendar.ns.soap.InboxType;
import org.oasis_open.docs.ws_calendar.ns.soap.IntegerPropertyType;
import org.oasis_open.docs.ws_calendar.ns.soap.LastModifiedDateTimeType;
import org.oasis_open.docs.ws_calendar.ns.soap.MaxAttendeesPerInstanceType;
import org.oasis_open.docs.ws_calendar.ns.soap.MaxInstancesType;
import org.oasis_open.docs.ws_calendar.ns.soap.MaxResourceSizeType;
import org.oasis_open.docs.ws_calendar.ns.soap.OutboxType;
import org.oasis_open.docs.ws_calendar.ns.soap.PrincipalHomeType;
import org.oasis_open.docs.ws_calendar.ns.soap.ResourceDescriptionType;
import org.oasis_open.docs.ws_calendar.ns.soap.ResourceTimezoneIdType;
import org.oasis_open.docs.ws_calendar.ns.soap.ResourceTypeType;
import org.oasis_open.docs.ws_calendar.ns.soap.StringPropertyType;
import org.oasis_open.docs.ws_calendar.ns.soap.SupportedCalendarComponentSetType;
import org.w3c.dom.Element;
import ietf.params.xml.ns.icalendar_2.ObjectFactory;
import ietf.params.xml.ns.icalendar_2.VavailabilityType;
import ietf.params.xml.ns.icalendar_2.VeventType;
import ietf.params.xml.ns.icalendar_2.VtodoType;
import java.io.Writer;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
/** Class to represent a calendar in caldav.
*
* @author Mike Douglass [email protected]
*/
public class CaldavCalNode extends CaldavBwNode {
private CalDAVEvent ical;
private AccessPrincipal owner;
private CurrentAccess currentAccess;
private final static HashMap<QName, PropertyTagEntry> propertyNames =
new HashMap<QName, PropertyTagEntry>();
private final static HashMap<String, PropertyTagXrdEntry> xrdNames =
new HashMap<String, PropertyTagXrdEntry>();
private final static HashMap<QName, PropertyTagEntry> calWSSoapNames =
new HashMap<QName, PropertyTagEntry>();
static {
addPropEntry(propertyNames, CaldavTags.calendarDescription);
addPropEntry(propertyNames, CaldavTags.calendarFreeBusySet);
addPropEntry(propertyNames, CaldavTags.calendarTimezone);
addPropEntry(propertyNames, CaldavTags.maxAttendeesPerInstance);
addPropEntry(propertyNames, CaldavTags.maxDateTime);
addPropEntry(propertyNames, CaldavTags.maxInstances);
addPropEntry(propertyNames, CaldavTags.maxResourceSize);
addPropEntry(propertyNames, CaldavTags.minDateTime);
addPropEntry(propertyNames, CaldavTags.scheduleCalendarTransp);
addPropEntry(propertyNames, CaldavTags.scheduleDefaultCalendarURL);
addPropEntry(propertyNames, CaldavTags.supportedCalendarComponentSet);
addPropEntry(propertyNames, CaldavTags.supportedCalendarData);
addPropEntry(propertyNames, AppleServerTags.getctag);
addPropEntry(propertyNames, AppleServerTags.sharedUrl);
addPropEntry(propertyNames, AppleIcalTags.calendarColor);
/* Default alarms */
addPropEntry(propertyNames, CaldavTags.defaultAlarmVeventDate);
addPropEntry(propertyNames, CaldavTags.defaultAlarmVeventDatetime);
addPropEntry(propertyNames, CaldavTags.defaultAlarmVtodoDate);
addPropEntry(propertyNames, CaldavTags.defaultAlarmVtodoDatetime);
//addXrdEntry(xrdNames, CalWSXrdDefs.calendarCollection, true);
addXrdEntry(xrdNames, CalWSXrdDefs.collection, true, true); // for all resource types
addXrdEntry(xrdNames, CalWSXrdDefs.description, true, false);
addXrdEntry(xrdNames, CalWSXrdDefs.maxAttendeesPerInstance, true, false);
addXrdEntry(xrdNames, CalWSXrdDefs.maxDateTime, true, false);
addXrdEntry(xrdNames, CalWSXrdDefs.maxInstances, true, false);
addXrdEntry(xrdNames, CalWSXrdDefs.maxResourceSize, true, false);
addXrdEntry(xrdNames, CalWSXrdDefs.minDateTime, true, false);
addXrdEntry(xrdNames, CalWSXrdDefs.principalHome, true, true);
addXrdEntry(xrdNames, CalWSXrdDefs.timezone, true, false);
addXrdEntry(xrdNames, CalWSXrdDefs.supportedCalendarComponentSet, true, false);
addCalWSSoapName(CalWSSoapTags.childCollection, true);
addCalWSSoapName(CalWSSoapTags.maxAttendeesPerInstance, true);
addCalWSSoapName(CalWSSoapTags.maxDateTime, true);
addCalWSSoapName(CalWSSoapTags.maxInstances, true);
addCalWSSoapName(CalWSSoapTags.maxResourceSize, true);
addCalWSSoapName(CalWSSoapTags.minDateTime, true);
addCalWSSoapName(CalWSSoapTags.principalHome, true);
addCalWSSoapName(CalWSSoapTags.resourceDescription, true);
addCalWSSoapName(CalWSSoapTags.resourceType, true);
addCalWSSoapName(CalWSSoapTags.resourceTimezoneId, true);
addCalWSSoapName(CalWSSoapTags.supportedCalendarComponentSet, true);
addCalWSSoapName(CalWSSoapTags.timezoneServer, true);
}
/** Place holder for status
*
* @param sysi
* @param status
* @param uri
*/
public CaldavCalNode(final SysIntf sysi,
final int status,
final String uri) {
super(true, sysi, uri);
setStatus(status);
}
/**
* @param cdURI
* @param sysi
* @throws WebdavException
*/
public CaldavCalNode(final CaldavURI cdURI,
final SysIntf sysi) throws WebdavException {
super(cdURI, sysi);
col = cdURI.getCol();
collection = true;
allowsGet = false;
exists = cdURI.getExists();
}
/**
* @param col
* @param sysi
* @throws WebdavException
*/
public CaldavCalNode(final CalDAVCollection col,
final SysIntf sysi) throws WebdavException {
super(sysi, col.getParentPath(), true, col.getPath());
allowsGet = false;
this.col = col;
exists = true;
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#getOwner()
*/
@Override
public AccessPrincipal getOwner() throws WebdavException {
if (owner == null) {
if (col == null) {
return null;
}
owner = col.getOwner();
}
return owner;
}
@Override
public void init(final boolean content) throws WebdavException {
if (!content) {
return;
}
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#getEtagValue(boolean)
*/
@Override
public String getEtagValue(final boolean strong) throws WebdavException {
/* We need the etag of the target if this is an alias */
CalDAVCollection c = (CalDAVCollection)getCollection(true); // deref
if (c == null) {
return null;
}
String val = c.getEtag();
if (strong) {
return val;
}
return "W/" + val;
}
/* (non-Javadoc)
* @see org.bedework.caldav.server.CaldavBwNode#getEtokenValue()
*/
@Override
public String getEtokenValue() throws WebdavException {
return concatEtoken(getEtagValue(true), "");
}
/**
* @return true if scheduling allowed
* @throws WebdavException
*/
public boolean getSchedulingAllowed() throws WebdavException {
/* It's the alias target that matters */
CalDAVCollection c = (CalDAVCollection)getCollection(true); // deref
if (c == null) {
return false;
}
int type = c.getCalType();
if (type == CalDAVCollection.calTypeInbox) {
return true;
}
if (type == CalDAVCollection.calTypeOutbox) {
return true;
}
if (type == CalDAVCollection.calTypeCalendarCollection) {
return true;
}
return false;
}
/**
* @return sharing status or null if none.
* @throws WebdavException
*/
public String getSharingStatus() throws WebdavException {
return getCollection(false).getProperty(AppleServerTags.invite);
}
/**
* @param methodTag - acts as a flag for the method type
* @throws WebdavException
*/
@Override
public void setDefaults(final QName methodTag) throws WebdavException {
if (!CaldavTags.mkcalendar.equals(methodTag)) {
return;
}
CalDAVCollection c = (CalDAVCollection)getCollection(false); // Don't deref
c.setCalType(CalDAVCollection.calTypeCalendarCollection);
}
/* (non-Javadoc)
* @see org.bedework.caldav.server.CaldavBwNode#getChildren()
*/
@Override
public Collection<? extends WdEntity> getChildren() throws WebdavException {
/* For the moment we're going to do this the inefficient way.
We really need to have calendar defs that can be expressed as a search
allowing us to retrieve all the ids of objects within a calendar.
*/
try {
CalDAVCollection c = (CalDAVCollection)getCollection(true); // deref
if (c == null) { // no access?
return null;
}
if (!c.entitiesAllowed()) {
if (debug) {
debugMsg("POSSIBLE SEARCH: getChildren for cal " + c.getPath());
}
Collection<WdEntity> ch = new ArrayList<WdEntity>();
ch.addAll(getSysi().getCollections(c));
ch.addAll(getSysi().getFiles(c));
return ch;
}
/* Otherwise, return the events in this calendar */
/* Note we use the undereferenced version for the fetch */
c = (CalDAVCollection)getCollection(false); // don't deref
if (debug) {
debugMsg("Get all resources in calendar " + c.getPath());
}
return getSysi().getEvents(c, null, null, null);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/**
* @param fbcal
* @throws WebdavException
*/
public void setFreeBusy(final CalDAVEvent fbcal) throws WebdavException {
try {
ical = fbcal;
allowsGet = true;
} catch (Throwable t) {
if (debug) {
error(t);
}
throw new WebdavException(t);
}
}
@Override
public String writeContent(final XmlEmit xml,
final Writer wtr,
final String contentType) throws WebdavException {
try {
Collection<CalDAVEvent> evs = new ArrayList<CalDAVEvent>();
evs.add(ical);
return getSysi().writeCalendar(evs,
MethodEmitted.noMethod,
xml,
wtr,
contentType);
} catch (WebdavException we) {
throw we;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#getContentString()
*/
@Override
public String getContentString() throws WebdavException {
init(true);
if (ical == null) {
return null;
}
return ical.toString();
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#update()
*/
@Override
public void update() throws WebdavException {
// ALIAS probably not unaliasing here
if (col != null) {
getSysi().updateCollection(col);
}
}
/* ====================================================================
* Required webdav properties
* ==================================================================== */
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#getContentLang()
*/
@Override
public String getContentLang() throws WebdavException {
return "en";
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#getContentLen()
*/
@Override
public long getContentLen() throws WebdavException {
String s = getContentString();
if (s == null) {
return 0;
}
return s.getBytes().length;
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#getContentType()
*/
@Override
public String getContentType() throws WebdavException {
if (ical != null) {
return "text/calendar; charset=UTF-8";
}
return null;
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#getCreDate()
*/
@Override
public String getCreDate() throws WebdavException {
return null;
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#getDisplayname()
*/
@Override
public String getDisplayname() throws WebdavException {
if (col == null) {
return null;
}
return col.getDisplayName();
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#getLastmodDate()
*/
@Override
public String getLastmodDate() throws WebdavException {
init(false);
if (col == null) {
return null;
}
try {
return DateTimeUtil.fromISODateTimeUTCtoRfc822(col.getLastmod());
} catch (Throwable t) {
throw new WebdavException(t);
}
}
@Override
public boolean allowsSyncReport() throws WebdavException {
return getSysi().allowsSyncReport(col);
}
@Override
public boolean getDeleted() throws WebdavException {
return col.getDeleted();
}
@Override
public String getSyncToken() throws WebdavException {
return getSysi().getSyncToken(col);
}
/* ====================================================================
* Abstract methods
* ==================================================================== */
@Override
public CurrentAccess getCurrentAccess() throws WebdavException {
if (currentAccess != null) {
return currentAccess;
}
CalDAVCollection c = (CalDAVCollection)getCollection(true); // We want access of underlying object?
if (c == null) {
return null;
}
try {
currentAccess = getSysi().checkAccess(c, PrivilegeDefs.privAny, true);
} catch (Throwable t) {
throw new WebdavException(t);
}
return currentAccess;
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#trailSlash()
*/
@Override
public boolean trailSlash() {
return true;
}
/* ====================================================================
* Property methods
* ==================================================================== */
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#removeProperty(org.w3c.dom.Element)
*/
@Override
public boolean removeProperty(final Element val,
final SetPropertyResult spr) throws WebdavException {
if (super.removeProperty(val, spr)) {
return true;
}
try {
if (XmlUtil.nodeMatches(val, CaldavTags.calendarTimezone)) {
col.setTimezone(null);
return true;
}
if (XmlUtil.nodeMatches(val, CaldavTags.defaultAlarmVeventDate) ||
XmlUtil.nodeMatches(val, CaldavTags.defaultAlarmVeventDatetime) ||
XmlUtil.nodeMatches(val, CaldavTags.defaultAlarmVtodoDate) ||
XmlUtil.nodeMatches(val, CaldavTags.defaultAlarmVtodoDatetime)) {
col.setProperty(new QName(val.getNamespaceURI(), val.getLocalName()),
null);
return true;
}
return false;
} catch (WebdavException wde) {
throw wde;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#setProperty(org.w3c.dom.Element)
*/
@Override
public boolean setProperty(final Element val,
final SetPropertyResult spr) throws WebdavException {
if (super.setProperty(val, spr)) {
return true;
}
try {
if (XmlUtil.nodeMatches(val, WebdavTags.description)) {
if (checkCalForSetProp(spr)) {
col.setDescription(XmlUtil.getElementContent(val));
}
return true;
}
if (XmlUtil.nodeMatches(val, CaldavTags.calendarDescription)) {
if (checkCalForSetProp(spr)) {
col.setDescription(XmlUtil.getElementContent(val));
}
return true;
}
if (XmlUtil.nodeMatches(val, WebdavTags.displayname)) {
if (checkCalForSetProp(spr)) {
col.setDisplayName(XmlUtil.getElementContent(val));
}
return true;
}
if (XmlUtil.nodeMatches(val, WebdavTags.resourcetype)) {
Collection<Element> propVals = XmlUtil.getElements(val);
for (Element pval: propVals) {
if (XmlUtil.nodeMatches(pval, WebdavTags.collection)) {
// Fine
continue;
}
if (XmlUtil.nodeMatches(pval, CaldavTags.calendar)) {
// This is only valid for an (extended) mkcol
if (!WebdavTags.mkcol.equals(spr.rootElement)) {
throw new WebdavForbidden();
}
CalDAVCollection c = (CalDAVCollection)getCollection(false); // Don't deref
c.setCalType(CalDAVCollection.calTypeCalendarCollection);
continue;
}
if (XmlUtil.nodeMatches(pval, AppleServerTags.sharedOwner)) {
// This is only valid for an the owner
CalDAVCollection c = (CalDAVCollection)getCollection(false); // Don't deref
if (!c.getOwner().equals(getSysi().getPrincipal())) {
throw new WebdavForbidden("Not owner");
}
c.setProperty(AppleServerTags.shared, "true");
continue;
}
}
return true;
}
if (XmlUtil.nodeMatches(val, CaldavTags.scheduleCalendarTransp)) {
Element cval = XmlUtil.getOnlyElement(val);
if (XmlUtil.nodeMatches(cval, CaldavTags.opaque)) {
col.setAffectsFreeBusy(true);
} else if (XmlUtil.nodeMatches(cval, CaldavTags.transparent)) {
col.setAffectsFreeBusy(true);
} else {
throw new WebdavBadRequest();
}
return true;
}
if (XmlUtil.nodeMatches(val, CaldavTags.calendarFreeBusySet)) {
// Only valid for inbox
if (col.getCalType() != CalDAVCollection.calTypeInbox) {
throw new WebdavForbidden("Not on inbox");
}
spr.status = HttpServletResponse.SC_NOT_IMPLEMENTED;
spr.message = "Unimplemented - calendarFreeBusySet";
warn("Unimplemented - calendarFreeBusySet");
return true;
}
if (XmlUtil.nodeMatches(val, CaldavTags.calendarTimezone)) {
col.setTimezone(getSysi().tzidFromTzdef(XmlUtil.getElementContent(val)));
return true;
}
if (XmlUtil.nodeMatches(val, AppleIcalTags.calendarColor)) {
col.setColor(XmlUtil.getElementContent(val));
return true;
}
if (XmlUtil.nodeMatches(val, CaldavTags.defaultAlarmVeventDate) ||
XmlUtil.nodeMatches(val, CaldavTags.defaultAlarmVeventDatetime) ||
XmlUtil.nodeMatches(val, CaldavTags.defaultAlarmVtodoDate) ||
XmlUtil.nodeMatches(val, CaldavTags.defaultAlarmVtodoDatetime)) {
String al = XmlUtil.getElementContent(val, false);
if (al == null) {
return false;
}
if (al.length() > 0) {
if (!getSysi().validateAlarm(al)) {
return false;
}
}
col.setProperty(new QName(val.getNamespaceURI(), val.getLocalName()),
al);
return true;
}
return false;
} catch (WebdavException wde) {
throw wde;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#knownProperty(edu.rpi.sss.util.xml.QName)
*/
@Override
public boolean knownProperty(final QName tag) {
if (propertyNames.get(tag) != null) {
return true;
}
// Not ours
return super.knownProperty(tag);
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#generatePropertyValue(edu.rpi.sss.util.xml.QName, edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf, boolean)
*/
@Override
public boolean generatePropertyValue(final QName tag,
final WebdavNsIntf intf,
final boolean allProp) throws WebdavException {
XmlEmit xml = intf.getXmlEmit();
try {
int calType;
CalDAVCollection c = (CalDAVCollection)getCollection(true); // deref this
CalDAVCollection cundereffed =
(CalDAVCollection)getCollection(false); // don't deref this
if (c == null) {
// Probably no access -- fake it up as a collection
calType = CalDAVCollection.calTypeCollection;
} else {
calType = c.getCalType();
}
if (tag.equals(WebdavTags.resourcetype)) {
// dav 13.9
xml.openTag(tag);
xml.emptyTag(WebdavTags.collection);
if (debug) {
debugMsg("generatePropResourcetype for " + col);
}
//boolean isCollection = cal.getCalendarCollection();
if (calType == CalDAVCollection.calTypeInbox) {
xml.emptyTag(CaldavTags.scheduleInbox);
} else if (calType == CalDAVCollection.calTypeOutbox) {
xml.emptyTag(CaldavTags.scheduleOutbox);
} else if (calType == CalDAVCollection.calTypeCalendarCollection) {
xml.emptyTag(CaldavTags.calendar);
} else if (calType == CalDAVCollection.calTypeNotifications) {
xml.emptyTag(AppleServerTags.notifications);
}
if (Boolean.valueOf(c.getProperty(AppleServerTags.shared))) {
if (c.getOwner().equals(getSysi().getPrincipal())) {
xml.emptyTag(AppleServerTags.sharedOwner);
} else {
xml.emptyTag(AppleServerTags.shared);
}
}
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.scheduleCalendarTransp)) {
xml.openTag(tag);
- if ((c == null) || c.getAffectsFreeBusy()) {
+ if (col.getAffectsFreeBusy()) {
xml.emptyTag(CaldavTags.opaque);
} else {
xml.emptyTag(CaldavTags.transparent);
}
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.scheduleDefaultCalendarURL) &&
(calType == CalDAVCollection.calTypeInbox)) {
xml.openTag(tag);
CalPrincipalInfo cinfo = getSysi().getCalPrincipalInfo(getOwner());
if (cinfo.defaultCalendarPath != null) {
generateHref(xml, cinfo.defaultCalendarPath);
}
xml.closeTag(tag);
return true;
}
if (tag.equals(AppleServerTags.getctag)) {
if (c != null) {
xml.property(tag, c.getEtag());
} else {
xml.property(tag, col.getEtag());
}
return true;
}
if (tag.equals(AppleServerTags.sharedUrl)) {
if (!cundereffed.isAlias()) {
return false;
}
xml.openTag(tag);
xml.property(WebdavTags.href, cundereffed.getAliasUri());
xml.closeTag(tag);
return true;
}
if (tag.equals(AppleIcalTags.calendarColor)) {
String val = col.getColor();
if (val == null) {
return false;
}
xml.property(tag, val);
return true;
}
if (tag.equals(CaldavTags.calendarDescription)) {
xml.property(tag, col.getDescription());
return true;
}
if ((col.getCalType() == CalDAVCollection.calTypeInbox) &&
(tag.equals(CaldavTags.calendarFreeBusySet))) {
xml.openTag(tag);
Collection<String> hrefs = getSysi().getFreebusySet();
for (String href: hrefs) {
xml.property(WebdavTags.href, href);
}
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.maxAttendeesPerInstance)) {
if ((calType != CalDAVCollection.calTypeCalendarCollection) &&
(calType != CalDAVCollection.calTypeInbox) &&
(calType != CalDAVCollection.calTypeOutbox)) {
return false;
}
Integer val = getSysi().getSystemProperties().getMaxAttendeesPerInstance();
if (val == null) {
return false;
}
xml.property(tag, String.valueOf(val));
return true;
}
if (tag.equals(CaldavTags.maxDateTime)) {
if ((calType != CalDAVCollection.calTypeCalendarCollection) &&
(calType != CalDAVCollection.calTypeInbox) &&
(calType != CalDAVCollection.calTypeOutbox)) {
return false;
}
Integer val = getSysi().getSystemProperties().getMaxAttendeesPerInstance();
if (val == null) {
return false;
}
xml.property(tag, String.valueOf(val));
return true;
}
if (tag.equals(CaldavTags.maxInstances)) {
if ((calType != CalDAVCollection.calTypeCalendarCollection) &&
(calType != CalDAVCollection.calTypeInbox) &&
(calType != CalDAVCollection.calTypeOutbox)) {
return false;
}
Integer val = getSysi().getSystemProperties().getMaxInstances();
if (val == null) {
return false;
}
xml.property(tag, String.valueOf(val));
return true;
}
if (tag.equals(CaldavTags.maxResourceSize)) {
if ((calType != CalDAVCollection.calTypeCalendarCollection) &&
(calType != CalDAVCollection.calTypeInbox) &&
(calType != CalDAVCollection.calTypeOutbox)) {
return false;
}
Integer val = getSysi().getSystemProperties().getMaxUserEntitySize();
if (val == null) {
return false;
}
xml.property(tag, String.valueOf(val));
return true;
}
if (tag.equals(CaldavTags.minDateTime)) {
if ((calType != CalDAVCollection.calTypeCalendarCollection) &&
(calType != CalDAVCollection.calTypeInbox) &&
(calType != CalDAVCollection.calTypeOutbox)) {
return false;
}
String val = getSysi().getSystemProperties().getMinDateTime();
if (val == null) {
return false;
}
xml.property(tag, val);
return true;
}
if (tag.equals(CaldavTags.supportedCalendarComponentSet)) {
/* e.g.
* <C:supported-calendar-component-set
* xmlns:C="urn:ietf:params:xml:ns:caldav">
* <C:comp name="VEVENT"/>
* <C:comp name="VTODO"/>
* </C:supported-calendar-component-set>
*/
if ((calType != CalDAVCollection.calTypeCalendarCollection) &&
(calType != CalDAVCollection.calTypeInbox) &&
(calType != CalDAVCollection.calTypeOutbox)) {
return false;
}
xml.openTag(tag);
xml.startTag(CaldavTags.comp);
xml.attribute("name", "VEVENT");
xml.endEmptyTag();
xml.newline();
xml.startTag(CaldavTags.comp);
xml.attribute("name", "VTODO");
xml.endEmptyTag();
xml.newline();
xml.startTag(CaldavTags.comp);
xml.attribute("name", "VAVAILABILITY");
xml.endEmptyTag();
xml.newline();
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.supportedCalendarData)) {
/* e.g.
* <C:supported-calendar-data
* xmlns:C="urn:ietf:params:xml:ns:caldav">
* <C:calendar-data content-type="text/calendar" version="2.0"/>
* </C:supported-calendar-data>
*/
xml.openTag(tag);
xml.startTag(CaldavTags.calendarData);
xml.attribute("content-type", "text/calendar");
xml.attribute("version", "2.0");
xml.endEmptyTag();
xml.newline();
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.calendarTimezone)) {
String tzid = col.getTimezone();
if (tzid == null) {
return false;
}
String val = getSysi().toStringTzCalendar(tzid);
if (val == null) {
return false;
}
xml.cdataProperty(tag, val);
return true;
}
if (tag.equals(CaldavTags.defaultAlarmVeventDate) ||
tag.equals(CaldavTags.defaultAlarmVeventDatetime) ||
tag.equals(CaldavTags.defaultAlarmVtodoDate) ||
tag.equals(CaldavTags.defaultAlarmVtodoDatetime)) {
/* Private to user - look at alias only */
if (cundereffed == null) {
return false;
}
String val = cundereffed.getProperty(tag);
if (val == null) {
return false;
}
xml.cdataProperty(tag, val);
return true;
}
// Not known - try higher
return super.generatePropertyValue(tag, intf, allProp);
} catch (WebdavException wde) {
throw wde;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
@Override
public boolean generateCalWsProperty(final List<GetPropertiesBasePropertyType> props,
final QName tag,
final WebdavNsIntf intf,
final boolean allProp) throws WebdavException {
try {
/*
addCalWSSoapName(CalWSSoapTags.timezoneServer, true);
*/
if (tag.equals(CalWSSoapTags.childCollection)) {
for (WebdavNsNode child: intf.getChildren(this)) {
CaldavBwNode cn = (CaldavBwNode)child;
ChildCollectionType cc = new ChildCollectionType();
cc.setHref(cn.getUrlValue());
List<Object> rtypes = cc.getCalendarCollectionOrCollection();
if (!cn.isCollection()) {
continue;
}
rtypes.add(new CollectionType());
if (cn.isCalendarCollection()) {
rtypes.add(new CalendarCollectionType());
}
props.add(cc);
}
return true;
}
if (tag.equals(CalWSSoapTags.lastModifiedDateTime)) {
String val = col.getLastmod();
if (val == null) {
return true;
}
LastModifiedDateTimeType lmdt = new LastModifiedDateTimeType();
lmdt.setDateTime(XcalUtil.fromDtval(val));
props.add(lmdt);
return true;
}
if (tag.equals(CalWSSoapTags.maxAttendeesPerInstance)) {
if (!rootNode) {
return true;
}
Integer val = getSysi().getSystemProperties().getMaxAttendeesPerInstance();
if (val != null) {
props.add(intProp(new MaxAttendeesPerInstanceType(),
val));
}
return true;
}
if (tag.equals(CalWSSoapTags.maxDateTime)) {
return true;
}
/*
if (name.equals(CalWSXrdDefs.maxDateTime)) {
if (!rootNode) {
return true;
}
Integer val = getSysi().getSystemProperties().getMaxAttendeesPerInstance();
if (val == null) {
return false;
}
props.add(prop);
return true;
}*/
if (tag.equals(CalWSSoapTags.maxInstances)) {
if (!rootNode) {
return true;
}
Integer val = getSysi().getSystemProperties().getMaxInstances();
if (val != null) {
props.add(intProp(new MaxInstancesType(),
val));
}
return true;
}
if (tag.equals(CalWSSoapTags.maxResourceSize)) {
if (!rootNode) {
return true;
}
Integer val = getSysi().getSystemProperties().getMaxUserEntitySize();
if (val != null) {
props.add(intProp(new MaxResourceSizeType(),
val));
}
return true;
}
if (tag.equals(CalWSSoapTags.minDateTime)) {
return true;
}
/*
if (name.equals(CalWSXrdDefs.minDateTime)) {
if (!rootNode) {
return true;
}
String val = getSysi().getSystemProperties().getMinDateTime();
if (val == null) {
return false;
}
props.add(xrdProperty(name, val));
return true;
}
*/
if (tag.equals(CalWSSoapTags.principalHome)) {
if (!rootNode || intf.getAnonymous()) {
return true;
}
SysIntf si = getSysi();
CalPrincipalInfo cinfo = si.getCalPrincipalInfo(si.getPrincipal());
if (cinfo.userHomePath != null) {
props.add(strProp(new PrincipalHomeType(), cinfo.userHomePath));
}
return true;
}
if (tag.equals(CalWSSoapTags.resourceDescription)) {
String s = col.getDescription();
if (s != null) {
props.add(strProp(new ResourceDescriptionType(), s));
}
return true;
}
if (tag.equals(CalWSSoapTags.resourceType)) {
ResourceTypeType rt = new ResourceTypeType();
int calType;
CalDAVCollection c = (CalDAVCollection)getCollection(true); // deref this
if (c == null) {
// Probably no access -- fake it up as a collection
calType = CalDAVCollection.calTypeCollection;
} else {
calType = c.getCalType();
}
List<Object> rtypes = rt.getCalendarCollectionOrCollectionOrInbox();
rtypes.add(new CollectionType());
if (calType == CalDAVCollection.calTypeInbox) {
rtypes.add(new InboxType());
} else if (calType == CalDAVCollection.calTypeOutbox) {
rtypes.add(new OutboxType());
} else if (calType == CalDAVCollection.calTypeCalendarCollection) {
rtypes.add(new CalendarCollectionType());
}
props.add(rt);
return true;
}
if (tag.equals(CalWSSoapTags.resourceTimezoneId)) {
String tzid = col.getTimezone();
if (tzid != null) {
props.add(strProp(new ResourceTimezoneIdType(), tzid));
}
return true;
}
if (tag.equals(CalWSSoapTags.supportedCalendarComponentSet)) {
SupportedCalendarComponentSetType sccs = new SupportedCalendarComponentSetType();
ObjectFactory of = new ObjectFactory();
VeventType ev = new VeventType();
sccs.getBaseComponent().add(of.createVevent(ev));
VtodoType td = new VtodoType();
sccs.getBaseComponent().add(of.createVtodo(td));
VavailabilityType av = new VavailabilityType();
sccs.getBaseComponent().add(of.createVavailability(av));
props.add(sccs);
return true;
}
// Not known - try higher
return super.generateCalWsProperty(props, tag, intf, allProp);
} catch (WebdavException wde) {
throw wde;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
private GetPropertiesBasePropertyType intProp(final IntegerPropertyType prop,
final Integer val) {
prop.setInteger(BigInteger.valueOf(val.longValue()));
return prop;
}
private GetPropertiesBasePropertyType strProp(final StringPropertyType prop,
final String val) {
prop.setString(val);
return prop;
}
@Override
public boolean generateXrdProperties(final List<Object> props,
final String name,
final WebdavNsIntf intf,
final boolean allProp) throws WebdavException {
try {
int calType;
CalDAVCollection c = (CalDAVCollection)getCollection(true); // deref this
if (c == null) {
// Probably no access -- fake it up as a collection
calType = CalDAVCollection.calTypeCollection;
} else {
calType = c.getCalType();
}
if (name.equals(CalWSXrdDefs.collection)) {
props.add(xrdEmptyProperty(name));
//boolean isCollection = cal.getCalendarCollection();
if (calType == CalDAVCollection.calTypeInbox) {
props.add(xrdEmptyProperty(CalWSXrdDefs.inbox));
} else if (calType == CalDAVCollection.calTypeOutbox) {
props.add(xrdEmptyProperty(CalWSXrdDefs.outbox));
} else if (calType == CalDAVCollection.calTypeCalendarCollection) {
props.add(xrdEmptyProperty(CalWSXrdDefs.calendarCollection));
}
return true;
}
if (name.equals(CalWSXrdDefs.description)) {
String s = col.getDescription();
if (s == null) {
return true;
}
props.add(xrdProperty(name, s));
return true;
}
if (name.equals(CalWSXrdDefs.principalHome)) {
if (!rootNode || intf.getAnonymous()) {
return true;
}
SysIntf si = getSysi();
CalPrincipalInfo cinfo = si.getCalPrincipalInfo(si.getPrincipal());
if (cinfo.userHomePath == null) {
return true;
}
props.add(xrdProperty(name,
getUrlValue(cinfo.userHomePath, true)));
return true;
}
if (name.equals(CalWSXrdDefs.maxAttendeesPerInstance)) {
if (!rootNode) {
return true;
}
Integer val = getSysi().getSystemProperties().getMaxAttendeesPerInstance();
if (val == null) {
return true;
}
props.add(xrdProperty(name,
String.valueOf(val)));
return true;
}
if (name.equals(CalWSXrdDefs.maxDateTime)) {
if (!rootNode) {
return true;
}
Integer val = getSysi().getSystemProperties().getMaxAttendeesPerInstance();
if (val == null) {
return false;
}
props.add(xrdProperty(name,
String.valueOf(val)));
return true;
}
if (name.equals(CalWSXrdDefs.maxInstances)) {
if (!rootNode) {
return true;
}
Integer val = getSysi().getSystemProperties().getMaxInstances();
if (val == null) {
return false;
}
props.add(xrdProperty(name,
String.valueOf(val)));
return true;
}
if (name.equals(CalWSXrdDefs.maxResourceSize)) {
if (!rootNode) {
return true;
}
Integer val = getSysi().getSystemProperties().getMaxUserEntitySize();
if (val == null) {
return false;
}
props.add(xrdProperty(name,
String.valueOf(val)));
return true;
}
if (name.equals(CalWSXrdDefs.minDateTime)) {
if (!rootNode) {
return true;
}
String val = getSysi().getSystemProperties().getMinDateTime();
if (val == null) {
return false;
}
props.add(xrdProperty(name, val));
return true;
}
if (name.equals(CalWSXrdDefs.timezone)) {
String tzid = col.getTimezone();
if (tzid == null) {
return false;
}
props.add(xrdProperty(name, tzid));
return true;
}
if (name.equals(CalWSXrdDefs.supportedCalendarComponentSet)) {
SupportedCalendarComponentSetType sccs = new SupportedCalendarComponentSetType();
ObjectFactory of = new ObjectFactory();
VeventType ev = new VeventType();
sccs.getBaseComponent().add(of.createVevent(ev));
VtodoType td = new VtodoType();
sccs.getBaseComponent().add(of.createVtodo(td));
VavailabilityType av = new VavailabilityType();
sccs.getBaseComponent().add(of.createVavailability(av));
JAXBElement<SupportedCalendarComponentSetType> el =
new JAXBElement<SupportedCalendarComponentSetType>(CalWSSoapTags.supportedCalendarComponentSet,
SupportedCalendarComponentSetType.class,
sccs);
props.add(el);
return true;
}
// Not known - try higher
return super.generateXrdProperties(props, name, intf, allProp);
} catch (WebdavException wde) {
throw wde;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* (non-Javadoc)
* @see edu.rpi.cct.webdav.servlet.shared.WebdavNsNode#getPropertyNames()
*/
@Override
public Collection<PropertyTagEntry> getPropertyNames()throws WebdavException {
Collection<PropertyTagEntry> res = new ArrayList<PropertyTagEntry>();
res.addAll(super.getPropertyNames());
res.addAll(propertyNames.values());
return res;
}
@Override
public Collection<PropertyTagEntry> getCalWSSoapNames() throws WebdavException {
Collection<PropertyTagEntry> res = new ArrayList<PropertyTagEntry>();
res.addAll(super.getCalWSSoapNames());
res.addAll(calWSSoapNames.values());
return res;
}
/* (non-Javadoc)
* @see org.bedework.caldav.server.CaldavBwNode#getXrdNames()
*/
@Override
public Collection<PropertyTagXrdEntry> getXrdNames()throws WebdavException {
Collection<PropertyTagXrdEntry> res = new ArrayList<PropertyTagXrdEntry>();
res.addAll(super.getXrdNames());
res.addAll(xrdNames.values());
return res;
}
/* (non-Javadoc)
* @see org.bedework.caldav.server.CaldavBwNode#getSupportedReports()
*/
@Override
public Collection<QName> getSupportedReports() throws WebdavException {
Collection<QName> res = new ArrayList<QName>();
CalDAVCollection c = (CalDAVCollection)getCollection(true); // deref
if (c == null) {
return res;
}
res.addAll(super.getSupportedReports());
/* Cannot do free-busy on in and outbox */
if (c.freebusyAllowed()) {
res.add(CaldavTags.freeBusyQuery); // Calendar access
}
return res;
}
/* ====================================================================
* Object methods
* ==================================================================== */
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("CaldavCalNode{cduri=");
sb.append("path=");
sb.append(getPath());
sb.append(", isCalendarCollection()=");
try {
sb.append(isCalendarCollection());
} catch (Throwable t) {
sb.append("exception(" + t.getMessage() + ")");
}
sb.append("}");
return sb.toString();
}
/* ====================================================================
* Private methods
* ==================================================================== */
private boolean checkCalForSetProp(final SetPropertyResult spr) {
if (col != null) {
return true;
}
spr.status = HttpServletResponse.SC_NOT_FOUND;
spr.message = "Not found";
return false;
}
}
| true | true | public boolean generatePropertyValue(final QName tag,
final WebdavNsIntf intf,
final boolean allProp) throws WebdavException {
XmlEmit xml = intf.getXmlEmit();
try {
int calType;
CalDAVCollection c = (CalDAVCollection)getCollection(true); // deref this
CalDAVCollection cundereffed =
(CalDAVCollection)getCollection(false); // don't deref this
if (c == null) {
// Probably no access -- fake it up as a collection
calType = CalDAVCollection.calTypeCollection;
} else {
calType = c.getCalType();
}
if (tag.equals(WebdavTags.resourcetype)) {
// dav 13.9
xml.openTag(tag);
xml.emptyTag(WebdavTags.collection);
if (debug) {
debugMsg("generatePropResourcetype for " + col);
}
//boolean isCollection = cal.getCalendarCollection();
if (calType == CalDAVCollection.calTypeInbox) {
xml.emptyTag(CaldavTags.scheduleInbox);
} else if (calType == CalDAVCollection.calTypeOutbox) {
xml.emptyTag(CaldavTags.scheduleOutbox);
} else if (calType == CalDAVCollection.calTypeCalendarCollection) {
xml.emptyTag(CaldavTags.calendar);
} else if (calType == CalDAVCollection.calTypeNotifications) {
xml.emptyTag(AppleServerTags.notifications);
}
if (Boolean.valueOf(c.getProperty(AppleServerTags.shared))) {
if (c.getOwner().equals(getSysi().getPrincipal())) {
xml.emptyTag(AppleServerTags.sharedOwner);
} else {
xml.emptyTag(AppleServerTags.shared);
}
}
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.scheduleCalendarTransp)) {
xml.openTag(tag);
if ((c == null) || c.getAffectsFreeBusy()) {
xml.emptyTag(CaldavTags.opaque);
} else {
xml.emptyTag(CaldavTags.transparent);
}
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.scheduleDefaultCalendarURL) &&
(calType == CalDAVCollection.calTypeInbox)) {
xml.openTag(tag);
CalPrincipalInfo cinfo = getSysi().getCalPrincipalInfo(getOwner());
if (cinfo.defaultCalendarPath != null) {
generateHref(xml, cinfo.defaultCalendarPath);
}
xml.closeTag(tag);
return true;
}
if (tag.equals(AppleServerTags.getctag)) {
if (c != null) {
xml.property(tag, c.getEtag());
} else {
xml.property(tag, col.getEtag());
}
return true;
}
if (tag.equals(AppleServerTags.sharedUrl)) {
if (!cundereffed.isAlias()) {
return false;
}
xml.openTag(tag);
xml.property(WebdavTags.href, cundereffed.getAliasUri());
xml.closeTag(tag);
return true;
}
if (tag.equals(AppleIcalTags.calendarColor)) {
String val = col.getColor();
if (val == null) {
return false;
}
xml.property(tag, val);
return true;
}
if (tag.equals(CaldavTags.calendarDescription)) {
xml.property(tag, col.getDescription());
return true;
}
if ((col.getCalType() == CalDAVCollection.calTypeInbox) &&
(tag.equals(CaldavTags.calendarFreeBusySet))) {
xml.openTag(tag);
Collection<String> hrefs = getSysi().getFreebusySet();
for (String href: hrefs) {
xml.property(WebdavTags.href, href);
}
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.maxAttendeesPerInstance)) {
if ((calType != CalDAVCollection.calTypeCalendarCollection) &&
(calType != CalDAVCollection.calTypeInbox) &&
(calType != CalDAVCollection.calTypeOutbox)) {
return false;
}
Integer val = getSysi().getSystemProperties().getMaxAttendeesPerInstance();
if (val == null) {
return false;
}
xml.property(tag, String.valueOf(val));
return true;
}
if (tag.equals(CaldavTags.maxDateTime)) {
if ((calType != CalDAVCollection.calTypeCalendarCollection) &&
(calType != CalDAVCollection.calTypeInbox) &&
(calType != CalDAVCollection.calTypeOutbox)) {
return false;
}
Integer val = getSysi().getSystemProperties().getMaxAttendeesPerInstance();
if (val == null) {
return false;
}
xml.property(tag, String.valueOf(val));
return true;
}
if (tag.equals(CaldavTags.maxInstances)) {
if ((calType != CalDAVCollection.calTypeCalendarCollection) &&
(calType != CalDAVCollection.calTypeInbox) &&
(calType != CalDAVCollection.calTypeOutbox)) {
return false;
}
Integer val = getSysi().getSystemProperties().getMaxInstances();
if (val == null) {
return false;
}
xml.property(tag, String.valueOf(val));
return true;
}
if (tag.equals(CaldavTags.maxResourceSize)) {
if ((calType != CalDAVCollection.calTypeCalendarCollection) &&
(calType != CalDAVCollection.calTypeInbox) &&
(calType != CalDAVCollection.calTypeOutbox)) {
return false;
}
Integer val = getSysi().getSystemProperties().getMaxUserEntitySize();
if (val == null) {
return false;
}
xml.property(tag, String.valueOf(val));
return true;
}
if (tag.equals(CaldavTags.minDateTime)) {
if ((calType != CalDAVCollection.calTypeCalendarCollection) &&
(calType != CalDAVCollection.calTypeInbox) &&
(calType != CalDAVCollection.calTypeOutbox)) {
return false;
}
String val = getSysi().getSystemProperties().getMinDateTime();
if (val == null) {
return false;
}
xml.property(tag, val);
return true;
}
if (tag.equals(CaldavTags.supportedCalendarComponentSet)) {
/* e.g.
* <C:supported-calendar-component-set
* xmlns:C="urn:ietf:params:xml:ns:caldav">
* <C:comp name="VEVENT"/>
* <C:comp name="VTODO"/>
* </C:supported-calendar-component-set>
*/
if ((calType != CalDAVCollection.calTypeCalendarCollection) &&
(calType != CalDAVCollection.calTypeInbox) &&
(calType != CalDAVCollection.calTypeOutbox)) {
return false;
}
xml.openTag(tag);
xml.startTag(CaldavTags.comp);
xml.attribute("name", "VEVENT");
xml.endEmptyTag();
xml.newline();
xml.startTag(CaldavTags.comp);
xml.attribute("name", "VTODO");
xml.endEmptyTag();
xml.newline();
xml.startTag(CaldavTags.comp);
xml.attribute("name", "VAVAILABILITY");
xml.endEmptyTag();
xml.newline();
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.supportedCalendarData)) {
/* e.g.
* <C:supported-calendar-data
* xmlns:C="urn:ietf:params:xml:ns:caldav">
* <C:calendar-data content-type="text/calendar" version="2.0"/>
* </C:supported-calendar-data>
*/
xml.openTag(tag);
xml.startTag(CaldavTags.calendarData);
xml.attribute("content-type", "text/calendar");
xml.attribute("version", "2.0");
xml.endEmptyTag();
xml.newline();
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.calendarTimezone)) {
String tzid = col.getTimezone();
if (tzid == null) {
return false;
}
String val = getSysi().toStringTzCalendar(tzid);
if (val == null) {
return false;
}
xml.cdataProperty(tag, val);
return true;
}
if (tag.equals(CaldavTags.defaultAlarmVeventDate) ||
tag.equals(CaldavTags.defaultAlarmVeventDatetime) ||
tag.equals(CaldavTags.defaultAlarmVtodoDate) ||
tag.equals(CaldavTags.defaultAlarmVtodoDatetime)) {
/* Private to user - look at alias only */
if (cundereffed == null) {
return false;
}
String val = cundereffed.getProperty(tag);
if (val == null) {
return false;
}
xml.cdataProperty(tag, val);
return true;
}
// Not known - try higher
return super.generatePropertyValue(tag, intf, allProp);
} catch (WebdavException wde) {
throw wde;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
| public boolean generatePropertyValue(final QName tag,
final WebdavNsIntf intf,
final boolean allProp) throws WebdavException {
XmlEmit xml = intf.getXmlEmit();
try {
int calType;
CalDAVCollection c = (CalDAVCollection)getCollection(true); // deref this
CalDAVCollection cundereffed =
(CalDAVCollection)getCollection(false); // don't deref this
if (c == null) {
// Probably no access -- fake it up as a collection
calType = CalDAVCollection.calTypeCollection;
} else {
calType = c.getCalType();
}
if (tag.equals(WebdavTags.resourcetype)) {
// dav 13.9
xml.openTag(tag);
xml.emptyTag(WebdavTags.collection);
if (debug) {
debugMsg("generatePropResourcetype for " + col);
}
//boolean isCollection = cal.getCalendarCollection();
if (calType == CalDAVCollection.calTypeInbox) {
xml.emptyTag(CaldavTags.scheduleInbox);
} else if (calType == CalDAVCollection.calTypeOutbox) {
xml.emptyTag(CaldavTags.scheduleOutbox);
} else if (calType == CalDAVCollection.calTypeCalendarCollection) {
xml.emptyTag(CaldavTags.calendar);
} else if (calType == CalDAVCollection.calTypeNotifications) {
xml.emptyTag(AppleServerTags.notifications);
}
if (Boolean.valueOf(c.getProperty(AppleServerTags.shared))) {
if (c.getOwner().equals(getSysi().getPrincipal())) {
xml.emptyTag(AppleServerTags.sharedOwner);
} else {
xml.emptyTag(AppleServerTags.shared);
}
}
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.scheduleCalendarTransp)) {
xml.openTag(tag);
if (col.getAffectsFreeBusy()) {
xml.emptyTag(CaldavTags.opaque);
} else {
xml.emptyTag(CaldavTags.transparent);
}
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.scheduleDefaultCalendarURL) &&
(calType == CalDAVCollection.calTypeInbox)) {
xml.openTag(tag);
CalPrincipalInfo cinfo = getSysi().getCalPrincipalInfo(getOwner());
if (cinfo.defaultCalendarPath != null) {
generateHref(xml, cinfo.defaultCalendarPath);
}
xml.closeTag(tag);
return true;
}
if (tag.equals(AppleServerTags.getctag)) {
if (c != null) {
xml.property(tag, c.getEtag());
} else {
xml.property(tag, col.getEtag());
}
return true;
}
if (tag.equals(AppleServerTags.sharedUrl)) {
if (!cundereffed.isAlias()) {
return false;
}
xml.openTag(tag);
xml.property(WebdavTags.href, cundereffed.getAliasUri());
xml.closeTag(tag);
return true;
}
if (tag.equals(AppleIcalTags.calendarColor)) {
String val = col.getColor();
if (val == null) {
return false;
}
xml.property(tag, val);
return true;
}
if (tag.equals(CaldavTags.calendarDescription)) {
xml.property(tag, col.getDescription());
return true;
}
if ((col.getCalType() == CalDAVCollection.calTypeInbox) &&
(tag.equals(CaldavTags.calendarFreeBusySet))) {
xml.openTag(tag);
Collection<String> hrefs = getSysi().getFreebusySet();
for (String href: hrefs) {
xml.property(WebdavTags.href, href);
}
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.maxAttendeesPerInstance)) {
if ((calType != CalDAVCollection.calTypeCalendarCollection) &&
(calType != CalDAVCollection.calTypeInbox) &&
(calType != CalDAVCollection.calTypeOutbox)) {
return false;
}
Integer val = getSysi().getSystemProperties().getMaxAttendeesPerInstance();
if (val == null) {
return false;
}
xml.property(tag, String.valueOf(val));
return true;
}
if (tag.equals(CaldavTags.maxDateTime)) {
if ((calType != CalDAVCollection.calTypeCalendarCollection) &&
(calType != CalDAVCollection.calTypeInbox) &&
(calType != CalDAVCollection.calTypeOutbox)) {
return false;
}
Integer val = getSysi().getSystemProperties().getMaxAttendeesPerInstance();
if (val == null) {
return false;
}
xml.property(tag, String.valueOf(val));
return true;
}
if (tag.equals(CaldavTags.maxInstances)) {
if ((calType != CalDAVCollection.calTypeCalendarCollection) &&
(calType != CalDAVCollection.calTypeInbox) &&
(calType != CalDAVCollection.calTypeOutbox)) {
return false;
}
Integer val = getSysi().getSystemProperties().getMaxInstances();
if (val == null) {
return false;
}
xml.property(tag, String.valueOf(val));
return true;
}
if (tag.equals(CaldavTags.maxResourceSize)) {
if ((calType != CalDAVCollection.calTypeCalendarCollection) &&
(calType != CalDAVCollection.calTypeInbox) &&
(calType != CalDAVCollection.calTypeOutbox)) {
return false;
}
Integer val = getSysi().getSystemProperties().getMaxUserEntitySize();
if (val == null) {
return false;
}
xml.property(tag, String.valueOf(val));
return true;
}
if (tag.equals(CaldavTags.minDateTime)) {
if ((calType != CalDAVCollection.calTypeCalendarCollection) &&
(calType != CalDAVCollection.calTypeInbox) &&
(calType != CalDAVCollection.calTypeOutbox)) {
return false;
}
String val = getSysi().getSystemProperties().getMinDateTime();
if (val == null) {
return false;
}
xml.property(tag, val);
return true;
}
if (tag.equals(CaldavTags.supportedCalendarComponentSet)) {
/* e.g.
* <C:supported-calendar-component-set
* xmlns:C="urn:ietf:params:xml:ns:caldav">
* <C:comp name="VEVENT"/>
* <C:comp name="VTODO"/>
* </C:supported-calendar-component-set>
*/
if ((calType != CalDAVCollection.calTypeCalendarCollection) &&
(calType != CalDAVCollection.calTypeInbox) &&
(calType != CalDAVCollection.calTypeOutbox)) {
return false;
}
xml.openTag(tag);
xml.startTag(CaldavTags.comp);
xml.attribute("name", "VEVENT");
xml.endEmptyTag();
xml.newline();
xml.startTag(CaldavTags.comp);
xml.attribute("name", "VTODO");
xml.endEmptyTag();
xml.newline();
xml.startTag(CaldavTags.comp);
xml.attribute("name", "VAVAILABILITY");
xml.endEmptyTag();
xml.newline();
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.supportedCalendarData)) {
/* e.g.
* <C:supported-calendar-data
* xmlns:C="urn:ietf:params:xml:ns:caldav">
* <C:calendar-data content-type="text/calendar" version="2.0"/>
* </C:supported-calendar-data>
*/
xml.openTag(tag);
xml.startTag(CaldavTags.calendarData);
xml.attribute("content-type", "text/calendar");
xml.attribute("version", "2.0");
xml.endEmptyTag();
xml.newline();
xml.closeTag(tag);
return true;
}
if (tag.equals(CaldavTags.calendarTimezone)) {
String tzid = col.getTimezone();
if (tzid == null) {
return false;
}
String val = getSysi().toStringTzCalendar(tzid);
if (val == null) {
return false;
}
xml.cdataProperty(tag, val);
return true;
}
if (tag.equals(CaldavTags.defaultAlarmVeventDate) ||
tag.equals(CaldavTags.defaultAlarmVeventDatetime) ||
tag.equals(CaldavTags.defaultAlarmVtodoDate) ||
tag.equals(CaldavTags.defaultAlarmVtodoDatetime)) {
/* Private to user - look at alias only */
if (cundereffed == null) {
return false;
}
String val = cundereffed.getProperty(tag);
if (val == null) {
return false;
}
xml.cdataProperty(tag, val);
return true;
}
// Not known - try higher
return super.generatePropertyValue(tag, intf, allProp);
} catch (WebdavException wde) {
throw wde;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
|
diff --git a/src/cz/cuni/mff/peckam/java/origamist/utils/RedBlackTree.java b/src/cz/cuni/mff/peckam/java/origamist/utils/RedBlackTree.java
index 0f890df..7dd8bfe 100644
--- a/src/cz/cuni/mff/peckam/java/origamist/utils/RedBlackTree.java
+++ b/src/cz/cuni/mff/peckam/java/origamist/utils/RedBlackTree.java
@@ -1,1956 +1,1956 @@
package cz.cuni.mff.peckam.java.origamist.utils;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
/**
* A red-black tree implementation.
*
* Inspired by the Sun JRE's implementation.
*
* @author Martin Pecka
*/
public class RedBlackTree<K, V> extends AbstractMap<K, V> implements SortedMap<K, V>, Cloneable, Serializable
{
/** */
private static final long serialVersionUID = 919286545866124006L;
/** The comparator to be used for comparing the keys. */
protected final Comparator<? super K> comparator;
/** The root of the tree. */
protected transient Entry root = null;
/** Number of elements of the tree. */
protected transient int size = 0;
/** Number of modifications, used for detecting concurrent modifications while using iterators. */
protected transient int modCount = 0;
/**
* Colors of the tree's nodes.
*
* @author Martin Pecka
*/
protected enum Color
{
RED, BLACK
};
/**
* Construct a new red-black tree with the default comparator. The default comparator needs all values inserted into
* or deleted from the tree to implement {@link Comparable}<K>. If an element doesn't implement it, an insert
* or delete method will end up throwing a {@link ClassCastException}.
*/
public RedBlackTree()
{
comparator = getDefaultComparator();
}
/**
* Construct a new red-black tree using the given comparator. The comparator must be able to compare every two
* "valid" keys, and must throw a {@link ClassCastException} if an "invalid" key is to be compared.
*
* @param comparator The comparator to use for comparing this tree's element's keys.
*/
public RedBlackTree(Comparator<? super K> comparator)
{
this.comparator = comparator;
}
/**
* Create a new red-black tree with entries from the given map. Use the default comparator to compare the keys. The
* keys must implement {@link Comparable}<K>.
*
* @param m The map to take entries from.
*
* @throws ClassCastException If a key from the given map doesn't implement the {@link Comparable}<K>
* interface.
* @throws NullPointerException If <code>m == null</code> or if the map contains a <code>null</code> key and the
* comparator doesn't support it.
*/
public RedBlackTree(Map<? extends K, ? extends V> m)
{
this();
putAll(m);
}
/**
* Create a new red-black tree with entries from the given sorted map. The map's comparator is used. This is an
* effective (linear time) algorithm.
*
* @param m The sorted map to take entries from.
*/
public RedBlackTree(SortedMap<K, ? extends V> m)
{
this(m.comparator());
buildFromSorted(m.size(), m.entrySet().iterator());
}
/**
* @return The number of entries in this tree.
*/
@Override
public int size()
{
return size;
}
/**
* Test if the tree contains an entry with the given key.
*
* Runs in logarithmic time (or linear to the tree's height).
*
* @throws ClassCastException If the specified key cannot be compared with the keys currently in the map
* @throws NullPointerException If the specified key is <code>null</code> and this tree's comparator does not permit
* <code>null</code> keys.
*/
@SuppressWarnings("unchecked")
@Override
public boolean containsKey(Object key)
{
return getEntry((K) key) != null;
}
/**
* Test if the tree contains an entry with the given value.
*
* Runs in time linear to the size of the tree (ineffective).
*/
@SuppressWarnings("unchecked")
@Override
public boolean containsValue(Object value)
{
if (root == null)
return false;
return getPathForValue((V) value).size() > 0;
}
/**
* Return the value associated to the given key.
*
* Runs in logarithmic time (or linear to the tree's height).
*
* @throws ClassCastException if the specified key cannot be compared with the keys currently in the map.
* @throws NullPointerException If the specified key is <code>null</code> and this tree's comparator does not permit
* <code>null</code> keys.
*/
@Override
public V get(Object key)
{
@SuppressWarnings("unchecked")
Entry e = getEntry((K) key);
return (e == null ? null : e.value);
}
/**
* @return The comparator used for comparing keys.
*/
@Override
public Comparator<? super K> comparator()
{
return comparator;
}
/**
* Return the lowest key in the tree.
*
* Runs in logarithmic time (or linear to the tree's height).
*
* @throws NoSuchElementException {@inheritDoc}
*/
@Override
public K firstKey()
{
Entry e = getFirstEntry();
if (e == null)
throw new NoSuchElementException("No first key was found.");
return e.getKey();
}
/**
* Return the highest key in the tree.
*
* Runs in logarithmic time (or linear to the tree's height).
*
* @throws NoSuchElementException {@inheritDoc}
*/
public K lastKey()
{
Entry e = getLastEntry();
if (e == null)
throw new NoSuchElementException("No last key was found.");
return e.getKey();
}
/**
* Puts all entries from the given map into this tree.
*
* If the provided map is a {@link SortedMap} and the tree is empty, a linear-time algorithm is used, othwerwise
* this operations takes O(n*log n) time.
*
* @throws ClassCastException If a key or value has invalid class.
* @throws NullPointerException If the specified map is <code>null</code> or the specified map contains a
* <code>null</code> key and this tree does not permit <code>null</code> keys.
*/
public void putAll(Map<? extends K, ? extends V> map)
{
if (size == 0 && map.size() != 0 && map instanceof SortedMap<?, ?>) {
Comparator<?> c = ((SortedMap<? extends K, ? extends V>) map).comparator();
if (comparator.equals(c)) {
++modCount;
buildFromSorted(map.size(), map.entrySet().iterator());
return;
}
}
super.putAll(map);
}
/**
* Return the entry for the given key. If the key is not found, return <code>null</code>.
*
* Runs in logarithmic time (or linear to the tree's height).
*
* @param key The key to find the entry for.
* @return The entry for the given key. If the key is not found, return <code>null</code>.
*
* @throws NullPointerException If key is <code>null</code> and this tree does not permit <code>null</code> keys.
*/
protected Entry getEntry(K key)
{
Entry p = root;
while (p != null) {
int cmp = comparator.compare(key, p.key);
if (cmp < 0)
p = p.left;
else if (cmp > 0)
p = p.right;
else
return p;
}
return null;
}
/**
* Returns the first entry in the tree (according to the comparator).
*
* @return The entry with the lowest key. <code>null</code> if the tree is empty.
*/
protected Entry getFirstEntry()
{
Entry p = root;
if (p != null)
while (p.left != null)
p = p.left;
return p;
}
/**
* Returns the last entry in the tree (according to the comparator).
*
* @return The entry with the highest key. <code>null</code> if the tree is empty.
*/
protected Entry getLastEntry()
{
Entry p = root;
if (p != null)
while (p.right != null)
p = p.right;
return p;
}
/**
* Return the path to the given key. If this tree doesn't contain the given key, the path will end with the entry
* the key would be a child of.
*
* Runs in logarithmic time (or linear to the tree's height).
*
* @param key The key to find path for.
* @return Return the path to the given key. If this tree doesn't contain the given key, the path will end with the
* entry the key would be a child of.
*/
protected TreePath getPath(K key)
{
TreePath path = new TreePath();
Entry p = root;
while (p != null) {
path.addLast(p);
int cmp = comparator.compare(key, p.key);
if (cmp < 0)
p = p.left;
else if (cmp > 0)
p = p.right;
else
break;
}
return path;
}
/**
* Return the path to the given value. If this tree doesn't contain the given value, empty path will be returned.
*
* Runs in time linear to the size of this tree (ineffective).
*
* @param value The value to find path for.
* @return The path to the given value. If this tree doesn't contain the given value, empty path will be returned.
*/
protected TreePath getPathForValue(V value)
{
TreePath path = new TreePath();
path.add(root);
if (searchPathForValue(value, path)) {
return path;
} else {
return new TreePath();
}
}
/**
* Return whether the subtree defined by the last entry of the given path contains the given value. If it contains,
* <code>path</code> will contain the path to the value's entry, otherwise it will be left unchanged.
*
* @param value The value to find path for.
* @param path The path that defines the subtree to search within.
* @return Return whether the subtree defined by the last entry of the given path contains the given value.
*/
protected boolean searchPathForValue(V value, TreePath path)
{
Entry p = path.getLast();
if (p.value.equals(value)) {
return true;
} else {
if (p.left != null) {
path.addLast(p.left);
if (searchPathForValue(value, path)) {
return true;
}
path.removeLast();
}
if (p.right != null) {
path.addLast(p.right);
if (searchPathForValue(value, path)) {
return true;
}
path.removeLast();
}
}
return false;
}
/**
* Return an unmodifiable view of the entry for the given key.
*
* @param key The key to find the entry for.
* @return The entry for the given key. If the key is not found, return <code>null</code>.
*
* @throws NullPointerException If key is <code>null</code> and this tree does not permit <code>null</code> keys.
*/
public Map.Entry<K, V> getEntryForKey(K key)
{
return exportEntry(getEntry(key));
}
/**
* Put the key and value in the tree.
*
* Runs in logarithmic time (or linear to the tree's height).
*
* @throws ClassCastException If the specified key cannot be compared with the keys currently in the map.
* @throws NullPointerException If the specified key is <code>null</code> and this tree's comparator does not permit
* <code>null</code> keys.
*/
@Override
public V put(K key, V value)
{
if (root == null) {
comparator.compare(key, key); // throws NPE if the comparator doesn't support null
root = new Entry(key, value);
size = 1;
modCount++;
return null;
}
TreePath path = getPath(key);
// if we found the key, just change its associated value
if (path.endsWithKey(key))
return path.getLast().setValue(value);
int cmp = comparator.compare(key, path.getLast().getKey());
// now we have the new entry's parent as the last item on the path
Entry e = new Entry(key, value);
if (cmp < 0)
path.getLast().left = e;
else
path.getLast().right = e;
path.addLast(e);
repairTreeAfterInsert(path);
size++;
modCount++;
return null;
}
/**
* Removes the entry with the given key, if it exists in the tree.
*
* Runs in logarithmic time (or linear to the tree's height).
*
* @throws ClassCastException if the specified key cannot be compared with the keys currently in the map.
* @throws NullPointerException If the specified key is <code>null</code> and this tree's comparator does not permit
* <code>null</code> keys.
*/
@Override
public V remove(Object key)
{
@SuppressWarnings("unchecked")
K k = (K) key;
TreePath path = getPath(k);
if (!path.endsWithKey(k))
return null;
V oldValue = path.getLast().value;
deleteLastPathEntry(path);
return oldValue;
}
@Override
public void clear()
{
modCount++;
size = 0;
root = null;
}
/**
* Repair the tree structure after insert.
*
* @param path The path to the newly added entry.
*/
protected void repairTreeAfterInsert(RedBlackTree<K, V>.TreePath path)
{
path.getLast().color = Color.RED;
while (path.size() > 1 && path.getLast(1).color == Color.RED) {
if (path.getLast(1) == leftOf(path.getLast(2))) {
Entry y = rightOf(path.getLast(2));
if (colorOf(y) == Color.RED) {
setColor(path.getLast(2), Color.BLACK);
setColor(y, Color.BLACK);
setColor(path.getLast(2), Color.RED);
path.removeLast();
path.removeLast();
} else {
if (path.getLast() == rightOf(path.getLast(1))) {
path.removeLast();
path.rotateLeft();
}
setColor(path.getLast(1), Color.BLACK);
setColor(path.getLast(2), Color.RED);
path.removeLast();
path.removeLast();
path.rotateRight();
}
} else {
Entry y = leftOf(path.getLast(2));
if (colorOf(y) == Color.RED) {
setColor(path.getLast(1), Color.BLACK);
setColor(y, Color.BLACK);
setColor(path.getLast(2), Color.RED);
path.removeLast();
path.removeLast();
} else {
if (path.getLast() == leftOf(path.getLast(1))) {
path.removeLast();
path.rotateRight();
}
setColor(path.getLast(1), Color.BLACK);
setColor(path.getLast(2), Color.RED);
path.removeLast();
path.removeLast();
path.rotateLeft();
}
}
}
root.color = Color.BLACK;
}
/**
* Delete the path's last entry and repair the tree. The path will be returned in an undetermined state.
*
* @param path The path to the entry to be deleted.
*/
protected void deleteLastPathEntry(RedBlackTree<K, V>.TreePath path)
{
modCount++;
size--;
Entry p = path.getLast();
// If p has 2 children, copy successor's element to p and then make p point to successor.
if (p.left != null && p.right != null) {
path.moveToSuccesor();
Entry s = path.getLast();
p.key = s.key;
p.value = s.value;
p = s;
}
// now we can be sure that p has at most one non-null child
// Start fixup at replacement node, if it exists.
Entry replacement = (p.left != null ? p.left : p.right);
if (replacement != null) {
if (path.size() == 1)
root = replacement;
else if (p == path.getLast(1).left)
path.getLast(1).left = replacement;
else
path.getLast(1).right = replacement;
path.removeLast();
path.addLast(replacement);
// Fix replacement
if (p.color == Color.BLACK)
repairTreeAfterDeletion(path);
} else if (path.size() == 1) { // return if we are the only node.
root = null;
} else { // No children. Use self as phantom replacement and unlink.
if (p.color == Color.BLACK)
repairTreeAfterDeletion(path);
if (path.size() > 1) {
if (p == path.getLast(1).left)
path.getLast(1).left = null;
else if (p == path.getLast(1).right)
path.getLast(1).right = null;
path.removeLast();
}
}
}
/**
* Repair the tree structure after deletion.
*
* @param path Path points to the entry used as replacement (or the deleted entry itself if it has no children).
* After the repair is complete, path leads to the entry with the same key as it led before calling this
* procedure.
*/
protected void repairTreeAfterDeletion(RedBlackTree<K, V>.TreePath path)
{
boolean setColor = false;
Entry toDelete = path.getLast();
while (path.size() > 1 && colorOf(path.getLast()) == Color.BLACK) {
if (path.getLast() == leftOf(path.getLast(1))) {
Entry sib = rightOf(path.getLast(1));
if (colorOf(sib) == Color.RED) {
setColor(sib, Color.BLACK);
setColor(path.getLast(1), Color.RED);
Entry p = path.removeLast();
path.rotateLeft(); // p still remains the left child of its original parent
path.addLast(p);
sib = rightOf(path.getLast(1));
}
if (colorOf(leftOf(sib)) == Color.BLACK && colorOf(rightOf(sib)) == Color.BLACK) {
setColor(sib, Color.RED);
path.removeLast();
setColor = true;
} else {
if (colorOf(rightOf(sib)) == Color.BLACK) {
setColor(leftOf(sib), Color.BLACK);
setColor(sib, Color.RED);
Entry p = path.removeLast();
path.addLast(sib);
path.rotateRight(); // rotate p's sibling
path.removeLast(); // and let path lead to p again
path.removeLast();
path.addLast(p);
sib = rightOf(path.getLast(1));
}
setColor(sib, colorOf(path.getLast(1)));
setColor(path.getLast(1), Color.BLACK);
setColor(rightOf(sib), Color.BLACK);
path.removeLast();
path.rotateLeft();
setColor(root, Color.BLACK);
setColor = false;
break;
}
} else { // symmetric
Entry sib = leftOf(path.getLast(1));
if (colorOf(sib) == Color.RED) {
setColor(sib, Color.BLACK);
setColor(path.getLast(1), Color.RED);
Entry p = path.removeLast();
path.rotateRight();
path.addLast(p); // p still remains the left child of its original parent
sib = leftOf(path.getLast(1));
}
if (colorOf(rightOf(sib)) == Color.BLACK && colorOf(leftOf(sib)) == Color.BLACK) {
setColor(sib, Color.RED);
path.removeLast();
setColor = true;
} else {
if (colorOf(leftOf(sib)) == Color.BLACK) {
setColor(rightOf(sib), Color.BLACK);
setColor(sib, Color.RED);
Entry p = path.removeLast();
path.addLast(sib);
path.rotateLeft(); // rotate p's sibling
path.removeLast(); // and let path lead to p again
path.removeLast();
path.addLast(p);
sib = leftOf(path.getLast(1));
}
setColor(sib, colorOf(path.getLast(1)));
setColor(path.getLast(1), Color.BLACK);
setColor(leftOf(sib), Color.BLACK);
path.removeLast();
path.rotateRight();
setColor(root, Color.BLACK);
setColor = false;
break;
}
}
}
if (setColor)
setColor(path.getLast(), Color.BLACK);
// return to the initial endpoint
boolean goHigher = comparator.compare(toDelete.getKey(), path.getLast().getKey()) >= 0;
- while (!path.endsWithKey(toDelete.getKey())) {
+ while (path.size() > 0 && !path.endsWithKey(toDelete.getKey())) {
if (goHigher)
path.moveToSuccesor();
else
path.moveToPredecessor();
}
}
/**
* Linear time tree building algorithm from sorted data.
*
* It is assumed that the comparator of the tree is already set prior to calling this method.
*
* @param size The size of the built tree.
* @param it New entries are created from entries from this iterator.
*/
protected void buildFromSorted(int size, Iterator<?> it)
{
this.size = size;
root = buildFromSorted(0, 0, size - 1, computeRedLevel(size), it);
}
/**
* Find the level down to which to assign all nodes BLACK. This is the last `full' level of the complete binary tree
* produced by buildTree. The remaining nodes are colored RED. (This makes a `nice' set of color assignments wrt
* future insertions.) This level number is computed by finding the number of splits needed to reach the zeroeth
* node. (The answer is ~lg(N), but in any case must be computed by same quick O(lg(N)) loop.)
*/
protected int computeRedLevel(int sz)
{
int level = 0;
for (int m = sz - 1; m >= 0; m = m / 2 - 1)
level++;
return level;
}
/**
* Recursive "helper method" that does the real work of the previous method.
*
* It is assumed that the comparator and size fields of the RedBlackTree are already set prior to calling this
* method. (It ignores both fields.)
*
* @param level The current level of tree. Initial call should be 0.
* @param lo The first element index of this subtree. Initial should be 0.
* @param hi The last element index of this subtree. Initial should be size-1.
* @param redLevel The level at which nodes should be red. Must be equal to computeRedLevel for tree of this size.
* @param it New entries are created from entries from this iterator.
*/
private final Entry buildFromSorted(int level, int lo, int hi, int redLevel, Iterator<?> it)
{
/*
* Strategy: The root is the middlemost element. To get to it, we
* have to first recursively construct the entire left subtree,
* so as to grab all of its elements. We can then proceed with right
* subtree.
*
* The lo and hi arguments are the minimum and maximum
* indices to pull out of the iterator or stream for current subtree.
* They are not actually indexed, we just proceed sequentially,
* ensuring that items are extracted in corresponding order.
*/
if (hi < lo)
return null;
int mid = (lo + hi) / 2;
Entry left = null;
if (lo < mid)
left = buildFromSorted(level + 1, lo, mid - 1, redLevel, it);
K key;
V value;
@SuppressWarnings("unchecked")
Map.Entry<K, V> entry = (java.util.Map.Entry<K, V>) it.next();
key = entry.getKey();
value = entry.getValue();
Entry middle = new Entry(key, value);
// color nodes in non-full bottommost level red
if (level == redLevel)
middle.color = Color.RED;
if (left != null) {
middle.left = left;
}
if (mid < hi) {
Entry right = buildFromSorted(level + 1, mid + 1, hi, redLevel, it);
middle.right = right;
}
return middle;
}
/**
* Returns a shallow copy of this <code>RedBlackTree</code> instance. (The keys and
* values themselves are not cloned.)
*
* @return A shallow copy of this tree.
*/
@SuppressWarnings("unchecked")
@Override
public RedBlackTree<K, V> clone()
{
RedBlackTree<K, V> clone = null;
try {
clone = (RedBlackTree<K, V>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
clone.root = null;
clone.size = 0;
clone.modCount = 0;
clone.entrySet = null;
clone.keySet = null;
clone.buildFromSorted(size, entrySet().iterator());
return clone;
}
/**
* A view on a part of this tree.
*
* @author Martin Pecka
*/
protected class SubMap extends AbstractMap<K, V> implements SortedMap<K, V>
{
/** Bounds. */
protected K from, to;
/** Are the bounds inclusive? */
protected boolean fromIncl, toIncl;
/** Ignore bounds? */
protected boolean fromStart, toEnd;
/**
* Create a submap defined by the arguments.
*
* @param fromStart If true, ignore the lower bound, the submap will be down-unbounded.
* @param from The lower bound.
* @param fromIncl If true, the lower bound is treated as inclusive.
* @param toEnd If true, ignore the upper bound, the submap will be up-unbounded.
* @param to The upper bound.
* @param toIncl If true, the upper bound is treated as inclusive.
*
* @throws IllegalArgumentException If from > to and the bounds aren't ignored.
*/
public SubMap(boolean fromStart, K from, boolean fromIncl, boolean toEnd, K to, boolean toIncl)
{
if (!fromStart && !toEnd) {
if (comparator.compare(from, to) > 0)
throw new IllegalArgumentException("Cannot construct submap with from > to.");
} else {
if (!fromStart)
comparator.compare(from, from); // type check
if (!toEnd)
comparator.compare(to, to); // type check
}
this.from = from;
this.to = to;
this.fromIncl = fromIncl;
this.toIncl = toIncl;
this.fromStart = fromStart;
this.toEnd = toEnd;
}
@Override
public int size()
{
return (fromStart && toEnd) ? RedBlackTree.this.size() : entrySet().size();
}
@Override
public boolean isEmpty()
{
return (fromStart && toEnd) ? RedBlackTree.this.isEmpty() : entrySet().isEmpty();
}
/**
* Returns true if the given key is in the range this submap works on.
*
* @param key The key to compare.
* @return true if the given key is in the range this submap works on.
*
* @throws NullPointerException If the key is <code>null</code> and the iterator doesn't handle
* <code>null</code> values.
* @throws ClassCastException If key cannot be cast to the type of keys in the tree.
*/
protected boolean keyValid(Object key)
{
@SuppressWarnings("unchecked")
K k = (K) key;
comparator.compare(k, k); // check type
return (fromStart || comparator.compare(from, k) < (fromIncl ? 1 : 0))
&& (toEnd || comparator.compare(k, to) < (toIncl ? 1 : 0));
}
@Override
public boolean containsKey(Object key)
{
return keyValid(key) && RedBlackTree.this.containsKey(key);
}
@Override
public boolean containsValue(Object value)
{
@SuppressWarnings("unchecked")
TreePath path = getPathForValue((V) value);
if (path.size() == 0)
return false;
return containsKey(path.getLast().getKey());
}
@Override
public V get(Object key)
{
if (!keyValid(key))
return null;
return RedBlackTree.this.get(key);
}
@Override
public V put(K key, V value)
{
if (!keyValid(key))
throw new IllegalArgumentException("The given key is out of range.");
return null;
}
@Override
public V remove(Object key)
{
return keyValid(key) ? RedBlackTree.this.remove(key) : null;
}
@Override
public void putAll(Map<? extends K, ? extends V> m)
{
if (fromStart && toEnd) {
RedBlackTree.this.putAll(m);
} else {
for (Entry<? extends K, ? extends V> e : m.entrySet()) {
put(e.getKey(), e.getValue());
}
}
}
@Override
public void clear()
{
if (fromStart && toEnd) {
RedBlackTree.this.clear();
} else {
entrySet().clear();
}
}
@Override
public Comparator<? super K> comparator()
{
return comparator;
}
@Override
public SortedMap<K, V> subMap(K fromKey, K toKey)
{
if (!keyValid(fromKey))
throw new IllegalArgumentException(
"Cannot construct submap with lower bound outside the containing submap.");
if (!keyValid(toKey))
throw new IllegalArgumentException(
"Cannot construct submap with upper bound outside the containing submap.");
return RedBlackTree.this.subMap(fromKey, toKey);
}
@Override
public SortedMap<K, V> headMap(K toKey)
{
if (!keyValid(toKey))
throw new IllegalArgumentException(
"Cannot construct submap with upper bound outside the containing submap.");
if (fromStart) {
return RedBlackTree.this.headMap(toKey);
} else {
return subMap(from, toKey);
}
}
@Override
public SortedMap<K, V> tailMap(K fromKey)
{
if (!keyValid(fromKey))
throw new IllegalArgumentException(
"Cannot construct submap with lower bound outside the containing submap.");
if (toEnd) {
return RedBlackTree.this.tailMap(fromKey);
} else {
return subMap(fromKey, to);
}
}
@Override
public K firstKey()
{
if (fromStart) {
return RedBlackTree.this.firstKey();
} else {
TreePath path = getPath(from);
while (path.size() > 0 && comparator.compare(path.getLast().getKey(), from) < (fromIncl ? 0 : 1))
path.moveToSuccesor();
if (path.size() > 0) {
return path.getLast().getKey();
} else {
return null;
}
}
}
@Override
public K lastKey()
{
if (toEnd) {
return RedBlackTree.this.lastKey();
} else {
TreePath path = getPath(to);
while (path.size() > 0 && comparator.compare(to, path.getLast().getKey()) < (toIncl ? 0 : 1))
path.moveToPredecessor();
if (path.size() > 0) {
return path.getLast().getKey();
} else {
return null;
}
}
}
protected SortedSet<K> keySet = null;
protected class SubMapKeySet extends AbstractSet<K> implements SortedSet<K>
{
@Override
public Iterator<K> iterator()
{
RedBlackTree<K, V>.Entry first = fromStart ? getFirstEntry() : getEntry(firstKey());
return new KeyIterator(first) {
@Override
public boolean hasNext()
{
return super.hasNext() && keyValid(pathToNext.getLast().getKey());
}
};
}
@Override
public int size()
{
return SubMap.this.size();
}
@Override
public boolean remove(Object o)
{
int oldSize = SubMap.this.size();
SubMap.this.remove(o);
return oldSize != SubMap.this.size();
}
@Override
public boolean contains(Object o)
{
return SubMap.this.containsKey(o);
}
@Override
public Comparator<? super K> comparator()
{
return comparator;
}
@Override
public SortedSet<K> subSet(K fromElement, K toElement)
{
return new SubMap(false, fromElement, true, false, toElement, false).keySet();
}
@Override
public SortedSet<K> headSet(K toElement)
{
return new SubMap(true, null, true, false, toElement, false).keySet();
}
@Override
public SortedSet<K> tailSet(K fromElement)
{
return new SubMap(false, fromElement, true, true, null, false).keySet();
}
@Override
public K first()
{
return SubMap.this.firstKey();
}
@Override
public K last()
{
return SubMap.this.lastKey();
}
}
@Override
public SortedSet<K> keySet()
{
if (keySet == null)
keySet = new SubMapKeySet();
return keySet;
}
protected class SubMapValues extends AbstractCollection<V>
{
@Override
public Iterator<V> iterator()
{
RedBlackTree<K, V>.Entry first = fromStart ? getFirstEntry() : getEntry(firstKey());
return new ValueIterator(first) {
@Override
public boolean hasNext()
{
return super.hasNext() && keyValid(pathToNext.getLast().getKey());
}
};
}
@Override
public int size()
{
return SubMap.this.size();
}
}
@Override
public Collection<V> values()
{
if (values == null)
values = new SubMapValues();
return values;
}
protected Set<Map.Entry<K, V>> entrySet = null;
protected class SubMapEntrySet extends AbstractSet<Map.Entry<K, V>>
{
@Override
public Iterator<Map.Entry<K, V>> iterator()
{
RedBlackTree<K, V>.Entry first = fromStart ? getFirstEntry() : getEntry(firstKey());
return new EntryIterator(first) {
@Override
public boolean hasNext()
{
return super.hasNext() && keyValid(pathToNext.getLast().getKey());
}
};
}
/** Cache modcount in the times we last computed submap size. */
private int sizeModCount = -1;
/** */
private int cachedSize = 0;
@Override
public int size()
{
if (sizeModCount == modCount) {
return cachedSize;
}
sizeModCount = modCount;
TreePath path = getPath(SubMap.this.firstKey());
K last = SubMap.this.lastKey();
cachedSize = 0;
while (path.size() > 0 && comparator.compare(path.getLast().getKey(), last) <= 0) {
cachedSize++;
path.moveToSuccesor();
}
return cachedSize;
}
@Override
public boolean remove(Object o)
{
@SuppressWarnings("unchecked")
Map.Entry<K, V> e = (Map.Entry<K, V>) o;
TreePath path = getPath(e.getKey());
if (!path.endsWithKey(e.getKey()))
return false;
if (!valEquals(path.getLast().getValue(), e.getValue()))
return false;
int oldSize = SubMap.this.size();
SubMap.this.remove(e.getKey());
return oldSize != SubMap.this.size();
}
@Override
public boolean contains(Object o)
{
@SuppressWarnings("unchecked")
Map.Entry<K, V> e = (Map.Entry<K, V>) o;
if (!keyValid(e.getKey()))
return false;
Map.Entry<K, V> treeE = getEntryForKey(e.getKey());
return treeE != null && valEquals(treeE.getValue(), e.getValue());
}
}
@Override
public Set<Map.Entry<K, V>> entrySet()
{
if (entrySet == null)
entrySet = new SubMapEntrySet();
return entrySet;
}
}
/**
* @throws ClassCastException If the key cannot be compared to the keys in the tree.
* @throws NullPointerException If the specified key is <code>null</code> and this tree's comparator does not permit
* <code>null</code> keys.
* @throws IllegalArgumentException If <code>fromKey > toKey</code>.
*/
@Override
public SortedMap<K, V> subMap(K fromKey, K toKey)
{
return new SubMap(false, fromKey, true, false, toKey, false);
}
/**
* @throws ClassCastException If the key cannot be compared to the keys in the tree.
* @throws NullPointerException If the specified key is <code>null</code> and this tree's comparator does not permit
* <code>null</code> keys.
*/
@Override
public SortedMap<K, V> headMap(K toKey)
{
return new SubMap(true, null, true, false, toKey, false);
}
/**
* @throws ClassCastException If the key cannot be compared to the keys in the tree.
* @throws NullPointerException If the specified key is <code>null</code> and this tree's comparator does not permit
* <code>null</code> keys.
*/
@Override
public SortedMap<K, V> tailMap(K fromKey)
{
return new SubMap(false, fromKey, true, true, null, false);
}
/**
* The view of the values of this tree.
*
* @author Martin Pecka
*/
class Values extends AbstractCollection<V>
{
@Override
public Iterator<V> iterator()
{
return new ValueIterator(getFirstEntry());
}
@Override
public int size()
{
return RedBlackTree.this.size();
}
@Override
public boolean contains(Object o)
{
return RedBlackTree.this.containsValue(o);
}
@Override
public boolean remove(Object o)
{
@SuppressWarnings("unchecked")
TreePath path = getPathForValue((V) o);
if (path.size() > 0) {
deleteLastPathEntry(path);
return true;
}
return false;
}
@Override
public void clear()
{
RedBlackTree.this.clear();
}
}
/**
* A set of views on the entries of the tree.
*
* @author Martin Pecka
*/
class EntrySet extends AbstractSet<Map.Entry<K, V>>
{
@Override
public Iterator<Map.Entry<K, V>> iterator()
{
return new EntryIterator(getFirstEntry());
}
@Override
public boolean contains(Object o)
{
if (!(o instanceof Map.Entry<?, ?>))
return false;
@SuppressWarnings("unchecked")
Map.Entry<K, V> entry = (Map.Entry<K, V>) o;
Entry p = getEntry(entry.getKey());
return p != null && valEquals(p.getValue(), entry.getValue());
}
@Override
public boolean remove(Object o)
{
if (!(o instanceof Map.Entry))
return false;
@SuppressWarnings("unchecked")
Map.Entry<K, V> entry = (Map.Entry<K, V>) o;
TreePath path = getPath(entry.getKey());
if (path.endsWithKey(entry.getKey()) && valEquals(path.getLast().getValue(), entry.getValue())) {
deleteLastPathEntry(path);
return true;
}
return false;
}
@Override
public int size()
{
return RedBlackTree.this.size();
}
@Override
public void clear()
{
RedBlackTree.this.clear();
}
}
/**
* The view of keys in this tree.
*
* @author Martin Pecka
*/
protected class KeySet extends AbstractSet<K> implements SortedSet<K>
{
@Override
public Iterator<K> iterator()
{
return keyIterator();
}
public Iterator<K> descendingIterator()
{
return descendingKeyIterator();
}
@Override
public int size()
{
return RedBlackTree.this.size();
}
@Override
public K first()
{
return firstKey();
}
@Override
public K last()
{
return lastKey();
}
@Override
public Comparator<? super K> comparator()
{
return RedBlackTree.this.comparator();
}
@Override
public boolean remove(Object o)
{
int oldSize = size();
RedBlackTree.this.remove(o);
return size() != oldSize;
}
@Override
public SortedSet<K> subSet(K fromElement, K toElement)
{
return new SubMap(false, fromElement, true, false, toElement, false).keySet();
}
@Override
public SortedSet<K> headSet(K toElement)
{
return new SubMap(true, null, true, false, toElement, false).keySet();
}
@Override
public SortedSet<K> tailSet(K fromElement)
{
return new SubMap(false, fromElement, true, true, null, false).keySet();
}
}
private Set<K> keySet = null;
@Override
public Set<K> keySet()
{
if (keySet == null)
keySet = new KeySet();
return keySet;
}
private Collection<V> values = null;
@Override
public Collection<V> values()
{
if (values == null)
values = new Values();
return values;
}
/** A view of the tree's entries. */
private transient EntrySet entrySet = null;
@Override
public Set<Map.Entry<K, V>> entrySet()
{
if (entrySet == null)
entrySet = new EntrySet();
return entrySet;
}
/**
* The base for all iterators.
*/
protected abstract class BaseEntryIterator<T> implements Iterator<T>
{
/** The path to the last returned entry. */
protected TreePath pathToLastReturned;
/** The path to "next" entry (if prevEntry() was called, this contains the path to the previous entry). */
protected TreePath pathToNext;
/**
* Modification counter state in the time of this iterator's creation - serves for revealing concurrent
* modification.
*/
protected int expectedModCount;
/** Set to true in each remove() call and to false in each nextEntry() and prevEntry(). */
protected boolean usedRemove = false;
/**
* Create the iterator with <code>first</code> as the first entry to be returned by next().
*
* @param first The first entry to return. Can be <code>null</code> (in that case the iterator will be empty).
*/
public BaseEntryIterator(Entry first)
{
expectedModCount = modCount;
pathToLastReturned = null;
if (first != null)
pathToNext = getPath(first.getKey());
else
pathToNext = new TreePath();
}
@Override
public boolean hasNext()
{
return pathToNext.size() > 0;
}
/**
* @return The next entry.
*/
protected Entry nextEntry()
{
if (pathToNext.size() == 0)
throw new NoSuchElementException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
usedRemove = false;
pathToLastReturned = pathToNext;
pathToNext = new TreePath();
pathToNext.addAll(pathToLastReturned);
pathToNext.moveToSuccesor();
return pathToLastReturned.getLast();
}
/**
* @return The previous entry.
*/
protected Entry prevEntry()
{
if (pathToNext.size() == 0)
throw new NoSuchElementException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
usedRemove = false;
pathToLastReturned = pathToNext;
pathToNext = new TreePath();
pathToNext.addAll(pathToLastReturned);
pathToNext.moveToPredecessor();
return pathToLastReturned.getLast();
}
@Override
public void remove()
{
if (pathToLastReturned == null || usedRemove)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
deleteLastPathEntry(pathToLastReturned);
// the path to the next node may have changed
pathToNext = getPath(pathToNext.getLast().getKey());
expectedModCount = modCount;
usedRemove = true;
}
}
/**
* Iterator over entries.
*
* @author Martin Pecka
*/
protected class EntryIterator extends BaseEntryIterator<Map.Entry<K, V>>
{
/**
* Create the iterator over entries beginning with first.
*
* @param first The first entry to start with.
*/
public EntryIterator(Entry first)
{
super(first);
}
@Override
public Map.Entry<K, V> next()
{
return nextEntry();
}
}
/**
* Iterator over values (but sorted by keys).
*
* @author Martin Pecka
*/
protected class ValueIterator extends BaseEntryIterator<V>
{
/**
* Create the iterator over values beginning with <code>first</code> as the first entry.
*
* @param first The first entry to start with.
*/
public ValueIterator(Entry first)
{
super(first);
}
@Override
public V next()
{
return nextEntry().value;
}
}
/**
* Iterator over keys.
*
* @author Martin Pecka
*/
protected class KeyIterator extends BaseEntryIterator<K>
{
/**
* Create the iterator over keys beginning with <code>first</code> as the first entry.
*
* @param first The first entry to start with.
*/
public KeyIterator(Entry first)
{
super(first);
}
@Override
public K next()
{
return nextEntry().key;
}
}
/**
* Iterator over keys in reverse order.
*
* @author Martin Pecka
*/
protected class DescendingKeyIterator extends BaseEntryIterator<K>
{
/**
* Create the iterator over keys beginning with <code>first</code> as the first entry.
*
* @param first The first entry to start with.
*/
public DescendingKeyIterator(Entry first)
{
super(first);
}
@Override
public K next()
{
return prevEntry().key;
}
}
/**
* @return The iterator over keys in ascending order.
*/
public Iterator<K> keyIterator()
{
return new KeyIterator(getFirstEntry());
}
/**
* @return The iterator over keys in descending order.
*/
public Iterator<K> descendingKeyIterator()
{
return new DescendingKeyIterator(getLastEntry());
}
/**
* Test two values for equality. Differs from o1.equals(o2) only in that it copes with <tt>null</tt> o1 properly.
*/
protected final static boolean valEquals(Object o1, Object o2)
{
return (o1 == null ? o2 == null : o1.equals(o2));
}
/**
* Return SimpleImmutableEntry for entry, or <code>null</code> if <code>null</code>.
*/
protected static <K, V> Map.Entry<K, V> exportEntry(RedBlackTree<K, V>.Entry e)
{
return e == null ? null : new AbstractMap.SimpleImmutableEntry<K, V>(e);
}
/**
* Return the color of the given entry, or Black, if it is <code>null</code>.
*
* @param p The entry to get color of.
* @return The color of the given entry, or Black, if it is <code>null</code>.
*/
protected static <K, V> Color colorOf(RedBlackTree<K, V>.Entry p)
{
return (p == null ? Color.BLACK : p.color);
}
/**
* Set p's color to c, if p isn't <code>null</code>.
*
* @param p The entry to set color for.
* @param c The color to set.
*/
protected static <K, V> void setColor(RedBlackTree<K, V>.Entry p, Color c)
{
if (p != null)
p.color = c;
}
/**
* Return the left child of p, or <code>null</code> if p is <code>null</code>.
*
* @param p The entry to get left child of.
* @return The left child of p, or <code>null</code> if p is <code>null</code>.
*/
protected static <K, V> RedBlackTree<K, V>.Entry leftOf(RedBlackTree<K, V>.Entry p)
{
return (p == null) ? null : p.left;
}
/**
* Return the right child of p, or <code>null</code> if p is <code>null</code>.
*
* @param p The entry to get right child of.
* @return The right child of p, or <code>null</code> if p is <code>null</code>.
*/
protected static <K, V> RedBlackTree<K, V>.Entry rightOf(RedBlackTree<K, V>.Entry p)
{
return (p == null) ? null : p.right;
}
/**
* Save the state of the tree's instance to a stream.
*
* @param s The stream to write in.
*
* @serialData The <i>size</i> of the RedBlackTree (the number of key-value mappings) is emitted (int), followed by
* the key (Object) and value (Object) for each key-value mapping represented by the RedBlackTree. The
* key-value mappings are emitted in key-order.
*/
private void writeObject(ObjectOutputStream s) throws IOException
{
// Write out the Comparator and any hidden stuff
s.defaultWriteObject();
// Write out size (number of Mappings)
s.writeInt(size);
// Write out keys and values (alternating)
for (Iterator<Map.Entry<K, V>> i = entrySet().iterator(); i.hasNext();) {
Map.Entry<K, V> e = i.next();
s.writeObject(e.getKey());
s.writeObject(e.getValue());
}
}
/**
* Reconstitute the tree's instance from a stream.
*
* @param s The stream to read from.
*/
@SuppressWarnings("unchecked")
private void readObject(final ObjectInputStream s) throws IOException, ClassNotFoundException
{
// Read in the Comparator and any hidden stuff
s.defaultReadObject();
// Read in size
int size = s.readInt();
List<RedBlackTree<K, V>.Entry> data = new LinkedList<RedBlackTree<K, V>.Entry>();
for (int i = 0; i < size; i++) {
K key = (K) s.readObject();
V value = (V) s.readObject();
data.add(new Entry(key, value));
}
buildFromSorted(size, data.iterator());
}
/**
* @return The default comparator to be used if no other comparator is provided.
*/
protected Comparator<? super K> getDefaultComparator()
{
return new Comparator<K>() {
@SuppressWarnings("unchecked")
@Override
public int compare(K o1, K o2) throws ClassCastException
{
Comparable<K> o1c = (Comparable<K>) o1;
return o1c.compareTo(o2);
}
};
}
/**
* A path to a tree's entry, the very first element is the tree's root.
*
* @author Martin Pecka
*/
protected class TreePath extends LinkedList<Entry>
{
/** */
private static final long serialVersionUID = -5735382496269541155L;
/**
* Returns true if this path ends with an entry with the given key.
*
* @param key The key to check.
* @return true if this path ends with an entry with the given key.
*/
public boolean endsWithKey(K key)
{
if (size() == 0)
return false;
K k = getLast().key;
return (key == null ? k == null : key.equals(k));
}
/**
* Return the index-th last entry from the path. Indexed from 0. If it doesn't exist, return <code>null</code>.
*
* @param index The index from the end of the path.
* @return The index-th last entry from the path. Indexed from 0. If it doesn't exist, return <code>null</code>.
*/
public Entry getLast(int index)
{
int i = size() - index - 1;
if (i < 0)
return null;
return get(i);
}
/**
* Make this path lead to it's current last entry's successor. Empty the path if the current last entry is the
* last entry in the tree.
*
* @return The successor, or <code>null</code> if it doesn't exist.
*/
protected Entry moveToSuccesor()
{
if (size() == 0)
return null;
if (getLast().right != null) {
addLast(getLast().right);
while (getLast().left != null) {
addLast(getLast().left);
}
} else {
while (size() > 0 && getLast(1) != null && getLast() == getLast(1).right) {
removeLast();
}
removeLast();
}
return getLast(0);
}
/**
* Make this path lead to it's current last entry's predecessor. Empty the path if the current last entry is the
* first entry in the tree.
*
* @return The predecessor, or <code>null</code> if it doesn't exist.
*/
protected Entry moveToPredecessor()
{
if (size() == 0)
return null;
if (getLast().left != null) {
addLast(getLast().left);
while (getLast().right != null) {
addLast(getLast().right);
}
} else {
while (size() > 0 && getLast(1) != null && getLast() == getLast(1).left) {
removeLast();
}
removeLast();
}
return getLast(0);
}
/**
* Rotate left the last path's entry and repair the path so that it is the new path to its previous last entry.
*/
public void rotateLeft()
{
if (size() > 0) {
Entry p = getLast(), q = p.right;
p.right = q.left;
// substitute p with q in the path
removeLast();
addLast(q);
if (size() == 1)
root = q;
else if (getLast(1).left == p)
getLast(1).left = q;
else
getLast(1).right = q;
q.left = p;
addLast(p);
}
}
/**
* Rotate right the last path's entry and repair the path so that it is the new path to its previous last entry.
*/
public void rotateRight()
{
if (size() > 0) {
Entry p = getLast(), q = p.left;
p.left = q.right;
// substitute p with q in the path
removeLast();
addLast(q);
if (size() == 1)
root = q;
else if (getLast(1).left == p)
getLast(1).left = q;
else
getLast(1).right = q;
q.right = p;
addLast(p);
}
}
}
/**
* Entry in the Tree.
*/
protected class Entry implements Map.Entry<K, V>
{
K key;
V value;
Entry left = null;
Entry right = null;
Color color = Color.BLACK;
/**
* Make a new entry with given key and value, and with <tt>null</tt> child links, and BLACK color.
*/
Entry(K key, V value)
{
this.key = key;
this.value = value;
}
@Override
public K getKey()
{
return key;
}
@Override
public V getValue()
{
return value;
}
@Override
public V setValue(V value)
{
V oldValue = this.value;
this.value = value;
return oldValue;
}
@Override
public boolean equals(Object o)
{
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?, ?> e = (Map.Entry<?, ?>) o;
return valEquals(key, e.getKey()) && valEquals(value, e.getValue());
}
@Override
public int hashCode()
{
int keyHash = (key == null ? 0 : key.hashCode());
int valueHash = (value == null ? 0 : value.hashCode());
return keyHash ^ valueHash;
}
@Override
public String toString()
{
return key + "=" + value;
}
}
}
| true | true | protected void repairTreeAfterDeletion(RedBlackTree<K, V>.TreePath path)
{
boolean setColor = false;
Entry toDelete = path.getLast();
while (path.size() > 1 && colorOf(path.getLast()) == Color.BLACK) {
if (path.getLast() == leftOf(path.getLast(1))) {
Entry sib = rightOf(path.getLast(1));
if (colorOf(sib) == Color.RED) {
setColor(sib, Color.BLACK);
setColor(path.getLast(1), Color.RED);
Entry p = path.removeLast();
path.rotateLeft(); // p still remains the left child of its original parent
path.addLast(p);
sib = rightOf(path.getLast(1));
}
if (colorOf(leftOf(sib)) == Color.BLACK && colorOf(rightOf(sib)) == Color.BLACK) {
setColor(sib, Color.RED);
path.removeLast();
setColor = true;
} else {
if (colorOf(rightOf(sib)) == Color.BLACK) {
setColor(leftOf(sib), Color.BLACK);
setColor(sib, Color.RED);
Entry p = path.removeLast();
path.addLast(sib);
path.rotateRight(); // rotate p's sibling
path.removeLast(); // and let path lead to p again
path.removeLast();
path.addLast(p);
sib = rightOf(path.getLast(1));
}
setColor(sib, colorOf(path.getLast(1)));
setColor(path.getLast(1), Color.BLACK);
setColor(rightOf(sib), Color.BLACK);
path.removeLast();
path.rotateLeft();
setColor(root, Color.BLACK);
setColor = false;
break;
}
} else { // symmetric
Entry sib = leftOf(path.getLast(1));
if (colorOf(sib) == Color.RED) {
setColor(sib, Color.BLACK);
setColor(path.getLast(1), Color.RED);
Entry p = path.removeLast();
path.rotateRight();
path.addLast(p); // p still remains the left child of its original parent
sib = leftOf(path.getLast(1));
}
if (colorOf(rightOf(sib)) == Color.BLACK && colorOf(leftOf(sib)) == Color.BLACK) {
setColor(sib, Color.RED);
path.removeLast();
setColor = true;
} else {
if (colorOf(leftOf(sib)) == Color.BLACK) {
setColor(rightOf(sib), Color.BLACK);
setColor(sib, Color.RED);
Entry p = path.removeLast();
path.addLast(sib);
path.rotateLeft(); // rotate p's sibling
path.removeLast(); // and let path lead to p again
path.removeLast();
path.addLast(p);
sib = leftOf(path.getLast(1));
}
setColor(sib, colorOf(path.getLast(1)));
setColor(path.getLast(1), Color.BLACK);
setColor(leftOf(sib), Color.BLACK);
path.removeLast();
path.rotateRight();
setColor(root, Color.BLACK);
setColor = false;
break;
}
}
}
if (setColor)
setColor(path.getLast(), Color.BLACK);
// return to the initial endpoint
boolean goHigher = comparator.compare(toDelete.getKey(), path.getLast().getKey()) >= 0;
while (!path.endsWithKey(toDelete.getKey())) {
if (goHigher)
path.moveToSuccesor();
else
path.moveToPredecessor();
}
}
| protected void repairTreeAfterDeletion(RedBlackTree<K, V>.TreePath path)
{
boolean setColor = false;
Entry toDelete = path.getLast();
while (path.size() > 1 && colorOf(path.getLast()) == Color.BLACK) {
if (path.getLast() == leftOf(path.getLast(1))) {
Entry sib = rightOf(path.getLast(1));
if (colorOf(sib) == Color.RED) {
setColor(sib, Color.BLACK);
setColor(path.getLast(1), Color.RED);
Entry p = path.removeLast();
path.rotateLeft(); // p still remains the left child of its original parent
path.addLast(p);
sib = rightOf(path.getLast(1));
}
if (colorOf(leftOf(sib)) == Color.BLACK && colorOf(rightOf(sib)) == Color.BLACK) {
setColor(sib, Color.RED);
path.removeLast();
setColor = true;
} else {
if (colorOf(rightOf(sib)) == Color.BLACK) {
setColor(leftOf(sib), Color.BLACK);
setColor(sib, Color.RED);
Entry p = path.removeLast();
path.addLast(sib);
path.rotateRight(); // rotate p's sibling
path.removeLast(); // and let path lead to p again
path.removeLast();
path.addLast(p);
sib = rightOf(path.getLast(1));
}
setColor(sib, colorOf(path.getLast(1)));
setColor(path.getLast(1), Color.BLACK);
setColor(rightOf(sib), Color.BLACK);
path.removeLast();
path.rotateLeft();
setColor(root, Color.BLACK);
setColor = false;
break;
}
} else { // symmetric
Entry sib = leftOf(path.getLast(1));
if (colorOf(sib) == Color.RED) {
setColor(sib, Color.BLACK);
setColor(path.getLast(1), Color.RED);
Entry p = path.removeLast();
path.rotateRight();
path.addLast(p); // p still remains the left child of its original parent
sib = leftOf(path.getLast(1));
}
if (colorOf(rightOf(sib)) == Color.BLACK && colorOf(leftOf(sib)) == Color.BLACK) {
setColor(sib, Color.RED);
path.removeLast();
setColor = true;
} else {
if (colorOf(leftOf(sib)) == Color.BLACK) {
setColor(rightOf(sib), Color.BLACK);
setColor(sib, Color.RED);
Entry p = path.removeLast();
path.addLast(sib);
path.rotateLeft(); // rotate p's sibling
path.removeLast(); // and let path lead to p again
path.removeLast();
path.addLast(p);
sib = leftOf(path.getLast(1));
}
setColor(sib, colorOf(path.getLast(1)));
setColor(path.getLast(1), Color.BLACK);
setColor(leftOf(sib), Color.BLACK);
path.removeLast();
path.rotateRight();
setColor(root, Color.BLACK);
setColor = false;
break;
}
}
}
if (setColor)
setColor(path.getLast(), Color.BLACK);
// return to the initial endpoint
boolean goHigher = comparator.compare(toDelete.getKey(), path.getLast().getKey()) >= 0;
while (path.size() > 0 && !path.endsWithKey(toDelete.getKey())) {
if (goHigher)
path.moveToSuccesor();
else
path.moveToPredecessor();
}
}
|
diff --git a/src/com/github/groupENIGMA/journalEgocentrique/MainActivity.java b/src/com/github/groupENIGMA/journalEgocentrique/MainActivity.java
index f007d5b..c0b7479 100644
--- a/src/com/github/groupENIGMA/journalEgocentrique/MainActivity.java
+++ b/src/com/github/groupENIGMA/journalEgocentrique/MainActivity.java
@@ -1,309 +1,311 @@
package com.github.groupENIGMA.journalEgocentrique;
import java.util.Calendar;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.*;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import com.github.groupENIGMA.journalEgocentrique.model.DB;
import com.github.groupENIGMA.journalEgocentrique.model.Day;
import com.github.groupENIGMA.journalEgocentrique.model.Entry;
import com.github.groupENIGMA.journalEgocentrique.model.Photo;
public class MainActivity extends Activity {
public final static String EXTRA_WRITE_NOTE_NoteId = "NoteId";
public final static String EXTRA_WRITE_NOTE_DayId = "EntryId";
public final static String EXTRA_PHOTO_ACTIVITY_DayId = "DayId";
private final static String PREF_SELECTED_ENTRY = "selectedEntry_id";
private DB dataBase;
private DaysArrayAdapter daysListArrayAdapter;
private Day selectedDay = null;
private SharedPreferences sharedPreferences;
// Views for the Detail Section of the UI
ListView entryListView;
ImageView dailyPhotoHeader;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dataBase = new DB(getApplicationContext());
// Open the shared preferences file
sharedPreferences = getSharedPreferences(
AppConstants.SHARED_PREFERENCES_FILENAME,
MODE_PRIVATE
);
// Open database connection
dataBase.open();
// Display the list of days with an Entry
displayMasterLayout();
// Prepare the Detail Layout
prepareDetailLayout();
// Display the last viewed Day (if any)
SharedPreferences pref = getPreferences(MODE_PRIVATE);
long id = pref.getLong(PREF_SELECTED_ENTRY, -1L);
if(id != -1) {
selectedDay = dataBase.getDay(id);
displayDetailLayout();
}
else {
selectedDay = null;
}
// If the Entry for today already exists disable the AddEntry button
if (dataBase.existsDay()) {
Button addEntry = (Button)findViewById(R.id.ListDaysAddEntryButton);
addEntry.setEnabled(false);
}
}
@Override
protected void onResume() {
super.onResume();
// Database connection must be reopened if the app was previously
// "paused" with onPause()
if (!dataBase.isOpen()) {
dataBase.open();
}
displayDetailLayout();
}
/**
* Display the "Master" section of the UI (the list of Days)
*/
private void displayMasterLayout() {
// Get the ListView that display the days
ListView daysListView = (ListView)findViewById(R.id.daysList);
// Get the list of available days from the database
List<Calendar> daysList = dataBase.getDatesList();
// Create and set the custom ArrayAdapter DaysArrayAdapter
daysListArrayAdapter = new DaysArrayAdapter(
this, R.layout.row, daysList
);
daysListView.setAdapter(daysListArrayAdapter);
// Set the listener
OnItemClickListener clickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id) {
selectedDay = dataBase.getDay(
(Calendar) adapter.getItemAtPosition(position)
);
// Display the Detail of the selected day
displayDetailLayout();
}
};
daysListView.setOnItemClickListener(clickListener);
}
/**
* Prepare the "Detail" section of the UI (Daily photo + Entry)
*
* This is in a separate method from displayDetailLayout because
* addHeaderView can be called only once per ListView
*/
private void prepareDetailLayout() {
// Get the ListView
entryListView = (ListView) findViewById(R.id.EntryList);
// Get the View with the daily Photo
LayoutInflater inflater = LayoutInflater.from(this);
dailyPhotoHeader = (ImageView) inflater
.inflate(R.layout.main_detail_photo_header, null, false);
// Add the header with the DailyPhoto to the detailView
entryListView.addHeaderView(dailyPhotoHeader);
}
/**
* Display the "Detail" section of the UI (Daily photo + Entry)
*/
private void displayDetailLayout() {
// The Detail section will be displayed only when there's a Day selected
if (selectedDay != null) {
// Get the list of Entry for the selectedDay
List<Entry> entries = selectedDay.getEntries();
// Prepare the custom ArrayAdapter
EntryAdapter entryAdapter = new EntryAdapter(
this, R.layout.main_row_entry, entries
);
// If available, display the Photo in the header
Photo dailyPhoto = selectedDay.getPhoto();
if (dailyPhoto != null) {
String photoPath = dailyPhoto.getPathThumb();
dailyPhotoHeader.setImageURI(Uri.parse(photoPath));
}
+ else
+ dailyPhotoHeader.setImageResource(R.drawable.ic_launcher);
// If the selected Day can be updated add the listener that starts
// the PhotoActivity (to take a new Photo)
if (selectedDay.canBeUpdated()) {
dailyPhotoHeader.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
// Start the PhotoActivity
Intent intent = new Intent(
getApplicationContext(),
PhotoActivity.class
);
intent.putExtra(
EXTRA_PHOTO_ACTIVITY_DayId,
selectedDay.getId()
);
startActivity(intent);
return false;
}
});
}
// The Photo can't be updated
else {
// TODO
// A Toast saying something like: "You can't change this photo"
// or something similar
// Remove this when the Toast is ready
dailyPhotoHeader.setOnTouchListener(null);
}
// Set the custom ArrayAdapter to the detailView
entryListView.setAdapter(entryAdapter);
// Add the onLongClickListener that activates the WriteNote activity
// that can be used to update the Entry text
OnItemClickListener clickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id) {
// Enable the onLongClickListener only if the Entry can be
// updated.
Entry selectedEntry = (Entry) adapter
.getItemAtPosition(position);
if (selectedEntry.canBeUpdated(sharedPreferences)) {
Intent intent = new Intent(
getApplicationContext(), WriteNote.class
);
intent.putExtra(
EXTRA_WRITE_NOTE_NoteId, selectedEntry.getId()
);
startActivity(intent);
}
// The Entry can't be updated
else {
// TODO display a Toast with the error
}
}
};
entryListView.setOnItemClickListener(clickListener);
}
}
@Override
protected void onPause(){
super.onPause();
// Get the preference file
SharedPreferences pref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor edit = pref.edit();
// Save selected Day (if any)
if (selectedDay == null) {
edit.putLong(PREF_SELECTED_ENTRY, -1L);
}
else {
edit.putLong(PREF_SELECTED_ENTRY, selectedDay.getId());
}
edit.commit();
// Close database connection
dataBase.close();
}
/**
* Adds an Entry for today to the database and to the displayed list.
* Used by ListDaysAddEntryButton in main.xml
*
* @param view as required by android:onClick xml attribute. Not used.
*/
public void addTodayEntry(View view) {
// New Entry in the database
selectedDay = dataBase.createDay();
// Entry to the beginning of the displayed list
daysListArrayAdapter.insert(selectedDay.getDate(), 0);
// Disable the ListDaysAddEntryButton
Button addEntry = (Button)findViewById(R.id.ListDaysAddEntryButton);
addEntry.setEnabled(false);
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.newNote:
Intent intent = new Intent(
getApplicationContext(), WriteNote.class
);
intent.putExtra(EXTRA_WRITE_NOTE_NoteId, -1L);
intent.putExtra(EXTRA_WRITE_NOTE_DayId, selectedDay.getId());
startActivity(intent);
return true;
case R.id.settings:
Intent settings = new Intent(getApplicationContext(), Settings.class);
startActivity(settings);
return true;
case R.id.deleteEntry:
if(selectedDay != null){
dataBase.deleteDay(selectedDay);
selectedDay = null;
return true;
}
case R.id.gallery:
Intent gallery = new Intent(getApplicationContext(), GalleryActivity.class);
startActivity(gallery);
return true;
case R.id.share:
Intent share = new Intent(getApplicationContext(), ShareActivity.class);
share.putExtra("EntryId", selectedDay.getId());
startActivity(share);
return true;
}
return false;
}
}
| true | true | private void displayDetailLayout() {
// The Detail section will be displayed only when there's a Day selected
if (selectedDay != null) {
// Get the list of Entry for the selectedDay
List<Entry> entries = selectedDay.getEntries();
// Prepare the custom ArrayAdapter
EntryAdapter entryAdapter = new EntryAdapter(
this, R.layout.main_row_entry, entries
);
// If available, display the Photo in the header
Photo dailyPhoto = selectedDay.getPhoto();
if (dailyPhoto != null) {
String photoPath = dailyPhoto.getPathThumb();
dailyPhotoHeader.setImageURI(Uri.parse(photoPath));
}
// If the selected Day can be updated add the listener that starts
// the PhotoActivity (to take a new Photo)
if (selectedDay.canBeUpdated()) {
dailyPhotoHeader.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
// Start the PhotoActivity
Intent intent = new Intent(
getApplicationContext(),
PhotoActivity.class
);
intent.putExtra(
EXTRA_PHOTO_ACTIVITY_DayId,
selectedDay.getId()
);
startActivity(intent);
return false;
}
});
}
// The Photo can't be updated
else {
// TODO
// A Toast saying something like: "You can't change this photo"
// or something similar
// Remove this when the Toast is ready
dailyPhotoHeader.setOnTouchListener(null);
}
// Set the custom ArrayAdapter to the detailView
entryListView.setAdapter(entryAdapter);
// Add the onLongClickListener that activates the WriteNote activity
// that can be used to update the Entry text
OnItemClickListener clickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id) {
// Enable the onLongClickListener only if the Entry can be
// updated.
Entry selectedEntry = (Entry) adapter
.getItemAtPosition(position);
if (selectedEntry.canBeUpdated(sharedPreferences)) {
Intent intent = new Intent(
getApplicationContext(), WriteNote.class
);
intent.putExtra(
EXTRA_WRITE_NOTE_NoteId, selectedEntry.getId()
);
startActivity(intent);
}
// The Entry can't be updated
else {
// TODO display a Toast with the error
}
}
};
entryListView.setOnItemClickListener(clickListener);
}
}
| private void displayDetailLayout() {
// The Detail section will be displayed only when there's a Day selected
if (selectedDay != null) {
// Get the list of Entry for the selectedDay
List<Entry> entries = selectedDay.getEntries();
// Prepare the custom ArrayAdapter
EntryAdapter entryAdapter = new EntryAdapter(
this, R.layout.main_row_entry, entries
);
// If available, display the Photo in the header
Photo dailyPhoto = selectedDay.getPhoto();
if (dailyPhoto != null) {
String photoPath = dailyPhoto.getPathThumb();
dailyPhotoHeader.setImageURI(Uri.parse(photoPath));
}
else
dailyPhotoHeader.setImageResource(R.drawable.ic_launcher);
// If the selected Day can be updated add the listener that starts
// the PhotoActivity (to take a new Photo)
if (selectedDay.canBeUpdated()) {
dailyPhotoHeader.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
// Start the PhotoActivity
Intent intent = new Intent(
getApplicationContext(),
PhotoActivity.class
);
intent.putExtra(
EXTRA_PHOTO_ACTIVITY_DayId,
selectedDay.getId()
);
startActivity(intent);
return false;
}
});
}
// The Photo can't be updated
else {
// TODO
// A Toast saying something like: "You can't change this photo"
// or something similar
// Remove this when the Toast is ready
dailyPhotoHeader.setOnTouchListener(null);
}
// Set the custom ArrayAdapter to the detailView
entryListView.setAdapter(entryAdapter);
// Add the onLongClickListener that activates the WriteNote activity
// that can be used to update the Entry text
OnItemClickListener clickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id) {
// Enable the onLongClickListener only if the Entry can be
// updated.
Entry selectedEntry = (Entry) adapter
.getItemAtPosition(position);
if (selectedEntry.canBeUpdated(sharedPreferences)) {
Intent intent = new Intent(
getApplicationContext(), WriteNote.class
);
intent.putExtra(
EXTRA_WRITE_NOTE_NoteId, selectedEntry.getId()
);
startActivity(intent);
}
// The Entry can't be updated
else {
// TODO display a Toast with the error
}
}
};
entryListView.setOnItemClickListener(clickListener);
}
}
|
diff --git a/ebms-as4/src/main/java/org/jentrata/ebms/as4/internal/routes/EbmsOutboundRouteBuilder.java b/ebms-as4/src/main/java/org/jentrata/ebms/as4/internal/routes/EbmsOutboundRouteBuilder.java
index 34a1e0b..e417af8 100644
--- a/ebms-as4/src/main/java/org/jentrata/ebms/as4/internal/routes/EbmsOutboundRouteBuilder.java
+++ b/ebms-as4/src/main/java/org/jentrata/ebms/as4/internal/routes/EbmsOutboundRouteBuilder.java
@@ -1,174 +1,175 @@
package org.jentrata.ebms.as4.internal.routes;
import org.apache.camel.Exchange;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import org.jentrata.ebms.EbmsConstants;
import org.jentrata.ebms.MessageStatusType;
import org.jentrata.ebms.cpa.CPARepository;
import org.jentrata.ebms.cpa.PartnerAgreement;
import org.jentrata.ebms.messaging.MessageStore;
import java.io.IOException;
import java.net.ConnectException;
/**
* Setups and outbound route per trading partner
*
* @author aaronwalker
*/
public class EbmsOutboundRouteBuilder extends RouteBuilder {
private String outboundEbmsQueue = "activemq:queue:jentrata_internal_ebms_outbound";
private String ebmsResponseInbound = "activemq:queue:jentrata_internal_ebms_response";
private String messageUpdateEndpoint = MessageStore.DEFAULT_MESSAGE_UPDATE_ENDPOINT;
private CPARepository cpaRepository;
private String httpProxyHost = null;
private String httpProxyPort = null;
private String httpClientOverride = null;
@Override
public void configure() throws Exception {
from(outboundEbmsQueue)
.removeHeaders("Camel*")
.removeHeaders("JMS*")
.setHeader(EbmsConstants.MESSAGE_STATUS, constant(MessageStatusType.DELIVER))
.setHeader(EbmsConstants.MESSAGE_STATUS_DESCRIPTION, constant(null))
.to(messageUpdateEndpoint)
.recipientList(simple("direct:outbox_${headers.JentrataCPAId}"))
.routeId("_jentrataEbmsOutbound");
for(PartnerAgreement agreement : cpaRepository.getActivePartnerAgreements()) {
from("direct:outbox_" + agreement.getCpaId())
.log(LoggingLevel.INFO,"Delivering message to cpaId:${headers.JentrataCPAId} - type:${headers.JentrataMessageType} - msgId:${headers.JentrataMessageId}")
.onException(Exception.class)
.handled(true)
.log(LoggingLevel.WARN,"Failed to send cpaId:${headers.JentrataCPAId} - type:${headers.JentrataMessageType} - msgId:${headers.JentrataMessgeId}: ${exception.message}")
.to("direct:processFailure")
.end()
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.to(configureEndpoint(agreement.getProtocol().getAddress()))
.convertBodyTo(String.class)
.choice()
.when(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(200))
.to("direct:processSuccess")
.setProperty(EbmsConstants.CPA_ID,header(EbmsConstants.CPA_ID))
+ .setProperty(EbmsConstants.CONTENT_TYPE,header(Exchange.CONTENT_TYPE))
.removeHeaders("*")
- .setHeader(EbmsConstants.CONTENT_TYPE,constant(EbmsConstants.SOAP_XML_CONTENT_TYPE))
+ .setHeader(EbmsConstants.CONTENT_TYPE,property(EbmsConstants.CONTENT_TYPE))
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.setHeader(EbmsConstants.CPA_ID,property(EbmsConstants.CPA_ID))
.inOnly(ebmsResponseInbound)
.when(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(204))
.to("direct:processSuccess")
.otherwise()
.to("direct:processFailure")
.routeId("_jentrataEbmsOutbound" + agreement.getCpaId());
}
from("direct:processSuccess")
.log(LoggingLevel.INFO,"Successfully delivered cpaId:${headers.JentrataCPAId} - type:${headers.JentrataMessageType} - msgId:${headers.JentrataMessageId} - responseCode:${headers.CamelHttpResponseCode}")
- .log(LoggingLevel.DEBUG, "responseCode:${headers.CamelHttpResponseCode}\n${body}")
+ .log(LoggingLevel.DEBUG, "responseCode:${headers.CamelHttpResponseCode}\nheaders:${headers}\n${body}")
.setHeader(EbmsConstants.MESSAGE_STATUS, constant(MessageStatusType.DELIVERED))
.setHeader(EbmsConstants.MESSAGE_STATUS_DESCRIPTION, constant(null))
.to(messageUpdateEndpoint)
.wireTap(EventNotificationRouteBuilder.SEND_NOTIFICATION_ENDPOINT)
.routeId("_jentrataEbmsOutboundSuccess");
from("direct:processFailure")
.log(LoggingLevel.ERROR, "Failed to deliver cpaId:${headers.JentrataCPAId} - type:${headers.JentrataMessageType} - msgId:${headers.JentrataMessgeId} - responseCode:${headers.CamelHttpResponseCode}")
- .log(LoggingLevel.DEBUG,"responseCode:${headers.CamelHttpResponseCode}\n${body}")
+ .log(LoggingLevel.DEBUG, "responseCode:${headers.CamelHttpResponseCode}\nheaders:${headers}\n${body}")
.setHeader(EbmsConstants.MESSAGE_STATUS, constant(MessageStatusType.FAILED))
.setHeader(EbmsConstants.MESSAGE_STATUS_DESCRIPTION, simple("${headers.CamelHttpResponseCode} - ${body}"))
.to(messageUpdateEndpoint)
.wireTap(EventNotificationRouteBuilder.SEND_NOTIFICATION_ENDPOINT)
.routeId("_jentrataEbmsOutboundFailure");
}
public String getOutboundEbmsQueue() {
return outboundEbmsQueue;
}
public void setOutboundEbmsQueue(String outboundEbmsQueue) {
this.outboundEbmsQueue = outboundEbmsQueue;
}
public String getEbmsResponseInbound() {
return ebmsResponseInbound;
}
public void setEbmsResponseInbound(String ebmsResponseInbound) {
this.ebmsResponseInbound = ebmsResponseInbound;
}
public String getMessageUpdateEndpoint() {
return messageUpdateEndpoint;
}
public void setMessageUpdateEndpoint(String messageUpdateEndpoint) {
this.messageUpdateEndpoint = messageUpdateEndpoint;
}
public CPARepository getCpaRepository() {
return cpaRepository;
}
public void setCpaRepository(CPARepository cpaRepository) {
this.cpaRepository = cpaRepository;
}
public String getHttpProxyHost() {
return httpProxyHost;
}
public void setHttpProxyHost(String httpProxyHost) {
this.httpProxyHost = httpProxyHost;
}
public String getHttpProxyPort() {
return httpProxyPort;
}
public void setHttpProxyPort(String httpProxyPort) {
this.httpProxyPort = httpProxyPort;
}
public String getHttpClientOverride() {
return httpClientOverride;
}
public void setHttpClientOverride(String httpClientOverride) {
this.httpClientOverride = httpClientOverride;
}
private String configureEndpoint(String endpoint) {
if(endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
return endpoint + configureOptions(endpoint);
} else {
return endpoint;
}
}
protected String configureOptions(String endpoint) {
StringBuilder options = new StringBuilder();
if(endpoint.contains("?")) {
options.append("&");
} else {
options.append("?");
}
options.append("throwExceptionOnFailure=false");
if(isNotEmpty(httpClientOverride)) {
options.append("&" + httpClientOverride);
} else {
if(isNotEmpty(httpProxyHost) && isNotEmpty(httpProxyPort)) {
options.append("&proxyHost=" + httpProxyHost);
options.append("&proxyPort=" + httpProxyPort);
}
}
return options.toString();
}
private static boolean isNotEmpty(String s) {
return s != null && s.length() > 0;
}
}
| false | true | public void configure() throws Exception {
from(outboundEbmsQueue)
.removeHeaders("Camel*")
.removeHeaders("JMS*")
.setHeader(EbmsConstants.MESSAGE_STATUS, constant(MessageStatusType.DELIVER))
.setHeader(EbmsConstants.MESSAGE_STATUS_DESCRIPTION, constant(null))
.to(messageUpdateEndpoint)
.recipientList(simple("direct:outbox_${headers.JentrataCPAId}"))
.routeId("_jentrataEbmsOutbound");
for(PartnerAgreement agreement : cpaRepository.getActivePartnerAgreements()) {
from("direct:outbox_" + agreement.getCpaId())
.log(LoggingLevel.INFO,"Delivering message to cpaId:${headers.JentrataCPAId} - type:${headers.JentrataMessageType} - msgId:${headers.JentrataMessageId}")
.onException(Exception.class)
.handled(true)
.log(LoggingLevel.WARN,"Failed to send cpaId:${headers.JentrataCPAId} - type:${headers.JentrataMessageType} - msgId:${headers.JentrataMessgeId}: ${exception.message}")
.to("direct:processFailure")
.end()
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.to(configureEndpoint(agreement.getProtocol().getAddress()))
.convertBodyTo(String.class)
.choice()
.when(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(200))
.to("direct:processSuccess")
.setProperty(EbmsConstants.CPA_ID,header(EbmsConstants.CPA_ID))
.removeHeaders("*")
.setHeader(EbmsConstants.CONTENT_TYPE,constant(EbmsConstants.SOAP_XML_CONTENT_TYPE))
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.setHeader(EbmsConstants.CPA_ID,property(EbmsConstants.CPA_ID))
.inOnly(ebmsResponseInbound)
.when(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(204))
.to("direct:processSuccess")
.otherwise()
.to("direct:processFailure")
.routeId("_jentrataEbmsOutbound" + agreement.getCpaId());
}
from("direct:processSuccess")
.log(LoggingLevel.INFO,"Successfully delivered cpaId:${headers.JentrataCPAId} - type:${headers.JentrataMessageType} - msgId:${headers.JentrataMessageId} - responseCode:${headers.CamelHttpResponseCode}")
.log(LoggingLevel.DEBUG, "responseCode:${headers.CamelHttpResponseCode}\n${body}")
.setHeader(EbmsConstants.MESSAGE_STATUS, constant(MessageStatusType.DELIVERED))
.setHeader(EbmsConstants.MESSAGE_STATUS_DESCRIPTION, constant(null))
.to(messageUpdateEndpoint)
.wireTap(EventNotificationRouteBuilder.SEND_NOTIFICATION_ENDPOINT)
.routeId("_jentrataEbmsOutboundSuccess");
from("direct:processFailure")
.log(LoggingLevel.ERROR, "Failed to deliver cpaId:${headers.JentrataCPAId} - type:${headers.JentrataMessageType} - msgId:${headers.JentrataMessgeId} - responseCode:${headers.CamelHttpResponseCode}")
.log(LoggingLevel.DEBUG,"responseCode:${headers.CamelHttpResponseCode}\n${body}")
.setHeader(EbmsConstants.MESSAGE_STATUS, constant(MessageStatusType.FAILED))
.setHeader(EbmsConstants.MESSAGE_STATUS_DESCRIPTION, simple("${headers.CamelHttpResponseCode} - ${body}"))
.to(messageUpdateEndpoint)
.wireTap(EventNotificationRouteBuilder.SEND_NOTIFICATION_ENDPOINT)
.routeId("_jentrataEbmsOutboundFailure");
}
| public void configure() throws Exception {
from(outboundEbmsQueue)
.removeHeaders("Camel*")
.removeHeaders("JMS*")
.setHeader(EbmsConstants.MESSAGE_STATUS, constant(MessageStatusType.DELIVER))
.setHeader(EbmsConstants.MESSAGE_STATUS_DESCRIPTION, constant(null))
.to(messageUpdateEndpoint)
.recipientList(simple("direct:outbox_${headers.JentrataCPAId}"))
.routeId("_jentrataEbmsOutbound");
for(PartnerAgreement agreement : cpaRepository.getActivePartnerAgreements()) {
from("direct:outbox_" + agreement.getCpaId())
.log(LoggingLevel.INFO,"Delivering message to cpaId:${headers.JentrataCPAId} - type:${headers.JentrataMessageType} - msgId:${headers.JentrataMessageId}")
.onException(Exception.class)
.handled(true)
.log(LoggingLevel.WARN,"Failed to send cpaId:${headers.JentrataCPAId} - type:${headers.JentrataMessageType} - msgId:${headers.JentrataMessgeId}: ${exception.message}")
.to("direct:processFailure")
.end()
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.to(configureEndpoint(agreement.getProtocol().getAddress()))
.convertBodyTo(String.class)
.choice()
.when(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(200))
.to("direct:processSuccess")
.setProperty(EbmsConstants.CPA_ID,header(EbmsConstants.CPA_ID))
.setProperty(EbmsConstants.CONTENT_TYPE,header(Exchange.CONTENT_TYPE))
.removeHeaders("*")
.setHeader(EbmsConstants.CONTENT_TYPE,property(EbmsConstants.CONTENT_TYPE))
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.setHeader(EbmsConstants.CPA_ID,property(EbmsConstants.CPA_ID))
.inOnly(ebmsResponseInbound)
.when(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(204))
.to("direct:processSuccess")
.otherwise()
.to("direct:processFailure")
.routeId("_jentrataEbmsOutbound" + agreement.getCpaId());
}
from("direct:processSuccess")
.log(LoggingLevel.INFO,"Successfully delivered cpaId:${headers.JentrataCPAId} - type:${headers.JentrataMessageType} - msgId:${headers.JentrataMessageId} - responseCode:${headers.CamelHttpResponseCode}")
.log(LoggingLevel.DEBUG, "responseCode:${headers.CamelHttpResponseCode}\nheaders:${headers}\n${body}")
.setHeader(EbmsConstants.MESSAGE_STATUS, constant(MessageStatusType.DELIVERED))
.setHeader(EbmsConstants.MESSAGE_STATUS_DESCRIPTION, constant(null))
.to(messageUpdateEndpoint)
.wireTap(EventNotificationRouteBuilder.SEND_NOTIFICATION_ENDPOINT)
.routeId("_jentrataEbmsOutboundSuccess");
from("direct:processFailure")
.log(LoggingLevel.ERROR, "Failed to deliver cpaId:${headers.JentrataCPAId} - type:${headers.JentrataMessageType} - msgId:${headers.JentrataMessgeId} - responseCode:${headers.CamelHttpResponseCode}")
.log(LoggingLevel.DEBUG, "responseCode:${headers.CamelHttpResponseCode}\nheaders:${headers}\n${body}")
.setHeader(EbmsConstants.MESSAGE_STATUS, constant(MessageStatusType.FAILED))
.setHeader(EbmsConstants.MESSAGE_STATUS_DESCRIPTION, simple("${headers.CamelHttpResponseCode} - ${body}"))
.to(messageUpdateEndpoint)
.wireTap(EventNotificationRouteBuilder.SEND_NOTIFICATION_ENDPOINT)
.routeId("_jentrataEbmsOutboundFailure");
}
|
diff --git a/stage/src/main/java/org/jboss/test/faces/staging/StaticServlet.java b/stage/src/main/java/org/jboss/test/faces/staging/StaticServlet.java
index 95775d3..d464cfc 100644
--- a/stage/src/main/java/org/jboss/test/faces/staging/StaticServlet.java
+++ b/stage/src/main/java/org/jboss/test/faces/staging/StaticServlet.java
@@ -1,50 +1,50 @@
/**
*
*/
package org.jboss.test.faces.staging;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author asmirnov
*
*/
@SuppressWarnings("serial")
public class StaticServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
- InputStream inputStream = getServletContext().getResourceAsStream(req.getServletPath());
+ InputStream inputStream = getServletContext().getResourceAsStream(req.getPathInfo());
if(null != inputStream){
String fileName = req.getServletPath();
String mimeType = getServletContext().getMimeType(fileName);
if(null == mimeType){
mimeType = "text/plain";
}
resp.setContentType(mimeType);
ServletOutputStream outputStream = resp.getOutputStream();
int c;
while((c = inputStream.read())>0){
outputStream.write(c);
}
inputStream.close();
outputStream.close();
} else {
resp.sendError(404, "not found");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
| true | true | protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
InputStream inputStream = getServletContext().getResourceAsStream(req.getServletPath());
if(null != inputStream){
String fileName = req.getServletPath();
String mimeType = getServletContext().getMimeType(fileName);
if(null == mimeType){
mimeType = "text/plain";
}
resp.setContentType(mimeType);
ServletOutputStream outputStream = resp.getOutputStream();
int c;
while((c = inputStream.read())>0){
outputStream.write(c);
}
inputStream.close();
outputStream.close();
} else {
resp.sendError(404, "not found");
}
}
| protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
InputStream inputStream = getServletContext().getResourceAsStream(req.getPathInfo());
if(null != inputStream){
String fileName = req.getServletPath();
String mimeType = getServletContext().getMimeType(fileName);
if(null == mimeType){
mimeType = "text/plain";
}
resp.setContentType(mimeType);
ServletOutputStream outputStream = resp.getOutputStream();
int c;
while((c = inputStream.read())>0){
outputStream.write(c);
}
inputStream.close();
outputStream.close();
} else {
resp.sendError(404, "not found");
}
}
|
diff --git a/vramel-core/src/main/java/com/nxttxn/vramel/components/vertx/VertxConsumer.java b/vramel-core/src/main/java/com/nxttxn/vramel/components/vertx/VertxConsumer.java
index 2fa3291..e995b75 100644
--- a/vramel-core/src/main/java/com/nxttxn/vramel/components/vertx/VertxConsumer.java
+++ b/vramel-core/src/main/java/com/nxttxn/vramel/components/vertx/VertxConsumer.java
@@ -1,104 +1,104 @@
package com.nxttxn.vramel.components.vertx;
import com.google.common.base.Optional;
import com.nxttxn.vramel.*;
import com.nxttxn.vramel.impl.DefaultConsumer;
import com.nxttxn.vramel.impl.DefaultExchangeHolder;
import com.nxttxn.vramel.processor.async.AsyncExchangeResult;
import com.nxttxn.vramel.processor.async.OptionalAsyncResultHandler;
import org.apache.commons.lang3.SerializationUtils;
import org.vertx.java.core.Handler;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.eventbus.Message;
/**
* Created with IntelliJ IDEA.
* User: chuck
* Date: 6/19/13
* Time: 11:17 AM
* To change this template use File | Settings | File Templates.
*/
public class VertxConsumer extends DefaultConsumer {
private final VertxChannelAdapter endpoint;
public VertxConsumer(final Endpoint endpoint, final Processor processor) throws Exception {
super(endpoint, processor);
this.endpoint = (VertxChannelAdapter) endpoint;
getEventBus().registerHandler(this.endpoint.getAddress(), new Handler<Message<byte[]>>() {
@Override
public void handle(final Message<byte[]> message) {
logger.info("[Vertx Consumer] [{}] Received Message", ((VertxChannelAdapter) endpoint).getAddress());
Exchange exchange = getEndpoint().createExchange();
try {
DefaultExchangeHolder.unmarshal(exchange, message.body);
logger.debug("[Vertx Consumer] Unmarshalled exchange. Exchange transferred.");
} catch (Exception e) {
- logger.error("[Vertx Consumer] Not valid for exchange transfer", e);
+ logger.trace("[Vertx Consumer] Not valid for exchange transfer. Trying VertxMessage.", e);
try {
final VertxMessage vertxMessage = (VertxMessage) SerializationUtils.deserialize(message.body);
exchange.getIn().setBody(vertxMessage.getBody());
exchange.getIn().setHeaders(vertxMessage.getHeaders());
logger.debug("[Vertx Consumer] VertxMessage processed and new exchange created.");
} catch (Exception e1) {
exchange.getIn().setBody(message.body);
- logger.debug("[Vertx Consumer] New exchange created with message body.");
+ logger.trace("[Vertx Consumer] New exchange created with message body.");
}
}
try {
final Exchange request = exchange;
logger.debug("[Vertx Consumer] received message: " + exchange.toString());
getAsyncProcessor().process(request, new OptionalAsyncResultHandler() {
@Override
public void handle(AsyncExchangeResult optionalAsyncResult) {
if (optionalAsyncResult.failed()) {
request.setException(optionalAsyncResult.getException());
sendError(message, request);
return;
}
final Optional<Exchange> result = optionalAsyncResult.result;
if (result.isPresent()) {
replyWithExchange(message, result.get());
} else {
replyWithExchange(message, request);
}
}
});
} catch (Exception e) {
logger.error(String.format("[Vertx Consumer] Error processing flow: %s", ((VertxChannelAdapter) endpoint).getAddress()), e);
exchange.setException(new RuntimeVramelException("Vertx consumer failed to process message: " + e.getMessage()));
sendError(message, exchange);
}
}
});
}
private EventBus getEventBus() {
return endpoint.getVramelContext().getEventBus();
}
protected void sendError(Message<byte[]> message, Exchange exchange) {
logger.error("Error during the exchange processing", exchange.getException());
replyWithExchange(message, exchange);
}
private void replyWithExchange(Message<byte[]> message, Exchange exchange) {
try {
DefaultExchangeHolder holder = DefaultExchangeHolder.marshal(exchange);
message.reply(holder.getBytes());
} catch (Exception e) {
logger.error("Unable to marshal the exchange for return", e);
}
}
}
| false | true | public VertxConsumer(final Endpoint endpoint, final Processor processor) throws Exception {
super(endpoint, processor);
this.endpoint = (VertxChannelAdapter) endpoint;
getEventBus().registerHandler(this.endpoint.getAddress(), new Handler<Message<byte[]>>() {
@Override
public void handle(final Message<byte[]> message) {
logger.info("[Vertx Consumer] [{}] Received Message", ((VertxChannelAdapter) endpoint).getAddress());
Exchange exchange = getEndpoint().createExchange();
try {
DefaultExchangeHolder.unmarshal(exchange, message.body);
logger.debug("[Vertx Consumer] Unmarshalled exchange. Exchange transferred.");
} catch (Exception e) {
logger.error("[Vertx Consumer] Not valid for exchange transfer", e);
try {
final VertxMessage vertxMessage = (VertxMessage) SerializationUtils.deserialize(message.body);
exchange.getIn().setBody(vertxMessage.getBody());
exchange.getIn().setHeaders(vertxMessage.getHeaders());
logger.debug("[Vertx Consumer] VertxMessage processed and new exchange created.");
} catch (Exception e1) {
exchange.getIn().setBody(message.body);
logger.debug("[Vertx Consumer] New exchange created with message body.");
}
}
try {
final Exchange request = exchange;
logger.debug("[Vertx Consumer] received message: " + exchange.toString());
getAsyncProcessor().process(request, new OptionalAsyncResultHandler() {
@Override
public void handle(AsyncExchangeResult optionalAsyncResult) {
if (optionalAsyncResult.failed()) {
request.setException(optionalAsyncResult.getException());
sendError(message, request);
return;
}
final Optional<Exchange> result = optionalAsyncResult.result;
if (result.isPresent()) {
replyWithExchange(message, result.get());
} else {
replyWithExchange(message, request);
}
}
});
} catch (Exception e) {
logger.error(String.format("[Vertx Consumer] Error processing flow: %s", ((VertxChannelAdapter) endpoint).getAddress()), e);
exchange.setException(new RuntimeVramelException("Vertx consumer failed to process message: " + e.getMessage()));
sendError(message, exchange);
}
}
});
}
| public VertxConsumer(final Endpoint endpoint, final Processor processor) throws Exception {
super(endpoint, processor);
this.endpoint = (VertxChannelAdapter) endpoint;
getEventBus().registerHandler(this.endpoint.getAddress(), new Handler<Message<byte[]>>() {
@Override
public void handle(final Message<byte[]> message) {
logger.info("[Vertx Consumer] [{}] Received Message", ((VertxChannelAdapter) endpoint).getAddress());
Exchange exchange = getEndpoint().createExchange();
try {
DefaultExchangeHolder.unmarshal(exchange, message.body);
logger.debug("[Vertx Consumer] Unmarshalled exchange. Exchange transferred.");
} catch (Exception e) {
logger.trace("[Vertx Consumer] Not valid for exchange transfer. Trying VertxMessage.", e);
try {
final VertxMessage vertxMessage = (VertxMessage) SerializationUtils.deserialize(message.body);
exchange.getIn().setBody(vertxMessage.getBody());
exchange.getIn().setHeaders(vertxMessage.getHeaders());
logger.debug("[Vertx Consumer] VertxMessage processed and new exchange created.");
} catch (Exception e1) {
exchange.getIn().setBody(message.body);
logger.trace("[Vertx Consumer] New exchange created with message body.");
}
}
try {
final Exchange request = exchange;
logger.debug("[Vertx Consumer] received message: " + exchange.toString());
getAsyncProcessor().process(request, new OptionalAsyncResultHandler() {
@Override
public void handle(AsyncExchangeResult optionalAsyncResult) {
if (optionalAsyncResult.failed()) {
request.setException(optionalAsyncResult.getException());
sendError(message, request);
return;
}
final Optional<Exchange> result = optionalAsyncResult.result;
if (result.isPresent()) {
replyWithExchange(message, result.get());
} else {
replyWithExchange(message, request);
}
}
});
} catch (Exception e) {
logger.error(String.format("[Vertx Consumer] Error processing flow: %s", ((VertxChannelAdapter) endpoint).getAddress()), e);
exchange.setException(new RuntimeVramelException("Vertx consumer failed to process message: " + e.getMessage()));
sendError(message, exchange);
}
}
});
}
|
diff --git a/src/com/redhat/qe/sm/cli/tests/PofilterTranslationTests.java b/src/com/redhat/qe/sm/cli/tests/PofilterTranslationTests.java
index 180cd771..77cd0b32 100644
--- a/src/com/redhat/qe/sm/cli/tests/PofilterTranslationTests.java
+++ b/src/com/redhat/qe/sm/cli/tests/PofilterTranslationTests.java
@@ -1,591 +1,591 @@
package com.redhat.qe.sm.cli.tests;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.redhat.qe.Assert;
import com.redhat.qe.auto.bugzilla.BlockedByBzBug;
import com.redhat.qe.auto.testng.TestNGUtils;
import com.redhat.qe.sm.base.SubscriptionManagerCLITestScript;
import com.redhat.qe.sm.data.Translation;
import com.redhat.qe.tools.RemoteFileTasks;
import com.redhat.qe.tools.SSHCommandResult;
import com.redhat.qe.tools.SSHCommandRunner;
//import com.sun.org.apache.xalan.internal.xsltc.compiler.Pattern;
/**
* @author fsharath
* @author jsefler
* @References
* Engineering Localization Services: https://home.corp.redhat.com/node/53593
* http://git.fedorahosted.org/git/?p=subscription-manager.git;a=blob;f=po/pt.po;h=0854212f4fab348a25f0542625df343653a4a097;hb=RHEL6.3
* Here is the raw rhsm.po file for LANG=pt
* http://git.fedorahosted.org/git/?p=subscription-manager.git;a=blob;f=po/pt.po;hb=RHEL6.3
*
* https://engineering.redhat.com/trac/LocalizationServices
* https://engineering.redhat.com/trac/LocalizationServices/wiki/L10nRHEL6LanguageSupportCriteria
*
* https://translate.zanata.org/zanata/project/view/subscription-manager/iter/0.99.X/stats
*
* https://fedora.transifex.net/projects/p/fedora/
*
* http://translate.sourceforge.net/wiki/
* http://translate.sourceforge.net/wiki/toolkit/index
* http://translate.sourceforge.net/wiki/toolkit/pofilter
* http://translate.sourceforge.net/wiki/toolkit/pofilter_tests
* http://translate.sourceforge.net/wiki/toolkit/installation
*
* https://github.com/translate/translate
*
* Translation Bug Reporting Process
* https://engineering.redhat.com/trac/LocalizationServices/wiki/L10nBugReportingProcess
**/
@Test(groups={"PofilterTranslationTests"})
public class PofilterTranslationTests extends SubscriptionManagerCLITestScript {
// Test Methods ***********************************************************************
@Test( description="run pofilter translate tests on subscription manager translation files",
dataProvider="getSubscriptionManagerTranslationFilePofilterTestData",
groups={},
enabled=true)
//@ImplementsNitrateTest(caseId=)
public void subscriptionManagerPofilter_Test(Object bugzilla, String pofilterTest, File translationFile) {
pofilter_Test(client, pofilterTest, translationFile);
}
@Test( description="run pofilter translate tests on candlepin translation files",
dataProvider="getCandlepinTranslationFilePofilterTestData",
groups={},
enabled=true)
//@ImplementsNitrateTest(caseId=)
public void candlepinPofilter_Test(Object bugzilla, String pofilterTest, File translationFile) {
pofilter_Test(server, pofilterTest, translationFile);
}
// Candidates for an automated Test:
// Configuration Methods ***********************************************************************
@BeforeClass(groups={"setup"})
public void setupBeforeClass() {
// for debugging purposes, load a reduced list of pofilterTests
if (!getProperty("sm.debug.pofilterTests", "").equals("")) pofilterTests = Arrays.asList(getProperty("sm.debug.pofilterTests", "").trim().split(" *, *"));
}
// Protected Methods ***********************************************************************
// see http://translate.sourceforge.net/wiki/toolkit/pofilter_tests
// Critical -- can break a program
// accelerators, escapes, newlines, nplurals, printf, tabs, variables, xmltags, dialogsizes
// Functional -- may confuse the user
// acronyms, blank, emails, filepaths, functions, gconf, kdecomments, long, musttranslatewords, notranslatewords, numbers, options, purepunc, sentencecount, short, spellcheck, urls, unchanged
// Cosmetic -- make it look better
// brackets, doublequoting, doublespacing, doublewords, endpunc, endwhitespace, puncspacing, simplecaps, simpleplurals, startcaps, singlequoting, startpunc, startwhitespace, validchars
// Extraction -- useful mainly for extracting certain types of string
// compendiumconflicts, credits, hassuggestion, isfuzzy, isreview, untranslated
protected List<String> pofilterTests = Arrays.asList(
// Critical -- can break a program
"accelerators", "escapes", "newlines", /*nplurals,*/ "printf", "tabs", "variables", "xmltags", /*dialogsizes,*/
// Functional -- may confuse the user
/*acronyms,*/ "blank", "emails", "filepaths", /*functions,*/ "gconf", /*kdecomments,*/ "long", /*musttranslatewords,*/ "notranslatewords", /*numbers,*/ "options", /*purepunc,*/ /*sentencecount,*/ "short", /*spellcheck,*/ "urls", "unchanged",
// Cosmetic -- make it look better
/*brackets, doublequoting, doublespacing,*/ "doublewords", /*endpunc, endwhitespace, puncspacing, simplecaps, simpleplurals, startcaps, singlequoting, startpunc, startwhitespace, validchars */
// Extraction -- useful mainly for extracting certain types of string
/*compendiumconflicts, credits, hassuggestion, isfuzzy, isreview,*/ "untranslated");
protected void pofilter_Test(SSHCommandRunner sshCommandRunner, String pofilterTest, File translationFile) {
log.info("For an explanation of pofilter test '"+pofilterTest+"', see: http://translate.sourceforge.net/wiki/toolkit/pofilter_tests");
File translationPoFile = new File(translationFile.getPath().replaceFirst(".mo$", ".po"));
// if pofilter test -> notranslatewords, create a file with words that don't have to be translated to native language
final String notranslateFile = "/tmp/notranslatefile";
if (pofilterTest.equals("notranslatewords")) {
// The words that need not be translated can be added this list
List<String> notranslateWords = Arrays.asList("Red Hat","subscription-manager","python-rhsm");
// remove former notranslate file
sshCommandRunner.runCommandAndWait("rm -f "+notranslateFile);
// echo all of the notranslateWords to the notranslateFile
for(String str : notranslateWords) {
String echoCommand = "echo \""+str+"\" >> "+notranslateFile;
sshCommandRunner.runCommandAndWait(echoCommand);
}
Assert.assertTrue(RemoteFileTasks.testExists(sshCommandRunner, notranslateFile),"The pofilter notranslate file '"+notranslateFile+"' has been created on the client.");
}
// execute the pofilter test
String pofilterCommand = "pofilter --gnome -t "+pofilterTest;
if (pofilterTest.equals("notranslatewords")) pofilterCommand += " --notranslatefile="+notranslateFile;
SSHCommandResult pofilterResult = sshCommandRunner.runCommandAndWait(pofilterCommand+" "+translationPoFile);
Assert.assertEquals(pofilterResult.getExitCode(), new Integer(0), "Successfully executed the pofilter tests.");
// convert the pofilter test results into a list of failed Translation objects for simplified handling of special cases
List<Translation> pofilterFailedTranslations = Translation.parse(pofilterResult.getStdout());
// remove the first translation which contains only meta data
if (!pofilterFailedTranslations.isEmpty() && pofilterFailedTranslations.get(0).msgid.equals("")) pofilterFailedTranslations.remove(0);
// ignore the following special cases of acceptable results..........
//List<String> ignorableMsgIds = Arrays.asList();
List<String> ignorableMsgIds = new ArrayList<String>();
if (pofilterTest.equals("accelerators")) {
if (translationFile.getPath().contains("/hi/")/* || translationFile.getPath().contains("hi")*/) ignorableMsgIds = Arrays.asList("proxy url in the form of proxy_hostname:proxy_port");
if (translationFile.getPath().contains("/ru/")/* || translationFile.getPath().contains("ru")*/) ignorableMsgIds = Arrays.asList("proxy url in the form of proxy_hostname:proxy_port");
}
if (pofilterTest.equals("newlines")) {
ignorableMsgIds = Arrays.asList(
"Optional language to use for email notification when subscription redemption is complete. Examples: en-us, de-de",
"\n"+"Unable to register.\n"+"For further assistance, please contact Red Hat Global Support Services.",
"Tip: Forgot your login or password? Look it up at http://red.ht/lost_password",
"Unable to perform refresh due to the following exception: %s",
""+"This migration script requires the system to be registered to RHN Classic.\n"+"However this system appears to be registered to '%s'.\n"+"Exiting.",
"The tool you are using is attempting to re-register using RHN Certificate-Based technology. Red Hat recommends (except in a few cases) that customers only register with RHN once.",
// bug 825397 ""+"Redeeming the subscription may take a few minutes.\n"+"Please provide an email address to receive notification\n"+"when the redemption is complete.", // the Subscription Redemption dialog actually expands to accommodate the message, therefore we could ignore it // bug 825397 should fix this
// bug 825388 ""+"We have detected that you have multiple service level\n"+"agreements on various products. Please select how you\n"+"want them assigned.", // bug 825388 or 825397 should fix this
"\n"+"This machine appears to be already registered to Certificate-based RHN. Exiting.",
"\n"+"This machine appears to be already registered to Red Hat Subscription Management. Exiting.");
}
if (pofilterTest.equals("xmltags")) {
Boolean match = false;
for(Translation pofilterFailedTranslation : pofilterFailedTranslations) {
// Parsing mgID and msgStr for XMLTags
Pattern xmlTags = Pattern.compile("<.+?>");
Matcher tagsMsgID = xmlTags.matcher(pofilterFailedTranslation.msgid);
Matcher tagsMsgStr = xmlTags.matcher(pofilterFailedTranslation.msgstr);
// Populating a msgID tags into a list
ArrayList<String> msgIDTags = new ArrayList<String>();
while(tagsMsgID.find()) {
msgIDTags.add(tagsMsgID.group());
}
// Sorting an list of msgID tags
ArrayList<String> msgIDTagsSort = new ArrayList<String>(msgIDTags);
Collections.sort(msgIDTagsSort);
// Populating a msgStr tags into a list
ArrayList<String> msgStrTags = new ArrayList<String>();
while(tagsMsgStr.find()) {
msgStrTags.add(tagsMsgStr.group());
}
// Sorting an list of msgStr tags
ArrayList<String> msgStrTagsSort = new ArrayList<String>(msgStrTags);
Collections.sort(msgStrTagsSort);
// Verifying whether XMLtags are opened and closed appropriately
// If the above condition holds, then check for XML Tag ordering
if(msgIDTagsSort.equals(msgStrTagsSort) && msgIDTagsSort.size() == msgStrTagsSort.size()) {
int size = msgIDTags.size(),count=0;
// Stack to hold XML tags
Stack<String> stackMsgIDTags = new Stack<String>();
Stack<String> stackMsgStrTags = new Stack<String>();
// Temporary stack to hold popped elements
Stack<String> tempStackMsgIDTags = new Stack<String>();
Stack<String> tempStackMsgStrTags = new Stack<String>();
while(count< size) {
// If it's not a close tag push into stack
if(!msgIDTags.get(count).contains("/")) stackMsgIDTags.push(msgIDTags.get(count));
else {
if(checkTags(stackMsgIDTags,tempStackMsgIDTags,msgIDTags.get(count))) match = true;
else {
// If an open XMLtag doesn't have an appropriate close tag exit loop
match = false;
break;
}
}
// If it's not a close tag push into stack
if(!msgStrTags.get(count).contains("/")) stackMsgStrTags.push(msgStrTags.get(count));
else {
if(checkTags(stackMsgStrTags,tempStackMsgStrTags,msgStrTags.get(count))) match = true;
else {
// If an open XMLtag doesn't have an appropriate close tag exit loop
match = false;
break;
}
}
// Incrementing count to point to the next element
count++;
}
}
if(match) ignorableMsgIds.add(pofilterFailedTranslation.msgid);
}
}
if (pofilterTest.equals("filepaths")) {
for(Translation pofilterFailedTranslation : pofilterFailedTranslations) {
// Parsing mgID and msgStr for FilePaths ending ' ' (space)
Pattern filePath = Pattern.compile("/.*?( |$)", Pattern.MULTILINE);
Matcher filePathMsgID = filePath.matcher(pofilterFailedTranslation.msgid);
Matcher filePathMsgStr = filePath.matcher(pofilterFailedTranslation.msgstr);
ArrayList<String> filePathsInID = new ArrayList<String>();
ArrayList<String> filePathsInStr = new ArrayList<String>();
// Reading the filePaths into a list
while(filePathMsgID.find()) {
filePathsInID.add(filePathMsgID.group());
}
while(filePathMsgStr.find()) {
filePathsInStr.add(filePathMsgStr.group());
}
// If the lists are equal in size, then compare the contents of msdID->filePath and msgStr->filePath
//if(filePathsInID.size() == filePathsInStr.size()) {
for(int i=0;i<filePathsInID.size();i++) {
// If the msgID->filePath ends with '.', remove '.' and compare with msgStr->filePath
if(filePathsInID.get(i).trim().startsWith("//")) {
ignorableMsgIds.add(pofilterFailedTranslation.msgid);
continue;
}
//contains("//")) ignoreMsgIDs.add(pofilterFailedTranslation.msgid);
if(filePathsInID.get(i).trim().charAt(filePathsInID.get(i).trim().length()-1) == '.') {
String filePathID = filePathsInID.get(i).trim().substring(0, filePathsInID.get(i).trim().length()-1);
if(filePathID.equals(filePathsInStr.get(i).trim())) ignorableMsgIds.add(pofilterFailedTranslation.msgid);
}
/*else {
if(filePathsInID.get(i).trim().equals(filePathsInStr.get(i).trim())) ignoreMsgIDs.add(pofilterFailedTranslation.msgid);
}*/
}
//}
}
}
// TODO remove or comment this ignore case once the msgID is corrected
// error: msgid "Error: you must register or specify --username and password to list service levels"
// rectified: msgid "Error: you must register or specify --username and --password to list service levels"
if (pofilterTest.equals("options")) {
ignorableMsgIds = Arrays.asList("Error: you must register or specify --username and password to list service levels");
}
if (pofilterTest.equals("short")) {
ignorableMsgIds = Arrays.asList("No","Yes","Key","Value","N/A","None","Number");
}
if (pofilterTest.equals("doublewords")) {
ignorableMsgIds.addAll(Arrays.asList("Subscription Subscriptions Box","Subscription Subscriptions Label"));
List<String> moreIgnorableMsgIdsFor_pa = Arrays.asList("Server URL can not be None");
List<String> moreIgnorableMsgIdsFor_hi = Arrays.asList("Server URL can not be None");
List<String> moreIgnorableMsgIdsFor_fr = Arrays.asList("The Subscription Management Service you register with will provide your system with updates and allow additional management."); // msgstr "Le service de gestion des abonnements « Subscription Management » avec lequel vous vous enregistrez fournira à votre système des mises à jour et permettra une gestion supplémentaire."
if((translationFile.getPath().contains("/pa/")/*||translationFile.getPath().contains("pa")*/)) ignorableMsgIds.addAll(moreIgnorableMsgIdsFor_pa);
if((translationFile.getPath().contains("/hi/")/*||translationFile.getPath().contains("hi")*/)) ignorableMsgIds.addAll(moreIgnorableMsgIdsFor_hi);
if((translationFile.getPath().contains("/fr/")/*||translationFile.getPath().contains("fr")*/)) ignorableMsgIds.addAll(moreIgnorableMsgIdsFor_fr);
}
if (pofilterTest.equals("unchanged")) {
ignorableMsgIds.addAll(Arrays.asList("registration_dialog_action_area","server_label","server_entry","proxy_button","hostname[:port][/prefix]","default_button","choose_server_label","<b>SKU:</b>","%prog [options]","<b>HTTP Proxy</b>","<b>python-rhsm version:</b> %s","<b>python-rhsm Version:</b> %s","close_button","facts_view","register_button","register_dialog_main_vbox","registration_dialog_action_area\n","prod 1, prod2, prod 3, prod 4, prod 5, prod 6, prod 7, prod 8","%s of %s","floating-point","integer","long integer","Copyright (c) 2012 Red Hat, Inc.","RHN Classic","env_select_vbox_label","environment_treeview","no_subs_label","org_selection_label","org_selection_scrolledwindow","owner_treeview","progress_label","subscription-manager: %s","python-rhsm: %s","register_details_label","register_progressbar","system_instructions_label","system_name_label","connectionStatusLabel",""+"\n"+"This software is licensed to you under the GNU General Public License, version 2 (GPLv2). There is NO WARRANTY for this software, express or implied, including the implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 along with this software; if not, see:\n"+"\n"+"http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt\n"+"\n"+"Red Hat trademarks are not licensed under GPLv2. No permission is granted to use or replicate Red Hat trademarks that are incorporated in this software or its documentation.\n","progress_label","Red Hat Subscription Manager", "Red Hat Subscription Validity Applet"));
List<String> moreIgnorableMsgIdsFor_bn_IN = Arrays.asList("Red Hat Subscription Validity Applet","Subscription Validity Applet");
List<String> moreIgnorableMsgIdsFor_ta_IN = Arrays.asList("org id: %s","Repo Id: \\t%s","Repo Url: \\t%s");
List<String> moreIgnorableMsgIdsFor_pt_BR = Arrays.asList("<b>subscription management service version:</b> %s","Status","Status: \\t%s","Login:","Virtual","_Help","hostname[:port][/prefix]","org id: %s","virtual");
List<String> moreIgnorableMsgIdsFor_de_DE = Arrays.asList("Subscription Manager","Red Hat account: ","Account","<b>Account:</b>","Account: \\t%s","<b>Subscription Management Service Version:</b> %s","<b>subscription management service version:</b> %s","Login:","Name","Name: \\t%s","Status","Status: \\t%s","Version","Version: \\t%s","_System","long integer","name: %s","label","Label","Name: %s","Release: %s","integer","Tags","Org: ");
List<String> moreIgnorableMsgIdsFor_es_ES = Arrays.asList("No","%s: error: %s");
List<String> moreIgnorableMsgIdsFor_zh_TW = Arrays.asList("%%prog %s [OPTIONS]","%%prog %s [OPTIONS] CERT_FILE","%prog [OPTIONS]");
List<String> moreIgnorableMsgIdsFor_te = Arrays.asList("page 2");
List<String> moreIgnorableMsgIdsFor_pa = Arrays.asList("<b>python-rhsm version:</b> %s");
List<String> moreIgnorableMsgIdsFor_fr = Arrays.asList("Options","Type","Arch","Version","page 2","%prog [options]");
List<String> moreIgnorableMsgIdsFor_it = Arrays.asList("<b>Account:</b>","Account: \\t%s","<b>Arch:</b>","Arch: \\t%s","Arch","Login:","No","Password:","Release: %s","Password: ");
if (translationFile.getPath().contains("/bn_IN/")/*||translationFile.getPath().contains("bn_IN")*/) ignorableMsgIds.addAll(moreIgnorableMsgIdsFor_bn_IN);
if (translationFile.getPath().contains("/ta_IN/")/*||translationFile.getPath().contains("ta_IN")*/) ignorableMsgIds.addAll(moreIgnorableMsgIdsFor_ta_IN);
if (translationFile.getPath().contains("/pt_BR/")/*||translationFile.getPath().contains("pt_BR")*/) ignorableMsgIds.addAll(moreIgnorableMsgIdsFor_pt_BR);
if (translationFile.getPath().contains("/de_DE/")/*||translationFile.getPath().contains("de_DE")*/) ignorableMsgIds.addAll(moreIgnorableMsgIdsFor_de_DE);
if (translationFile.getPath().contains("/es_ES/")/*||translationFile.getPath().contains("es_ES")*/) ignorableMsgIds.addAll(moreIgnorableMsgIdsFor_es_ES);
if (translationFile.getPath().contains("/zh_TW/")/*||translationFile.getPath().contains("zh_TW")*/) ignorableMsgIds.addAll(moreIgnorableMsgIdsFor_zh_TW);
if (translationFile.getPath().contains("/te/") /*||translationFile.getPath().contains("te")*/) ignorableMsgIds.addAll(moreIgnorableMsgIdsFor_te);
if (translationFile.getPath().contains("/pa/") /*||translationFile.getPath().contains("pa")*/) ignorableMsgIds.addAll(moreIgnorableMsgIdsFor_pa);
if (translationFile.getPath().contains("/fr/") /*||translationFile.getPath().contains("fr")*/) ignorableMsgIds.addAll(moreIgnorableMsgIdsFor_fr);
if (translationFile.getPath().contains("/it/") /*||translationFile.getPath().contains("it")*/) ignorableMsgIds.addAll(moreIgnorableMsgIdsFor_it);
}
if (pofilterTest.equals("urls")) {
if(translationFile.getPath().contains("/zh_CN/")) ignorableMsgIds.addAll(Arrays.asList("Server URL has an invalid scheme. http:// and https:// are supported"));
}
// pluck out the ignorable pofilter test results
for (String msgid : ignorableMsgIds) {
Translation ignoreTranslation = Translation.findFirstInstanceWithMatchingFieldFromList("msgid", msgid, pofilterFailedTranslations);
if (ignoreTranslation!=null) {
log.info("Ignoring result of pofiliter test '"+pofilterTest+"' for msgid: "+ignoreTranslation.msgid);
pofilterFailedTranslations.remove(ignoreTranslation);
}
}
// for convenience reading the logs, log warnings for the failed pofilter test results (when some of the failed test are being ignored)
if (!ignorableMsgIds.isEmpty()) for (Translation pofilterFailedTranslation : pofilterFailedTranslations) {
log.warning("Failed result of pofiliter test '"+pofilterTest+"' for translation: "+pofilterFailedTranslation);
}
// assert that there are no failed pofilter translation test results
Assert.assertEquals(pofilterFailedTranslations.size(),0, "Discounting the ignored test results, the number of failed pofilter '"+pofilterTest+"' tests for translation file '"+translationFile+"'.");
}
/**
* @param str
* @return the tag character (Eg: <b> or </b> return_val = 'b')
*/
protected char parseElement(String str){
return str.charAt(str.length()-2);
}
/**
* @param tags
* @param temp
* @param tagElement
* @return whether every open tag has an appropriate close tag in order
*/
protected Boolean checkTags(Stack<String> tags, Stack<String> temp, String tagElement) {
// If there are no open tags in the stack -> return
if(tags.empty()) return false;
String popElement = tags.pop();
// If openTag in stack = closeTag -> return
if(!popElement.contains("/") && parseElement(popElement) == parseElement(tagElement)) return true;
else {
// Continue popping elements from stack and push to temp until appropriate open tag is found
while(popElement.contains("/") || parseElement(popElement) != parseElement(tagElement)) {
temp.push(popElement);
// If stack = empty and no match, push back the popped elements -> return
if(tags.empty()) {
while(!temp.empty()) {
tags.push(temp.pop());
}
return false;
}
popElement = tags.pop();
}
// If a match is found, push back the popped elements -> return
while(!temp.empty()) tags.push(temp.pop());
}
return true;
}
// Data Providers ***********************************************************************
@DataProvider(name="getSubscriptionManagerTranslationFilePofilterTestData")
public Object[][] getSubscriptionManagerTranslationFilePofilterTestDataAs2dArray() {
return TestNGUtils.convertListOfListsTo2dArray(getSubscriptionManagerTranslationFilePofilterTestDataAsListOfLists());
}
protected List<List<Object>> getSubscriptionManagerTranslationFilePofilterTestDataAsListOfLists() {
List<List<Object>> ll = new ArrayList<List<Object>>();
// Client side
Map<File,List<Translation>> translationFileMapForSubscriptionManager = buildTranslationFileMapForSubscriptionManager();
for (File translationFile : translationFileMapForSubscriptionManager.keySet()) {
for (String pofilterTest : pofilterTests) {
Set<String> bugIds = new HashSet<String>();
// Bug 825362 [es_ES] failed pofilter accelerator tests for subscription-manager translations
if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/es_ES/")) bugIds.add("825362");
// Bug 825367 [zh_CN] failed pofilter accelerator tests for subscription-manager translations
if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/zh_CN/")) bugIds.add("825367");
// Bug 860084 - [ja_JP] two accelerators for msgid "Configure Pro_xy"
- if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/ja_JP/")) bugIds.add("860084");
+ if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/ja/")) bugIds.add("860084");
// Bug 825397 Many translated languages fail the pofilter newlines test
if (pofilterTest.equals("newlines") && !(translationFile.getPath().contains("/zh_CN/")||translationFile.getPath().contains("/ru/")||translationFile.getPath().contains("/ja/"))) bugIds.add("825397");
// Bug 825393 [ml_IN][es_ES] translations should not use character ¶ for a new line.
if (pofilterTest.equals("newlines") && translationFile.getPath().contains("/ml/")) bugIds.add("825393");
if (pofilterTest.equals("newlines") && translationFile.getPath().contains("/es_ES/")) bugIds.add("825393");
// Bug 827059 [kn] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/kn/")) bugIds.add("827059");
// Bug 827079 [es-ES] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/es_ES/")) bugIds.add("827079");
// Bug 827085 [hi] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/hi/")) bugIds.add("827085");
// Bug 827089 [hi] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/te/")) bugIds.add("827089");
// Bug 827113 Many Translated languages fail the pofilter tabs test
if (pofilterTest.equals("tabs") && !(translationFile.getPath().contains("/pa/")||translationFile.getPath().contains("/mr/")||translationFile.getPath().contains("/de_DE/")||translationFile.getPath().contains("/bn_IN/"))) bugIds.add("825397");
// Bug 827161 [bn_IN] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("827161");
// Bug 827208 [or] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/or/")) bugIds.add("827208");
// Bug 827214 [or] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("827214");
// Bug 828368 - [kn] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/kn/")) bugIds.add("828368");
// Bug 828365 - [kn] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/kn/")) bugIds.add("828365");
// Bug 828372 - [es_ES] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/es_ES/")) bugIds.add("828372");
// Bug 828416 - [ru] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/ru/")) bugIds.add("828416");
// Bug 843113 - [ta_IN] failed pofilter xmltags test for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("843113");
// Bug 828566 [bn-IN] cosmetic bug for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("828566");
// Bug 828567 [as] cosmetic bug for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/as/")) bugIds.add("828567");
// Bug 828576 - [ta_IN] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("828576");
// Bug 828579 - [ml] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/ml/")) bugIds.add("828579");
// Bug 828580 - [mr] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/mr/")) bugIds.add("828580");
// Bug 828583 - [ko] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/ko/")) bugIds.add("828583");
// Bug 828810 - [kn] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/kn/")) bugIds.add("828810");
// Bug 828816 - [es_ES] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/es_ES/")) bugIds.add("828816");
// Bug 828821 - [hi] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/hi/")) bugIds.add("828821");
// Bug 828867 - [te] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/te/")) bugIds.add("828867");
// Bug 828903 - [bn_IN] failed pofilter options tests for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("828903");
// Bug 828930 - [as] failed pofilter options tests for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/as/")) bugIds.add("828930");
// Bug 828948 - [or] failed pofilter options tests for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/or/")) bugIds.add("828948");
// Bug 828954 - [ta_IN] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("828954");
// Bug 828958 - [pt_BR] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/pt_BR/")) bugIds.add("828958");
// Bug 828961 - [gu] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/gu/")) bugIds.add("828961");
// Bug 828965 - [hi] failed pofilter options test for subscription-manager trasnlations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/hi/")) bugIds.add("828965");
// Bug 828966 - [zh_CN] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/zh_CN/")) bugIds.add("828966");
// Bug 828969 - [te] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/te/")) bugIds.add("828969");
// Bug 842898 - [it] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/it/")) bugIds.add("842898");
// Bug 828985 - [ml] failed pofilter urls test for subscription manager translations
if (pofilterTest.equals("urls") && translationFile.getPath().contains("/ml/")) bugIds.add("828985");
// Bug 828989 - [pt_BR] failed pofilter urls test for subscription-manager translations
if (pofilterTest.equals("urls") && translationFile.getPath().contains("/pt_BR/")) bugIds.add("828989");
// Bug 860088 - [de_DE] translation for a url should not be altered
if (pofilterTest.equals("urls") && translationFile.getPath().contains("/de_DE/")) bugIds.add("860088");
// Bug 845304 - translation of the word "[OPTIONS]" has reverted
if (pofilterTest.equals("unchanged")) bugIds.add("845304");
// Bug 829459 - [bn_IN] failed pofilter unchanged option test for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("829459");
// Bug 829470 - [or] failed pofilter unchanged options for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/or/")) bugIds.add("829470");
// Bug 829471 - [ta_IN] failed pofilter unchanged optioon test for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("829471");
// Bug 829476 - [ml] failed pofilter unchanged option test for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/ml/")) bugIds.add("829476");
// Bug 829479 - [pt_BR] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/pt_BR/")) {bugIds.add("829479"); bugIds.add("828958");}
// Bug 829482 - [zh_TW] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/zh_TW/")) bugIds.add("829482");
// Bug 829483 - [de_DE] failed pofilter unchanged options test for suubscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/de_DE/")) bugIds.add("829483");
// Bug 829486 - [fr] failed pofilter unchanged options test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/fr/")) bugIds.add("829486");
// Bug 829488 - [es_ES] failed pofilter unchanged option tests for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/es_ES/")) bugIds.add("829488");
// Bug 829491 - [it] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/it/")) bugIds.add("829491");
// Bug 829492 - [hi] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/hi/")) bugIds.add("829492");
// Bug 829494 - [zh_CN] failed pofilter unchanged option for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/zh_CN/")) bugIds.add("829494");
// Bug 829495 - [pa] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/pa/")) bugIds.add("829495");
// Bug 840914 - [te] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/te/")) bugIds.add("840914");
// Bug 840644 - [ta_IN] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("840644");
// Bug 855087 - [mr] missing translation for the word "OPTIONS"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/mr/")) bugIds.add("855087");
// Bug 855085 - [as] missing translation for the word "OPTIONS"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/as/")) bugIds.add("855085");
// Bug 855081 - [pt_BR] untranslated msgid "Arch"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/pt_BR/")) bugIds.add("855081");
// Bug 841011 - [kn] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("doublewords") && translationFile.getPath().contains("/kn/")) bugIds.add("841011");
BlockedByBzBug blockedByBzBug = new BlockedByBzBug(bugIds.toArray(new String[]{}));
ll.add(Arrays.asList(new Object[] {blockedByBzBug, pofilterTest, translationFile}));
}
}
return ll;
}
@DataProvider(name="getCandlepinTranslationFilePofilterTestData")
public Object[][] getCandlepinTranslationFilePofilterTestDataAs2dArray() {
return TestNGUtils.convertListOfListsTo2dArray(getCandlepinTranslationFilePofilterTestDataAsListOfLists());
}
protected List<List<Object>> getCandlepinTranslationFilePofilterTestDataAsListOfLists() {
List<List<Object>> ll = new ArrayList<List<Object>>();
// Server side
Map<File,List<Translation>> translationFileMapForCandlepin = buildTranslationFileMapForCandlepin();
for (File translationFile : translationFileMapForCandlepin.keySet()) {
for (String pofilterTest : pofilterTests) {
BlockedByBzBug bugzilla = null;
// Bug 842450 - [ja_JP] failed pofilter newlines option test for candlepin translations
if (pofilterTest.equals("newlines") && translationFile.getName().equals("ja.po")) bugzilla = new BlockedByBzBug("842450");
if (pofilterTest.equals("tabs") && translationFile.getName().equals("ja.po")) bugzilla = new BlockedByBzBug("842450");
// Bug 842784 - [ALL LANG] failed pofilter untranslated option test for candlepin translations
if (pofilterTest.equals("untranslated")) bugzilla = new BlockedByBzBug("842784");
ll.add(Arrays.asList(new Object[] {bugzilla, pofilterTest, translationFile}));
}
}
return ll;
}
}
| true | true | protected List<List<Object>> getSubscriptionManagerTranslationFilePofilterTestDataAsListOfLists() {
List<List<Object>> ll = new ArrayList<List<Object>>();
// Client side
Map<File,List<Translation>> translationFileMapForSubscriptionManager = buildTranslationFileMapForSubscriptionManager();
for (File translationFile : translationFileMapForSubscriptionManager.keySet()) {
for (String pofilterTest : pofilterTests) {
Set<String> bugIds = new HashSet<String>();
// Bug 825362 [es_ES] failed pofilter accelerator tests for subscription-manager translations
if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/es_ES/")) bugIds.add("825362");
// Bug 825367 [zh_CN] failed pofilter accelerator tests for subscription-manager translations
if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/zh_CN/")) bugIds.add("825367");
// Bug 860084 - [ja_JP] two accelerators for msgid "Configure Pro_xy"
if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/ja_JP/")) bugIds.add("860084");
// Bug 825397 Many translated languages fail the pofilter newlines test
if (pofilterTest.equals("newlines") && !(translationFile.getPath().contains("/zh_CN/")||translationFile.getPath().contains("/ru/")||translationFile.getPath().contains("/ja/"))) bugIds.add("825397");
// Bug 825393 [ml_IN][es_ES] translations should not use character ¶ for a new line.
if (pofilterTest.equals("newlines") && translationFile.getPath().contains("/ml/")) bugIds.add("825393");
if (pofilterTest.equals("newlines") && translationFile.getPath().contains("/es_ES/")) bugIds.add("825393");
// Bug 827059 [kn] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/kn/")) bugIds.add("827059");
// Bug 827079 [es-ES] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/es_ES/")) bugIds.add("827079");
// Bug 827085 [hi] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/hi/")) bugIds.add("827085");
// Bug 827089 [hi] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/te/")) bugIds.add("827089");
// Bug 827113 Many Translated languages fail the pofilter tabs test
if (pofilterTest.equals("tabs") && !(translationFile.getPath().contains("/pa/")||translationFile.getPath().contains("/mr/")||translationFile.getPath().contains("/de_DE/")||translationFile.getPath().contains("/bn_IN/"))) bugIds.add("825397");
// Bug 827161 [bn_IN] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("827161");
// Bug 827208 [or] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/or/")) bugIds.add("827208");
// Bug 827214 [or] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("827214");
// Bug 828368 - [kn] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/kn/")) bugIds.add("828368");
// Bug 828365 - [kn] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/kn/")) bugIds.add("828365");
// Bug 828372 - [es_ES] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/es_ES/")) bugIds.add("828372");
// Bug 828416 - [ru] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/ru/")) bugIds.add("828416");
// Bug 843113 - [ta_IN] failed pofilter xmltags test for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("843113");
// Bug 828566 [bn-IN] cosmetic bug for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("828566");
// Bug 828567 [as] cosmetic bug for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/as/")) bugIds.add("828567");
// Bug 828576 - [ta_IN] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("828576");
// Bug 828579 - [ml] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/ml/")) bugIds.add("828579");
// Bug 828580 - [mr] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/mr/")) bugIds.add("828580");
// Bug 828583 - [ko] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/ko/")) bugIds.add("828583");
// Bug 828810 - [kn] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/kn/")) bugIds.add("828810");
// Bug 828816 - [es_ES] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/es_ES/")) bugIds.add("828816");
// Bug 828821 - [hi] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/hi/")) bugIds.add("828821");
// Bug 828867 - [te] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/te/")) bugIds.add("828867");
// Bug 828903 - [bn_IN] failed pofilter options tests for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("828903");
// Bug 828930 - [as] failed pofilter options tests for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/as/")) bugIds.add("828930");
// Bug 828948 - [or] failed pofilter options tests for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/or/")) bugIds.add("828948");
// Bug 828954 - [ta_IN] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("828954");
// Bug 828958 - [pt_BR] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/pt_BR/")) bugIds.add("828958");
// Bug 828961 - [gu] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/gu/")) bugIds.add("828961");
// Bug 828965 - [hi] failed pofilter options test for subscription-manager trasnlations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/hi/")) bugIds.add("828965");
// Bug 828966 - [zh_CN] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/zh_CN/")) bugIds.add("828966");
// Bug 828969 - [te] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/te/")) bugIds.add("828969");
// Bug 842898 - [it] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/it/")) bugIds.add("842898");
// Bug 828985 - [ml] failed pofilter urls test for subscription manager translations
if (pofilterTest.equals("urls") && translationFile.getPath().contains("/ml/")) bugIds.add("828985");
// Bug 828989 - [pt_BR] failed pofilter urls test for subscription-manager translations
if (pofilterTest.equals("urls") && translationFile.getPath().contains("/pt_BR/")) bugIds.add("828989");
// Bug 860088 - [de_DE] translation for a url should not be altered
if (pofilterTest.equals("urls") && translationFile.getPath().contains("/de_DE/")) bugIds.add("860088");
// Bug 845304 - translation of the word "[OPTIONS]" has reverted
if (pofilterTest.equals("unchanged")) bugIds.add("845304");
// Bug 829459 - [bn_IN] failed pofilter unchanged option test for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("829459");
// Bug 829470 - [or] failed pofilter unchanged options for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/or/")) bugIds.add("829470");
// Bug 829471 - [ta_IN] failed pofilter unchanged optioon test for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("829471");
// Bug 829476 - [ml] failed pofilter unchanged option test for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/ml/")) bugIds.add("829476");
// Bug 829479 - [pt_BR] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/pt_BR/")) {bugIds.add("829479"); bugIds.add("828958");}
// Bug 829482 - [zh_TW] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/zh_TW/")) bugIds.add("829482");
// Bug 829483 - [de_DE] failed pofilter unchanged options test for suubscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/de_DE/")) bugIds.add("829483");
// Bug 829486 - [fr] failed pofilter unchanged options test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/fr/")) bugIds.add("829486");
// Bug 829488 - [es_ES] failed pofilter unchanged option tests for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/es_ES/")) bugIds.add("829488");
// Bug 829491 - [it] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/it/")) bugIds.add("829491");
// Bug 829492 - [hi] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/hi/")) bugIds.add("829492");
// Bug 829494 - [zh_CN] failed pofilter unchanged option for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/zh_CN/")) bugIds.add("829494");
// Bug 829495 - [pa] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/pa/")) bugIds.add("829495");
// Bug 840914 - [te] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/te/")) bugIds.add("840914");
// Bug 840644 - [ta_IN] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("840644");
// Bug 855087 - [mr] missing translation for the word "OPTIONS"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/mr/")) bugIds.add("855087");
// Bug 855085 - [as] missing translation for the word "OPTIONS"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/as/")) bugIds.add("855085");
// Bug 855081 - [pt_BR] untranslated msgid "Arch"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/pt_BR/")) bugIds.add("855081");
// Bug 841011 - [kn] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("doublewords") && translationFile.getPath().contains("/kn/")) bugIds.add("841011");
BlockedByBzBug blockedByBzBug = new BlockedByBzBug(bugIds.toArray(new String[]{}));
ll.add(Arrays.asList(new Object[] {blockedByBzBug, pofilterTest, translationFile}));
}
}
| protected List<List<Object>> getSubscriptionManagerTranslationFilePofilterTestDataAsListOfLists() {
List<List<Object>> ll = new ArrayList<List<Object>>();
// Client side
Map<File,List<Translation>> translationFileMapForSubscriptionManager = buildTranslationFileMapForSubscriptionManager();
for (File translationFile : translationFileMapForSubscriptionManager.keySet()) {
for (String pofilterTest : pofilterTests) {
Set<String> bugIds = new HashSet<String>();
// Bug 825362 [es_ES] failed pofilter accelerator tests for subscription-manager translations
if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/es_ES/")) bugIds.add("825362");
// Bug 825367 [zh_CN] failed pofilter accelerator tests for subscription-manager translations
if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/zh_CN/")) bugIds.add("825367");
// Bug 860084 - [ja_JP] two accelerators for msgid "Configure Pro_xy"
if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/ja/")) bugIds.add("860084");
// Bug 825397 Many translated languages fail the pofilter newlines test
if (pofilterTest.equals("newlines") && !(translationFile.getPath().contains("/zh_CN/")||translationFile.getPath().contains("/ru/")||translationFile.getPath().contains("/ja/"))) bugIds.add("825397");
// Bug 825393 [ml_IN][es_ES] translations should not use character ¶ for a new line.
if (pofilterTest.equals("newlines") && translationFile.getPath().contains("/ml/")) bugIds.add("825393");
if (pofilterTest.equals("newlines") && translationFile.getPath().contains("/es_ES/")) bugIds.add("825393");
// Bug 827059 [kn] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/kn/")) bugIds.add("827059");
// Bug 827079 [es-ES] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/es_ES/")) bugIds.add("827079");
// Bug 827085 [hi] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/hi/")) bugIds.add("827085");
// Bug 827089 [hi] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/te/")) bugIds.add("827089");
// Bug 827113 Many Translated languages fail the pofilter tabs test
if (pofilterTest.equals("tabs") && !(translationFile.getPath().contains("/pa/")||translationFile.getPath().contains("/mr/")||translationFile.getPath().contains("/de_DE/")||translationFile.getPath().contains("/bn_IN/"))) bugIds.add("825397");
// Bug 827161 [bn_IN] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("827161");
// Bug 827208 [or] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/or/")) bugIds.add("827208");
// Bug 827214 [or] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("827214");
// Bug 828368 - [kn] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/kn/")) bugIds.add("828368");
// Bug 828365 - [kn] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/kn/")) bugIds.add("828365");
// Bug 828372 - [es_ES] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/es_ES/")) bugIds.add("828372");
// Bug 828416 - [ru] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/ru/")) bugIds.add("828416");
// Bug 843113 - [ta_IN] failed pofilter xmltags test for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("843113");
// Bug 828566 [bn-IN] cosmetic bug for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("828566");
// Bug 828567 [as] cosmetic bug for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/as/")) bugIds.add("828567");
// Bug 828576 - [ta_IN] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("828576");
// Bug 828579 - [ml] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/ml/")) bugIds.add("828579");
// Bug 828580 - [mr] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/mr/")) bugIds.add("828580");
// Bug 828583 - [ko] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/ko/")) bugIds.add("828583");
// Bug 828810 - [kn] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/kn/")) bugIds.add("828810");
// Bug 828816 - [es_ES] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/es_ES/")) bugIds.add("828816");
// Bug 828821 - [hi] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/hi/")) bugIds.add("828821");
// Bug 828867 - [te] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/te/")) bugIds.add("828867");
// Bug 828903 - [bn_IN] failed pofilter options tests for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("828903");
// Bug 828930 - [as] failed pofilter options tests for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/as/")) bugIds.add("828930");
// Bug 828948 - [or] failed pofilter options tests for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/or/")) bugIds.add("828948");
// Bug 828954 - [ta_IN] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("828954");
// Bug 828958 - [pt_BR] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/pt_BR/")) bugIds.add("828958");
// Bug 828961 - [gu] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/gu/")) bugIds.add("828961");
// Bug 828965 - [hi] failed pofilter options test for subscription-manager trasnlations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/hi/")) bugIds.add("828965");
// Bug 828966 - [zh_CN] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/zh_CN/")) bugIds.add("828966");
// Bug 828969 - [te] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/te/")) bugIds.add("828969");
// Bug 842898 - [it] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/it/")) bugIds.add("842898");
// Bug 828985 - [ml] failed pofilter urls test for subscription manager translations
if (pofilterTest.equals("urls") && translationFile.getPath().contains("/ml/")) bugIds.add("828985");
// Bug 828989 - [pt_BR] failed pofilter urls test for subscription-manager translations
if (pofilterTest.equals("urls") && translationFile.getPath().contains("/pt_BR/")) bugIds.add("828989");
// Bug 860088 - [de_DE] translation for a url should not be altered
if (pofilterTest.equals("urls") && translationFile.getPath().contains("/de_DE/")) bugIds.add("860088");
// Bug 845304 - translation of the word "[OPTIONS]" has reverted
if (pofilterTest.equals("unchanged")) bugIds.add("845304");
// Bug 829459 - [bn_IN] failed pofilter unchanged option test for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("829459");
// Bug 829470 - [or] failed pofilter unchanged options for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/or/")) bugIds.add("829470");
// Bug 829471 - [ta_IN] failed pofilter unchanged optioon test for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("829471");
// Bug 829476 - [ml] failed pofilter unchanged option test for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/ml/")) bugIds.add("829476");
// Bug 829479 - [pt_BR] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/pt_BR/")) {bugIds.add("829479"); bugIds.add("828958");}
// Bug 829482 - [zh_TW] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/zh_TW/")) bugIds.add("829482");
// Bug 829483 - [de_DE] failed pofilter unchanged options test for suubscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/de_DE/")) bugIds.add("829483");
// Bug 829486 - [fr] failed pofilter unchanged options test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/fr/")) bugIds.add("829486");
// Bug 829488 - [es_ES] failed pofilter unchanged option tests for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/es_ES/")) bugIds.add("829488");
// Bug 829491 - [it] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/it/")) bugIds.add("829491");
// Bug 829492 - [hi] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/hi/")) bugIds.add("829492");
// Bug 829494 - [zh_CN] failed pofilter unchanged option for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/zh_CN/")) bugIds.add("829494");
// Bug 829495 - [pa] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/pa/")) bugIds.add("829495");
// Bug 840914 - [te] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/te/")) bugIds.add("840914");
// Bug 840644 - [ta_IN] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("840644");
// Bug 855087 - [mr] missing translation for the word "OPTIONS"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/mr/")) bugIds.add("855087");
// Bug 855085 - [as] missing translation for the word "OPTIONS"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/as/")) bugIds.add("855085");
// Bug 855081 - [pt_BR] untranslated msgid "Arch"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/pt_BR/")) bugIds.add("855081");
// Bug 841011 - [kn] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("doublewords") && translationFile.getPath().contains("/kn/")) bugIds.add("841011");
BlockedByBzBug blockedByBzBug = new BlockedByBzBug(bugIds.toArray(new String[]{}));
ll.add(Arrays.asList(new Object[] {blockedByBzBug, pofilterTest, translationFile}));
}
}
|
diff --git a/com.sap.core.odata.processor.core/src/main/java/com/sap/core/odata/processor/core/jpa/ODataExpressionParser.java b/com.sap.core.odata.processor.core/src/main/java/com/sap/core/odata/processor/core/jpa/ODataExpressionParser.java
index dca3ca8b9..ee8605b54 100644
--- a/com.sap.core.odata.processor.core/src/main/java/com/sap/core/odata/processor/core/jpa/ODataExpressionParser.java
+++ b/com.sap.core.odata.processor.core/src/main/java/com/sap/core/odata/processor/core/jpa/ODataExpressionParser.java
@@ -1,350 +1,350 @@
package com.sap.core.odata.processor.core.jpa;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import com.sap.core.odata.api.edm.EdmException;
import com.sap.core.odata.api.edm.EdmLiteralKind;
import com.sap.core.odata.api.edm.EdmMapping;
import com.sap.core.odata.api.edm.EdmProperty;
import com.sap.core.odata.api.edm.EdmSimpleType;
import com.sap.core.odata.api.edm.EdmSimpleTypeException;
import com.sap.core.odata.api.edm.EdmSimpleTypeKind;
import com.sap.core.odata.api.exception.ODataException;
import com.sap.core.odata.api.exception.ODataNotImplementedException;
import com.sap.core.odata.api.uri.KeyPredicate;
import com.sap.core.odata.api.uri.expression.BinaryExpression;
import com.sap.core.odata.api.uri.expression.BinaryOperator;
import com.sap.core.odata.api.uri.expression.CommonExpression;
import com.sap.core.odata.api.uri.expression.ExpressionKind;
import com.sap.core.odata.api.uri.expression.FilterExpression;
import com.sap.core.odata.api.uri.expression.LiteralExpression;
import com.sap.core.odata.api.uri.expression.MemberExpression;
import com.sap.core.odata.api.uri.expression.MethodExpression;
import com.sap.core.odata.api.uri.expression.MethodOperator;
import com.sap.core.odata.api.uri.expression.OrderByExpression;
import com.sap.core.odata.api.uri.expression.OrderExpression;
import com.sap.core.odata.api.uri.expression.PropertyExpression;
import com.sap.core.odata.api.uri.expression.SortOrder;
import com.sap.core.odata.api.uri.expression.UnaryExpression;
import com.sap.core.odata.processor.api.jpa.exception.ODataJPARuntimeException;
import com.sap.core.odata.processor.api.jpa.jpql.JPQLStatement;
/**
* This class contains utility methods for parsing the filter expressions built by core library from user OData Query.
*
* @author SAP AG
*
*/
public class ODataExpressionParser {
public static final String EMPTY = ""; //$NON-NLS-1$
public static Integer methodFlag = 0;
/**
* This method returns the parsed where condition corresponding to the filter input in the user query.
*
* @param whereExpression
*
* @return Parsed where condition String
* @throws ODataException
*/
public static String parseToJPAWhereExpression(final CommonExpression whereExpression, final String tableAlias) throws ODataException {
switch (whereExpression.getKind()) {
case UNARY:
final UnaryExpression unaryExpression = (UnaryExpression) whereExpression;
final String operand = parseToJPAWhereExpression(unaryExpression.getOperand(), tableAlias);
switch (unaryExpression.getOperator()) {
case NOT:
return JPQLStatement.Operator.NOT + "(" + operand + ")"; //$NON-NLS-1$ //$NON-NLS-2$
case MINUS:
if (operand.startsWith("-")) {
return operand.substring(1);
}
else {
return "-" + operand; //$NON-NLS-1$
}
default:
throw new ODataNotImplementedException();
}
case FILTER:
return parseToJPAWhereExpression(((FilterExpression) whereExpression).getExpression(), tableAlias);
case BINARY:
final BinaryExpression binaryExpression = (BinaryExpression) whereExpression;
if ((binaryExpression.getLeftOperand().getKind() == ExpressionKind.METHOD) && ((binaryExpression.getOperator() == BinaryOperator.EQ) || (binaryExpression.getOperator() == BinaryOperator.NE)) && (((MethodExpression) binaryExpression.getLeftOperand()).getMethod() == MethodOperator.SUBSTRINGOF)) {
methodFlag = 1;
}
final String left = parseToJPAWhereExpression(binaryExpression.getLeftOperand(), tableAlias);
final String right = parseToJPAWhereExpression(binaryExpression.getRightOperand(), tableAlias);
switch (binaryExpression.getOperator()) {
case AND:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.AND + JPQLStatement.DELIMITER.SPACE + right;
case OR:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.OR + JPQLStatement.DELIMITER.SPACE + right;
case EQ:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.EQ + JPQLStatement.DELIMITER.SPACE + right;
case NE:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.NE + JPQLStatement.DELIMITER.SPACE + right;
case LT:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.LT + JPQLStatement.DELIMITER.SPACE + right;
case LE:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.LE + JPQLStatement.DELIMITER.SPACE + right;
case GT:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.GT + JPQLStatement.DELIMITER.SPACE + right;
case GE:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.GE + JPQLStatement.DELIMITER.SPACE + right;
case PROPERTY_ACCESS:
throw new ODataNotImplementedException();
default:
throw new ODataNotImplementedException();
}
case PROPERTY:
String returnStr = tableAlias + JPQLStatement.DELIMITER.PERIOD + ((EdmProperty) ((PropertyExpression) whereExpression).getEdmProperty()).getMapping().getInternalName();
return returnStr;
case MEMBER:
String memberExpStr = EMPTY;
int i = 0;
MemberExpression member = null;
CommonExpression tempExp = whereExpression;
while (tempExp != null && tempExp.getKind() == ExpressionKind.MEMBER) {
member = (MemberExpression) tempExp;
if (i > 0) {
memberExpStr = JPQLStatement.DELIMITER.PERIOD + memberExpStr;
}
i++;
memberExpStr = ((EdmProperty) ((PropertyExpression) member.getProperty()).getEdmProperty()).getMapping().getInternalName() + memberExpStr;
tempExp = member.getPath();
}
memberExpStr = ((EdmProperty) ((PropertyExpression) tempExp).getEdmProperty()).getMapping().getInternalName() + JPQLStatement.DELIMITER.PERIOD + memberExpStr;
return tableAlias + JPQLStatement.DELIMITER.PERIOD + memberExpStr;
case LITERAL:
final LiteralExpression literal = (LiteralExpression) whereExpression;
final EdmSimpleType literalType = (EdmSimpleType) literal.getEdmType();
String value = literalType.valueToString(literalType.valueOfString(literal.getUriLiteral(), EdmLiteralKind.URI, null, literalType.getDefaultType()), EdmLiteralKind.DEFAULT, null);
return evaluateComparingExpression(value, literalType);
case METHOD:
final MethodExpression methodExpression = (MethodExpression) whereExpression;
String first = parseToJPAWhereExpression(methodExpression.getParameters().get(0), tableAlias);
final String second = methodExpression.getParameterCount() > 1 ?
parseToJPAWhereExpression(methodExpression.getParameters().get(1), tableAlias) : null;
String third = methodExpression.getParameterCount() > 2 ?
parseToJPAWhereExpression(methodExpression.getParameters().get(2), tableAlias) : null;
switch (methodExpression.getMethod()) {
case SUBSTRING:
third = third != null ? ", " + third : "";
return String.format("SUBSTRING(%s, %s + 1 %s)", first, second, third);
case SUBSTRINGOF:
first = first.substring(1, first.length() - 1);
if (methodFlag == 1) {
methodFlag = 0;
- return String.format("(CASE WHEN %s LIKE '%%%s%%' THEN TRUE ELSE FALSE END)", second, first);
+ return String.format("(CASE WHEN (%s LIKE '%%%s%%') THEN TRUE ELSE FALSE END)", second, first);
}
else {
- return String.format("(CASE WHEN %s LIKE '%%%s%%' THEN TRUE ELSE FALSE END) = true", second, first);
+ return String.format("(CASE WHEN (%s LIKE '%%%s%%') THEN TRUE ELSE FALSE END) = true", second, first);
}
case TOLOWER:
return String.format("LOWER(%s)", first);
default:
throw new ODataNotImplementedException();
}
default:
throw new ODataNotImplementedException();
}
}
/**
* This method parses the select clause
*
* @param tableAlias
* @param selectedFields
* @return
*/
public static String parseToJPASelectExpression(final String tableAlias, final ArrayList<String> selectedFields) {
if ((selectedFields == null) || (selectedFields.size() == 0)) {
return tableAlias;
}
String selectClause = EMPTY;
Iterator<String> itr = selectedFields.iterator();
int count = 0;
while (itr.hasNext()) {
selectClause = selectClause + tableAlias + JPQLStatement.DELIMITER.PERIOD + itr.next();
count++;
if (count < selectedFields.size()) {
selectClause = selectClause + JPQLStatement.DELIMITER.COMMA + JPQLStatement.DELIMITER.SPACE;
}
}
return selectClause;
}
/**
* This method parses the order by condition in the query.
*
* @param orderByExpression
* @return
* @throws ODataJPARuntimeException
*/
public static HashMap<String, String> parseToJPAOrderByExpression(final OrderByExpression orderByExpression, final String tableAlias) throws ODataJPARuntimeException {
HashMap<String, String> orderByMap = new HashMap<String, String>();
if (orderByExpression != null && orderByExpression.getOrders() != null) {
List<OrderExpression> orderBys = orderByExpression.getOrders();
String orderByField = null;
String orderByDirection = null;
for (OrderExpression orderBy : orderBys) {
try {
orderByField = ((EdmProperty) ((PropertyExpression) orderBy.getExpression()).getEdmProperty()).getMapping().getInternalName();
orderByDirection = (orderBy.getSortOrder() == SortOrder.asc) ? EMPTY : "DESC"; //$NON-NLS-1$
orderByMap.put(tableAlias + JPQLStatement.DELIMITER.PERIOD + orderByField, orderByDirection);
} catch (EdmException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.GENERAL.addContent(e
.getMessage()), e);
}
}
}
return orderByMap;
}
/**
* This method evaluated the where expression for read of an entity based on the keys specified in the query.
*
* @param keyPredicates
* @return the evaluated where expression
*/
public static String parseKeyPredicates(final List<KeyPredicate> keyPredicates, final String tableAlias) throws ODataJPARuntimeException {
String literal = null;
String propertyName = null;
EdmSimpleType edmSimpleType = null;
StringBuilder keyFilters = new StringBuilder();
int i = 0;
for (KeyPredicate keyPredicate : keyPredicates) {
if (i > 0) {
keyFilters.append(JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.AND + JPQLStatement.DELIMITER.SPACE);
}
i++;
literal = keyPredicate.getLiteral();
try {
EdmMapping mapping = keyPredicate.getProperty().getMapping();
if (mapping != null)
propertyName = keyPredicate.getProperty().getMapping().getInternalName();
else
propertyName = keyPredicate.getProperty().getName(); // Get external Name
edmSimpleType = (EdmSimpleType) keyPredicate.getProperty().getType();
} catch (EdmException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.GENERAL.addContent(e
.getMessage()), e);
}
literal = evaluateComparingExpression(literal, edmSimpleType);
if (edmSimpleType == EdmSimpleTypeKind.DateTime.getEdmSimpleTypeInstance()
|| edmSimpleType == EdmSimpleTypeKind.DateTimeOffset.getEdmSimpleTypeInstance()) {
literal = literal.substring(literal.indexOf('\''), literal.indexOf('}'));
}
keyFilters.append(tableAlias + JPQLStatement.DELIMITER.PERIOD + propertyName + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.EQ + JPQLStatement.DELIMITER.SPACE + literal);
}
if (keyFilters.length() > 0) {
return keyFilters.toString();
} else {
return null;
}
}
/**
* This method evaluates the expression based on the type instance. Used for adding escape characters where necessary.
*
* @param value
* @param edmSimpleType
* @return the evaluated expression
* @throws ODataJPARuntimeException
*/
private static String evaluateComparingExpression(String value, final EdmSimpleType edmSimpleType) throws ODataJPARuntimeException {
if (edmSimpleType == EdmSimpleTypeKind.String.getEdmSimpleTypeInstance()
|| edmSimpleType == EdmSimpleTypeKind.Guid.getEdmSimpleTypeInstance())
{
value = "\'" + value + "\'"; //$NON-NLS-1$ //$NON-NLS-2$
} else if (edmSimpleType == EdmSimpleTypeKind.DateTime.getEdmSimpleTypeInstance()
|| edmSimpleType == EdmSimpleTypeKind.DateTimeOffset.getEdmSimpleTypeInstance())
{
try {
Calendar datetime = (Calendar) edmSimpleType.valueOfString(value, EdmLiteralKind.DEFAULT, null, edmSimpleType.getDefaultType());
String year = String.format("%04d", datetime.get(Calendar.YEAR));
String month = String.format("%02d", datetime.get(Calendar.MONTH) + 1);
String day = String.format("%02d", datetime.get(Calendar.DAY_OF_MONTH));
String hour = String.format("%02d", datetime.get(Calendar.HOUR_OF_DAY));
String min = String.format("%02d", datetime.get(Calendar.MINUTE));
String sec = String.format("%02d", datetime.get(Calendar.SECOND));
value = JPQLStatement.DELIMITER.LEFT_BRACE + JPQLStatement.KEYWORD.TIMESTAMP + JPQLStatement.DELIMITER.SPACE + "\'" + year + JPQLStatement.DELIMITER.HYPHEN + month + JPQLStatement.DELIMITER.HYPHEN + day + JPQLStatement.DELIMITER.SPACE + hour + JPQLStatement.DELIMITER.COLON + min + JPQLStatement.DELIMITER.COLON + sec + JPQLStatement.KEYWORD.OFFSET + "\'" + JPQLStatement.DELIMITER.RIGHT_BRACE;
} catch (EdmSimpleTypeException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.GENERAL.addContent(e
.getMessage()), e);
}
} else if (edmSimpleType == EdmSimpleTypeKind.Time.getEdmSimpleTypeInstance()) {
try {
Calendar time = (Calendar) edmSimpleType.valueOfString(value, EdmLiteralKind.DEFAULT, null, edmSimpleType.getDefaultType());
String hourValue = String.format("%02d", time.get(Calendar.HOUR_OF_DAY));
String minValue = String.format("%02d", time.get(Calendar.MINUTE));
String secValue = String.format("%02d", time.get(Calendar.SECOND));
value = "\'" + hourValue + JPQLStatement.DELIMITER.COLON + minValue + JPQLStatement.DELIMITER.COLON + secValue + "\'";
} catch (EdmSimpleTypeException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.GENERAL.addContent(e
.getMessage()), e);
}
} else if (edmSimpleType == EdmSimpleTypeKind.Int64.getEdmSimpleTypeInstance()) {
value = value + JPQLStatement.DELIMITER.LONG; //$NON-NLS-1$
}
return value;
}
public static HashMap<String, String> parseKeyPropertiesToJPAOrderByExpression(final List<EdmProperty> edmPropertylist, final String tableAlias) throws ODataJPARuntimeException {
HashMap<String, String> orderByMap = new HashMap<String, String>();
String propertyName = null;
for (EdmProperty edmProperty : edmPropertylist) {
try {
EdmMapping mapping = edmProperty.getMapping();
if (mapping != null && mapping.getInternalName() != null) {
propertyName = mapping.getInternalName();// For embedded/complex keys
} else {
propertyName = edmProperty.getName();
}
} catch (EdmException e) {
throw ODataJPARuntimeException.throwException(
ODataJPARuntimeException.GENERAL.addContent(e
.getMessage()), e);
}
orderByMap.put(tableAlias + JPQLStatement.DELIMITER.PERIOD + propertyName, EMPTY);
}
return orderByMap;
}
}
| false | true | public static String parseToJPAWhereExpression(final CommonExpression whereExpression, final String tableAlias) throws ODataException {
switch (whereExpression.getKind()) {
case UNARY:
final UnaryExpression unaryExpression = (UnaryExpression) whereExpression;
final String operand = parseToJPAWhereExpression(unaryExpression.getOperand(), tableAlias);
switch (unaryExpression.getOperator()) {
case NOT:
return JPQLStatement.Operator.NOT + "(" + operand + ")"; //$NON-NLS-1$ //$NON-NLS-2$
case MINUS:
if (operand.startsWith("-")) {
return operand.substring(1);
}
else {
return "-" + operand; //$NON-NLS-1$
}
default:
throw new ODataNotImplementedException();
}
case FILTER:
return parseToJPAWhereExpression(((FilterExpression) whereExpression).getExpression(), tableAlias);
case BINARY:
final BinaryExpression binaryExpression = (BinaryExpression) whereExpression;
if ((binaryExpression.getLeftOperand().getKind() == ExpressionKind.METHOD) && ((binaryExpression.getOperator() == BinaryOperator.EQ) || (binaryExpression.getOperator() == BinaryOperator.NE)) && (((MethodExpression) binaryExpression.getLeftOperand()).getMethod() == MethodOperator.SUBSTRINGOF)) {
methodFlag = 1;
}
final String left = parseToJPAWhereExpression(binaryExpression.getLeftOperand(), tableAlias);
final String right = parseToJPAWhereExpression(binaryExpression.getRightOperand(), tableAlias);
switch (binaryExpression.getOperator()) {
case AND:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.AND + JPQLStatement.DELIMITER.SPACE + right;
case OR:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.OR + JPQLStatement.DELIMITER.SPACE + right;
case EQ:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.EQ + JPQLStatement.DELIMITER.SPACE + right;
case NE:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.NE + JPQLStatement.DELIMITER.SPACE + right;
case LT:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.LT + JPQLStatement.DELIMITER.SPACE + right;
case LE:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.LE + JPQLStatement.DELIMITER.SPACE + right;
case GT:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.GT + JPQLStatement.DELIMITER.SPACE + right;
case GE:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.GE + JPQLStatement.DELIMITER.SPACE + right;
case PROPERTY_ACCESS:
throw new ODataNotImplementedException();
default:
throw new ODataNotImplementedException();
}
case PROPERTY:
String returnStr = tableAlias + JPQLStatement.DELIMITER.PERIOD + ((EdmProperty) ((PropertyExpression) whereExpression).getEdmProperty()).getMapping().getInternalName();
return returnStr;
case MEMBER:
String memberExpStr = EMPTY;
int i = 0;
MemberExpression member = null;
CommonExpression tempExp = whereExpression;
while (tempExp != null && tempExp.getKind() == ExpressionKind.MEMBER) {
member = (MemberExpression) tempExp;
if (i > 0) {
memberExpStr = JPQLStatement.DELIMITER.PERIOD + memberExpStr;
}
i++;
memberExpStr = ((EdmProperty) ((PropertyExpression) member.getProperty()).getEdmProperty()).getMapping().getInternalName() + memberExpStr;
tempExp = member.getPath();
}
memberExpStr = ((EdmProperty) ((PropertyExpression) tempExp).getEdmProperty()).getMapping().getInternalName() + JPQLStatement.DELIMITER.PERIOD + memberExpStr;
return tableAlias + JPQLStatement.DELIMITER.PERIOD + memberExpStr;
case LITERAL:
final LiteralExpression literal = (LiteralExpression) whereExpression;
final EdmSimpleType literalType = (EdmSimpleType) literal.getEdmType();
String value = literalType.valueToString(literalType.valueOfString(literal.getUriLiteral(), EdmLiteralKind.URI, null, literalType.getDefaultType()), EdmLiteralKind.DEFAULT, null);
return evaluateComparingExpression(value, literalType);
case METHOD:
final MethodExpression methodExpression = (MethodExpression) whereExpression;
String first = parseToJPAWhereExpression(methodExpression.getParameters().get(0), tableAlias);
final String second = methodExpression.getParameterCount() > 1 ?
parseToJPAWhereExpression(methodExpression.getParameters().get(1), tableAlias) : null;
String third = methodExpression.getParameterCount() > 2 ?
parseToJPAWhereExpression(methodExpression.getParameters().get(2), tableAlias) : null;
switch (methodExpression.getMethod()) {
case SUBSTRING:
third = third != null ? ", " + third : "";
return String.format("SUBSTRING(%s, %s + 1 %s)", first, second, third);
case SUBSTRINGOF:
first = first.substring(1, first.length() - 1);
if (methodFlag == 1) {
methodFlag = 0;
return String.format("(CASE WHEN %s LIKE '%%%s%%' THEN TRUE ELSE FALSE END)", second, first);
}
else {
return String.format("(CASE WHEN %s LIKE '%%%s%%' THEN TRUE ELSE FALSE END) = true", second, first);
}
case TOLOWER:
return String.format("LOWER(%s)", first);
default:
throw new ODataNotImplementedException();
}
default:
throw new ODataNotImplementedException();
}
}
| public static String parseToJPAWhereExpression(final CommonExpression whereExpression, final String tableAlias) throws ODataException {
switch (whereExpression.getKind()) {
case UNARY:
final UnaryExpression unaryExpression = (UnaryExpression) whereExpression;
final String operand = parseToJPAWhereExpression(unaryExpression.getOperand(), tableAlias);
switch (unaryExpression.getOperator()) {
case NOT:
return JPQLStatement.Operator.NOT + "(" + operand + ")"; //$NON-NLS-1$ //$NON-NLS-2$
case MINUS:
if (operand.startsWith("-")) {
return operand.substring(1);
}
else {
return "-" + operand; //$NON-NLS-1$
}
default:
throw new ODataNotImplementedException();
}
case FILTER:
return parseToJPAWhereExpression(((FilterExpression) whereExpression).getExpression(), tableAlias);
case BINARY:
final BinaryExpression binaryExpression = (BinaryExpression) whereExpression;
if ((binaryExpression.getLeftOperand().getKind() == ExpressionKind.METHOD) && ((binaryExpression.getOperator() == BinaryOperator.EQ) || (binaryExpression.getOperator() == BinaryOperator.NE)) && (((MethodExpression) binaryExpression.getLeftOperand()).getMethod() == MethodOperator.SUBSTRINGOF)) {
methodFlag = 1;
}
final String left = parseToJPAWhereExpression(binaryExpression.getLeftOperand(), tableAlias);
final String right = parseToJPAWhereExpression(binaryExpression.getRightOperand(), tableAlias);
switch (binaryExpression.getOperator()) {
case AND:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.AND + JPQLStatement.DELIMITER.SPACE + right;
case OR:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.OR + JPQLStatement.DELIMITER.SPACE + right;
case EQ:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.EQ + JPQLStatement.DELIMITER.SPACE + right;
case NE:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.NE + JPQLStatement.DELIMITER.SPACE + right;
case LT:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.LT + JPQLStatement.DELIMITER.SPACE + right;
case LE:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.LE + JPQLStatement.DELIMITER.SPACE + right;
case GT:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.GT + JPQLStatement.DELIMITER.SPACE + right;
case GE:
return left + JPQLStatement.DELIMITER.SPACE + JPQLStatement.Operator.GE + JPQLStatement.DELIMITER.SPACE + right;
case PROPERTY_ACCESS:
throw new ODataNotImplementedException();
default:
throw new ODataNotImplementedException();
}
case PROPERTY:
String returnStr = tableAlias + JPQLStatement.DELIMITER.PERIOD + ((EdmProperty) ((PropertyExpression) whereExpression).getEdmProperty()).getMapping().getInternalName();
return returnStr;
case MEMBER:
String memberExpStr = EMPTY;
int i = 0;
MemberExpression member = null;
CommonExpression tempExp = whereExpression;
while (tempExp != null && tempExp.getKind() == ExpressionKind.MEMBER) {
member = (MemberExpression) tempExp;
if (i > 0) {
memberExpStr = JPQLStatement.DELIMITER.PERIOD + memberExpStr;
}
i++;
memberExpStr = ((EdmProperty) ((PropertyExpression) member.getProperty()).getEdmProperty()).getMapping().getInternalName() + memberExpStr;
tempExp = member.getPath();
}
memberExpStr = ((EdmProperty) ((PropertyExpression) tempExp).getEdmProperty()).getMapping().getInternalName() + JPQLStatement.DELIMITER.PERIOD + memberExpStr;
return tableAlias + JPQLStatement.DELIMITER.PERIOD + memberExpStr;
case LITERAL:
final LiteralExpression literal = (LiteralExpression) whereExpression;
final EdmSimpleType literalType = (EdmSimpleType) literal.getEdmType();
String value = literalType.valueToString(literalType.valueOfString(literal.getUriLiteral(), EdmLiteralKind.URI, null, literalType.getDefaultType()), EdmLiteralKind.DEFAULT, null);
return evaluateComparingExpression(value, literalType);
case METHOD:
final MethodExpression methodExpression = (MethodExpression) whereExpression;
String first = parseToJPAWhereExpression(methodExpression.getParameters().get(0), tableAlias);
final String second = methodExpression.getParameterCount() > 1 ?
parseToJPAWhereExpression(methodExpression.getParameters().get(1), tableAlias) : null;
String third = methodExpression.getParameterCount() > 2 ?
parseToJPAWhereExpression(methodExpression.getParameters().get(2), tableAlias) : null;
switch (methodExpression.getMethod()) {
case SUBSTRING:
third = third != null ? ", " + third : "";
return String.format("SUBSTRING(%s, %s + 1 %s)", first, second, third);
case SUBSTRINGOF:
first = first.substring(1, first.length() - 1);
if (methodFlag == 1) {
methodFlag = 0;
return String.format("(CASE WHEN (%s LIKE '%%%s%%') THEN TRUE ELSE FALSE END)", second, first);
}
else {
return String.format("(CASE WHEN (%s LIKE '%%%s%%') THEN TRUE ELSE FALSE END) = true", second, first);
}
case TOLOWER:
return String.format("LOWER(%s)", first);
default:
throw new ODataNotImplementedException();
}
default:
throw new ODataNotImplementedException();
}
}
|
diff --git a/source/net/yacy/cora/services/federated/solr/SolrScheme.java b/source/net/yacy/cora/services/federated/solr/SolrScheme.java
index a94d0759d..074c0f2eb 100644
--- a/source/net/yacy/cora/services/federated/solr/SolrScheme.java
+++ b/source/net/yacy/cora/services/federated/solr/SolrScheme.java
@@ -1,256 +1,256 @@
/**
* SolrScheme
* Copyright 2011 by Michael Peter Christen
* First released 14.04.2011 at http://yacy.net
*
* $LastChangedDate: 2011-04-14 22:05:04 +0200 (Do, 14 Apr 2011) $
* $LastChangedRevision: 7654 $
* $LastChangedBy: orbiter $
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
*/
package net.yacy.cora.services.federated.solr;
import java.net.InetAddress;
import java.util.Collection;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import net.yacy.cora.document.UTF8;
import net.yacy.cora.protocol.Domains;
import net.yacy.cora.protocol.ResponseHeader;
import net.yacy.document.Document;
import net.yacy.document.parser.html.ContentScraper;
import net.yacy.document.parser.html.ImageEntry;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.cora.document.MultiProtocolURI;
import org.apache.solr.common.SolrInputDocument;
public enum SolrScheme {
SolrCell,
DublinCore;
public SolrInputDocument yacy2solr(String id, ResponseHeader header, Document document) {
if (this == SolrCell) return yacy2solrSolrCell(id, header, document);
return null;
}
public static SolrInputDocument yacy2solrSolrCell(String id, ResponseHeader header, Document yacydoc) {
// we user the SolrCell design as index scheme
SolrInputDocument solrdoc = new SolrInputDocument();
DigestURI digestURI = new DigestURI(yacydoc.dc_source());
solrdoc.addField("id", id);
solrdoc.addField("sku", digestURI.toNormalform(true, false), 3.0f);
InetAddress address = Domains.dnsResolve(digestURI.getHost());
if (address != null) solrdoc.addField("ip_s", address.getHostAddress());
if (digestURI.getHost() != null) solrdoc.addField("host_s", digestURI.getHost());
solrdoc.addField("title", yacydoc.dc_title());
solrdoc.addField("author", yacydoc.dc_creator());
solrdoc.addField("description", yacydoc.dc_description());
solrdoc.addField("content_type", yacydoc.dc_format());
solrdoc.addField("last_modified", header.lastModified());
solrdoc.addField("keywords", yacydoc.dc_subject(' '));
String content = UTF8.String(yacydoc.getTextBytes());
solrdoc.addField("text_t", content);
int contentwc = content.split(" ").length;
solrdoc.addField("wordcount_i", contentwc);
// path elements of link
String path = digestURI.getPath();
if (path != null) {
String[] paths = path.split("/");
if (paths.length > 0) solrdoc.addField("attr_paths", paths);
}
// list all links
Map<MultiProtocolURI, Properties> alllinks = yacydoc.getAnchors();
int c = 0;
String[] inboundlinks = new String[yacydoc.inboundLinkCount()];
solrdoc.addField("inboundlinkscount_i", inboundlinks.length);
for (MultiProtocolURI url: yacydoc.inboundLinks()) {
Properties p = alllinks.get(url);
String name = p.getProperty("name", "");
String rel = p.getProperty("rel", "");
inboundlinks[c++] =
"<a href=\"" + url.toNormalform(false, false) + "\"" +
((rel.toLowerCase().equals("nofollow")) ? " rel=\"nofollow\"" : "") +
">" +
((name.length() > 0) ? name : "") + "</a>";
}
solrdoc.addField("attr_inboundlinks", inboundlinks);
c = 0;
String[] outboundlinks = new String[yacydoc.outboundLinkCount()];
solrdoc.addField("outboundlinkscount_i", outboundlinks.length);
for (MultiProtocolURI url: yacydoc.outboundLinks()) {
Properties p = alllinks.get(url);
String name = p.getProperty("name", "");
String rel = p.getProperty("rel", "");
outboundlinks[c++] =
"<a href=\"" + url.toNormalform(false, false) + "\"" +
((rel.toLowerCase().equals("nofollow")) ? " rel=\"nofollow\"" : "") +
">" +
((name.length() > 0) ? name : "") + "</a>";
}
- solrdoc.addField("attr_outboundlinks", yacydoc.outboundLinks().toArray());
+ solrdoc.addField("attr_outboundlinks", outboundlinks);
// charset
solrdoc.addField("charset_s", yacydoc.getCharset());
// coordinates
if (yacydoc.lat() != 0.0f && yacydoc.lon() != 0.0f) {
solrdoc.addField("lon_coordinate", yacydoc.lon());
solrdoc.addField("lat_coordinate", yacydoc.lat());
}
solrdoc.addField("httpstatus_i", 200);
Object parser = yacydoc.getParserObject();
if (parser instanceof ContentScraper) {
ContentScraper html = (ContentScraper) parser;
// header tags
int h = 0;
int f = 1;
for (int i = 1; i <= 6; i++) {
String[] hs = html.getHeadlines(i);
h = h | (hs.length > 0 ? f : 0);
f = f * 2;
solrdoc.addField("attr_h" + i, hs);
}
solrdoc.addField("htags_i", h);
// meta tags
Map<String, String> metas = html.getMetas();
String robots = metas.get("robots");
if (robots != null) solrdoc.addField("metarobots_t", robots);
String generator = metas.get("generator");
if (generator != null) solrdoc.addField("metagenerator_t", generator);
// bold, italic
String[] bold = html.getBold();
solrdoc.addField("boldcount_i", bold.length);
if (bold.length > 0) {
solrdoc.addField("attr_bold", bold);
solrdoc.addField("attr_boldcount", html.getBoldCount(bold));
}
String[] italic = html.getItalic();
solrdoc.addField("italiccount_i", italic.length);
if (italic.length > 0) {
solrdoc.addField("attr_italic", italic);
solrdoc.addField("attr_italiccount", html.getItalicCount(italic));
}
String[] li = html.getLi();
solrdoc.addField("licount_i", li.length);
if (li.length > 0) solrdoc.addField("attr_li", li);
// images
Collection<ImageEntry> imagesc = html.getImages().values();
String[] images = new String[imagesc.size()];
c = 0;
for (ImageEntry ie: imagesc) images[c++] = ie.toString();
solrdoc.addField("imagescount_i", images.length);
if (images.length > 0) solrdoc.addField("attr_images", images);
// style sheets
Map<MultiProtocolURI, String> csss = html.getCSS();
String[] css = new String[csss.size()];
c = 0;
for (Map.Entry<MultiProtocolURI, String> entry: csss.entrySet()) {
css[c++] =
"<link rel=\"stylesheet\" type=\"text/css\" media=\"" + entry.getValue() + "\"" +
" href=\""+ entry.getKey().toNormalform(false, false, false, false) + "\" />";
}
solrdoc.addField("csscount_i", css.length);
if (css.length > 0) solrdoc.addField("attr_css", css);
// Scripts
Set<MultiProtocolURI> scriptss = html.getScript();
String[] scripts = new String[scriptss.size()];
c = 0;
for (MultiProtocolURI url: scriptss) {
scripts[c++] = url.toNormalform(false, false, false, false);
}
solrdoc.addField("scriptscount_i", scripts.length);
if (scripts.length > 0) solrdoc.addField("attr_scripts", scripts);
// Frames
Set<MultiProtocolURI> framess = html.getFrames();
String[] frames = new String[framess.size()];
c = 0;
for (MultiProtocolURI entry: framess) {
frames[c++] = entry.toNormalform(false, false, false, false);
}
solrdoc.addField("framesscount_i", frames.length);
if (frames.length > 0) solrdoc.addField("attr_frames", frames);
// IFrames
Set<MultiProtocolURI> iframess = html.getFrames();
String[] iframes = new String[iframess.size()];
c = 0;
for (MultiProtocolURI entry: iframess) {
iframes[c++] = entry.toNormalform(false, false, false, false);
}
solrdoc.addField("iframesscount_i", iframes.length);
if (iframes.length > 0) solrdoc.addField("attr_iframes", iframes);
// flash embedded
solrdoc.addField("flash_b", html.containsFlash());
// generic evaluation pattern
for (String model: html.getEvaluationModelNames()) {
String[] scorenames = html.getEvaluationModelScoreNames(model);
if (scorenames.length > 0) {
solrdoc.addField("attr_" + model, scorenames);
solrdoc.addField("attr_" + model + "count", html.getEvaluationModelScoreCounts(model, scorenames));
}
}
}
return solrdoc;
}
/*
* standard solr scheme
<field name="name" type="textgen" indexed="true" stored="true"/>
<field name="cat" type="string" indexed="true" stored="true" multiValued="true"/>
<field name="features" type="text" indexed="true" stored="true" multiValued="true"/>
<field name="includes" type="text" indexed="true" stored="true" termVectors="true" termPositions="true" termOffsets="true" />
<field name="weight" type="float" indexed="true" stored="true"/>
<field name="price" type="float" indexed="true" stored="true"/>
<field name="popularity" type="int" indexed="true" stored="true" />
<!-- Common metadata fields, named specifically to match up with
SolrCell metadata when parsing rich documents such as Word, PDF.
Some fields are multiValued only because Tika currently may return
multiple values for them.
-->
<field name="title" type="text" indexed="true" stored="true" multiValued="true"/>
<field name="subject" type="text" indexed="true" stored="true"/>
<field name="description" type="text" indexed="true" stored="true"/>
<field name="comments" type="text" indexed="true" stored="true"/>
<field name="author" type="textgen" indexed="true" stored="true"/>
<field name="keywords" type="textgen" indexed="true" stored="true"/>
<field name="category" type="textgen" indexed="true" stored="true"/>
<field name="content_type" type="string" indexed="true" stored="true" multiValued="true"/>
<field name="last_modified" type="date" indexed="true" stored="true"/>
<field name="links" type="string" indexed="true" stored="true" multiValued="true"/>
*/
}
| true | true | public static SolrInputDocument yacy2solrSolrCell(String id, ResponseHeader header, Document yacydoc) {
// we user the SolrCell design as index scheme
SolrInputDocument solrdoc = new SolrInputDocument();
DigestURI digestURI = new DigestURI(yacydoc.dc_source());
solrdoc.addField("id", id);
solrdoc.addField("sku", digestURI.toNormalform(true, false), 3.0f);
InetAddress address = Domains.dnsResolve(digestURI.getHost());
if (address != null) solrdoc.addField("ip_s", address.getHostAddress());
if (digestURI.getHost() != null) solrdoc.addField("host_s", digestURI.getHost());
solrdoc.addField("title", yacydoc.dc_title());
solrdoc.addField("author", yacydoc.dc_creator());
solrdoc.addField("description", yacydoc.dc_description());
solrdoc.addField("content_type", yacydoc.dc_format());
solrdoc.addField("last_modified", header.lastModified());
solrdoc.addField("keywords", yacydoc.dc_subject(' '));
String content = UTF8.String(yacydoc.getTextBytes());
solrdoc.addField("text_t", content);
int contentwc = content.split(" ").length;
solrdoc.addField("wordcount_i", contentwc);
// path elements of link
String path = digestURI.getPath();
if (path != null) {
String[] paths = path.split("/");
if (paths.length > 0) solrdoc.addField("attr_paths", paths);
}
// list all links
Map<MultiProtocolURI, Properties> alllinks = yacydoc.getAnchors();
int c = 0;
String[] inboundlinks = new String[yacydoc.inboundLinkCount()];
solrdoc.addField("inboundlinkscount_i", inboundlinks.length);
for (MultiProtocolURI url: yacydoc.inboundLinks()) {
Properties p = alllinks.get(url);
String name = p.getProperty("name", "");
String rel = p.getProperty("rel", "");
inboundlinks[c++] =
"<a href=\"" + url.toNormalform(false, false) + "\"" +
((rel.toLowerCase().equals("nofollow")) ? " rel=\"nofollow\"" : "") +
">" +
((name.length() > 0) ? name : "") + "</a>";
}
solrdoc.addField("attr_inboundlinks", inboundlinks);
c = 0;
String[] outboundlinks = new String[yacydoc.outboundLinkCount()];
solrdoc.addField("outboundlinkscount_i", outboundlinks.length);
for (MultiProtocolURI url: yacydoc.outboundLinks()) {
Properties p = alllinks.get(url);
String name = p.getProperty("name", "");
String rel = p.getProperty("rel", "");
outboundlinks[c++] =
"<a href=\"" + url.toNormalform(false, false) + "\"" +
((rel.toLowerCase().equals("nofollow")) ? " rel=\"nofollow\"" : "") +
">" +
((name.length() > 0) ? name : "") + "</a>";
}
solrdoc.addField("attr_outboundlinks", yacydoc.outboundLinks().toArray());
// charset
solrdoc.addField("charset_s", yacydoc.getCharset());
// coordinates
if (yacydoc.lat() != 0.0f && yacydoc.lon() != 0.0f) {
solrdoc.addField("lon_coordinate", yacydoc.lon());
solrdoc.addField("lat_coordinate", yacydoc.lat());
}
solrdoc.addField("httpstatus_i", 200);
Object parser = yacydoc.getParserObject();
if (parser instanceof ContentScraper) {
ContentScraper html = (ContentScraper) parser;
// header tags
int h = 0;
int f = 1;
for (int i = 1; i <= 6; i++) {
String[] hs = html.getHeadlines(i);
h = h | (hs.length > 0 ? f : 0);
f = f * 2;
solrdoc.addField("attr_h" + i, hs);
}
solrdoc.addField("htags_i", h);
// meta tags
Map<String, String> metas = html.getMetas();
String robots = metas.get("robots");
if (robots != null) solrdoc.addField("metarobots_t", robots);
String generator = metas.get("generator");
if (generator != null) solrdoc.addField("metagenerator_t", generator);
// bold, italic
String[] bold = html.getBold();
solrdoc.addField("boldcount_i", bold.length);
if (bold.length > 0) {
solrdoc.addField("attr_bold", bold);
solrdoc.addField("attr_boldcount", html.getBoldCount(bold));
}
String[] italic = html.getItalic();
solrdoc.addField("italiccount_i", italic.length);
if (italic.length > 0) {
solrdoc.addField("attr_italic", italic);
solrdoc.addField("attr_italiccount", html.getItalicCount(italic));
}
String[] li = html.getLi();
solrdoc.addField("licount_i", li.length);
if (li.length > 0) solrdoc.addField("attr_li", li);
// images
Collection<ImageEntry> imagesc = html.getImages().values();
String[] images = new String[imagesc.size()];
c = 0;
for (ImageEntry ie: imagesc) images[c++] = ie.toString();
solrdoc.addField("imagescount_i", images.length);
if (images.length > 0) solrdoc.addField("attr_images", images);
// style sheets
Map<MultiProtocolURI, String> csss = html.getCSS();
String[] css = new String[csss.size()];
c = 0;
for (Map.Entry<MultiProtocolURI, String> entry: csss.entrySet()) {
css[c++] =
"<link rel=\"stylesheet\" type=\"text/css\" media=\"" + entry.getValue() + "\"" +
" href=\""+ entry.getKey().toNormalform(false, false, false, false) + "\" />";
}
solrdoc.addField("csscount_i", css.length);
if (css.length > 0) solrdoc.addField("attr_css", css);
// Scripts
Set<MultiProtocolURI> scriptss = html.getScript();
String[] scripts = new String[scriptss.size()];
c = 0;
for (MultiProtocolURI url: scriptss) {
scripts[c++] = url.toNormalform(false, false, false, false);
}
solrdoc.addField("scriptscount_i", scripts.length);
if (scripts.length > 0) solrdoc.addField("attr_scripts", scripts);
// Frames
Set<MultiProtocolURI> framess = html.getFrames();
String[] frames = new String[framess.size()];
c = 0;
for (MultiProtocolURI entry: framess) {
frames[c++] = entry.toNormalform(false, false, false, false);
}
solrdoc.addField("framesscount_i", frames.length);
if (frames.length > 0) solrdoc.addField("attr_frames", frames);
// IFrames
Set<MultiProtocolURI> iframess = html.getFrames();
String[] iframes = new String[iframess.size()];
c = 0;
for (MultiProtocolURI entry: iframess) {
iframes[c++] = entry.toNormalform(false, false, false, false);
}
solrdoc.addField("iframesscount_i", iframes.length);
if (iframes.length > 0) solrdoc.addField("attr_iframes", iframes);
// flash embedded
solrdoc.addField("flash_b", html.containsFlash());
// generic evaluation pattern
for (String model: html.getEvaluationModelNames()) {
String[] scorenames = html.getEvaluationModelScoreNames(model);
if (scorenames.length > 0) {
solrdoc.addField("attr_" + model, scorenames);
solrdoc.addField("attr_" + model + "count", html.getEvaluationModelScoreCounts(model, scorenames));
}
}
}
return solrdoc;
}
| public static SolrInputDocument yacy2solrSolrCell(String id, ResponseHeader header, Document yacydoc) {
// we user the SolrCell design as index scheme
SolrInputDocument solrdoc = new SolrInputDocument();
DigestURI digestURI = new DigestURI(yacydoc.dc_source());
solrdoc.addField("id", id);
solrdoc.addField("sku", digestURI.toNormalform(true, false), 3.0f);
InetAddress address = Domains.dnsResolve(digestURI.getHost());
if (address != null) solrdoc.addField("ip_s", address.getHostAddress());
if (digestURI.getHost() != null) solrdoc.addField("host_s", digestURI.getHost());
solrdoc.addField("title", yacydoc.dc_title());
solrdoc.addField("author", yacydoc.dc_creator());
solrdoc.addField("description", yacydoc.dc_description());
solrdoc.addField("content_type", yacydoc.dc_format());
solrdoc.addField("last_modified", header.lastModified());
solrdoc.addField("keywords", yacydoc.dc_subject(' '));
String content = UTF8.String(yacydoc.getTextBytes());
solrdoc.addField("text_t", content);
int contentwc = content.split(" ").length;
solrdoc.addField("wordcount_i", contentwc);
// path elements of link
String path = digestURI.getPath();
if (path != null) {
String[] paths = path.split("/");
if (paths.length > 0) solrdoc.addField("attr_paths", paths);
}
// list all links
Map<MultiProtocolURI, Properties> alllinks = yacydoc.getAnchors();
int c = 0;
String[] inboundlinks = new String[yacydoc.inboundLinkCount()];
solrdoc.addField("inboundlinkscount_i", inboundlinks.length);
for (MultiProtocolURI url: yacydoc.inboundLinks()) {
Properties p = alllinks.get(url);
String name = p.getProperty("name", "");
String rel = p.getProperty("rel", "");
inboundlinks[c++] =
"<a href=\"" + url.toNormalform(false, false) + "\"" +
((rel.toLowerCase().equals("nofollow")) ? " rel=\"nofollow\"" : "") +
">" +
((name.length() > 0) ? name : "") + "</a>";
}
solrdoc.addField("attr_inboundlinks", inboundlinks);
c = 0;
String[] outboundlinks = new String[yacydoc.outboundLinkCount()];
solrdoc.addField("outboundlinkscount_i", outboundlinks.length);
for (MultiProtocolURI url: yacydoc.outboundLinks()) {
Properties p = alllinks.get(url);
String name = p.getProperty("name", "");
String rel = p.getProperty("rel", "");
outboundlinks[c++] =
"<a href=\"" + url.toNormalform(false, false) + "\"" +
((rel.toLowerCase().equals("nofollow")) ? " rel=\"nofollow\"" : "") +
">" +
((name.length() > 0) ? name : "") + "</a>";
}
solrdoc.addField("attr_outboundlinks", outboundlinks);
// charset
solrdoc.addField("charset_s", yacydoc.getCharset());
// coordinates
if (yacydoc.lat() != 0.0f && yacydoc.lon() != 0.0f) {
solrdoc.addField("lon_coordinate", yacydoc.lon());
solrdoc.addField("lat_coordinate", yacydoc.lat());
}
solrdoc.addField("httpstatus_i", 200);
Object parser = yacydoc.getParserObject();
if (parser instanceof ContentScraper) {
ContentScraper html = (ContentScraper) parser;
// header tags
int h = 0;
int f = 1;
for (int i = 1; i <= 6; i++) {
String[] hs = html.getHeadlines(i);
h = h | (hs.length > 0 ? f : 0);
f = f * 2;
solrdoc.addField("attr_h" + i, hs);
}
solrdoc.addField("htags_i", h);
// meta tags
Map<String, String> metas = html.getMetas();
String robots = metas.get("robots");
if (robots != null) solrdoc.addField("metarobots_t", robots);
String generator = metas.get("generator");
if (generator != null) solrdoc.addField("metagenerator_t", generator);
// bold, italic
String[] bold = html.getBold();
solrdoc.addField("boldcount_i", bold.length);
if (bold.length > 0) {
solrdoc.addField("attr_bold", bold);
solrdoc.addField("attr_boldcount", html.getBoldCount(bold));
}
String[] italic = html.getItalic();
solrdoc.addField("italiccount_i", italic.length);
if (italic.length > 0) {
solrdoc.addField("attr_italic", italic);
solrdoc.addField("attr_italiccount", html.getItalicCount(italic));
}
String[] li = html.getLi();
solrdoc.addField("licount_i", li.length);
if (li.length > 0) solrdoc.addField("attr_li", li);
// images
Collection<ImageEntry> imagesc = html.getImages().values();
String[] images = new String[imagesc.size()];
c = 0;
for (ImageEntry ie: imagesc) images[c++] = ie.toString();
solrdoc.addField("imagescount_i", images.length);
if (images.length > 0) solrdoc.addField("attr_images", images);
// style sheets
Map<MultiProtocolURI, String> csss = html.getCSS();
String[] css = new String[csss.size()];
c = 0;
for (Map.Entry<MultiProtocolURI, String> entry: csss.entrySet()) {
css[c++] =
"<link rel=\"stylesheet\" type=\"text/css\" media=\"" + entry.getValue() + "\"" +
" href=\""+ entry.getKey().toNormalform(false, false, false, false) + "\" />";
}
solrdoc.addField("csscount_i", css.length);
if (css.length > 0) solrdoc.addField("attr_css", css);
// Scripts
Set<MultiProtocolURI> scriptss = html.getScript();
String[] scripts = new String[scriptss.size()];
c = 0;
for (MultiProtocolURI url: scriptss) {
scripts[c++] = url.toNormalform(false, false, false, false);
}
solrdoc.addField("scriptscount_i", scripts.length);
if (scripts.length > 0) solrdoc.addField("attr_scripts", scripts);
// Frames
Set<MultiProtocolURI> framess = html.getFrames();
String[] frames = new String[framess.size()];
c = 0;
for (MultiProtocolURI entry: framess) {
frames[c++] = entry.toNormalform(false, false, false, false);
}
solrdoc.addField("framesscount_i", frames.length);
if (frames.length > 0) solrdoc.addField("attr_frames", frames);
// IFrames
Set<MultiProtocolURI> iframess = html.getFrames();
String[] iframes = new String[iframess.size()];
c = 0;
for (MultiProtocolURI entry: iframess) {
iframes[c++] = entry.toNormalform(false, false, false, false);
}
solrdoc.addField("iframesscount_i", iframes.length);
if (iframes.length > 0) solrdoc.addField("attr_iframes", iframes);
// flash embedded
solrdoc.addField("flash_b", html.containsFlash());
// generic evaluation pattern
for (String model: html.getEvaluationModelNames()) {
String[] scorenames = html.getEvaluationModelScoreNames(model);
if (scorenames.length > 0) {
solrdoc.addField("attr_" + model, scorenames);
solrdoc.addField("attr_" + model + "count", html.getEvaluationModelScoreCounts(model, scorenames));
}
}
}
return solrdoc;
}
|
diff --git a/vo/src/main/uk/ac/starlink/vo/ResourceTableModel.java b/vo/src/main/uk/ac/starlink/vo/ResourceTableModel.java
index 4124b53f4..0847e9ee1 100644
--- a/vo/src/main/uk/ac/starlink/vo/ResourceTableModel.java
+++ b/vo/src/main/uk/ac/starlink/vo/ResourceTableModel.java
@@ -1,113 +1,114 @@
package uk.ac.starlink.vo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import uk.ac.starlink.util.gui.ArrayTableColumn;
import uk.ac.starlink.util.gui.ArrayTableModel;
/**
* TableModel in which each row represents a {@link RegResource}.
*
* @author Mark Taylor
* @since 18 Dec 2008
*/
public class ResourceTableModel extends ArrayTableModel {
/**
* Constructs a ResourceTableModel with no AccessRef column.
*/
public ResourceTableModel() {
this( false );
}
/**
* Constructs a ResourceTableModel with an optional AccessRef column.
* This is a bit problematic - there is not a formal 1:1 relationship
* between RegResources, which is what are displayed per-row in
* this table, and RegCapabilityInterfaces, which are what host
* AccessRefs (a.k.a. Service URLs). In many cases however, the
* relationship is in fact 1:1.
* If <code>includeAcref</code> is set true, a column is added for
* this information, and it's populated only in the cases where
* a 1:1 relationship does actually hold.
*
* @param includeAcref true if the access ref column is to be included
*/
public ResourceTableModel( boolean includeAcref ) {
super();
List colList = new ArrayList( Arrays.asList( new ArrayTableColumn[] {
new ArrayTableColumn( "shortName", String.class ) {
public Object getValue( Object item ) {
return getResource( item ).getShortName();
}
},
new ArrayTableColumn( "title", String.class ) {
public Object getValue( Object item ) {
return getResource( item ).getTitle();
}
},
new ArrayTableColumn( "identifier", String.class ) {
public Object getValue( Object item ) {
return getResource( item ).getIdentifier();
}
},
new ArrayTableColumn( "publisher", String.class ) {
public Object getValue( Object item ) {
return getResource( item ).getIdentifier();
}
},
new ArrayTableColumn( "contact", String.class ) {
public Object getValue( Object item ) {
return getResource( item ).getContact();
}
},
new ArrayTableColumn( "refURL", String.class ) {
public Object getValue( Object item ) {
return getResource( item ).getReferenceUrl();
}
},
} ) );
if ( includeAcref ) {
colList.add( new ArrayTableColumn( "soleAccessURL", String.class ) {
public Object getValue( Object item ) {
RegCapabilityInterface[] caps =
getResource( item ).getCapabilities();
return ( caps != null && caps.length == 1 )
? caps[ 0 ].getAccessUrl()
: null;
}
} );
}
setColumns( (ArrayTableColumn[])
colList.toArray( new ArrayTableColumn[ 0 ] ) );
+ setItems( new RegResource[ 0 ] );
}
/**
* Sets the data for this table.
*
* @param resources resource array
*/
public void setResources( RegResource[] resources ) {
super.setItems( resources );
}
/**
* Returns the data array for this table.
*
* @return resource array
*/
public RegResource[] getResources() {
return (RegResource[]) super.getItems();
}
/**
* Returns the RegResource object corresponding to a given row item.
*
* @param row data object
* @return resource
*/
private RegResource getResource( Object item ) {
return (RegResource) item;
}
}
| true | true | public ResourceTableModel( boolean includeAcref ) {
super();
List colList = new ArrayList( Arrays.asList( new ArrayTableColumn[] {
new ArrayTableColumn( "shortName", String.class ) {
public Object getValue( Object item ) {
return getResource( item ).getShortName();
}
},
new ArrayTableColumn( "title", String.class ) {
public Object getValue( Object item ) {
return getResource( item ).getTitle();
}
},
new ArrayTableColumn( "identifier", String.class ) {
public Object getValue( Object item ) {
return getResource( item ).getIdentifier();
}
},
new ArrayTableColumn( "publisher", String.class ) {
public Object getValue( Object item ) {
return getResource( item ).getIdentifier();
}
},
new ArrayTableColumn( "contact", String.class ) {
public Object getValue( Object item ) {
return getResource( item ).getContact();
}
},
new ArrayTableColumn( "refURL", String.class ) {
public Object getValue( Object item ) {
return getResource( item ).getReferenceUrl();
}
},
} ) );
if ( includeAcref ) {
colList.add( new ArrayTableColumn( "soleAccessURL", String.class ) {
public Object getValue( Object item ) {
RegCapabilityInterface[] caps =
getResource( item ).getCapabilities();
return ( caps != null && caps.length == 1 )
? caps[ 0 ].getAccessUrl()
: null;
}
} );
}
setColumns( (ArrayTableColumn[])
colList.toArray( new ArrayTableColumn[ 0 ] ) );
}
| public ResourceTableModel( boolean includeAcref ) {
super();
List colList = new ArrayList( Arrays.asList( new ArrayTableColumn[] {
new ArrayTableColumn( "shortName", String.class ) {
public Object getValue( Object item ) {
return getResource( item ).getShortName();
}
},
new ArrayTableColumn( "title", String.class ) {
public Object getValue( Object item ) {
return getResource( item ).getTitle();
}
},
new ArrayTableColumn( "identifier", String.class ) {
public Object getValue( Object item ) {
return getResource( item ).getIdentifier();
}
},
new ArrayTableColumn( "publisher", String.class ) {
public Object getValue( Object item ) {
return getResource( item ).getIdentifier();
}
},
new ArrayTableColumn( "contact", String.class ) {
public Object getValue( Object item ) {
return getResource( item ).getContact();
}
},
new ArrayTableColumn( "refURL", String.class ) {
public Object getValue( Object item ) {
return getResource( item ).getReferenceUrl();
}
},
} ) );
if ( includeAcref ) {
colList.add( new ArrayTableColumn( "soleAccessURL", String.class ) {
public Object getValue( Object item ) {
RegCapabilityInterface[] caps =
getResource( item ).getCapabilities();
return ( caps != null && caps.length == 1 )
? caps[ 0 ].getAccessUrl()
: null;
}
} );
}
setColumns( (ArrayTableColumn[])
colList.toArray( new ArrayTableColumn[ 0 ] ) );
setItems( new RegResource[ 0 ] );
}
|
diff --git a/src/smarthouse/simulation/SimulationFrame.java b/src/smarthouse/simulation/SimulationFrame.java
index e82de36..1b6e60f 100644
--- a/src/smarthouse/simulation/SimulationFrame.java
+++ b/src/smarthouse/simulation/SimulationFrame.java
@@ -1,377 +1,377 @@
package smarthouse.simulation;
import jade.gui.GuiEvent;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.Timer;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import Data.Constants;
public class SimulationFrame extends JFrame {
private SimulationAgent myAgent;
private HashMap<String, Room> rooms = new HashMap<String, Room>();
private HashMap<String, ImageIcon> cachedIcons = new HashMap<String, ImageIcon>();
private int[] currentTime = {7, 0};
private int currentDay = 0;
private boolean dayTime = false;
private Timer timer;
private JTextField time;
private JLabel day;
private JTextArea logs;
private JSlider livingroomTempSlider;
private JLabel livingroomTempThreshold;
private JSlider kitchenTempSlider;
private JLabel kitchenTempThreshold;
private JSlider bedroomTempSlider;
private JLabel bedroomTempThreshold;
private boolean running = false;
public SimulationFrame(SimulationAgent agent) {
super();
setSize(1024, 600);
setTitle("Smarthouse");
myAgent = agent;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
String startTemp = null;
try {
startTemp = new String(String.format("%.1f°C", Constants.INITIAL_TEMP).getBytes(), "UTF-8");
} catch (UnsupportedEncodingException e1) {
startTemp = String.format("%.1f C", Constants.INITIAL_TEMP);
}
/* Cached Images */
cachedIcons.put("play", new ImageIcon("icons/play.png"));
cachedIcons.put("stop", new ImageIcon("icons/stop.png"));
cachedIcons.put("fastforward", new ImageIcon("icons/fastforward.png"));
/* Rooms creation */
Room livingroom = new Room(320, 480, Color.GREEN);
Room kitchen = new Room(320, 240, Color.RED);
Room bedroom = new Room(320, 240, Color.BLUE);
rooms.put(Constants.PLACE_LIVINGROOM, livingroom);
rooms.put(Constants.PLACE_KITCHEN, kitchen);
rooms.put(Constants.PLACE_BEDROOM, bedroom);
livingroom.setLocation(10, 10);
kitchen.setLocation(330, 10);
bedroom.setLocation(330, 250);
getContentPane().add(livingroom);
getContentPane().add(kitchen);
getContentPane().add(bedroom);
/* Living room's furniture */
livingroom.addLight(6, 6, 10);
livingroom.addLight(155, 235, 10);
livingroom.addShutter(0, 100, 40, true);
livingroom.addShutter(0, 340, 40, true);
livingroom.addWindow(5, 100, 40, true);
livingroom.addWindow(5, 340, 40, true);
livingroom.addHeater(140, 10, 40, false);
livingroom.addHeater(140, 459, 40, false);
/* Kitchen's furniture */
kitchen.addLight(155, 115, 10);
kitchen.addShutter(315, 100, 40, true);
kitchen.addWindow(310, 100, 40, true);
kitchen.addHeater(140, 219, 40, false);
/* Bedroom's furniture */
bedroom.addLight(300, 85, 10);
bedroom.addLight(300, 135, 10);
bedroom.addShutter(140, 235, 40, false);
bedroom.addWindow(140, 230, 40, false);
bedroom.addHeater(140, 10, 40, false);
/* Time UI */
time = new JTextField("7:00",5);
JLabel timeLabel = new JLabel("time:");
day = new JLabel("Monday");
JButton pause = new JButton(cachedIcons.get("play"));
JButton forward = new JButton(cachedIcons.get("fastforward"));
time.setSize(40, 20);
timeLabel.setSize(40, 20);
day.setSize(70, 20);
pause.setSize(20, 20);
forward.setSize(20, 20);
time.setLocation(50, 500);
timeLabel.setLocation(10, 500);
day.setLocation(100, 500);
pause.setLocation(10, 530);
forward.setLocation(40, 530);
getContentPane().add(time);
getContentPane().add(timeLabel);
getContentPane().add(day);
getContentPane().add(pause);
getContentPane().add(forward);
/* Living room UI */
JPanel livingroomPanel = new JPanel();
livingroomPanel.setLayout(null);
livingroomPanel.setBorder(BorderFactory.createTitledBorder("Living room"));
livingroomPanel.setSize(145, 70);
livingroomPanel.setLocation(190, 495);
getContentPane().add(livingroomPanel);
JLabel livingroomTemp = new JLabel(startTemp);
livingroomTemp.setSize(50, 20);
livingroomTemp.setLocation(20, 15);
livingroomPanel.add(livingroomTemp);
livingroom.addThermometer(livingroomTemp);
livingroomTempSlider = new JSlider(JSlider.HORIZONTAL, 10, 30, 18);
livingroomTempSlider.setSize(115, 20);
livingroomTempSlider.setLocation(15, 40);
livingroomPanel.add(livingroomTempSlider);
- livingroomTempThreshold = new JLabel("18.0°C");
+ livingroomTempThreshold = new JLabel(startTemp);
livingroomTempThreshold.setSize(50, 20);
livingroomTempThreshold.setLocation(80, 15);
livingroomPanel.add(livingroomTempThreshold);
/* Kitchen UI */
JPanel kitchenPanel = new JPanel();
kitchenPanel.setLayout(null);
kitchenPanel.setBorder(BorderFactory.createTitledBorder("Kitchen"));
kitchenPanel.setSize(145, 70);
kitchenPanel.setLocation(345, 495);
getContentPane().add(kitchenPanel);
JLabel kitchenTemp = new JLabel(startTemp);
kitchenTemp.setSize(50, 20);
kitchenTemp.setLocation(20, 15);
kitchenPanel.add(kitchenTemp);
kitchen.addThermometer(kitchenTemp);
kitchenTempSlider = new JSlider(JSlider.HORIZONTAL, 10, 30, 18);
kitchenTempSlider.setSize(115, 20);
kitchenTempSlider.setLocation(15, 40);
kitchenPanel.add(kitchenTempSlider);
- kitchenTempThreshold = new JLabel("18.0°C");
+ kitchenTempThreshold = new JLabel(startTemp);
kitchenTempThreshold.setSize(50, 20);
kitchenTempThreshold.setLocation(80, 15);
kitchenPanel.add(kitchenTempThreshold);
/* Bedroom UI */
JPanel bedroomPanel = new JPanel();
bedroomPanel.setLayout(null);
bedroomPanel.setBorder(BorderFactory.createTitledBorder("Bedroom"));
bedroomPanel.setSize(145, 70);
bedroomPanel.setLocation(500, 495);
getContentPane().add(bedroomPanel);
JLabel bedroomTemp = new JLabel(startTemp);
bedroomTemp.setSize(50, 20);
bedroomTemp.setLocation(20, 15);
bedroomPanel.add(bedroomTemp);
bedroom.addThermometer(bedroomTemp);
bedroomTempSlider = new JSlider(JSlider.HORIZONTAL, 10, 30, 18);
bedroomTempSlider.setSize(115, 20);
bedroomTempSlider.setLocation(15, 40);
bedroomPanel.add(bedroomTempSlider);
- bedroomTempThreshold = new JLabel("18.0°C");
+ bedroomTempThreshold = new JLabel(startTemp);
bedroomTempThreshold.setSize(50, 20);
bedroomTempThreshold.setLocation(80, 15);
bedroomPanel.add(bedroomTempThreshold);
/* Logs */
logs = new JTextArea();
logs.setEditable(false);
logs.setLineWrap(true);
logs.setWrapStyleWord(true);
JScrollPane scrollLog = new JScrollPane(logs);
scrollLog.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );
scrollLog.setSize(349, 547);
scrollLog.setLocation(660, 15);
getContentPane().add(scrollLog);
/* Timer */
timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
addTime(0, 0, 1);
}
});
timer.setInitialDelay(0);
timer.setRepeats(true);
/* Actions */
time.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() != KeyEvent.VK_ENTER) {
return;
}
String time = ((JTextField) e.getSource()).getText();
int hours = Integer.parseInt(time.split(":")[0]);
int minutes = Integer.parseInt(time.split(":")[1]);
setTime(0, hours, minutes);
}
});
pause.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (running) {
((JButton) e.getSource()).setIcon(cachedIcons.get("play"));
timer.stop();
} else {
((JButton) e.getSource()).setIcon(cachedIcons.get("stop"));
timer.start();
}
running = !running;
}
});
forward.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
timer.stop();
timer.setDelay(50);
timer.start();
}
public void mouseReleased(MouseEvent e) {
timer.stop();
timer.setDelay(1000);
if (running) {
timer.start();
}
}
});
livingroomTempSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
double threshold = livingroomTempSlider.getValue();
rooms.get("livingroom").setTempThreshold(threshold);
try {
livingroomTempThreshold.setText(new String(String.format("%.1f°C", threshold).getBytes(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
livingroomTempThreshold.setText(String.format("%.1f C", threshold));
}
}
});
kitchenTempSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
double threshold = kitchenTempSlider.getValue();
rooms.get("kitchen").setTempThreshold(threshold);
try {
kitchenTempThreshold.setText(new String(String.format("%.1f°C", threshold).getBytes(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
kitchenTempThreshold.setText(String.format("%.1f C", threshold));
}
}
});
bedroomTempSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
double threshold = bedroomTempSlider.getValue();
rooms.get("bedroom").setTempThreshold(threshold);
try {
bedroomTempThreshold.setText(new String(String.format("%.1f°C", threshold).getBytes(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
bedroomTempThreshold.setText(String.format("%.1f C", threshold));
}
}
});
/* Start the simulation */
setVisible(true);
}
public Room getRoom(String name) {
return rooms.get(name);
}
public int[] getTime() {
return new int[]{currentDay, currentTime[0], currentTime[1]};
}
public synchronized void setTime(int day, int hours, int minutes) {
// TODO: notify agents
currentDay = day;
currentTime[0] = hours;
currentTime[1] = minutes;
GuiEvent event = new GuiEvent(this, Constants.GUI_EVENT_TIME);
event.addParameter(day);
event.addParameter(hours);
event.addParameter(minutes);
myAgent.postGuiEvent(event);
if (hours >= 8 && hours < 22) {
setDay(true);
} else {
setDay(false);
}
time.setText(hours + ":" + String.format("%02d", minutes));
this.day.setText(Constants.dayOfWeek[currentDay]);
}
public void addTime(int days, int hours, int minutes) {
int m = currentTime[1] + minutes;
int h = currentTime[0] + hours;
int d = currentDay + days;
d = (d + h/24) % 7;
h = (h + m/60) % 24;
m = m % 60;
setTime(d, h, m);
int elapsed = ((days * 24) + hours) * 60 + minutes;
for (Room room : rooms.values()) {
for (int i = 0; i < elapsed; ++i) {
room.tick();
}
}
}
public boolean isDay() {
return dayTime;
}
public void setDay(boolean day) {
if (day == dayTime) {
return;
}
if (day) {
appendLog("Sun is rising.");
} else {
appendLog("Sun is setting.");
}
for (Room room : rooms.values()) {
room.setDay(day);
}
dayTime = day;
}
public synchronized void appendLog(String txt) {
String time = currentTime[0] + ":" + String.format("%02d", currentTime[1]);
logs.setText(logs.getText() + time + ": " + txt + "\n");
}
}
| false | true | public SimulationFrame(SimulationAgent agent) {
super();
setSize(1024, 600);
setTitle("Smarthouse");
myAgent = agent;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
String startTemp = null;
try {
startTemp = new String(String.format("%.1f°C", Constants.INITIAL_TEMP).getBytes(), "UTF-8");
} catch (UnsupportedEncodingException e1) {
startTemp = String.format("%.1f C", Constants.INITIAL_TEMP);
}
/* Cached Images */
cachedIcons.put("play", new ImageIcon("icons/play.png"));
cachedIcons.put("stop", new ImageIcon("icons/stop.png"));
cachedIcons.put("fastforward", new ImageIcon("icons/fastforward.png"));
/* Rooms creation */
Room livingroom = new Room(320, 480, Color.GREEN);
Room kitchen = new Room(320, 240, Color.RED);
Room bedroom = new Room(320, 240, Color.BLUE);
rooms.put(Constants.PLACE_LIVINGROOM, livingroom);
rooms.put(Constants.PLACE_KITCHEN, kitchen);
rooms.put(Constants.PLACE_BEDROOM, bedroom);
livingroom.setLocation(10, 10);
kitchen.setLocation(330, 10);
bedroom.setLocation(330, 250);
getContentPane().add(livingroom);
getContentPane().add(kitchen);
getContentPane().add(bedroom);
/* Living room's furniture */
livingroom.addLight(6, 6, 10);
livingroom.addLight(155, 235, 10);
livingroom.addShutter(0, 100, 40, true);
livingroom.addShutter(0, 340, 40, true);
livingroom.addWindow(5, 100, 40, true);
livingroom.addWindow(5, 340, 40, true);
livingroom.addHeater(140, 10, 40, false);
livingroom.addHeater(140, 459, 40, false);
/* Kitchen's furniture */
kitchen.addLight(155, 115, 10);
kitchen.addShutter(315, 100, 40, true);
kitchen.addWindow(310, 100, 40, true);
kitchen.addHeater(140, 219, 40, false);
/* Bedroom's furniture */
bedroom.addLight(300, 85, 10);
bedroom.addLight(300, 135, 10);
bedroom.addShutter(140, 235, 40, false);
bedroom.addWindow(140, 230, 40, false);
bedroom.addHeater(140, 10, 40, false);
/* Time UI */
time = new JTextField("7:00",5);
JLabel timeLabel = new JLabel("time:");
day = new JLabel("Monday");
JButton pause = new JButton(cachedIcons.get("play"));
JButton forward = new JButton(cachedIcons.get("fastforward"));
time.setSize(40, 20);
timeLabel.setSize(40, 20);
day.setSize(70, 20);
pause.setSize(20, 20);
forward.setSize(20, 20);
time.setLocation(50, 500);
timeLabel.setLocation(10, 500);
day.setLocation(100, 500);
pause.setLocation(10, 530);
forward.setLocation(40, 530);
getContentPane().add(time);
getContentPane().add(timeLabel);
getContentPane().add(day);
getContentPane().add(pause);
getContentPane().add(forward);
/* Living room UI */
JPanel livingroomPanel = new JPanel();
livingroomPanel.setLayout(null);
livingroomPanel.setBorder(BorderFactory.createTitledBorder("Living room"));
livingroomPanel.setSize(145, 70);
livingroomPanel.setLocation(190, 495);
getContentPane().add(livingroomPanel);
JLabel livingroomTemp = new JLabel(startTemp);
livingroomTemp.setSize(50, 20);
livingroomTemp.setLocation(20, 15);
livingroomPanel.add(livingroomTemp);
livingroom.addThermometer(livingroomTemp);
livingroomTempSlider = new JSlider(JSlider.HORIZONTAL, 10, 30, 18);
livingroomTempSlider.setSize(115, 20);
livingroomTempSlider.setLocation(15, 40);
livingroomPanel.add(livingroomTempSlider);
livingroomTempThreshold = new JLabel("18.0°C");
livingroomTempThreshold.setSize(50, 20);
livingroomTempThreshold.setLocation(80, 15);
livingroomPanel.add(livingroomTempThreshold);
/* Kitchen UI */
JPanel kitchenPanel = new JPanel();
kitchenPanel.setLayout(null);
kitchenPanel.setBorder(BorderFactory.createTitledBorder("Kitchen"));
kitchenPanel.setSize(145, 70);
kitchenPanel.setLocation(345, 495);
getContentPane().add(kitchenPanel);
JLabel kitchenTemp = new JLabel(startTemp);
kitchenTemp.setSize(50, 20);
kitchenTemp.setLocation(20, 15);
kitchenPanel.add(kitchenTemp);
kitchen.addThermometer(kitchenTemp);
kitchenTempSlider = new JSlider(JSlider.HORIZONTAL, 10, 30, 18);
kitchenTempSlider.setSize(115, 20);
kitchenTempSlider.setLocation(15, 40);
kitchenPanel.add(kitchenTempSlider);
kitchenTempThreshold = new JLabel("18.0°C");
kitchenTempThreshold.setSize(50, 20);
kitchenTempThreshold.setLocation(80, 15);
kitchenPanel.add(kitchenTempThreshold);
/* Bedroom UI */
JPanel bedroomPanel = new JPanel();
bedroomPanel.setLayout(null);
bedroomPanel.setBorder(BorderFactory.createTitledBorder("Bedroom"));
bedroomPanel.setSize(145, 70);
bedroomPanel.setLocation(500, 495);
getContentPane().add(bedroomPanel);
JLabel bedroomTemp = new JLabel(startTemp);
bedroomTemp.setSize(50, 20);
bedroomTemp.setLocation(20, 15);
bedroomPanel.add(bedroomTemp);
bedroom.addThermometer(bedroomTemp);
bedroomTempSlider = new JSlider(JSlider.HORIZONTAL, 10, 30, 18);
bedroomTempSlider.setSize(115, 20);
bedroomTempSlider.setLocation(15, 40);
bedroomPanel.add(bedroomTempSlider);
bedroomTempThreshold = new JLabel("18.0°C");
bedroomTempThreshold.setSize(50, 20);
bedroomTempThreshold.setLocation(80, 15);
bedroomPanel.add(bedroomTempThreshold);
/* Logs */
logs = new JTextArea();
logs.setEditable(false);
logs.setLineWrap(true);
logs.setWrapStyleWord(true);
JScrollPane scrollLog = new JScrollPane(logs);
scrollLog.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );
scrollLog.setSize(349, 547);
scrollLog.setLocation(660, 15);
getContentPane().add(scrollLog);
/* Timer */
timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
addTime(0, 0, 1);
}
});
timer.setInitialDelay(0);
timer.setRepeats(true);
/* Actions */
time.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() != KeyEvent.VK_ENTER) {
return;
}
String time = ((JTextField) e.getSource()).getText();
int hours = Integer.parseInt(time.split(":")[0]);
int minutes = Integer.parseInt(time.split(":")[1]);
setTime(0, hours, minutes);
}
});
pause.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (running) {
((JButton) e.getSource()).setIcon(cachedIcons.get("play"));
timer.stop();
} else {
((JButton) e.getSource()).setIcon(cachedIcons.get("stop"));
timer.start();
}
running = !running;
}
});
forward.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
timer.stop();
timer.setDelay(50);
timer.start();
}
public void mouseReleased(MouseEvent e) {
timer.stop();
timer.setDelay(1000);
if (running) {
timer.start();
}
}
});
livingroomTempSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
double threshold = livingroomTempSlider.getValue();
rooms.get("livingroom").setTempThreshold(threshold);
try {
livingroomTempThreshold.setText(new String(String.format("%.1f°C", threshold).getBytes(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
livingroomTempThreshold.setText(String.format("%.1f C", threshold));
}
}
});
kitchenTempSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
double threshold = kitchenTempSlider.getValue();
rooms.get("kitchen").setTempThreshold(threshold);
try {
kitchenTempThreshold.setText(new String(String.format("%.1f°C", threshold).getBytes(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
kitchenTempThreshold.setText(String.format("%.1f C", threshold));
}
}
});
bedroomTempSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
double threshold = bedroomTempSlider.getValue();
rooms.get("bedroom").setTempThreshold(threshold);
try {
bedroomTempThreshold.setText(new String(String.format("%.1f°C", threshold).getBytes(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
bedroomTempThreshold.setText(String.format("%.1f C", threshold));
}
}
});
/* Start the simulation */
setVisible(true);
}
| public SimulationFrame(SimulationAgent agent) {
super();
setSize(1024, 600);
setTitle("Smarthouse");
myAgent = agent;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
String startTemp = null;
try {
startTemp = new String(String.format("%.1f°C", Constants.INITIAL_TEMP).getBytes(), "UTF-8");
} catch (UnsupportedEncodingException e1) {
startTemp = String.format("%.1f C", Constants.INITIAL_TEMP);
}
/* Cached Images */
cachedIcons.put("play", new ImageIcon("icons/play.png"));
cachedIcons.put("stop", new ImageIcon("icons/stop.png"));
cachedIcons.put("fastforward", new ImageIcon("icons/fastforward.png"));
/* Rooms creation */
Room livingroom = new Room(320, 480, Color.GREEN);
Room kitchen = new Room(320, 240, Color.RED);
Room bedroom = new Room(320, 240, Color.BLUE);
rooms.put(Constants.PLACE_LIVINGROOM, livingroom);
rooms.put(Constants.PLACE_KITCHEN, kitchen);
rooms.put(Constants.PLACE_BEDROOM, bedroom);
livingroom.setLocation(10, 10);
kitchen.setLocation(330, 10);
bedroom.setLocation(330, 250);
getContentPane().add(livingroom);
getContentPane().add(kitchen);
getContentPane().add(bedroom);
/* Living room's furniture */
livingroom.addLight(6, 6, 10);
livingroom.addLight(155, 235, 10);
livingroom.addShutter(0, 100, 40, true);
livingroom.addShutter(0, 340, 40, true);
livingroom.addWindow(5, 100, 40, true);
livingroom.addWindow(5, 340, 40, true);
livingroom.addHeater(140, 10, 40, false);
livingroom.addHeater(140, 459, 40, false);
/* Kitchen's furniture */
kitchen.addLight(155, 115, 10);
kitchen.addShutter(315, 100, 40, true);
kitchen.addWindow(310, 100, 40, true);
kitchen.addHeater(140, 219, 40, false);
/* Bedroom's furniture */
bedroom.addLight(300, 85, 10);
bedroom.addLight(300, 135, 10);
bedroom.addShutter(140, 235, 40, false);
bedroom.addWindow(140, 230, 40, false);
bedroom.addHeater(140, 10, 40, false);
/* Time UI */
time = new JTextField("7:00",5);
JLabel timeLabel = new JLabel("time:");
day = new JLabel("Monday");
JButton pause = new JButton(cachedIcons.get("play"));
JButton forward = new JButton(cachedIcons.get("fastforward"));
time.setSize(40, 20);
timeLabel.setSize(40, 20);
day.setSize(70, 20);
pause.setSize(20, 20);
forward.setSize(20, 20);
time.setLocation(50, 500);
timeLabel.setLocation(10, 500);
day.setLocation(100, 500);
pause.setLocation(10, 530);
forward.setLocation(40, 530);
getContentPane().add(time);
getContentPane().add(timeLabel);
getContentPane().add(day);
getContentPane().add(pause);
getContentPane().add(forward);
/* Living room UI */
JPanel livingroomPanel = new JPanel();
livingroomPanel.setLayout(null);
livingroomPanel.setBorder(BorderFactory.createTitledBorder("Living room"));
livingroomPanel.setSize(145, 70);
livingroomPanel.setLocation(190, 495);
getContentPane().add(livingroomPanel);
JLabel livingroomTemp = new JLabel(startTemp);
livingroomTemp.setSize(50, 20);
livingroomTemp.setLocation(20, 15);
livingroomPanel.add(livingroomTemp);
livingroom.addThermometer(livingroomTemp);
livingroomTempSlider = new JSlider(JSlider.HORIZONTAL, 10, 30, 18);
livingroomTempSlider.setSize(115, 20);
livingroomTempSlider.setLocation(15, 40);
livingroomPanel.add(livingroomTempSlider);
livingroomTempThreshold = new JLabel(startTemp);
livingroomTempThreshold.setSize(50, 20);
livingroomTempThreshold.setLocation(80, 15);
livingroomPanel.add(livingroomTempThreshold);
/* Kitchen UI */
JPanel kitchenPanel = new JPanel();
kitchenPanel.setLayout(null);
kitchenPanel.setBorder(BorderFactory.createTitledBorder("Kitchen"));
kitchenPanel.setSize(145, 70);
kitchenPanel.setLocation(345, 495);
getContentPane().add(kitchenPanel);
JLabel kitchenTemp = new JLabel(startTemp);
kitchenTemp.setSize(50, 20);
kitchenTemp.setLocation(20, 15);
kitchenPanel.add(kitchenTemp);
kitchen.addThermometer(kitchenTemp);
kitchenTempSlider = new JSlider(JSlider.HORIZONTAL, 10, 30, 18);
kitchenTempSlider.setSize(115, 20);
kitchenTempSlider.setLocation(15, 40);
kitchenPanel.add(kitchenTempSlider);
kitchenTempThreshold = new JLabel(startTemp);
kitchenTempThreshold.setSize(50, 20);
kitchenTempThreshold.setLocation(80, 15);
kitchenPanel.add(kitchenTempThreshold);
/* Bedroom UI */
JPanel bedroomPanel = new JPanel();
bedroomPanel.setLayout(null);
bedroomPanel.setBorder(BorderFactory.createTitledBorder("Bedroom"));
bedroomPanel.setSize(145, 70);
bedroomPanel.setLocation(500, 495);
getContentPane().add(bedroomPanel);
JLabel bedroomTemp = new JLabel(startTemp);
bedroomTemp.setSize(50, 20);
bedroomTemp.setLocation(20, 15);
bedroomPanel.add(bedroomTemp);
bedroom.addThermometer(bedroomTemp);
bedroomTempSlider = new JSlider(JSlider.HORIZONTAL, 10, 30, 18);
bedroomTempSlider.setSize(115, 20);
bedroomTempSlider.setLocation(15, 40);
bedroomPanel.add(bedroomTempSlider);
bedroomTempThreshold = new JLabel(startTemp);
bedroomTempThreshold.setSize(50, 20);
bedroomTempThreshold.setLocation(80, 15);
bedroomPanel.add(bedroomTempThreshold);
/* Logs */
logs = new JTextArea();
logs.setEditable(false);
logs.setLineWrap(true);
logs.setWrapStyleWord(true);
JScrollPane scrollLog = new JScrollPane(logs);
scrollLog.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );
scrollLog.setSize(349, 547);
scrollLog.setLocation(660, 15);
getContentPane().add(scrollLog);
/* Timer */
timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
addTime(0, 0, 1);
}
});
timer.setInitialDelay(0);
timer.setRepeats(true);
/* Actions */
time.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() != KeyEvent.VK_ENTER) {
return;
}
String time = ((JTextField) e.getSource()).getText();
int hours = Integer.parseInt(time.split(":")[0]);
int minutes = Integer.parseInt(time.split(":")[1]);
setTime(0, hours, minutes);
}
});
pause.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (running) {
((JButton) e.getSource()).setIcon(cachedIcons.get("play"));
timer.stop();
} else {
((JButton) e.getSource()).setIcon(cachedIcons.get("stop"));
timer.start();
}
running = !running;
}
});
forward.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
timer.stop();
timer.setDelay(50);
timer.start();
}
public void mouseReleased(MouseEvent e) {
timer.stop();
timer.setDelay(1000);
if (running) {
timer.start();
}
}
});
livingroomTempSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
double threshold = livingroomTempSlider.getValue();
rooms.get("livingroom").setTempThreshold(threshold);
try {
livingroomTempThreshold.setText(new String(String.format("%.1f°C", threshold).getBytes(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
livingroomTempThreshold.setText(String.format("%.1f C", threshold));
}
}
});
kitchenTempSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
double threshold = kitchenTempSlider.getValue();
rooms.get("kitchen").setTempThreshold(threshold);
try {
kitchenTempThreshold.setText(new String(String.format("%.1f°C", threshold).getBytes(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
kitchenTempThreshold.setText(String.format("%.1f C", threshold));
}
}
});
bedroomTempSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
double threshold = bedroomTempSlider.getValue();
rooms.get("bedroom").setTempThreshold(threshold);
try {
bedroomTempThreshold.setText(new String(String.format("%.1f°C", threshold).getBytes(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
bedroomTempThreshold.setText(String.format("%.1f C", threshold));
}
}
});
/* Start the simulation */
setVisible(true);
}
|
diff --git a/src/game/Map.java b/src/game/Map.java
index c7c15d7..f92ddbd 100644
--- a/src/game/Map.java
+++ b/src/game/Map.java
@@ -1,117 +1,117 @@
package game;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
public class Map {
private static final int TILE_SIZE = 10;
private final int width;
private final int height;
private final List<List<Ground>> tiles;
private final BufferedImage offscreen;
private final BufferedImage map_img;
public Map(String name) throws IOException {
URL url = this.getClass().getResource("/resources/maps/"+name);
assert (url != null);
map_img = (BufferedImage) new ImageIcon(ImageIO.read(url)).getImage();
width = map_img.getWidth() * TILE_SIZE;
height = map_img.getHeight() * TILE_SIZE;
tiles = new ArrayList<List<Ground>>(height);
offscreen = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
}
public Ground get(final int x, final int y) {
if (x < 0 || y < 0 || x >= width || y >= height) {
return Ground.Void;
}
final int tileX = x / TILE_SIZE;
final int tileY = y / TILE_SIZE;
return tiles.get(tileX).get(tileY);
}
public void paint(Graphics g, Component observer) {
g.drawImage(offscreen, 0, 0, observer);
}
public Image cloneImage() {
BufferedImage img = new BufferedImage(offscreen.getWidth(), offscreen.getHeight(), offscreen.getType());
Graphics g = img.getGraphics();
g.drawImage(offscreen, 0, 0, null);
return img;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public void init(Base red, Base blue) {
// TODO paint a nicer map!
for (int img_x = 0; img_x < map_img.getWidth(); img_x++) {
List<Ground> row = new ArrayList<Ground>(width);
for (int img_y = 0; img_y < map_img.getWidth(); img_y++) {
- int pixel = map_img.getRGB(img_y, img_x);
+ int pixel = map_img.getRGB(img_x, img_y);
Ground ground = Ground.Void;
switch (pixel) {
case 0xff3a9d3a:
ground = Ground.Grass;
break;
case 0xff375954:
ground = Ground.Swamp;
break;
case 0xffe8d35e:
ground = Ground.Sand;
break;
case 0xff323f05:
ground = Ground.Forest;
break;
case 0xff0000ff: /* BLUE */
ground = Ground.Grass;
blue.setPosition(img_x*TILE_SIZE+(TILE_SIZE/2), img_y*TILE_SIZE+(TILE_SIZE/2));
break;
case 0xff787878:
ground = Ground.Rocks;
break;
case 0xffffffff: /* WHITE */
ground = Ground.Grass;
break;
case 0xffff0000: /* RED */
ground = Ground.Grass;
red.setPosition(img_x*TILE_SIZE+(TILE_SIZE/2), img_y*TILE_SIZE+(TILE_SIZE/2));
break;
case 0xff3674db:
ground = Ground.Water;
break;
default:
throw new RuntimeException("Map broken. Unknown color: "+Integer.toHexString(pixel));
}
row.add(img_y, ground);
/* paint offscreen image */
for (int i = 0; i < TILE_SIZE; i++) {
for (int j = 0; j < TILE_SIZE; j++) {
offscreen.setRGB(img_x*TILE_SIZE+i, img_y*TILE_SIZE+j, pixel);
}
}
}
tiles.add(row);
}
}
}
| true | true | public void init(Base red, Base blue) {
// TODO paint a nicer map!
for (int img_x = 0; img_x < map_img.getWidth(); img_x++) {
List<Ground> row = new ArrayList<Ground>(width);
for (int img_y = 0; img_y < map_img.getWidth(); img_y++) {
int pixel = map_img.getRGB(img_y, img_x);
Ground ground = Ground.Void;
switch (pixel) {
case 0xff3a9d3a:
ground = Ground.Grass;
break;
case 0xff375954:
ground = Ground.Swamp;
break;
case 0xffe8d35e:
ground = Ground.Sand;
break;
case 0xff323f05:
ground = Ground.Forest;
break;
case 0xff0000ff: /* BLUE */
ground = Ground.Grass;
blue.setPosition(img_x*TILE_SIZE+(TILE_SIZE/2), img_y*TILE_SIZE+(TILE_SIZE/2));
break;
case 0xff787878:
ground = Ground.Rocks;
break;
case 0xffffffff: /* WHITE */
ground = Ground.Grass;
break;
case 0xffff0000: /* RED */
ground = Ground.Grass;
red.setPosition(img_x*TILE_SIZE+(TILE_SIZE/2), img_y*TILE_SIZE+(TILE_SIZE/2));
break;
case 0xff3674db:
ground = Ground.Water;
break;
default:
throw new RuntimeException("Map broken. Unknown color: "+Integer.toHexString(pixel));
}
row.add(img_y, ground);
/* paint offscreen image */
for (int i = 0; i < TILE_SIZE; i++) {
for (int j = 0; j < TILE_SIZE; j++) {
offscreen.setRGB(img_x*TILE_SIZE+i, img_y*TILE_SIZE+j, pixel);
}
}
}
tiles.add(row);
}
}
| public void init(Base red, Base blue) {
// TODO paint a nicer map!
for (int img_x = 0; img_x < map_img.getWidth(); img_x++) {
List<Ground> row = new ArrayList<Ground>(width);
for (int img_y = 0; img_y < map_img.getWidth(); img_y++) {
int pixel = map_img.getRGB(img_x, img_y);
Ground ground = Ground.Void;
switch (pixel) {
case 0xff3a9d3a:
ground = Ground.Grass;
break;
case 0xff375954:
ground = Ground.Swamp;
break;
case 0xffe8d35e:
ground = Ground.Sand;
break;
case 0xff323f05:
ground = Ground.Forest;
break;
case 0xff0000ff: /* BLUE */
ground = Ground.Grass;
blue.setPosition(img_x*TILE_SIZE+(TILE_SIZE/2), img_y*TILE_SIZE+(TILE_SIZE/2));
break;
case 0xff787878:
ground = Ground.Rocks;
break;
case 0xffffffff: /* WHITE */
ground = Ground.Grass;
break;
case 0xffff0000: /* RED */
ground = Ground.Grass;
red.setPosition(img_x*TILE_SIZE+(TILE_SIZE/2), img_y*TILE_SIZE+(TILE_SIZE/2));
break;
case 0xff3674db:
ground = Ground.Water;
break;
default:
throw new RuntimeException("Map broken. Unknown color: "+Integer.toHexString(pixel));
}
row.add(img_y, ground);
/* paint offscreen image */
for (int i = 0; i < TILE_SIZE; i++) {
for (int j = 0; j < TILE_SIZE; j++) {
offscreen.setRGB(img_x*TILE_SIZE+i, img_y*TILE_SIZE+j, pixel);
}
}
}
tiles.add(row);
}
}
|
diff --git a/src/main/java/org/jboss/as/plugin/deployment/AbstractDeployment.java b/src/main/java/org/jboss/as/plugin/deployment/AbstractDeployment.java
index 786d168..6c6150b 100644
--- a/src/main/java/org/jboss/as/plugin/deployment/AbstractDeployment.java
+++ b/src/main/java/org/jboss/as/plugin/deployment/AbstractDeployment.java
@@ -1,278 +1,278 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.plugin.deployment;
import static org.jboss.as.controller.client.helpers.ClientConstants.DEPLOYMENT;
import static org.jboss.as.controller.client.helpers.ClientConstants.FAILURE_DESCRIPTION;
import static org.jboss.as.controller.client.helpers.ClientConstants.OP;
import static org.jboss.as.controller.client.helpers.ClientConstants.OUTCOME;
import static org.jboss.as.controller.client.helpers.ClientConstants.RESULT;
import static org.jboss.as.controller.client.helpers.ClientConstants.SUCCESS;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Collections;
import java.util.List;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.jboss.as.controller.client.helpers.standalone.DeploymentAction;
import org.jboss.as.controller.client.helpers.standalone.DeploymentPlan;
import org.jboss.as.controller.client.helpers.standalone.DeploymentPlanBuilder;
import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentActionResult;
import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentManager;
import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentPlanResult;
import org.jboss.as.controller.client.helpers.standalone.ServerUpdateActionResult;
import org.jboss.as.plugin.deployment.common.AbstractServerConnection;
import org.jboss.dmr.ModelNode;
/**
* The default implementation for executing build plans on the server.
*
* @author <a href="mailto:[email protected]">James R. Perkins</a>
* @author Stuart Douglas
* @requiresDependencyResolution runtime
*/
abstract class AbstractDeployment extends AbstractServerConnection {
// These will be moved org.jboss.as.controller.client.helpers.ClientConstants next release.
private static final String CHILD_TYPE = "child-type";
private static final String FAILED = "failed";
private static final String READ_CHILDREN_NAMES_OPERATION = "read-children-names";
private static final String NO_NAME_MSG = "No name defined, using default deployment name.";
private static final String NAME_DEFINED_MSG_FMT = "Using '%s' for the deployment name.";
/**
* @parameter default-value="${project}"
* @readonly
* @required
*/
private MavenProject project;
/**
* Specifies the name used for the deployment.
*
* @parameter
*/
private String name;
/**
* Specifies the packaging type.
*
* @parameter default-value="${project.packaging}"
*/
private String packaging;
/**
* The target directory the application to be deployed is located.
*
* @parameter default-value="${project.build.directory}/"
*/
private File targetDir;
/**
* The file name of the application to be deployed.
*
* @parameter default-value="${project.build.finalName}.${project.packaging}"
*/
private String filename;
/**
* Set to {@code true} if you want the deployment to be skipped, otherwise {@code false}.
*
* @parameter default-value="false"
*/
private boolean skip;
/**
* The deployment name. The default is {@code null}.
*
* @return the deployment name, otherwise {@code null}.
*/
public String name() {
return name;
}
/**
* The target directory the archive is located. The default is {@code project.build.directory}.
*
* @return the target directory the archive is located.
*/
public final File targetDirectory() {
return targetDir;
}
/**
* The archive file.
*
* @return the archive file.
*/
public File file() {
return new File(targetDir, filename);
}
/**
* @return The deployment name
*/
public String deploymentName() {
return (name() == null ? file().getName() : name());
}
/**
* Creates the deployment plan.
*
* @param builder the builder used to create the deployment plan.
*
* @return the deployment plan or {@code null} to ignore the plan.
*
* @throws IOException if the deployment plan cannot be created.
*/
public abstract DeploymentPlan createPlan(DeploymentPlanBuilder builder) throws IOException, MojoFailureException;
/**
* The goal of the deployment.
*
* @return the goal of the deployment.
*/
public abstract String goal();
/*
* (non-Javadoc)
*
* @see org.apache.maven.plugin.Mojo#execute()
*/
@Override
public final void execute() throws MojoExecutionException, MojoFailureException {
if (skip) {
getLog().debug(String.format("Skipping deployment of %s:%s", project.getGroupId(), project.getArtifactId()));
return;
}
try {
// Check the packaging type
if (checkPackaging() && IgnoredPackageTypes.isIgnored(packaging)) {
getLog().debug(String.format("Ignoring packaging type %s.", packaging));
} else {
final InetAddress host = hostAddress();
getLog().info(String.format("Executing goal %s on server %s (%s) port %s.", goal(), host.getHostName(), host.getHostAddress(), port()));
final ServerDeploymentManager manager = ServerDeploymentManager.Factory.create(client());
final DeploymentPlanBuilder builder = manager.newDeploymentPlan();
final DeploymentPlan plan = createPlan(builder);
if (plan == null) {
getLog().debug(String.format("Ignoring goal %s as the plan was null.", goal()));
} else {
if (plan.getDeploymentActions().size() > 0) {
final ServerDeploymentPlanResult planResult = manager.execute(plan).get();
// Check the results
for (DeploymentAction action : plan.getDeploymentActions()) {
final ServerDeploymentActionResult actionResult = planResult.getDeploymentActionResult(action.getId());
final ServerUpdateActionResult.Result result = actionResult.getResult();
switch (result) {
case FAILED:
throw new MojoExecutionException("Deployment failed.", actionResult.getDeploymentException());
case NOT_EXECUTED:
throw new MojoExecutionException("Deployment not executed.", actionResult.getDeploymentException());
case ROLLED_BACK:
throw new MojoExecutionException("Deployment failed and was rolled back.", actionResult.getDeploymentException());
case CONFIGURATION_MODIFIED_REQUIRES_RESTART:
getLog().warn("Action was executed, but the server requires a restart.");
break;
default:
break;
}
getLog().debug(String.format("Deployment Plan Id : %s", planResult.getDeploymentPlanId()));
}
} else {
getLog().warn(String.format("Goal %s failed on file %s. No deployment actions exist. Plan: %s", goal(), file().getName(), plan));
}
}
}
} catch (Exception e) {
- throw new MojoExecutionException(String.format("Could not execute goal %s on %s. Reason: %s", goal(), file().getName(), e.getMessage()), e);
+ throw new MojoExecutionException(String.format("Could not execute goal %s on %s. Reason: %s", goal(), file(), e.getMessage()), e);
} finally {
safeCloseClient();
}
}
/**
* Checks to see if the deployment exists.
*
* @return {@code true} if the deployment exists, {@code false} if the deployment does not exist or cannot be
* determined.
*
* @throws java.io.IOException if an error occurred.
*/
protected final boolean deploymentExists() throws IOException {
// CLI :read-children-names(child-type=deployment)
final ModelNode op = new ModelNode();
op.get(OP).set(READ_CHILDREN_NAMES_OPERATION);
op.get(CHILD_TYPE).set(DEPLOYMENT);
final ModelNode result = client().execute(op);
final String deploymentName = deploymentName();
// Check to make sure there is an outcome
if (result.hasDefined(OUTCOME)) {
if (result.get(OUTCOME).asString().equals(SUCCESS)) {
final List<ModelNode> deployments = (result.hasDefined(RESULT) ? result.get(RESULT).asList() : Collections.<ModelNode>emptyList());
for (ModelNode n : deployments) {
if (n.asString().equals(deploymentName)) {
return true;
}
}
} else if (result.get(OUTCOME).asString().equals(FAILED)) {
getLog().warn(String.format("A failure occurred when checking existing deployments. Error: %s",
(result.hasDefined(FAILURE_DESCRIPTION) ? result.get(FAILURE_DESCRIPTION).asString() : "Unknown")));
}
} else {
getLog().warn(String.format("An unexpected response was found checking the deployment. Result: %s", result));
}
return false;
}
/**
* A message indicating the name has not been defined.
*
* @return the message.
*/
protected String nameNotDefinedMessage() {
return NO_NAME_MSG;
}
/**
* A message indicating the name has been defined and will be used.
*
* @return the message.
*/
protected String nameDefinedMessage() {
return String.format(NAME_DEFINED_MSG_FMT, name());
}
/**
* @return True if the package type should be checked for ignored packaging types
*/
protected boolean checkPackaging() {
return true;
}
}
| true | true | public final void execute() throws MojoExecutionException, MojoFailureException {
if (skip) {
getLog().debug(String.format("Skipping deployment of %s:%s", project.getGroupId(), project.getArtifactId()));
return;
}
try {
// Check the packaging type
if (checkPackaging() && IgnoredPackageTypes.isIgnored(packaging)) {
getLog().debug(String.format("Ignoring packaging type %s.", packaging));
} else {
final InetAddress host = hostAddress();
getLog().info(String.format("Executing goal %s on server %s (%s) port %s.", goal(), host.getHostName(), host.getHostAddress(), port()));
final ServerDeploymentManager manager = ServerDeploymentManager.Factory.create(client());
final DeploymentPlanBuilder builder = manager.newDeploymentPlan();
final DeploymentPlan plan = createPlan(builder);
if (plan == null) {
getLog().debug(String.format("Ignoring goal %s as the plan was null.", goal()));
} else {
if (plan.getDeploymentActions().size() > 0) {
final ServerDeploymentPlanResult planResult = manager.execute(plan).get();
// Check the results
for (DeploymentAction action : plan.getDeploymentActions()) {
final ServerDeploymentActionResult actionResult = planResult.getDeploymentActionResult(action.getId());
final ServerUpdateActionResult.Result result = actionResult.getResult();
switch (result) {
case FAILED:
throw new MojoExecutionException("Deployment failed.", actionResult.getDeploymentException());
case NOT_EXECUTED:
throw new MojoExecutionException("Deployment not executed.", actionResult.getDeploymentException());
case ROLLED_BACK:
throw new MojoExecutionException("Deployment failed and was rolled back.", actionResult.getDeploymentException());
case CONFIGURATION_MODIFIED_REQUIRES_RESTART:
getLog().warn("Action was executed, but the server requires a restart.");
break;
default:
break;
}
getLog().debug(String.format("Deployment Plan Id : %s", planResult.getDeploymentPlanId()));
}
} else {
getLog().warn(String.format("Goal %s failed on file %s. No deployment actions exist. Plan: %s", goal(), file().getName(), plan));
}
}
}
} catch (Exception e) {
throw new MojoExecutionException(String.format("Could not execute goal %s on %s. Reason: %s", goal(), file().getName(), e.getMessage()), e);
} finally {
safeCloseClient();
}
}
| public final void execute() throws MojoExecutionException, MojoFailureException {
if (skip) {
getLog().debug(String.format("Skipping deployment of %s:%s", project.getGroupId(), project.getArtifactId()));
return;
}
try {
// Check the packaging type
if (checkPackaging() && IgnoredPackageTypes.isIgnored(packaging)) {
getLog().debug(String.format("Ignoring packaging type %s.", packaging));
} else {
final InetAddress host = hostAddress();
getLog().info(String.format("Executing goal %s on server %s (%s) port %s.", goal(), host.getHostName(), host.getHostAddress(), port()));
final ServerDeploymentManager manager = ServerDeploymentManager.Factory.create(client());
final DeploymentPlanBuilder builder = manager.newDeploymentPlan();
final DeploymentPlan plan = createPlan(builder);
if (plan == null) {
getLog().debug(String.format("Ignoring goal %s as the plan was null.", goal()));
} else {
if (plan.getDeploymentActions().size() > 0) {
final ServerDeploymentPlanResult planResult = manager.execute(plan).get();
// Check the results
for (DeploymentAction action : plan.getDeploymentActions()) {
final ServerDeploymentActionResult actionResult = planResult.getDeploymentActionResult(action.getId());
final ServerUpdateActionResult.Result result = actionResult.getResult();
switch (result) {
case FAILED:
throw new MojoExecutionException("Deployment failed.", actionResult.getDeploymentException());
case NOT_EXECUTED:
throw new MojoExecutionException("Deployment not executed.", actionResult.getDeploymentException());
case ROLLED_BACK:
throw new MojoExecutionException("Deployment failed and was rolled back.", actionResult.getDeploymentException());
case CONFIGURATION_MODIFIED_REQUIRES_RESTART:
getLog().warn("Action was executed, but the server requires a restart.");
break;
default:
break;
}
getLog().debug(String.format("Deployment Plan Id : %s", planResult.getDeploymentPlanId()));
}
} else {
getLog().warn(String.format("Goal %s failed on file %s. No deployment actions exist. Plan: %s", goal(), file().getName(), plan));
}
}
}
} catch (Exception e) {
throw new MojoExecutionException(String.format("Could not execute goal %s on %s. Reason: %s", goal(), file(), e.getMessage()), e);
} finally {
safeCloseClient();
}
}
|
diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/LocationManager.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/LocationManager.java
index 385a7861..86fbf646 100644
--- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/LocationManager.java
+++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/LocationManager.java
@@ -1,355 +1,355 @@
/*******************************************************************************
* Copyright (c) 2004, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.core.runtime.adaptor;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import org.eclipse.core.runtime.internal.adaptor.BasicLocation;
import org.eclipse.osgi.framework.adaptor.FrameworkAdaptor;
import org.eclipse.osgi.framework.internal.core.FrameworkProperties;
import org.eclipse.osgi.service.datalocation.Location;
/**
* This class is used to manage the various Locations for Eclipse.
* <p>
* Clients may not extend this class.
* </p>
* @since 3.1
*/
public class LocationManager {
private static Location installLocation = null;
private static Location configurationLocation = null;
private static Location userLocation = null;
private static Location instanceLocation = null;
public static final String READ_ONLY_AREA_SUFFIX = ".readOnly"; //$NON-NLS-1$
public static final String PROP_INSTALL_AREA = "osgi.install.area"; //$NON-NLS-1$
public static final String PROP_CONFIG_AREA = "osgi.configuration.area"; //$NON-NLS-1$
public static final String PROP_CONFIG_AREA_DEFAULT = "osgi.configuration.area.default"; //$NON-NLS-1$
public static final String PROP_SHARED_CONFIG_AREA = "osgi.sharedConfiguration.area"; //$NON-NLS-1$
public static final String PROP_INSTANCE_AREA = "osgi.instance.area"; //$NON-NLS-1$
public static final String PROP_INSTANCE_AREA_DEFAULT = "osgi.instance.area.default"; //$NON-NLS-1$
public static final String PROP_USER_AREA = "osgi.user.area"; //$NON-NLS-1$
public static final String PROP_USER_AREA_DEFAULT = "osgi.user.area.default"; //$NON-NLS-1$
public static final String PROP_MANIFEST_CACHE = "osgi.manifest.cache"; //$NON-NLS-1$
public static final String PROP_USER_HOME = "user.home"; //$NON-NLS-1$
public static final String PROP_USER_DIR = "user.dir"; //$NON-NLS-1$
// configuration area file/dir names
public static final String BUNDLES_DIR = "bundles"; //$NON-NLS-1$
public static final String STATE_FILE = ".state"; //$NON-NLS-1$
public static final String LAZY_FILE = ".lazy"; //$NON-NLS-1$
public static final String BUNDLE_DATA_FILE = ".bundledata"; //$NON-NLS-1$
public static final String MANIFESTS_DIR = "manifests"; //$NON-NLS-1$
public static final String CONFIG_FILE = "config.ini"; //$NON-NLS-1$
public static final String ECLIPSE_PROPERTIES = "eclipse.properties"; //$NON-NLS-1$
// Constants for configuration location discovery
private static final String ECLIPSE = "eclipse"; //$NON-NLS-1$
private static final String PRODUCT_SITE_MARKER = ".eclipseproduct"; //$NON-NLS-1$
private static final String PRODUCT_SITE_ID = "id"; //$NON-NLS-1$
private static final String PRODUCT_SITE_VERSION = "version"; //$NON-NLS-1$
private static final String CONFIG_DIR = "configuration"; //$NON-NLS-1$
// Data mode constants for user, configuration and data locations.
private static final String NONE = "@none"; //$NON-NLS-1$
private static final String NO_DEFAULT = "@noDefault"; //$NON-NLS-1$
private static final String USER_HOME = "@user.home"; //$NON-NLS-1$
private static final String USER_DIR = "@user.dir"; //$NON-NLS-1$
/**
* Builds a URL with the given specification
* @param spec the URL specification
* @param trailingSlash flag to indicate a trailing slash on the spec
* @return a URL
*/
public static URL buildURL(String spec, boolean trailingSlash) {
if (spec == null)
return null;
boolean isFile = spec.startsWith("file:"); //$NON-NLS-1$
try {
if (isFile)
return adjustTrailingSlash(new File(spec.substring(5)).toURL(), trailingSlash);
else
return new URL(spec);
} catch (MalformedURLException e) {
// if we failed and it is a file spec, there is nothing more we can do
// otherwise, try to make the spec into a file URL.
if (isFile)
return null;
try {
return adjustTrailingSlash(new File(spec).toURL(), trailingSlash);
} catch (MalformedURLException e1) {
return null;
}
}
}
private static URL adjustTrailingSlash(URL url, boolean trailingSlash) throws MalformedURLException {
String file = url.getFile();
if (trailingSlash == (file.endsWith("/"))) //$NON-NLS-1$
return url;
file = trailingSlash ? file + "/" : file.substring(0, file.length() - 1); //$NON-NLS-1$
return new URL(url.getProtocol(), url.getHost(), file);
}
private static void mungeConfigurationLocation() {
// if the config property was set, munge it for backwards compatibility.
String location = FrameworkProperties.getProperty(PROP_CONFIG_AREA);
if (location != null) {
location = buildURL(location, false).toExternalForm();
if (location.endsWith(".cfg")) { //$NON-NLS-1$
int index = location.lastIndexOf('/');
location = location.substring(0, index + 1);
}
if (!location.endsWith("/")) //$NON-NLS-1$
location += "/"; //$NON-NLS-1$
FrameworkProperties.setProperty(PROP_CONFIG_AREA, location);
}
}
/**
* Initializes the Location objects for the LocationManager.
*/
public static void initializeLocations() {
// do install location initialization first since others may depend on it
// assumes that the property is already set
- installLocation = buildLocation(PROP_INSTALL_AREA, null, null, true);
+ installLocation = buildLocation(PROP_INSTALL_AREA, null, "", true); //$NON-NLS-1$
Location temp = buildLocation(PROP_USER_AREA_DEFAULT, null, "", false); //$NON-NLS-1$
URL defaultLocation = temp == null ? null : temp.getURL();
if (defaultLocation == null)
defaultLocation = buildURL(new File(FrameworkProperties.getProperty(PROP_USER_HOME), "user").getAbsolutePath(), true); //$NON-NLS-1$
userLocation = buildLocation(PROP_USER_AREA, defaultLocation, "", false); //$NON-NLS-1$
temp = buildLocation(PROP_INSTANCE_AREA_DEFAULT, null, "", false); //$NON-NLS-1$
defaultLocation = temp == null ? null : temp.getURL();
if (defaultLocation == null)
defaultLocation = buildURL(new File(FrameworkProperties.getProperty(PROP_USER_DIR), "workspace").getAbsolutePath(), true); //$NON-NLS-1$
instanceLocation = buildLocation(PROP_INSTANCE_AREA, defaultLocation, "", false); //$NON-NLS-1$
mungeConfigurationLocation();
// compute a default but it is very unlikely to be used since main will have computed everything
temp = buildLocation(PROP_CONFIG_AREA_DEFAULT, null, "", false); //$NON-NLS-1$
defaultLocation = temp == null ? null : temp.getURL();
if (defaultLocation == null)
defaultLocation = buildURL(computeDefaultConfigurationLocation(), true);
configurationLocation = buildLocation(PROP_CONFIG_AREA, defaultLocation, "", false); //$NON-NLS-1$
// get the parent location based on the system property. This will have been set on the
// way in either by the caller/user or by main. There will be no parent location if we are not
// cascaded.
URL parentLocation = computeSharedConfigurationLocation();
if (parentLocation != null && !parentLocation.equals(configurationLocation.getURL())) {
Location parent = new BasicLocation(null, parentLocation, true);
((BasicLocation) configurationLocation).setParent(parent);
}
initializeDerivedConfigurationLocations();
}
private static Location buildLocation(String property, URL defaultLocation, String userDefaultAppendage, boolean readOnlyDefault) {
String location = FrameworkProperties.clearProperty(property);
// the user/product may specify a non-default readOnly setting
String userReadOnlySetting = FrameworkProperties.getProperty(property + READ_ONLY_AREA_SUFFIX);
boolean readOnly = (userReadOnlySetting == null ? readOnlyDefault : Boolean.valueOf(userReadOnlySetting).booleanValue());
// if the instance location is not set, predict where the workspace will be and
// put the instance area inside the workspace meta area.
if (location == null)
return new BasicLocation(property, defaultLocation, readOnly);
String trimmedLocation = location.trim();
if (trimmedLocation.equalsIgnoreCase(NONE))
return null;
if (trimmedLocation.equalsIgnoreCase(NO_DEFAULT))
return new BasicLocation(property, null, readOnly);
if (trimmedLocation.startsWith(USER_HOME)) {
String base = substituteVar(location, USER_HOME, PROP_USER_HOME);
location = new File(base, userDefaultAppendage).getAbsolutePath();
} else if (trimmedLocation.startsWith(USER_DIR)) {
String base = substituteVar(location, USER_DIR, PROP_USER_DIR);
location = new File(base, userDefaultAppendage).getAbsolutePath();
}
URL url = buildURL(location, true);
BasicLocation result = null;
if (url != null) {
result = new BasicLocation(property, null, readOnly);
result.setURL(url, false);
}
return result;
}
private static String substituteVar(String source, String var, String prop) {
String value = FrameworkProperties.getProperty(prop, ""); //$NON-NLS-1$
return value + source.substring(var.length());
}
private static void initializeDerivedConfigurationLocations() {
if (FrameworkProperties.getProperty(PROP_MANIFEST_CACHE) == null)
FrameworkProperties.setProperty(PROP_MANIFEST_CACHE, getConfigurationFile(MANIFESTS_DIR).getAbsolutePath());
}
private static URL computeInstallConfigurationLocation() {
String property = FrameworkProperties.getProperty(PROP_INSTALL_AREA);
if (property != null) {
try {
return new URL(property);
} catch (MalformedURLException e) {
// do nothing here since it is basically impossible to get a bogus url
}
}
return null;
}
private static URL computeSharedConfigurationLocation() {
String property = FrameworkProperties.getProperty(PROP_SHARED_CONFIG_AREA);
if (property == null)
return null;
try {
URL sharedConfigurationURL = new URL(property);
if (sharedConfigurationURL.getPath().startsWith("/")) //$NON-NLS-1$
// absolute
return sharedConfigurationURL;
URL installURL = installLocation.getURL();
if (!sharedConfigurationURL.getProtocol().equals(installURL.getProtocol()))
// different protocol
return sharedConfigurationURL;
sharedConfigurationURL = new URL(installURL, sharedConfigurationURL.getPath());
FrameworkProperties.setProperty(PROP_SHARED_CONFIG_AREA, sharedConfigurationURL.toExternalForm());
} catch (MalformedURLException e) {
// do nothing here since it is basically impossible to get a bogus url
}
return null;
}
private static String computeDefaultConfigurationLocation() {
// 1) We store the config state relative to the 'eclipse' directory if possible
// 2) If this directory is read-only
// we store the state in <user.home>/.eclipse/<application-id>_<version> where <user.home>
// is unique for each local user, and <application-id> is the one
// defined in .eclipseproduct marker file. If .eclipseproduct does not
// exist, use "eclipse" as the application-id.
URL installURL = computeInstallConfigurationLocation();
if (installURL != null) {
File installDir = new File(installURL.getFile());
if ("file".equals(installURL.getProtocol()) && canWrite(installDir)) //$NON-NLS-1$
return new File(installDir, CONFIG_DIR).getAbsolutePath();
}
// We can't write in the eclipse install dir so try for some place in the user's home dir
return computeDefaultUserAreaLocation(CONFIG_DIR);
}
private static boolean canWrite(File installDir) {
if (installDir.canWrite() == false)
return false;
if (!installDir.isDirectory())
return false;
File fileTest = null;
try {
fileTest = File.createTempFile("writtableArea", null, installDir); //$NON-NLS-1$
} catch (IOException e) {
//If an exception occured while trying to create the file, it means that it is not writtable
return false;
} finally {
if (fileTest != null)
fileTest.delete();
}
return true;
}
private static String computeDefaultUserAreaLocation(String pathAppendage) {
// we store the state in <user.home>/.eclipse/<application-id>_<version> where <user.home>
// is unique for each local user, and <application-id> is the one
// defined in .eclipseproduct marker file. If .eclipseproduct does not
// exist, use "eclipse" as the application-id.
String installProperty = FrameworkProperties.getProperty(PROP_INSTALL_AREA);
URL installURL = buildURL(installProperty, true);
if (installURL == null)
return null;
File installDir = new File(installURL.getFile());
String appName = "." + ECLIPSE; //$NON-NLS-1$
File eclipseProduct = new File(installDir, PRODUCT_SITE_MARKER);
if (eclipseProduct.exists()) {
Properties props = new Properties();
try {
props.load(new FileInputStream(eclipseProduct));
String appId = props.getProperty(PRODUCT_SITE_ID);
if (appId == null || appId.trim().length() == 0)
appId = ECLIPSE;
String appVersion = props.getProperty(PRODUCT_SITE_VERSION);
if (appVersion == null || appVersion.trim().length() == 0)
appVersion = ""; //$NON-NLS-1$
appName += File.separator + appId + "_" + appVersion; //$NON-NLS-1$
} catch (IOException e) {
// Do nothing if we get an exception. We will default to a standard location
// in the user's home dir.
}
}
String userHome = FrameworkProperties.getProperty(PROP_USER_HOME);
return new File(userHome, appName + "/" + pathAppendage).getAbsolutePath(); //$NON-NLS-1$
}
/**
* Returns the user Location object
* @return the user Location object
*/
public static Location getUserLocation() {
return userLocation;
}
/**
* Returns the configuration Location object
* @return the configuration Location object
*/
public static Location getConfigurationLocation() {
return configurationLocation;
}
/**
* Returns the install Location object
* @return the install Location object
*/
public static Location getInstallLocation() {
return installLocation;
}
/**
* Returns the instance Location object
* @return the instance Location object
*/
public static Location getInstanceLocation() {
return instanceLocation;
}
/**
* Returns the File object under the configuration location used for the OSGi configuration
* @return the OSGi configuration directory
*/
public static File getOSGiConfigurationDir() {
// TODO assumes the URL is a file: url
return new File(configurationLocation.getURL().getFile(), FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME);
}
/**
* Returns a file from the configuration area that can be used by the framework
* @param filename the filename
* @return a file from the configuration area
*/
public static File getConfigurationFile(String filename) {
File dir = getOSGiConfigurationDir();
if (!dir.exists())
dir.mkdirs();
return new File(dir, filename);
}
}
| true | true | public static void initializeLocations() {
// do install location initialization first since others may depend on it
// assumes that the property is already set
installLocation = buildLocation(PROP_INSTALL_AREA, null, null, true);
Location temp = buildLocation(PROP_USER_AREA_DEFAULT, null, "", false); //$NON-NLS-1$
URL defaultLocation = temp == null ? null : temp.getURL();
if (defaultLocation == null)
defaultLocation = buildURL(new File(FrameworkProperties.getProperty(PROP_USER_HOME), "user").getAbsolutePath(), true); //$NON-NLS-1$
userLocation = buildLocation(PROP_USER_AREA, defaultLocation, "", false); //$NON-NLS-1$
temp = buildLocation(PROP_INSTANCE_AREA_DEFAULT, null, "", false); //$NON-NLS-1$
defaultLocation = temp == null ? null : temp.getURL();
if (defaultLocation == null)
defaultLocation = buildURL(new File(FrameworkProperties.getProperty(PROP_USER_DIR), "workspace").getAbsolutePath(), true); //$NON-NLS-1$
instanceLocation = buildLocation(PROP_INSTANCE_AREA, defaultLocation, "", false); //$NON-NLS-1$
mungeConfigurationLocation();
// compute a default but it is very unlikely to be used since main will have computed everything
temp = buildLocation(PROP_CONFIG_AREA_DEFAULT, null, "", false); //$NON-NLS-1$
defaultLocation = temp == null ? null : temp.getURL();
if (defaultLocation == null)
defaultLocation = buildURL(computeDefaultConfigurationLocation(), true);
configurationLocation = buildLocation(PROP_CONFIG_AREA, defaultLocation, "", false); //$NON-NLS-1$
// get the parent location based on the system property. This will have been set on the
// way in either by the caller/user or by main. There will be no parent location if we are not
// cascaded.
URL parentLocation = computeSharedConfigurationLocation();
if (parentLocation != null && !parentLocation.equals(configurationLocation.getURL())) {
Location parent = new BasicLocation(null, parentLocation, true);
((BasicLocation) configurationLocation).setParent(parent);
}
initializeDerivedConfigurationLocations();
}
| public static void initializeLocations() {
// do install location initialization first since others may depend on it
// assumes that the property is already set
installLocation = buildLocation(PROP_INSTALL_AREA, null, "", true); //$NON-NLS-1$
Location temp = buildLocation(PROP_USER_AREA_DEFAULT, null, "", false); //$NON-NLS-1$
URL defaultLocation = temp == null ? null : temp.getURL();
if (defaultLocation == null)
defaultLocation = buildURL(new File(FrameworkProperties.getProperty(PROP_USER_HOME), "user").getAbsolutePath(), true); //$NON-NLS-1$
userLocation = buildLocation(PROP_USER_AREA, defaultLocation, "", false); //$NON-NLS-1$
temp = buildLocation(PROP_INSTANCE_AREA_DEFAULT, null, "", false); //$NON-NLS-1$
defaultLocation = temp == null ? null : temp.getURL();
if (defaultLocation == null)
defaultLocation = buildURL(new File(FrameworkProperties.getProperty(PROP_USER_DIR), "workspace").getAbsolutePath(), true); //$NON-NLS-1$
instanceLocation = buildLocation(PROP_INSTANCE_AREA, defaultLocation, "", false); //$NON-NLS-1$
mungeConfigurationLocation();
// compute a default but it is very unlikely to be used since main will have computed everything
temp = buildLocation(PROP_CONFIG_AREA_DEFAULT, null, "", false); //$NON-NLS-1$
defaultLocation = temp == null ? null : temp.getURL();
if (defaultLocation == null)
defaultLocation = buildURL(computeDefaultConfigurationLocation(), true);
configurationLocation = buildLocation(PROP_CONFIG_AREA, defaultLocation, "", false); //$NON-NLS-1$
// get the parent location based on the system property. This will have been set on the
// way in either by the caller/user or by main. There will be no parent location if we are not
// cascaded.
URL parentLocation = computeSharedConfigurationLocation();
if (parentLocation != null && !parentLocation.equals(configurationLocation.getURL())) {
Location parent = new BasicLocation(null, parentLocation, true);
((BasicLocation) configurationLocation).setParent(parent);
}
initializeDerivedConfigurationLocations();
}
|
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/ITextualDate.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/ITextualDate.java
index 445d7305b..fc67d36e2 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/ui/ITextualDate.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/ITextualDate.java
@@ -1,266 +1,268 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.terminal.gwt.client.ui;
import java.util.Date;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.ContainerResizedListener;
import com.itmill.toolkit.terminal.gwt.client.Focusable;
import com.itmill.toolkit.terminal.gwt.client.LocaleNotLoadedException;
import com.itmill.toolkit.terminal.gwt.client.LocaleService;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
import com.itmill.toolkit.terminal.gwt.client.Util;
public class ITextualDate extends IDateField implements Paintable, Field,
ChangeListener, ContainerResizedListener, Focusable {
private static final String PARSE_ERROR_CLASSNAME = CLASSNAME
+ "-parseerror";
private final ITextField text;
private String formatStr;
private String width;
private boolean needLayout;
protected int fieldExtraWidth = -1;
public ITextualDate() {
super();
text = new ITextField();
text.addChangeListener(this);
add(text);
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
int origRes = currentResolution;
super.updateFromUIDL(uidl, client);
if (origRes != currentResolution) {
// force recreating format string
formatStr = null;
}
buildDate();
}
protected String getFormatString() {
if (formatStr == null) {
if (currentResolution == RESOLUTION_YEAR) {
formatStr = "yyyy"; // force full year
} else {
try {
String frmString = LocaleService
.getDateFormat(currentLocale);
frmString = cleanFormat(frmString);
String delim = LocaleService
.getClockDelimiter(currentLocale);
if (currentResolution >= RESOLUTION_HOUR) {
if (dts.isTwelveHourClock()) {
frmString += " hh";
} else {
frmString += " HH";
}
if (currentResolution >= RESOLUTION_MIN) {
frmString += ":mm";
if (currentResolution >= RESOLUTION_SEC) {
frmString += ":ss";
if (currentResolution >= RESOLUTION_MSEC) {
frmString += ".SSS";
}
}
}
if (dts.isTwelveHourClock()) {
frmString += " aaa";
}
}
formatStr = frmString;
} catch (LocaleNotLoadedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return formatStr;
}
/**
*
*/
protected void buildDate() {
removeStyleName(PARSE_ERROR_CLASSNAME);
// Create the initial text for the textfield
String dateText;
if (date != null) {
dateText = DateTimeFormat.getFormat(getFormatString()).format(date);
} else {
dateText = "";
}
text.setText(dateText);
text.setEnabled(enabled && !readonly);
if (readonly) {
text.addStyleName("i-readonly");
} else {
text.removeStyleName("i-readonly");
}
}
public void onChange(Widget sender) {
if (sender == text) {
if (!text.getText().equals("")) {
try {
date = DateTimeFormat.getFormat(getFormatString()).parse(
text.getText());
// remove possibly added invalid value indication
removeStyleName(PARSE_ERROR_CLASSNAME);
} catch (final Exception e) {
ApplicationConnection.getConsole().log(e.getMessage());
addStyleName(PARSE_ERROR_CLASSNAME);
client.updateVariable(id, "lastInvalidDateString", text
.getText(), false);
date = null;
}
} else {
date = null;
// remove possibly added invalid value indication
removeStyleName(PARSE_ERROR_CLASSNAME);
}
- showingDate = new Date(date.getTime());
+ if (date != null) {
+ showingDate = new Date(date.getTime());
+ }
// Update variables
// (only the smallest defining resolution needs to be
// immediate)
client.updateVariable(id, "year",
date != null ? date.getYear() + 1900 : -1,
currentResolution == IDateField.RESOLUTION_YEAR
&& immediate);
if (currentResolution >= IDateField.RESOLUTION_MONTH) {
client.updateVariable(id, "month", date != null ? date
.getMonth() + 1 : -1,
currentResolution == IDateField.RESOLUTION_MONTH
&& immediate);
}
if (currentResolution >= IDateField.RESOLUTION_DAY) {
client.updateVariable(id, "day", date != null ? date.getDate()
: -1, currentResolution == IDateField.RESOLUTION_DAY
&& immediate);
}
if (currentResolution >= IDateField.RESOLUTION_HOUR) {
client.updateVariable(id, "hour", date != null ? date
.getHours() : -1,
currentResolution == IDateField.RESOLUTION_HOUR
&& immediate);
}
if (currentResolution >= IDateField.RESOLUTION_MIN) {
client.updateVariable(id, "min", date != null ? date
.getMinutes() : -1,
currentResolution == IDateField.RESOLUTION_MIN
&& immediate);
}
if (currentResolution >= IDateField.RESOLUTION_SEC) {
client.updateVariable(id, "sec", date != null ? date
.getSeconds() : -1,
currentResolution == IDateField.RESOLUTION_SEC
&& immediate);
}
if (currentResolution == IDateField.RESOLUTION_MSEC) {
client.updateVariable(id, "msec",
date != null ? getMilliseconds() : -1, immediate);
}
}
}
private String cleanFormat(String format) {
// Remove unnecessary d & M if resolution is too low
if (currentResolution < IDateField.RESOLUTION_DAY) {
format = format.replaceAll("d", "");
}
if (currentResolution < IDateField.RESOLUTION_MONTH) {
format = format.replaceAll("M", "");
}
// Remove unsupported patterns
// TODO support for 'G', era designator (used at least in Japan)
format = format.replaceAll("[GzZwWkK]", "");
// Remove extra delimiters ('/' and '.')
while (format.startsWith("/") || format.startsWith(".")
|| format.startsWith("-")) {
format = format.substring(1);
}
while (format.endsWith("/") || format.endsWith(".")
|| format.endsWith("-")) {
format = format.substring(0, format.length() - 1);
}
// Remove duplicate delimiters
format = format.replaceAll("//", "/");
format = format.replaceAll("\\.\\.", ".");
format = format.replaceAll("--", "-");
return format.trim();
}
public void setWidth(String newWidth) {
if (!"".equals(newWidth) && (width == null || !newWidth.equals(width))) {
if (Util.isIE6()) {
text.setColumns(1); // in IE6 cols ~ min-width
}
needLayout = true;
width = newWidth;
super.setWidth(width);
iLayout();
if (newWidth.indexOf("%") < 0) {
needLayout = false;
}
} else {
if ("".equals(newWidth) && width != null && !"".equals(width)) {
super.setWidth("");
needLayout = true;
iLayout();
needLayout = false;
width = null;
}
}
}
/**
* Returns pixels in x-axis reserved for other than textfield content.
*
* @return extra width in pixels
*/
protected int getFieldExtraWidth() {
if (fieldExtraWidth < 0) {
text.setWidth("0px");
fieldExtraWidth = text.getOffsetWidth();
}
return fieldExtraWidth;
}
public void iLayout() {
if (needLayout) {
text.setWidth((getOffsetWidth() - getFieldExtraWidth()) + "px");
}
}
public void focus() {
text.setFocus(true);
}
}
| true | true | public void onChange(Widget sender) {
if (sender == text) {
if (!text.getText().equals("")) {
try {
date = DateTimeFormat.getFormat(getFormatString()).parse(
text.getText());
// remove possibly added invalid value indication
removeStyleName(PARSE_ERROR_CLASSNAME);
} catch (final Exception e) {
ApplicationConnection.getConsole().log(e.getMessage());
addStyleName(PARSE_ERROR_CLASSNAME);
client.updateVariable(id, "lastInvalidDateString", text
.getText(), false);
date = null;
}
} else {
date = null;
// remove possibly added invalid value indication
removeStyleName(PARSE_ERROR_CLASSNAME);
}
showingDate = new Date(date.getTime());
// Update variables
// (only the smallest defining resolution needs to be
// immediate)
client.updateVariable(id, "year",
date != null ? date.getYear() + 1900 : -1,
currentResolution == IDateField.RESOLUTION_YEAR
&& immediate);
if (currentResolution >= IDateField.RESOLUTION_MONTH) {
client.updateVariable(id, "month", date != null ? date
.getMonth() + 1 : -1,
currentResolution == IDateField.RESOLUTION_MONTH
&& immediate);
}
if (currentResolution >= IDateField.RESOLUTION_DAY) {
client.updateVariable(id, "day", date != null ? date.getDate()
: -1, currentResolution == IDateField.RESOLUTION_DAY
&& immediate);
}
if (currentResolution >= IDateField.RESOLUTION_HOUR) {
client.updateVariable(id, "hour", date != null ? date
.getHours() : -1,
currentResolution == IDateField.RESOLUTION_HOUR
&& immediate);
}
if (currentResolution >= IDateField.RESOLUTION_MIN) {
client.updateVariable(id, "min", date != null ? date
.getMinutes() : -1,
currentResolution == IDateField.RESOLUTION_MIN
&& immediate);
}
if (currentResolution >= IDateField.RESOLUTION_SEC) {
client.updateVariable(id, "sec", date != null ? date
.getSeconds() : -1,
currentResolution == IDateField.RESOLUTION_SEC
&& immediate);
}
if (currentResolution == IDateField.RESOLUTION_MSEC) {
client.updateVariable(id, "msec",
date != null ? getMilliseconds() : -1, immediate);
}
}
}
| public void onChange(Widget sender) {
if (sender == text) {
if (!text.getText().equals("")) {
try {
date = DateTimeFormat.getFormat(getFormatString()).parse(
text.getText());
// remove possibly added invalid value indication
removeStyleName(PARSE_ERROR_CLASSNAME);
} catch (final Exception e) {
ApplicationConnection.getConsole().log(e.getMessage());
addStyleName(PARSE_ERROR_CLASSNAME);
client.updateVariable(id, "lastInvalidDateString", text
.getText(), false);
date = null;
}
} else {
date = null;
// remove possibly added invalid value indication
removeStyleName(PARSE_ERROR_CLASSNAME);
}
if (date != null) {
showingDate = new Date(date.getTime());
}
// Update variables
// (only the smallest defining resolution needs to be
// immediate)
client.updateVariable(id, "year",
date != null ? date.getYear() + 1900 : -1,
currentResolution == IDateField.RESOLUTION_YEAR
&& immediate);
if (currentResolution >= IDateField.RESOLUTION_MONTH) {
client.updateVariable(id, "month", date != null ? date
.getMonth() + 1 : -1,
currentResolution == IDateField.RESOLUTION_MONTH
&& immediate);
}
if (currentResolution >= IDateField.RESOLUTION_DAY) {
client.updateVariable(id, "day", date != null ? date.getDate()
: -1, currentResolution == IDateField.RESOLUTION_DAY
&& immediate);
}
if (currentResolution >= IDateField.RESOLUTION_HOUR) {
client.updateVariable(id, "hour", date != null ? date
.getHours() : -1,
currentResolution == IDateField.RESOLUTION_HOUR
&& immediate);
}
if (currentResolution >= IDateField.RESOLUTION_MIN) {
client.updateVariable(id, "min", date != null ? date
.getMinutes() : -1,
currentResolution == IDateField.RESOLUTION_MIN
&& immediate);
}
if (currentResolution >= IDateField.RESOLUTION_SEC) {
client.updateVariable(id, "sec", date != null ? date
.getSeconds() : -1,
currentResolution == IDateField.RESOLUTION_SEC
&& immediate);
}
if (currentResolution == IDateField.RESOLUTION_MSEC) {
client.updateVariable(id, "msec",
date != null ? getMilliseconds() : -1, immediate);
}
}
}
|
diff --git a/src/edu/berkeley/cs162/KVClient.java b/src/edu/berkeley/cs162/KVClient.java
index c72fd93..a2b4fb9 100644
--- a/src/edu/berkeley/cs162/KVClient.java
+++ b/src/edu/berkeley/cs162/KVClient.java
@@ -1,214 +1,214 @@
/**
* Client component for generating load for the KeyValue store.
* This is also used by the Master server to reach the slave nodes.
*
* @author Mosharaf Chowdhury (http://www.mosharaf.com)
* @author Prashanth Mohan (http://www.cs.berkeley.edu/~prmohan)
*
* Copyright (c) 2012, University of California at Berkeley
* 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 University of California, Berkeley 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 AUTHORS 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 edu.berkeley.cs162;
import java.net.Socket;
import java.io.IOException;
import java.io.InputStream;
import java.net.UnknownHostException;
/**
* This class is used to communicate with (appropriately marshalling and unmarshalling)
* objects implementing the {@link KeyValueInterface}.
*
* @param <K> Java Generic type for the Key
* @param <V> Java Generic type for the Value
*/
public class KVClient implements KeyValueInterface {
private String server = null;
private int port = 0;
/**
* @param server is the DNS reference to the Key-Value server
* @param port is the port on which the Key-Value server is listening
*/
public KVClient(String server, int port) {
this.server = server;
this.port = port;
}
private Socket connectHost() throws KVException {
Socket socket = null;
try {
socket = new Socket(this.server, this.port);
} catch(UnknownHostException u) {
throw new KVException(new KVMessage("resp", "Network Error: Could not connect"));
} catch(IOException io) {
throw new KVException(new KVMessage("resp", "Network Error: Could not create socket"));
}
return socket;
}
private void closeHost(Socket sock) throws KVException {
try {
sock.close();
} catch(IOException io) {
throw new KVException(new KVMessage("resp", "Unknown Error: Couldn’t close connection"));
}
}
private void shutdownOut(Socket socket) throws KVException {
try {
socket.shutdownOutput();
} catch(IOException io) {
throw new KVException(new KVMessage("resp", "Unknown Error: Couldn’t shut down output"));
}
}
private InputStream setupInput(Socket socket) throws KVException {
InputStream in;
try {
in = socket.getInputStream();
} catch(IOException io) {
throw new KVException(new KVMessage("resp", "Network Error: Could not receive data"));
}
return in;
}
public void put(String key, String value) throws KVException {
Socket socket = connectHost();
KVMessage kvReq = new KVMessage("putreq");
kvReq.setKey(key);
kvReq.setValue(value);
kvReq.sendMessage(socket);
System.out.println("Request: " + kvReq.toXML());
shutdownOut(socket);
InputStream in = setupInput(socket);
KVMessage kvResp = new KVMessage(in);
if(!kvResp.getMessage().equals("Success")) {
throw new KVException(kvResp);
}
System.out.println("Response: " + kvResp.toXML());
closeHost(socket);
}
public String get(String key) throws KVException {
Socket socket = connectHost();
KVMessage kvReq = new KVMessage("getreq");
kvReq.setKey(key);
kvReq.sendMessage(socket);
System.out.println("Request: " + kvReq.toXML());
String result = "";
shutdownOut(socket);
InputStream in = setupInput(socket);
KVMessage kvResp = new KVMessage(in);
- if(!kvResp.getMessage().equals("Does not exist") && kvResp.getValue() == null) {
+ if(kvResp.getValue() == null) {
throw new KVException(kvResp);
}
result = kvResp.getValue();
System.out.println("Response:" + kvResp.toXML());
closeHost(socket);
return result;
}
public void del(String key) throws KVException {
Socket socket = connectHost();
KVMessage kvReq = new KVMessage("delreq");
kvReq.setKey(key);
kvReq.sendMessage(socket);
System.out.println("Request: " + kvReq.toXML());
shutdownOut(socket);
InputStream in = setupInput(socket);
KVMessage kvResp = new KVMessage(in);
if(!kvResp.getMessage().equals("Success"))
throw new KVException(kvResp);
System.out.println("Response:" + kvResp.toXML());
closeHost(socket);
}
// public boolean connectTest(){
// try {
// KVServer kvserver = new KVServer(100, 10);
// SocketServer sserver = new SocketServer("localhost", 8080);
// Thread server = new Thread(new runServer(kvserver, sserver));
// server.start();
// Socket socket = this.connectHost();
// sserver.stop();
// server.stop();
// while(server.isAlive()){
// Thread.currentThread().yield();
// }
// return socket.isConnected();
// } catch (Exception e){
// System.out.println(e.getMessage());
// return false;
// }
// }
// public boolean closeTest(){
// try {
// KVServer kvserver = new KVServer(100, 10);
// SocketServer sserver = new SocketServer("localhost", 8080);
// Thread server = new Thread(new runServer(kvserver, sserver));
// server.start();
// Socket socket = this.connectHost();
// this.closeHost(socket);
// sserver.stop();
// server.stop();
// while(server.isAlive()){
// Thread.currentThread().yield();
// }
// return socket.isClosed();
// } catch (Exception e){
// System.out.println(e.getMessage());
// return false;
// }
// }
// private class runServer implements Runnable{
// KVServer server;
// SocketServer ss;
// public runServer(KVServer s, SocketServer socketServer){
// kvclient.ss = socketServer;
// kvclient.server = s;
// }
// public void run(){
// try {
// System.out.println("Binding Server:");
// NetworkHandler handler = new KVClientHandler(kvclient.server);
// ss.addHandler(handler);
// ss.connect();
// System.out.println("Starting Server");
// ss.run();
// } catch (Exception e){
// ;
// }
// }
// }
}
| true | true | public String get(String key) throws KVException {
Socket socket = connectHost();
KVMessage kvReq = new KVMessage("getreq");
kvReq.setKey(key);
kvReq.sendMessage(socket);
System.out.println("Request: " + kvReq.toXML());
String result = "";
shutdownOut(socket);
InputStream in = setupInput(socket);
KVMessage kvResp = new KVMessage(in);
if(!kvResp.getMessage().equals("Does not exist") && kvResp.getValue() == null) {
throw new KVException(kvResp);
}
result = kvResp.getValue();
System.out.println("Response:" + kvResp.toXML());
closeHost(socket);
return result;
}
| public String get(String key) throws KVException {
Socket socket = connectHost();
KVMessage kvReq = new KVMessage("getreq");
kvReq.setKey(key);
kvReq.sendMessage(socket);
System.out.println("Request: " + kvReq.toXML());
String result = "";
shutdownOut(socket);
InputStream in = setupInput(socket);
KVMessage kvResp = new KVMessage(in);
if(kvResp.getValue() == null) {
throw new KVException(kvResp);
}
result = kvResp.getValue();
System.out.println("Response:" + kvResp.toXML());
closeHost(socket);
return result;
}
|
diff --git a/jsf2-integration/src/main/java/com/steeplesoft/jsf/facestester/context/mojarra/FacesTesterAnnotationScanner.java b/jsf2-integration/src/main/java/com/steeplesoft/jsf/facestester/context/mojarra/FacesTesterAnnotationScanner.java
index 57770d2..928ad64 100644
--- a/jsf2-integration/src/main/java/com/steeplesoft/jsf/facestester/context/mojarra/FacesTesterAnnotationScanner.java
+++ b/jsf2-integration/src/main/java/com/steeplesoft/jsf/facestester/context/mojarra/FacesTesterAnnotationScanner.java
@@ -1,121 +1,121 @@
/*
* Copyright (c) 2009, Jason Lee <[email protected]>
* 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 <ORGANIZATION> 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 HOLDER 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.steeplesoft.jsf.facestester.context.mojarra;
import com.steeplesoft.jsf.facestester.Util;
import com.sun.faces.spi.AnnotationProvider;
import java.io.File;
import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.faces.component.behavior.FacesBehavior;
import javax.faces.convert.FacesConverter;
import javax.faces.bean.ManagedBean;
import javax.faces.component.FacesComponent;
import javax.faces.event.NamedEvent;
import javax.faces.render.FacesBehaviorRenderer;
import javax.faces.render.FacesRenderer;
import javax.faces.validator.FacesValidator;
import javax.servlet.ServletContext;
/**
*
* @author jasonlee
*/
public class FacesTesterAnnotationScanner extends AnnotationProvider {
protected static Set<Class<? extends Annotation>> annotations = new HashSet<Class<? extends Annotation>>();
protected AnnotationProvider parentProvider;
public FacesTesterAnnotationScanner(ServletContext sc, AnnotationProvider parent) {
super(sc);
this.parentProvider = parent;
Collections.addAll(annotations,
FacesComponent.class,
FacesConverter.class,
FacesValidator.class,
FacesRenderer.class,
ManagedBean.class,
NamedEvent.class,
FacesBehavior.class,
FacesBehaviorRenderer.class);
}
@Override
public Map<Class<? extends Annotation>, Set<Class<?>>> getAnnotatedClasses() {
Map<Class<? extends Annotation>, Set<Class<?>>> annotatedClasses = new HashMap<Class<? extends Annotation>, Set<Class<?>>>();
// TODO: This needs to be configurable. Once I get this working...
processBuildDirectories(new File("target/classes"), annotatedClasses);
Map<Class<? extends Annotation>, Set<Class<?>>> parentsClasses = parentProvider.getAnnotatedClasses();
if (parentsClasses != null) {
annotatedClasses.putAll(parentsClasses);
}
return annotatedClasses;
}
protected void processBuildDirectories(File startingDir, Map<Class<? extends Annotation>, Set<Class<?>>> classList) {
assert (startingDir.exists());
assert (startingDir.isDirectory());
for (File file : startingDir.listFiles()) {
if (file.isDirectory()) {
processBuildDirectories(file, classList);
} else {
if (file.getName().endsWith(".class")) {
String classFile = file.getPath().substring("test/classes/".length() + 2);
- classFile = classFile.substring(0, classFile.length() - 6).replace("/", ".");
+ classFile = classFile.substring(0, classFile.length() - 6).replace(File.separator, ".");
try {
Class clazz = Class.forName(classFile);
for (Class annotation : annotations) {
if (clazz.isAnnotationPresent(annotation)) {
Set<Class<?>> classes = classList.get(annotation);
if (classes == null) {
classes = new HashSet<Class<?>>();
classList.put(annotation, classes);
}
classes.add(clazz);
}
}
} catch (ClassNotFoundException ex) {
//
}
}
}
}
}
}
| true | true | protected void processBuildDirectories(File startingDir, Map<Class<? extends Annotation>, Set<Class<?>>> classList) {
assert (startingDir.exists());
assert (startingDir.isDirectory());
for (File file : startingDir.listFiles()) {
if (file.isDirectory()) {
processBuildDirectories(file, classList);
} else {
if (file.getName().endsWith(".class")) {
String classFile = file.getPath().substring("test/classes/".length() + 2);
classFile = classFile.substring(0, classFile.length() - 6).replace("/", ".");
try {
Class clazz = Class.forName(classFile);
for (Class annotation : annotations) {
if (clazz.isAnnotationPresent(annotation)) {
Set<Class<?>> classes = classList.get(annotation);
if (classes == null) {
classes = new HashSet<Class<?>>();
classList.put(annotation, classes);
}
classes.add(clazz);
}
}
} catch (ClassNotFoundException ex) {
//
}
}
}
}
}
| protected void processBuildDirectories(File startingDir, Map<Class<? extends Annotation>, Set<Class<?>>> classList) {
assert (startingDir.exists());
assert (startingDir.isDirectory());
for (File file : startingDir.listFiles()) {
if (file.isDirectory()) {
processBuildDirectories(file, classList);
} else {
if (file.getName().endsWith(".class")) {
String classFile = file.getPath().substring("test/classes/".length() + 2);
classFile = classFile.substring(0, classFile.length() - 6).replace(File.separator, ".");
try {
Class clazz = Class.forName(classFile);
for (Class annotation : annotations) {
if (clazz.isAnnotationPresent(annotation)) {
Set<Class<?>> classes = classList.get(annotation);
if (classes == null) {
classes = new HashSet<Class<?>>();
classList.put(annotation, classes);
}
classes.add(clazz);
}
}
} catch (ClassNotFoundException ex) {
//
}
}
}
}
}
|
diff --git a/SimpleAgent/src/test/device/GripperTest.java b/SimpleAgent/src/test/device/GripperTest.java
index 714d8d8..63e99a3 100644
--- a/SimpleAgent/src/test/device/GripperTest.java
+++ b/SimpleAgent/src/test/device/GripperTest.java
@@ -1,238 +1,238 @@
/**
*
*/
package test.device;
import java.util.concurrent.CopyOnWriteArrayList;
import junit.framework.JUnit4TestAdapter;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import data.Host;
import device.Device;
import device.DeviceNode;
import device.Gripper;
import device.IDevice;
import device.IGripperListener;
/**
* @author sebastian
*
*/
public class GripperTest
{
static DeviceNode deviceNode;
static Gripper gripper;
IGripperListener cb;
boolean isOpen;
boolean isClosed;
boolean isClosedLifted;
boolean isReleasedOpen;
boolean isLifted;
boolean isReleased;
@BeforeClass public static void setUpBeforeClass() throws Exception
{
- int port = 6671;
+ int port = 6665;
String host = "localhost";
/** Device list */
CopyOnWriteArrayList<Device> devList = new CopyOnWriteArrayList<Device>();
devList.add( new Device(IDevice.DEVICE_GRIPPER_CODE,host,port,0) );
devList.add( new Device(IDevice.DEVICE_ACTARRAY_CODE,host,port,0) );
devList.add( new Device(IDevice.DEVICE_DIO_CODE,host,port,0) );
/** Host list */
CopyOnWriteArrayList<Host> hostList = new CopyOnWriteArrayList<Host>();
hostList.add(new Host(host,port));
/** Get the device node */
deviceNode = new DeviceNode(hostList.toArray(new Host[hostList.size()]), devList.toArray(new Device[devList.size()]));
assertNotNull(deviceNode);
deviceNode.runThreaded();
gripper = (Gripper) deviceNode.getDevice(new Device(IDevice.DEVICE_GRIPPER_CODE, null, -1, -1));
assertNotNull(gripper);
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
}
@AfterClass public static void tearDownAfterClass() throws Exception
{
deviceNode.shutdown();
}
@Before public void setUp()
{
cb = new IGripperListener()
{
@Override public void whenOpened() { doneOpen(); }
@Override public void whenClosed() { doneClose(); }
@Override public void whenLifted() { doneLift(); }
@Override public void whenReleased() { doneRelease(); }
@Override public void whenClosedLifted() { doneCL(); }
@Override public void whenReleasedOpened() { doneRO(); }
@Override public void whenError() { }
};
gripper.addIsDoneListener(cb);
}
@After public void tearDown()
{
gripper.removeIsDoneListener(cb);
}
void doneOpen()
{
isOpen = true;
System.out.println(" open.");
}
void doneClose()
{
isClosed = true;
System.out.println(" closed.");
}
void doneLift()
{
isLifted = true;
System.out.println(" lifted.");
}
void doneRelease()
{
isReleased = true;
System.out.println(" released.");
}
void doneCL()
{
isClosedLifted = true;
System.out.println(" closed and lifted.");
}
void doneRO()
{
isReleasedOpen = true;
System.out.println(" released and opened.");
}
/**
* Test method for {@link device.Gripper#stop()}.
*/
@Test public void testStop()
{
System.out.println("Test stop..");
gripper.stop();
}
/**
* Test method for {@link device.Gripper#open()}.
*/
@Test public void testOpen()
{
isOpen = false;
System.out.print("Test open..");
gripper.open(null);
try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); }
assertTrue( isOpen == true );
System.out.println();
}
/**
* Test method for {@link device.Gripper#close()}.
*/
@Test public void testClose()
{
isClosed = false;
System.out.print("Test close..");
gripper.close(null);
try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); }
assertTrue( isClosed == true );
System.out.println();
}
/**
* Test method for {@link device.Gripper#lift()}.
*/
@Test public void testLift()
{
isLifted = false;
System.out.print("Test lift..");
gripper.lift(null);
try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); }
assertEquals(isLifted, true);
System.out.println();
}
/**
* Test method for {@link device.Gripper#release()}.
*/
@Test public void testRelease()
{
isReleased = false;
System.out.print("Test release..");
gripper.release(null);
try { Thread.sleep(6000); } catch (InterruptedException e) { e.printStackTrace(); }
assertEquals(isReleased, true);
System.out.println();
}
/**
* Test method for {@link device.Gripper#lift()}.
*/
@Test public void testLift2()
{
isLifted = false;
System.out.print("Test lift..");
gripper.lift(null);
try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); }
assertEquals(isLifted, true);
System.out.println();
}
@Test public void testReleaseOpen()
{
isReleasedOpen = false;
System.out.print("Test release and open..");
gripper.releaseOpen(null);
try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); }
assertEquals(isReleasedOpen, true);
System.out.println();
}
@Test public void testcloseLift()
{
isClosedLifted = false;
System.out.print("Test close and lift..");
gripper.closeLift(null);
try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); }
assertEquals(isClosedLifted, true);
System.out.println();
}
/**
* Test method for {@link device.Gripper#getState()}.
*/
public Gripper.stateType getState()
{
Gripper.stateType state = gripper.getState();
System.out.println("Gripper state: "+state);
return state;
}
// @Test public void testLiftWithObject()
// {
// gripper.open();
// gripper.liftWithObject();
// }
/** To use JUnit test suite */
public static JUnit4TestAdapter suite()
{
return new JUnit4TestAdapter(GripperTest.class);
}
}
| true | true | @BeforeClass public static void setUpBeforeClass() throws Exception
{
int port = 6671;
String host = "localhost";
/** Device list */
CopyOnWriteArrayList<Device> devList = new CopyOnWriteArrayList<Device>();
devList.add( new Device(IDevice.DEVICE_GRIPPER_CODE,host,port,0) );
devList.add( new Device(IDevice.DEVICE_ACTARRAY_CODE,host,port,0) );
devList.add( new Device(IDevice.DEVICE_DIO_CODE,host,port,0) );
/** Host list */
CopyOnWriteArrayList<Host> hostList = new CopyOnWriteArrayList<Host>();
hostList.add(new Host(host,port));
/** Get the device node */
deviceNode = new DeviceNode(hostList.toArray(new Host[hostList.size()]), devList.toArray(new Device[devList.size()]));
assertNotNull(deviceNode);
deviceNode.runThreaded();
gripper = (Gripper) deviceNode.getDevice(new Device(IDevice.DEVICE_GRIPPER_CODE, null, -1, -1));
assertNotNull(gripper);
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
}
| @BeforeClass public static void setUpBeforeClass() throws Exception
{
int port = 6665;
String host = "localhost";
/** Device list */
CopyOnWriteArrayList<Device> devList = new CopyOnWriteArrayList<Device>();
devList.add( new Device(IDevice.DEVICE_GRIPPER_CODE,host,port,0) );
devList.add( new Device(IDevice.DEVICE_ACTARRAY_CODE,host,port,0) );
devList.add( new Device(IDevice.DEVICE_DIO_CODE,host,port,0) );
/** Host list */
CopyOnWriteArrayList<Host> hostList = new CopyOnWriteArrayList<Host>();
hostList.add(new Host(host,port));
/** Get the device node */
deviceNode = new DeviceNode(hostList.toArray(new Host[hostList.size()]), devList.toArray(new Device[devList.size()]));
assertNotNull(deviceNode);
deviceNode.runThreaded();
gripper = (Gripper) deviceNode.getDevice(new Device(IDevice.DEVICE_GRIPPER_CODE, null, -1, -1));
assertNotNull(gripper);
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
}
|
diff --git a/compute/src/main/java/org/jclouds/compute/RunScriptOnNodesException.java b/compute/src/main/java/org/jclouds/compute/RunScriptOnNodesException.java
index f16005b32..318bd3c32 100644
--- a/compute/src/main/java/org/jclouds/compute/RunScriptOnNodesException.java
+++ b/compute/src/main/java/org/jclouds/compute/RunScriptOnNodesException.java
@@ -1,96 +1,96 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <[email protected]>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.compute;
import java.util.Map;
import javax.annotation.Nullable;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.options.RunScriptOptions;
import org.jclouds.compute.util.ComputeUtils;
import org.jclouds.ssh.ExecResponse;
/**
*
* @author Adrian Cole
*/
public class RunScriptOnNodesException extends Exception {
/** The serialVersionUID */
private static final long serialVersionUID = -2272965726680821281L;
private final String tag;
private final byte[] runScript;
private final RunScriptOptions options;
private final Map<NodeMetadata, ExecResponse> successfulNodes;
private final Map<? extends NodeMetadata, ? extends Throwable> failedNodes;
private final Map<?, Exception> executionExceptions;
public RunScriptOnNodesException(String tag, final byte[] runScript,
@Nullable final RunScriptOptions options,
Map<NodeMetadata, ExecResponse> successfulNodes, Map<?, Exception> executionExceptions,
Map<? extends NodeMetadata, ? extends Throwable> failedNodes) {
- super(String.format("error runScript on node tag(%s) options(%s) exceptions: %s", tag,
+ super(String.format("error runScript on node tag(%s) options(%s)%n%s%n%s", tag,
options, ComputeUtils.createExecutionErrorMessage(executionExceptions), ComputeUtils
.createNodeErrorMessage(failedNodes)));
this.tag = tag;
this.runScript = runScript;
this.options = options;
this.successfulNodes = successfulNodes;
this.failedNodes = failedNodes;
this.executionExceptions = executionExceptions;
}
/**
*
* @return Nodes that performed ssh without error
*/
public Map<NodeMetadata, ExecResponse> getSuccessfulNodes() {
return successfulNodes;
}
/**
*
* @return Nodes that performed startup without error, but incurred problems applying options
*/
public Map<?, ? extends Throwable> getExecutionErrors() {
return executionExceptions;
}
/**
*
* @return Nodes that performed startup without error, but incurred problems applying options
*/
public Map<? extends NodeMetadata, ? extends Throwable> getNodeErrors() {
return failedNodes;
}
public String getTag() {
return tag;
}
public byte[] getRunScript() {
return runScript;
}
public RunScriptOptions getOptions() {
return options;
}
}
| true | true | public RunScriptOnNodesException(String tag, final byte[] runScript,
@Nullable final RunScriptOptions options,
Map<NodeMetadata, ExecResponse> successfulNodes, Map<?, Exception> executionExceptions,
Map<? extends NodeMetadata, ? extends Throwable> failedNodes) {
super(String.format("error runScript on node tag(%s) options(%s) exceptions: %s", tag,
options, ComputeUtils.createExecutionErrorMessage(executionExceptions), ComputeUtils
.createNodeErrorMessage(failedNodes)));
this.tag = tag;
this.runScript = runScript;
this.options = options;
this.successfulNodes = successfulNodes;
this.failedNodes = failedNodes;
this.executionExceptions = executionExceptions;
}
| public RunScriptOnNodesException(String tag, final byte[] runScript,
@Nullable final RunScriptOptions options,
Map<NodeMetadata, ExecResponse> successfulNodes, Map<?, Exception> executionExceptions,
Map<? extends NodeMetadata, ? extends Throwable> failedNodes) {
super(String.format("error runScript on node tag(%s) options(%s)%n%s%n%s", tag,
options, ComputeUtils.createExecutionErrorMessage(executionExceptions), ComputeUtils
.createNodeErrorMessage(failedNodes)));
this.tag = tag;
this.runScript = runScript;
this.options = options;
this.successfulNodes = successfulNodes;
this.failedNodes = failedNodes;
this.executionExceptions = executionExceptions;
}
|
diff --git a/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsConsoleParser.java b/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsConsoleParser.java
index 301d337c5..6d2f94869 100644
--- a/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsConsoleParser.java
+++ b/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsConsoleParser.java
@@ -1,175 +1,175 @@
/**********************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
**********************************************************************/
package org.eclipse.cdt.internal.core.index.ctagsindexer;
import java.util.StringTokenizer;
import org.eclipse.cdt.core.IConsoleParser;
import org.eclipse.cdt.core.search.ICSearchConstants;
import org.eclipse.cdt.internal.core.index.domsourceindexer.IndexEncoderUtil;
import org.eclipse.cdt.internal.core.index.impl.IndexedFile;
import org.eclipse.cdt.internal.core.search.indexing.IIndexEncodingConstants;
import org.eclipse.cdt.internal.core.search.indexing.IIndexEncodingConstants.EntryType;
/**
* @author Bogdan Gheorghe
*/
public class CTagsConsoleParser implements IConsoleParser {
final static String TAB_SEPARATOR = "\t"; //$NON-NLS-1$
final static String PATTERN_SEPARATOR = ";\""; //$NON-NLS-1$
final static String COLONCOLON = "::"; //$NON-NLS-1$
final static String LANGUAGE = "language"; //$NON-NLS-1$
final static String KIND = "kind"; //$NON-NLS-1$
final static String LINE = "line"; //$NON-NLS-1$
final static String FILE = "file"; //$NON-NLS-1$
final static String INHERITS = "inherits"; //$NON-NLS-1$
final static String ACCESS = "access"; //$NON-NLS-1$
final static String IMPLEMENTATION = "implementation"; //$NON-NLS-1$
final static String CLASS = "class"; //$NON-NLS-1$
final static String MACRO = "macro"; //$NON-NLS-1$
final static String ENUMERATOR = "enumerator"; //$NON-NLS-1$
final static String FUNCTION = "function"; //$NON-NLS-1$
final static String ENUM = "enum"; //$NON-NLS-1$
final static String MEMBER = "member"; //$NON-NLS-1$
final static String NAMESPACE = "namespace"; //$NON-NLS-1$
final static String PROTOTYPE = "prototype"; //$NON-NLS-1$
final static String STRUCT = "struct"; //$NON-NLS-1$
final static String TYPEDEF = "typedef"; //$NON-NLS-1$
final static String UNION = "union"; //$NON-NLS-1$
final static String VARIABLE = "variable"; //$NON-NLS-1$
final static String EXTERNALVAR = ""; //$NON-NLS-1$
private CTagsIndexerRunner indexer;
public CTagsConsoleParser(CTagsIndexerRunner indexer){
this.indexer = indexer;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.index.ctagsindexer.IConsoleParser#processLine(java.lang.String)
*/
public boolean processLine(String line) {
CTagEntry tempTag = new CTagEntry(this, line);
if (indexer != null)
encodeTag(tempTag);
return false;
}
public CTagEntry processLineReturnTag(String line){
CTagEntry tempTag = new CTagEntry(this, line);
return tempTag;
}
/**
* @param tempTag
*/
private void encodeTag(CTagEntry tempTag) {
EntryType entryType = null;
String kind = (String)tempTag.tagExtensionField.get(KIND);
if (kind == null)
return;
char[][] fullName = getQualifiedName(tempTag);
ICSearchConstants.LimitTo type = ICSearchConstants.DECLARATIONS;
if (kind.equals(CLASS)){
entryType = IIndexEncodingConstants.CLASS;
} else if (kind.equals(MACRO)){
entryType = IIndexEncodingConstants.MACRO;
} else if (kind.equals(ENUMERATOR)){
entryType = IIndexEncodingConstants.ENUMERATOR;
} else if (kind.equals(FUNCTION)){
entryType = IIndexEncodingConstants.FUNCTION;
} else if (kind.equals(ENUM)){
entryType = IIndexEncodingConstants.ENUM;
} else if (kind.equals(MEMBER)){
entryType = IIndexEncodingConstants.FIELD;
} else if (kind.equals(NAMESPACE)){
entryType = IIndexEncodingConstants.NAMESPACE;
} else if (kind.equals(PROTOTYPE)){
entryType = IIndexEncodingConstants.FUNCTION;
- type = ICSearchConstants.DEFINITIONS;
+ //type = ICSearchConstants.DEFINITIONS;
} else if (kind.equals(STRUCT)){
entryType = IIndexEncodingConstants.STRUCT;
} else if (kind.equals(TYPEDEF)){
entryType = IIndexEncodingConstants.TYPEDEF;
} else if (kind.equals(UNION)){
entryType = IIndexEncodingConstants.UNION;
} else if (kind.equals(VARIABLE)){
entryType = IIndexEncodingConstants.VAR;
} else if (kind.equals(EXTERNALVAR)){
}
if (entryType != null)
indexer.getOutput().addRef(IndexEncoderUtil.encodeEntry(fullName,entryType,type), getIndexFlag());
}
/**
* @return
*/
private int getIndexFlag() {
int fileNum = 0;
IndexedFile mainIndexFile = indexer.getOutput().getIndexedFile(
indexer.getResourceFile().getFullPath().toString());
if (mainIndexFile != null)
fileNum = mainIndexFile.getFileNumber();
return fileNum;
}
/**
* @param tempTag
* @return
*/
public char[][] getQualifiedName(CTagEntry tempTag) {
char[][] fullName = null;
String name = null;
String[] types = {NAMESPACE, CLASS, STRUCT, UNION, FUNCTION, ENUM};
for (int i=0; i<types.length; i++){
//look for name
name = (String) tempTag.tagExtensionField.get(types[i]);
if (name != null)
break;
}
if (name != null){
StringTokenizer st = new StringTokenizer(name, COLONCOLON);
fullName = new char[st.countTokens() + 1][];
int i=0;
while (st.hasMoreTokens()){
fullName[i] = st.nextToken().toCharArray();
i++;
}
fullName[i] = tempTag.elementName.toCharArray();
} else {
fullName = new char[1][];
fullName[0] = tempTag.elementName.toCharArray();
}
return fullName;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.index.ctagsindexer.IConsoleParser#shutdown()
*/
public void shutdown() {
// TODO Auto-generated method stub
}
}
| true | true | private void encodeTag(CTagEntry tempTag) {
EntryType entryType = null;
String kind = (String)tempTag.tagExtensionField.get(KIND);
if (kind == null)
return;
char[][] fullName = getQualifiedName(tempTag);
ICSearchConstants.LimitTo type = ICSearchConstants.DECLARATIONS;
if (kind.equals(CLASS)){
entryType = IIndexEncodingConstants.CLASS;
} else if (kind.equals(MACRO)){
entryType = IIndexEncodingConstants.MACRO;
} else if (kind.equals(ENUMERATOR)){
entryType = IIndexEncodingConstants.ENUMERATOR;
} else if (kind.equals(FUNCTION)){
entryType = IIndexEncodingConstants.FUNCTION;
} else if (kind.equals(ENUM)){
entryType = IIndexEncodingConstants.ENUM;
} else if (kind.equals(MEMBER)){
entryType = IIndexEncodingConstants.FIELD;
} else if (kind.equals(NAMESPACE)){
entryType = IIndexEncodingConstants.NAMESPACE;
} else if (kind.equals(PROTOTYPE)){
entryType = IIndexEncodingConstants.FUNCTION;
type = ICSearchConstants.DEFINITIONS;
} else if (kind.equals(STRUCT)){
entryType = IIndexEncodingConstants.STRUCT;
} else if (kind.equals(TYPEDEF)){
entryType = IIndexEncodingConstants.TYPEDEF;
} else if (kind.equals(UNION)){
entryType = IIndexEncodingConstants.UNION;
} else if (kind.equals(VARIABLE)){
entryType = IIndexEncodingConstants.VAR;
} else if (kind.equals(EXTERNALVAR)){
}
if (entryType != null)
indexer.getOutput().addRef(IndexEncoderUtil.encodeEntry(fullName,entryType,type), getIndexFlag());
}
| private void encodeTag(CTagEntry tempTag) {
EntryType entryType = null;
String kind = (String)tempTag.tagExtensionField.get(KIND);
if (kind == null)
return;
char[][] fullName = getQualifiedName(tempTag);
ICSearchConstants.LimitTo type = ICSearchConstants.DECLARATIONS;
if (kind.equals(CLASS)){
entryType = IIndexEncodingConstants.CLASS;
} else if (kind.equals(MACRO)){
entryType = IIndexEncodingConstants.MACRO;
} else if (kind.equals(ENUMERATOR)){
entryType = IIndexEncodingConstants.ENUMERATOR;
} else if (kind.equals(FUNCTION)){
entryType = IIndexEncodingConstants.FUNCTION;
} else if (kind.equals(ENUM)){
entryType = IIndexEncodingConstants.ENUM;
} else if (kind.equals(MEMBER)){
entryType = IIndexEncodingConstants.FIELD;
} else if (kind.equals(NAMESPACE)){
entryType = IIndexEncodingConstants.NAMESPACE;
} else if (kind.equals(PROTOTYPE)){
entryType = IIndexEncodingConstants.FUNCTION;
//type = ICSearchConstants.DEFINITIONS;
} else if (kind.equals(STRUCT)){
entryType = IIndexEncodingConstants.STRUCT;
} else if (kind.equals(TYPEDEF)){
entryType = IIndexEncodingConstants.TYPEDEF;
} else if (kind.equals(UNION)){
entryType = IIndexEncodingConstants.UNION;
} else if (kind.equals(VARIABLE)){
entryType = IIndexEncodingConstants.VAR;
} else if (kind.equals(EXTERNALVAR)){
}
if (entryType != null)
indexer.getOutput().addRef(IndexEncoderUtil.encodeEntry(fullName,entryType,type), getIndexFlag());
}
|
diff --git a/src/com/globalmesh/action/user/UserGetAction.java b/src/com/globalmesh/action/user/UserGetAction.java
index 5cff3f6..01db027 100644
--- a/src/com/globalmesh/action/user/UserGetAction.java
+++ b/src/com/globalmesh/action/user/UserGetAction.java
@@ -1,78 +1,78 @@
/**
*
*/
package com.globalmesh.action.user;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.globalmesh.dao.MovieDetailDAO;
import com.globalmesh.dao.SaleDAO;
import com.globalmesh.dao.UserDAO;
import com.globalmesh.dto.BookingDetails;
import com.globalmesh.dto.Sale;
import com.globalmesh.dto.User;
import com.globalmesh.util.Constants;
import com.globalmesh.util.Utility;
/**
* @author Dil
*
*/
@SuppressWarnings("serial")
public class UserGetAction extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String email = (String) req.getSession().getAttribute("email");
if(email == null){
req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message", Utility.getCONFG().getProperty(Constants.LOGIN_NEED_MESSAGE));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);
} else {
User user = null;
user = UserDAO.INSTANCE.getUserByEmail(email);
Calendar from = Calendar.getInstance();
from.add(Calendar.DATE, -1);
Calendar to = Calendar.getInstance();
- to.add(Calendar.DATE, 15);
+ to.add(Calendar.DATE, 31);
DateFormat showDateFormat = new SimpleDateFormat("yyyy-MM-dd");
DateFormat showTimeFormat = new SimpleDateFormat("hh:mm a");
List<Sale> userSale = SaleDAO.INSTANCE.listSalesFromTOByUser(from.getTime(), to.getTime(), user.getUserId());
List<BookingDetails> bookings = new ArrayList<BookingDetails>(userSale.size());
for (Sale sale : userSale) {
BookingDetails b = new BookingDetails();
b.setShowDate(showDateFormat.format(sale.getShowDate()));
b.setShowTime(showTimeFormat.format(sale.getShowDate()));
b.setTransactionDate(showDateFormat.format(sale.getTransactionDate()));
b.setSeatNumbers(sale.getSeats());
b.setMovieName(MovieDetailDAO.INSTANCE.getMovieById(sale.getMovie()).getMovieName());
b.setSaleId(sale.getId());
bookings.add(b);
}
req.setAttribute("bookings", bookings);
req.setAttribute("user", user);
req.setAttribute("msgClass", Constants.MSG_CSS_INFO);
req.setAttribute("message", Utility.getCONFG().getProperty(Constants.USER_PROFILE_UPDATE_INFO));
req.getRequestDispatcher("/profile.jsp").forward(req, resp);
}
}
}
| true | true | protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String email = (String) req.getSession().getAttribute("email");
if(email == null){
req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message", Utility.getCONFG().getProperty(Constants.LOGIN_NEED_MESSAGE));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);
} else {
User user = null;
user = UserDAO.INSTANCE.getUserByEmail(email);
Calendar from = Calendar.getInstance();
from.add(Calendar.DATE, -1);
Calendar to = Calendar.getInstance();
to.add(Calendar.DATE, 15);
DateFormat showDateFormat = new SimpleDateFormat("yyyy-MM-dd");
DateFormat showTimeFormat = new SimpleDateFormat("hh:mm a");
List<Sale> userSale = SaleDAO.INSTANCE.listSalesFromTOByUser(from.getTime(), to.getTime(), user.getUserId());
List<BookingDetails> bookings = new ArrayList<BookingDetails>(userSale.size());
for (Sale sale : userSale) {
BookingDetails b = new BookingDetails();
b.setShowDate(showDateFormat.format(sale.getShowDate()));
b.setShowTime(showTimeFormat.format(sale.getShowDate()));
b.setTransactionDate(showDateFormat.format(sale.getTransactionDate()));
b.setSeatNumbers(sale.getSeats());
b.setMovieName(MovieDetailDAO.INSTANCE.getMovieById(sale.getMovie()).getMovieName());
b.setSaleId(sale.getId());
bookings.add(b);
}
req.setAttribute("bookings", bookings);
req.setAttribute("user", user);
req.setAttribute("msgClass", Constants.MSG_CSS_INFO);
req.setAttribute("message", Utility.getCONFG().getProperty(Constants.USER_PROFILE_UPDATE_INFO));
req.getRequestDispatcher("/profile.jsp").forward(req, resp);
}
}
| protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String email = (String) req.getSession().getAttribute("email");
if(email == null){
req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message", Utility.getCONFG().getProperty(Constants.LOGIN_NEED_MESSAGE));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);
} else {
User user = null;
user = UserDAO.INSTANCE.getUserByEmail(email);
Calendar from = Calendar.getInstance();
from.add(Calendar.DATE, -1);
Calendar to = Calendar.getInstance();
to.add(Calendar.DATE, 31);
DateFormat showDateFormat = new SimpleDateFormat("yyyy-MM-dd");
DateFormat showTimeFormat = new SimpleDateFormat("hh:mm a");
List<Sale> userSale = SaleDAO.INSTANCE.listSalesFromTOByUser(from.getTime(), to.getTime(), user.getUserId());
List<BookingDetails> bookings = new ArrayList<BookingDetails>(userSale.size());
for (Sale sale : userSale) {
BookingDetails b = new BookingDetails();
b.setShowDate(showDateFormat.format(sale.getShowDate()));
b.setShowTime(showTimeFormat.format(sale.getShowDate()));
b.setTransactionDate(showDateFormat.format(sale.getTransactionDate()));
b.setSeatNumbers(sale.getSeats());
b.setMovieName(MovieDetailDAO.INSTANCE.getMovieById(sale.getMovie()).getMovieName());
b.setSaleId(sale.getId());
bookings.add(b);
}
req.setAttribute("bookings", bookings);
req.setAttribute("user", user);
req.setAttribute("msgClass", Constants.MSG_CSS_INFO);
req.setAttribute("message", Utility.getCONFG().getProperty(Constants.USER_PROFILE_UPDATE_INFO));
req.getRequestDispatcher("/profile.jsp").forward(req, resp);
}
}
|
diff --git a/sonar-server/src/main/java/org/sonar/server/permission/InternalPermissionTemplateService.java b/sonar-server/src/main/java/org/sonar/server/permission/InternalPermissionTemplateService.java
index 6afe026c32..db518e31d6 100644
--- a/sonar-server/src/main/java/org/sonar/server/permission/InternalPermissionTemplateService.java
+++ b/sonar-server/src/main/java/org/sonar/server/permission/InternalPermissionTemplateService.java
@@ -1,155 +1,155 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2013 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.permission;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.ServerComponent;
import org.sonar.core.user.PermissionDao;
import org.sonar.core.user.PermissionTemplateDto;
import org.sonar.core.user.UserDao;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ServerErrorException;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import java.util.List;
/**
* Used by ruby code <pre>Internal.permission_templates</pre>
*/
public class InternalPermissionTemplateService implements ServerComponent {
private static final Logger LOG = LoggerFactory.getLogger(InternalPermissionTemplateService.class);
private final PermissionDao permissionDao;
private final UserDao userDao;
public InternalPermissionTemplateService(PermissionDao permissionDao, UserDao userDao) {
this.permissionDao = permissionDao;
this.userDao = userDao;
}
@CheckForNull
public PermissionTemplate selectPermissionTemplate(String templateName) {
PermissionTemplateUpdater.checkUserCredentials();
PermissionTemplateDto permissionTemplateDto = permissionDao.selectPermissionTemplate(templateName);
return PermissionTemplate.create(permissionTemplateDto);
}
public List<PermissionTemplate> selectAllPermissionTemplates() {
PermissionTemplateUpdater.checkUserCredentials();
List<PermissionTemplate> permissionTemplates = Lists.newArrayList();
List<PermissionTemplateDto> permissionTemplateDtos = permissionDao.selectAllPermissionTemplates();
if(permissionTemplateDtos != null) {
for (PermissionTemplateDto permissionTemplateDto : permissionTemplateDtos) {
permissionTemplates.add(PermissionTemplate.create(permissionTemplateDto));
}
}
return permissionTemplates;
}
public PermissionTemplate createPermissionTemplate(String name, @Nullable String description) {
PermissionTemplateUpdater.checkUserCredentials();
validateTemplateName(null, name);
PermissionTemplateDto permissionTemplateDto = permissionDao.createPermissionTemplate(name, description);
if(permissionTemplateDto.getId() == null) {
String errorMsg = "Template creation failed";
LOG.error(errorMsg);
throw new ServerErrorException(errorMsg);
}
return PermissionTemplate.create(permissionTemplateDto);
}
public void updatePermissionTemplate(Long templateId, String newName, @Nullable String newDescription) {
PermissionTemplateUpdater.checkUserCredentials();
validateTemplateName(templateId, newName);
permissionDao.updatePermissionTemplate(templateId, newName, newDescription);
}
public void deletePermissionTemplate(Long templateId) {
PermissionTemplateUpdater.checkUserCredentials();
permissionDao.deletePermissionTemplate(templateId);
}
public void addUserPermission(String templateName, String permission, String userLogin) {
PermissionTemplateUpdater updater = new PermissionTemplateUpdater(templateName, permission, userLogin, permissionDao, userDao) {
@Override
protected void doExecute(Long templateId, String permission) {
Long userId = getUserId();
permissionDao.addUserPermission(templateId, userId, permission);
}
};
updater.executeUpdate();
}
public void removeUserPermission(String templateName, String permission, String userLogin) {
PermissionTemplateUpdater updater = new PermissionTemplateUpdater(templateName, permission, userLogin, permissionDao, userDao) {
@Override
protected void doExecute(Long templateId, String permission) {
Long userId = getUserId();
permissionDao.removeUserPermission(templateId, userId, permission);
}
};
updater.executeUpdate();
}
public void addGroupPermission(String templateName, String permission, String groupName) {
PermissionTemplateUpdater updater = new PermissionTemplateUpdater(templateName, permission, groupName, permissionDao, userDao) {
@Override
protected void doExecute(Long templateId, String permission) {
Long groupId = getGroupId();
permissionDao.addGroupPermission(templateId, groupId, permission);
}
};
updater.executeUpdate();
}
public void removeGroupPermission(String templateName, String permission, String groupName) {
PermissionTemplateUpdater updater = new PermissionTemplateUpdater(templateName, permission, groupName, permissionDao, userDao) {
@Override
protected void doExecute(Long templateId, String permission) {
Long groupId = getGroupId();
permissionDao.removeGroupPermission(templateId, groupId, permission);
}
};
updater.executeUpdate();
}
private void validateTemplateName(Long templateId, String templateName) {
if(templateName == null) {
String errorMsg = "The name field is mandatory";
LOG.error(errorMsg);
throw new BadRequestException(errorMsg);
}
List<PermissionTemplateDto> existingTemplates = permissionDao.selectAllPermissionTemplates();
if(existingTemplates != null) {
for (PermissionTemplateDto existingTemplate : existingTemplates) {
- if((templateId == null || templateId != existingTemplate.getId()) && (existingTemplate.getName().equals(templateName))) {
+ if((templateId == null || !existingTemplate.getId().equals(templateId)) && (existingTemplate.getName().equals(templateName))) {
String errorMsg = "A template with that name already exists";
LOG.error(errorMsg);
throw new BadRequestException(errorMsg);
}
}
}
}
}
| true | true | private void validateTemplateName(Long templateId, String templateName) {
if(templateName == null) {
String errorMsg = "The name field is mandatory";
LOG.error(errorMsg);
throw new BadRequestException(errorMsg);
}
List<PermissionTemplateDto> existingTemplates = permissionDao.selectAllPermissionTemplates();
if(existingTemplates != null) {
for (PermissionTemplateDto existingTemplate : existingTemplates) {
if((templateId == null || templateId != existingTemplate.getId()) && (existingTemplate.getName().equals(templateName))) {
String errorMsg = "A template with that name already exists";
LOG.error(errorMsg);
throw new BadRequestException(errorMsg);
}
}
}
}
| private void validateTemplateName(Long templateId, String templateName) {
if(templateName == null) {
String errorMsg = "The name field is mandatory";
LOG.error(errorMsg);
throw new BadRequestException(errorMsg);
}
List<PermissionTemplateDto> existingTemplates = permissionDao.selectAllPermissionTemplates();
if(existingTemplates != null) {
for (PermissionTemplateDto existingTemplate : existingTemplates) {
if((templateId == null || !existingTemplate.getId().equals(templateId)) && (existingTemplate.getName().equals(templateName))) {
String errorMsg = "A template with that name already exists";
LOG.error(errorMsg);
throw new BadRequestException(errorMsg);
}
}
}
}
|
diff --git a/src/main/java/org/mule/tooling/jubula/JubulaMojo.java b/src/main/java/org/mule/tooling/jubula/JubulaMojo.java
index 51f4055..ddc0490 100644
--- a/src/main/java/org/mule/tooling/jubula/JubulaMojo.java
+++ b/src/main/java/org/mule/tooling/jubula/JubulaMojo.java
@@ -1,190 +1,190 @@
/**
* Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com
*
* The software in this package is published under the terms of the CPAL v1.0
* license, a copy of which has been included with this distribution in the
* LICENSE.txt file.
*/
package org.mule.tooling.jubula;
import java.io.File;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.mule.tooling.jubula.cliexecutor.JubulaCliExecutor;
import org.mule.tooling.jubula.cliexecutor.JubulaCliExecutorFactory;
import org.mule.tooling.jubula.cliexecutor.SyncCallback;
/**
* Goal that runs Jubula Functional Tests.
*
* @goal test
* @phase integration-test
*/
public class JubulaMojo extends AbstractMojo {
/**
* Where the .js files will be located for running.
*
* @parameter expression="${project.build.directory}"
* @readonly
* @required
*/
private File buildDirectory;
/**
* The id for the aut being run.
*
* @parameter
* @required
*/
private String autId;
/**
* The working directory of the RCP under test.
*
* @parameter
* @required
*/
private String rcpWorkingDir;
/**
* The name of the executable file of the RCP.
*
* @parameter
* @required
*/
private String executableFileName;
/**
* The keyboard layout
*
* @parameter default-value="EN_US"
* @required
*/
private String keyboardLayout;
/**
* The address where the aut agent will be listening (localhost:60000 by
* default)
*
* @parameter default-value="localhost:60000"
* @required
*/
private String autAgentAddress;
/**
* The test project name
*
* @parameter
* @required
*/
private String projectName;
/**
* The test project version (1.0 by default)
*
* @parameter default-value="1.0"
* @required
*/
private String projectVersion;
/**
* The address of the database containing the jubula data (jdbc:..).
*
* @parameter
* @required
*/
private String databaseUrl;
/**
* The username to access the db
*
* @parameter
* @required
*/
private String databaseUser;
/**
* The password to access the db
*
* @parameter
* @required
*/
private String databasePassword;
/**
* The job to run
*
* @parameter
* @required
*/
private String testJob;
@Override
public void execute() throws MojoExecutionException {
JubulaMavenPluginContext.initializeContext(buildDirectory);
String jubulaInstallationPath = JubulaMavenPluginContext
.pathToJubulaInstallationDirectory();
JubulaCliExecutor jubulaCliExecutor = new JubulaCliExecutorFactory()
.getNewInstance(jubulaInstallationPath);
SyncCallback startAutAgentCallback = new SyncCallback();
// start the aut agent
jubulaCliExecutor.startAutAgent(startAutAgentCallback);
// now we should wait until the aut agent is live, but there's no
// indication of it, so... wait for a while
safeSleep(5000);
String workspacePath = new File(buildDirectory,
JubulaMavenPluginContext.RCPWORKSPACE_DIRECTORY_NAME)
.getAbsolutePath();
SyncCallback startAutCallback = new SyncCallback();
String[] hostAndPort = autAgentAddress.split(":");
if (hostAndPort.length != 2)
throw new MojoExecutionException(
"Please provide the AUT Agent address as <host>:<port>");
String autAgentHost = hostAndPort[0];
String autAgentPort = hostAndPort[1];
try {
jubulaCliExecutor.startAut(autId, rcpWorkingDir,
executableFileName, workspacePath, keyboardLayout,
autAgentHost, autAgentPort, startAutCallback);
// now we should wait until the aut is live, but there's no
// indication of it, so... wait for ANOTHER while
// TODO - maybe make this configurable by parameter
safeSleep(20000);
String datadir = ".";
String resultsDir = new File(buildDirectory,
JubulaMavenPluginContext.RESULTS_DIRECTORY_NAME)
.getAbsolutePath();
boolean runTests = jubulaCliExecutor.runTests(projectName,
projectVersion, workspacePath, databaseUrl, databaseUser,
databasePassword, autAgentHost, autAgentPort,
keyboardLayout, testJob, datadir, resultsDir);
- if (!runTests)
- throw new MojoExecutionException(
- "There were errors running the tests");
+// if (!runTests)
+// throw new MojoExecutionException(
+// "There were errors running the tests");
} finally {
jubulaCliExecutor.stopAutAgent();
}
}
private void safeSleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true | true | public void execute() throws MojoExecutionException {
JubulaMavenPluginContext.initializeContext(buildDirectory);
String jubulaInstallationPath = JubulaMavenPluginContext
.pathToJubulaInstallationDirectory();
JubulaCliExecutor jubulaCliExecutor = new JubulaCliExecutorFactory()
.getNewInstance(jubulaInstallationPath);
SyncCallback startAutAgentCallback = new SyncCallback();
// start the aut agent
jubulaCliExecutor.startAutAgent(startAutAgentCallback);
// now we should wait until the aut agent is live, but there's no
// indication of it, so... wait for a while
safeSleep(5000);
String workspacePath = new File(buildDirectory,
JubulaMavenPluginContext.RCPWORKSPACE_DIRECTORY_NAME)
.getAbsolutePath();
SyncCallback startAutCallback = new SyncCallback();
String[] hostAndPort = autAgentAddress.split(":");
if (hostAndPort.length != 2)
throw new MojoExecutionException(
"Please provide the AUT Agent address as <host>:<port>");
String autAgentHost = hostAndPort[0];
String autAgentPort = hostAndPort[1];
try {
jubulaCliExecutor.startAut(autId, rcpWorkingDir,
executableFileName, workspacePath, keyboardLayout,
autAgentHost, autAgentPort, startAutCallback);
// now we should wait until the aut is live, but there's no
// indication of it, so... wait for ANOTHER while
// TODO - maybe make this configurable by parameter
safeSleep(20000);
String datadir = ".";
String resultsDir = new File(buildDirectory,
JubulaMavenPluginContext.RESULTS_DIRECTORY_NAME)
.getAbsolutePath();
boolean runTests = jubulaCliExecutor.runTests(projectName,
projectVersion, workspacePath, databaseUrl, databaseUser,
databasePassword, autAgentHost, autAgentPort,
keyboardLayout, testJob, datadir, resultsDir);
if (!runTests)
throw new MojoExecutionException(
"There were errors running the tests");
} finally {
jubulaCliExecutor.stopAutAgent();
}
}
| public void execute() throws MojoExecutionException {
JubulaMavenPluginContext.initializeContext(buildDirectory);
String jubulaInstallationPath = JubulaMavenPluginContext
.pathToJubulaInstallationDirectory();
JubulaCliExecutor jubulaCliExecutor = new JubulaCliExecutorFactory()
.getNewInstance(jubulaInstallationPath);
SyncCallback startAutAgentCallback = new SyncCallback();
// start the aut agent
jubulaCliExecutor.startAutAgent(startAutAgentCallback);
// now we should wait until the aut agent is live, but there's no
// indication of it, so... wait for a while
safeSleep(5000);
String workspacePath = new File(buildDirectory,
JubulaMavenPluginContext.RCPWORKSPACE_DIRECTORY_NAME)
.getAbsolutePath();
SyncCallback startAutCallback = new SyncCallback();
String[] hostAndPort = autAgentAddress.split(":");
if (hostAndPort.length != 2)
throw new MojoExecutionException(
"Please provide the AUT Agent address as <host>:<port>");
String autAgentHost = hostAndPort[0];
String autAgentPort = hostAndPort[1];
try {
jubulaCliExecutor.startAut(autId, rcpWorkingDir,
executableFileName, workspacePath, keyboardLayout,
autAgentHost, autAgentPort, startAutCallback);
// now we should wait until the aut is live, but there's no
// indication of it, so... wait for ANOTHER while
// TODO - maybe make this configurable by parameter
safeSleep(20000);
String datadir = ".";
String resultsDir = new File(buildDirectory,
JubulaMavenPluginContext.RESULTS_DIRECTORY_NAME)
.getAbsolutePath();
boolean runTests = jubulaCliExecutor.runTests(projectName,
projectVersion, workspacePath, databaseUrl, databaseUser,
databasePassword, autAgentHost, autAgentPort,
keyboardLayout, testJob, datadir, resultsDir);
// if (!runTests)
// throw new MojoExecutionException(
// "There were errors running the tests");
} finally {
jubulaCliExecutor.stopAutAgent();
}
}
|
diff --git a/src/com/dmdirc/plugins/PluginInfo.java b/src/com/dmdirc/plugins/PluginInfo.java
index f61eaf697..e94968409 100644
--- a/src/com/dmdirc/plugins/PluginInfo.java
+++ b/src/com/dmdirc/plugins/PluginInfo.java
@@ -1,965 +1,965 @@
/*
* Copyright (c) 2006-2008 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* SVN: $Id$
*/
package com.dmdirc.plugins;
import com.dmdirc.Main;
import com.dmdirc.actions.ActionManager;
import com.dmdirc.actions.CoreActionType;
import com.dmdirc.util.resourcemanager.ResourceManager;
import com.dmdirc.logger.Logger;
import com.dmdirc.logger.ErrorLevel;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;
import java.util.List;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.net.URL;
import java.net.URISyntaxException;
public class PluginInfo implements Comparable<PluginInfo> {
/** Plugin Meta Data */
private Properties metaData = null;
/** URL that this plugin was loaded from */
private final URL url;
/** Filename for this plugin (taken from URL) */
private final String filename;
/** The actual Plugin from this jar */
private Plugin plugin = null;
/** The classloader used for this Plugin */
private PluginClassLoader classloader = null;
/** The resource manager used by this pluginInfo */
private ResourceManager myResourceManager = null;
/** Is this plugin only loaded temporarily? */
private boolean tempLoaded = false;
/** List of classes this plugin has */
private List<String> myClasses = new ArrayList<String>();
/** Requirements error message. */
private String requirementsError = "";
/** Last Error Message. */
private String lastError = "No Error";
/**
* Create a new PluginInfo.
*
* @param url URL to file that this plugin is stored in.
* @throws PluginException if there is an error loading the Plugin
* @since 0.6
*/
public PluginInfo(final URL url) throws PluginException {
this(url, true);
}
/**
* Create a new PluginInfo.
*
* @param url URL to file that this plugin is stored in.
* @param load Should this plugin be loaded, or is this just a placeholder? (true for load, false for placeholder)
* @throws PluginException if there is an error loading the Plugin
* @since 0.6
*/
public PluginInfo(final URL url, final boolean load) throws PluginException {
this.url = url;
this.filename = (new File(url.getPath())).getName();
ResourceManager res;
// Check for updates.
if (new File(getFullFilename()+".update").exists() && new File(getFullFilename()).delete()) {
new File(getFullFilename()+".update").renameTo(new File(getFullFilename()));
}
if (!load) {
// Load the metaData if available.
metaData = new Properties();
try {
res = getResourceManager();
if (res.resourceExists("META-INF/plugin.info")) {
metaData.load(res.getResourceInputStream("META-INF/plugin.info"));
}
} catch (IOException e) {
} catch (IllegalArgumentException e) {
}
return;
}
try {
res = getResourceManager();
} catch (IOException ioe) {
lastError = "Error with resourcemanager: "+ioe.getMessage();
throw new PluginException("Plugin "+filename+" failed to load, error with resourcemanager: "+ioe.getMessage(), ioe);
}
try {
if (res.resourceExists("META-INF/plugin.info")) {
metaData = new Properties();
metaData.load(res.getResourceInputStream("META-INF/plugin.info"));
} else {
lastError = "plugin.info not found";
throw new PluginException("Plugin "+filename+" failed to load, plugin.info doesn't exist in jar");
}
} catch (IOException e) {
lastError = "plugin.info IOException: "+e.getMessage();
throw new PluginException("Plugin "+filename+" failed to load, plugin.info failed to open - "+e.getMessage(), e);
} catch (IllegalArgumentException e) {
lastError = "plugin.info IllegalArgumentException: "+e.getMessage();
throw new PluginException("Plugin "+filename+" failed to load, plugin.info failed to open - "+e.getMessage(), e);
}
if (getVersion() < 0) {
lastError = "Incomplete plugin.info (Missing or invalid 'version')";
throw new PluginException("Plugin "+filename+" failed to load, incomplete plugin.info (Missing or invalid 'version')");
} else if (getAuthor().isEmpty()) {
lastError = "Incomplete plugin.info (Missing or invalid 'author')";
throw new PluginException("Plugin "+filename+" failed to load, incomplete plugin.info (Missing 'author')");
} else if (getName().isEmpty()) {
lastError = "Incomplete plugin.info (Missing or invalid 'name')";
throw new PluginException("Plugin "+filename+" failed to load, incomplete plugin.info (Missing 'name')");
} else if (getMinVersion().isEmpty()) {
lastError = "Incomplete plugin.info (Missing or invalid 'minversion')";
throw new PluginException("Plugin "+filename+" failed to load, incomplete plugin.info (Missing 'minversion')");
} else if (getMainClass().isEmpty()) {
lastError = "Incomplete plugin.info (Missing or invalid 'mainclass')";
throw new PluginException("Plugin "+filename+" failed to load, incomplete plugin.info (Missing 'mainclass')");
}
if (checkRequirements()) {
final String mainClass = getMainClass().replace('.', '/')+".class";
if (!res.resourceExists(mainClass)) {
lastError = "main class file ("+mainClass+") not found in jar.";
throw new PluginException("Plugin "+filename+" failed to load, main class file ("+mainClass+") not found in jar.");
}
for (final String classfilename : res.getResourcesStartingWith("")) {
String classname = classfilename.replace('/', '.');
if (classname.matches("^.*\\.class$")) {
classname = classname.replaceAll("\\.class$", "");
myClasses.add(classname);
}
}
if (isPersistant() && loadAll()) { loadEntirePlugin(); }
} else {
lastError = "One or more requirements not met ("+requirementsError+")";
throw new PluginException("Plugin "+filename+" was not loaded, one or more requirements not met ("+requirementsError+")");
}
}
/**
* Called when the plugin is updated using the updater.
* Reloads metaData and updates the list of files.
*/
public void pluginUpdated() {
try {
// Force a new resourcemanager just incase.
final ResourceManager res = getResourceManager(true);
myClasses.clear();
for (final String classfilename : res.getResourcesStartingWith("")) {
String classname = classfilename.replace('/', '.');
if (classname.matches("^.*\\.class$")) {
classname = classname.replaceAll("\\.class$", "");
myClasses.add(classname);
}
}
updateMetaData();
} catch (IOException ioe) {
}
}
/**
* Try to reload the metaData from the plugin.info file.
* If this fails, the old data will be used still.
*
* @return true if metaData was reloaded ok, else false.
*/
public boolean updateMetaData() {
try {
// Force a new resourcemanager just incase.
final ResourceManager res = getResourceManager(true);
if (res.resourceExists("META-INF/plugin.info")) {
final Properties newMetaData = new Properties();
newMetaData.load(res.getResourceInputStream("META-INF/plugin.info"));
metaData = newMetaData;
return true;
}
} catch (IOException ioe) {
} catch (IllegalArgumentException e) {
}
return false;
}
/**
* Get the contents of requirementsError
*
* @return requirementsError
*/
public String getRequirementsError() {
return requirementsError;
}
/**
* Get the resource manager for this plugin
*
* @throws IOException if there is any problem getting a ResourceManager for this plugin
*/
public synchronized ResourceManager getResourceManager() throws IOException {
return getResourceManager(false);
}
/**
* Get the resource manager for this plugin
*
* @param forceNew Force a new resource manager rather than using the old one.
* @throws IOException if there is any problem getting a ResourceManager for this plugin
* @since 0.6
*/
public synchronized ResourceManager getResourceManager(final boolean forceNew) throws IOException {
if (myResourceManager == null || forceNew) {
myResourceManager = ResourceManager.getResourceManager("jar://"+getFullFilename());
// Clear the resourcemanager in 10 seconds to stop us holding the file open
final Timer timer = new Timer(filename+"-resourcemanagerTimer");
final TimerTask timerTask = new TimerTask(){
public void run() {
myResourceManager = null;
}
};
timer.schedule(timerTask, 10000);
}
return myResourceManager;
}
/**
* Checks to see if the minimum version requirement of the plugin is
* satisfied.
* If either version is non-positive, the test passes.
* On failure, the requirementsError field will contain a user-friendly
* error message.
*
* @param desired The desired minimum version of DMDirc.
* @param actual The actual current version of DMDirc.
* @return True if the test passed, false otherwise
*/
protected boolean checkMinimumVersion(final String desired, final int actual) {
int idesired;
try {
idesired = Integer.parseInt(desired);
} catch (NumberFormatException ex) {
requirementsError = "'minversion' is a non-integer";
return false;
}
if (actual > 0 && idesired > 0 && actual < idesired) {
requirementsError = "Plugin is for a newer version of DMDirc";
return false;
} else {
return true;
}
}
/**
* Checks to see if the maximum version requirement of the plugin is
* satisfied.
* If either version is non-positive, the test passes.
* If the desired version is empty, the test passes.
* On failure, the requirementsError field will contain a user-friendly
* error message.
*
* @param desired The desired maximum version of DMDirc.
* @param actual The actual current version of DMDirc.
* @return True if the test passed, false otherwise
*/
protected boolean checkMaximumVersion(final String desired, final int actual) {
int idesired;
if (desired.isEmpty()) {
return true;
}
try {
idesired = Integer.parseInt(desired);
} catch (NumberFormatException ex) {
requirementsError = "'maxversion' is a non-integer";
return false;
}
if (actual > 0 && idesired > 0 && actual > idesired) {
requirementsError = "Plugin is for an older version of DMDirc";
return false;
} else {
return true;
}
}
/**
* Checks to see if the OS requirements of the plugin are satisfied.
* If the desired string is empty, the test passes.
* Otherwise it is used as one to three colon-delimited regular expressions,
* to test the name, version and architecture of the OS, respectively.
* On failure, the requirementsError field will contain a user-friendly
* error message.
*
* @param desired The desired OS requirements
* @param actualName The actual name of the OS
* @param actualVersion The actual version of the OS
* @param actualArch The actual architecture of the OS
* @return True if the test passes, false otherwise
*/
protected boolean checkOS(final String desired, final String actualName, final String actualVersion, final String actualArch) {
if (desired.isEmpty()) {
return true;
}
final String[] desiredParts = desired.split(":");
if (!actualName.toLowerCase().matches(desiredParts[0])) {
requirementsError = "Invalid OS. (Wanted: '" + desiredParts[0] + "', actual: '" + actualName + "')";
return false;
} else if (desiredParts.length > 1 && !actualVersion.toLowerCase().matches(desiredParts[1])) {
requirementsError = "Invalid OS version. (Wanted: '" + desiredParts[1] + "', actual: '" + actualVersion + "')";
return false;
} else if (desiredParts.length > 2 && !actualArch.toLowerCase().matches(desiredParts[2])) {
requirementsError = "Invalid OS architecture. (Wanted: '" + desiredParts[2] + "', actual: '" + actualArch + "')";
return false;
}
return true;
}
/**
* Checks to see if the UI requirements of the plugin are satisfied.
* If the desired string is empty, the test passes.
* Otherwise it is used as a regular expressions against the package of the
* UIController to test what UI is currently in use.
* On failure, the requirementsError field will contain a user-friendly
* error message.
*
* @param desired The desired UI requirements
* @param actual The package of the current UI in use.
* @return True if the test passes, false otherwise
*/
protected boolean checkUI(final String desired, final String actual) {
if (desired.isEmpty()) {
return true;
}
if (!actual.toLowerCase().matches(desired)) {
requirementsError = "Invalid UI. (Wanted: '" + desired + "', actual: '" + actual + "')";
return false;
}
return true;
}
/**
* Checks to see if the file requirements of the plugin are satisfied.
* If the desired string is empty, the test passes.
* Otherwise it is passed to File.exists() to see if the file is valid.
* Multiple files can be specified by using a "," to separate. And either/or
* files can be specified using a "|" (eg /usr/bin/bash|/bin/bash)
* If the test fails, the requirementsError field will contain a
* user-friendly error message.
*
* @param desired The desired file requirements
* @return True if the test passes, false otherwise
*/
protected boolean checkFiles(final String desired) {
if (desired.isEmpty()) {
return true;
}
for (String files : desired.split(",")) {
final String[] filelist = files.split("\\|");
boolean foundFile = false;
for (String file : filelist) {
if ((new File(file)).exists()) {
foundFile = true;
break;
}
}
if (!foundFile) {
requirementsError = "Required file '"+files+"' not found";
return false;
}
}
return true;
}
/**
* Checks to see if the plugin requirements of the plugin are satisfied.
* If the desired string is empty, the test passes.
* Plugins should be specified as:
* plugin1[:minversion[:maxversion]],plugin2[:minversion[:maxversion]]
* Plugins will be attempted to be loaded if not loaded, else the test will
* fail if the versions don't match, or the plugin isn't known.
* If the test fails, the requirementsError field will contain a
* user-friendly error message.
*
* @param desired The desired file requirements
* @return True if the test passes, false otherwise
*/
protected boolean checkPlugins(final String desired) {
if (desired.isEmpty()) {
return true;
}
for (String plugin : desired.split(",")) {
final String[] data = plugin.split(":");
final PluginInfo pi = PluginManager.getPluginManager().getPluginInfoByName(data[0], true);
if (pi == null) {
requirementsError = "Required plugin '"+data[0]+"' was not found";
return false;
} else {
if (data.length > 1) {
// Check plugin minimum version matches.
try {
final int minversion = Integer.parseInt(data[1]);
if (pi.getVersion() < minversion) {
requirementsError = "Plugin '"+data[0]+"' is too old (Required Version: "+minversion+", Actual Version: "+pi.getVersion()+")";
return false;
} else {
if (data.length > 2) {
// Check plugin maximum version matches.
try {
final int maxversion = Integer.parseInt(data[2]);
if (pi.getVersion() > maxversion) {
requirementsError = "Plugin '"+data[0]+"' is too new (Required Version: "+maxversion+", Actual Version: "+pi.getVersion()+")";
return false;
}
} catch (NumberFormatException nfe) {
requirementsError = "Plugin max-version '"+data[2]+"' for plugin ('"+data[0]+"') is a non-integer";
return false;
}
}
}
} catch (NumberFormatException nfe) {
requirementsError = "Plugin min-version '"+data[1]+"' for plugin ('"+data[0]+"') is a non-integer";
return false;
}
}
}
}
return true;
}
/**
* Are the requirements for this plugin met?
*
* @return true/false (Actual error if false is in the requirementsError field)
*/
public boolean checkRequirements() {
if (metaData == null) {
// No meta-data, so no requirements.
return true;
}
final String uiPackage;
if (Main.getUI().getClass().getPackage() != null) {
uiPackage = Main.getUI().getClass().getPackage().getName();
} else {
final String uiController = Main.getUI().getClass().getName();
if (uiController.lastIndexOf('.') >= 0) {
uiPackage = uiController.substring(0,uiController.lastIndexOf('.'));
} else {
uiPackage = uiController;
}
}
if (!checkMinimumVersion(getMinVersion(), Main.SVN_REVISION) ||
!checkMaximumVersion(getMaxVersion(), Main.SVN_REVISION) ||
!checkOS(getMetaInfo(new String[]{"required-os", "require-os"}), System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch")) ||
!checkFiles(getMetaInfo(new String[]{"required-files", "require-files", "required-file", "require-file"})) ||
!checkUI(getMetaInfo(new String[]{"required-ui", "require-ui"}), uiPackage) ||
!checkPlugins(getMetaInfo(new String[]{"required-plugins", "require-plugins", "required-plugin", "require-plugin"}))
) {
return false;
}
// All requirements passed, woo \o
return true;
}
/**
* Is this plugin loaded?
*/
public boolean isLoaded() {
return (plugin != null) && !tempLoaded;
}
/**
* Is this plugin temporarily loaded?
*/
public boolean isTempLoaded() {
return (plugin != null) && tempLoaded;
}
/**
* Load entire plugin.
* This loads all files in the jar immediately.
*
* @throws PluginException if there is an error with the resourcemanager
*/
private void loadEntirePlugin() throws PluginException {
// Load the main "Plugin" from the jar
loadPlugin();
// Now load all the rest.
for (String classname : myClasses) {
loadClass(classname);
}
}
/**
* Try to Load the plugin files temporarily.
*/
public void loadPluginTemp() {
tempLoaded = true;
loadPlugin();
}
/**
* Load any required plugins
*/
public void loadRequired() {
final String required = getMetaInfo(new String[]{"required-plugins", "require-plugins", "required-plugin", "require-plugin"});
for (String plugin : required.split(",")) {
final String[] data = plugin.split(":");
if (!data[0].trim().isEmpty()) {
final PluginInfo pi = PluginManager.getPluginManager().getPluginInfoByName(data[0], true);
if (pi == null) {
return;
}
if (tempLoaded) {
pi.loadPluginTemp();
} else {
pi.loadPlugin();
}
}
}
}
/**
* Load the plugin files.
*/
public void loadPlugin() {
if (isTempLoaded()) {
tempLoaded = false;
loadRequired();
plugin.onLoad();
} else {
if (isLoaded() || metaData == null) {
lastError = "Not Loading: ("+isLoaded()+"||"+(metaData == null)+")";
return;
}
loadRequired();
loadClass(getMainClass());
if (isLoaded()) {
ActionManager.processEvent(CoreActionType.PLUGIN_LOADED, null, this);
}
}
}
/**
* Load the given classname.
*
* @param classname Class to load
*/
private void loadClass(final String classname) {
try {
if (classloader == null) {
classloader = new PluginClassLoader(this);
}
// Don't reload a class if its already loaded.
if (classloader.isClassLoaded(classname, true)) {
lastError = "Classloader says we are already loaded.";
return;
}
final Class<?> c = classloader.loadClass(classname);
final Constructor<?> constructor = c.getConstructor(new Class[] {});
// Only try and construct the main class, anything else should be constructed
// by the plugin itself.
if (classname.equals(getMainClass())) {
final Object temp = constructor.newInstance(new Object[] {});
if (temp instanceof Plugin) {
if (((Plugin) temp).checkPrerequisites()) {
plugin = (Plugin) temp;
if (!tempLoaded) {
try {
plugin.onLoad();
} catch (Exception e) {
lastError = "Error in onLoad for "+getName()+":"+e.getMessage();
Logger.userError(ErrorLevel.MEDIUM, "Error in onLoad for "+getName()+":"+e.getMessage(), e);
unloadPlugin();
}
}
} else {
if (!tempLoaded) {
lastError = "Prerequisites for plugin not met. ('"+filename+":"+getMainClass()+"')";
Logger.userError(ErrorLevel.LOW, "Prerequisites for plugin not met. ('"+filename+":"+getMainClass()+"')");
}
}
}
}
} catch (ClassNotFoundException cnfe) {
lastError = "Class not found ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+cnfe.getMessage();
Logger.userError(ErrorLevel.LOW, "Class not found ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+cnfe.getMessage(), cnfe);
} catch (NoSuchMethodException nsme) {
// Don't moan about missing constructors for any class thats not the main Class
lastError = "Constructor missing ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+nsme.getMessage();
if (classname.equals(getMainClass())) {
Logger.userError(ErrorLevel.LOW, "Constructor missing ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+nsme.getMessage(), nsme);
}
} catch (IllegalAccessException iae) {
lastError = "Unable to access constructor ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+iae.getMessage();
Logger.userError(ErrorLevel.LOW, "Unable to access constructor ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+iae.getMessage(), iae);
} catch (InvocationTargetException ite) {
lastError = "Unable to invoke target ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+ite.getMessage();
Logger.userError(ErrorLevel.LOW, "Unable to invoke target ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+ite.getMessage(), ite);
} catch (InstantiationException ie) {
lastError = "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+ie.getMessage();
Logger.userError(ErrorLevel.LOW, "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+ie.getMessage(), ie);
} catch (NoClassDefFoundError ncdf) {
lastError = "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - Unable to find class: " + ncdf.getMessage();
Logger.userError(ErrorLevel.LOW, "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - Unable to find class: " + ncdf.getMessage(), ncdf);
} catch (VerifyError ve) {
lastError = "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - Incompatible: "+ve.getMessage();
Logger.userError(ErrorLevel.LOW, "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - Incompatible: "+ve.getMessage(), ve);
}
}
/**
* Unload the plugin if possible.
*/
public void unloadPlugin() {
if (!isPersistant() && (isLoaded() || isTempLoaded())) {
if (!isTempLoaded()) {
try {
plugin.onUnload();
} catch (Exception e) {
lastError = "Error in onUnload for "+getName()+":"+e.getMessage();
Logger.userError(ErrorLevel.MEDIUM, "Error in onUnload for "+getName()+":"+e.getMessage(), e);
}
ActionManager.processEvent(CoreActionType.PLUGIN_UNLOADED, null, this);
}
tempLoaded = false;
plugin = null;
classloader = null;
}
}
/**
* Get the last Error
*
* @return last Error
*/
public String getLastError() { return lastError; }
/**
* Get the list of Classes
*
* @return Classes this plugin has
*/
public List<String> getClassList() {
return myClasses;
}
/**
* Get the main Class
*
* @return Main Class to begin loading.
*/
public String getMainClass() { return metaData.getProperty("mainclass",""); }
/**
* Get the Plugin for this plugin.
*
* @return Plugin
*/
public Plugin getPlugin() { return plugin; }
/**
* Get the PluginClassLoader for this plugin.
*
* @return PluginClassLoader
*/
protected PluginClassLoader getPluginClassLoader() { return classloader; }
/**
* Get the plugin friendly version
*
* @return Plugin friendly Version
*/
- public String getFriendlyVersion() { return metaData.getProperty("friendlyversion",""); }
+ public String getFriendlyVersion() { return metaData.getProperty("friendlyversion", getVersion()); }
/**
* Get the plugin version
*
* @return Plugin Version
*/
public int getVersion() {
try {
return Integer.parseInt(metaData.getProperty("version","0"));
} catch (NumberFormatException nfe) {
return -1;
}
}
/**
* Get the id for this plugin on the addons site.
* If a plugin has been submitted to addons.dmdirc.com, and plugin.info
* contains a property addonid then this will return it.
* This is used along with the version property to allow the auto-updater to
* update the addon if the author submits a new version to the addons site.
*
* @return Addon Site ID number
* -1 If not present
* -2 If non-integer
*/
public int getAddonID() {
try {
return Integer.parseInt(metaData.getProperty("addonid","-1"));
} catch (NumberFormatException nfe) {
return -2;
}
}
/**
* Is this a persistant plugin?
*
* @return true if persistant, else false
*/
public boolean isPersistant() {
final String persistance = metaData.getProperty("persistant","no");
return persistance.equalsIgnoreCase("true") || persistance.equalsIgnoreCase("yes");
}
/**
* Does this plugin contain any persistant classes?
*
* @return true if this plugin contains any persistant classes, else false
*/
public boolean hasPersistant() {
final String persistance = metaData.getProperty("persistant","no");
if (persistance.equalsIgnoreCase("true")) {
return true;
} else {
for (Object keyObject : metaData.keySet()) {
if (keyObject.toString().toLowerCase().startsWith("persistant-")) {
return true;
}
}
}
return false;
}
/**
* Get a list of all persistant classes in this plugin
*
* @return List of all persistant classes in this plugin
*/
public List<String> getPersistantClasses() {
final List<String> result = new ArrayList<String>();
final String persistance = metaData.getProperty("persistant","no");
if (persistance.equalsIgnoreCase("true")) {
try {
ResourceManager res = getResourceManager();
for (final String filename : res.getResourcesStartingWith("")) {
if (filename.matches("^.*\\.class$")) {
result.add(filename.replaceAll("\\.class$", "").replace('/', '.'));
}
}
} catch (IOException e) {
// Jar no longer exists?
}
} else {
for (Object keyObject : metaData.keySet()) {
if (keyObject.toString().toLowerCase().startsWith("persistant-")) {
result.add(keyObject.toString().substring(11));
}
}
}
return result;
}
/**
* Is this a persistant class?
*
* @param classname class to check persistance of
* @return true if file (or whole plugin) is persistant, else false
*/
public boolean isPersistant(final String classname) {
if (isPersistant()) {
return true;
} else {
final String persistance = metaData.getProperty("persistant-"+classname,"no");
return persistance.equalsIgnoreCase("true") || persistance.equalsIgnoreCase("yes");
}
}
/**
* Get the plugin Filename.
*
* @return Filename of plugin
*/
public String getFilename() { return filename; }
/**
* Get the full plugin Filename (inc dirname)
*
* @return Filename of plugin
*/
public String getFullFilename() { return url.getPath(); }
/**
* Get the plugin Author.
*
* @return Author of plugin
*/
public String getAuthor() { return getMetaInfo("author",""); }
/**
* Get the plugin Description.
*
* @return Description of plugin
*/
public String getDescription() { return getMetaInfo("description",""); }
/**
* Get the minimum dmdirc version required to run the plugin.
*
* @return minimum dmdirc version required to run the plugin.
*/
public String getMinVersion() { return getMetaInfo("minversion",""); }
/**
* Get the (optional) maximum dmdirc version on which this plugin can run
*
* @return optional maximum dmdirc version on which this plugin can run
*/
public String getMaxVersion() { return getMetaInfo("maxversion",""); }
/**
* Get the name of the plugin. (Used to identify the plugin)
*
* @return Name of plugin
*/
public String getName() { return getMetaInfo("name",""); }
/**
* Get the nice name of the plugin. (Displayed to users)
*
* @return Nice Name of plugin
*/
public String getNiceName() { return getMetaInfo("nicename",getName()); }
/**
* String Representation of this plugin
*
* @return String Representation of this plugin
*/
@Override
public String toString() { return getNiceName()+" - "+filename; }
/**
* Does this plugin want all its classes loaded?
*
* @return true/false if loadall=true || loadall=yes
*/
public boolean loadAll() {
final String loadAll = metaData.getProperty("loadall","no");
return loadAll.equalsIgnoreCase("true") || loadAll.equalsIgnoreCase("yes");
}
/**
* Get misc meta-information.
*
* @param metainfo The metainfo to return
* @return Misc Meta Info (or "" if not found);
*/
public String getMetaInfo(final String metainfo) { return getMetaInfo(metainfo,""); }
/**
* Get misc meta-information.
*
* @param metainfo The metainfo to return
* @param fallback Fallback value if requested value is not found
* @return Misc Meta Info (or fallback if not found);
*/
public String getMetaInfo(final String metainfo, final String fallback) { return metaData.getProperty(metainfo,fallback); }
/**
* Get misc meta-information.
*
* @param metainfo The metainfos to look for in order. If the first item in
* the array is not found, the next will be looked for, and
* so on until either one is found, or none are found.
* @return Misc Meta Info (or "" if none are found);
*/
public String getMetaInfo(final String[] metainfo) { return getMetaInfo(metainfo,""); }
/**
* Get misc meta-information.
*
* @param metainfo The metainfos to look for in order. If the first item in
* the array is not found, the next will be looked for, and
* so on until either one is found, or none are found.
* @param fallback Fallback value if requested values are not found
* @return Misc Meta Info (or "" if none are found);
*/
public String getMetaInfo(final String[] metainfo, final String fallback) {
for (String meta : metainfo) {
String result = metaData.getProperty(meta);
if (result != null) { return result; }
}
return fallback;
}
/**
* Compares this object with the specified object for order.
* Returns a negative integer, zero, or a positive integer as per String.compareTo();
*
* @param o Object to compare to
* @return a negative integer, zero, or a positive integer.
*/
@Override
public int compareTo(final PluginInfo o) {
return toString().compareTo(o.toString());
}
}
| true | true | public boolean checkRequirements() {
if (metaData == null) {
// No meta-data, so no requirements.
return true;
}
final String uiPackage;
if (Main.getUI().getClass().getPackage() != null) {
uiPackage = Main.getUI().getClass().getPackage().getName();
} else {
final String uiController = Main.getUI().getClass().getName();
if (uiController.lastIndexOf('.') >= 0) {
uiPackage = uiController.substring(0,uiController.lastIndexOf('.'));
} else {
uiPackage = uiController;
}
}
if (!checkMinimumVersion(getMinVersion(), Main.SVN_REVISION) ||
!checkMaximumVersion(getMaxVersion(), Main.SVN_REVISION) ||
!checkOS(getMetaInfo(new String[]{"required-os", "require-os"}), System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch")) ||
!checkFiles(getMetaInfo(new String[]{"required-files", "require-files", "required-file", "require-file"})) ||
!checkUI(getMetaInfo(new String[]{"required-ui", "require-ui"}), uiPackage) ||
!checkPlugins(getMetaInfo(new String[]{"required-plugins", "require-plugins", "required-plugin", "require-plugin"}))
) {
return false;
}
// All requirements passed, woo \o
return true;
}
/**
* Is this plugin loaded?
*/
public boolean isLoaded() {
return (plugin != null) && !tempLoaded;
}
/**
* Is this plugin temporarily loaded?
*/
public boolean isTempLoaded() {
return (plugin != null) && tempLoaded;
}
/**
* Load entire plugin.
* This loads all files in the jar immediately.
*
* @throws PluginException if there is an error with the resourcemanager
*/
private void loadEntirePlugin() throws PluginException {
// Load the main "Plugin" from the jar
loadPlugin();
// Now load all the rest.
for (String classname : myClasses) {
loadClass(classname);
}
}
/**
* Try to Load the plugin files temporarily.
*/
public void loadPluginTemp() {
tempLoaded = true;
loadPlugin();
}
/**
* Load any required plugins
*/
public void loadRequired() {
final String required = getMetaInfo(new String[]{"required-plugins", "require-plugins", "required-plugin", "require-plugin"});
for (String plugin : required.split(",")) {
final String[] data = plugin.split(":");
if (!data[0].trim().isEmpty()) {
final PluginInfo pi = PluginManager.getPluginManager().getPluginInfoByName(data[0], true);
if (pi == null) {
return;
}
if (tempLoaded) {
pi.loadPluginTemp();
} else {
pi.loadPlugin();
}
}
}
}
/**
* Load the plugin files.
*/
public void loadPlugin() {
if (isTempLoaded()) {
tempLoaded = false;
loadRequired();
plugin.onLoad();
} else {
if (isLoaded() || metaData == null) {
lastError = "Not Loading: ("+isLoaded()+"||"+(metaData == null)+")";
return;
}
loadRequired();
loadClass(getMainClass());
if (isLoaded()) {
ActionManager.processEvent(CoreActionType.PLUGIN_LOADED, null, this);
}
}
}
/**
* Load the given classname.
*
* @param classname Class to load
*/
private void loadClass(final String classname) {
try {
if (classloader == null) {
classloader = new PluginClassLoader(this);
}
// Don't reload a class if its already loaded.
if (classloader.isClassLoaded(classname, true)) {
lastError = "Classloader says we are already loaded.";
return;
}
final Class<?> c = classloader.loadClass(classname);
final Constructor<?> constructor = c.getConstructor(new Class[] {});
// Only try and construct the main class, anything else should be constructed
// by the plugin itself.
if (classname.equals(getMainClass())) {
final Object temp = constructor.newInstance(new Object[] {});
if (temp instanceof Plugin) {
if (((Plugin) temp).checkPrerequisites()) {
plugin = (Plugin) temp;
if (!tempLoaded) {
try {
plugin.onLoad();
} catch (Exception e) {
lastError = "Error in onLoad for "+getName()+":"+e.getMessage();
Logger.userError(ErrorLevel.MEDIUM, "Error in onLoad for "+getName()+":"+e.getMessage(), e);
unloadPlugin();
}
}
} else {
if (!tempLoaded) {
lastError = "Prerequisites for plugin not met. ('"+filename+":"+getMainClass()+"')";
Logger.userError(ErrorLevel.LOW, "Prerequisites for plugin not met. ('"+filename+":"+getMainClass()+"')");
}
}
}
}
} catch (ClassNotFoundException cnfe) {
lastError = "Class not found ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+cnfe.getMessage();
Logger.userError(ErrorLevel.LOW, "Class not found ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+cnfe.getMessage(), cnfe);
} catch (NoSuchMethodException nsme) {
// Don't moan about missing constructors for any class thats not the main Class
lastError = "Constructor missing ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+nsme.getMessage();
if (classname.equals(getMainClass())) {
Logger.userError(ErrorLevel.LOW, "Constructor missing ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+nsme.getMessage(), nsme);
}
} catch (IllegalAccessException iae) {
lastError = "Unable to access constructor ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+iae.getMessage();
Logger.userError(ErrorLevel.LOW, "Unable to access constructor ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+iae.getMessage(), iae);
} catch (InvocationTargetException ite) {
lastError = "Unable to invoke target ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+ite.getMessage();
Logger.userError(ErrorLevel.LOW, "Unable to invoke target ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+ite.getMessage(), ite);
} catch (InstantiationException ie) {
lastError = "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+ie.getMessage();
Logger.userError(ErrorLevel.LOW, "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+ie.getMessage(), ie);
} catch (NoClassDefFoundError ncdf) {
lastError = "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - Unable to find class: " + ncdf.getMessage();
Logger.userError(ErrorLevel.LOW, "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - Unable to find class: " + ncdf.getMessage(), ncdf);
} catch (VerifyError ve) {
lastError = "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - Incompatible: "+ve.getMessage();
Logger.userError(ErrorLevel.LOW, "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - Incompatible: "+ve.getMessage(), ve);
}
}
/**
* Unload the plugin if possible.
*/
public void unloadPlugin() {
if (!isPersistant() && (isLoaded() || isTempLoaded())) {
if (!isTempLoaded()) {
try {
plugin.onUnload();
} catch (Exception e) {
lastError = "Error in onUnload for "+getName()+":"+e.getMessage();
Logger.userError(ErrorLevel.MEDIUM, "Error in onUnload for "+getName()+":"+e.getMessage(), e);
}
ActionManager.processEvent(CoreActionType.PLUGIN_UNLOADED, null, this);
}
tempLoaded = false;
plugin = null;
classloader = null;
}
}
/**
* Get the last Error
*
* @return last Error
*/
public String getLastError() { return lastError; }
/**
* Get the list of Classes
*
* @return Classes this plugin has
*/
public List<String> getClassList() {
return myClasses;
}
/**
* Get the main Class
*
* @return Main Class to begin loading.
*/
public String getMainClass() { return metaData.getProperty("mainclass",""); }
/**
* Get the Plugin for this plugin.
*
* @return Plugin
*/
public Plugin getPlugin() { return plugin; }
/**
* Get the PluginClassLoader for this plugin.
*
* @return PluginClassLoader
*/
protected PluginClassLoader getPluginClassLoader() { return classloader; }
/**
* Get the plugin friendly version
*
* @return Plugin friendly Version
*/
public String getFriendlyVersion() { return metaData.getProperty("friendlyversion",""); }
/**
* Get the plugin version
*
* @return Plugin Version
*/
public int getVersion() {
try {
return Integer.parseInt(metaData.getProperty("version","0"));
} catch (NumberFormatException nfe) {
return -1;
}
}
/**
* Get the id for this plugin on the addons site.
* If a plugin has been submitted to addons.dmdirc.com, and plugin.info
* contains a property addonid then this will return it.
* This is used along with the version property to allow the auto-updater to
* update the addon if the author submits a new version to the addons site.
*
* @return Addon Site ID number
* -1 If not present
* -2 If non-integer
*/
public int getAddonID() {
try {
return Integer.parseInt(metaData.getProperty("addonid","-1"));
} catch (NumberFormatException nfe) {
return -2;
}
}
/**
* Is this a persistant plugin?
*
* @return true if persistant, else false
*/
public boolean isPersistant() {
final String persistance = metaData.getProperty("persistant","no");
return persistance.equalsIgnoreCase("true") || persistance.equalsIgnoreCase("yes");
}
/**
* Does this plugin contain any persistant classes?
*
* @return true if this plugin contains any persistant classes, else false
*/
public boolean hasPersistant() {
final String persistance = metaData.getProperty("persistant","no");
if (persistance.equalsIgnoreCase("true")) {
return true;
} else {
for (Object keyObject : metaData.keySet()) {
if (keyObject.toString().toLowerCase().startsWith("persistant-")) {
return true;
}
}
}
return false;
}
/**
* Get a list of all persistant classes in this plugin
*
* @return List of all persistant classes in this plugin
*/
public List<String> getPersistantClasses() {
final List<String> result = new ArrayList<String>();
final String persistance = metaData.getProperty("persistant","no");
if (persistance.equalsIgnoreCase("true")) {
try {
ResourceManager res = getResourceManager();
for (final String filename : res.getResourcesStartingWith("")) {
if (filename.matches("^.*\\.class$")) {
result.add(filename.replaceAll("\\.class$", "").replace('/', '.'));
}
}
} catch (IOException e) {
// Jar no longer exists?
}
} else {
for (Object keyObject : metaData.keySet()) {
if (keyObject.toString().toLowerCase().startsWith("persistant-")) {
result.add(keyObject.toString().substring(11));
}
}
}
return result;
}
/**
* Is this a persistant class?
*
* @param classname class to check persistance of
* @return true if file (or whole plugin) is persistant, else false
*/
public boolean isPersistant(final String classname) {
if (isPersistant()) {
return true;
} else {
final String persistance = metaData.getProperty("persistant-"+classname,"no");
return persistance.equalsIgnoreCase("true") || persistance.equalsIgnoreCase("yes");
}
}
/**
* Get the plugin Filename.
*
* @return Filename of plugin
*/
public String getFilename() { return filename; }
/**
* Get the full plugin Filename (inc dirname)
*
* @return Filename of plugin
*/
public String getFullFilename() { return url.getPath(); }
/**
* Get the plugin Author.
*
* @return Author of plugin
*/
public String getAuthor() { return getMetaInfo("author",""); }
/**
* Get the plugin Description.
*
* @return Description of plugin
*/
public String getDescription() { return getMetaInfo("description",""); }
/**
* Get the minimum dmdirc version required to run the plugin.
*
* @return minimum dmdirc version required to run the plugin.
*/
public String getMinVersion() { return getMetaInfo("minversion",""); }
/**
* Get the (optional) maximum dmdirc version on which this plugin can run
*
* @return optional maximum dmdirc version on which this plugin can run
*/
public String getMaxVersion() { return getMetaInfo("maxversion",""); }
/**
* Get the name of the plugin. (Used to identify the plugin)
*
* @return Name of plugin
*/
public String getName() { return getMetaInfo("name",""); }
/**
* Get the nice name of the plugin. (Displayed to users)
*
* @return Nice Name of plugin
*/
public String getNiceName() { return getMetaInfo("nicename",getName()); }
/**
* String Representation of this plugin
*
* @return String Representation of this plugin
*/
@Override
public String toString() { return getNiceName()+" - "+filename; }
/**
* Does this plugin want all its classes loaded?
*
* @return true/false if loadall=true || loadall=yes
*/
public boolean loadAll() {
final String loadAll = metaData.getProperty("loadall","no");
return loadAll.equalsIgnoreCase("true") || loadAll.equalsIgnoreCase("yes");
}
/**
* Get misc meta-information.
*
* @param metainfo The metainfo to return
* @return Misc Meta Info (or "" if not found);
*/
public String getMetaInfo(final String metainfo) { return getMetaInfo(metainfo,""); }
/**
* Get misc meta-information.
*
* @param metainfo The metainfo to return
* @param fallback Fallback value if requested value is not found
* @return Misc Meta Info (or fallback if not found);
*/
public String getMetaInfo(final String metainfo, final String fallback) { return metaData.getProperty(metainfo,fallback); }
/**
* Get misc meta-information.
*
* @param metainfo The metainfos to look for in order. If the first item in
* the array is not found, the next will be looked for, and
* so on until either one is found, or none are found.
* @return Misc Meta Info (or "" if none are found);
*/
public String getMetaInfo(final String[] metainfo) { return getMetaInfo(metainfo,""); }
/**
* Get misc meta-information.
*
* @param metainfo The metainfos to look for in order. If the first item in
* the array is not found, the next will be looked for, and
* so on until either one is found, or none are found.
* @param fallback Fallback value if requested values are not found
* @return Misc Meta Info (or "" if none are found);
*/
public String getMetaInfo(final String[] metainfo, final String fallback) {
for (String meta : metainfo) {
String result = metaData.getProperty(meta);
if (result != null) { return result; }
}
return fallback;
}
/**
* Compares this object with the specified object for order.
* Returns a negative integer, zero, or a positive integer as per String.compareTo();
*
* @param o Object to compare to
* @return a negative integer, zero, or a positive integer.
*/
@Override
public int compareTo(final PluginInfo o) {
return toString().compareTo(o.toString());
}
}
| public boolean checkRequirements() {
if (metaData == null) {
// No meta-data, so no requirements.
return true;
}
final String uiPackage;
if (Main.getUI().getClass().getPackage() != null) {
uiPackage = Main.getUI().getClass().getPackage().getName();
} else {
final String uiController = Main.getUI().getClass().getName();
if (uiController.lastIndexOf('.') >= 0) {
uiPackage = uiController.substring(0,uiController.lastIndexOf('.'));
} else {
uiPackage = uiController;
}
}
if (!checkMinimumVersion(getMinVersion(), Main.SVN_REVISION) ||
!checkMaximumVersion(getMaxVersion(), Main.SVN_REVISION) ||
!checkOS(getMetaInfo(new String[]{"required-os", "require-os"}), System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch")) ||
!checkFiles(getMetaInfo(new String[]{"required-files", "require-files", "required-file", "require-file"})) ||
!checkUI(getMetaInfo(new String[]{"required-ui", "require-ui"}), uiPackage) ||
!checkPlugins(getMetaInfo(new String[]{"required-plugins", "require-plugins", "required-plugin", "require-plugin"}))
) {
return false;
}
// All requirements passed, woo \o
return true;
}
/**
* Is this plugin loaded?
*/
public boolean isLoaded() {
return (plugin != null) && !tempLoaded;
}
/**
* Is this plugin temporarily loaded?
*/
public boolean isTempLoaded() {
return (plugin != null) && tempLoaded;
}
/**
* Load entire plugin.
* This loads all files in the jar immediately.
*
* @throws PluginException if there is an error with the resourcemanager
*/
private void loadEntirePlugin() throws PluginException {
// Load the main "Plugin" from the jar
loadPlugin();
// Now load all the rest.
for (String classname : myClasses) {
loadClass(classname);
}
}
/**
* Try to Load the plugin files temporarily.
*/
public void loadPluginTemp() {
tempLoaded = true;
loadPlugin();
}
/**
* Load any required plugins
*/
public void loadRequired() {
final String required = getMetaInfo(new String[]{"required-plugins", "require-plugins", "required-plugin", "require-plugin"});
for (String plugin : required.split(",")) {
final String[] data = plugin.split(":");
if (!data[0].trim().isEmpty()) {
final PluginInfo pi = PluginManager.getPluginManager().getPluginInfoByName(data[0], true);
if (pi == null) {
return;
}
if (tempLoaded) {
pi.loadPluginTemp();
} else {
pi.loadPlugin();
}
}
}
}
/**
* Load the plugin files.
*/
public void loadPlugin() {
if (isTempLoaded()) {
tempLoaded = false;
loadRequired();
plugin.onLoad();
} else {
if (isLoaded() || metaData == null) {
lastError = "Not Loading: ("+isLoaded()+"||"+(metaData == null)+")";
return;
}
loadRequired();
loadClass(getMainClass());
if (isLoaded()) {
ActionManager.processEvent(CoreActionType.PLUGIN_LOADED, null, this);
}
}
}
/**
* Load the given classname.
*
* @param classname Class to load
*/
private void loadClass(final String classname) {
try {
if (classloader == null) {
classloader = new PluginClassLoader(this);
}
// Don't reload a class if its already loaded.
if (classloader.isClassLoaded(classname, true)) {
lastError = "Classloader says we are already loaded.";
return;
}
final Class<?> c = classloader.loadClass(classname);
final Constructor<?> constructor = c.getConstructor(new Class[] {});
// Only try and construct the main class, anything else should be constructed
// by the plugin itself.
if (classname.equals(getMainClass())) {
final Object temp = constructor.newInstance(new Object[] {});
if (temp instanceof Plugin) {
if (((Plugin) temp).checkPrerequisites()) {
plugin = (Plugin) temp;
if (!tempLoaded) {
try {
plugin.onLoad();
} catch (Exception e) {
lastError = "Error in onLoad for "+getName()+":"+e.getMessage();
Logger.userError(ErrorLevel.MEDIUM, "Error in onLoad for "+getName()+":"+e.getMessage(), e);
unloadPlugin();
}
}
} else {
if (!tempLoaded) {
lastError = "Prerequisites for plugin not met. ('"+filename+":"+getMainClass()+"')";
Logger.userError(ErrorLevel.LOW, "Prerequisites for plugin not met. ('"+filename+":"+getMainClass()+"')");
}
}
}
}
} catch (ClassNotFoundException cnfe) {
lastError = "Class not found ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+cnfe.getMessage();
Logger.userError(ErrorLevel.LOW, "Class not found ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+cnfe.getMessage(), cnfe);
} catch (NoSuchMethodException nsme) {
// Don't moan about missing constructors for any class thats not the main Class
lastError = "Constructor missing ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+nsme.getMessage();
if (classname.equals(getMainClass())) {
Logger.userError(ErrorLevel.LOW, "Constructor missing ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+nsme.getMessage(), nsme);
}
} catch (IllegalAccessException iae) {
lastError = "Unable to access constructor ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+iae.getMessage();
Logger.userError(ErrorLevel.LOW, "Unable to access constructor ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+iae.getMessage(), iae);
} catch (InvocationTargetException ite) {
lastError = "Unable to invoke target ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+ite.getMessage();
Logger.userError(ErrorLevel.LOW, "Unable to invoke target ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+ite.getMessage(), ite);
} catch (InstantiationException ie) {
lastError = "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+ie.getMessage();
Logger.userError(ErrorLevel.LOW, "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - "+ie.getMessage(), ie);
} catch (NoClassDefFoundError ncdf) {
lastError = "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - Unable to find class: " + ncdf.getMessage();
Logger.userError(ErrorLevel.LOW, "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - Unable to find class: " + ncdf.getMessage(), ncdf);
} catch (VerifyError ve) {
lastError = "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - Incompatible: "+ve.getMessage();
Logger.userError(ErrorLevel.LOW, "Unable to instantiate plugin ('"+filename+":"+classname+":"+classname.equals(getMainClass())+"') - Incompatible: "+ve.getMessage(), ve);
}
}
/**
* Unload the plugin if possible.
*/
public void unloadPlugin() {
if (!isPersistant() && (isLoaded() || isTempLoaded())) {
if (!isTempLoaded()) {
try {
plugin.onUnload();
} catch (Exception e) {
lastError = "Error in onUnload for "+getName()+":"+e.getMessage();
Logger.userError(ErrorLevel.MEDIUM, "Error in onUnload for "+getName()+":"+e.getMessage(), e);
}
ActionManager.processEvent(CoreActionType.PLUGIN_UNLOADED, null, this);
}
tempLoaded = false;
plugin = null;
classloader = null;
}
}
/**
* Get the last Error
*
* @return last Error
*/
public String getLastError() { return lastError; }
/**
* Get the list of Classes
*
* @return Classes this plugin has
*/
public List<String> getClassList() {
return myClasses;
}
/**
* Get the main Class
*
* @return Main Class to begin loading.
*/
public String getMainClass() { return metaData.getProperty("mainclass",""); }
/**
* Get the Plugin for this plugin.
*
* @return Plugin
*/
public Plugin getPlugin() { return plugin; }
/**
* Get the PluginClassLoader for this plugin.
*
* @return PluginClassLoader
*/
protected PluginClassLoader getPluginClassLoader() { return classloader; }
/**
* Get the plugin friendly version
*
* @return Plugin friendly Version
*/
public String getFriendlyVersion() { return metaData.getProperty("friendlyversion", getVersion()); }
/**
* Get the plugin version
*
* @return Plugin Version
*/
public int getVersion() {
try {
return Integer.parseInt(metaData.getProperty("version","0"));
} catch (NumberFormatException nfe) {
return -1;
}
}
/**
* Get the id for this plugin on the addons site.
* If a plugin has been submitted to addons.dmdirc.com, and plugin.info
* contains a property addonid then this will return it.
* This is used along with the version property to allow the auto-updater to
* update the addon if the author submits a new version to the addons site.
*
* @return Addon Site ID number
* -1 If not present
* -2 If non-integer
*/
public int getAddonID() {
try {
return Integer.parseInt(metaData.getProperty("addonid","-1"));
} catch (NumberFormatException nfe) {
return -2;
}
}
/**
* Is this a persistant plugin?
*
* @return true if persistant, else false
*/
public boolean isPersistant() {
final String persistance = metaData.getProperty("persistant","no");
return persistance.equalsIgnoreCase("true") || persistance.equalsIgnoreCase("yes");
}
/**
* Does this plugin contain any persistant classes?
*
* @return true if this plugin contains any persistant classes, else false
*/
public boolean hasPersistant() {
final String persistance = metaData.getProperty("persistant","no");
if (persistance.equalsIgnoreCase("true")) {
return true;
} else {
for (Object keyObject : metaData.keySet()) {
if (keyObject.toString().toLowerCase().startsWith("persistant-")) {
return true;
}
}
}
return false;
}
/**
* Get a list of all persistant classes in this plugin
*
* @return List of all persistant classes in this plugin
*/
public List<String> getPersistantClasses() {
final List<String> result = new ArrayList<String>();
final String persistance = metaData.getProperty("persistant","no");
if (persistance.equalsIgnoreCase("true")) {
try {
ResourceManager res = getResourceManager();
for (final String filename : res.getResourcesStartingWith("")) {
if (filename.matches("^.*\\.class$")) {
result.add(filename.replaceAll("\\.class$", "").replace('/', '.'));
}
}
} catch (IOException e) {
// Jar no longer exists?
}
} else {
for (Object keyObject : metaData.keySet()) {
if (keyObject.toString().toLowerCase().startsWith("persistant-")) {
result.add(keyObject.toString().substring(11));
}
}
}
return result;
}
/**
* Is this a persistant class?
*
* @param classname class to check persistance of
* @return true if file (or whole plugin) is persistant, else false
*/
public boolean isPersistant(final String classname) {
if (isPersistant()) {
return true;
} else {
final String persistance = metaData.getProperty("persistant-"+classname,"no");
return persistance.equalsIgnoreCase("true") || persistance.equalsIgnoreCase("yes");
}
}
/**
* Get the plugin Filename.
*
* @return Filename of plugin
*/
public String getFilename() { return filename; }
/**
* Get the full plugin Filename (inc dirname)
*
* @return Filename of plugin
*/
public String getFullFilename() { return url.getPath(); }
/**
* Get the plugin Author.
*
* @return Author of plugin
*/
public String getAuthor() { return getMetaInfo("author",""); }
/**
* Get the plugin Description.
*
* @return Description of plugin
*/
public String getDescription() { return getMetaInfo("description",""); }
/**
* Get the minimum dmdirc version required to run the plugin.
*
* @return minimum dmdirc version required to run the plugin.
*/
public String getMinVersion() { return getMetaInfo("minversion",""); }
/**
* Get the (optional) maximum dmdirc version on which this plugin can run
*
* @return optional maximum dmdirc version on which this plugin can run
*/
public String getMaxVersion() { return getMetaInfo("maxversion",""); }
/**
* Get the name of the plugin. (Used to identify the plugin)
*
* @return Name of plugin
*/
public String getName() { return getMetaInfo("name",""); }
/**
* Get the nice name of the plugin. (Displayed to users)
*
* @return Nice Name of plugin
*/
public String getNiceName() { return getMetaInfo("nicename",getName()); }
/**
* String Representation of this plugin
*
* @return String Representation of this plugin
*/
@Override
public String toString() { return getNiceName()+" - "+filename; }
/**
* Does this plugin want all its classes loaded?
*
* @return true/false if loadall=true || loadall=yes
*/
public boolean loadAll() {
final String loadAll = metaData.getProperty("loadall","no");
return loadAll.equalsIgnoreCase("true") || loadAll.equalsIgnoreCase("yes");
}
/**
* Get misc meta-information.
*
* @param metainfo The metainfo to return
* @return Misc Meta Info (or "" if not found);
*/
public String getMetaInfo(final String metainfo) { return getMetaInfo(metainfo,""); }
/**
* Get misc meta-information.
*
* @param metainfo The metainfo to return
* @param fallback Fallback value if requested value is not found
* @return Misc Meta Info (or fallback if not found);
*/
public String getMetaInfo(final String metainfo, final String fallback) { return metaData.getProperty(metainfo,fallback); }
/**
* Get misc meta-information.
*
* @param metainfo The metainfos to look for in order. If the first item in
* the array is not found, the next will be looked for, and
* so on until either one is found, or none are found.
* @return Misc Meta Info (or "" if none are found);
*/
public String getMetaInfo(final String[] metainfo) { return getMetaInfo(metainfo,""); }
/**
* Get misc meta-information.
*
* @param metainfo The metainfos to look for in order. If the first item in
* the array is not found, the next will be looked for, and
* so on until either one is found, or none are found.
* @param fallback Fallback value if requested values are not found
* @return Misc Meta Info (or "" if none are found);
*/
public String getMetaInfo(final String[] metainfo, final String fallback) {
for (String meta : metainfo) {
String result = metaData.getProperty(meta);
if (result != null) { return result; }
}
return fallback;
}
/**
* Compares this object with the specified object for order.
* Returns a negative integer, zero, or a positive integer as per String.compareTo();
*
* @param o Object to compare to
* @return a negative integer, zero, or a positive integer.
*/
@Override
public int compareTo(final PluginInfo o) {
return toString().compareTo(o.toString());
}
}
|
diff --git a/src/com/monitoring/munin_node/plugins/fw_packets.java b/src/com/monitoring/munin_node/plugins/fw_packets.java
index bd63986..d55b6bd 100644
--- a/src/com/monitoring/munin_node/plugins/fw_packets.java
+++ b/src/com/monitoring/munin_node/plugins/fw_packets.java
@@ -1,95 +1,96 @@
package com.monitoring.munin_node.plugins;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import com.monitoring.munin_node.plugin_api.Plugin_API;
public class fw_packets implements Plugin_API {
@Override
public String getName() {
return "Firewall Packets";
}
@Override
public String getCat() {
return "Network";
}
/*@Override
public String getConfig() {
return output.toString();
}
@Override
public String getUpdate() {
}*/
@Override
public Boolean needsContext() {
// TODO Auto-generated method stub
return false;
}
@Override
public Void setContext(Context context) {
// TODO Auto-generated method stub
return null;
}
@Override
public Void run(Handler handler) {
StringBuffer output = new StringBuffer();
output.append("graph_title Firewall Throughput\n");
output.append("graph_args --base 1000 -l 0\n");
output.append("graph_vlabel Packets/${graph_period}\n");
output.append("graph_category network\n");
output.append("received.label Received\n");
output.append("received.draw AREA\n");
output.append("received.type DERIVE\n");
output.append("received.min 0\n");
output.append("forwarded.label Forwarded\n");
output.append("forwarded.draw LINE2\n");
output.append("forwarded.type DERIVE\n");
output.append("forwarded.min 0");
BufferedReader in = null;
String received = "";
String forwarded = "";
try {
in = new BufferedReader(new FileReader("/proc/net/snmp"));
+ in.readLine();
String ipline = in.readLine();
final Pattern ip = Pattern.compile("^Ip:[\\s]+[\\d]+[\\s]+[\\d]+[\\s]+([\\d]+)[\\s]+[\\d]+[\\s]+[\\d]+[\\s]+([\\d])+.*");
Matcher ip_matcher = ip.matcher(ipline);
if(ip_matcher.find()){
received = ip_matcher.group(1);
forwarded = ip_matcher.group(2);
}
} catch (FileNotFoundException e) {
received = "U";
forwarded = "U";
} catch (IOException e) {
received = "U";
forwarded = "U";
}
Bundle bundle = new Bundle();
bundle.putString("name", this.getName());
bundle.putString("config", output.toString());
bundle.putString("update", "received.value "+received+"\nforwarded.value "+forwarded);
Message msg = Message.obtain(handler, 42, bundle);
handler.sendMessage(msg);
return null;
}
}
| true | true | public Void run(Handler handler) {
StringBuffer output = new StringBuffer();
output.append("graph_title Firewall Throughput\n");
output.append("graph_args --base 1000 -l 0\n");
output.append("graph_vlabel Packets/${graph_period}\n");
output.append("graph_category network\n");
output.append("received.label Received\n");
output.append("received.draw AREA\n");
output.append("received.type DERIVE\n");
output.append("received.min 0\n");
output.append("forwarded.label Forwarded\n");
output.append("forwarded.draw LINE2\n");
output.append("forwarded.type DERIVE\n");
output.append("forwarded.min 0");
BufferedReader in = null;
String received = "";
String forwarded = "";
try {
in = new BufferedReader(new FileReader("/proc/net/snmp"));
String ipline = in.readLine();
final Pattern ip = Pattern.compile("^Ip:[\\s]+[\\d]+[\\s]+[\\d]+[\\s]+([\\d]+)[\\s]+[\\d]+[\\s]+[\\d]+[\\s]+([\\d])+.*");
Matcher ip_matcher = ip.matcher(ipline);
if(ip_matcher.find()){
received = ip_matcher.group(1);
forwarded = ip_matcher.group(2);
}
} catch (FileNotFoundException e) {
received = "U";
forwarded = "U";
} catch (IOException e) {
received = "U";
forwarded = "U";
}
Bundle bundle = new Bundle();
bundle.putString("name", this.getName());
bundle.putString("config", output.toString());
bundle.putString("update", "received.value "+received+"\nforwarded.value "+forwarded);
Message msg = Message.obtain(handler, 42, bundle);
handler.sendMessage(msg);
return null;
}
| public Void run(Handler handler) {
StringBuffer output = new StringBuffer();
output.append("graph_title Firewall Throughput\n");
output.append("graph_args --base 1000 -l 0\n");
output.append("graph_vlabel Packets/${graph_period}\n");
output.append("graph_category network\n");
output.append("received.label Received\n");
output.append("received.draw AREA\n");
output.append("received.type DERIVE\n");
output.append("received.min 0\n");
output.append("forwarded.label Forwarded\n");
output.append("forwarded.draw LINE2\n");
output.append("forwarded.type DERIVE\n");
output.append("forwarded.min 0");
BufferedReader in = null;
String received = "";
String forwarded = "";
try {
in = new BufferedReader(new FileReader("/proc/net/snmp"));
in.readLine();
String ipline = in.readLine();
final Pattern ip = Pattern.compile("^Ip:[\\s]+[\\d]+[\\s]+[\\d]+[\\s]+([\\d]+)[\\s]+[\\d]+[\\s]+[\\d]+[\\s]+([\\d])+.*");
Matcher ip_matcher = ip.matcher(ipline);
if(ip_matcher.find()){
received = ip_matcher.group(1);
forwarded = ip_matcher.group(2);
}
} catch (FileNotFoundException e) {
received = "U";
forwarded = "U";
} catch (IOException e) {
received = "U";
forwarded = "U";
}
Bundle bundle = new Bundle();
bundle.putString("name", this.getName());
bundle.putString("config", output.toString());
bundle.putString("update", "received.value "+received+"\nforwarded.value "+forwarded);
Message msg = Message.obtain(handler, 42, bundle);
handler.sendMessage(msg);
return null;
}
|
diff --git a/dspace/src/org/dspace/app/webui/servlet/admin/EditCommunitiesServlet.java b/dspace/src/org/dspace/app/webui/servlet/admin/EditCommunitiesServlet.java
index 0cd5e0082..65cc70ae7 100644
--- a/dspace/src/org/dspace/app/webui/servlet/admin/EditCommunitiesServlet.java
+++ b/dspace/src/org/dspace/app/webui/servlet/admin/EditCommunitiesServlet.java
@@ -1,617 +1,621 @@
/*
* EditCommunities.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002, 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.app.webui.servlet.admin;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.webui.servlet.DSpaceServlet;
import org.dspace.app.webui.util.FileUploadRequest;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Bitstream;
import org.dspace.content.BitstreamFormat;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.FormatIdentifier;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.eperson.Group;
/**
* Servlet for editing communities and collections, including deletion,
* creation, and metadata editing
*
* @author Robert Tansley
* @version $Revision$
*/
public class EditCommunitiesServlet extends DSpaceServlet
{
/** User wants to edit a community */
public static final int START_EDIT_COMMUNITY = 1;
/** User wants to delete a community */
public static final int START_DELETE_COMMUNITY = 2;
/** User wants to create a community */
public static final int START_CREATE_COMMUNITY = 3;
/** User wants to edit a collection */
public static final int START_EDIT_COLLECTION = 4;
/** User wants to delete a collection */
public static final int START_DELETE_COLLECTION = 5;
/** User wants to create a collection */
public static final int START_CREATE_COLLECTION = 6;
/** User commited community edit or creation */
public static final int CONFIRM_EDIT_COMMUNITY = 7;
/** User confirmed community deletion*/
public static final int CONFIRM_DELETE_COMMUNITY = 8;
/** User commited collection edit or creation */
public static final int CONFIRM_EDIT_COLLECTION = 9;
/** User wants to delete a collection */
public static final int CONFIRM_DELETE_COLLECTION = 10;
/** Logger */
private static Logger log = Logger.getLogger(EditCommunitiesServlet.class);
protected void doDSGet(Context context,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException, SQLException, AuthorizeException
{
// GET just displays the list of communities and collections
showControls(context, request, response);
}
protected void doDSPost(Context context,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException, SQLException, AuthorizeException
{
// First, see if we have a multipart request (uploading a logo)
String contentType = request.getContentType();
if (contentType != null &&
contentType.indexOf("multipart/form-data") != -1)
{
// This is a multipart request, so it's a file upload
processUploadLogo(context, request, response);
return;
}
/*
* Respond to submitted forms. Each form includes an "action" parameter
* indicating what needs to be done (from the constants above.)
*/
int action = UIUtil.getIntParameter(request, "action");
/*
* Most of the forms supply one or both of these values. Since we just
* get null if we try and find something with ID -1, we'll just try
* and find both here to save hassle later on
*/
Community community = Community.find(context,
UIUtil.getIntParameter(request, "community_id"));
Collection collection = Collection.find(context,
UIUtil.getIntParameter(request, "collection_id"));
// Just about every JSP will need the values we received
request.setAttribute("community", community);
request.setAttribute("collection", collection);
/*
* First we check for a "cancel" button - if it's been pressed, we
* simply return to the main control page
*/
if (request.getParameter("submit_cancel") != null)
{
showControls(context, request, response);
return;
}
// Now proceed according to "action" parameter
switch (action)
{
case START_EDIT_COMMUNITY:
// Display the relevant "edit community" page
JSPManager.showJSP(request, response, "/admin/edit-community.jsp");
break;
case START_DELETE_COMMUNITY:
// Show "confirm delete" page
JSPManager.showJSP(request, response,
"/admin/confirm-delete-community.jsp");
break;
case START_CREATE_COMMUNITY:
// Display edit community page with empty fields + create button
JSPManager.showJSP(request, response, "/admin/edit-community.jsp");
break;
case START_EDIT_COLLECTION:
// Display the relevant "edit collection" page
JSPManager.showJSP(request, response, "/admin/edit-collection.jsp");
break;
case START_DELETE_COLLECTION:
// Show "confirm delete" page
JSPManager.showJSP(request, response,
"/admin/confirm-delete-collection.jsp");
break;
case START_CREATE_COLLECTION:
// Display edit collection page with empty fields + create button
JSPManager.showJSP(request, response, "/admin/edit-collection.jsp");
break;
case CONFIRM_EDIT_COMMUNITY:
// Edit or creation of a community confirmed
processConfirmEditCommunity(context, request, response, community);
break;
case CONFIRM_DELETE_COMMUNITY:
// Delete the community
community.delete();
// Show main control page
showControls(context, request, response);
// Commit changes to DB
context.complete();
break;
case CONFIRM_EDIT_COLLECTION:
// Edit or creation of a collection confirmed
processConfirmEditCollection(
context, request, response, community, collection);
break;
case CONFIRM_DELETE_COLLECTION:
// Delete the collection
community.removeCollection(collection);
// Show main control page
showControls(context, request, response);
// Commit changes to DB
context.complete();
break;
default:
// Erm... weird action value received.
log.warn(LogManager.getHeader(context,
"integrity_error",
UIUtil.getRequestLogInfo(request)));
JSPManager.showIntegrityError(request, response);
}
}
/**
* Show list of communities and collections with controls
*
* @param context Current DSpace context
* @param request Current HTTP request
* @param response Current HTTP response
*/
private void showControls(Context context,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException, SQLException, AuthorizeException
{
Community[] communities = Community.findAll(context);
// Build up a map in which the keys are community IDs and the
// values are collections - this is so the JSP doesn't have to do
// the work
Map communityIDToCollection = new HashMap();
for (int i = 0; i < communities.length; i++)
{
communityIDToCollection.put(new Integer(communities[i].getID()),
communities[i].getCollections());
}
log.info(LogManager.getHeader(context,
"view_editcommunities",
""));
// Set attributes for JSP
request.setAttribute("communities", communities);
request.setAttribute("collections.map", communityIDToCollection);
JSPManager.showJSP(request, response, "/admin/list-communities.jsp");
}
/**
* Create/update community metadata from a posted form
*
* @param context DSpace context
* @param request the HTTP request containing posted info
* @param response the HTTP response
* @param community the community to update (or null for creation)
*/
private void processConfirmEditCommunity(Context context,
HttpServletRequest request,
HttpServletResponse response,
Community community)
throws ServletException, IOException, SQLException, AuthorizeException
{
if (request.getParameter("create").equals("true"))
{
// We need to create a new community
community = Community.create(context);
// Set attribute
request.setAttribute("community", community);
}
community.setMetadata("name", request.getParameter("name"));
community.setMetadata("short_description",
request.getParameter("short_description"));
String intro = request.getParameter("introductory_text");
if (intro.equals(""))
{
intro = null;
}
String copy = request.getParameter("copyright_text");
if (copy.equals(""))
{
copy = null;
}
String side = request.getParameter("side_bar_text");
if (side.equals(""))
{
side = null;
}
community.setMetadata("introductory_text", intro);
community.setMetadata("copyright_text", copy);
community.setMetadata("side_bar_text", side);
community.update();
// Which button was pressed?
String button = UIUtil.getSubmitButton(request, "submit");
if (button.equals("submit_set_logo"))
{
// Change the logo - delete any that might be there first
community.setLogo(null);
community.update();
// Display "upload logo" page. Necessary attributes already set by
// doDSPost()
JSPManager.showJSP(request, response, "/admin/upload-logo.jsp");
}
else if(button.equals("submit_delete_logo"))
{
// Simply delete logo
community.setLogo(null);
community.update();
// Show edit page again - attributes set in doDSPost()
JSPManager.showJSP(request, response, "/admin/edit-community.jsp");
}
else
{
// Button at bottom clicked - show main control page
showControls(context, request, response);
}
// Commit changes to DB
context.complete();
}
/**
* Create/update collection metadata from a posted form
*
* @param context DSpace context
* @param request the HTTP request containing posted info
* @param response the HTTP response
* @param community the community the collection is in
* @param collection the collection to update (or null for creation)
*/
private void processConfirmEditCollection(Context context,
HttpServletRequest request,
HttpServletResponse response,
Community community,
Collection collection)
throws ServletException, IOException, SQLException, AuthorizeException
{
if (request.getParameter("create").equals("true"))
{
// We need to create a new community
collection = community.createCollection();
request.setAttribute("collection", collection);
}
// Update the basic metadata
collection.setMetadata("name", request.getParameter("name"));
collection.setMetadata("short_description",
request.getParameter("short_description"));
String intro = request.getParameter("introductory_text");
if (intro.equals(""))
{
intro = null;
}
String copy = request.getParameter("copyright_text");
if (copy.equals(""))
{
copy = null;
}
String side = request.getParameter("side_bar_text");
if (side.equals(""))
{
side = null;
}
String license = request.getParameter("license");
if (license.equals(""))
{
license = null;
}
String provenance = request.getParameter("provenance_description");
if (provenance.equals(""))
{
provenance = null;
}
collection.setMetadata("introductory_text", intro);
collection.setMetadata("copyright_text", copy);
collection.setMetadata("side_bar_text", side);
collection.setMetadata("license", license);
collection.setMetadata("provenance_description", provenance);
// Which button was pressed?
String button = UIUtil.getSubmitButton(request, "submit");
if (button.equals("submit_set_logo"))
{
// Change the logo - delete any that might be there first
collection.setLogo(null);
// Display "upload logo" page. Necessary attributes already set by
// doDSPost()
JSPManager.showJSP(request, response, "/admin/upload-logo.jsp");
}
else if(button.equals("submit_delete_logo"))
{
// Simply delete logo
collection.setLogo(null);
// Show edit page again - attributes set in doDSPost()
JSPManager.showJSP(request, response, "/admin/edit-collection.jsp");
}
else if(button.startsWith("submit_wf_create_"))
{
int step = Integer.parseInt(button.substring(17));
// Create new group
Group newGroup = Group.create(context);
newGroup.setName("COLLECTION_" + collection.getID() + "_WFSTEP_" +
step);
newGroup.update();
collection.setWorkflowGroup(step, newGroup);
collection.update();
// Forward to group edit page
response.sendRedirect(response.encodeRedirectURL(
request.getContextPath() + "/admin/groups?group=" +
newGroup.getID()));
}
else if(button.startsWith("submit_wf_edit_"))
{
int step = Integer.parseInt(button.substring(15));
// Edit workflow group
Group g = collection.getWorkflowGroup(step);
response.sendRedirect(response.encodeRedirectURL(
request.getContextPath() + "/admin/groups?group=" +
g.getID()));
}
else if(button.startsWith("submit_wf_delete_"))
{
// Delete workflow group
int step = Integer.parseInt(button.substring(17));
Group g = collection.getWorkflowGroup(step);
collection.setWorkflowGroup(step, null);
// Have to update to avoid ref. integrity error
collection.update();
g.delete();
// Show edit page again - attributes set in doDSPost()
JSPManager.showJSP(request, response, "/admin/edit-collection.jsp");
}
else if(button.equals("submit_create_template"))
{
// Create a template item
collection.createTemplateItem();
// Forward to edit page for new template item
Item i = collection.getTemplateItem();
+ // have to update to avoid ref. integrity error
+ collection.update();
+ context.complete();
response.sendRedirect(response.encodeRedirectURL(
- request.getContextPath() + "/admin/edit_item?item_id=" +
+ request.getContextPath() + "/admin/edit-item?item_id=" +
i.getID()));
+ return;
}
else if(button.equals("submit_edit_template"))
{
// Forward to edit page for template item
Item i = collection.getTemplateItem();
response.sendRedirect(response.encodeRedirectURL(
- request.getContextPath() + "/admin/edit_item?item_id=" +
+ request.getContextPath() + "/admin/edit-item?item_id=" +
i.getID()));
}
else if(button.equals("submit_delete_template"))
{
collection.removeTemplateItem();
// Show edit page again - attributes set in doDSPost()
JSPManager.showJSP(request, response, "/admin/edit-collection.jsp");
}
else
{
// Plain old "create/update" button pressed - go back to main page
showControls(context, request, response);
}
// Commit changes to DB
- collection.update();
- context.complete();
+ collection.update();
+ context.complete();
}
/**
* Process the input from the upload logo page
*
* @param context current DSpace context
* @param request current servlet request object
* @param response current servlet response object
*/
private void processUploadLogo(Context context,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException, SQLException, AuthorizeException
{
// Wrap multipart request to get the submission info
FileUploadRequest wrapper = new FileUploadRequest(request);
Community community = Community.find(context,
UIUtil.getIntParameter(wrapper, "community_id"));
Collection collection = Collection.find(context,
UIUtil.getIntParameter(wrapper, "collection_id"));
File temp = wrapper.getFile("file");
// Read the temp file as logo
InputStream is = new BufferedInputStream(new FileInputStream(
temp));
Bitstream logoBS;
if (community != null)
{
logoBS = community.setLogo(is);
}
else
{
logoBS = collection.setLogo(is);
}
// Strip all but the last filename. It would be nice
// to know which OS the file came from.
String noPath = wrapper.getFilesystemName("file");
while (noPath.indexOf('/') > -1)
{
noPath = noPath.substring(
noPath.indexOf('/') + 1);
}
while (noPath.indexOf('\\') > -1)
{
noPath = noPath.substring(
noPath.indexOf('\\') + 1);
}
logoBS.setName(noPath);
logoBS.setSource(wrapper.getFilesystemName("file"));
// Identify the format
BitstreamFormat bf = FormatIdentifier.guessFormat(context, logoBS);
logoBS.setFormat(bf);
logoBS.update();
if (community != null)
{
community.update();
// Show community edit page
request.setAttribute("community", community);
JSPManager.showJSP(request, response, "/admin/edit-community.jsp");
}
else
{
collection.update();
// Show collection edit page
request.setAttribute("collection", collection);
JSPManager.showJSP(request, response, "/admin/edit-collection.jsp");
}
// Remove temp file
temp.delete();
// Update DB
context.complete();
}
}
| false | true | private void processConfirmEditCollection(Context context,
HttpServletRequest request,
HttpServletResponse response,
Community community,
Collection collection)
throws ServletException, IOException, SQLException, AuthorizeException
{
if (request.getParameter("create").equals("true"))
{
// We need to create a new community
collection = community.createCollection();
request.setAttribute("collection", collection);
}
// Update the basic metadata
collection.setMetadata("name", request.getParameter("name"));
collection.setMetadata("short_description",
request.getParameter("short_description"));
String intro = request.getParameter("introductory_text");
if (intro.equals(""))
{
intro = null;
}
String copy = request.getParameter("copyright_text");
if (copy.equals(""))
{
copy = null;
}
String side = request.getParameter("side_bar_text");
if (side.equals(""))
{
side = null;
}
String license = request.getParameter("license");
if (license.equals(""))
{
license = null;
}
String provenance = request.getParameter("provenance_description");
if (provenance.equals(""))
{
provenance = null;
}
collection.setMetadata("introductory_text", intro);
collection.setMetadata("copyright_text", copy);
collection.setMetadata("side_bar_text", side);
collection.setMetadata("license", license);
collection.setMetadata("provenance_description", provenance);
// Which button was pressed?
String button = UIUtil.getSubmitButton(request, "submit");
if (button.equals("submit_set_logo"))
{
// Change the logo - delete any that might be there first
collection.setLogo(null);
// Display "upload logo" page. Necessary attributes already set by
// doDSPost()
JSPManager.showJSP(request, response, "/admin/upload-logo.jsp");
}
else if(button.equals("submit_delete_logo"))
{
// Simply delete logo
collection.setLogo(null);
// Show edit page again - attributes set in doDSPost()
JSPManager.showJSP(request, response, "/admin/edit-collection.jsp");
}
else if(button.startsWith("submit_wf_create_"))
{
int step = Integer.parseInt(button.substring(17));
// Create new group
Group newGroup = Group.create(context);
newGroup.setName("COLLECTION_" + collection.getID() + "_WFSTEP_" +
step);
newGroup.update();
collection.setWorkflowGroup(step, newGroup);
collection.update();
// Forward to group edit page
response.sendRedirect(response.encodeRedirectURL(
request.getContextPath() + "/admin/groups?group=" +
newGroup.getID()));
}
else if(button.startsWith("submit_wf_edit_"))
{
int step = Integer.parseInt(button.substring(15));
// Edit workflow group
Group g = collection.getWorkflowGroup(step);
response.sendRedirect(response.encodeRedirectURL(
request.getContextPath() + "/admin/groups?group=" +
g.getID()));
}
else if(button.startsWith("submit_wf_delete_"))
{
// Delete workflow group
int step = Integer.parseInt(button.substring(17));
Group g = collection.getWorkflowGroup(step);
collection.setWorkflowGroup(step, null);
// Have to update to avoid ref. integrity error
collection.update();
g.delete();
// Show edit page again - attributes set in doDSPost()
JSPManager.showJSP(request, response, "/admin/edit-collection.jsp");
}
else if(button.equals("submit_create_template"))
{
// Create a template item
collection.createTemplateItem();
// Forward to edit page for new template item
Item i = collection.getTemplateItem();
response.sendRedirect(response.encodeRedirectURL(
request.getContextPath() + "/admin/edit_item?item_id=" +
i.getID()));
}
else if(button.equals("submit_edit_template"))
{
// Forward to edit page for template item
Item i = collection.getTemplateItem();
response.sendRedirect(response.encodeRedirectURL(
request.getContextPath() + "/admin/edit_item?item_id=" +
i.getID()));
}
else if(button.equals("submit_delete_template"))
{
collection.removeTemplateItem();
// Show edit page again - attributes set in doDSPost()
JSPManager.showJSP(request, response, "/admin/edit-collection.jsp");
}
else
{
// Plain old "create/update" button pressed - go back to main page
showControls(context, request, response);
}
// Commit changes to DB
collection.update();
context.complete();
}
| private void processConfirmEditCollection(Context context,
HttpServletRequest request,
HttpServletResponse response,
Community community,
Collection collection)
throws ServletException, IOException, SQLException, AuthorizeException
{
if (request.getParameter("create").equals("true"))
{
// We need to create a new community
collection = community.createCollection();
request.setAttribute("collection", collection);
}
// Update the basic metadata
collection.setMetadata("name", request.getParameter("name"));
collection.setMetadata("short_description",
request.getParameter("short_description"));
String intro = request.getParameter("introductory_text");
if (intro.equals(""))
{
intro = null;
}
String copy = request.getParameter("copyright_text");
if (copy.equals(""))
{
copy = null;
}
String side = request.getParameter("side_bar_text");
if (side.equals(""))
{
side = null;
}
String license = request.getParameter("license");
if (license.equals(""))
{
license = null;
}
String provenance = request.getParameter("provenance_description");
if (provenance.equals(""))
{
provenance = null;
}
collection.setMetadata("introductory_text", intro);
collection.setMetadata("copyright_text", copy);
collection.setMetadata("side_bar_text", side);
collection.setMetadata("license", license);
collection.setMetadata("provenance_description", provenance);
// Which button was pressed?
String button = UIUtil.getSubmitButton(request, "submit");
if (button.equals("submit_set_logo"))
{
// Change the logo - delete any that might be there first
collection.setLogo(null);
// Display "upload logo" page. Necessary attributes already set by
// doDSPost()
JSPManager.showJSP(request, response, "/admin/upload-logo.jsp");
}
else if(button.equals("submit_delete_logo"))
{
// Simply delete logo
collection.setLogo(null);
// Show edit page again - attributes set in doDSPost()
JSPManager.showJSP(request, response, "/admin/edit-collection.jsp");
}
else if(button.startsWith("submit_wf_create_"))
{
int step = Integer.parseInt(button.substring(17));
// Create new group
Group newGroup = Group.create(context);
newGroup.setName("COLLECTION_" + collection.getID() + "_WFSTEP_" +
step);
newGroup.update();
collection.setWorkflowGroup(step, newGroup);
collection.update();
// Forward to group edit page
response.sendRedirect(response.encodeRedirectURL(
request.getContextPath() + "/admin/groups?group=" +
newGroup.getID()));
}
else if(button.startsWith("submit_wf_edit_"))
{
int step = Integer.parseInt(button.substring(15));
// Edit workflow group
Group g = collection.getWorkflowGroup(step);
response.sendRedirect(response.encodeRedirectURL(
request.getContextPath() + "/admin/groups?group=" +
g.getID()));
}
else if(button.startsWith("submit_wf_delete_"))
{
// Delete workflow group
int step = Integer.parseInt(button.substring(17));
Group g = collection.getWorkflowGroup(step);
collection.setWorkflowGroup(step, null);
// Have to update to avoid ref. integrity error
collection.update();
g.delete();
// Show edit page again - attributes set in doDSPost()
JSPManager.showJSP(request, response, "/admin/edit-collection.jsp");
}
else if(button.equals("submit_create_template"))
{
// Create a template item
collection.createTemplateItem();
// Forward to edit page for new template item
Item i = collection.getTemplateItem();
// have to update to avoid ref. integrity error
collection.update();
context.complete();
response.sendRedirect(response.encodeRedirectURL(
request.getContextPath() + "/admin/edit-item?item_id=" +
i.getID()));
return;
}
else if(button.equals("submit_edit_template"))
{
// Forward to edit page for template item
Item i = collection.getTemplateItem();
response.sendRedirect(response.encodeRedirectURL(
request.getContextPath() + "/admin/edit-item?item_id=" +
i.getID()));
}
else if(button.equals("submit_delete_template"))
{
collection.removeTemplateItem();
// Show edit page again - attributes set in doDSPost()
JSPManager.showJSP(request, response, "/admin/edit-collection.jsp");
}
else
{
// Plain old "create/update" button pressed - go back to main page
showControls(context, request, response);
}
// Commit changes to DB
collection.update();
context.complete();
}
|
diff --git a/Asgn2/src/solution/ContainerLabel.java b/Asgn2/src/solution/ContainerLabel.java
index d562992..c50932b 100644
--- a/Asgn2/src/solution/ContainerLabel.java
+++ b/Asgn2/src/solution/ContainerLabel.java
@@ -1,69 +1,70 @@
package solution;
/**
* @author Jacob Evans, Bodaniel Jeanes
*/
public class ContainerLabel {
int identifier, kind, kindLength, identifierLength;
public ContainerLabel(Integer a_kind, Integer a_kindLength,
Integer a_identifier, Integer a_identifierLength)
throws LabelException, IllegalArgumentException {
// No null parameters supported
if ((a_kind == null) || (a_identifier == null)
|| (a_kindLength == null) || (a_identifierLength == null)) {
throw new IllegalArgumentException(
"Cannot give null values for any parameters");
}
// No negative numbers supported
- if ((a_kind < 0) || (a_identifier < 0) || (a_kindLength < 0)
- || (a_identifierLength < 0)) {
- throw new LabelException("Cannot give negative values to cargo");
+ if ((a_kind < 0) || (a_identifier < 0) || (a_kindLength <= 0)
+ || (a_identifierLength <= 0)) {
+ throw new LabelException(
+ "Cannot give negative values for kind/identifier or zero lengths");
}
// Check that the label kind and identifier are valid range
if ((a_kindLength > 3) || (a_identifierLength > 5)) {
throw new LabelException("Cannot assign that high a value");
}
// TODO test to see if the length is larger than allowed values, smaller
// than the length
identifier = a_identifier;
kind = a_kind;
kindLength = a_kindLength;
identifierLength = a_identifierLength;
}
Integer getIdentifier() {
return identifier;
}
Integer getKind() {
return kind;
}
public boolean matches(ContainerLabel a_label)
throws IllegalArgumentException {
if (a_label == null) {
throw new IllegalArgumentException();
}
if ((getKind() == a_label.getKind())
&& (getIdentifier() == a_label.getIdentifier())) {
return true;
}
return false;
}
@Override
public String toString() {
return String.format("%1$03d%2$05d", kind, identifier);
}
}
| true | true | public ContainerLabel(Integer a_kind, Integer a_kindLength,
Integer a_identifier, Integer a_identifierLength)
throws LabelException, IllegalArgumentException {
// No null parameters supported
if ((a_kind == null) || (a_identifier == null)
|| (a_kindLength == null) || (a_identifierLength == null)) {
throw new IllegalArgumentException(
"Cannot give null values for any parameters");
}
// No negative numbers supported
if ((a_kind < 0) || (a_identifier < 0) || (a_kindLength < 0)
|| (a_identifierLength < 0)) {
throw new LabelException("Cannot give negative values to cargo");
}
// Check that the label kind and identifier are valid range
if ((a_kindLength > 3) || (a_identifierLength > 5)) {
throw new LabelException("Cannot assign that high a value");
}
// TODO test to see if the length is larger than allowed values, smaller
// than the length
identifier = a_identifier;
kind = a_kind;
kindLength = a_kindLength;
identifierLength = a_identifierLength;
}
| public ContainerLabel(Integer a_kind, Integer a_kindLength,
Integer a_identifier, Integer a_identifierLength)
throws LabelException, IllegalArgumentException {
// No null parameters supported
if ((a_kind == null) || (a_identifier == null)
|| (a_kindLength == null) || (a_identifierLength == null)) {
throw new IllegalArgumentException(
"Cannot give null values for any parameters");
}
// No negative numbers supported
if ((a_kind < 0) || (a_identifier < 0) || (a_kindLength <= 0)
|| (a_identifierLength <= 0)) {
throw new LabelException(
"Cannot give negative values for kind/identifier or zero lengths");
}
// Check that the label kind and identifier are valid range
if ((a_kindLength > 3) || (a_identifierLength > 5)) {
throw new LabelException("Cannot assign that high a value");
}
// TODO test to see if the length is larger than allowed values, smaller
// than the length
identifier = a_identifier;
kind = a_kind;
kindLength = a_kindLength;
identifierLength = a_identifierLength;
}
|
diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutorWithMocks.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutorWithMocks.java
index 41517c202..4827d8319 100644
--- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutorWithMocks.java
+++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutorWithMocks.java
@@ -1,148 +1,148 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.nodemanager;
import static junit.framework.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ContainerLaunchContext;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TestLinuxContainerExecutorWithMocks {
@SuppressWarnings("unused")
private static final Log LOG = LogFactory
.getLog(TestLinuxContainerExecutorWithMocks.class);
private LinuxContainerExecutor mockExec = null;
private final File mockParamFile = new File("./params.txt");
private void deleteMockParamFile() {
if(mockParamFile.exists()) {
mockParamFile.delete();
}
}
private List<String> readMockParams() throws IOException {
LinkedList<String> ret = new LinkedList<String>();
LineNumberReader reader = new LineNumberReader(new FileReader(
mockParamFile));
String line;
while((line = reader.readLine()) != null) {
ret.add(line);
}
reader.close();
return ret;
}
@Before
public void setup() {
File f = new File("./src/test/resources/mock-container-executor");
if(!f.canExecute()) {
f.setExecutable(true);
}
String executorPath = f.getAbsolutePath();
Configuration conf = new Configuration();
conf.set(YarnConfiguration.NM_LINUX_CONTAINER_EXECUTOR_PATH, executorPath);
mockExec = new LinuxContainerExecutor();
mockExec.setConf(conf);
}
@After
public void tearDown() {
deleteMockParamFile();
}
@Test
public void testContainerLaunch() throws IOException {
String appSubmitter = "nobody";
String cmd = String.valueOf(
LinuxContainerExecutor.Commands.LAUNCH_CONTAINER.getValue());
String appId = "APP_ID";
String containerId = "CONTAINER_ID";
Container container = mock(Container.class);
ContainerId cId = mock(ContainerId.class);
ContainerLaunchContext context = mock(ContainerLaunchContext.class);
HashMap<String, String> env = new HashMap<String,String>();
when(container.getContainerID()).thenReturn(cId);
when(container.getLaunchContext()).thenReturn(context);
when(cId.toString()).thenReturn(containerId);
when(context.getEnvironment()).thenReturn(env);
Path scriptPath = new Path("file:///bin/echo");
Path tokensPath = new Path("file:///dev/null");
Path workDir = new Path("/tmp");
Path pidFile = new Path(workDir, "pid.txt");
mockExec.activateContainer(cId, pidFile);
int ret = mockExec.launchContainer(container, scriptPath, tokensPath,
appSubmitter, appId, workDir);
assertEquals(0, ret);
assertEquals(Arrays.asList(appSubmitter, cmd, appId, containerId,
- workDir.toString(), "/bin/echo", "/dev/null", pidFile),
+ workDir.toString(), "/bin/echo", "/dev/null", pidFile.toString()),
readMockParams());
}
@Test
public void testContainerKill() throws IOException {
String appSubmitter = "nobody";
String cmd = String.valueOf(
LinuxContainerExecutor.Commands.SIGNAL_CONTAINER.getValue());
ContainerExecutor.Signal signal = ContainerExecutor.Signal.QUIT;
String sigVal = String.valueOf(signal.getValue());
mockExec.signalContainer(appSubmitter, "1000", signal);
assertEquals(Arrays.asList(appSubmitter, cmd, "1000", sigVal),
readMockParams());
}
@Test
public void testDeleteAsUser() throws IOException {
String appSubmitter = "nobody";
String cmd = String.valueOf(
LinuxContainerExecutor.Commands.DELETE_AS_USER.getValue());
Path dir = new Path("/tmp/testdir");
mockExec.deleteAsUser(appSubmitter, dir);
assertEquals(Arrays.asList(appSubmitter, cmd, "/tmp/testdir"),
readMockParams());
}
}
| true | true | public void testContainerLaunch() throws IOException {
String appSubmitter = "nobody";
String cmd = String.valueOf(
LinuxContainerExecutor.Commands.LAUNCH_CONTAINER.getValue());
String appId = "APP_ID";
String containerId = "CONTAINER_ID";
Container container = mock(Container.class);
ContainerId cId = mock(ContainerId.class);
ContainerLaunchContext context = mock(ContainerLaunchContext.class);
HashMap<String, String> env = new HashMap<String,String>();
when(container.getContainerID()).thenReturn(cId);
when(container.getLaunchContext()).thenReturn(context);
when(cId.toString()).thenReturn(containerId);
when(context.getEnvironment()).thenReturn(env);
Path scriptPath = new Path("file:///bin/echo");
Path tokensPath = new Path("file:///dev/null");
Path workDir = new Path("/tmp");
Path pidFile = new Path(workDir, "pid.txt");
mockExec.activateContainer(cId, pidFile);
int ret = mockExec.launchContainer(container, scriptPath, tokensPath,
appSubmitter, appId, workDir);
assertEquals(0, ret);
assertEquals(Arrays.asList(appSubmitter, cmd, appId, containerId,
workDir.toString(), "/bin/echo", "/dev/null", pidFile),
readMockParams());
}
| public void testContainerLaunch() throws IOException {
String appSubmitter = "nobody";
String cmd = String.valueOf(
LinuxContainerExecutor.Commands.LAUNCH_CONTAINER.getValue());
String appId = "APP_ID";
String containerId = "CONTAINER_ID";
Container container = mock(Container.class);
ContainerId cId = mock(ContainerId.class);
ContainerLaunchContext context = mock(ContainerLaunchContext.class);
HashMap<String, String> env = new HashMap<String,String>();
when(container.getContainerID()).thenReturn(cId);
when(container.getLaunchContext()).thenReturn(context);
when(cId.toString()).thenReturn(containerId);
when(context.getEnvironment()).thenReturn(env);
Path scriptPath = new Path("file:///bin/echo");
Path tokensPath = new Path("file:///dev/null");
Path workDir = new Path("/tmp");
Path pidFile = new Path(workDir, "pid.txt");
mockExec.activateContainer(cId, pidFile);
int ret = mockExec.launchContainer(container, scriptPath, tokensPath,
appSubmitter, appId, workDir);
assertEquals(0, ret);
assertEquals(Arrays.asList(appSubmitter, cmd, appId, containerId,
workDir.toString(), "/bin/echo", "/dev/null", pidFile.toString()),
readMockParams());
}
|
diff --git a/src/ibis/satin/impl/Stats.java b/src/ibis/satin/impl/Stats.java
index 18dbbc29..400391ab 100644
--- a/src/ibis/satin/impl/Stats.java
+++ b/src/ibis/satin/impl/Stats.java
@@ -1,749 +1,749 @@
/* $Id$ */
package ibis.satin.impl;
import ibis.util.Timer;
public abstract class Stats extends SharedObjects {
protected StatsMessage createStats() {
StatsMessage s = new StatsMessage();
s.spawns = spawns;
s.jobsExecuted = jobsExecuted;
s.syncs = syncs;
s.aborts = aborts;
s.abortMessages = abortMessages;
s.abortedJobs = abortedJobs;
s.stealAttempts = stealAttempts;
s.stealSuccess = stealSuccess;
s.tupleMsgs = tupleMsgs;
s.tupleBytes = tupleBytes;
s.stolenJobs = stolenJobs;
s.stealRequests = stealRequests;
s.interClusterMessages = interClusterMessages;
s.intraClusterMessages = intraClusterMessages;
s.interClusterBytes = interClusterBytes;
s.intraClusterBytes = intraClusterBytes;
s.stealTime = stealTimer.totalTimeVal();
s.handleStealTime = handleStealTimer.totalTimeVal();
s.abortTime = abortTimer.totalTimeVal();
s.idleTime = idleTimer.totalTimeVal();
s.idleCount = idleTimer.nrTimes();
s.pollTime = pollTimer.totalTimeVal();
s.pollCount = pollTimer.nrTimes();
s.tupleTime = tupleTimer.totalTimeVal();
s.handleTupleTime = handleTupleTimer.totalTimeVal();
s.tupleWaitTime = tupleOrderingWaitTimer.totalTimeVal();
s.tupleWaitCount = tupleOrderingWaitTimer.nrTimes();
s.invocationRecordWriteTime = invocationRecordWriteTimer.totalTimeVal();
s.invocationRecordWriteCount = invocationRecordWriteTimer.nrTimes();
s.invocationRecordReadTime = invocationRecordReadTimer.totalTimeVal();
s.invocationRecordReadCount = invocationRecordReadTimer.nrTimes();
s.returnRecordWriteTime = returnRecordWriteTimer.totalTimeVal();
s.returnRecordWriteCount = returnRecordWriteTimer.nrTimes();
s.returnRecordReadTime = returnRecordReadTimer.totalTimeVal();
s.returnRecordReadCount = returnRecordReadTimer.nrTimes();
s.returnRecordBytes = returnRecordBytes;
//fault tolerance
if (FAULT_TOLERANCE) {
s.tableResultUpdates = globalResultTable.numResultUpdates;
s.tableLockUpdates = globalResultTable.numLockUpdates;
s.tableUpdateMessages = globalResultTable.numUpdateMessages;
s.tableLookups = globalResultTable.numLookups;
s.tableSuccessfulLookups = globalResultTable.numLookupsSucceded;
s.tableRemoteLookups = globalResultTable.numRemoteLookups;
s.killedOrphans = killedOrphans;
s.restartedJobs = restartedJobs;
s.tableLookupTime = lookupTimer.totalTimeVal();
s.tableUpdateTime = updateTimer.totalTimeVal();
s.tableHandleUpdateTime = handleUpdateTimer.totalTimeVal();
s.tableHandleLookupTime = handleLookupTimer.totalTimeVal();
s.tableSerializationTime = tableSerializationTimer.totalTimeVal();
s.tableDeserializationTime = tableDeserializationTimer
.totalTimeVal();
s.tableCheckTime = redoTimer.totalTimeVal();
s.crashHandlingTime = crashTimer.totalTimeVal();
s.addReplicaTime = addReplicaTimer.totalTimeVal();
}
if (SHARED_OBJECTS) {
s.soInvocations = soInvocations;
s.soInvocationsBytes = soInvocationsBytes;
s.soTransfers = soTransfers;
s.soTransfersBytes = soTransfersBytes;
s.handleSOInvocationsTime = handleSOInvocationsTimer.totalTimeVal();
s.broadcastSOInvocationsTime = broadcastSOInvocationsTimer
.totalTimeVal();
s.soTransferTime = soTransferTimer.totalTimeVal();
s.soSerializationTime = soSerializationTimer.totalTimeVal();
s.soDeserializationTime = soDeserializationTimer.totalTimeVal();
s.soBcastTime = soBroadcastTransferTimer.totalTimeVal();
s.soBcastSerializationTime = soBroadcastSerializationTimer.totalTimeVal();
s.soBcastDeserializationTime = soBroadcastDeserializationTimer.totalTimeVal();
s.soRealMessageCount = soRealMessageCount;
s.soBcasts = soBcasts;
s.soBcastBytes = soBcastBytes;
}
return s;
}
private double perStats(double tm, long cnt) {
if (cnt == 0) {
return 0.0;
}
return tm / cnt;
}
protected void printStats() {
int size;
synchronized (this) {
// size = victims.size();
// No, this is one too few. (Ceriel)
size = victims.size() + 1;
}
// add my own stats
StatsMessage me = createStats();
totalStats.add(me);
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
// pf.setMaximumIntegerDigits(3);
// pf.setMinimumIntegerDigits(3);
// for percentages
java.text.NumberFormat pf = java.text.NumberFormat.getInstance();
pf.setMaximumFractionDigits(3);
pf.setMinimumFractionDigits(3);
pf.setGroupingUsed(false);
out.println("-------------------------------SATIN STATISTICS------"
+ "--------------------------");
if (SPAWN_STATS) {
out.println("SATIN: SPAWN: " + nf.format(totalStats.spawns)
+ " spawns, " + nf.format(totalStats.jobsExecuted)
+ " executed, " + nf.format(totalStats.syncs) + " syncs");
if (ABORTS) {
out.println("SATIN: ABORT: "
+ nf.format(totalStats.aborts) + " aborts, "
+ nf.format(totalStats.abortMessages) + " abort msgs, "
+ nf.format(totalStats.abortedJobs) + " aborted jobs");
}
}
if (TUPLE_STATS) {
out.println("SATIN: TUPLE_SPACE: "
+ nf.format(totalStats.tupleMsgs) + " bcasts, "
+ nf.format(totalStats.tupleBytes) + " bytes");
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL: poll count = "
+ nf.format(totalStats.pollCount));
}
if (IDLE_TIMING) {
out.println("SATIN: IDLE: idle count = "
+ nf.format(totalStats.idleCount));
}
if (STEAL_STATS) {
out.println("SATIN: STEAL: "
+ nf.format(totalStats.stealAttempts)
+ " attempts, "
+ nf.format(totalStats.stealSuccess)
+ " successes ("
+ pf.format(perStats((double) totalStats.stealSuccess,
totalStats.stealAttempts) * 100.0) + " %)");
if (totalStats.asyncStealAttempts != 0) {
out.println("SATIN: ASYNCSTEAL: "
+ nf.format(totalStats.asyncStealAttempts)
+ " attempts, "
+ nf.format(totalStats.asyncStealSuccess)
+ " successes ("
+ pf.format(perStats((double) totalStats.asyncStealSuccess,
totalStats.asyncStealAttempts) * 100.0) + " %)");
}
out.println("SATIN: MESSAGES: intra "
+ nf.format(totalStats.intraClusterMessages) + " msgs, "
+ nf.format(totalStats.intraClusterBytes) + " bytes; inter "
+ nf.format(totalStats.interClusterMessages) + " msgs, "
+ nf.format(totalStats.interClusterBytes) + " bytes");
}
if (FAULT_TOLERANCE && GRT_STATS) {
out.println("SATIN: GLOBAL_RESULT_TABLE: result updates "
+ nf.format(totalStats.tableResultUpdates)
+ ",update messages "
+ nf.format(totalStats.tableUpdateMessages) + ", lock updates "
+ nf.format(totalStats.tableLockUpdates) + ",lookups "
+ nf.format(totalStats.tableLookups) + ",successful "
+ nf.format(totalStats.tableSuccessfulLookups) + ",remote "
+ nf.format(totalStats.tableRemoteLookups));
}
if (FAULT_TOLERANCE && FT_STATS) {
out.println("SATIN: FAULT_TOLERANCE: killed orphans "
+ nf.format(totalStats.killedOrphans));
out.println("SATIN: FAULT_TOLERANCE: restarted jobs "
+ nf.format(totalStats.restartedJobs));
}
if (SHARED_OBJECTS && SO_STATS) {
out.println("SATIN: SO_CALLS: "
- + nf.format(totalStats.soInvocations) + " invocations "
+ + nf.format(totalStats.soInvocations) + " invocations, "
+ nf.format(totalStats.soInvocationsBytes) + " bytes, "
+ nf.format(totalStats.soRealMessageCount) + " messages");
out.println("SATIN: SO_TRANSFER: "
- + nf.format(totalStats.soTransfers) + " transfers "
+ + nf.format(totalStats.soTransfers) + " transfers, "
+ nf.format(totalStats.soTransfersBytes) + " bytes ");
out.println("SATIN: SO_BCAST : "
- + nf.format(totalStats.soBcasts) + " bcasts "
+ + nf.format(totalStats.soBcasts) + " bcasts, "
+ nf.format(totalStats.soBcastBytes) + " bytes ");
}
out.println("-------------------------------SATIN TOTAL TIMES"
+ "-------------------------------");
if (STEAL_TIMING) {
out.println("SATIN: STEAL_TIME: total "
+ Timer.format(totalStats.stealTime)
+ " time/req "
+ Timer.format(perStats(totalStats.stealTime,
totalStats.stealAttempts)));
out.println("SATIN: HANDLE_STEAL_TIME: total "
+ Timer.format(totalStats.handleStealTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.handleStealTime,
totalStats.stealAttempts)));
out.println("SATIN: INV SERIALIZATION_TIME: total "
+ Timer.format(totalStats.invocationRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(totalStats.invocationRecordWriteTime,
totalStats.stealSuccess)));
out.println("SATIN: INV DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.invocationRecordReadTime)
+ " time/read "
+ Timer.format(perStats(totalStats.invocationRecordReadTime,
totalStats.stealSuccess)));
out.println("SATIN: RET SERIALIZATION_TIME: total "
+ Timer.format(totalStats.returnRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(totalStats.returnRecordWriteTime,
totalStats.returnRecordWriteCount)));
out.println("SATIN: RET DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.returnRecordReadTime)
+ " time/read "
+ Timer.format(perStats(totalStats.returnRecordReadTime,
totalStats.returnRecordReadCount)));
}
if (ABORT_TIMING) {
out.println("SATIN: ABORT_TIME: total "
+ Timer.format(totalStats.abortTime)
+ " time/abort "
+ Timer
.format(perStats(totalStats.abortTime, totalStats.aborts)));
}
if (TUPLE_TIMING) {
out.println("SATIN: TUPLE_SPACE_BCAST_TIME: total "
+ Timer.format(totalStats.tupleTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.tupleTime,
totalStats.tupleMsgs)));
out.println("SATIN: TUPLE_SPACE_WAIT_TIME: total "
+ Timer.format(totalStats.tupleWaitTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.tupleWaitTime,
totalStats.tupleWaitCount)));
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL_TIME: total "
+ Timer.format(totalStats.pollTime)
+ " time/poll "
+ Timer.format(perStats(totalStats.pollTime,
totalStats.pollCount)));
}
if (IDLE_TIMING) {
out.println("SATIN: IDLE_TIME: total "
+ Timer.format(totalStats.idleTime)
+ " time/idle "
+ Timer.format(perStats(totalStats.idleTime,
totalStats.idleCount)));
}
if (FAULT_TOLERANCE && GRT_TIMING) {
out
.println("SATIN: GRT_UPDATE_TIME: total "
+ Timer.format(totalStats.tableUpdateTime)
+ " time/update "
+ Timer
.format(perStats(
totalStats.tableUpdateTime,
(totalStats.tableResultUpdates + totalStats.tableLockUpdates))));
out.println("SATIN: GRT_LOOKUP_TIME: total "
+ Timer.format(totalStats.tableLookupTime)
+ " time/lookup "
+ Timer.format(perStats(totalStats.tableLookupTime,
totalStats.tableLookups)));
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: total "
+ Timer.format(totalStats.tableHandleUpdateTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.tableHandleUpdateTime,
totalStats.tableResultUpdates * (size - 1))));
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: total "
+ Timer.format(totalStats.tableHandleLookupTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.tableHandleLookupTime,
totalStats.tableRemoteLookups)));
out.println("SATIN: GRT_SERIALIZATION_TIME: total "
+ Timer.format(totalStats.tableSerializationTime));
out.println("SATIN: GRT_DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.tableDeserializationTime));
out.println("SATIN: GRT_CHECK_TIME: total "
+ Timer.format(totalStats.tableCheckTime)
+ " time/check "
+ Timer.format(perStats(totalStats.tableCheckTime,
totalStats.tableLookups)));
}
if (FAULT_TOLERANCE && CRASH_TIMING) {
out.println("SATIN: CRASH_HANDLING_TIME: total "
+ Timer.format(totalStats.crashHandlingTime));
}
if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) {
out.println("SATIN: ADD_REPLICA_TIME: total "
+ Timer.format(totalStats.addReplicaTime));
}
if (SHARED_OBJECTS && SO_TIMING) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: total "
+ Timer.format(totalStats.broadcastSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(totalStats.broadcastSOInvocationsTime,
totalStats.soInvocations)));
out.println("SATIN: HANDLE_SO_INVOCATIONS: total "
+ Timer.format(totalStats.handleSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(totalStats.handleSOInvocationsTime,
totalStats.soInvocations * (size - 1))));
out.println("SATIN: SO_TRANSFERS: total "
+ Timer.format(totalStats.soTransferTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soTransferTime,
totalStats.soTransfers)));
out.println("SATIN: SO_SERIALIZATION: total "
+ Timer.format(totalStats.soSerializationTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soSerializationTime,
totalStats.soTransfers)));
out.println("SATIN: SO_DESERIALIZATION: total "
+ Timer.format(totalStats.soDeserializationTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soDeserializationTime,
totalStats.soTransfers)));
out.println("SATIN: SO_BCASTS : total "
+ Timer.format(totalStats.soBcastTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.soBcastTime,
totalStats.soBcasts)));
out.println("SATIN: SO_BCAST_SERIALIZATION total "
+ Timer.format(totalStats.soBcastSerializationTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.soBcastSerializationTime,
totalStats.soBcasts)));
out.println("SATIN: SO_BCAST_DESERIALIZATION: total "
+ Timer.format(totalStats.soBcastDeserializationTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.soBcastDeserializationTime,
totalStats.soBcasts)));
}
out.println("-------------------------------SATIN RUN TIME "
+ "BREAKDOWN------------------------");
out.println("SATIN: TOTAL_RUN_TIME: "
+ Timer.format(totalTimer.totalTimeVal()));
double lbTime = (totalStats.stealTime + totalStats.handleStealTime
- totalStats.invocationRecordReadTime - totalStats.invocationRecordWriteTime)
/ size;
if (lbTime < 0.0) {
lbTime = 0.0;
}
double lbPerc = lbTime / totalTimer.totalTimeVal() * 100.0;
double serTime = (totalStats.invocationRecordWriteTime
+ totalStats.invocationRecordReadTime
+ totalStats.returnRecordWriteTime + totalStats.returnRecordReadTime)
/ size;
double serPerc = serTime / totalTimer.totalTimeVal() * 100.0;
double abortTime = totalStats.abortTime / size;
double abortPerc = abortTime / totalTimer.totalTimeVal() * 100.0;
double tupleTime = totalStats.tupleTime / size;
double tuplePerc = tupleTime / totalTimer.totalTimeVal() * 100.0;
double handleTupleTime = totalStats.handleTupleTime / size;
double handleTuplePerc = handleTupleTime / totalTimer.totalTimeVal()
* 100.0;
double tupleWaitTime = totalStats.tupleWaitTime / size;
double tupleWaitPerc = tupleWaitTime / totalTimer.totalTimeVal()
* 100.0;
double pollTime = totalStats.pollTime / size;
double pollPerc = pollTime / totalTimer.totalTimeVal() * 100.0;
double tableUpdateTime = totalStats.tableUpdateTime / size;
double tableUpdatePerc = tableUpdateTime / totalTimer.totalTimeVal()
* 100.0;
double tableLookupTime = totalStats.tableLookupTime / size;
double tableLookupPerc = tableLookupTime / totalTimer.totalTimeVal()
* 100.0;
double tableHandleUpdateTime = totalStats.tableHandleUpdateTime / size;
double tableHandleUpdatePerc = tableHandleUpdateTime
/ totalTimer.totalTimeVal() * 100.0;
double tableHandleLookupTime = totalStats.tableHandleLookupTime / size;
double tableHandleLookupPerc = tableHandleLookupTime
/ totalTimer.totalTimeVal() * 100.0;
double tableSerializationTime = totalStats.tableSerializationTime
/ size;
double tableSerializationPerc = tableSerializationTime
/ totalTimer.totalTimeVal() * 100;
double tableDeserializationTime = totalStats.tableDeserializationTime
/ size;
double tableDeserializationPerc = tableDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double crashHandlingTime = totalStats.crashHandlingTime / size;
double crashHandlingPerc = crashHandlingTime
/ totalTimer.totalTimeVal() * 100.0;
double addReplicaTime = totalStats.addReplicaTime / size;
double addReplicaPerc = addReplicaTime / totalTimer.totalTimeVal()
* 100.0;
double broadcastSOInvocationsTime = totalStats.broadcastSOInvocationsTime
/ size;
double broadcastSOInvocationsPerc = broadcastSOInvocationsTime
/ totalTimer.totalTimeVal() * 100;
double handleSOInvocationsTime = totalStats.handleSOInvocationsTime
/ size;
double handleSOInvocationsPerc = handleSOInvocationsTime
/ totalTimer.totalTimeVal() * 100;
double soTransferTime = totalStats.soTransferTime / size;
double soTransferPerc = soTransferTime / totalTimer.totalTimeVal()
* 100;
double soSerializationTime = totalStats.soSerializationTime / size;
double soSerializationPerc = soSerializationTime
/ totalTimer.totalTimeVal() * 100;
double soDeserializationTime = totalStats.soDeserializationTime / size;
double soDeserializationPerc = soDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double totalOverhead = abortTime
+ tupleTime
+ handleTupleTime
+ tupleWaitTime
+ pollTime
+ tableUpdateTime
+ tableLookupTime
+ tableHandleUpdateTime
+ tableHandleLookupTime
+ handleSOInvocationsTime
+ broadcastSOInvocationsTime
+ soTransferTime
+ (totalStats.stealTime + totalStats.handleStealTime
+ totalStats.returnRecordReadTime + totalStats.returnRecordWriteTime)
/ size;
double totalPerc = totalOverhead / totalTimer.totalTimeVal() * 100.0;
double appTime = totalTimer.totalTimeVal() - totalOverhead;
if (appTime < 0.0) {
appTime = 0.0;
}
double appPerc = appTime / totalTimer.totalTimeVal() * 100.0;
if (STEAL_TIMING) {
out.println("SATIN: LOAD_BALANCING_TIME: avg. per machine "
+ Timer.format(lbTime) + " (" + (lbPerc < 10 ? " " : "")
+ pf.format(lbPerc) + " %)");
out.println("SATIN: (DE)SERIALIZATION_TIME: avg. per machine "
+ Timer.format(serTime) + " (" + (serPerc < 10 ? " " : "")
+ pf.format(serPerc) + " %)");
}
if (ABORT_TIMING) {
out.println("SATIN: ABORT_TIME: avg. per machine "
+ Timer.format(abortTime) + " (" + (abortPerc < 10 ? " " : "")
+ pf.format(abortPerc) + " %)");
}
if (TUPLE_TIMING) {
out.println("SATIN: TUPLE_SPACE_BCAST_TIME: avg. per machine "
+ Timer.format(tupleTime) + " (" + (tuplePerc < 10 ? " " : "")
+ pf.format(tuplePerc) + " %)");
out.println("SATIN: TUPLE_SPACE_HANDLE_TIME: avg. per machine "
+ Timer.format(handleTupleTime) + " ("
+ (handleTuplePerc < 10 ? " " : "")
+ pf.format(handleTuplePerc) + " %)");
out.println("SATIN: TUPLE_SPACE_WAIT_TIME: avg. per machine "
+ Timer.format(tupleWaitTime) + " ("
+ (tupleWaitPerc < 10 ? " " : "") + pf.format(tupleWaitPerc)
+ " %)");
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL_TIME: avg. per machine "
+ Timer.format(pollTime) + " (" + (pollPerc < 10 ? " " : "")
+ pf.format(pollPerc) + " %)");
}
if (FAULT_TOLERANCE && GRT_TIMING) {
out.println("SATIN: GRT_UPDATE_TIME: avg. per machine "
+ Timer.format(tableUpdateTime) + " ("
+ pf.format(tableUpdatePerc) + " %)");
out.println("SATIN: GRT_LOOKUP_TIME: avg. per machine "
+ Timer.format(tableLookupTime) + " ("
+ pf.format(tableLookupPerc) + " %)");
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: avg. per machine "
+ Timer.format(tableHandleUpdateTime) + " ("
+ pf.format(tableHandleUpdatePerc) + " %)");
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: avg. per machine "
+ Timer.format(tableHandleLookupTime) + " ("
+ pf.format(tableHandleLookupPerc) + " %)");
out.println("SATIN: GRT_SERIALIZATION_TIME: avg. per machine "
+ Timer.format(tableSerializationTime) + " ("
+ pf.format(tableSerializationPerc) + " %)");
out.println("SATIN: GRT_DESERIALIZATION_TIME: avg. per machine "
+ Timer.format(tableDeserializationTime) + " ("
+ pf.format(tableDeserializationPerc) + " %)");
}
if (FAULT_TOLERANCE && CRASH_TIMING) {
out.println("SATIN: CRASH_HANDLING_TIME: avg. per machine "
+ Timer.format(crashHandlingTime) + " ("
+ pf.format(crashHandlingPerc) + " %)");
}
if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) {
out.println("SATIN: ADD_REPLICA_TIME: avg. per machine "
+ Timer.format(addReplicaTime) + " ("
+ pf.format(addReplicaPerc) + " %)");
}
if (SHARED_OBJECTS && SO_TIMING) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: avg. per machine "
+ Timer.format(broadcastSOInvocationsTime) + " ( "
+ pf.format(broadcastSOInvocationsPerc) + " %)");
out.println("SATIN: HANDLE_SO_INVOCATIONS: avg. per machine "
+ Timer.format(handleSOInvocationsTime) + " ( "
+ pf.format(handleSOInvocationsPerc) + " %)");
out.println("SATIN: SO_TRANSFERS: avg. per machine "
+ Timer.format(soTransferTime) + " ( "
+ pf.format(soTransferPerc) + " %)");
out.println("SATIN: SO_SERIALIZATION: avg. per machine "
+ Timer.format(soSerializationTime) + " ( "
+ pf.format(soSerializationPerc) + " %)");
out.println("SATIN: SO_DESERIALIZATION: avg. per machine "
+ Timer.format(soDeserializationTime) + " ( "
+ pf.format(soDeserializationPerc) + " %)");
}
out.println("\nSATIN: TOTAL_PARALLEL_OVERHEAD: avg. per machine "
+ Timer.format(totalOverhead) + " (" + (totalPerc < 10 ? " " : "")
+ pf.format(totalPerc) + " %)");
out.println("SATIN: USEFUL_APP_TIME: avg. per machine "
+ Timer.format(appTime) + " (" + (appPerc < 10 ? " " : "")
+ pf.format(appPerc) + " %)");
}
protected void printDetailedStats() {
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
if (SPAWN_STATS) {
out.println("SATIN '" + ident + "': SPAWN_STATS: spawns = "
+ spawns + " executed = " + jobsExecuted + " syncs = " + syncs);
if (ABORTS) {
out.println("SATIN '" + ident + "': ABORT_STATS 1: aborts = "
+ aborts + " abort msgs = " + abortMessages
+ " aborted jobs = " + abortedJobs);
}
}
if (TUPLE_STATS) {
out.println("SATIN '" + ident
+ "': TUPLE_STATS 1: tuple bcast msgs: " + tupleMsgs
+ ", bytes = " + nf.format(tupleBytes));
}
if (STEAL_STATS) {
out.println("SATIN '" + ident + "': INTRA_STATS: messages = "
+ intraClusterMessages + ", bytes = "
+ nf.format(intraClusterBytes));
out.println("SATIN '" + ident + "': INTER_STATS: messages = "
+ interClusterMessages + ", bytes = "
+ nf.format(interClusterBytes));
out.println("SATIN '" + ident + "': STEAL_STATS 1: attempts = "
+ stealAttempts + " success = " + stealSuccess + " ("
+ (perStats((double) stealSuccess, stealAttempts) * 100.0)
+ " %)");
out.println("SATIN '" + ident + "': STEAL_STATS 2: requests = "
+ stealRequests + " jobs stolen = " + stolenJobs);
if (STEAL_TIMING) {
out.println("SATIN '" + ident + "': STEAL_STATS 3: attempts = "
+ stealTimer.nrTimes() + " total time = "
+ stealTimer.totalTime() + " avg time = "
+ stealTimer.averageTime());
out.println("SATIN '" + ident
+ "': STEAL_STATS 4: handleSteals = "
+ handleStealTimer.nrTimes() + " total time = "
+ handleStealTimer.totalTime() + " avg time = "
+ handleStealTimer.averageTime());
out.println("SATIN '" + ident
+ "': STEAL_STATS 5: invocationRecordWrites = "
+ invocationRecordWriteTimer.nrTimes() + " total time = "
+ invocationRecordWriteTimer.totalTime() + " avg time = "
+ invocationRecordWriteTimer.averageTime());
out.println("SATIN '" + ident
+ "': STEAL_STATS 6: invocationRecordReads = "
+ invocationRecordReadTimer.nrTimes() + " total time = "
+ invocationRecordReadTimer.totalTime() + " avg time = "
+ invocationRecordReadTimer.averageTime());
out.println("SATIN '" + ident
+ "': STEAL_STATS 7: returnRecordWrites = "
+ returnRecordWriteTimer.nrTimes() + " total time = "
+ returnRecordWriteTimer.totalTime() + " avg time = "
+ returnRecordWriteTimer.averageTime());
out.println("SATIN '" + ident
+ "': STEAL_STATS 8: returnRecordReads = "
+ returnRecordReadTimer.nrTimes() + " total time = "
+ returnRecordReadTimer.totalTime() + " avg time = "
+ returnRecordReadTimer.averageTime());
}
if (ABORTS && ABORT_TIMING) {
out.println("SATIN '" + ident + "': ABORT_STATS 2: aborts = "
+ abortTimer.nrTimes() + " total time = "
+ abortTimer.totalTime() + " avg time = "
+ abortTimer.averageTime());
}
if (IDLE_TIMING) {
out.println("SATIN '" + ident + "': IDLE_STATS: idle count = "
+ idleTimer.nrTimes() + " total time = "
+ idleTimer.totalTime() + " avg time = "
+ idleTimer.averageTime());
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN '" + ident + "': POLL_STATS: poll count = "
+ pollTimer.nrTimes() + " total time = "
+ pollTimer.totalTime() + " avg time = "
+ pollTimer.averageTime());
}
if (STEAL_TIMING && IDLE_TIMING) {
out.println("SATIN '"
+ ident
+ "': COMM_STATS: software comm time = "
+ Timer.format(stealTimer.totalTimeVal()
+ handleStealTimer.totalTimeVal()
- idleTimer.totalTimeVal()));
}
if (TUPLE_TIMING) {
out.println("SATIN '" + ident + "': TUPLE_STATS 2: bcasts = "
+ tupleTimer.nrTimes() + " total time = "
+ tupleTimer.totalTime() + " avg time = "
+ tupleTimer.averageTime());
out.println("SATIN '" + ident + "': TUPLE_STATS 3: waits = "
+ tupleOrderingWaitTimer.nrTimes() + " total time = "
+ tupleOrderingWaitTimer.totalTime() + " avg time = "
+ tupleOrderingWaitTimer.averageTime());
}
algorithm.printStats(out);
}
if (FAULT_TOLERANCE) {
if (GRT_STATS) {
out.println("SATIN '" + ident + "': "
+ globalResultTable.numResultUpdates
+ " result updates of the table.");
out.println("SATIN '" + ident + "': "
+ globalResultTable.numLockUpdates
+ " lock updates of the table.");
out
.println("SATIN '" + ident + "': "
+ globalResultTable.numUpdateMessages
+ " update messages.");
out.println("SATIN '" + ident + "': "
+ globalResultTable.numLookupsSucceded
+ " lookups succeded, of which:");
out.println("SATIN '" + ident + "': "
+ globalResultTable.numRemoteLookups + " remote lookups.");
out.println("SATIN '" + ident + "': "
+ globalResultTable.maxNumEntries + " entries maximally.");
}
if (GRT_TIMING) {
out.println("SATIN '" + ident + "': " + lookupTimer.totalTime()
+ " spent in lookups");
out.println("SATIN '" + ident + "': "
+ lookupTimer.averageTime() + " per lookup");
out.println("SATIN '" + ident + "': " + updateTimer.totalTime()
+ " spent in updates");
out.println("SATIN '" + ident + "': "
+ updateTimer.averageTime() + " per update");
out.println("SATIN '" + ident + "': "
+ handleUpdateTimer.totalTime()
+ " spent in handling updates");
out.println("SATIN '" + ident + "': "
+ handleUpdateTimer.averageTime() + " per update handle");
out.println("SATIN '" + ident + "': "
+ handleLookupTimer.totalTime()
+ " spent in handling lookups");
out.println("SATIN '" + ident + "': "
+ handleLookupTimer.averageTime() + " per lookup handle");
}
if (CRASH_TIMING) {
out.println("SATIN '" + ident + "': " + crashTimer.totalTime()
+ " spent in handling crashes");
}
if (TABLE_CHECK_TIMING) {
out.println("SATIN '" + ident + "': " + redoTimer.totalTime()
+ " spent in redoing");
}
if (FT_STATS) {
out.println("SATIN '" + ident + "': " + killedOrphans
+ " orphans killed");
out.println("SATIN '" + ident + "': " + restartedJobs
+ " jobs restarted");
}
}
if (SHARED_OBJECTS && SO_STATS) {
out.println("SATIN '" + ident.name() + "': " + soInvocations
+ " shared object invocations sent.");
out.println("SATIN '" + ident.name() + "': " + soTransfers
+ " shared objects transfered.");
}
}
}
| false | true | protected void printStats() {
int size;
synchronized (this) {
// size = victims.size();
// No, this is one too few. (Ceriel)
size = victims.size() + 1;
}
// add my own stats
StatsMessage me = createStats();
totalStats.add(me);
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
// pf.setMaximumIntegerDigits(3);
// pf.setMinimumIntegerDigits(3);
// for percentages
java.text.NumberFormat pf = java.text.NumberFormat.getInstance();
pf.setMaximumFractionDigits(3);
pf.setMinimumFractionDigits(3);
pf.setGroupingUsed(false);
out.println("-------------------------------SATIN STATISTICS------"
+ "--------------------------");
if (SPAWN_STATS) {
out.println("SATIN: SPAWN: " + nf.format(totalStats.spawns)
+ " spawns, " + nf.format(totalStats.jobsExecuted)
+ " executed, " + nf.format(totalStats.syncs) + " syncs");
if (ABORTS) {
out.println("SATIN: ABORT: "
+ nf.format(totalStats.aborts) + " aborts, "
+ nf.format(totalStats.abortMessages) + " abort msgs, "
+ nf.format(totalStats.abortedJobs) + " aborted jobs");
}
}
if (TUPLE_STATS) {
out.println("SATIN: TUPLE_SPACE: "
+ nf.format(totalStats.tupleMsgs) + " bcasts, "
+ nf.format(totalStats.tupleBytes) + " bytes");
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL: poll count = "
+ nf.format(totalStats.pollCount));
}
if (IDLE_TIMING) {
out.println("SATIN: IDLE: idle count = "
+ nf.format(totalStats.idleCount));
}
if (STEAL_STATS) {
out.println("SATIN: STEAL: "
+ nf.format(totalStats.stealAttempts)
+ " attempts, "
+ nf.format(totalStats.stealSuccess)
+ " successes ("
+ pf.format(perStats((double) totalStats.stealSuccess,
totalStats.stealAttempts) * 100.0) + " %)");
if (totalStats.asyncStealAttempts != 0) {
out.println("SATIN: ASYNCSTEAL: "
+ nf.format(totalStats.asyncStealAttempts)
+ " attempts, "
+ nf.format(totalStats.asyncStealSuccess)
+ " successes ("
+ pf.format(perStats((double) totalStats.asyncStealSuccess,
totalStats.asyncStealAttempts) * 100.0) + " %)");
}
out.println("SATIN: MESSAGES: intra "
+ nf.format(totalStats.intraClusterMessages) + " msgs, "
+ nf.format(totalStats.intraClusterBytes) + " bytes; inter "
+ nf.format(totalStats.interClusterMessages) + " msgs, "
+ nf.format(totalStats.interClusterBytes) + " bytes");
}
if (FAULT_TOLERANCE && GRT_STATS) {
out.println("SATIN: GLOBAL_RESULT_TABLE: result updates "
+ nf.format(totalStats.tableResultUpdates)
+ ",update messages "
+ nf.format(totalStats.tableUpdateMessages) + ", lock updates "
+ nf.format(totalStats.tableLockUpdates) + ",lookups "
+ nf.format(totalStats.tableLookups) + ",successful "
+ nf.format(totalStats.tableSuccessfulLookups) + ",remote "
+ nf.format(totalStats.tableRemoteLookups));
}
if (FAULT_TOLERANCE && FT_STATS) {
out.println("SATIN: FAULT_TOLERANCE: killed orphans "
+ nf.format(totalStats.killedOrphans));
out.println("SATIN: FAULT_TOLERANCE: restarted jobs "
+ nf.format(totalStats.restartedJobs));
}
if (SHARED_OBJECTS && SO_STATS) {
out.println("SATIN: SO_CALLS: "
+ nf.format(totalStats.soInvocations) + " invocations "
+ nf.format(totalStats.soInvocationsBytes) + " bytes, "
+ nf.format(totalStats.soRealMessageCount) + " messages");
out.println("SATIN: SO_TRANSFER: "
+ nf.format(totalStats.soTransfers) + " transfers "
+ nf.format(totalStats.soTransfersBytes) + " bytes ");
out.println("SATIN: SO_BCAST : "
+ nf.format(totalStats.soBcasts) + " bcasts "
+ nf.format(totalStats.soBcastBytes) + " bytes ");
}
out.println("-------------------------------SATIN TOTAL TIMES"
+ "-------------------------------");
if (STEAL_TIMING) {
out.println("SATIN: STEAL_TIME: total "
+ Timer.format(totalStats.stealTime)
+ " time/req "
+ Timer.format(perStats(totalStats.stealTime,
totalStats.stealAttempts)));
out.println("SATIN: HANDLE_STEAL_TIME: total "
+ Timer.format(totalStats.handleStealTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.handleStealTime,
totalStats.stealAttempts)));
out.println("SATIN: INV SERIALIZATION_TIME: total "
+ Timer.format(totalStats.invocationRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(totalStats.invocationRecordWriteTime,
totalStats.stealSuccess)));
out.println("SATIN: INV DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.invocationRecordReadTime)
+ " time/read "
+ Timer.format(perStats(totalStats.invocationRecordReadTime,
totalStats.stealSuccess)));
out.println("SATIN: RET SERIALIZATION_TIME: total "
+ Timer.format(totalStats.returnRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(totalStats.returnRecordWriteTime,
totalStats.returnRecordWriteCount)));
out.println("SATIN: RET DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.returnRecordReadTime)
+ " time/read "
+ Timer.format(perStats(totalStats.returnRecordReadTime,
totalStats.returnRecordReadCount)));
}
if (ABORT_TIMING) {
out.println("SATIN: ABORT_TIME: total "
+ Timer.format(totalStats.abortTime)
+ " time/abort "
+ Timer
.format(perStats(totalStats.abortTime, totalStats.aborts)));
}
if (TUPLE_TIMING) {
out.println("SATIN: TUPLE_SPACE_BCAST_TIME: total "
+ Timer.format(totalStats.tupleTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.tupleTime,
totalStats.tupleMsgs)));
out.println("SATIN: TUPLE_SPACE_WAIT_TIME: total "
+ Timer.format(totalStats.tupleWaitTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.tupleWaitTime,
totalStats.tupleWaitCount)));
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL_TIME: total "
+ Timer.format(totalStats.pollTime)
+ " time/poll "
+ Timer.format(perStats(totalStats.pollTime,
totalStats.pollCount)));
}
if (IDLE_TIMING) {
out.println("SATIN: IDLE_TIME: total "
+ Timer.format(totalStats.idleTime)
+ " time/idle "
+ Timer.format(perStats(totalStats.idleTime,
totalStats.idleCount)));
}
if (FAULT_TOLERANCE && GRT_TIMING) {
out
.println("SATIN: GRT_UPDATE_TIME: total "
+ Timer.format(totalStats.tableUpdateTime)
+ " time/update "
+ Timer
.format(perStats(
totalStats.tableUpdateTime,
(totalStats.tableResultUpdates + totalStats.tableLockUpdates))));
out.println("SATIN: GRT_LOOKUP_TIME: total "
+ Timer.format(totalStats.tableLookupTime)
+ " time/lookup "
+ Timer.format(perStats(totalStats.tableLookupTime,
totalStats.tableLookups)));
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: total "
+ Timer.format(totalStats.tableHandleUpdateTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.tableHandleUpdateTime,
totalStats.tableResultUpdates * (size - 1))));
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: total "
+ Timer.format(totalStats.tableHandleLookupTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.tableHandleLookupTime,
totalStats.tableRemoteLookups)));
out.println("SATIN: GRT_SERIALIZATION_TIME: total "
+ Timer.format(totalStats.tableSerializationTime));
out.println("SATIN: GRT_DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.tableDeserializationTime));
out.println("SATIN: GRT_CHECK_TIME: total "
+ Timer.format(totalStats.tableCheckTime)
+ " time/check "
+ Timer.format(perStats(totalStats.tableCheckTime,
totalStats.tableLookups)));
}
if (FAULT_TOLERANCE && CRASH_TIMING) {
out.println("SATIN: CRASH_HANDLING_TIME: total "
+ Timer.format(totalStats.crashHandlingTime));
}
if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) {
out.println("SATIN: ADD_REPLICA_TIME: total "
+ Timer.format(totalStats.addReplicaTime));
}
if (SHARED_OBJECTS && SO_TIMING) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: total "
+ Timer.format(totalStats.broadcastSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(totalStats.broadcastSOInvocationsTime,
totalStats.soInvocations)));
out.println("SATIN: HANDLE_SO_INVOCATIONS: total "
+ Timer.format(totalStats.handleSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(totalStats.handleSOInvocationsTime,
totalStats.soInvocations * (size - 1))));
out.println("SATIN: SO_TRANSFERS: total "
+ Timer.format(totalStats.soTransferTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soTransferTime,
totalStats.soTransfers)));
out.println("SATIN: SO_SERIALIZATION: total "
+ Timer.format(totalStats.soSerializationTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soSerializationTime,
totalStats.soTransfers)));
out.println("SATIN: SO_DESERIALIZATION: total "
+ Timer.format(totalStats.soDeserializationTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soDeserializationTime,
totalStats.soTransfers)));
out.println("SATIN: SO_BCASTS : total "
+ Timer.format(totalStats.soBcastTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.soBcastTime,
totalStats.soBcasts)));
out.println("SATIN: SO_BCAST_SERIALIZATION total "
+ Timer.format(totalStats.soBcastSerializationTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.soBcastSerializationTime,
totalStats.soBcasts)));
out.println("SATIN: SO_BCAST_DESERIALIZATION: total "
+ Timer.format(totalStats.soBcastDeserializationTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.soBcastDeserializationTime,
totalStats.soBcasts)));
}
out.println("-------------------------------SATIN RUN TIME "
+ "BREAKDOWN------------------------");
out.println("SATIN: TOTAL_RUN_TIME: "
+ Timer.format(totalTimer.totalTimeVal()));
double lbTime = (totalStats.stealTime + totalStats.handleStealTime
- totalStats.invocationRecordReadTime - totalStats.invocationRecordWriteTime)
/ size;
if (lbTime < 0.0) {
lbTime = 0.0;
}
double lbPerc = lbTime / totalTimer.totalTimeVal() * 100.0;
double serTime = (totalStats.invocationRecordWriteTime
+ totalStats.invocationRecordReadTime
+ totalStats.returnRecordWriteTime + totalStats.returnRecordReadTime)
/ size;
double serPerc = serTime / totalTimer.totalTimeVal() * 100.0;
double abortTime = totalStats.abortTime / size;
double abortPerc = abortTime / totalTimer.totalTimeVal() * 100.0;
double tupleTime = totalStats.tupleTime / size;
double tuplePerc = tupleTime / totalTimer.totalTimeVal() * 100.0;
double handleTupleTime = totalStats.handleTupleTime / size;
double handleTuplePerc = handleTupleTime / totalTimer.totalTimeVal()
* 100.0;
double tupleWaitTime = totalStats.tupleWaitTime / size;
double tupleWaitPerc = tupleWaitTime / totalTimer.totalTimeVal()
* 100.0;
double pollTime = totalStats.pollTime / size;
double pollPerc = pollTime / totalTimer.totalTimeVal() * 100.0;
double tableUpdateTime = totalStats.tableUpdateTime / size;
double tableUpdatePerc = tableUpdateTime / totalTimer.totalTimeVal()
* 100.0;
double tableLookupTime = totalStats.tableLookupTime / size;
double tableLookupPerc = tableLookupTime / totalTimer.totalTimeVal()
* 100.0;
double tableHandleUpdateTime = totalStats.tableHandleUpdateTime / size;
double tableHandleUpdatePerc = tableHandleUpdateTime
/ totalTimer.totalTimeVal() * 100.0;
double tableHandleLookupTime = totalStats.tableHandleLookupTime / size;
double tableHandleLookupPerc = tableHandleLookupTime
/ totalTimer.totalTimeVal() * 100.0;
double tableSerializationTime = totalStats.tableSerializationTime
/ size;
double tableSerializationPerc = tableSerializationTime
/ totalTimer.totalTimeVal() * 100;
double tableDeserializationTime = totalStats.tableDeserializationTime
/ size;
double tableDeserializationPerc = tableDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double crashHandlingTime = totalStats.crashHandlingTime / size;
double crashHandlingPerc = crashHandlingTime
/ totalTimer.totalTimeVal() * 100.0;
double addReplicaTime = totalStats.addReplicaTime / size;
double addReplicaPerc = addReplicaTime / totalTimer.totalTimeVal()
* 100.0;
double broadcastSOInvocationsTime = totalStats.broadcastSOInvocationsTime
/ size;
double broadcastSOInvocationsPerc = broadcastSOInvocationsTime
/ totalTimer.totalTimeVal() * 100;
double handleSOInvocationsTime = totalStats.handleSOInvocationsTime
/ size;
double handleSOInvocationsPerc = handleSOInvocationsTime
/ totalTimer.totalTimeVal() * 100;
double soTransferTime = totalStats.soTransferTime / size;
double soTransferPerc = soTransferTime / totalTimer.totalTimeVal()
* 100;
double soSerializationTime = totalStats.soSerializationTime / size;
double soSerializationPerc = soSerializationTime
/ totalTimer.totalTimeVal() * 100;
double soDeserializationTime = totalStats.soDeserializationTime / size;
double soDeserializationPerc = soDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double totalOverhead = abortTime
+ tupleTime
+ handleTupleTime
+ tupleWaitTime
+ pollTime
+ tableUpdateTime
+ tableLookupTime
+ tableHandleUpdateTime
+ tableHandleLookupTime
+ handleSOInvocationsTime
+ broadcastSOInvocationsTime
+ soTransferTime
+ (totalStats.stealTime + totalStats.handleStealTime
+ totalStats.returnRecordReadTime + totalStats.returnRecordWriteTime)
/ size;
double totalPerc = totalOverhead / totalTimer.totalTimeVal() * 100.0;
double appTime = totalTimer.totalTimeVal() - totalOverhead;
if (appTime < 0.0) {
appTime = 0.0;
}
double appPerc = appTime / totalTimer.totalTimeVal() * 100.0;
if (STEAL_TIMING) {
out.println("SATIN: LOAD_BALANCING_TIME: avg. per machine "
+ Timer.format(lbTime) + " (" + (lbPerc < 10 ? " " : "")
+ pf.format(lbPerc) + " %)");
out.println("SATIN: (DE)SERIALIZATION_TIME: avg. per machine "
+ Timer.format(serTime) + " (" + (serPerc < 10 ? " " : "")
+ pf.format(serPerc) + " %)");
}
if (ABORT_TIMING) {
out.println("SATIN: ABORT_TIME: avg. per machine "
+ Timer.format(abortTime) + " (" + (abortPerc < 10 ? " " : "")
+ pf.format(abortPerc) + " %)");
}
if (TUPLE_TIMING) {
out.println("SATIN: TUPLE_SPACE_BCAST_TIME: avg. per machine "
+ Timer.format(tupleTime) + " (" + (tuplePerc < 10 ? " " : "")
+ pf.format(tuplePerc) + " %)");
out.println("SATIN: TUPLE_SPACE_HANDLE_TIME: avg. per machine "
+ Timer.format(handleTupleTime) + " ("
+ (handleTuplePerc < 10 ? " " : "")
+ pf.format(handleTuplePerc) + " %)");
out.println("SATIN: TUPLE_SPACE_WAIT_TIME: avg. per machine "
+ Timer.format(tupleWaitTime) + " ("
+ (tupleWaitPerc < 10 ? " " : "") + pf.format(tupleWaitPerc)
+ " %)");
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL_TIME: avg. per machine "
+ Timer.format(pollTime) + " (" + (pollPerc < 10 ? " " : "")
+ pf.format(pollPerc) + " %)");
}
if (FAULT_TOLERANCE && GRT_TIMING) {
out.println("SATIN: GRT_UPDATE_TIME: avg. per machine "
+ Timer.format(tableUpdateTime) + " ("
+ pf.format(tableUpdatePerc) + " %)");
out.println("SATIN: GRT_LOOKUP_TIME: avg. per machine "
+ Timer.format(tableLookupTime) + " ("
+ pf.format(tableLookupPerc) + " %)");
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: avg. per machine "
+ Timer.format(tableHandleUpdateTime) + " ("
+ pf.format(tableHandleUpdatePerc) + " %)");
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: avg. per machine "
+ Timer.format(tableHandleLookupTime) + " ("
+ pf.format(tableHandleLookupPerc) + " %)");
out.println("SATIN: GRT_SERIALIZATION_TIME: avg. per machine "
+ Timer.format(tableSerializationTime) + " ("
+ pf.format(tableSerializationPerc) + " %)");
out.println("SATIN: GRT_DESERIALIZATION_TIME: avg. per machine "
+ Timer.format(tableDeserializationTime) + " ("
+ pf.format(tableDeserializationPerc) + " %)");
}
if (FAULT_TOLERANCE && CRASH_TIMING) {
out.println("SATIN: CRASH_HANDLING_TIME: avg. per machine "
+ Timer.format(crashHandlingTime) + " ("
+ pf.format(crashHandlingPerc) + " %)");
}
if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) {
out.println("SATIN: ADD_REPLICA_TIME: avg. per machine "
+ Timer.format(addReplicaTime) + " ("
+ pf.format(addReplicaPerc) + " %)");
}
if (SHARED_OBJECTS && SO_TIMING) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: avg. per machine "
+ Timer.format(broadcastSOInvocationsTime) + " ( "
+ pf.format(broadcastSOInvocationsPerc) + " %)");
out.println("SATIN: HANDLE_SO_INVOCATIONS: avg. per machine "
+ Timer.format(handleSOInvocationsTime) + " ( "
+ pf.format(handleSOInvocationsPerc) + " %)");
out.println("SATIN: SO_TRANSFERS: avg. per machine "
+ Timer.format(soTransferTime) + " ( "
+ pf.format(soTransferPerc) + " %)");
out.println("SATIN: SO_SERIALIZATION: avg. per machine "
+ Timer.format(soSerializationTime) + " ( "
+ pf.format(soSerializationPerc) + " %)");
out.println("SATIN: SO_DESERIALIZATION: avg. per machine "
+ Timer.format(soDeserializationTime) + " ( "
+ pf.format(soDeserializationPerc) + " %)");
}
out.println("\nSATIN: TOTAL_PARALLEL_OVERHEAD: avg. per machine "
+ Timer.format(totalOverhead) + " (" + (totalPerc < 10 ? " " : "")
+ pf.format(totalPerc) + " %)");
out.println("SATIN: USEFUL_APP_TIME: avg. per machine "
+ Timer.format(appTime) + " (" + (appPerc < 10 ? " " : "")
+ pf.format(appPerc) + " %)");
}
| protected void printStats() {
int size;
synchronized (this) {
// size = victims.size();
// No, this is one too few. (Ceriel)
size = victims.size() + 1;
}
// add my own stats
StatsMessage me = createStats();
totalStats.add(me);
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
// pf.setMaximumIntegerDigits(3);
// pf.setMinimumIntegerDigits(3);
// for percentages
java.text.NumberFormat pf = java.text.NumberFormat.getInstance();
pf.setMaximumFractionDigits(3);
pf.setMinimumFractionDigits(3);
pf.setGroupingUsed(false);
out.println("-------------------------------SATIN STATISTICS------"
+ "--------------------------");
if (SPAWN_STATS) {
out.println("SATIN: SPAWN: " + nf.format(totalStats.spawns)
+ " spawns, " + nf.format(totalStats.jobsExecuted)
+ " executed, " + nf.format(totalStats.syncs) + " syncs");
if (ABORTS) {
out.println("SATIN: ABORT: "
+ nf.format(totalStats.aborts) + " aborts, "
+ nf.format(totalStats.abortMessages) + " abort msgs, "
+ nf.format(totalStats.abortedJobs) + " aborted jobs");
}
}
if (TUPLE_STATS) {
out.println("SATIN: TUPLE_SPACE: "
+ nf.format(totalStats.tupleMsgs) + " bcasts, "
+ nf.format(totalStats.tupleBytes) + " bytes");
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL: poll count = "
+ nf.format(totalStats.pollCount));
}
if (IDLE_TIMING) {
out.println("SATIN: IDLE: idle count = "
+ nf.format(totalStats.idleCount));
}
if (STEAL_STATS) {
out.println("SATIN: STEAL: "
+ nf.format(totalStats.stealAttempts)
+ " attempts, "
+ nf.format(totalStats.stealSuccess)
+ " successes ("
+ pf.format(perStats((double) totalStats.stealSuccess,
totalStats.stealAttempts) * 100.0) + " %)");
if (totalStats.asyncStealAttempts != 0) {
out.println("SATIN: ASYNCSTEAL: "
+ nf.format(totalStats.asyncStealAttempts)
+ " attempts, "
+ nf.format(totalStats.asyncStealSuccess)
+ " successes ("
+ pf.format(perStats((double) totalStats.asyncStealSuccess,
totalStats.asyncStealAttempts) * 100.0) + " %)");
}
out.println("SATIN: MESSAGES: intra "
+ nf.format(totalStats.intraClusterMessages) + " msgs, "
+ nf.format(totalStats.intraClusterBytes) + " bytes; inter "
+ nf.format(totalStats.interClusterMessages) + " msgs, "
+ nf.format(totalStats.interClusterBytes) + " bytes");
}
if (FAULT_TOLERANCE && GRT_STATS) {
out.println("SATIN: GLOBAL_RESULT_TABLE: result updates "
+ nf.format(totalStats.tableResultUpdates)
+ ",update messages "
+ nf.format(totalStats.tableUpdateMessages) + ", lock updates "
+ nf.format(totalStats.tableLockUpdates) + ",lookups "
+ nf.format(totalStats.tableLookups) + ",successful "
+ nf.format(totalStats.tableSuccessfulLookups) + ",remote "
+ nf.format(totalStats.tableRemoteLookups));
}
if (FAULT_TOLERANCE && FT_STATS) {
out.println("SATIN: FAULT_TOLERANCE: killed orphans "
+ nf.format(totalStats.killedOrphans));
out.println("SATIN: FAULT_TOLERANCE: restarted jobs "
+ nf.format(totalStats.restartedJobs));
}
if (SHARED_OBJECTS && SO_STATS) {
out.println("SATIN: SO_CALLS: "
+ nf.format(totalStats.soInvocations) + " invocations, "
+ nf.format(totalStats.soInvocationsBytes) + " bytes, "
+ nf.format(totalStats.soRealMessageCount) + " messages");
out.println("SATIN: SO_TRANSFER: "
+ nf.format(totalStats.soTransfers) + " transfers, "
+ nf.format(totalStats.soTransfersBytes) + " bytes ");
out.println("SATIN: SO_BCAST : "
+ nf.format(totalStats.soBcasts) + " bcasts, "
+ nf.format(totalStats.soBcastBytes) + " bytes ");
}
out.println("-------------------------------SATIN TOTAL TIMES"
+ "-------------------------------");
if (STEAL_TIMING) {
out.println("SATIN: STEAL_TIME: total "
+ Timer.format(totalStats.stealTime)
+ " time/req "
+ Timer.format(perStats(totalStats.stealTime,
totalStats.stealAttempts)));
out.println("SATIN: HANDLE_STEAL_TIME: total "
+ Timer.format(totalStats.handleStealTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.handleStealTime,
totalStats.stealAttempts)));
out.println("SATIN: INV SERIALIZATION_TIME: total "
+ Timer.format(totalStats.invocationRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(totalStats.invocationRecordWriteTime,
totalStats.stealSuccess)));
out.println("SATIN: INV DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.invocationRecordReadTime)
+ " time/read "
+ Timer.format(perStats(totalStats.invocationRecordReadTime,
totalStats.stealSuccess)));
out.println("SATIN: RET SERIALIZATION_TIME: total "
+ Timer.format(totalStats.returnRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(totalStats.returnRecordWriteTime,
totalStats.returnRecordWriteCount)));
out.println("SATIN: RET DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.returnRecordReadTime)
+ " time/read "
+ Timer.format(perStats(totalStats.returnRecordReadTime,
totalStats.returnRecordReadCount)));
}
if (ABORT_TIMING) {
out.println("SATIN: ABORT_TIME: total "
+ Timer.format(totalStats.abortTime)
+ " time/abort "
+ Timer
.format(perStats(totalStats.abortTime, totalStats.aborts)));
}
if (TUPLE_TIMING) {
out.println("SATIN: TUPLE_SPACE_BCAST_TIME: total "
+ Timer.format(totalStats.tupleTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.tupleTime,
totalStats.tupleMsgs)));
out.println("SATIN: TUPLE_SPACE_WAIT_TIME: total "
+ Timer.format(totalStats.tupleWaitTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.tupleWaitTime,
totalStats.tupleWaitCount)));
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL_TIME: total "
+ Timer.format(totalStats.pollTime)
+ " time/poll "
+ Timer.format(perStats(totalStats.pollTime,
totalStats.pollCount)));
}
if (IDLE_TIMING) {
out.println("SATIN: IDLE_TIME: total "
+ Timer.format(totalStats.idleTime)
+ " time/idle "
+ Timer.format(perStats(totalStats.idleTime,
totalStats.idleCount)));
}
if (FAULT_TOLERANCE && GRT_TIMING) {
out
.println("SATIN: GRT_UPDATE_TIME: total "
+ Timer.format(totalStats.tableUpdateTime)
+ " time/update "
+ Timer
.format(perStats(
totalStats.tableUpdateTime,
(totalStats.tableResultUpdates + totalStats.tableLockUpdates))));
out.println("SATIN: GRT_LOOKUP_TIME: total "
+ Timer.format(totalStats.tableLookupTime)
+ " time/lookup "
+ Timer.format(perStats(totalStats.tableLookupTime,
totalStats.tableLookups)));
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: total "
+ Timer.format(totalStats.tableHandleUpdateTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.tableHandleUpdateTime,
totalStats.tableResultUpdates * (size - 1))));
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: total "
+ Timer.format(totalStats.tableHandleLookupTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.tableHandleLookupTime,
totalStats.tableRemoteLookups)));
out.println("SATIN: GRT_SERIALIZATION_TIME: total "
+ Timer.format(totalStats.tableSerializationTime));
out.println("SATIN: GRT_DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.tableDeserializationTime));
out.println("SATIN: GRT_CHECK_TIME: total "
+ Timer.format(totalStats.tableCheckTime)
+ " time/check "
+ Timer.format(perStats(totalStats.tableCheckTime,
totalStats.tableLookups)));
}
if (FAULT_TOLERANCE && CRASH_TIMING) {
out.println("SATIN: CRASH_HANDLING_TIME: total "
+ Timer.format(totalStats.crashHandlingTime));
}
if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) {
out.println("SATIN: ADD_REPLICA_TIME: total "
+ Timer.format(totalStats.addReplicaTime));
}
if (SHARED_OBJECTS && SO_TIMING) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: total "
+ Timer.format(totalStats.broadcastSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(totalStats.broadcastSOInvocationsTime,
totalStats.soInvocations)));
out.println("SATIN: HANDLE_SO_INVOCATIONS: total "
+ Timer.format(totalStats.handleSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(totalStats.handleSOInvocationsTime,
totalStats.soInvocations * (size - 1))));
out.println("SATIN: SO_TRANSFERS: total "
+ Timer.format(totalStats.soTransferTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soTransferTime,
totalStats.soTransfers)));
out.println("SATIN: SO_SERIALIZATION: total "
+ Timer.format(totalStats.soSerializationTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soSerializationTime,
totalStats.soTransfers)));
out.println("SATIN: SO_DESERIALIZATION: total "
+ Timer.format(totalStats.soDeserializationTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soDeserializationTime,
totalStats.soTransfers)));
out.println("SATIN: SO_BCASTS : total "
+ Timer.format(totalStats.soBcastTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.soBcastTime,
totalStats.soBcasts)));
out.println("SATIN: SO_BCAST_SERIALIZATION total "
+ Timer.format(totalStats.soBcastSerializationTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.soBcastSerializationTime,
totalStats.soBcasts)));
out.println("SATIN: SO_BCAST_DESERIALIZATION: total "
+ Timer.format(totalStats.soBcastDeserializationTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.soBcastDeserializationTime,
totalStats.soBcasts)));
}
out.println("-------------------------------SATIN RUN TIME "
+ "BREAKDOWN------------------------");
out.println("SATIN: TOTAL_RUN_TIME: "
+ Timer.format(totalTimer.totalTimeVal()));
double lbTime = (totalStats.stealTime + totalStats.handleStealTime
- totalStats.invocationRecordReadTime - totalStats.invocationRecordWriteTime)
/ size;
if (lbTime < 0.0) {
lbTime = 0.0;
}
double lbPerc = lbTime / totalTimer.totalTimeVal() * 100.0;
double serTime = (totalStats.invocationRecordWriteTime
+ totalStats.invocationRecordReadTime
+ totalStats.returnRecordWriteTime + totalStats.returnRecordReadTime)
/ size;
double serPerc = serTime / totalTimer.totalTimeVal() * 100.0;
double abortTime = totalStats.abortTime / size;
double abortPerc = abortTime / totalTimer.totalTimeVal() * 100.0;
double tupleTime = totalStats.tupleTime / size;
double tuplePerc = tupleTime / totalTimer.totalTimeVal() * 100.0;
double handleTupleTime = totalStats.handleTupleTime / size;
double handleTuplePerc = handleTupleTime / totalTimer.totalTimeVal()
* 100.0;
double tupleWaitTime = totalStats.tupleWaitTime / size;
double tupleWaitPerc = tupleWaitTime / totalTimer.totalTimeVal()
* 100.0;
double pollTime = totalStats.pollTime / size;
double pollPerc = pollTime / totalTimer.totalTimeVal() * 100.0;
double tableUpdateTime = totalStats.tableUpdateTime / size;
double tableUpdatePerc = tableUpdateTime / totalTimer.totalTimeVal()
* 100.0;
double tableLookupTime = totalStats.tableLookupTime / size;
double tableLookupPerc = tableLookupTime / totalTimer.totalTimeVal()
* 100.0;
double tableHandleUpdateTime = totalStats.tableHandleUpdateTime / size;
double tableHandleUpdatePerc = tableHandleUpdateTime
/ totalTimer.totalTimeVal() * 100.0;
double tableHandleLookupTime = totalStats.tableHandleLookupTime / size;
double tableHandleLookupPerc = tableHandleLookupTime
/ totalTimer.totalTimeVal() * 100.0;
double tableSerializationTime = totalStats.tableSerializationTime
/ size;
double tableSerializationPerc = tableSerializationTime
/ totalTimer.totalTimeVal() * 100;
double tableDeserializationTime = totalStats.tableDeserializationTime
/ size;
double tableDeserializationPerc = tableDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double crashHandlingTime = totalStats.crashHandlingTime / size;
double crashHandlingPerc = crashHandlingTime
/ totalTimer.totalTimeVal() * 100.0;
double addReplicaTime = totalStats.addReplicaTime / size;
double addReplicaPerc = addReplicaTime / totalTimer.totalTimeVal()
* 100.0;
double broadcastSOInvocationsTime = totalStats.broadcastSOInvocationsTime
/ size;
double broadcastSOInvocationsPerc = broadcastSOInvocationsTime
/ totalTimer.totalTimeVal() * 100;
double handleSOInvocationsTime = totalStats.handleSOInvocationsTime
/ size;
double handleSOInvocationsPerc = handleSOInvocationsTime
/ totalTimer.totalTimeVal() * 100;
double soTransferTime = totalStats.soTransferTime / size;
double soTransferPerc = soTransferTime / totalTimer.totalTimeVal()
* 100;
double soSerializationTime = totalStats.soSerializationTime / size;
double soSerializationPerc = soSerializationTime
/ totalTimer.totalTimeVal() * 100;
double soDeserializationTime = totalStats.soDeserializationTime / size;
double soDeserializationPerc = soDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double totalOverhead = abortTime
+ tupleTime
+ handleTupleTime
+ tupleWaitTime
+ pollTime
+ tableUpdateTime
+ tableLookupTime
+ tableHandleUpdateTime
+ tableHandleLookupTime
+ handleSOInvocationsTime
+ broadcastSOInvocationsTime
+ soTransferTime
+ (totalStats.stealTime + totalStats.handleStealTime
+ totalStats.returnRecordReadTime + totalStats.returnRecordWriteTime)
/ size;
double totalPerc = totalOverhead / totalTimer.totalTimeVal() * 100.0;
double appTime = totalTimer.totalTimeVal() - totalOverhead;
if (appTime < 0.0) {
appTime = 0.0;
}
double appPerc = appTime / totalTimer.totalTimeVal() * 100.0;
if (STEAL_TIMING) {
out.println("SATIN: LOAD_BALANCING_TIME: avg. per machine "
+ Timer.format(lbTime) + " (" + (lbPerc < 10 ? " " : "")
+ pf.format(lbPerc) + " %)");
out.println("SATIN: (DE)SERIALIZATION_TIME: avg. per machine "
+ Timer.format(serTime) + " (" + (serPerc < 10 ? " " : "")
+ pf.format(serPerc) + " %)");
}
if (ABORT_TIMING) {
out.println("SATIN: ABORT_TIME: avg. per machine "
+ Timer.format(abortTime) + " (" + (abortPerc < 10 ? " " : "")
+ pf.format(abortPerc) + " %)");
}
if (TUPLE_TIMING) {
out.println("SATIN: TUPLE_SPACE_BCAST_TIME: avg. per machine "
+ Timer.format(tupleTime) + " (" + (tuplePerc < 10 ? " " : "")
+ pf.format(tuplePerc) + " %)");
out.println("SATIN: TUPLE_SPACE_HANDLE_TIME: avg. per machine "
+ Timer.format(handleTupleTime) + " ("
+ (handleTuplePerc < 10 ? " " : "")
+ pf.format(handleTuplePerc) + " %)");
out.println("SATIN: TUPLE_SPACE_WAIT_TIME: avg. per machine "
+ Timer.format(tupleWaitTime) + " ("
+ (tupleWaitPerc < 10 ? " " : "") + pf.format(tupleWaitPerc)
+ " %)");
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL_TIME: avg. per machine "
+ Timer.format(pollTime) + " (" + (pollPerc < 10 ? " " : "")
+ pf.format(pollPerc) + " %)");
}
if (FAULT_TOLERANCE && GRT_TIMING) {
out.println("SATIN: GRT_UPDATE_TIME: avg. per machine "
+ Timer.format(tableUpdateTime) + " ("
+ pf.format(tableUpdatePerc) + " %)");
out.println("SATIN: GRT_LOOKUP_TIME: avg. per machine "
+ Timer.format(tableLookupTime) + " ("
+ pf.format(tableLookupPerc) + " %)");
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: avg. per machine "
+ Timer.format(tableHandleUpdateTime) + " ("
+ pf.format(tableHandleUpdatePerc) + " %)");
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: avg. per machine "
+ Timer.format(tableHandleLookupTime) + " ("
+ pf.format(tableHandleLookupPerc) + " %)");
out.println("SATIN: GRT_SERIALIZATION_TIME: avg. per machine "
+ Timer.format(tableSerializationTime) + " ("
+ pf.format(tableSerializationPerc) + " %)");
out.println("SATIN: GRT_DESERIALIZATION_TIME: avg. per machine "
+ Timer.format(tableDeserializationTime) + " ("
+ pf.format(tableDeserializationPerc) + " %)");
}
if (FAULT_TOLERANCE && CRASH_TIMING) {
out.println("SATIN: CRASH_HANDLING_TIME: avg. per machine "
+ Timer.format(crashHandlingTime) + " ("
+ pf.format(crashHandlingPerc) + " %)");
}
if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) {
out.println("SATIN: ADD_REPLICA_TIME: avg. per machine "
+ Timer.format(addReplicaTime) + " ("
+ pf.format(addReplicaPerc) + " %)");
}
if (SHARED_OBJECTS && SO_TIMING) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: avg. per machine "
+ Timer.format(broadcastSOInvocationsTime) + " ( "
+ pf.format(broadcastSOInvocationsPerc) + " %)");
out.println("SATIN: HANDLE_SO_INVOCATIONS: avg. per machine "
+ Timer.format(handleSOInvocationsTime) + " ( "
+ pf.format(handleSOInvocationsPerc) + " %)");
out.println("SATIN: SO_TRANSFERS: avg. per machine "
+ Timer.format(soTransferTime) + " ( "
+ pf.format(soTransferPerc) + " %)");
out.println("SATIN: SO_SERIALIZATION: avg. per machine "
+ Timer.format(soSerializationTime) + " ( "
+ pf.format(soSerializationPerc) + " %)");
out.println("SATIN: SO_DESERIALIZATION: avg. per machine "
+ Timer.format(soDeserializationTime) + " ( "
+ pf.format(soDeserializationPerc) + " %)");
}
out.println("\nSATIN: TOTAL_PARALLEL_OVERHEAD: avg. per machine "
+ Timer.format(totalOverhead) + " (" + (totalPerc < 10 ? " " : "")
+ pf.format(totalPerc) + " %)");
out.println("SATIN: USEFUL_APP_TIME: avg. per machine "
+ Timer.format(appTime) + " (" + (appPerc < 10 ? " " : "")
+ pf.format(appPerc) + " %)");
}
|
diff --git a/src/highlevelui/lcdui/reference/classes/javax/microedition/lcdui/DateField.java b/src/highlevelui/lcdui/reference/classes/javax/microedition/lcdui/DateField.java
index 22180ed7..dc5e89af 100644
--- a/src/highlevelui/lcdui/reference/classes/javax/microedition/lcdui/DateField.java
+++ b/src/highlevelui/lcdui/reference/classes/javax/microedition/lcdui/DateField.java
@@ -1,356 +1,355 @@
/*
*
*
* Copyright 1990-2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* 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 version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package javax.microedition.lcdui;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
/**
* A <code>DateField</code> is an editable component for presenting
* date and time (calendar)
* information that may be placed into a <code>Form</code>. Value for
* this field can be
* initially set or left unset. If value is not set then the UI for the field
* shows this clearly. The field value for "not initialized
* state" is not valid
* value and <code>getDate()</code> for this state returns <code>null</code>.
* <p>
* Instance of a <code>DateField</code> can be configured to accept
* date or time information
* or both of them. This input mode configuration is done by
* <code>DATE</code>, <code>TIME</code> or
* <code>DATE_TIME</code> static fields of this
* class. <code>DATE</code> input mode allows to set only
* date information and <code>TIME</code> only time information
* (hours, minutes). <code>DATE_TIME</code>
* allows to set both clock time and date values.
* <p>
* In <code>TIME</code> input mode the date components of
* <code>Date</code> object
* must be set to the "zero epoch" value of January 1, 1970.
* <p>
* Calendar calculations in this field are based on default locale and defined
* time zone. Because of the calculations and different input modes date object
* may not contain same millisecond value when set to this field and get back
* from this field.
* @since MIDP 1.0
*/
public class DateField extends Item {
/**
* Input mode for date information (day, month, year). With this mode this
* <code>DateField</code> presents and allows only to modify date
* value. The time
* information of date object is ignored.
*
* <P>Value <code>1</code> is assigned to <code>DATE</code>.</P>
*/
public static final int DATE = 1;
/**
* Input mode for time information (hours and minutes). With this mode this
* <code>DateField</code> presents and allows only to modify
* time. The date components
* should be set to the "zero epoch" value of January 1, 1970 and
* should not be accessed.
*
* <P>Value <code>2</code> is assigned to <code>TIME</code>.</P>
*/
public static final int TIME = 2;
/**
* Input mode for date (day, month, year) and time (minutes, hours)
* information. With this mode this <code>DateField</code>
* presents and allows to modify
* both time and date information.
*
* <P>Value <code>3</code> is assigned to <code>DATE_TIME</code>.</P>
*/
public static final int DATE_TIME = 3;
/**
* Creates a <code>DateField</code> object with the specified
* label and mode. This call
* is identical to <code>DateField(label, mode, null)</code>.
*
* @param label item label
* @param mode the input mode, one of <code>DATE</code>, <code>TIME</code>
* or <code>DATE_TIME</code>
* @throws IllegalArgumentException if the input <code>mode's</code>
* value is invalid
*/
public DateField(String label, int mode) {
this(label, mode, null);
}
/**
* Creates a date field in which calendar calculations are based
* on specific
* <code>TimeZone</code> object and the default calendaring system for the
* current locale.
* The value of the <code>DateField</code> is initially in the
* "uninitialized" state.
* If <code>timeZone</code> is <code>null</code>, the system's
* default time zone is used.
*
* @param label item label
* @param mode the input mode, one of <code>DATE</code>, <code>TIME</code>
* or <code>DATE_TIME</code>
* @param timeZone a specific time zone, or <code>null</code> for the
* default time zone
* @throws IllegalArgumentException if the input <code>mode's</code> value
* is invalid
*/
public DateField(String label, int mode, java.util.TimeZone timeZone) {
super(label);
synchronized (Display.LCDUILock) {
if ((mode != DATE) && (mode != TIME) && (mode != DATE_TIME)) {
throw new IllegalArgumentException("Invalid input mode");
}
this.mode = mode;
if (timeZone == null) {
timeZone = TimeZone.getDefault();
}
this.currentDate = Calendar.getInstance(timeZone);
itemLF = dateFieldLF = LFFactory.getFactory().getDateFieldLF(this);
} // synchronized
}
/**
* Returns date value of this field. Returned value is
* <code>null</code> if field
* value is
* not initialized. The date object is constructed according the rules of
* locale specific calendaring system and defined time zone.
*
* In <code>TIME</code> mode field the date components are set to
* the "zero
* epoch" value of January 1, 1970. If a date object that presents
* time beyond one day from this "zero epoch" then this field
* is in "not
* initialized" state and this method returns <code>null</code>.
*
* In <code>DATE</code> mode field the time component of the calendar is
* set to zero when constructing the date object.
*
* @return date object representing time or date depending on input mode
* @see #setDate
*/
public java.util.Date getDate() {
synchronized (Display.LCDUILock) {
// NOTE:
// defensive copy of the Date object is necessary
// because CLDC's Calendar returns a reference to an internal,
// shared Date object. See bugID: 4479408.
// original:
// return (initialized ?
// new java.util.Date(currentDate.getTime().getTime()) : null);
if (initialized) {
java.util.Date retDate = dateFieldLF.lGetDate();
if (retDate == null) {
return new java.util.Date(currentDate.getTime().getTime());
} else {
return retDate;
}
}
return null;
} // synchronized
}
/**
* Sets a new value for this field. <code>null</code> can be
* passed to set the field
* state to "not initialized" state. The input mode of
* this field defines
* what components of passed <code>Date</code> object is used.<p>
*
* In <code>TIME</code> input mode the date components must be set
* to the "zero
* epoch" value of January 1, 1970. If a date object that presents
* time
* beyond one day then this field is in "not initialized" state.
* In <code>TIME</code> input mode the date component of
* <code>Date</code> object is ignored and time
* component is used to precision of minutes.<p>
*
* In <code>DATE</code> input mode the time component of
* <code>Date</code> object is ignored.<p>
*
* In <code>DATE_TIME</code> input mode the date and time
* component of <code>Date</code> are used but
* only to precision of minutes.
*
* @param date new value for this field
* @see #getDate
*/
public void setDate(java.util.Date date) {
synchronized (Display.LCDUILock) {
setDateImpl(date);
dateFieldLF.lSetDate(date);
} // synchronized
}
/**
* Gets input mode for this date field. Valid input modes are
* <code>DATE</code>, <code>TIME</code> and <code>DATE_TIME</code>.
*
* @return input mode of this field
* @see #setInputMode
*/
public int getInputMode() {
// SYNC NOTE: return of atomic value, no locking necessary
return mode;
}
/**
* Set input mode for this date field. Valid input modes are
* <code>DATE</code>, <code>TIME</code> and <code>DATE_TIME</code>.
*
* @param mode the input mode, must be one of <code>DATE</code>,
* <code>TIME</code> or <code>DATE_TIME</code>
* @throws IllegalArgumentException if an invalid value is specified
* @see #getInputMode
*/
public void setInputMode(int mode) {
if ((mode != DATE) && (mode != TIME) && (mode != DATE_TIME)) {
throw new IllegalArgumentException("Invalid input mode");
}
synchronized (Display.LCDUILock) {
if (this.mode != mode) {
this.mode = mode;
// While the input mode is changed
// some irrelevant values for new mode could be lost.
// Currently that is allowed by the spec.
// So for TIME mode we make sure that time is set
// on a zero epoch date
// and for DATE mode we zero out hours and minutes
if (mode == TIME) {
currentDate.set(Calendar.YEAR, 1970);
currentDate.set(Calendar.MONTH, Calendar.JANUARY);
currentDate.set(Calendar.DATE, 1);
} else if (mode == DATE) {
currentDate.set(Calendar.HOUR, 0);
currentDate.set(Calendar.HOUR_OF_DAY, 0);
currentDate.set(Calendar.MINUTE, 0);
}
dateFieldLF.lSetInputMode(mode);
}
} // synchronized
}
// package private
/**
* Sets the date.
* @param date the date value to set to.
*/
void setDateImpl(java.util.Date date) {
if (date == null) {
initialized = false;
} else {
currentDate.setTime(date);
if (mode == TIME) {
- if (currentDate.getTime().getTime() >= 24*60*60*1000) {
- initialized = false;
+ if (currentDate.get(Calendar.YEAR) != 1970 ||
+ currentDate.get(Calendar.MONTH) != Calendar.JANUARY ||
+ currentDate.get (Calendar.DATE) != 1) {
+ initialized = false;
} else {
- currentDate.set(Calendar.YEAR, 1970);
- currentDate.set(Calendar.MONTH, Calendar.JANUARY);
- currentDate.set(Calendar.DATE, 1);
- initialized = true;
+ initialized = true;
}
} else {
// Currently spec does not prohibit from losing
// irrelevant for that mode information
// so we always zero out hours and minutes
// NOTE: the specification doesn't prohibit
// the loss of information irrelevant to
// the current input mode, so we always zero out the
// hours and minutes.
if (mode == DATE) {
currentDate.set(Calendar.HOUR, 0);
currentDate.set(Calendar.HOUR_OF_DAY, 0);
currentDate.set(Calendar.MINUTE, 0);
}
initialized = true;
}
// always ignore seconds and milliseconds
currentDate.set(Calendar.SECOND, 0);
currentDate.set(Calendar.MILLISECOND, 0);
}
}
/**
* Return whether the Item takes user input focus.
*
* @return Always return <code>true</code>
*/
boolean acceptFocus() {
return true;
}
/**
* The look&feel associated with this DateField.
* Set in the constructor.
*/
DateFieldLF dateFieldLF; // = null
/**
* A flag indicating the initialization state of this DateField
*/
boolean initialized; // = false;
/**
* The mode of this DateField
*/
int mode;
/**
* The last saved date.
* This is used for making the last saved date bold.
*/
Calendar currentDate;
}
| false | true | void setDateImpl(java.util.Date date) {
if (date == null) {
initialized = false;
} else {
currentDate.setTime(date);
if (mode == TIME) {
if (currentDate.getTime().getTime() >= 24*60*60*1000) {
initialized = false;
} else {
currentDate.set(Calendar.YEAR, 1970);
currentDate.set(Calendar.MONTH, Calendar.JANUARY);
currentDate.set(Calendar.DATE, 1);
initialized = true;
}
} else {
// Currently spec does not prohibit from losing
// irrelevant for that mode information
// so we always zero out hours and minutes
// NOTE: the specification doesn't prohibit
// the loss of information irrelevant to
// the current input mode, so we always zero out the
// hours and minutes.
if (mode == DATE) {
currentDate.set(Calendar.HOUR, 0);
currentDate.set(Calendar.HOUR_OF_DAY, 0);
currentDate.set(Calendar.MINUTE, 0);
}
initialized = true;
}
// always ignore seconds and milliseconds
currentDate.set(Calendar.SECOND, 0);
currentDate.set(Calendar.MILLISECOND, 0);
}
}
| void setDateImpl(java.util.Date date) {
if (date == null) {
initialized = false;
} else {
currentDate.setTime(date);
if (mode == TIME) {
if (currentDate.get(Calendar.YEAR) != 1970 ||
currentDate.get(Calendar.MONTH) != Calendar.JANUARY ||
currentDate.get (Calendar.DATE) != 1) {
initialized = false;
} else {
initialized = true;
}
} else {
// Currently spec does not prohibit from losing
// irrelevant for that mode information
// so we always zero out hours and minutes
// NOTE: the specification doesn't prohibit
// the loss of information irrelevant to
// the current input mode, so we always zero out the
// hours and minutes.
if (mode == DATE) {
currentDate.set(Calendar.HOUR, 0);
currentDate.set(Calendar.HOUR_OF_DAY, 0);
currentDate.set(Calendar.MINUTE, 0);
}
initialized = true;
}
// always ignore seconds and milliseconds
currentDate.set(Calendar.SECOND, 0);
currentDate.set(Calendar.MILLISECOND, 0);
}
}
|
diff --git a/samples/jaxp/SourceValidator.java b/samples/jaxp/SourceValidator.java
index ede7fd02..8f72857f 100644
--- a/samples/jaxp/SourceValidator.java
+++ b/samples/jaxp/SourceValidator.java
@@ -1,548 +1,549 @@
/*
* Copyright 2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jaxp;
import java.io.PrintWriter;
import java.util.Vector;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.w3c.dom.Document;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* <p>A sample demonstrating how to use the JAXP 1.3 Validation API
* to create a validator and use the validator to validate input
* from SAX, DOM or a stream. The output of this program shows the
* time spent executing the Validator.validate(Source) method.</p>
*
* <p>This class is useful as a "poor-man's" performance tester to
* compare the speed of various JAXP 1.3 validators with different
* input sources. However, it is important to note that the first
* validation time of a validator will include both VM class load time
* and validator initialization that would not be present in subsequent
* validations with the same document. Also note that when the source for
* validation is SAX or a stream, the validation time will also include
* the time to parse the document, whereas the DOM validation is
* completely in memory.</p>
*
* <p><strong>Note:</strong> The results produced by this program
* should never be accepted as true performance measurements.</p>
*
* @author Michael Glavassevich, IBM
*
* @version $Id$
*/
public class SourceValidator
implements ErrorHandler {
//
// Constants
//
// feature ids
/** Schema full checking feature id (http://apache.org/xml/features/validation/schema-full-checking). */
protected static final String SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking";
/** Honour all schema locations feature id (http://apache.org/xml/features/honour-all-schemaLocations). */
protected static final String HONOUR_ALL_SCHEMA_LOCATIONS_ID = "http://apache.org/xml/features/honour-all-schemaLocations";
/** Validate schema annotations feature id (http://apache.org/xml/features/validate-annotations) */
protected static final String VALIDATE_ANNOTATIONS_ID = "http://apache.org/xml/features/validate-annotations";
/** Generate synthetic schema annotations feature id (http://apache.org/xml/features/generate-synthetic-annotations). */
protected static final String GENERATE_SYNTHETIC_ANNOTATIONS_ID = "http://apache.org/xml/features/generate-synthetic-annotations";
// default settings
/** Default repetition (1). */
protected static final int DEFAULT_REPETITION = 1;
/** Default validation source. */
protected static final String DEFAULT_VALIDATION_SOURCE = "sax";
/** Default schema full checking support (false). */
protected static final boolean DEFAULT_SCHEMA_FULL_CHECKING = false;
/** Default honour all schema locations (false). */
protected static final boolean DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS = false;
/** Default validate schema annotations (false). */
protected static final boolean DEFAULT_VALIDATE_ANNOTATIONS = false;
/** Default generate synthetic schema annotations (false). */
protected static final boolean DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS = false;
/** Default memory usage report (false). */
protected static final boolean DEFAULT_MEMORY_USAGE = false;
//
// Data
//
protected PrintWriter fOut = new PrintWriter(System.out);
//
// Constructors
//
/** Default constructor. */
public SourceValidator() {
} // <init>()
//
// Public methods
//
public void validate(Validator validator,
Source source, String systemId,
int repetitions, boolean memoryUsage) {
try {
long timeBefore = System.currentTimeMillis();
long memoryBefore = Runtime.getRuntime().freeMemory();
for (int j = 0; j < repetitions; ++j) {
validator.validate(source);
}
long memoryAfter = Runtime.getRuntime().freeMemory();
long timeAfter = System.currentTimeMillis();
long time = timeAfter - timeBefore;
long memory = memoryUsage
? memoryBefore - memoryAfter : Long.MIN_VALUE;
printResults(fOut, systemId, time, memory, repetitions);
}
catch (SAXParseException e) {
// ignore
}
catch (Exception e) {
System.err.println("error: Parse error occurred - "+e.getMessage());
Exception se = e;
if (e instanceof SAXException) {
se = ((SAXException)e).getException();
}
if (se != null)
se.printStackTrace(System.err);
else
e.printStackTrace(System.err);
}
} // validate(Validator,Source,String,int,boolean)
/** Prints the results. */
public void printResults(PrintWriter out, String uri, long time,
long memory, int repetition) {
// filename.xml: 631 ms
out.print(uri);
out.print(": ");
if (repetition == 1) {
out.print(time);
}
else {
out.print(time);
out.print('/');
out.print(repetition);
out.print('=');
out.print(((float)time)/repetition);
}
out.print(" ms");
if (memory != Long.MIN_VALUE) {
out.print(", ");
out.print(memory);
out.print(" bytes");
}
out.println();
out.flush();
} // printResults(PrintWriter,String,long,long,int)
//
// ErrorHandler methods
//
/** Warning. */
public void warning(SAXParseException ex) throws SAXException {
printError("Warning", ex);
} // warning(SAXParseException)
/** Error. */
public void error(SAXParseException ex) throws SAXException {
printError("Error", ex);
} // error(SAXParseException)
/** Fatal error. */
public void fatalError(SAXParseException ex) throws SAXException {
printError("Fatal Error", ex);
throw ex;
} // fatalError(SAXParseException)
//
// Protected methods
//
/** Prints the error message. */
protected void printError(String type, SAXParseException ex) {
System.err.print("[");
System.err.print(type);
System.err.print("] ");
String systemId = ex.getSystemId();
if (systemId != null) {
int index = systemId.lastIndexOf('/');
if (index != -1)
systemId = systemId.substring(index + 1);
System.err.print(systemId);
}
System.err.print(':');
System.err.print(ex.getLineNumber());
System.err.print(':');
System.err.print(ex.getColumnNumber());
System.err.print(": ");
System.err.print(ex.getMessage());
System.err.println();
System.err.flush();
} // printError(String,SAXParseException)
//
// MAIN
//
/** Main program entry point. */
public static void main (String [] argv) {
// is there anything to do?
if (argv.length == 0) {
printUsage();
System.exit(1);
}
// variables
Vector schemas = null;
Vector instances = null;
int repetition = DEFAULT_REPETITION;
String validationSource = DEFAULT_VALIDATION_SOURCE;
boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;
boolean memoryUsage = DEFAULT_MEMORY_USAGE;
// process arguments
for (int i = 0; i < argv.length; ++i) {
String arg = argv[i];
if (arg.startsWith("-")) {
String option = arg.substring(1);
if (option.equals("x")) {
if (++i == argv.length) {
System.err.println("error: Missing argument to -x option.");
continue;
}
String number = argv[i];
try {
int value = Integer.parseInt(number);
if (value < 1) {
System.err.println("error: Repetition must be at least 1.");
continue;
}
repetition = value;
}
catch (NumberFormatException e) {
System.err.println("error: invalid number ("+number+").");
}
continue;
}
if (arg.equals("-a")) {
// process -a: schema documents
if (schemas == null) {
schemas = new Vector();
}
while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
schemas.add(arg);
++i;
}
continue;
}
if (arg.equals("-i")) {
// process -i: instance documents
if (instances == null) {
instances = new Vector();
}
while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
instances.add(arg);
++i;
}
continue;
}
if (arg.equals("-vs")) {
if (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
if (arg.equals("sax") || arg.equals("dom") || arg.equals("stream")) {
validationSource = arg;
}
else {
System.err.println("error: unknown source type ("+arg+").");
}
}
continue;
}
if (option.equalsIgnoreCase("f")) {
schemaFullChecking = option.equals("f");
continue;
}
if (option.equalsIgnoreCase("hs")) {
honourAllSchemaLocations = option.equals("hs");
continue;
}
if (option.equalsIgnoreCase("va")) {
validateAnnotations = option.equals("va");
continue;
}
if (option.equalsIgnoreCase("ga")) {
generateSyntheticAnnotations = option.equals("ga");
continue;
}
if (option.equalsIgnoreCase("m")) {
memoryUsage = option.equals("m");
continue;
}
if (option.equals("h")) {
printUsage();
continue;
}
System.err.println("error: unknown option ("+option+").");
continue;
}
}
try {
// Create new instance of SourceValidator.
SourceValidator sourceValidator = new SourceValidator();
// Create SchemaFactory and configure
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
factory.setErrorHandler(sourceValidator);
try {
factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: SchemaFactory does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: SchemaFactory does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
}
try {
factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: SchemaFactory does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: SchemaFactory does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
}
try {
factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: SchemaFactory does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: SchemaFactory does not support feature ("+VALIDATE_ANNOTATIONS_ID+")");
}
try {
factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: SchemaFactory does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: SchemaFactory does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
}
// Build Schema from sources
Schema schema;
if (schemas != null && schemas.size() > 0) {
final int length = schemas.size();
StreamSource[] sources = new StreamSource[length];
for (int j = 0; j < length; ++j) {
sources[j] = new StreamSource((String) schemas.elementAt(j));
}
schema = factory.newSchema(sources);
}
else {
schema = factory.newSchema();
}
// Setup validator and input source.
Validator validator = schema.newValidator();
validator.setErrorHandler(sourceValidator);
try {
validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: Validator does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: Validator does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
}
try {
validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: Validator does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: Validator does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
}
try {
validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: Validator does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: Validator does not support feature ("+VALIDATE_ANNOTATIONS_ID+")");
}
try {
validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: Validator does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: Validator does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
}
// Validate instance documents
if (instances != null && instances.size() > 0) {
final int length = instances.size();
if (validationSource.equals("sax")) {
// SAXSource
XMLReader reader = XMLReaderFactory.createXMLReader();
for (int j = 0; j < length; ++j) {
String systemId = (String) instances.elementAt(j);
SAXSource source = new SAXSource(reader, new InputSource(systemId));
sourceValidator.validate(validator, source, systemId, repetition, memoryUsage);
}
}
else if (validationSource.equals("dom")) {
// DOMSource
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
+ db.setErrorHandler(sourceValidator);
for (int j = 0; j < length; ++j) {
String systemId = (String) instances.elementAt(j);
Document doc = db.parse(systemId);
DOMSource source = new DOMSource(doc);
source.setSystemId(systemId);
sourceValidator.validate(validator, source, systemId, repetition, memoryUsage);
}
}
else {
// StreamSource
for (int j = 0; j < length; ++j) {
String systemId = (String) instances.elementAt(j);
StreamSource source = new StreamSource(systemId);
sourceValidator.validate(validator, source, systemId, repetition, memoryUsage);
}
}
}
}
catch (SAXParseException e) {
// ignore
}
catch (Exception e) {
System.err.println("error: Parse error occurred - "+e.getMessage());
if (e instanceof SAXException) {
Exception nested = ((SAXException)e).getException();
if (nested != null) {
e = nested;
}
}
e.printStackTrace(System.err);
}
} // main(String[])
//
// Private static methods
//
/** Prints the usage. */
private static void printUsage() {
System.err.println("usage: java jaxp.SourceValidator (options) ...");
System.err.println();
System.err.println("options:");
System.err.println(" -x number Select number of repetitions.");
System.err.println(" -a uri ... Provide a list of schema documents");
System.err.println(" -i uri ... Provide a list of instance documents to validate");
System.err.println(" -vs source Select validation source (sax|dom|stream)");
System.err.println(" -f | -F Turn on/off Schema full checking.");
System.err.println(" NOTE: Not supported by all schema factories and validators.");
System.err.println(" -hs | -HS Turn on/off honouring of all schema locations.");
System.err.println(" NOTE: Not supported by all schema factories and validators.");
System.err.println(" -va | -VA Turn on/off validation of schema annotations.");
System.err.println(" NOTE: Not supported by all schema factories and validators.");
System.err.println(" -ga | -GA Turn on/off generation of synthetic schema annotations.");
System.err.println(" NOTE: Not supported by all schema factories and validators.");
System.err.println(" -m | -M Turn on/off memory usage report");
System.err.println(" -h This help screen.");
System.err.println();
System.err.println("defaults:");
System.err.println(" Repetition: " + DEFAULT_REPETITION);
System.err.println(" Validation source: " + DEFAULT_VALIDATION_SOURCE);
System.err.print(" Schema full checking: ");
System.err.println(DEFAULT_SCHEMA_FULL_CHECKING ? "on" : "off");
System.err.print(" Honour all schema locations: ");
System.err.println(DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS ? "on" : "off");
System.err.print(" Validate annotations: ");
System.err.println(DEFAULT_VALIDATE_ANNOTATIONS ? "on" : "off");
System.err.print(" Generate synthetic annotations: ");
System.err.println(DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS ? "on" : "off");
System.err.print(" Memory: ");
System.err.println(DEFAULT_MEMORY_USAGE ? "on" : "off");
System.err.println();
System.err.println("notes:");
System.err.println(" The speed and memory results from this program should NOT be used as the");
System.err.println(" basis of parser performance comparison! Real analytical methods should be");
System.err.println(" used. For better results, perform multiple document validations within the");
System.err.println(" same virtual machine to remove class loading from parse time and memory usage.");
} // printUsage()
} // class SourceValidator
| true | true | public static void main (String [] argv) {
// is there anything to do?
if (argv.length == 0) {
printUsage();
System.exit(1);
}
// variables
Vector schemas = null;
Vector instances = null;
int repetition = DEFAULT_REPETITION;
String validationSource = DEFAULT_VALIDATION_SOURCE;
boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;
boolean memoryUsage = DEFAULT_MEMORY_USAGE;
// process arguments
for (int i = 0; i < argv.length; ++i) {
String arg = argv[i];
if (arg.startsWith("-")) {
String option = arg.substring(1);
if (option.equals("x")) {
if (++i == argv.length) {
System.err.println("error: Missing argument to -x option.");
continue;
}
String number = argv[i];
try {
int value = Integer.parseInt(number);
if (value < 1) {
System.err.println("error: Repetition must be at least 1.");
continue;
}
repetition = value;
}
catch (NumberFormatException e) {
System.err.println("error: invalid number ("+number+").");
}
continue;
}
if (arg.equals("-a")) {
// process -a: schema documents
if (schemas == null) {
schemas = new Vector();
}
while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
schemas.add(arg);
++i;
}
continue;
}
if (arg.equals("-i")) {
// process -i: instance documents
if (instances == null) {
instances = new Vector();
}
while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
instances.add(arg);
++i;
}
continue;
}
if (arg.equals("-vs")) {
if (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
if (arg.equals("sax") || arg.equals("dom") || arg.equals("stream")) {
validationSource = arg;
}
else {
System.err.println("error: unknown source type ("+arg+").");
}
}
continue;
}
if (option.equalsIgnoreCase("f")) {
schemaFullChecking = option.equals("f");
continue;
}
if (option.equalsIgnoreCase("hs")) {
honourAllSchemaLocations = option.equals("hs");
continue;
}
if (option.equalsIgnoreCase("va")) {
validateAnnotations = option.equals("va");
continue;
}
if (option.equalsIgnoreCase("ga")) {
generateSyntheticAnnotations = option.equals("ga");
continue;
}
if (option.equalsIgnoreCase("m")) {
memoryUsage = option.equals("m");
continue;
}
if (option.equals("h")) {
printUsage();
continue;
}
System.err.println("error: unknown option ("+option+").");
continue;
}
}
try {
// Create new instance of SourceValidator.
SourceValidator sourceValidator = new SourceValidator();
// Create SchemaFactory and configure
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
factory.setErrorHandler(sourceValidator);
try {
factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: SchemaFactory does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: SchemaFactory does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
}
try {
factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: SchemaFactory does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: SchemaFactory does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
}
try {
factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: SchemaFactory does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: SchemaFactory does not support feature ("+VALIDATE_ANNOTATIONS_ID+")");
}
try {
factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: SchemaFactory does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: SchemaFactory does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
}
// Build Schema from sources
Schema schema;
if (schemas != null && schemas.size() > 0) {
final int length = schemas.size();
StreamSource[] sources = new StreamSource[length];
for (int j = 0; j < length; ++j) {
sources[j] = new StreamSource((String) schemas.elementAt(j));
}
schema = factory.newSchema(sources);
}
else {
schema = factory.newSchema();
}
// Setup validator and input source.
Validator validator = schema.newValidator();
validator.setErrorHandler(sourceValidator);
try {
validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: Validator does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: Validator does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
}
try {
validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: Validator does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: Validator does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
}
try {
validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: Validator does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: Validator does not support feature ("+VALIDATE_ANNOTATIONS_ID+")");
}
try {
validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: Validator does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: Validator does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
}
// Validate instance documents
if (instances != null && instances.size() > 0) {
final int length = instances.size();
if (validationSource.equals("sax")) {
// SAXSource
XMLReader reader = XMLReaderFactory.createXMLReader();
for (int j = 0; j < length; ++j) {
String systemId = (String) instances.elementAt(j);
SAXSource source = new SAXSource(reader, new InputSource(systemId));
sourceValidator.validate(validator, source, systemId, repetition, memoryUsage);
}
}
else if (validationSource.equals("dom")) {
// DOMSource
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
for (int j = 0; j < length; ++j) {
String systemId = (String) instances.elementAt(j);
Document doc = db.parse(systemId);
DOMSource source = new DOMSource(doc);
source.setSystemId(systemId);
sourceValidator.validate(validator, source, systemId, repetition, memoryUsage);
}
}
else {
// StreamSource
for (int j = 0; j < length; ++j) {
String systemId = (String) instances.elementAt(j);
StreamSource source = new StreamSource(systemId);
sourceValidator.validate(validator, source, systemId, repetition, memoryUsage);
}
}
}
}
catch (SAXParseException e) {
// ignore
}
catch (Exception e) {
System.err.println("error: Parse error occurred - "+e.getMessage());
if (e instanceof SAXException) {
Exception nested = ((SAXException)e).getException();
if (nested != null) {
e = nested;
}
}
e.printStackTrace(System.err);
}
} // main(String[])
| public static void main (String [] argv) {
// is there anything to do?
if (argv.length == 0) {
printUsage();
System.exit(1);
}
// variables
Vector schemas = null;
Vector instances = null;
int repetition = DEFAULT_REPETITION;
String validationSource = DEFAULT_VALIDATION_SOURCE;
boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;
boolean memoryUsage = DEFAULT_MEMORY_USAGE;
// process arguments
for (int i = 0; i < argv.length; ++i) {
String arg = argv[i];
if (arg.startsWith("-")) {
String option = arg.substring(1);
if (option.equals("x")) {
if (++i == argv.length) {
System.err.println("error: Missing argument to -x option.");
continue;
}
String number = argv[i];
try {
int value = Integer.parseInt(number);
if (value < 1) {
System.err.println("error: Repetition must be at least 1.");
continue;
}
repetition = value;
}
catch (NumberFormatException e) {
System.err.println("error: invalid number ("+number+").");
}
continue;
}
if (arg.equals("-a")) {
// process -a: schema documents
if (schemas == null) {
schemas = new Vector();
}
while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
schemas.add(arg);
++i;
}
continue;
}
if (arg.equals("-i")) {
// process -i: instance documents
if (instances == null) {
instances = new Vector();
}
while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
instances.add(arg);
++i;
}
continue;
}
if (arg.equals("-vs")) {
if (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
if (arg.equals("sax") || arg.equals("dom") || arg.equals("stream")) {
validationSource = arg;
}
else {
System.err.println("error: unknown source type ("+arg+").");
}
}
continue;
}
if (option.equalsIgnoreCase("f")) {
schemaFullChecking = option.equals("f");
continue;
}
if (option.equalsIgnoreCase("hs")) {
honourAllSchemaLocations = option.equals("hs");
continue;
}
if (option.equalsIgnoreCase("va")) {
validateAnnotations = option.equals("va");
continue;
}
if (option.equalsIgnoreCase("ga")) {
generateSyntheticAnnotations = option.equals("ga");
continue;
}
if (option.equalsIgnoreCase("m")) {
memoryUsage = option.equals("m");
continue;
}
if (option.equals("h")) {
printUsage();
continue;
}
System.err.println("error: unknown option ("+option+").");
continue;
}
}
try {
// Create new instance of SourceValidator.
SourceValidator sourceValidator = new SourceValidator();
// Create SchemaFactory and configure
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
factory.setErrorHandler(sourceValidator);
try {
factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: SchemaFactory does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: SchemaFactory does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
}
try {
factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: SchemaFactory does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: SchemaFactory does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
}
try {
factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: SchemaFactory does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: SchemaFactory does not support feature ("+VALIDATE_ANNOTATIONS_ID+")");
}
try {
factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: SchemaFactory does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: SchemaFactory does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
}
// Build Schema from sources
Schema schema;
if (schemas != null && schemas.size() > 0) {
final int length = schemas.size();
StreamSource[] sources = new StreamSource[length];
for (int j = 0; j < length; ++j) {
sources[j] = new StreamSource((String) schemas.elementAt(j));
}
schema = factory.newSchema(sources);
}
else {
schema = factory.newSchema();
}
// Setup validator and input source.
Validator validator = schema.newValidator();
validator.setErrorHandler(sourceValidator);
try {
validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: Validator does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: Validator does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
}
try {
validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: Validator does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: Validator does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
}
try {
validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: Validator does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: Validator does not support feature ("+VALIDATE_ANNOTATIONS_ID+")");
}
try {
validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
}
catch (SAXNotRecognizedException e) {
System.err.println("warning: Validator does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
}
catch (SAXNotSupportedException e) {
System.err.println("warning: Validator does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")");
}
// Validate instance documents
if (instances != null && instances.size() > 0) {
final int length = instances.size();
if (validationSource.equals("sax")) {
// SAXSource
XMLReader reader = XMLReaderFactory.createXMLReader();
for (int j = 0; j < length; ++j) {
String systemId = (String) instances.elementAt(j);
SAXSource source = new SAXSource(reader, new InputSource(systemId));
sourceValidator.validate(validator, source, systemId, repetition, memoryUsage);
}
}
else if (validationSource.equals("dom")) {
// DOMSource
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
db.setErrorHandler(sourceValidator);
for (int j = 0; j < length; ++j) {
String systemId = (String) instances.elementAt(j);
Document doc = db.parse(systemId);
DOMSource source = new DOMSource(doc);
source.setSystemId(systemId);
sourceValidator.validate(validator, source, systemId, repetition, memoryUsage);
}
}
else {
// StreamSource
for (int j = 0; j < length; ++j) {
String systemId = (String) instances.elementAt(j);
StreamSource source = new StreamSource(systemId);
sourceValidator.validate(validator, source, systemId, repetition, memoryUsage);
}
}
}
}
catch (SAXParseException e) {
// ignore
}
catch (Exception e) {
System.err.println("error: Parse error occurred - "+e.getMessage());
if (e instanceof SAXException) {
Exception nested = ((SAXException)e).getException();
if (nested != null) {
e = nested;
}
}
e.printStackTrace(System.err);
}
} // main(String[])
|
diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/EntityIdentifier.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/EntityIdentifier.java
index 0c30c396b..2635bee75 100644
--- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/EntityIdentifier.java
+++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/EntityIdentifier.java
@@ -1,64 +1,64 @@
package org.mifosplatform.infrastructure.core.data;
import java.util.Map;
/**
* Represents the successful result of an REST API call.
*/
public class EntityIdentifier {
private Long entityId;
// TODO - Rename variable to commandId or taskId or something that shows
// this is the id of a command in a table/queue for processing.
@SuppressWarnings("unused")
private Long makerCheckerId;
private Map<String, Object> changes;
public static EntityIdentifier makerChecker(final Long makerCheckerId) {
return new EntityIdentifier(null, makerCheckerId, null);
}
public static EntityIdentifier makerChecker(final Long resourceId, final Long makerCheckerId) {
return new EntityIdentifier(resourceId, makerCheckerId, null);
}
public static EntityIdentifier withChanges(final Long resourceId, final Map<String, Object> changes) {
return new EntityIdentifier(resourceId, null, changes);
}
public static EntityIdentifier empty() {
return new EntityIdentifier(Long.valueOf(-1), null, null);
}
public EntityIdentifier() {
//
}
public EntityIdentifier(final Long entityId) {
this.entityId = entityId;
}
private EntityIdentifier(final Long entityId, final Long makerCheckerId, final Map<String, Object> changesOnly) {
this.entityId = entityId;
this.makerCheckerId = makerCheckerId;
this.changes = changesOnly;
}
public Long getEntityId() {
return this.entityId;
}
public void setEntityId(final Long entityId) {
this.entityId = entityId;
}
public Map<String, Object> getChanges() {
Map<String, Object> checkIfEmpty = null;
- if (!this.changes.isEmpty()) {
+ if (this.changes != null && !this.changes.isEmpty()) {
checkIfEmpty = this.changes;
}
return checkIfEmpty;
}
}
| true | true | public Map<String, Object> getChanges() {
Map<String, Object> checkIfEmpty = null;
if (!this.changes.isEmpty()) {
checkIfEmpty = this.changes;
}
return checkIfEmpty;
}
| public Map<String, Object> getChanges() {
Map<String, Object> checkIfEmpty = null;
if (this.changes != null && !this.changes.isEmpty()) {
checkIfEmpty = this.changes;
}
return checkIfEmpty;
}
|
diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/AbstractArtifactResolutionException.java b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/AbstractArtifactResolutionException.java
index fce822669..6cbeda22a 100644
--- a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/AbstractArtifactResolutionException.java
+++ b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/AbstractArtifactResolutionException.java
@@ -1,189 +1,189 @@
package org.apache.maven.artifact.resolver;
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.ArtifactRepository;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
/**
* Base class for artifact resolution exceptions.
*
* @author <a href="mailto:[email protected]">Brett Porter</a>
* @version $Id$
*/
public class AbstractArtifactResolutionException
extends Exception
{
private String groupId;
private String artifactId;
private String version;
private String type;
private List remoteRepositories;
private final String originalMessage;
private final String path;
static final String LS = System.getProperty( "line.separator" );
protected AbstractArtifactResolutionException( String message, String groupId, String artifactId, String version,
String type, List remoteRepositories, List path )
{
super( constructMessageBase( message, groupId, artifactId, version, type, remoteRepositories, path ) );
this.originalMessage = message;
this.groupId = groupId;
this.artifactId = artifactId;
this.type = type;
this.version = version;
this.remoteRepositories = remoteRepositories;
this.path = constructArtifactPath( path );
}
protected AbstractArtifactResolutionException( String message, String groupId, String artifactId, String version,
String type, List remoteRepositories, List path, Throwable t )
{
super( constructMessageBase( message, groupId, artifactId, version, type, remoteRepositories, path ), t );
this.originalMessage = message;
this.groupId = groupId;
this.artifactId = artifactId;
this.type = type;
this.version = version;
this.remoteRepositories = remoteRepositories;
this.path = constructArtifactPath( path );
}
protected AbstractArtifactResolutionException( String message, Artifact artifact )
{
this( message, artifact, null );
}
protected AbstractArtifactResolutionException( String message, Artifact artifact, List remoteRepositories )
{
this( message, artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getType(),
remoteRepositories, artifact.getDependencyTrail() );
}
protected AbstractArtifactResolutionException( String message, Artifact artifact, List remoteRepositories,
Throwable t )
{
this( message, artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getType(),
remoteRepositories, artifact.getDependencyTrail(), t );
}
public String getGroupId()
{
return groupId;
}
public String getArtifactId()
{
return artifactId;
}
public String getVersion()
{
return version;
}
public String getType()
{
return type;
}
public List getRemoteRepositories()
{
return remoteRepositories;
}
public String getOriginalMessage()
{
return originalMessage;
}
protected static String constructArtifactPath( List path )
{
StringBuffer sb = new StringBuffer();
if ( path != null )
{
sb.append( LS );
sb.append( "Path to dependency: " );
sb.append( LS );
int num = 1;
for ( Iterator i = path.iterator(); i.hasNext(); num++ )
{
sb.append( "\t" );
sb.append( num );
sb.append( ") " );
sb.append( i.next() );
sb.append( LS );
}
}
return sb.toString();
}
private static String constructMessageBase( String message, String groupId, String artifactId, String version,
String type, List remoteRepositories, List path )
{
StringBuffer sb = new StringBuffer();
sb.append( message );
sb.append( LS );
- sb.append( " " + groupId + ":" + artifactId + ":" + version + ":" + type );
+ sb.append( " " + groupId + ":" + artifactId + ":" + type + ":" + version );
sb.append( LS );
if ( remoteRepositories != null && !remoteRepositories.isEmpty() )
{
sb.append( LS );
sb.append( "from the specified remote repositories:" );
sb.append( LS + " " );
for ( Iterator i = new HashSet( remoteRepositories ).iterator(); i.hasNext(); )
{
ArtifactRepository remoteRepository = (ArtifactRepository) i.next();
sb.append( remoteRepository.getId() );
sb.append( " (" );
sb.append( remoteRepository.getUrl() );
sb.append( ")" );
if ( i.hasNext() )
{
sb.append( ",\n " );
}
}
}
sb.append( constructArtifactPath( path ) );
sb.append( LS );
return sb.toString();
}
public String getArtifactPath()
{
return path;
}
}
| true | true | private static String constructMessageBase( String message, String groupId, String artifactId, String version,
String type, List remoteRepositories, List path )
{
StringBuffer sb = new StringBuffer();
sb.append( message );
sb.append( LS );
sb.append( " " + groupId + ":" + artifactId + ":" + version + ":" + type );
sb.append( LS );
if ( remoteRepositories != null && !remoteRepositories.isEmpty() )
{
sb.append( LS );
sb.append( "from the specified remote repositories:" );
sb.append( LS + " " );
for ( Iterator i = new HashSet( remoteRepositories ).iterator(); i.hasNext(); )
{
ArtifactRepository remoteRepository = (ArtifactRepository) i.next();
sb.append( remoteRepository.getId() );
sb.append( " (" );
sb.append( remoteRepository.getUrl() );
sb.append( ")" );
if ( i.hasNext() )
{
sb.append( ",\n " );
}
}
}
sb.append( constructArtifactPath( path ) );
sb.append( LS );
return sb.toString();
}
| private static String constructMessageBase( String message, String groupId, String artifactId, String version,
String type, List remoteRepositories, List path )
{
StringBuffer sb = new StringBuffer();
sb.append( message );
sb.append( LS );
sb.append( " " + groupId + ":" + artifactId + ":" + type + ":" + version );
sb.append( LS );
if ( remoteRepositories != null && !remoteRepositories.isEmpty() )
{
sb.append( LS );
sb.append( "from the specified remote repositories:" );
sb.append( LS + " " );
for ( Iterator i = new HashSet( remoteRepositories ).iterator(); i.hasNext(); )
{
ArtifactRepository remoteRepository = (ArtifactRepository) i.next();
sb.append( remoteRepository.getId() );
sb.append( " (" );
sb.append( remoteRepository.getUrl() );
sb.append( ")" );
if ( i.hasNext() )
{
sb.append( ",\n " );
}
}
}
sb.append( constructArtifactPath( path ) );
sb.append( LS );
return sb.toString();
}
|
diff --git a/platform/src/main/java/org/rhq/plugins/platform/CpuComponent.java b/platform/src/main/java/org/rhq/plugins/platform/CpuComponent.java
index d5bc264748..f045126717 100644
--- a/platform/src/main/java/org/rhq/plugins/platform/CpuComponent.java
+++ b/platform/src/main/java/org/rhq/plugins/platform/CpuComponent.java
@@ -1,261 +1,262 @@
/*
* RHQ Management Platform
* Copyright (C) 2005-2008 Red Hat, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2, as
* published by the Free Software Foundation, and/or the GNU Lesser
* General Public License, version 2.1, also 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 and the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License
* and the GNU Lesser General Public License along with this program;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.rhq.plugins.platform;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.hyperic.sigar.Cpu;
import org.hyperic.sigar.CpuInfo;
import org.rhq.core.domain.measurement.AvailabilityType;
import org.rhq.core.domain.measurement.MeasurementDataNumeric;
import org.rhq.core.domain.measurement.MeasurementDataTrait;
import org.rhq.core.domain.measurement.MeasurementReport;
import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
import org.rhq.core.pluginapi.inventory.ResourceComponent;
import org.rhq.core.pluginapi.inventory.ResourceContext;
import org.rhq.core.pluginapi.measurement.MeasurementFacet;
import org.rhq.core.pluginapi.util.ObjectUtil;
import org.rhq.core.system.CpuInformation;
/**
* A Resource component representing a CPU core.
*/
public class CpuComponent implements ResourceComponent<PlatformComponent>, MeasurementFacet {
private CpuInformation cpuInformation = null;
private CpuEntry startCpuEntry = null;
/**
* A Map of cpu metric names to the last (Sigar) Cpu record used in calculations for that metric in getValues.
* This allows us to take proper cpu usage deltas for each metric, on different schedules. See
* RHQ-245 for why this is necessary.
*/
private Map<String, CpuEntry> cpuCache;
public void start(ResourceContext<PlatformComponent> resourceContext) {
if (resourceContext.getSystemInformation().isNative()) {
cpuInformation = resourceContext.getSystemInformation().getCpu(
Integer.parseInt(resourceContext.getResourceKey()));
cpuCache = new HashMap<String, CpuEntry>();
startCpuEntry = new CpuEntry(cpuInformation.getCpu());
}
return;
}
public void stop() {
return;
}
public AvailabilityType getAvailability() {
if (this.cpuInformation != null) {
this.cpuInformation.refresh();
return (this.cpuInformation.isEnabled()) ? AvailabilityType.UP : AvailabilityType.DOWN;
} else {
return AvailabilityType.UP;
}
}
public void getValues(MeasurementReport report, Set<MeasurementScheduleRequest> metrics) {
if (cpuInformation != null) {
cpuInformation.refresh();
Cpu cpu = null;
CpuEntry currentCpu = null;
CpuInfo cpuInfo = null; // this is probably gonna be used for traits only
for (MeasurementScheduleRequest request : metrics) {
String property = request.getName();
if (property.startsWith("Cpu.")) {
// Grab the current cpu info from SIGAR, only once for this cpu for all processed schedules
if (cpu == null) {
cpu = cpuInformation.getCpu();
}
property = property.substring(property.indexOf(".") + 1);
Long longValue = (Long) ObjectUtil.lookupAttributeProperty(cpu, property);
// A value of -1 indicates SIGAR does not support the metric on the Agent platform type.
if (longValue != null && longValue != -1) {
report.addData(new MeasurementDataNumeric(request, longValue.doubleValue()));
}
} else if (property.startsWith("CpuPerc.")) {
/*
* ! we no longer use the SIGAR CpuPerc object to report cpu percentage metrics. See
* ! RHQ-245 for an explanation. We now calculate our own percentages using
* ! the current raw cpu info from Sigar and the previous cpu numbers, cached per metric.
* ! This allows us to avoid the problem in RHQ-245 while handling perCpu-perMetric schedule
* ! granularity.
*/
// Grab the current cpu info from SIGAR, only once for this cpu for all processed schedules
if (null == cpu) {
cpu = cpuInformation.getCpu();
}
// Create a Cpu cacheEntry only once for this cpu for all processed schedules
if (null == currentCpu) {
currentCpu = new CpuEntry(cpu);
}
// Get the previous cpu numbers to be used for this metric and update the cache for the next go.
CpuEntry previousCpu = cpuCache.put(property, currentCpu);
previousCpu = (null == previousCpu) ? startCpuEntry : previousCpu;
- // if for some reason the delta time is excessive then toss
- // the metric, since it depends on a reasonable interval between
- // prev and curr. This can happen due to avail down or a newly
- // activated metric. Allow up to twice the metric interval.
+ // if for some reason the delta time is excessive then toss the metric, since it depends
+ // on a reasonable interval between prev and curr. This can happen due to avail down or a newly
+ // activated metric. Allow up to twice the metric interval. If the metric interval is
+ // 0 (for a live data request) then just use a 10 minute interval.
Number num = null;
long deltaTime = currentCpu.getTimestamp() - previousCpu.getTimestamp();
+ long metricInterval = (0 < request.getInterval()) ? request.getInterval() : 600000L;
- if (deltaTime <= (2 * request.getInterval())) {
+ if (deltaTime <= (2 * metricInterval)) {
// Use the same calculation that SIGAR uses to generate the percentages. The difference is that
// we use a safe "previous" cpu record.
num = getPercentage(previousCpu.getCpu(), cpu, property);
}
// Uncomment to see details about the calculations.
//System.out.println("\nCPU-" + cpuInformation.getCpuIndex() + " Interval="
// + ((currentCpu.getTimestamp() - previousCpu.getTimestamp()) / 1000) + " " + property + "="
// + num + "\n Prev=" + previousCpu + "\n Curr=" + currentCpu);
if (num != null) {
report.addData(new MeasurementDataNumeric(request, num.doubleValue()));
}
} else if (property.startsWith("CpuInfo.")) {
if (cpuInfo == null) {
cpuInfo = cpuInformation.getCpuInfo();
}
property = property.substring(property.indexOf(".") + 1);
Number num = ((Number) ObjectUtil.lookupAttributeProperty(cpuInfo, property));
if (num != null) {
report.addData(new MeasurementDataNumeric(request, num.doubleValue()));
}
} else if (property.startsWith("CpuTrait.")) {
if (cpuInfo == null) {
cpuInfo = cpuInformation.getCpuInfo();
}
property = property.substring(property.indexOf(".") + 1);
Object o = ObjectUtil.lookupAttributeProperty(cpuInfo, property);
if (o != null) {
String res;
if ("model".equals(property) || "vendor".equals(property)) {
res = (String) o;
} else {
res = String.valueOf(o);
}
report.addData(new MeasurementDataTrait(request, res));
}
}
}
}
return;
}
/**
* Calculate the percentage of CPU taken up by the requested cpu property (metric) for the interval
* defined by the prev and curr cpu numbers. This algorithm is taken from SIGAR. See
* http://svn.hyperic.org/projects/sigar/trunk/src/sigar_format.c ( sigar_cpu_perc_calculate() )
*/
private Number getPercentage(Cpu prev, Cpu curr, String property) {
Number result = 0.0;
double diff_user, diff_sys, diff_nice, diff_idle;
double diff_wait, diff_irq, diff_soft_irq, diff_stolen;
double diff_total;
diff_user = curr.getUser() - prev.getUser();
diff_sys = curr.getSys() - prev.getSys();
diff_nice = curr.getNice() - prev.getNice();
diff_idle = curr.getIdle() - prev.getIdle();
diff_wait = curr.getWait() - prev.getWait();
diff_irq = curr.getIrq() - prev.getIrq();
diff_soft_irq = curr.getSoftIrq() - prev.getSoftIrq();
diff_stolen = curr.getStolen() - prev.getStolen();
// It's not exactly clear to me what SIGAR is doing here. It may be to handle a rollover of
// the cumulative cpu usage numbers. If so, this code could maybe be improved to still
// determine the total usage.
diff_user = diff_user < 0 ? 0 : diff_user;
diff_sys = diff_sys < 0 ? 0 : diff_sys;
diff_nice = diff_nice < 0 ? 0 : diff_nice;
diff_idle = diff_idle < 0 ? 0 : diff_idle;
diff_wait = diff_wait < 0 ? 0 : diff_wait;
diff_irq = diff_irq < 0 ? 0 : diff_irq;
diff_soft_irq = diff_soft_irq < 0 ? 0 : diff_soft_irq;
diff_stolen = diff_stolen < 0 ? 0 : diff_stolen;
diff_total = diff_user + diff_sys + diff_nice + diff_idle + diff_wait + diff_irq + diff_soft_irq + diff_stolen;
property = property.substring(property.lastIndexOf(".") + 1, property.length());
if ("idle".equals(property)) {
result = diff_idle / diff_total;
} else if ("sys".equals(property)) {
result = diff_sys / diff_total;
} else if ("user".equals(property)) {
result = diff_user / diff_total;
} else if ("wait".equals(property)) {
result = diff_wait / diff_total;
} else if ("nice".equals(property)) {
result = diff_nice / diff_total;
} else if ("irq".equals(property)) {
result = diff_irq / diff_total;
} else if ("softIrq".equals(property)) {
result = diff_soft_irq / diff_total;
} else if ("stolen".equals(property)) {
result = diff_stolen / diff_total;
}
return result;
}
/**
* Just a private, immutable, utility class for associating a CPU and timestamp with the raw Cpu object from SIGAR.
*/
private class CpuEntry {
private Cpu cpu;
private long timestamp;
public CpuEntry(Cpu cpu) {
this.cpu = cpu;
this.timestamp = System.currentTimeMillis();
}
public Cpu getCpu() {
return cpu;
}
public long getTimestamp() {
return timestamp;
}
public String toString() {
return "CPU-" + cpuInformation.getCpuIndex() + "[" + new SimpleDateFormat("HH:mm:ss").format(timestamp)
+ "] = " + cpu;
}
}
}
| false | true | public void getValues(MeasurementReport report, Set<MeasurementScheduleRequest> metrics) {
if (cpuInformation != null) {
cpuInformation.refresh();
Cpu cpu = null;
CpuEntry currentCpu = null;
CpuInfo cpuInfo = null; // this is probably gonna be used for traits only
for (MeasurementScheduleRequest request : metrics) {
String property = request.getName();
if (property.startsWith("Cpu.")) {
// Grab the current cpu info from SIGAR, only once for this cpu for all processed schedules
if (cpu == null) {
cpu = cpuInformation.getCpu();
}
property = property.substring(property.indexOf(".") + 1);
Long longValue = (Long) ObjectUtil.lookupAttributeProperty(cpu, property);
// A value of -1 indicates SIGAR does not support the metric on the Agent platform type.
if (longValue != null && longValue != -1) {
report.addData(new MeasurementDataNumeric(request, longValue.doubleValue()));
}
} else if (property.startsWith("CpuPerc.")) {
/*
* ! we no longer use the SIGAR CpuPerc object to report cpu percentage metrics. See
* ! RHQ-245 for an explanation. We now calculate our own percentages using
* ! the current raw cpu info from Sigar and the previous cpu numbers, cached per metric.
* ! This allows us to avoid the problem in RHQ-245 while handling perCpu-perMetric schedule
* ! granularity.
*/
// Grab the current cpu info from SIGAR, only once for this cpu for all processed schedules
if (null == cpu) {
cpu = cpuInformation.getCpu();
}
// Create a Cpu cacheEntry only once for this cpu for all processed schedules
if (null == currentCpu) {
currentCpu = new CpuEntry(cpu);
}
// Get the previous cpu numbers to be used for this metric and update the cache for the next go.
CpuEntry previousCpu = cpuCache.put(property, currentCpu);
previousCpu = (null == previousCpu) ? startCpuEntry : previousCpu;
// if for some reason the delta time is excessive then toss
// the metric, since it depends on a reasonable interval between
// prev and curr. This can happen due to avail down or a newly
// activated metric. Allow up to twice the metric interval.
Number num = null;
long deltaTime = currentCpu.getTimestamp() - previousCpu.getTimestamp();
if (deltaTime <= (2 * request.getInterval())) {
// Use the same calculation that SIGAR uses to generate the percentages. The difference is that
// we use a safe "previous" cpu record.
num = getPercentage(previousCpu.getCpu(), cpu, property);
}
// Uncomment to see details about the calculations.
//System.out.println("\nCPU-" + cpuInformation.getCpuIndex() + " Interval="
// + ((currentCpu.getTimestamp() - previousCpu.getTimestamp()) / 1000) + " " + property + "="
// + num + "\n Prev=" + previousCpu + "\n Curr=" + currentCpu);
if (num != null) {
report.addData(new MeasurementDataNumeric(request, num.doubleValue()));
}
} else if (property.startsWith("CpuInfo.")) {
if (cpuInfo == null) {
cpuInfo = cpuInformation.getCpuInfo();
}
property = property.substring(property.indexOf(".") + 1);
Number num = ((Number) ObjectUtil.lookupAttributeProperty(cpuInfo, property));
if (num != null) {
report.addData(new MeasurementDataNumeric(request, num.doubleValue()));
}
} else if (property.startsWith("CpuTrait.")) {
if (cpuInfo == null) {
cpuInfo = cpuInformation.getCpuInfo();
}
property = property.substring(property.indexOf(".") + 1);
Object o = ObjectUtil.lookupAttributeProperty(cpuInfo, property);
if (o != null) {
String res;
if ("model".equals(property) || "vendor".equals(property)) {
res = (String) o;
} else {
res = String.valueOf(o);
}
report.addData(new MeasurementDataTrait(request, res));
}
}
}
}
return;
}
| public void getValues(MeasurementReport report, Set<MeasurementScheduleRequest> metrics) {
if (cpuInformation != null) {
cpuInformation.refresh();
Cpu cpu = null;
CpuEntry currentCpu = null;
CpuInfo cpuInfo = null; // this is probably gonna be used for traits only
for (MeasurementScheduleRequest request : metrics) {
String property = request.getName();
if (property.startsWith("Cpu.")) {
// Grab the current cpu info from SIGAR, only once for this cpu for all processed schedules
if (cpu == null) {
cpu = cpuInformation.getCpu();
}
property = property.substring(property.indexOf(".") + 1);
Long longValue = (Long) ObjectUtil.lookupAttributeProperty(cpu, property);
// A value of -1 indicates SIGAR does not support the metric on the Agent platform type.
if (longValue != null && longValue != -1) {
report.addData(new MeasurementDataNumeric(request, longValue.doubleValue()));
}
} else if (property.startsWith("CpuPerc.")) {
/*
* ! we no longer use the SIGAR CpuPerc object to report cpu percentage metrics. See
* ! RHQ-245 for an explanation. We now calculate our own percentages using
* ! the current raw cpu info from Sigar and the previous cpu numbers, cached per metric.
* ! This allows us to avoid the problem in RHQ-245 while handling perCpu-perMetric schedule
* ! granularity.
*/
// Grab the current cpu info from SIGAR, only once for this cpu for all processed schedules
if (null == cpu) {
cpu = cpuInformation.getCpu();
}
// Create a Cpu cacheEntry only once for this cpu for all processed schedules
if (null == currentCpu) {
currentCpu = new CpuEntry(cpu);
}
// Get the previous cpu numbers to be used for this metric and update the cache for the next go.
CpuEntry previousCpu = cpuCache.put(property, currentCpu);
previousCpu = (null == previousCpu) ? startCpuEntry : previousCpu;
// if for some reason the delta time is excessive then toss the metric, since it depends
// on a reasonable interval between prev and curr. This can happen due to avail down or a newly
// activated metric. Allow up to twice the metric interval. If the metric interval is
// 0 (for a live data request) then just use a 10 minute interval.
Number num = null;
long deltaTime = currentCpu.getTimestamp() - previousCpu.getTimestamp();
long metricInterval = (0 < request.getInterval()) ? request.getInterval() : 600000L;
if (deltaTime <= (2 * metricInterval)) {
// Use the same calculation that SIGAR uses to generate the percentages. The difference is that
// we use a safe "previous" cpu record.
num = getPercentage(previousCpu.getCpu(), cpu, property);
}
// Uncomment to see details about the calculations.
//System.out.println("\nCPU-" + cpuInformation.getCpuIndex() + " Interval="
// + ((currentCpu.getTimestamp() - previousCpu.getTimestamp()) / 1000) + " " + property + "="
// + num + "\n Prev=" + previousCpu + "\n Curr=" + currentCpu);
if (num != null) {
report.addData(new MeasurementDataNumeric(request, num.doubleValue()));
}
} else if (property.startsWith("CpuInfo.")) {
if (cpuInfo == null) {
cpuInfo = cpuInformation.getCpuInfo();
}
property = property.substring(property.indexOf(".") + 1);
Number num = ((Number) ObjectUtil.lookupAttributeProperty(cpuInfo, property));
if (num != null) {
report.addData(new MeasurementDataNumeric(request, num.doubleValue()));
}
} else if (property.startsWith("CpuTrait.")) {
if (cpuInfo == null) {
cpuInfo = cpuInformation.getCpuInfo();
}
property = property.substring(property.indexOf(".") + 1);
Object o = ObjectUtil.lookupAttributeProperty(cpuInfo, property);
if (o != null) {
String res;
if ("model".equals(property) || "vendor".equals(property)) {
res = (String) o;
} else {
res = String.valueOf(o);
}
report.addData(new MeasurementDataTrait(request, res));
}
}
}
}
return;
}
|
diff --git a/classes/com/sapienter/jbilling/server/order/OrderBL.java b/classes/com/sapienter/jbilling/server/order/OrderBL.java
index 3132dc88..248e6632 100644
--- a/classes/com/sapienter/jbilling/server/order/OrderBL.java
+++ b/classes/com/sapienter/jbilling/server/order/OrderBL.java
@@ -1,1052 +1,1052 @@
/*
The contents of this file are subject to the Jbilling 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.jbilling.com/JPL/
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 jbilling.
The Initial Developer of the Original Code is Emiliano Conde.
Portions created by Sapienter Billing Software Corp. are Copyright
(C) Sapienter Billing Software Corp. All Rights Reserved.
Contributor(s): ______________________________________.
*/
/*
* Created on 15-Mar-2003
*
* Copyright Sapienter Enterprise Software
*/
package com.sapienter.jbilling.server.order;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import javax.ejb.RemoveException;
import javax.naming.NamingException;
import org.apache.log4j.Logger;
import sun.jdbc.rowset.CachedRowSet;
import com.sapienter.jbilling.common.JNDILookup;
import com.sapienter.jbilling.common.SessionInternalError;
import com.sapienter.jbilling.common.Util;
import com.sapienter.jbilling.interfaces.EntityEntityLocal;
import com.sapienter.jbilling.interfaces.NotificationSessionLocal;
import com.sapienter.jbilling.interfaces.NotificationSessionLocalHome;
import com.sapienter.jbilling.interfaces.OrderEntityLocal;
import com.sapienter.jbilling.interfaces.OrderEntityLocalHome;
import com.sapienter.jbilling.interfaces.OrderLineEntityLocal;
import com.sapienter.jbilling.interfaces.OrderLineEntityLocalHome;
import com.sapienter.jbilling.interfaces.OrderLineTypeEntityLocal;
import com.sapienter.jbilling.interfaces.OrderLineTypeEntityLocalHome;
import com.sapienter.jbilling.interfaces.OrderPeriodEntityLocal;
import com.sapienter.jbilling.interfaces.OrderPeriodEntityLocalHome;
import com.sapienter.jbilling.server.entity.OrderDTO;
import com.sapienter.jbilling.server.item.ItemBL;
import com.sapienter.jbilling.server.item.ItemDTOEx;
import com.sapienter.jbilling.server.item.PromotionBL;
import com.sapienter.jbilling.server.list.ResultList;
import com.sapienter.jbilling.server.notification.MessageDTO;
import com.sapienter.jbilling.server.notification.NotificationBL;
import com.sapienter.jbilling.server.notification.NotificationNotFoundException;
import com.sapienter.jbilling.server.order.event.NewActiveUntilEvent;
import com.sapienter.jbilling.server.order.event.NewStatusEvent;
import com.sapienter.jbilling.server.pluggableTask.OrderProcessingTask;
import com.sapienter.jbilling.server.pluggableTask.PluggableTaskException;
import com.sapienter.jbilling.server.pluggableTask.PluggableTaskManager;
import com.sapienter.jbilling.server.pluggableTask.TaskException;
import com.sapienter.jbilling.server.process.ConfigurationBL;
import com.sapienter.jbilling.server.system.event.EventManager;
import com.sapienter.jbilling.server.user.ContactBL;
import com.sapienter.jbilling.server.user.EntityBL;
import com.sapienter.jbilling.server.user.UserBL;
import com.sapienter.jbilling.server.util.Constants;
import com.sapienter.jbilling.server.util.DTOFactory;
import com.sapienter.jbilling.server.util.EventLogger;
import com.sapienter.jbilling.server.util.PreferenceBL;
/**
* @author Emil
*/
public class OrderBL extends ResultList
implements OrderSQL {
private NewOrderDTO newOrder = null;
private JNDILookup EJBFactory = null;
private OrderEntityLocalHome orderHome = null;
private OrderEntityLocal order = null;
private OrderLineEntityLocalHome orderLineHome = null;
private OrderLineTypeEntityLocalHome orderLineTypeHome = null;
private OrderPeriodEntityLocalHome orderPeriodHome = null;
private Logger log = null;
private EventLogger eLogger = null;
public OrderBL(Integer orderId)
throws NamingException, FinderException {
init();
set(orderId);
}
public OrderBL() throws NamingException {
init();
}
public OrderBL (OrderEntityLocal order) {
try {
init();
} catch (NamingException e) {
throw new SessionInternalError(e);
}
this.order = order;
}
public OrderBL(NewOrderDTO order) throws NamingException {
newOrder = order;
init();
}
private void init() throws NamingException {
log = Logger.getLogger(OrderBL.class);
eLogger = EventLogger.getInstance();
EJBFactory = JNDILookup.getFactory(false);
orderHome = (OrderEntityLocalHome)
EJBFactory.lookUpLocalHome(
OrderEntityLocalHome.class,
OrderEntityLocalHome.JNDI_NAME);
orderLineHome = (OrderLineEntityLocalHome) EJBFactory.lookUpLocalHome(
OrderLineEntityLocalHome.class,
OrderLineEntityLocalHome.JNDI_NAME);
orderLineTypeHome = (OrderLineTypeEntityLocalHome)
EJBFactory.lookUpLocalHome(
OrderLineTypeEntityLocalHome.class,
OrderLineTypeEntityLocalHome.JNDI_NAME);
orderPeriodHome =
(OrderPeriodEntityLocalHome) EJBFactory.lookUpLocalHome(
OrderPeriodEntityLocalHome.class,
OrderPeriodEntityLocalHome.JNDI_NAME);
}
public OrderEntityLocal getEntity() {
return order;
}
public OrderEntityLocalHome getHome() {
return orderHome;
}
public OrderPeriodDTOEx getPeriod(Integer language, Integer id)
throws FinderException {
OrderPeriodEntityLocal period = orderPeriodHome.findByPrimaryKey(id);
OrderPeriodDTOEx dto = new OrderPeriodDTOEx();
dto.setDescription(period.getDescription(language));
dto.setEntityId(period.getEntityId());
dto.setId(period.getId());
dto.setUnitId(period.getUnitId());
dto.setValue(period.getValue());
return dto;
}
public void set(Integer id) throws FinderException {
order = orderHome.findByPrimaryKey(id);
}
public void set(OrderEntityLocal newOrder) {
order = newOrder;
}
public NewOrderDTO getNewOrderDTO() {
return newOrder;
}
public OrderWS getWS(Integer languageId)
throws FinderException, NamingException {
OrderWS retValue = new OrderWS(getDTO());
retValue.setPeriod(order.getPeriod().getId());
retValue.setPeriodStr(order.getPeriod().getDescription(languageId));
retValue.setBillingTypeStr(DTOFactory.getBillingTypeString(
order.getBillingTypeId(), languageId));
retValue.setUserId(order.getUser().getUserId());
Vector<OrderLineWS> lines = new Vector<OrderLineWS>();
for (Iterator it = order.getOrderLines().iterator(); it.hasNext();) {
OrderLineEntityLocal line = (OrderLineEntityLocal) it.next();
if (line.getDeleted().intValue() == 0) {
OrderLineWS lineWS = new OrderLineWS(DTOFactory.getOrderLineDTOEx(line));
lineWS.setTypeId(line.getType().getId());
lines.add(lineWS);
}
}
retValue.setOrderLines(new OrderLineWS[lines.size()]);
lines.toArray(retValue.getOrderLines());
return retValue;
}
public OrderDTO getDTO() {
return new OrderDTO(order.getId(), order.getBillingTypeId(),
order.getNotify(),
order.getActiveSince(), order.getActiveUntil(),
order.getCreateDate(), order.getNextBillableDay(),
order.getCreatedBy(), order.getStatusId(), order.getDeleted(),
order.getCurrencyId(), order.getLastNotified(),
order.getNotificationStep(), order.getDueDateUnitId(),
order.getDueDateValue(), order.getDfFm(),
order.getAnticipatePeriods(), order.getOwnInvoice(),
order.getNotesInInvoice(), order.getNotes());
}
public void setDTO(NewOrderDTO mOrder) {
newOrder = mOrder;
}
public void addItem(ItemDTOEx item, Integer quantity)
throws SessionInternalError {
// check if the item is already in the order
OrderLineDTOEx line =
(OrderLineDTOEx) newOrder.getOrderLine(item.getId());
BigDecimal additionAmount;
if (item.getPercentage() == null) {
additionAmount = new BigDecimal(item.getPrice().toString());
additionAmount = additionAmount.multiply(
new BigDecimal(quantity.toString()));
} else {
additionAmount = new BigDecimal(item.getPercentage().toString());
}
if (line == null) { // not yet there
Boolean editable = lookUpEditable(item.getOrderLineTypeId());
line = new OrderLineDTOEx(null, item.getId(), item.getDescription(),
new Float(additionAmount.floatValue()), quantity,
(item.getPercentage() == null) ? item.getPrice() :
item.getPercentage(),
new Integer(0), null, new Integer(0),
item.getOrderLineTypeId(), editable);
line.setItem(item);
newOrder.setOrderLine(item.getId(), line);
} else {
// the item is there, I just have to update the quantity
line.setQuantity(
new Integer(
line.getQuantity().intValue() + quantity.intValue()));
// and also the total amount for this order line
BigDecimal dec = new BigDecimal(line.getAmount().toString());
dec = dec.add(additionAmount);
line.setAmount(
new Float(dec.floatValue()));
}
}
public void deleteItem(Integer itemID) {
newOrder.removeOrderLine(itemID);
}
public void delete() {
for (Iterator it = order.getOrderLines().iterator(); it.hasNext();) {
OrderLineEntityLocal line = (OrderLineEntityLocal) it.next();
line.setDeleted(new Integer(1));
}
order.setDeleted(new Integer(1));
}
/**
* Method recalculate.
* Goes over the processing tasks configured in the database for this
* entity. The NewOrderDTO of this session is then modified.
*/
public void recalculate(Integer entityId) throws SessionInternalError {
log = Logger.getLogger(OrderBL.class);
log.debug("Processing and order for reviewing." + newOrder.getOrderLinesMap().size());
try {
PluggableTaskManager taskManager = new PluggableTaskManager(
entityId, Constants.PLUGGABLE_TASK_PROCESSING_ORDERS);
OrderProcessingTask task =
(OrderProcessingTask) taskManager.getNextClass();
while (task != null) {
task.doProcessing(newOrder);
task = (OrderProcessingTask) taskManager.getNextClass();
}
} catch (PluggableTaskException e) {
log.fatal("Problems handling order processing task.", e);
throw new SessionInternalError("Problems handling order " +
"processing task.");
} catch (TaskException e) {
log.fatal("Problems excecuting order processing task.", e);
throw new SessionInternalError("Problems executing order processing task.");
}
}
public Integer create(Integer entityId, Integer userAgentId,
NewOrderDTO orderDto) throws SessionInternalError {
Integer newOrderId = null;
try {
// if the order is a one-timer, force pre-paid to avoid any
// confusion
if (orderDto.getPeriod().equals(Constants.ORDER_PERIOD_ONCE)) {
orderDto.setBillingTypeId(Constants.ORDER_BILLING_PRE_PAID);
}
/*
* First create the order record
*/
// create the record
order = orderHome.create(entityId, orderDto.getPeriod(),
userAgentId, orderDto.getUserId(),
orderDto.getBillingTypeId(), orderDto.getCurrencyId());
order.setActiveUntil(orderDto.getActiveUntil());
order.setActiveSince(orderDto.getActiveSince());
order.setNotify(orderDto.getNotify());
order.setDueDateUnitId(orderDto.getDueDateUnitId());
order.setDueDateValue(orderDto.getDueDateValue());
order.setDfFm(orderDto.getDfFm());
order.setAnticipatePeriods(orderDto.getAnticipatePeriods());
order.setOwnInvoice(orderDto.getOwnInvoice());
order.setNotes(orderDto.getNotes());
order.setNotesInInvoice(orderDto.getNotesInInvoice());
// get the collection of lines to update the fk of the table
newOrderId = order.getId();
createLines(orderDto);
// update any promotion involved
updatePromotion(entityId, orderDto.getPromoCode());
} catch (Exception e) {
log.fatal("Create exception creating order entity bean", e);
throw new SessionInternalError(e);
}
return newOrderId;
}
public void update(Integer executorId, NewOrderDTO dto)
throws FinderException, CreateException {
// update first the order own fields
if (!Util.equal(order.getActiveUntil(), dto.getActiveUntil())) {
audit(executorId, order.getActiveUntil());
// this needs an event
NewActiveUntilEvent event = new NewActiveUntilEvent(
order.getId(), dto.getActiveUntil(),
order.getActiveUntil());
EventManager.process(event);
// update it
order.setActiveUntil(dto.getActiveUntil());
}
if (!Util.equal(order.getActiveSince(), dto.getActiveSince())) {
audit(executorId, order.getActiveSince());
order.setActiveSince(dto.getActiveSince());
}
setStatus(executorId, dto.getStatusId());
OrderPeriodEntityLocal period = orderPeriodHome.findByPrimaryKey(
dto.getPeriod());
if (order.getPeriod().getId().compareTo(period.getId()) != 0) {
audit(executorId, order.getPeriod().getId());
order.setPeriod(period);
}
order.setBillingTypeId(dto.getBillingTypeId());
order.setNotify(dto.getNotify());
order.setDueDateUnitId(dto.getDueDateUnitId());
order.setDueDateValue(dto.getDueDateValue());
order.setDfFm(dto.getDfFm());
order.setAnticipatePeriods(dto.getAnticipatePeriods());
order.setOwnInvoice(dto.getOwnInvoice());
order.setNotes(dto.getNotes());
order.setNotesInInvoice(dto.getNotesInInvoice());
// this one needs more to get updated
updateNextBillableDay(executorId, dto.getNextBillableDay());
OrderLineEntityLocal oldLine = null;
int nonDeletedLines = 0;
// Determine if the item of the order changes and, if it is,
// log a subscription change event.
log.info("Order lines: " + order.getOrderLines().size() + " --> new Order: "+
dto.getNumberOfLines().intValue());
if (dto.getNumberOfLines().intValue() == 1 &&
order.getOrderLines().size() >= 1) {
// This event needs to log the old item id and description, so
// it can only happen when updating orders with only one line.
for (Iterator i = order.getOrderLines().iterator(); i.hasNext();) {
// Check which order is not deleted.
OrderLineEntityLocal temp = (OrderLineEntityLocal)i.next();
if (temp.getDeleted() == 0) {
oldLine = temp;
nonDeletedLines++;
}
}
}
// now update this order's lines
// first, mark all the lines as deleted
for (Iterator it = order.getOrderLines().iterator(); it.hasNext();) {
OrderLineEntityLocal line = (OrderLineEntityLocal) it.next();
line.setDeleted(new Integer(1));
}
createLines(dto);
if (oldLine != null && nonDeletedLines == 1) {
OrderLineEntityLocal newLine = null;
for (Iterator i = order.getOrderLines().iterator(); i.hasNext();) {
OrderLineEntityLocal temp = (OrderLineEntityLocal)i.next();
if (temp.getDeleted() == 0) {
newLine = temp;
}
}
if (newLine != null && !oldLine.getItemId().equals(newLine.getItemId())) {
eLogger.audit(executorId,
Constants.TABLE_ORDER_LINE,
newLine.getId(), EventLogger.MODULE_ORDER_MAINTENANCE,
EventLogger.ORDER_LINE_UPDATED, oldLine.getId(),
oldLine.getDescription(),
null);
}
}
eLogger.audit(executorId, Constants.TABLE_PUCHASE_ORDER,
order.getId(),
EventLogger.MODULE_ORDER_MAINTENANCE,
EventLogger.ROW_UPDATED, null,
null, null);
}
private void updateNextBillableDay(Integer executorId, Date newDate) {
if (newDate == null) return;
// only if the new date is in the future
if (order.getNextBillableDay() == null ||
newDate.after(order.getNextBillableDay())) {
// this audit can be added to the order details screen
// otherwise the user can't account for the lost time
eLogger.audit(executorId, Constants.TABLE_PUCHASE_ORDER,
order.getId(),
EventLogger.MODULE_ORDER_MAINTENANCE,
EventLogger.ORDER_NEXT_BILL_DATE_UPDATED, null,
null, order.getNextBillableDay());
// do the actual update
order.setNextBillableDay(newDate);
} else {
log.info("order " + order.getId() +
" next billable day not updated from " +
order.getNextBillableDay() + " to " + newDate);
}
}
private void createLines(NewOrderDTO orderDto)
throws FinderException, CreateException {
Collection orderLines = order.getOrderLines();
/*
* now go over the order lines
*/
for (OrderLineDTOEx line : orderDto.getRawOrderLines()) {
// get the type id bean for the relationship
OrderLineTypeEntityLocal lineType =
orderLineTypeHome.findByPrimaryKey(line.getTypeId());
// first, create the line record
OrderLineEntityLocal newOrderLine =
orderLineHome.create(
line.getItemId(),
lineType,
line.getDescription(),
line.getAmount(),
line.getQuantity(),
line.getPrice(),
line.getItemPrice(),
new Integer(0));
// then update the order fk column
orderLines.add(newOrderLine);
}
}
private void updatePromotion(Integer entityId, String code)
throws NamingException {
if (code != null && code.length() > 0) {
PromotionBL promotion = new PromotionBL();
if (promotion.isPresent(entityId, code)) {
promotion.getEntity().getUsers().add(order.getUser());
} else {
log.error("Can't find promotion entity = " + entityId +
" code " + code);
}
}
}
/**
* Method lookUpEditable.
* Gets the row from order_line_type for the type specifed
* @param type
* The order line type to look.
* @return Boolean
* If it is editable or not
* @throws SessionInternalError
* If there was a problem accessing the entity bean
*/
static public Boolean lookUpEditable(Integer type)
throws SessionInternalError {
Boolean editable = null;
Logger log = Logger.getLogger(OrderBL.class);
try {
JNDILookup EJBFactory = JNDILookup.getFactory(false);
OrderLineTypeEntityLocalHome orderLineTypeHome =
(OrderLineTypeEntityLocalHome) EJBFactory.lookUpLocalHome(
OrderLineTypeEntityLocalHome.class,
OrderLineTypeEntityLocalHome.JNDI_NAME);
OrderLineTypeEntityLocal typeBean =
orderLineTypeHome.findByPrimaryKey(type);
editable = new Boolean(typeBean.getEditable().intValue() == 1);
} catch (Exception e) {
log.fatal(
"Exception looking up the editable flag of an order "
+ "line type. Type = "
+ type,
e);
throw new SessionInternalError("Looking up editable flag");
}
return editable;
}
public CachedRowSet getList(Integer entityID, Integer userRole,
Integer userId)
throws SQLException, Exception{
if(userRole.equals(Constants.TYPE_INTERNAL) ||
userRole.equals(Constants.TYPE_ROOT) ||
userRole.equals(Constants.TYPE_CLERK)) {
prepareStatement(OrderSQL.listInternal);
cachedResults.setInt(1,entityID.intValue());
} else if(userRole.equals(Constants.TYPE_PARTNER)) {
prepareStatement(OrderSQL.listPartner);
cachedResults.setInt(1, entityID.intValue());
cachedResults.setInt(2, userId.intValue());
} else if(userRole.equals(Constants.TYPE_CUSTOMER)) {
prepareStatement(OrderSQL.listCustomer);
cachedResults.setInt(1, userId.intValue());
} else {
throw new Exception("The orders list for the type " + userRole +
" is not supported");
}
execute();
conn.close();
return cachedResults;
}
public Integer getLatest(Integer userId)
throws SessionInternalError {
Integer retValue = null;
try {
prepareStatement(OrderSQL.getLatest);
cachedResults.setInt(1, userId.intValue());
execute();
if (cachedResults.next()) {
int value = cachedResults.getInt(1);
if (!cachedResults.wasNull()) {
retValue = new Integer(value);
}
}
cachedResults.close();
conn.close();
} catch (Exception e) {
throw new SessionInternalError(e);
}
return retValue;
}
public CachedRowSet getOrdersByProcessId(Integer processId)
throws SQLException, Exception{
prepareStatement(OrderSQL.listByProcess);
cachedResults.setInt(1,processId.intValue());
execute();
conn.close();
return cachedResults;
}
public void setStatus(Integer executorId, Integer statusId) {
if (statusId == null || order.getStatusId().equals(statusId)) {
return;
}
if (executorId != null) {
eLogger.audit(executorId, Constants.TABLE_PUCHASE_ORDER,
order.getId(),
EventLogger.MODULE_ORDER_MAINTENANCE,
EventLogger.ORDER_STATUS_CHANGE,
order.getStatusId(), null, null);
} else {
eLogger.auditBySystem(order.getUser().getEntity().getId(),
Constants.TABLE_PUCHASE_ORDER,
order.getId(),
EventLogger.MODULE_ORDER_MAINTENANCE,
EventLogger.ORDER_STATUS_CHANGE,
order.getStatusId(), null, null);
}
NewStatusEvent event = new NewStatusEvent(
order.getId(), order.getStatusId(), statusId);
EventManager.process(event);
order.setStatusId(statusId);
}
/**
* To be called from the http api, this simply looks for lines
* in the order that lack some fields, it finds that info based
* in the item.
* @param dto
*/
public void fillInLines(NewOrderDTO dto, Integer entityId)
throws NamingException, FinderException, SessionInternalError {
/*
* now go over the order lines
*/
Hashtable lines = dto.getOrderLinesMap();
Collection values = lines.values();
ItemBL itemBl = new ItemBL();
for (Iterator i = values.iterator(); i.hasNext();) {
OrderLineDTOEx line = (OrderLineDTOEx) i.next();
itemBl.set(line.getItemId());
Integer languageId = itemBl.getEntity().getEntity().
getLanguageId();
// this is needed for the basic pluggable task to work
line.setItem(itemBl.getDTO(languageId, dto.getUserId(),
entityId, dto.getCurrencyId()));
if (line.getPrice() == null) {
line.setPrice(itemBl.getPrice(dto.getUserId(),
dto.getCurrencyId(), entityId));
}
if (line.getDescription() == null) {
line.setDescription(itemBl.getEntity().getDescription(
languageId));
}
}
}
private void audit(Integer executorId, Date date) {
eLogger.audit(executorId, Constants.TABLE_PUCHASE_ORDER,
order.getId(),
EventLogger.MODULE_ORDER_MAINTENANCE,
EventLogger.ROW_UPDATED, null,
null, date);
}
private void audit(Integer executorId, Integer in) {
eLogger.audit(executorId, Constants.TABLE_PUCHASE_ORDER,
order.getId(),
EventLogger.MODULE_ORDER_MAINTENANCE,
EventLogger.ROW_UPDATED, in,
null, null);
}
public static boolean validate(OrderWS dto) {
boolean retValue = true;
if (dto.getUserId() == null || dto.getPeriod() == null ||
dto.getBillingTypeId() == null ||
dto.getOrderLines() == null) {
retValue = false;
} else {
for (int f = 0 ; f < dto.getOrderLines().length; f++) {
if (!validate(dto.getOrderLines()[f])) {
retValue = false;
break;
}
}
}
return retValue;
}
public static boolean validate(OrderLineWS dto) {
boolean retValue = true;
if (dto.getTypeId() == null || dto.getAmount() == null ||
dto.getDescription() == null || dto.getQuantity() == null) {
retValue = false;
}
return retValue;
}
public void reviewNotifications(Date today)
throws NamingException, FinderException, SQLException, Exception {
NotificationSessionLocalHome notificationHome =
(NotificationSessionLocalHome) EJBFactory.lookUpLocalHome(
NotificationSessionLocalHome.class,
NotificationSessionLocalHome.JNDI_NAME);
NotificationSessionLocal notificationSess =
notificationHome.create();
EntityBL entity = new EntityBL();
Collection entities = entity.getHome().findEntities();
for (Iterator it = entities.iterator(); it.hasNext(); ) {
EntityEntityLocal ent = (EntityEntityLocal) it.next();
// find the orders for this entity
prepareStatement(OrderSQL.getAboutToExpire);
cachedResults.setDate(1, new java.sql.Date(today.getTime()));
// calculate the until date
// get the this entity preferences for each of the steps
PreferenceBL pref = new PreferenceBL();
int totalSteps = 3;
int stepDays[] = new int[totalSteps];
boolean config = false;
int minStep = -1;
for (int f = 0; f < totalSteps; f++) {
try {
pref.set(ent.getId(), new Integer(
Constants.PREFERENCE_DAYS_ORDER_NOTIFICATION_S1.intValue() +
f));
if (pref.isNull()) {
stepDays[f] = -1;
} else {
stepDays[f] = pref.getInt();
config = true;
if (minStep == -1) {
minStep = f;
}
}
} catch (FinderException e) {
stepDays[f] = -1;
}
}
if (!config) {
log.warn("Preference missing to send a notification for " +
"entity " + ent.getId());
continue;
}
Calendar cal = Calendar.getInstance();
cal.clear();
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, stepDays[minStep]);
cachedResults.setDate(2, new java.sql.Date(
cal.getTime().getTime()));
// the entity
cachedResults.setInt(3, ent.getId().intValue());
// the total number of steps
cachedResults.setInt(4, totalSteps);
execute();
while (cachedResults.next()) {
int orderId = cachedResults.getInt(1);
Date activeUntil = cachedResults.getDate(2);
int currentStep = cachedResults.getInt(3);
int days = -1;
// find out how many days apply for this order step
for (int f = currentStep; f < totalSteps; f++) {
if (stepDays[f] >= 0) {
days = stepDays[f];
currentStep = f + 1;
break;
}
}
if (days == -1) {
throw new SessionInternalError("There are no more steps " +
"configured, but the order was selected. Order " +
" id = " + orderId);
}
// check that this order requires a notification
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, days);
if (activeUntil.compareTo(today) >= 0 &&
activeUntil.compareTo(cal.getTime()) <= 0) {
/*/ ok
log.debug("Selecting order " + orderId + " today = " +
today + " active unitl = " + activeUntil +
" days = " + days);
*/
} else {
/*
log.debug("Skipping order " + orderId + " today = " +
today + " active unitl = " + activeUntil +
" days = " + days);
*/
continue;
}
set(new Integer(orderId));
UserBL user = new UserBL(order.getUser());
try {
NotificationBL notification = new NotificationBL();
ContactBL contact = new ContactBL();
contact.set(user.getEntity().getUserId());
OrderDTOEx dto = DTOFactory.getOrderDTOEx(
new Integer(orderId), new Integer(1));
MessageDTO message = notification.getOrderNotification(
ent.getId(),
new Integer(currentStep),
user.getEntity().getLanguageIdField(),
order.getActiveSince(),
order.getActiveUntil(),
user.getEntity().getUserId(),
dto.getTotal(), order.getCurrencyId());
// update the order record only if the message is sent
if (notificationSess.notify(user.getEntity(), message).
booleanValue()) {
// if in the last step, turn the notification off, so
// it is skiped in the next process
if (currentStep >= totalSteps) {
order.setNotify(new Integer(0));
}
order.setNotificationStep(new Integer(currentStep));
order.setLastNotified(Calendar.getInstance().getTime());
}
} catch (NotificationNotFoundException e) {
log.warn("Without a message to send, this entity can't" +
" notify about orders. Skipping");
break;
}
}
+ cachedResults.close();
}
- cachedResults.close();
// The connection was found null when testing on Oracle
if (conn != null) {
conn.close();
}
}
public TimePeriod getDueDate()
throws NamingException, FinderException {
TimePeriod retValue = new TimePeriod();
if (order.getDueDateValue() == null) {
// let's go see the customer
if (order.getUser().getCustomer().getDueDateValue() == null) {
// still unset, let's go to the entity
ConfigurationBL config = new ConfigurationBL(
order.getUser().getEntity().getId());
retValue.setUnitId(config.getEntity().getDueDateUnitId());
retValue.setValue(config.getEntity().getDueDateValue());
} else {
retValue.setUnitId(order.getUser().getCustomer().
getDueDateUnitId());
retValue.setValue(order.getUser().getCustomer().getDueDateValue());
}
} else {
retValue.setUnitId(order.getDueDateUnitId());
retValue.setValue(order.getDueDateValue());
}
// df fm only applies if the entity uses it
PreferenceBL preference = new PreferenceBL();
try {
preference.set(order.getUser().getEntity().getId(),
Constants.PREFERENCE_USE_DF_FM);
} catch (FinderException e) {
// no problem go ahead use the defualts
}
if (preference.getInt() == 1) {
// now all over again for the Df Fm
if (order.getDfFm() == null) {
// let's go see the customer
if (order.getUser().getCustomer().getDfFm() == null) {
// still unset, let's go to the entity
ConfigurationBL config = new ConfigurationBL(
order.getUser().getEntity().getId());
retValue.setDf_fm(config.getEntity().getDfFm());
} else {
retValue.setDf_fm(order.getUser().getCustomer().getDfFm());
}
} else {
retValue.setDf_fm(order.getDfFm());
}
} else {
retValue.setDf_fm((Boolean) null);
}
retValue.setOwn_invoice(order.getOwnInvoice());
return retValue;
}
public Date getInvoicingDate() {
Date retValue;;
if (order.getNextBillableDay() != null) {
retValue = order.getNextBillableDay();
} else {
if (order.getActiveSince() != null) {
retValue = order.getActiveSince();
} else {
retValue = order.getCreateDate();
}
}
return retValue;
}
public Integer[] getManyWS(Integer userId, Integer number,
Integer languageId)
throws NamingException, FinderException {
// find the order records first
UserBL user = new UserBL(userId);
Collection orders = user.getEntity().getOrders();
Vector ordersVector = new Vector(orders); // needed to use sort
Collections.sort(ordersVector, new OrderEntityComparator());
Collections.reverse(ordersVector);
// now convert the entities to WS objects
Integer retValue[] = new Integer[ordersVector.size() >
number.intValue() ? number.intValue() :
ordersVector.size()];
for (int f = 0; f < ordersVector.size() && f < number.intValue();
f++) {
order = (OrderEntityLocal) ordersVector.get(f);
retValue[f] = order.getId();
}
return retValue;
}
public Integer[] getByUserAndPeriod(Integer userId, Integer statusId)
throws SessionInternalError {
// find the order records first
try {
Vector result = new Vector();
prepareStatement(OrderSQL.getByUserAndPeriod);
cachedResults.setInt(1, userId.intValue());
cachedResults.setInt(2, statusId.intValue());
execute();
while (cachedResults.next()) {
result.add(new Integer(cachedResults.getInt(1)));
}
cachedResults.close();
conn.close();
// now convert the vector to an int array
Integer retValue[] = new Integer[result.size()];
result.toArray(retValue);
return retValue;
} catch (Exception e) {
throw new SessionInternalError(e);
}
}
public OrderPeriodDTOEx[] getPeriods(Integer entityId, Integer languageId) {
OrderPeriodDTOEx retValue[] = null;
try {
Collection periods = orderPeriodHome.findByEntity(entityId);
retValue = new OrderPeriodDTOEx[periods.size()];
int f = 0;
for (Iterator it = periods.iterator(); it.hasNext(); f++) {
OrderPeriodEntityLocal period =
(OrderPeriodEntityLocal) it.next();
retValue[f] = new OrderPeriodDTOEx();
retValue[f].setId(period.getId());
retValue[f].setEntityId(period.getEntityId());
retValue[f].setUnitId(period.getUnitId());
retValue[f].setValue(period.getValue());
retValue[f].setDescription(period.getDescription(languageId));
}
} catch (FinderException e) {
retValue = new OrderPeriodDTOEx[0];
}
return retValue;
}
public void updatePeriods(Integer languageId, OrderPeriodDTOEx periods[])
throws FinderException {
for (int f = 0; f < periods.length; f++) {
OrderPeriodEntityLocal period = orderPeriodHome.findByPrimaryKey(
periods[f].getId());
period.setUnitId(periods[f].getUnitId());
period.setValue(periods[f].getValue());
period.setDescription(periods[f].getDescription(), languageId);
}
}
public void addPeriod(Integer entitytId, Integer languageId)
throws CreateException {
orderPeriodHome.create(entitytId, new Integer(1), new Integer(1), " ",
languageId);
}
public boolean deletePeriod(Integer periodId)
throws FinderException, RemoveException{
OrderPeriodEntityLocal period = orderPeriodHome.findByPrimaryKey(
periodId);
if (period.getOrders().size() > 0) {
return false;
} else {
period.remove();
return true;
}
}
public OrderLineWS getOrderLineWS(Integer id)
throws FinderException {
OrderLineEntityLocal line = orderLineHome.findByPrimaryKey(id);
OrderLineWS retValue = new OrderLineWS(line.getId(),line.getItemId(),
line.getDescription(), line.getAmount(), line.getQuantity(),
line.getPrice(), line.getItemPrice(), line.getCreateDate(),
line.getDeleted(), line.getType().getId(),
new Boolean(line.getEditable()));
return retValue;
}
public OrderLineEntityLocal getOrderLine(Integer id)
throws FinderException {
return orderLineHome.findByPrimaryKey(id);
}
public void updateOrderLine(OrderLineWS dto)
throws FinderException, RemoveException {
OrderLineEntityLocal line = orderLineHome.findByPrimaryKey(dto.getId());
if (dto.getQuantity() != null && dto.getQuantity().intValue() == 0) {
// deletes the order line if the quantity is 0
line.remove();
} else {
line.setAmount(dto.getAmount());
line.setDeleted(dto.getDeleted());
line.setDescription(dto.getDescription());
line.setItemId(dto.getItemId());
line.setItemPrice(dto.getItemPrice());
line.setPrice(dto.getPrice());
line.setQuantity(dto.getQuantity());
}
}
}
| false | true | public void reviewNotifications(Date today)
throws NamingException, FinderException, SQLException, Exception {
NotificationSessionLocalHome notificationHome =
(NotificationSessionLocalHome) EJBFactory.lookUpLocalHome(
NotificationSessionLocalHome.class,
NotificationSessionLocalHome.JNDI_NAME);
NotificationSessionLocal notificationSess =
notificationHome.create();
EntityBL entity = new EntityBL();
Collection entities = entity.getHome().findEntities();
for (Iterator it = entities.iterator(); it.hasNext(); ) {
EntityEntityLocal ent = (EntityEntityLocal) it.next();
// find the orders for this entity
prepareStatement(OrderSQL.getAboutToExpire);
cachedResults.setDate(1, new java.sql.Date(today.getTime()));
// calculate the until date
// get the this entity preferences for each of the steps
PreferenceBL pref = new PreferenceBL();
int totalSteps = 3;
int stepDays[] = new int[totalSteps];
boolean config = false;
int minStep = -1;
for (int f = 0; f < totalSteps; f++) {
try {
pref.set(ent.getId(), new Integer(
Constants.PREFERENCE_DAYS_ORDER_NOTIFICATION_S1.intValue() +
f));
if (pref.isNull()) {
stepDays[f] = -1;
} else {
stepDays[f] = pref.getInt();
config = true;
if (minStep == -1) {
minStep = f;
}
}
} catch (FinderException e) {
stepDays[f] = -1;
}
}
if (!config) {
log.warn("Preference missing to send a notification for " +
"entity " + ent.getId());
continue;
}
Calendar cal = Calendar.getInstance();
cal.clear();
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, stepDays[minStep]);
cachedResults.setDate(2, new java.sql.Date(
cal.getTime().getTime()));
// the entity
cachedResults.setInt(3, ent.getId().intValue());
// the total number of steps
cachedResults.setInt(4, totalSteps);
execute();
while (cachedResults.next()) {
int orderId = cachedResults.getInt(1);
Date activeUntil = cachedResults.getDate(2);
int currentStep = cachedResults.getInt(3);
int days = -1;
// find out how many days apply for this order step
for (int f = currentStep; f < totalSteps; f++) {
if (stepDays[f] >= 0) {
days = stepDays[f];
currentStep = f + 1;
break;
}
}
if (days == -1) {
throw new SessionInternalError("There are no more steps " +
"configured, but the order was selected. Order " +
" id = " + orderId);
}
// check that this order requires a notification
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, days);
if (activeUntil.compareTo(today) >= 0 &&
activeUntil.compareTo(cal.getTime()) <= 0) {
/*/ ok
log.debug("Selecting order " + orderId + " today = " +
today + " active unitl = " + activeUntil +
" days = " + days);
*/
} else {
/*
log.debug("Skipping order " + orderId + " today = " +
today + " active unitl = " + activeUntil +
" days = " + days);
*/
continue;
}
set(new Integer(orderId));
UserBL user = new UserBL(order.getUser());
try {
NotificationBL notification = new NotificationBL();
ContactBL contact = new ContactBL();
contact.set(user.getEntity().getUserId());
OrderDTOEx dto = DTOFactory.getOrderDTOEx(
new Integer(orderId), new Integer(1));
MessageDTO message = notification.getOrderNotification(
ent.getId(),
new Integer(currentStep),
user.getEntity().getLanguageIdField(),
order.getActiveSince(),
order.getActiveUntil(),
user.getEntity().getUserId(),
dto.getTotal(), order.getCurrencyId());
// update the order record only if the message is sent
if (notificationSess.notify(user.getEntity(), message).
booleanValue()) {
// if in the last step, turn the notification off, so
// it is skiped in the next process
if (currentStep >= totalSteps) {
order.setNotify(new Integer(0));
}
order.setNotificationStep(new Integer(currentStep));
order.setLastNotified(Calendar.getInstance().getTime());
}
} catch (NotificationNotFoundException e) {
log.warn("Without a message to send, this entity can't" +
" notify about orders. Skipping");
break;
}
}
}
cachedResults.close();
// The connection was found null when testing on Oracle
if (conn != null) {
conn.close();
}
}
| public void reviewNotifications(Date today)
throws NamingException, FinderException, SQLException, Exception {
NotificationSessionLocalHome notificationHome =
(NotificationSessionLocalHome) EJBFactory.lookUpLocalHome(
NotificationSessionLocalHome.class,
NotificationSessionLocalHome.JNDI_NAME);
NotificationSessionLocal notificationSess =
notificationHome.create();
EntityBL entity = new EntityBL();
Collection entities = entity.getHome().findEntities();
for (Iterator it = entities.iterator(); it.hasNext(); ) {
EntityEntityLocal ent = (EntityEntityLocal) it.next();
// find the orders for this entity
prepareStatement(OrderSQL.getAboutToExpire);
cachedResults.setDate(1, new java.sql.Date(today.getTime()));
// calculate the until date
// get the this entity preferences for each of the steps
PreferenceBL pref = new PreferenceBL();
int totalSteps = 3;
int stepDays[] = new int[totalSteps];
boolean config = false;
int minStep = -1;
for (int f = 0; f < totalSteps; f++) {
try {
pref.set(ent.getId(), new Integer(
Constants.PREFERENCE_DAYS_ORDER_NOTIFICATION_S1.intValue() +
f));
if (pref.isNull()) {
stepDays[f] = -1;
} else {
stepDays[f] = pref.getInt();
config = true;
if (minStep == -1) {
minStep = f;
}
}
} catch (FinderException e) {
stepDays[f] = -1;
}
}
if (!config) {
log.warn("Preference missing to send a notification for " +
"entity " + ent.getId());
continue;
}
Calendar cal = Calendar.getInstance();
cal.clear();
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, stepDays[minStep]);
cachedResults.setDate(2, new java.sql.Date(
cal.getTime().getTime()));
// the entity
cachedResults.setInt(3, ent.getId().intValue());
// the total number of steps
cachedResults.setInt(4, totalSteps);
execute();
while (cachedResults.next()) {
int orderId = cachedResults.getInt(1);
Date activeUntil = cachedResults.getDate(2);
int currentStep = cachedResults.getInt(3);
int days = -1;
// find out how many days apply for this order step
for (int f = currentStep; f < totalSteps; f++) {
if (stepDays[f] >= 0) {
days = stepDays[f];
currentStep = f + 1;
break;
}
}
if (days == -1) {
throw new SessionInternalError("There are no more steps " +
"configured, but the order was selected. Order " +
" id = " + orderId);
}
// check that this order requires a notification
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, days);
if (activeUntil.compareTo(today) >= 0 &&
activeUntil.compareTo(cal.getTime()) <= 0) {
/*/ ok
log.debug("Selecting order " + orderId + " today = " +
today + " active unitl = " + activeUntil +
" days = " + days);
*/
} else {
/*
log.debug("Skipping order " + orderId + " today = " +
today + " active unitl = " + activeUntil +
" days = " + days);
*/
continue;
}
set(new Integer(orderId));
UserBL user = new UserBL(order.getUser());
try {
NotificationBL notification = new NotificationBL();
ContactBL contact = new ContactBL();
contact.set(user.getEntity().getUserId());
OrderDTOEx dto = DTOFactory.getOrderDTOEx(
new Integer(orderId), new Integer(1));
MessageDTO message = notification.getOrderNotification(
ent.getId(),
new Integer(currentStep),
user.getEntity().getLanguageIdField(),
order.getActiveSince(),
order.getActiveUntil(),
user.getEntity().getUserId(),
dto.getTotal(), order.getCurrencyId());
// update the order record only if the message is sent
if (notificationSess.notify(user.getEntity(), message).
booleanValue()) {
// if in the last step, turn the notification off, so
// it is skiped in the next process
if (currentStep >= totalSteps) {
order.setNotify(new Integer(0));
}
order.setNotificationStep(new Integer(currentStep));
order.setLastNotified(Calendar.getInstance().getTime());
}
} catch (NotificationNotFoundException e) {
log.warn("Without a message to send, this entity can't" +
" notify about orders. Skipping");
break;
}
}
cachedResults.close();
}
// The connection was found null when testing on Oracle
if (conn != null) {
conn.close();
}
}
|
diff --git a/src/TheoremChecker.java b/src/TheoremChecker.java
index e9115a7..59a9ed6 100644
--- a/src/TheoremChecker.java
+++ b/src/TheoremChecker.java
@@ -1,94 +1,98 @@
import java.util.*;
public class TheoremChecker extends Expression{ //used to check whether Theorem matches expression
private HashMap<String, subExpression> subValues;
private Expression theorem;
private Expression toEvaluate;
public TheoremChecker() {
subValues = new HashMap<String, subExpression>();
}
public TheoremChecker(Expression thm, Expression tbe) throws IllegalInferenceException{
subValues = new HashMap<String, subExpression>();
theorem = thm;
toEvaluate = tbe;
if (ProofChecker.iAmDebugging){
System.out.println("Checking application of "+thm.toString()+" to "+tbe.toString());
}
constructorHelper(thm.getRoot(), tbe.getRoot()); //fills subValues HashMap
}
public boolean containsKey(String name) {
return subValues.containsKey(name);
}
public subExpression get(String name) {
return subValues.get(name);
}
//for printing errors with mismatched expressions
public String errorPrinting() {
String returnVal = "";
Set<String> keys = subValues.keySet();
if (keys.isEmpty()) {
return returnVal;
}
for (String key : keys) {
subExpression temp = subValues.get(key);
if (temp == null) {
returnVal = returnVal + key + "= NOT SET!, ";
} else {
returnVal = returnVal + key + "=" + subValues.get(key).toString()+", ";
}
}
returnVal = returnVal.substring(0,(returnVal.length()-2));
return returnVal;
}
private void constructorHelper(subExpression thm, subExpression tbe) throws IllegalInferenceException{
if (tbe == null) {
throw new IllegalInferenceException("Bad theorem application "+errorPrinting());
} else if (thm.isVariable()) {
- try {
+ try {
+ if ((subValues.containsKey(thm.getName())) &&
+ (!(subValues.get(thm.getName()).toString().equals(tbe.toString())))) {
+ throw new IllegalInferenceException("Bad theorem application "+ errorPrinting());
+ }
subValues.put(thm.getName(),tbe);
} catch (NullPointerException e) {
throw new IllegalInferenceException("Bad theorem application "+errorPrinting());
}
} else if (thm.getName().equals("~")) {
try {
constructorHelper(thm.getLeft(),tbe.getLeft());
} catch (NullPointerException e) {
throw new IllegalInferenceException("Bad theorem application "+errorPrinting());
}
} else {
try {
constructorHelper(thm.getLeft(),tbe.getLeft());
constructorHelper(thm.getRight(),tbe.getRight());
} catch (NullPointerException e) {
throw new IllegalInferenceException("Bad theorem application "+errorPrinting());
}
}
}
public boolean matches() {
return matchesHelper(theorem.getRoot(), toEvaluate.getRoot());
}
private boolean matchesHelper(subExpression thm, subExpression tbe) {
if (thm.isVariable()) {
return tbe.equals(subValues.get(thm.getName()));
} else if (thm.getName().equals(tbe.getName())) {
boolean lReturn = false;
boolean rReturn = false;
if (thm.getLeft() != null && tbe.getLeft() != null) {
lReturn = matchesHelper(thm.getLeft(), tbe.getLeft());
}
if (thm.getRight() != null && tbe.getRight() != null) {
rReturn = matchesHelper(thm.getRight(), tbe.getRight());
}
if (thm.getName().equals("~")) {
rReturn = true;
}
return lReturn && rReturn;
} else {
return false;
}
}
}
| true | true | private void constructorHelper(subExpression thm, subExpression tbe) throws IllegalInferenceException{
if (tbe == null) {
throw new IllegalInferenceException("Bad theorem application "+errorPrinting());
} else if (thm.isVariable()) {
try {
subValues.put(thm.getName(),tbe);
} catch (NullPointerException e) {
throw new IllegalInferenceException("Bad theorem application "+errorPrinting());
}
} else if (thm.getName().equals("~")) {
try {
constructorHelper(thm.getLeft(),tbe.getLeft());
} catch (NullPointerException e) {
throw new IllegalInferenceException("Bad theorem application "+errorPrinting());
}
} else {
try {
constructorHelper(thm.getLeft(),tbe.getLeft());
constructorHelper(thm.getRight(),tbe.getRight());
} catch (NullPointerException e) {
throw new IllegalInferenceException("Bad theorem application "+errorPrinting());
}
}
}
| private void constructorHelper(subExpression thm, subExpression tbe) throws IllegalInferenceException{
if (tbe == null) {
throw new IllegalInferenceException("Bad theorem application "+errorPrinting());
} else if (thm.isVariable()) {
try {
if ((subValues.containsKey(thm.getName())) &&
(!(subValues.get(thm.getName()).toString().equals(tbe.toString())))) {
throw new IllegalInferenceException("Bad theorem application "+ errorPrinting());
}
subValues.put(thm.getName(),tbe);
} catch (NullPointerException e) {
throw new IllegalInferenceException("Bad theorem application "+errorPrinting());
}
} else if (thm.getName().equals("~")) {
try {
constructorHelper(thm.getLeft(),tbe.getLeft());
} catch (NullPointerException e) {
throw new IllegalInferenceException("Bad theorem application "+errorPrinting());
}
} else {
try {
constructorHelper(thm.getLeft(),tbe.getLeft());
constructorHelper(thm.getRight(),tbe.getRight());
} catch (NullPointerException e) {
throw new IllegalInferenceException("Bad theorem application "+errorPrinting());
}
}
}
|
diff --git a/grisu-commons/src/main/java/grisu/model/status/StatusObject.java b/grisu-commons/src/main/java/grisu/model/status/StatusObject.java
index 98613928..3b832d75 100644
--- a/grisu-commons/src/main/java/grisu/model/status/StatusObject.java
+++ b/grisu-commons/src/main/java/grisu/model/status/StatusObject.java
@@ -1,232 +1,232 @@
package grisu.model.status;
import grisu.control.ServiceInterface;
import grisu.control.exceptions.StatusException;
import grisu.model.dto.DtoActionStatus;
import java.util.Date;
import java.util.Enumeration;
import java.util.Vector;
import java.util.concurrent.CountDownLatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StatusObject {
public interface Listener {
public void statusMessage(ActionStatusEvent event);
}
static final Logger myLogger = LoggerFactory.getLogger(StatusObject.class
.getName());
public static StatusObject waitForActionToFinish(ServiceInterface si, String handle)
throws StatusException {
return waitForActionToFinish(si, handle, 10, false);
}
public static StatusObject waitForActionToFinish(ServiceInterface si,
String handle, int recheckIntervalInSeconds, boolean exitIfFailed)
throws StatusException {
return waitForActionToFinish(si, handle, recheckIntervalInSeconds,
exitIfFailed, -1);
}
public static StatusObject waitForActionToFinish(ServiceInterface si,
String handle, int recheckIntervalInSeconds, boolean exitIfFailed,
int treshold_in_secs) throws StatusException {
final StatusObject temp = new StatusObject(si, handle);
temp.waitForActionToFinish(recheckIntervalInSeconds,
exitIfFailed, treshold_in_secs);
return temp;
}
private final ServiceInterface si;
private final String handle;
private volatile Thread t = null;
private Vector<Listener> listeners;
private DtoActionStatus lastStatus;
private double lastPercentage = 0;
private boolean taskFinished = false;
private long startMonitoringTime = -1;
private long finishedMonitoringTime = -1;
private volatile boolean waitWasInterrupted = false;
private final CountDownLatch finished = new CountDownLatch(1);
public StatusObject(ServiceInterface si, String handle) {
this(si, handle, (Vector) null);
}
public StatusObject(ServiceInterface si, String handle, Listener l) {
this(si, handle, (Vector) null);
addListener(l);
}
public StatusObject(ServiceInterface si, String handle,
Vector<Listener> listeners) {
this.si = si;
this.handle = handle;
this.listeners = listeners;
if (listeners != null) {
for (final Listener l : listeners) {
addListener(l);
}
}
}
synchronized public void addListener(Listener l) {
if (listeners == null) {
listeners = new Vector();
}
listeners.addElement(l);
}
private synchronized void createWaitThread(final int waitTime,
final int thresholdInSeconds) {
if (t == null) {
t = new Thread() {
@Override
public void run() {
while (!getStatus().isFinished()) {
try {
- if (((new Date().getTime() - startMonitoringTime) * 1000) < thresholdInSeconds) {
+ if ((new Date().getTime() - startMonitoringTime) < (thresholdInSeconds * 1000)) {
throw new InterruptedException(
"Threshold for task monitoring exceeded. Not waiting any longer...");
}
myLogger.debug("Waiting for task {} to finish...",
handle);
Thread.sleep(waitTime * 1000);
} catch (final InterruptedException e) {
myLogger.error(e.getLocalizedMessage(), e);
waitWasInterrupted = true;
break;
}
}
finishedMonitoringTime = new Date().getTime();
finished.countDown();
}
};
t.setName("Wait thread for status: " + handle);
startMonitoringTime = new Date().getTime();
t.start();
}
}
private void fireEvent(ActionStatusEvent message) {
if ((listeners != null) && !listeners.isEmpty()) {
// make a copy of the listener list in case
// anyone adds/removes mountPointsListeners
Vector targets;
synchronized (this) {
targets = (Vector) listeners.clone();
}
// walk through the listener list and
// call the gridproxychanged method in each
final Enumeration e = targets.elements();
while (e.hasMoreElements()) {
final Listener l = (Listener) e.nextElement();
l.statusMessage(message);
}
}
}
public String getHandle() {
return this.handle;
}
public synchronized DtoActionStatus getStatus() {
if (taskFinished) {
return lastStatus;
}
myLogger.debug("Checking status for: " + handle);
lastStatus = si.getActionStatus(handle);
if ((taskFinished != lastStatus.isFinished())
|| (lastPercentage != lastStatus.percentFinished())) {
lastPercentage = lastStatus.percentFinished();
taskFinished = lastStatus.isFinished();
fireEvent(new ActionStatusEvent(lastStatus));
}
myLogger.debug("Status for " + handle + ": "
+ lastStatus.percentFinished() + " %" + " / finished: "
+ lastStatus.isFinished());
return lastStatus;
}
synchronized public void removeListener(Listener l) {
if (listeners == null) {
listeners = new Vector<Listener>();
}
listeners.removeElement(l);
}
public void waitForActionToFinish(int recheckIntervalInSeconds,
boolean exitIfFailed)
throws StatusException {
waitForActionToFinish(recheckIntervalInSeconds, exitIfFailed,
-1);
}
/**
* Waits for the remote task to be finshed.
*
* @param recheckIntervalInSeconds
* how long to wait inbetween status checks
* @param exitIfFailed
* whether to return from wait if task not finished yet but
* failed already (maybe because at least one sub-task failed).
* @param threshholdInSeconds
* after how long to stop monitoring (in seconds) or -1 for never
* stop monitoring until task finished
* @return true if the task is finished, false if monitoring was interrupted
* either by thread interrupt or threshold
* @throws StatusException
* if the handle can't be found
*/
public void waitForActionToFinish(int recheckIntervalInSeconds,
boolean exitIfFailed, int threshholdInSeconds)
throws StatusException {
lastStatus = si.getActionStatus(handle);
if (lastStatus == null) {
throw new StatusException("Can't find status with handle "
+ this.handle);
}
if (lastStatus.isFinished()) {
return;
}
createWaitThread(recheckIntervalInSeconds, threshholdInSeconds);
try {
finished.await();
} catch (InterruptedException e) {
myLogger.error("Waiting for status " + handle
+ " to finish interrupted.", e);
waitWasInterrupted = true;
throw new StatusException(e.getLocalizedMessage(), e);
}
return;
}
}
| true | true | private synchronized void createWaitThread(final int waitTime,
final int thresholdInSeconds) {
if (t == null) {
t = new Thread() {
@Override
public void run() {
while (!getStatus().isFinished()) {
try {
if (((new Date().getTime() - startMonitoringTime) * 1000) < thresholdInSeconds) {
throw new InterruptedException(
"Threshold for task monitoring exceeded. Not waiting any longer...");
}
myLogger.debug("Waiting for task {} to finish...",
handle);
Thread.sleep(waitTime * 1000);
} catch (final InterruptedException e) {
myLogger.error(e.getLocalizedMessage(), e);
waitWasInterrupted = true;
break;
}
}
finishedMonitoringTime = new Date().getTime();
finished.countDown();
}
};
t.setName("Wait thread for status: " + handle);
startMonitoringTime = new Date().getTime();
t.start();
}
}
| private synchronized void createWaitThread(final int waitTime,
final int thresholdInSeconds) {
if (t == null) {
t = new Thread() {
@Override
public void run() {
while (!getStatus().isFinished()) {
try {
if ((new Date().getTime() - startMonitoringTime) < (thresholdInSeconds * 1000)) {
throw new InterruptedException(
"Threshold for task monitoring exceeded. Not waiting any longer...");
}
myLogger.debug("Waiting for task {} to finish...",
handle);
Thread.sleep(waitTime * 1000);
} catch (final InterruptedException e) {
myLogger.error(e.getLocalizedMessage(), e);
waitWasInterrupted = true;
break;
}
}
finishedMonitoringTime = new Date().getTime();
finished.countDown();
}
};
t.setName("Wait thread for status: " + handle);
startMonitoringTime = new Date().getTime();
t.start();
}
}
|
diff --git a/OpenPGP-Keychain-API/libraries/keychain-api-library/src/org/openintents/openpgp/util/OpenPgpListPreference.java b/OpenPGP-Keychain-API/libraries/keychain-api-library/src/org/openintents/openpgp/util/OpenPgpListPreference.java
index 7aea8f9fa..456bc96a9 100644
--- a/OpenPGP-Keychain-API/libraries/keychain-api-library/src/org/openintents/openpgp/util/OpenPgpListPreference.java
+++ b/OpenPGP-Keychain-API/libraries/keychain-api-library/src/org/openintents/openpgp/util/OpenPgpListPreference.java
@@ -1,249 +1,249 @@
/*
* Copyright (C) 2014 Dominik Schürmann <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openintents.openpgp.util;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.TextView;
import org.sufficientlysecure.keychain.api.R;
import java.util.ArrayList;
import java.util.List;
/**
* Does not extend ListPreference, but is very similar to it!
* http://grepcode.com/file_/repository.grepcode.com/java/ext/com.google.android/android/4.4_r1/android/preference/ListPreference.java/?v=source
*/
public class OpenPgpListPreference extends DialogPreference {
private static final String OPENKEYCHAIN_PACKAGE = "org.sufficientlysecure.keychain";
private static final String MARKET_INTENT_URI_BASE = "market://details?id=%s";
private static final Intent MARKET_INTENT = new Intent(Intent.ACTION_VIEW, Uri.parse(
String.format(MARKET_INTENT_URI_BASE, OPENKEYCHAIN_PACKAGE)));
private ArrayList<OpenPgpProviderEntry> mProviderList = new ArrayList<OpenPgpProviderEntry>();
private String mSelectedPackage;
public OpenPgpListPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public OpenPgpListPreference(Context context) {
this(context, null);
}
/**
* Public method to add new entries for legacy applications
*
* @param packageName
* @param simpleName
* @param icon
*/
public void addProvider(int position, String packageName, String simpleName, Drawable icon) {
mProviderList.add(position, new OpenPgpProviderEntry(packageName, simpleName, icon));
}
@Override
protected void onPrepareDialogBuilder(Builder builder) {
// get providers
mProviderList.clear();
Intent intent = new Intent(OpenPgpConstants.SERVICE_INTENT);
List<ResolveInfo> resInfo = getContext().getPackageManager().queryIntentServices(intent, 0);
if (!resInfo.isEmpty()) {
for (ResolveInfo resolveInfo : resInfo) {
if (resolveInfo.serviceInfo == null)
continue;
String packageName = resolveInfo.serviceInfo.packageName;
String simpleName = String.valueOf(resolveInfo.serviceInfo.loadLabel(getContext()
.getPackageManager()));
Drawable icon = resolveInfo.serviceInfo.loadIcon(getContext().getPackageManager());
mProviderList.add(new OpenPgpProviderEntry(packageName, simpleName, icon));
}
}
// add install links if empty
if (mProviderList.isEmpty()) {
resInfo = getContext().getPackageManager().queryIntentActivities
(MARKET_INTENT, 0);
for (ResolveInfo resolveInfo : resInfo) {
Intent marketIntent = new Intent(MARKET_INTENT);
- intent.setPackage(resolveInfo.activityInfo.packageName);
+ marketIntent.setPackage(resolveInfo.activityInfo.packageName);
Drawable icon = resolveInfo.activityInfo.loadIcon(getContext().getPackageManager());
String marketName = String.valueOf(resolveInfo.activityInfo.applicationInfo
.loadLabel(getContext().getPackageManager()));
String simpleName = String.format(getContext().getString(R.string
.openpgp_install_openkeychain_via), marketName);
mProviderList.add(new OpenPgpProviderEntry(OPENKEYCHAIN_PACKAGE, simpleName,
icon, marketIntent));
}
}
// add "none"-entry
mProviderList.add(0, new OpenPgpProviderEntry("",
getContext().getString(R.string.openpgp_list_preference_none),
getContext().getResources().getDrawable(R.drawable.ic_action_cancel_launchersize)));
// Init ArrayAdapter with OpenPGP Providers
ListAdapter adapter = new ArrayAdapter<OpenPgpProviderEntry>(getContext(),
android.R.layout.select_dialog_singlechoice, android.R.id.text1, mProviderList) {
public View getView(int position, View convertView, ViewGroup parent) {
// User super class to create the View
View v = super.getView(position, convertView, parent);
TextView tv = (TextView) v.findViewById(android.R.id.text1);
// Put the image on the TextView
tv.setCompoundDrawablesWithIntrinsicBounds(mProviderList.get(position).icon, null,
null, null);
// Add margin between image and text (support various screen densities)
int dp10 = (int) (10 * getContext().getResources().getDisplayMetrics().density + 0.5f);
tv.setCompoundDrawablePadding(dp10);
return v;
}
};
builder.setSingleChoiceItems(adapter, getIndexOfProviderList(getValue()),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
OpenPgpProviderEntry entry = mProviderList.get(which);
if (entry.intent != null) {
/*
* Intents are called as activity
*
* Current approach is to assume the user installed the app.
* If he does not, the selected package is not valid.
*
* However applications should always consider this could happen,
* as the user might remove the currently used OpenPGP app.
*/
getContext().startActivity(entry.intent);
}
mSelectedPackage = entry.packageName;
/*
* Clicking on an item simulates the positive button click, and dismisses
* the dialog.
*/
OpenPgpListPreference.this.onClick(dialog, DialogInterface.BUTTON_POSITIVE);
dialog.dismiss();
}
});
/*
* The typical interaction for list-based dialogs is to have click-on-an-item dismiss the
* dialog instead of the user having to press 'Ok'.
*/
builder.setPositiveButton(null, null);
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult && (mSelectedPackage != null)) {
if (callChangeListener(mSelectedPackage)) {
setValue(mSelectedPackage);
}
}
}
private int getIndexOfProviderList(String packageName) {
for (OpenPgpProviderEntry app : mProviderList) {
if (app.packageName.equals(packageName)) {
return mProviderList.indexOf(app);
}
}
return -1;
}
public void setValue(String packageName) {
mSelectedPackage = packageName;
persistString(packageName);
}
public String getValue() {
return mSelectedPackage;
}
public String getEntry() {
return getEntryByValue(mSelectedPackage);
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getString(index);
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
setValue(restoreValue ? getPersistedString(mSelectedPackage) : (String) defaultValue);
}
public String getEntryByValue(String packageName) {
for (OpenPgpProviderEntry app : mProviderList) {
if (app.packageName.equals(packageName)) {
return app.simpleName;
}
}
return null;
}
private static class OpenPgpProviderEntry {
private String packageName;
private String simpleName;
private Drawable icon;
private Intent intent;
public OpenPgpProviderEntry(String packageName, String simpleName, Drawable icon) {
this.packageName = packageName;
this.simpleName = simpleName;
this.icon = icon;
}
public OpenPgpProviderEntry(String packageName, String simpleName, Drawable icon, Intent intent) {
this(packageName, simpleName, icon);
this.intent = intent;
}
@Override
public String toString() {
return simpleName;
}
}
}
| true | true | protected void onPrepareDialogBuilder(Builder builder) {
// get providers
mProviderList.clear();
Intent intent = new Intent(OpenPgpConstants.SERVICE_INTENT);
List<ResolveInfo> resInfo = getContext().getPackageManager().queryIntentServices(intent, 0);
if (!resInfo.isEmpty()) {
for (ResolveInfo resolveInfo : resInfo) {
if (resolveInfo.serviceInfo == null)
continue;
String packageName = resolveInfo.serviceInfo.packageName;
String simpleName = String.valueOf(resolveInfo.serviceInfo.loadLabel(getContext()
.getPackageManager()));
Drawable icon = resolveInfo.serviceInfo.loadIcon(getContext().getPackageManager());
mProviderList.add(new OpenPgpProviderEntry(packageName, simpleName, icon));
}
}
// add install links if empty
if (mProviderList.isEmpty()) {
resInfo = getContext().getPackageManager().queryIntentActivities
(MARKET_INTENT, 0);
for (ResolveInfo resolveInfo : resInfo) {
Intent marketIntent = new Intent(MARKET_INTENT);
intent.setPackage(resolveInfo.activityInfo.packageName);
Drawable icon = resolveInfo.activityInfo.loadIcon(getContext().getPackageManager());
String marketName = String.valueOf(resolveInfo.activityInfo.applicationInfo
.loadLabel(getContext().getPackageManager()));
String simpleName = String.format(getContext().getString(R.string
.openpgp_install_openkeychain_via), marketName);
mProviderList.add(new OpenPgpProviderEntry(OPENKEYCHAIN_PACKAGE, simpleName,
icon, marketIntent));
}
}
// add "none"-entry
mProviderList.add(0, new OpenPgpProviderEntry("",
getContext().getString(R.string.openpgp_list_preference_none),
getContext().getResources().getDrawable(R.drawable.ic_action_cancel_launchersize)));
// Init ArrayAdapter with OpenPGP Providers
ListAdapter adapter = new ArrayAdapter<OpenPgpProviderEntry>(getContext(),
android.R.layout.select_dialog_singlechoice, android.R.id.text1, mProviderList) {
public View getView(int position, View convertView, ViewGroup parent) {
// User super class to create the View
View v = super.getView(position, convertView, parent);
TextView tv = (TextView) v.findViewById(android.R.id.text1);
// Put the image on the TextView
tv.setCompoundDrawablesWithIntrinsicBounds(mProviderList.get(position).icon, null,
null, null);
// Add margin between image and text (support various screen densities)
int dp10 = (int) (10 * getContext().getResources().getDisplayMetrics().density + 0.5f);
tv.setCompoundDrawablePadding(dp10);
return v;
}
};
builder.setSingleChoiceItems(adapter, getIndexOfProviderList(getValue()),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
OpenPgpProviderEntry entry = mProviderList.get(which);
if (entry.intent != null) {
/*
* Intents are called as activity
*
* Current approach is to assume the user installed the app.
* If he does not, the selected package is not valid.
*
* However applications should always consider this could happen,
* as the user might remove the currently used OpenPGP app.
*/
getContext().startActivity(entry.intent);
}
mSelectedPackage = entry.packageName;
/*
* Clicking on an item simulates the positive button click, and dismisses
* the dialog.
*/
OpenPgpListPreference.this.onClick(dialog, DialogInterface.BUTTON_POSITIVE);
dialog.dismiss();
}
});
/*
* The typical interaction for list-based dialogs is to have click-on-an-item dismiss the
* dialog instead of the user having to press 'Ok'.
*/
builder.setPositiveButton(null, null);
}
| protected void onPrepareDialogBuilder(Builder builder) {
// get providers
mProviderList.clear();
Intent intent = new Intent(OpenPgpConstants.SERVICE_INTENT);
List<ResolveInfo> resInfo = getContext().getPackageManager().queryIntentServices(intent, 0);
if (!resInfo.isEmpty()) {
for (ResolveInfo resolveInfo : resInfo) {
if (resolveInfo.serviceInfo == null)
continue;
String packageName = resolveInfo.serviceInfo.packageName;
String simpleName = String.valueOf(resolveInfo.serviceInfo.loadLabel(getContext()
.getPackageManager()));
Drawable icon = resolveInfo.serviceInfo.loadIcon(getContext().getPackageManager());
mProviderList.add(new OpenPgpProviderEntry(packageName, simpleName, icon));
}
}
// add install links if empty
if (mProviderList.isEmpty()) {
resInfo = getContext().getPackageManager().queryIntentActivities
(MARKET_INTENT, 0);
for (ResolveInfo resolveInfo : resInfo) {
Intent marketIntent = new Intent(MARKET_INTENT);
marketIntent.setPackage(resolveInfo.activityInfo.packageName);
Drawable icon = resolveInfo.activityInfo.loadIcon(getContext().getPackageManager());
String marketName = String.valueOf(resolveInfo.activityInfo.applicationInfo
.loadLabel(getContext().getPackageManager()));
String simpleName = String.format(getContext().getString(R.string
.openpgp_install_openkeychain_via), marketName);
mProviderList.add(new OpenPgpProviderEntry(OPENKEYCHAIN_PACKAGE, simpleName,
icon, marketIntent));
}
}
// add "none"-entry
mProviderList.add(0, new OpenPgpProviderEntry("",
getContext().getString(R.string.openpgp_list_preference_none),
getContext().getResources().getDrawable(R.drawable.ic_action_cancel_launchersize)));
// Init ArrayAdapter with OpenPGP Providers
ListAdapter adapter = new ArrayAdapter<OpenPgpProviderEntry>(getContext(),
android.R.layout.select_dialog_singlechoice, android.R.id.text1, mProviderList) {
public View getView(int position, View convertView, ViewGroup parent) {
// User super class to create the View
View v = super.getView(position, convertView, parent);
TextView tv = (TextView) v.findViewById(android.R.id.text1);
// Put the image on the TextView
tv.setCompoundDrawablesWithIntrinsicBounds(mProviderList.get(position).icon, null,
null, null);
// Add margin between image and text (support various screen densities)
int dp10 = (int) (10 * getContext().getResources().getDisplayMetrics().density + 0.5f);
tv.setCompoundDrawablePadding(dp10);
return v;
}
};
builder.setSingleChoiceItems(adapter, getIndexOfProviderList(getValue()),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
OpenPgpProviderEntry entry = mProviderList.get(which);
if (entry.intent != null) {
/*
* Intents are called as activity
*
* Current approach is to assume the user installed the app.
* If he does not, the selected package is not valid.
*
* However applications should always consider this could happen,
* as the user might remove the currently used OpenPGP app.
*/
getContext().startActivity(entry.intent);
}
mSelectedPackage = entry.packageName;
/*
* Clicking on an item simulates the positive button click, and dismisses
* the dialog.
*/
OpenPgpListPreference.this.onClick(dialog, DialogInterface.BUTTON_POSITIVE);
dialog.dismiss();
}
});
/*
* The typical interaction for list-based dialogs is to have click-on-an-item dismiss the
* dialog instead of the user having to press 'Ok'.
*/
builder.setPositiveButton(null, null);
}
|
diff --git a/src/main/java/net/pleiades/ResultsListener.java b/src/main/java/net/pleiades/ResultsListener.java
index 7b47da8..18a5aae 100644
--- a/src/main/java/net/pleiades/ResultsListener.java
+++ b/src/main/java/net/pleiades/ResultsListener.java
@@ -1,204 +1,205 @@
/**
* Pleiades
* Copyright (C) 2011 - 2012
* Computational Intelligence Research Group (CIRG@UP)
* Department of Computer Science
* University of Pretoria
* South Africa
*/
package net.pleiades;
import com.hazelcast.core.EntryEvent;
import com.hazelcast.core.EntryListener;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.IMap;
import com.hazelcast.core.IQueue;
import com.hazelcast.core.Message;
import com.hazelcast.core.MessageListener;
import com.hazelcast.core.Transaction;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.locks.Lock;
import net.pleiades.cluster.HazelcastCommunicator;
import net.pleiades.results.CilibSampleGatherer;
import net.pleiades.results.SampleGatherer;
import net.pleiades.simulations.Simulation;
import net.pleiades.tasks.Task;
public class ResultsListener implements EntryListener, MessageListener<Task> {
private SampleGatherer gatherer;
private Properties properties;
public ResultsListener() {
this.gatherer = new CilibSampleGatherer();
this.properties = Config.getConfiguration();
addListeners();
}
private void addListeners() {
Config.RESULTS_TOPIC.addMessageListener(this);
}
public void execute() {
HazelcastCommunicator cluster = new HazelcastCommunicator();
cluster.connect();
System.out.println("Now connected to Pleiades Cluster.\nWaiting for results...");
Hazelcast.<String, Simulation>getMap(Config.completedMap).addEntryListener(this, true);
}
@Override
public void entryAdded(EntryEvent event) {
System.out.println("Entry added key=" + event.getKey() + ", value=" + event.getValue());
}
@Override
public void entryRemoved(EntryEvent event) {
System.out.println("Entry removed key=" + event.getKey() + ", value=" + event.getValue() + "\n");
}
@Override
public void entryUpdated(EntryEvent event) {
}
@Override
public void entryEvicted(EntryEvent event) {
System.out.println("Entry evicted key=" + event.getKey() + ", value=" + event.getValue());
}
@Override
public synchronized void onMessage(Message<Task> message) {
if (message.getMessageObject().getId().equals("")) { //this attempts to gather jobs from the completed map after the gatherer crashed unexpectedly
System.out.println("Checking all results"); //see line 45 in net.pleiades.Gatherer.java
checkAll();
return;
}
Task t = message.getMessageObject();
Lock rLock = Hazelcast.getLock(Config.runningMap);
rLock.lock();
IMap<String, String> runningMap = Hazelcast.getMap(Config.runningMap);
Transaction txn = Hazelcast.getTransaction();
txn.begin();
try {
runningMap.remove(t.getId());
txn.commit();
} catch (Throwable e) {
txn.rollback();
} finally {
+ runningMap.forceUnlock(t.getId());
rLock.unlock();
}
System.out.println("Task completed:" + message.getMessageObject().getId());
Lock cLock = Hazelcast.getLock(Config.completedMap);
Lock jLock = Hazelcast.getLock(Config.simulationsMap);
cLock.lock();
IMap<String, Simulation> completedMap = Hazelcast.getMap(Config.completedMap);
txn.begin();
boolean gathering = false;
try {
Simulation cSimulation = completedMap.get(t.getParent().getID());
if (cSimulation == null) {
Config.RESULTS_TOPIC.publish(t); //republish this completed task
throw new Exception("No such simulation");
}
cSimulation.completeTask(t, properties);
if (cSimulation.isComplete()) {
completedMap.remove(t.getParent().getID());
System.out.println("\nGathering: " + cSimulation.getID());
System.out.println(cSimulation.getResults().size() + " tasks completed.");
jLock.lock();
IMap<String, List<Simulation>> simulationsMap = Hazelcast.getMap(Config.simulationsMap);
gathering = true;
gatherer.gatherResults(simulationsMap, completedMap, cSimulation);
simulationsMap.forceUnlock(cSimulation.getOwner());
if (cSimulation.jobComplete()) {
Utils.emailUser(cSimulation, new File(properties.getProperty("email_complete_template")), properties, "");
IQueue<String> errors = Hazelcast.getQueue(Config.errorQueue);
IMap<String, byte[]> fileQueue = Hazelcast.getMap(Config.fileMap);
Iterator<String> iter = errors.iterator();
while (iter.hasNext()) {
if (iter.next().startsWith(cSimulation.getJobID())) {
iter.remove();
}
}
System.out.println("Error Queue Size: " + errors.size());
fileQueue.remove(cSimulation.getFileKey());
fileQueue.forceUnlock(cSimulation.getFileKey());
System.out.println("File Queue Size: " + fileQueue.size());
}
} else {
completedMap.put(t.getParent().getID(), cSimulation);
}
completedMap.forceUnlock(t.getParent().getID());
txn.commit();
} catch (Throwable e) {
System.out.println("ERROR:");
e.printStackTrace();
txn.rollback();
} finally {
if (gathering) {
jLock.unlock();
}
cLock.unlock();
}
}
private void checkAll() {
Lock cLock = Hazelcast.getLock(Config.completedMap);
//Lock jLock = Hazelcast.getLock(Config.simulationsMap);
cLock.lock();
IMap<String, Simulation> completedMap = Hazelcast.getMap(Config.completedMap);
Transaction txn = Hazelcast.getTransaction();
for (Simulation cSimulation : completedMap.values()) {
txn.begin();
try {
if (cSimulation.isComplete()) {
completedMap.remove(cSimulation.getID());
System.out.println("\nGathering: " + cSimulation.getID());
System.out.println(cSimulation.getResults().size() + " tasks completed.");
// jLock.lock();
// IMap<String, List<Simulation>> simulationsMap = Hazelcast.getMap(Config.simulationsMap);
gatherer.gatherResults(null, completedMap, cSimulation);
// simulationsMap.forceUnlock(cSimulation.getOwner());
} else {
completedMap.put(cSimulation.getID(), cSimulation);
}
completedMap.forceUnlock(cSimulation.getID());
txn.commit();
} catch (Throwable e) {
System.out.println("ERROR:");
e.printStackTrace();
txn.rollback();
} finally {
//jLock.unlock();
cLock.unlock();
}
}
}
}
| true | true | public synchronized void onMessage(Message<Task> message) {
if (message.getMessageObject().getId().equals("")) { //this attempts to gather jobs from the completed map after the gatherer crashed unexpectedly
System.out.println("Checking all results"); //see line 45 in net.pleiades.Gatherer.java
checkAll();
return;
}
Task t = message.getMessageObject();
Lock rLock = Hazelcast.getLock(Config.runningMap);
rLock.lock();
IMap<String, String> runningMap = Hazelcast.getMap(Config.runningMap);
Transaction txn = Hazelcast.getTransaction();
txn.begin();
try {
runningMap.remove(t.getId());
txn.commit();
} catch (Throwable e) {
txn.rollback();
} finally {
rLock.unlock();
}
System.out.println("Task completed:" + message.getMessageObject().getId());
Lock cLock = Hazelcast.getLock(Config.completedMap);
Lock jLock = Hazelcast.getLock(Config.simulationsMap);
cLock.lock();
IMap<String, Simulation> completedMap = Hazelcast.getMap(Config.completedMap);
txn.begin();
boolean gathering = false;
try {
Simulation cSimulation = completedMap.get(t.getParent().getID());
if (cSimulation == null) {
Config.RESULTS_TOPIC.publish(t); //republish this completed task
throw new Exception("No such simulation");
}
cSimulation.completeTask(t, properties);
if (cSimulation.isComplete()) {
completedMap.remove(t.getParent().getID());
System.out.println("\nGathering: " + cSimulation.getID());
System.out.println(cSimulation.getResults().size() + " tasks completed.");
jLock.lock();
IMap<String, List<Simulation>> simulationsMap = Hazelcast.getMap(Config.simulationsMap);
gathering = true;
gatherer.gatherResults(simulationsMap, completedMap, cSimulation);
simulationsMap.forceUnlock(cSimulation.getOwner());
if (cSimulation.jobComplete()) {
Utils.emailUser(cSimulation, new File(properties.getProperty("email_complete_template")), properties, "");
IQueue<String> errors = Hazelcast.getQueue(Config.errorQueue);
IMap<String, byte[]> fileQueue = Hazelcast.getMap(Config.fileMap);
Iterator<String> iter = errors.iterator();
while (iter.hasNext()) {
if (iter.next().startsWith(cSimulation.getJobID())) {
iter.remove();
}
}
System.out.println("Error Queue Size: " + errors.size());
fileQueue.remove(cSimulation.getFileKey());
fileQueue.forceUnlock(cSimulation.getFileKey());
System.out.println("File Queue Size: " + fileQueue.size());
}
} else {
completedMap.put(t.getParent().getID(), cSimulation);
}
completedMap.forceUnlock(t.getParent().getID());
txn.commit();
} catch (Throwable e) {
System.out.println("ERROR:");
e.printStackTrace();
txn.rollback();
} finally {
if (gathering) {
jLock.unlock();
}
cLock.unlock();
}
}
| public synchronized void onMessage(Message<Task> message) {
if (message.getMessageObject().getId().equals("")) { //this attempts to gather jobs from the completed map after the gatherer crashed unexpectedly
System.out.println("Checking all results"); //see line 45 in net.pleiades.Gatherer.java
checkAll();
return;
}
Task t = message.getMessageObject();
Lock rLock = Hazelcast.getLock(Config.runningMap);
rLock.lock();
IMap<String, String> runningMap = Hazelcast.getMap(Config.runningMap);
Transaction txn = Hazelcast.getTransaction();
txn.begin();
try {
runningMap.remove(t.getId());
txn.commit();
} catch (Throwable e) {
txn.rollback();
} finally {
runningMap.forceUnlock(t.getId());
rLock.unlock();
}
System.out.println("Task completed:" + message.getMessageObject().getId());
Lock cLock = Hazelcast.getLock(Config.completedMap);
Lock jLock = Hazelcast.getLock(Config.simulationsMap);
cLock.lock();
IMap<String, Simulation> completedMap = Hazelcast.getMap(Config.completedMap);
txn.begin();
boolean gathering = false;
try {
Simulation cSimulation = completedMap.get(t.getParent().getID());
if (cSimulation == null) {
Config.RESULTS_TOPIC.publish(t); //republish this completed task
throw new Exception("No such simulation");
}
cSimulation.completeTask(t, properties);
if (cSimulation.isComplete()) {
completedMap.remove(t.getParent().getID());
System.out.println("\nGathering: " + cSimulation.getID());
System.out.println(cSimulation.getResults().size() + " tasks completed.");
jLock.lock();
IMap<String, List<Simulation>> simulationsMap = Hazelcast.getMap(Config.simulationsMap);
gathering = true;
gatherer.gatherResults(simulationsMap, completedMap, cSimulation);
simulationsMap.forceUnlock(cSimulation.getOwner());
if (cSimulation.jobComplete()) {
Utils.emailUser(cSimulation, new File(properties.getProperty("email_complete_template")), properties, "");
IQueue<String> errors = Hazelcast.getQueue(Config.errorQueue);
IMap<String, byte[]> fileQueue = Hazelcast.getMap(Config.fileMap);
Iterator<String> iter = errors.iterator();
while (iter.hasNext()) {
if (iter.next().startsWith(cSimulation.getJobID())) {
iter.remove();
}
}
System.out.println("Error Queue Size: " + errors.size());
fileQueue.remove(cSimulation.getFileKey());
fileQueue.forceUnlock(cSimulation.getFileKey());
System.out.println("File Queue Size: " + fileQueue.size());
}
} else {
completedMap.put(t.getParent().getID(), cSimulation);
}
completedMap.forceUnlock(t.getParent().getID());
txn.commit();
} catch (Throwable e) {
System.out.println("ERROR:");
e.printStackTrace();
txn.rollback();
} finally {
if (gathering) {
jLock.unlock();
}
cLock.unlock();
}
}
|
diff --git a/extension/richfaces/src/main/java/org/jboss/portletbridge/richfaces/context/FileUploadFacesContextFactory.java b/extension/richfaces/src/main/java/org/jboss/portletbridge/richfaces/context/FileUploadFacesContextFactory.java
index fe97ec4..6c19cb6 100644
--- a/extension/richfaces/src/main/java/org/jboss/portletbridge/richfaces/context/FileUploadFacesContextFactory.java
+++ b/extension/richfaces/src/main/java/org/jboss/portletbridge/richfaces/context/FileUploadFacesContextFactory.java
@@ -1,174 +1,174 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.portletbridge.richfaces.context;
import java.io.File;
import javax.faces.FacesException;
import javax.faces.FacesWrapper;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.context.FacesContextWrapper;
import javax.faces.lifecycle.Lifecycle;
import javax.portlet.ClientDataRequest;
import javax.portlet.PortletContext;
import javax.portlet.ResourceRequest;
import javax.servlet.http.HttpServletRequest;
import org.jboss.portletbridge.richfaces.request.HttpServletRequestAdapter;
import org.jboss.portletbridge.richfaces.request.MultipartResourceRequest25;
import org.jboss.portletbridge.richfaces.request.MultipartResourceRequestSizeExceeded;
import org.richfaces.request.MultipartRequest;
import org.richfaces.request.MultipartRequestParser;
import org.richfaces.request.ProgressControl;
/**
* @author <a href="http://community.jboss.org/people/kenfinni">Ken Finnigan</a>
*/
public class FileUploadFacesContextFactory extends FacesContextFactory implements FacesWrapper<FacesContextFactory> {
private FacesContextFactory wrappedFactory;
public FileUploadFacesContextFactory(FacesContextFactory wrappedFactory) {
super();
this.wrappedFactory = wrappedFactory;
}
@Override
public FacesContextFactory getWrapped() {
return this.wrappedFactory;
}
/**
* @see javax.faces.context.FacesContextFactory#getFacesContext(java.lang.Object, java.lang.Object, java.lang.Object,
* javax.faces.lifecycle.Lifecycle)
*/
@Override
public FacesContext getFacesContext(Object context, Object request, Object response, Lifecycle lifecycle)
throws FacesException {
if (request instanceof ClientDataRequest) {
ClientDataRequest clientRequest = (ClientDataRequest) request;
if (null != clientRequest.getContentType() && clientRequest.getContentType().startsWith("multipart/")) {
String uid = clientRequest.getParameter(org.richfaces.context.FileUploadFacesContextFactory.UID_KEY);
if (null != uid) {
- long contentLength = Long.parseLong(clientRequest.getProperty("content-length"));
+ long contentLength = clientRequest.getContentLength();
ProgressControl progressControl = new ProgressControl(uid, contentLength);
HttpServletRequest wrappedRequest = wrapMultipartRequestServlet25((PortletContext) context, clientRequest,
uid, contentLength, progressControl);
FacesContext facesContext = wrappedFactory.getFacesContext(context, wrappedRequest, response, lifecycle);
progressControl.setContextMap(facesContext.getExternalContext().getSessionMap());
return new FileUploadFacesContext(facesContext);
}
}
}
return wrappedFactory.getFacesContext(context, request, response, lifecycle);
}
private HttpServletRequest wrapMultipartRequestServlet25(PortletContext portletContext, ClientDataRequest request,
String uploadId, long contentLength, ProgressControl progressControl) {
HttpServletRequest multipartRequest;
HttpServletRequestAdapter adapter = new HttpServletRequestAdapter(request);
long maxRequestSize = getMaxRequestSize(portletContext);
if (maxRequestSize == 0 || contentLength <= maxRequestSize) {
boolean createTempFiles = isCreateTempFiles(portletContext);
String tempFilesDirectory = getTempFilesDirectory(portletContext);
MultipartRequestParser requestParser = new MultipartRequestParser(adapter, createTempFiles, tempFilesDirectory,
progressControl);
multipartRequest = new MultipartResourceRequest25((ResourceRequest)request, adapter, uploadId, progressControl, requestParser);
} else {
multipartRequest = new MultipartResourceRequestSizeExceeded((ResourceRequest)request, adapter, uploadId, progressControl);
}
request.setAttribute(MultipartRequest.REQUEST_ATTRIBUTE_NAME, multipartRequest);
return multipartRequest;
}
private long getMaxRequestSize(PortletContext portletContext) {
String param = portletContext.getInitParameter("org.richfaces.fileUpload.maxRequestSize");
if (param != null) {
return Long.parseLong(param);
}
return 0;
}
private boolean isCreateTempFiles(PortletContext portletContext) {
String param = portletContext.getInitParameter("org.richfaces.fileUpload.createTempFiles");
if (param != null) {
return Boolean.parseBoolean(param);
}
return true;
}
private String getTempFilesDirectory(PortletContext portletContext) {
String result = portletContext.getInitParameter("org.richfaces.fileUpload.tempFilesDirectory");
if (result == null) {
File servletTempDir = (File) portletContext.getAttribute("javax.servlet.context.tempdir");
if (servletTempDir != null) {
result = servletTempDir.getAbsolutePath();
}
}
if (result == null) {
result = new File(System.getProperty("java.io.tmpdir")).getAbsolutePath();
}
return result;
}
private static final class FileUploadFacesContext extends FacesContextWrapper {
private FacesContext wrappedContext;
public FileUploadFacesContext(FacesContext facesContext) {
super();
this.wrappedContext = facesContext;
}
@Override
public FacesContext getWrapped() {
return wrappedContext;
}
@Override
public void release() {
MultipartRequest multipartRequest = (MultipartRequest) getExternalContext().getRequestMap().get(
MultipartRequest.REQUEST_ATTRIBUTE_NAME);
if (multipartRequest != null) {
multipartRequest.release();
}
super.release();
}
}
}
| true | true | public FacesContext getFacesContext(Object context, Object request, Object response, Lifecycle lifecycle)
throws FacesException {
if (request instanceof ClientDataRequest) {
ClientDataRequest clientRequest = (ClientDataRequest) request;
if (null != clientRequest.getContentType() && clientRequest.getContentType().startsWith("multipart/")) {
String uid = clientRequest.getParameter(org.richfaces.context.FileUploadFacesContextFactory.UID_KEY);
if (null != uid) {
long contentLength = Long.parseLong(clientRequest.getProperty("content-length"));
ProgressControl progressControl = new ProgressControl(uid, contentLength);
HttpServletRequest wrappedRequest = wrapMultipartRequestServlet25((PortletContext) context, clientRequest,
uid, contentLength, progressControl);
FacesContext facesContext = wrappedFactory.getFacesContext(context, wrappedRequest, response, lifecycle);
progressControl.setContextMap(facesContext.getExternalContext().getSessionMap());
return new FileUploadFacesContext(facesContext);
}
}
}
return wrappedFactory.getFacesContext(context, request, response, lifecycle);
}
| public FacesContext getFacesContext(Object context, Object request, Object response, Lifecycle lifecycle)
throws FacesException {
if (request instanceof ClientDataRequest) {
ClientDataRequest clientRequest = (ClientDataRequest) request;
if (null != clientRequest.getContentType() && clientRequest.getContentType().startsWith("multipart/")) {
String uid = clientRequest.getParameter(org.richfaces.context.FileUploadFacesContextFactory.UID_KEY);
if (null != uid) {
long contentLength = clientRequest.getContentLength();
ProgressControl progressControl = new ProgressControl(uid, contentLength);
HttpServletRequest wrappedRequest = wrapMultipartRequestServlet25((PortletContext) context, clientRequest,
uid, contentLength, progressControl);
FacesContext facesContext = wrappedFactory.getFacesContext(context, wrappedRequest, response, lifecycle);
progressControl.setContextMap(facesContext.getExternalContext().getSessionMap());
return new FileUploadFacesContext(facesContext);
}
}
}
return wrappedFactory.getFacesContext(context, request, response, lifecycle);
}
|
diff --git a/src/com/matejdro/bukkit/portalstick/commands/RegionToolCommand.java b/src/com/matejdro/bukkit/portalstick/commands/RegionToolCommand.java
index 304ca2a..64bcc56 100644
--- a/src/com/matejdro/bukkit/portalstick/commands/RegionToolCommand.java
+++ b/src/com/matejdro/bukkit/portalstick/commands/RegionToolCommand.java
@@ -1,39 +1,39 @@
package com.matejdro.bukkit.portalstick.commands;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.matejdro.bukkit.portalstick.User;
import com.matejdro.bukkit.portalstick.UserManager;
import com.matejdro.bukkit.portalstick.util.Config;
import com.matejdro.bukkit.portalstick.util.Permission;
import com.matejdro.bukkit.portalstick.util.Util;
public class RegionToolCommand extends BaseCommand {
public RegionToolCommand() {
name = "regiontool";
argLength = 0;
usage = "<- enable/disable region selection mode";
}
public boolean execute() {
User user = UserManager.getUser(player);
if (user.getUsingTool()) {
user.setUsingTool(false);
Util.sendMessage(sender, "&aPortal region tool disabled");
}
else {
user.setUsingTool(true);
Util.sendMessage(sender, "&aPortal region tool enabled.`n- Left click to set position one`n- Right click to set position two");
if (!player.getInventory().contains(Config.RegionTool))
- player.getInventory().addItem(new ItemStack(Config.RegionTool));
+ player.getInventory().addItem(new ItemStack(Config.RegionTool, 1));
}
return true;
}
public boolean permission(Player player) {
return Permission.adminRegions(player);
}
}
| true | true | public boolean execute() {
User user = UserManager.getUser(player);
if (user.getUsingTool()) {
user.setUsingTool(false);
Util.sendMessage(sender, "&aPortal region tool disabled");
}
else {
user.setUsingTool(true);
Util.sendMessage(sender, "&aPortal region tool enabled.`n- Left click to set position one`n- Right click to set position two");
if (!player.getInventory().contains(Config.RegionTool))
player.getInventory().addItem(new ItemStack(Config.RegionTool));
}
return true;
}
| public boolean execute() {
User user = UserManager.getUser(player);
if (user.getUsingTool()) {
user.setUsingTool(false);
Util.sendMessage(sender, "&aPortal region tool disabled");
}
else {
user.setUsingTool(true);
Util.sendMessage(sender, "&aPortal region tool enabled.`n- Left click to set position one`n- Right click to set position two");
if (!player.getInventory().contains(Config.RegionTool))
player.getInventory().addItem(new ItemStack(Config.RegionTool, 1));
}
return true;
}
|
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/NycFareServiceImpl.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/NycFareServiceImpl.java
index f50f89bcb..03ec3ad5a 100644
--- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/NycFareServiceImpl.java
+++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/NycFareServiceImpl.java
@@ -1,379 +1,379 @@
/* 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 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.routing.impl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Currency;
import java.util.LinkedList;
import java.util.List;
import org.onebusaway.gtfs.model.AgencyAndId;
import org.onebusaway.gtfs.model.Route;
import org.onebusaway.gtfs.model.Trip;
import org.opentripplanner.routing.core.Fare;
import org.opentripplanner.routing.core.State;
import org.opentripplanner.routing.core.WrappedCurrency;
import org.opentripplanner.routing.core.Fare.FareType;
import org.opentripplanner.routing.edgetype.HopEdge;
import org.opentripplanner.routing.edgetype.PatternBoard;
import org.opentripplanner.routing.edgetype.StreetEdge;
import org.opentripplanner.routing.graph.Edge;
import org.opentripplanner.routing.services.FareService;
import org.opentripplanner.routing.spt.GraphPath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
enum NycFareState {
INIT,
SUBWAY_PRE_TRANSFER,
SUBWAY_PRE_TRANSFER_WALKED,
SUBWAY_POST_TRANSFER,
SIR_PRE_TRANSFER,
SIR_POST_TRANSFER_FROM_SUBWAY,
SIR_POST_TRANSFER_FROM_BUS,
EXPENSIVE_EXPRESS_BUS,
BUS_PRE_TRANSFER, CANARSIE,
}
/**
* This handles the New York City MTA's baroque fare rules for subways and buses
* with the following limitations:
* (1) the two hour limit on transfers is not enforced
* (2) the b61/b62 special case is not handled
* (3) MNR, LIRR, and LI Bus are not supported -- only subways and buses
*/
public class NycFareServiceImpl implements FareService, Serializable {
private static final Logger _log = LoggerFactory.getLogger(PatternBoard.class);
private static final long serialVersionUID = 1L;
private static final float ORDINARY_FARE = 2.25f;
private static final float EXPRESS_FARE = 5.50f;
private static final float EXPENSIVE_EXPRESS_FARE = 7.50f; // BxM4C only
public NycFareServiceImpl() {
}
@Override
public Fare getCost(GraphPath path) {
final List<AgencyAndId> SIR_PAID_STOPS = makeMtaStopList("S31", "S30");
final List<AgencyAndId> SUBWAY_FREE_TRANSFER_STOPS = makeMtaStopList(
"R11", "B08", "629");
final List<AgencyAndId> SIR_BONUS_STOPS = makeMtaStopList("140", "420",
"419", "418", "M22", "M23", "R27", "R26");
final List<AgencyAndId> SIR_BONUS_ROUTES = makeMtaStopList("M5", "M20",
"M15-SBS");
final List<AgencyAndId> CANARSIE = makeMtaStopList("L29", "303345");
LinkedList<State> states = path.states;
// create rides
List<Ride> rides = new ArrayList<Ride>();
Ride newRide = null;
final int SUBWAY = 1;
final int SIR = 2;
final int LOCAL_BUS = 3;
final int EXPRESS_BUS = 30;
final int EXPENSIVE_EXPRESS_BUS = 34;
final int WALK = -1;
for (State state : states) {
Edge backEdge = state.getBackEdge();
if (backEdge instanceof StreetEdge) {
if (newRide == null || !newRide.classifier.equals(WALK)) {
if (rides.size() == 0 || !rides.get(rides.size() - 1).classifier.equals(WALK)) {
newRide = new Ride();
newRide.classifier = WALK;
rides.add(newRide);
}
}
continue;
}
if (!(backEdge instanceof HopEdge)) {
newRide = null;
continue;
}
AgencyAndId routeId = state.getRoute();
if (routeId == null) {
newRide = null;
} else {
if (newRide == null || !routeId.equals(newRide.route)) {
newRide = new Ride();
rides.add(newRide);
newRide.firstStop = ((HopEdge) backEdge).getStartStop();
newRide.route = routeId;
Trip trip = state.getBackEdgeNarrative().getTrip();
Route route = trip.getRoute();
int type = route.getType();
newRide.classifier = type;
String shortName = route.getShortName();
if (shortName == null ) {
newRide.classifier = SUBWAY;
} else if (shortName.equals("BxM4C")) {
newRide.classifier = EXPENSIVE_EXPRESS_BUS;
} else if (shortName.startsWith("X")
|| shortName.startsWith("BxM")
|| shortName.startsWith("QM")
|| shortName.startsWith("BM")) {
newRide.classifier = EXPRESS_BUS; // Express bus
}
newRide.startTime = state.getTime();
}
newRide.lastStop = ((HopEdge) backEdge).getStartStop();
}
}
// There are no rides, so there's no fare.
if (rides.size() == 0) {
return null;
}
NycFareState state = NycFareState.INIT;
boolean lexFreeTransfer = false;
boolean canarsieFreeTransfer = false;
boolean siLocalBus = false;
boolean sirBonusTransfer = false;
float totalFare = 0;
for (Ride ride : rides) {
AgencyAndId firstStopId = null;
AgencyAndId lastStopId = null;
if (ride.firstStop != null) {
firstStopId = ride.firstStop.getId();
lastStopId = ride.lastStop.getId();
}
switch (state) {
case INIT:
lexFreeTransfer = siLocalBus = canarsieFreeTransfer = false;
if (ride.classifier.equals(WALK)) {
// walking keeps you in init
} else if (ride.classifier.equals(SUBWAY)) {
state = NycFareState.SUBWAY_PRE_TRANSFER;
totalFare += ORDINARY_FARE;
- if (SUBWAY_FREE_TRANSFER_STOPS.contains(ride.lastStop)) {
+ if (SUBWAY_FREE_TRANSFER_STOPS.contains(ride.lastStop.getId())) {
lexFreeTransfer = true;
}
- if (CANARSIE.contains(ride.lastStop)) {
+ if (CANARSIE.contains(ride.lastStop.getId())) {
canarsieFreeTransfer = true;
}
} else if (ride.classifier.equals(SIR)) {
state = NycFareState.SIR_PRE_TRANSFER;
if (SIR_PAID_STOPS.contains(firstStopId)
|| SIR_PAID_STOPS.contains(lastStopId)) {
totalFare += ORDINARY_FARE;
}
} else if (ride.classifier.equals(LOCAL_BUS)) {
state = NycFareState.BUS_PRE_TRANSFER;
totalFare += ORDINARY_FARE;
- if (CANARSIE.contains(ride.lastStop)) {
+ if (CANARSIE.contains(ride.lastStop.getId())) {
canarsieFreeTransfer = true;
}
siLocalBus = ride.route.getId().startsWith("S");
} else if (ride.classifier.equals(EXPRESS_BUS)) {
state = NycFareState.BUS_PRE_TRANSFER;
totalFare += EXPRESS_FARE;
} else if (ride.classifier.equals(EXPENSIVE_EXPRESS_BUS)) {
state = NycFareState.EXPENSIVE_EXPRESS_BUS;
totalFare += EXPENSIVE_EXPRESS_FARE;
}
break;
case SUBWAY_PRE_TRANSFER_WALKED:
if (ride.classifier.equals(SUBWAY)) {
// subway-to-subway transfers are verbotten except at
// lex and 59/63
if (!(lexFreeTransfer && SUBWAY_FREE_TRANSFER_STOPS
- .contains(ride.firstStop))) {
+ .contains(ride.firstStop.getId()))) {
totalFare += ORDINARY_FARE;
}
lexFreeTransfer = canarsieFreeTransfer = false;
- if (SUBWAY_FREE_TRANSFER_STOPS.contains(ride.lastStop)) {
+ if (SUBWAY_FREE_TRANSFER_STOPS.contains(ride.lastStop.getId())) {
lexFreeTransfer = true;
}
- if (CANARSIE.contains(ride.lastStop)) {
+ if (CANARSIE.contains(ride.lastStop.getId())) {
canarsieFreeTransfer = true;
}
}
/* FALL THROUGH */
case SUBWAY_PRE_TRANSFER:
// it will always be possible to transfer from the first subway
// trip to anywhere,
// since no sequence of subway trips takes greater than two
// hours (if only just)
if (ride.classifier.equals(WALK)) {
state = NycFareState.SUBWAY_PRE_TRANSFER_WALKED;
} else if (ride.classifier.equals(SIR)) {
state = NycFareState.SIR_POST_TRANSFER_FROM_SUBWAY;
} else if (ride.classifier.equals(LOCAL_BUS)) {
- if (CANARSIE.contains(ride.firstStop)
+ if (CANARSIE.contains(ride.firstStop.getId())
&& canarsieFreeTransfer) {
state = NycFareState.BUS_PRE_TRANSFER;
} else {
state = NycFareState.INIT;
}
} else if (ride.classifier.equals(EXPRESS_BUS)) {
// need to pay the upgrade cost
totalFare += EXPRESS_FARE - ORDINARY_FARE;
} else if (ride.classifier.equals(EXPENSIVE_EXPRESS_BUS)) {
totalFare += EXPENSIVE_EXPRESS_FARE; // no transfers to the
// BxMM4C
}
break;
case BUS_PRE_TRANSFER:
if (ride.classifier.equals(SUBWAY)) {
- if (CANARSIE.contains(ride.firstStop)
+ if (CANARSIE.contains(ride.firstStop.getId())
&& canarsieFreeTransfer) {
state = NycFareState.SUBWAY_PRE_TRANSFER;
} else {
state = NycFareState.INIT;
}
} else if (ride.classifier.equals(SIR)) {
if (siLocalBus) {
// SI local bus to SIR, so it is as if we started on the
// SIR (except that when we enter the bus or subway system we need to do
// so at certain places)
sirBonusTransfer = true;
state = NycFareState.SIR_PRE_TRANSFER;
} else {
//transfers exhausted
state = NycFareState.INIT;
}
} else if (ride.classifier.equals(LOCAL_BUS)) {
state = NycFareState.INIT;
} else if (ride.classifier.equals(EXPRESS_BUS)) {
// need to pay the upgrade cost
totalFare += EXPRESS_FARE - ORDINARY_FARE;
state = NycFareState.INIT;
} else if (ride.classifier.equals(EXPENSIVE_EXPRESS_BUS)) {
totalFare += EXPENSIVE_EXPRESS_FARE;
// no transfers to the BxMM4C
}
break;
case SIR_PRE_TRANSFER:
if (ride.classifier.equals(SUBWAY)) {
- if (sirBonusTransfer && !SIR_BONUS_STOPS.contains(ride.firstStop)) {
+ if (sirBonusTransfer && !SIR_BONUS_STOPS.contains(ride.firstStop.getId())) {
//we were relying on the bonus transfer to be in the "pre-transfer state",
//but the bonus transfer does not apply here
totalFare += ORDINARY_FARE;
}
- if (CANARSIE.contains(ride.lastStop)) {
+ if (CANARSIE.contains(ride.lastStop.getId())) {
canarsieFreeTransfer = true;
}
state = NycFareState.SUBWAY_POST_TRANSFER;
} else if (ride.classifier.equals(SIR)) {
/* should not happen, and unhandled */
_log.warn("Should not transfer from SIR to SIR");
} else if (ride.classifier.equals(LOCAL_BUS)) {
if (!SIR_BONUS_ROUTES.contains(ride.route)) {
totalFare += ORDINARY_FARE;
}
state = NycFareState.BUS_PRE_TRANSFER;
} else if (ride.classifier.equals(EXPRESS_BUS)) {
totalFare += EXPRESS_BUS;
state = NycFareState.BUS_PRE_TRANSFER;
} else if (ride.classifier.equals(EXPENSIVE_EXPRESS_BUS)) {
totalFare += EXPENSIVE_EXPRESS_BUS;
state = NycFareState.BUS_PRE_TRANSFER;
}
break;
case SIR_POST_TRANSFER_FROM_SUBWAY:
if (ride.classifier.equals(SUBWAY)) {
/* should not happen */
totalFare += ORDINARY_FARE;
state = NycFareState.SUBWAY_PRE_TRANSFER;
} else if (ride.classifier.equals(SIR)) {
/* should not happen, and unhandled */
_log.warn("Should not transfer from SIR to SIR");
} else if (ride.classifier.equals(LOCAL_BUS)) {
if (!ride.route.getId().startsWith("S")) {
totalFare += ORDINARY_FARE;
state = NycFareState.BUS_PRE_TRANSFER;
} else {
state = NycFareState.INIT;
}
} else if (ride.classifier.equals(EXPRESS_BUS)) {
// need to pay the full cost
totalFare += EXPRESS_FARE;
state = NycFareState.INIT;
} else if (ride.classifier.equals(EXPENSIVE_EXPRESS_BUS)) {
/* should not happen */
// no transfers to the BxMM4C
totalFare += EXPENSIVE_EXPRESS_FARE;
state = NycFareState.BUS_PRE_TRANSFER;
}
break;
case SUBWAY_POST_TRANSFER:
if (ride.classifier.equals(WALK)) {
if (!canarsieFreeTransfer) {
/* note: if we end up walking to another subway after alighting
* at Canarsie, we will mistakenly not be charged, but nobody
* would ever do this */
state = NycFareState.INIT;
}
} else if (ride.classifier.equals(SIR)) {
totalFare += ORDINARY_FARE;
state = NycFareState.SIR_PRE_TRANSFER;
} else if (ride.classifier.equals(LOCAL_BUS)) {
- if (!(CANARSIE.contains(ride.firstStop)
+ if (!(CANARSIE.contains(ride.firstStop.getId())
&& canarsieFreeTransfer)) {
totalFare += ORDINARY_FARE;
}
state = NycFareState.INIT;
} else if (ride.classifier.equals(SUBWAY)) {
//walking transfer
totalFare += ORDINARY_FARE;
state = NycFareState.SUBWAY_PRE_TRANSFER;
} else if (ride.classifier.equals(EXPRESS_BUS)) {
totalFare += EXPRESS_FARE;
state = NycFareState.BUS_PRE_TRANSFER;
} else if (ride.classifier.equals(EXPENSIVE_EXPRESS_BUS)) {
totalFare += EXPENSIVE_EXPRESS_FARE;
state = NycFareState.BUS_PRE_TRANSFER;
}
}
}
Currency currency = Currency.getInstance("USD");
Fare fare = new Fare();
fare.addFare(FareType.regular, new WrappedCurrency(currency),
(int) Math.round(totalFare
* Math.pow(10, currency.getDefaultFractionDigits())));
return fare;
}
private List<AgencyAndId> makeMtaStopList(String... stops) {
ArrayList<AgencyAndId> out = new ArrayList<AgencyAndId>();
for (String stop : stops) {
out.add(new AgencyAndId("MTA NYCT", stop));
out.add(new AgencyAndId("MTA NYCT", stop + "N"));
out.add(new AgencyAndId("MTA NYCT", stop + "S"));
}
return out;
}
}
| false | true | public Fare getCost(GraphPath path) {
final List<AgencyAndId> SIR_PAID_STOPS = makeMtaStopList("S31", "S30");
final List<AgencyAndId> SUBWAY_FREE_TRANSFER_STOPS = makeMtaStopList(
"R11", "B08", "629");
final List<AgencyAndId> SIR_BONUS_STOPS = makeMtaStopList("140", "420",
"419", "418", "M22", "M23", "R27", "R26");
final List<AgencyAndId> SIR_BONUS_ROUTES = makeMtaStopList("M5", "M20",
"M15-SBS");
final List<AgencyAndId> CANARSIE = makeMtaStopList("L29", "303345");
LinkedList<State> states = path.states;
// create rides
List<Ride> rides = new ArrayList<Ride>();
Ride newRide = null;
final int SUBWAY = 1;
final int SIR = 2;
final int LOCAL_BUS = 3;
final int EXPRESS_BUS = 30;
final int EXPENSIVE_EXPRESS_BUS = 34;
final int WALK = -1;
for (State state : states) {
Edge backEdge = state.getBackEdge();
if (backEdge instanceof StreetEdge) {
if (newRide == null || !newRide.classifier.equals(WALK)) {
if (rides.size() == 0 || !rides.get(rides.size() - 1).classifier.equals(WALK)) {
newRide = new Ride();
newRide.classifier = WALK;
rides.add(newRide);
}
}
continue;
}
if (!(backEdge instanceof HopEdge)) {
newRide = null;
continue;
}
AgencyAndId routeId = state.getRoute();
if (routeId == null) {
newRide = null;
} else {
if (newRide == null || !routeId.equals(newRide.route)) {
newRide = new Ride();
rides.add(newRide);
newRide.firstStop = ((HopEdge) backEdge).getStartStop();
newRide.route = routeId;
Trip trip = state.getBackEdgeNarrative().getTrip();
Route route = trip.getRoute();
int type = route.getType();
newRide.classifier = type;
String shortName = route.getShortName();
if (shortName == null ) {
newRide.classifier = SUBWAY;
} else if (shortName.equals("BxM4C")) {
newRide.classifier = EXPENSIVE_EXPRESS_BUS;
} else if (shortName.startsWith("X")
|| shortName.startsWith("BxM")
|| shortName.startsWith("QM")
|| shortName.startsWith("BM")) {
newRide.classifier = EXPRESS_BUS; // Express bus
}
newRide.startTime = state.getTime();
}
newRide.lastStop = ((HopEdge) backEdge).getStartStop();
}
}
// There are no rides, so there's no fare.
if (rides.size() == 0) {
return null;
}
NycFareState state = NycFareState.INIT;
boolean lexFreeTransfer = false;
boolean canarsieFreeTransfer = false;
boolean siLocalBus = false;
boolean sirBonusTransfer = false;
float totalFare = 0;
for (Ride ride : rides) {
AgencyAndId firstStopId = null;
AgencyAndId lastStopId = null;
if (ride.firstStop != null) {
firstStopId = ride.firstStop.getId();
lastStopId = ride.lastStop.getId();
}
switch (state) {
case INIT:
lexFreeTransfer = siLocalBus = canarsieFreeTransfer = false;
if (ride.classifier.equals(WALK)) {
// walking keeps you in init
} else if (ride.classifier.equals(SUBWAY)) {
state = NycFareState.SUBWAY_PRE_TRANSFER;
totalFare += ORDINARY_FARE;
if (SUBWAY_FREE_TRANSFER_STOPS.contains(ride.lastStop)) {
lexFreeTransfer = true;
}
if (CANARSIE.contains(ride.lastStop)) {
canarsieFreeTransfer = true;
}
} else if (ride.classifier.equals(SIR)) {
state = NycFareState.SIR_PRE_TRANSFER;
if (SIR_PAID_STOPS.contains(firstStopId)
|| SIR_PAID_STOPS.contains(lastStopId)) {
totalFare += ORDINARY_FARE;
}
} else if (ride.classifier.equals(LOCAL_BUS)) {
state = NycFareState.BUS_PRE_TRANSFER;
totalFare += ORDINARY_FARE;
if (CANARSIE.contains(ride.lastStop)) {
canarsieFreeTransfer = true;
}
siLocalBus = ride.route.getId().startsWith("S");
} else if (ride.classifier.equals(EXPRESS_BUS)) {
state = NycFareState.BUS_PRE_TRANSFER;
totalFare += EXPRESS_FARE;
} else if (ride.classifier.equals(EXPENSIVE_EXPRESS_BUS)) {
state = NycFareState.EXPENSIVE_EXPRESS_BUS;
totalFare += EXPENSIVE_EXPRESS_FARE;
}
break;
case SUBWAY_PRE_TRANSFER_WALKED:
if (ride.classifier.equals(SUBWAY)) {
// subway-to-subway transfers are verbotten except at
// lex and 59/63
if (!(lexFreeTransfer && SUBWAY_FREE_TRANSFER_STOPS
.contains(ride.firstStop))) {
totalFare += ORDINARY_FARE;
}
lexFreeTransfer = canarsieFreeTransfer = false;
if (SUBWAY_FREE_TRANSFER_STOPS.contains(ride.lastStop)) {
lexFreeTransfer = true;
}
if (CANARSIE.contains(ride.lastStop)) {
canarsieFreeTransfer = true;
}
}
/* FALL THROUGH */
case SUBWAY_PRE_TRANSFER:
// it will always be possible to transfer from the first subway
// trip to anywhere,
// since no sequence of subway trips takes greater than two
// hours (if only just)
if (ride.classifier.equals(WALK)) {
state = NycFareState.SUBWAY_PRE_TRANSFER_WALKED;
} else if (ride.classifier.equals(SIR)) {
state = NycFareState.SIR_POST_TRANSFER_FROM_SUBWAY;
} else if (ride.classifier.equals(LOCAL_BUS)) {
if (CANARSIE.contains(ride.firstStop)
&& canarsieFreeTransfer) {
state = NycFareState.BUS_PRE_TRANSFER;
} else {
state = NycFareState.INIT;
}
} else if (ride.classifier.equals(EXPRESS_BUS)) {
// need to pay the upgrade cost
totalFare += EXPRESS_FARE - ORDINARY_FARE;
} else if (ride.classifier.equals(EXPENSIVE_EXPRESS_BUS)) {
totalFare += EXPENSIVE_EXPRESS_FARE; // no transfers to the
// BxMM4C
}
break;
case BUS_PRE_TRANSFER:
if (ride.classifier.equals(SUBWAY)) {
if (CANARSIE.contains(ride.firstStop)
&& canarsieFreeTransfer) {
state = NycFareState.SUBWAY_PRE_TRANSFER;
} else {
state = NycFareState.INIT;
}
} else if (ride.classifier.equals(SIR)) {
if (siLocalBus) {
// SI local bus to SIR, so it is as if we started on the
// SIR (except that when we enter the bus or subway system we need to do
// so at certain places)
sirBonusTransfer = true;
state = NycFareState.SIR_PRE_TRANSFER;
} else {
//transfers exhausted
state = NycFareState.INIT;
}
} else if (ride.classifier.equals(LOCAL_BUS)) {
state = NycFareState.INIT;
} else if (ride.classifier.equals(EXPRESS_BUS)) {
// need to pay the upgrade cost
totalFare += EXPRESS_FARE - ORDINARY_FARE;
state = NycFareState.INIT;
} else if (ride.classifier.equals(EXPENSIVE_EXPRESS_BUS)) {
totalFare += EXPENSIVE_EXPRESS_FARE;
// no transfers to the BxMM4C
}
break;
case SIR_PRE_TRANSFER:
if (ride.classifier.equals(SUBWAY)) {
if (sirBonusTransfer && !SIR_BONUS_STOPS.contains(ride.firstStop)) {
//we were relying on the bonus transfer to be in the "pre-transfer state",
//but the bonus transfer does not apply here
totalFare += ORDINARY_FARE;
}
if (CANARSIE.contains(ride.lastStop)) {
canarsieFreeTransfer = true;
}
state = NycFareState.SUBWAY_POST_TRANSFER;
} else if (ride.classifier.equals(SIR)) {
/* should not happen, and unhandled */
_log.warn("Should not transfer from SIR to SIR");
} else if (ride.classifier.equals(LOCAL_BUS)) {
if (!SIR_BONUS_ROUTES.contains(ride.route)) {
totalFare += ORDINARY_FARE;
}
state = NycFareState.BUS_PRE_TRANSFER;
} else if (ride.classifier.equals(EXPRESS_BUS)) {
totalFare += EXPRESS_BUS;
state = NycFareState.BUS_PRE_TRANSFER;
} else if (ride.classifier.equals(EXPENSIVE_EXPRESS_BUS)) {
totalFare += EXPENSIVE_EXPRESS_BUS;
state = NycFareState.BUS_PRE_TRANSFER;
}
break;
case SIR_POST_TRANSFER_FROM_SUBWAY:
if (ride.classifier.equals(SUBWAY)) {
/* should not happen */
totalFare += ORDINARY_FARE;
state = NycFareState.SUBWAY_PRE_TRANSFER;
} else if (ride.classifier.equals(SIR)) {
/* should not happen, and unhandled */
_log.warn("Should not transfer from SIR to SIR");
} else if (ride.classifier.equals(LOCAL_BUS)) {
if (!ride.route.getId().startsWith("S")) {
totalFare += ORDINARY_FARE;
state = NycFareState.BUS_PRE_TRANSFER;
} else {
state = NycFareState.INIT;
}
} else if (ride.classifier.equals(EXPRESS_BUS)) {
// need to pay the full cost
totalFare += EXPRESS_FARE;
state = NycFareState.INIT;
} else if (ride.classifier.equals(EXPENSIVE_EXPRESS_BUS)) {
/* should not happen */
// no transfers to the BxMM4C
totalFare += EXPENSIVE_EXPRESS_FARE;
state = NycFareState.BUS_PRE_TRANSFER;
}
break;
case SUBWAY_POST_TRANSFER:
if (ride.classifier.equals(WALK)) {
if (!canarsieFreeTransfer) {
/* note: if we end up walking to another subway after alighting
* at Canarsie, we will mistakenly not be charged, but nobody
* would ever do this */
state = NycFareState.INIT;
}
} else if (ride.classifier.equals(SIR)) {
totalFare += ORDINARY_FARE;
state = NycFareState.SIR_PRE_TRANSFER;
} else if (ride.classifier.equals(LOCAL_BUS)) {
if (!(CANARSIE.contains(ride.firstStop)
&& canarsieFreeTransfer)) {
totalFare += ORDINARY_FARE;
}
state = NycFareState.INIT;
} else if (ride.classifier.equals(SUBWAY)) {
//walking transfer
totalFare += ORDINARY_FARE;
state = NycFareState.SUBWAY_PRE_TRANSFER;
} else if (ride.classifier.equals(EXPRESS_BUS)) {
totalFare += EXPRESS_FARE;
state = NycFareState.BUS_PRE_TRANSFER;
} else if (ride.classifier.equals(EXPENSIVE_EXPRESS_BUS)) {
totalFare += EXPENSIVE_EXPRESS_FARE;
state = NycFareState.BUS_PRE_TRANSFER;
}
}
}
Currency currency = Currency.getInstance("USD");
Fare fare = new Fare();
fare.addFare(FareType.regular, new WrappedCurrency(currency),
(int) Math.round(totalFare
* Math.pow(10, currency.getDefaultFractionDigits())));
return fare;
}
| public Fare getCost(GraphPath path) {
final List<AgencyAndId> SIR_PAID_STOPS = makeMtaStopList("S31", "S30");
final List<AgencyAndId> SUBWAY_FREE_TRANSFER_STOPS = makeMtaStopList(
"R11", "B08", "629");
final List<AgencyAndId> SIR_BONUS_STOPS = makeMtaStopList("140", "420",
"419", "418", "M22", "M23", "R27", "R26");
final List<AgencyAndId> SIR_BONUS_ROUTES = makeMtaStopList("M5", "M20",
"M15-SBS");
final List<AgencyAndId> CANARSIE = makeMtaStopList("L29", "303345");
LinkedList<State> states = path.states;
// create rides
List<Ride> rides = new ArrayList<Ride>();
Ride newRide = null;
final int SUBWAY = 1;
final int SIR = 2;
final int LOCAL_BUS = 3;
final int EXPRESS_BUS = 30;
final int EXPENSIVE_EXPRESS_BUS = 34;
final int WALK = -1;
for (State state : states) {
Edge backEdge = state.getBackEdge();
if (backEdge instanceof StreetEdge) {
if (newRide == null || !newRide.classifier.equals(WALK)) {
if (rides.size() == 0 || !rides.get(rides.size() - 1).classifier.equals(WALK)) {
newRide = new Ride();
newRide.classifier = WALK;
rides.add(newRide);
}
}
continue;
}
if (!(backEdge instanceof HopEdge)) {
newRide = null;
continue;
}
AgencyAndId routeId = state.getRoute();
if (routeId == null) {
newRide = null;
} else {
if (newRide == null || !routeId.equals(newRide.route)) {
newRide = new Ride();
rides.add(newRide);
newRide.firstStop = ((HopEdge) backEdge).getStartStop();
newRide.route = routeId;
Trip trip = state.getBackEdgeNarrative().getTrip();
Route route = trip.getRoute();
int type = route.getType();
newRide.classifier = type;
String shortName = route.getShortName();
if (shortName == null ) {
newRide.classifier = SUBWAY;
} else if (shortName.equals("BxM4C")) {
newRide.classifier = EXPENSIVE_EXPRESS_BUS;
} else if (shortName.startsWith("X")
|| shortName.startsWith("BxM")
|| shortName.startsWith("QM")
|| shortName.startsWith("BM")) {
newRide.classifier = EXPRESS_BUS; // Express bus
}
newRide.startTime = state.getTime();
}
newRide.lastStop = ((HopEdge) backEdge).getStartStop();
}
}
// There are no rides, so there's no fare.
if (rides.size() == 0) {
return null;
}
NycFareState state = NycFareState.INIT;
boolean lexFreeTransfer = false;
boolean canarsieFreeTransfer = false;
boolean siLocalBus = false;
boolean sirBonusTransfer = false;
float totalFare = 0;
for (Ride ride : rides) {
AgencyAndId firstStopId = null;
AgencyAndId lastStopId = null;
if (ride.firstStop != null) {
firstStopId = ride.firstStop.getId();
lastStopId = ride.lastStop.getId();
}
switch (state) {
case INIT:
lexFreeTransfer = siLocalBus = canarsieFreeTransfer = false;
if (ride.classifier.equals(WALK)) {
// walking keeps you in init
} else if (ride.classifier.equals(SUBWAY)) {
state = NycFareState.SUBWAY_PRE_TRANSFER;
totalFare += ORDINARY_FARE;
if (SUBWAY_FREE_TRANSFER_STOPS.contains(ride.lastStop.getId())) {
lexFreeTransfer = true;
}
if (CANARSIE.contains(ride.lastStop.getId())) {
canarsieFreeTransfer = true;
}
} else if (ride.classifier.equals(SIR)) {
state = NycFareState.SIR_PRE_TRANSFER;
if (SIR_PAID_STOPS.contains(firstStopId)
|| SIR_PAID_STOPS.contains(lastStopId)) {
totalFare += ORDINARY_FARE;
}
} else if (ride.classifier.equals(LOCAL_BUS)) {
state = NycFareState.BUS_PRE_TRANSFER;
totalFare += ORDINARY_FARE;
if (CANARSIE.contains(ride.lastStop.getId())) {
canarsieFreeTransfer = true;
}
siLocalBus = ride.route.getId().startsWith("S");
} else if (ride.classifier.equals(EXPRESS_BUS)) {
state = NycFareState.BUS_PRE_TRANSFER;
totalFare += EXPRESS_FARE;
} else if (ride.classifier.equals(EXPENSIVE_EXPRESS_BUS)) {
state = NycFareState.EXPENSIVE_EXPRESS_BUS;
totalFare += EXPENSIVE_EXPRESS_FARE;
}
break;
case SUBWAY_PRE_TRANSFER_WALKED:
if (ride.classifier.equals(SUBWAY)) {
// subway-to-subway transfers are verbotten except at
// lex and 59/63
if (!(lexFreeTransfer && SUBWAY_FREE_TRANSFER_STOPS
.contains(ride.firstStop.getId()))) {
totalFare += ORDINARY_FARE;
}
lexFreeTransfer = canarsieFreeTransfer = false;
if (SUBWAY_FREE_TRANSFER_STOPS.contains(ride.lastStop.getId())) {
lexFreeTransfer = true;
}
if (CANARSIE.contains(ride.lastStop.getId())) {
canarsieFreeTransfer = true;
}
}
/* FALL THROUGH */
case SUBWAY_PRE_TRANSFER:
// it will always be possible to transfer from the first subway
// trip to anywhere,
// since no sequence of subway trips takes greater than two
// hours (if only just)
if (ride.classifier.equals(WALK)) {
state = NycFareState.SUBWAY_PRE_TRANSFER_WALKED;
} else if (ride.classifier.equals(SIR)) {
state = NycFareState.SIR_POST_TRANSFER_FROM_SUBWAY;
} else if (ride.classifier.equals(LOCAL_BUS)) {
if (CANARSIE.contains(ride.firstStop.getId())
&& canarsieFreeTransfer) {
state = NycFareState.BUS_PRE_TRANSFER;
} else {
state = NycFareState.INIT;
}
} else if (ride.classifier.equals(EXPRESS_BUS)) {
// need to pay the upgrade cost
totalFare += EXPRESS_FARE - ORDINARY_FARE;
} else if (ride.classifier.equals(EXPENSIVE_EXPRESS_BUS)) {
totalFare += EXPENSIVE_EXPRESS_FARE; // no transfers to the
// BxMM4C
}
break;
case BUS_PRE_TRANSFER:
if (ride.classifier.equals(SUBWAY)) {
if (CANARSIE.contains(ride.firstStop.getId())
&& canarsieFreeTransfer) {
state = NycFareState.SUBWAY_PRE_TRANSFER;
} else {
state = NycFareState.INIT;
}
} else if (ride.classifier.equals(SIR)) {
if (siLocalBus) {
// SI local bus to SIR, so it is as if we started on the
// SIR (except that when we enter the bus or subway system we need to do
// so at certain places)
sirBonusTransfer = true;
state = NycFareState.SIR_PRE_TRANSFER;
} else {
//transfers exhausted
state = NycFareState.INIT;
}
} else if (ride.classifier.equals(LOCAL_BUS)) {
state = NycFareState.INIT;
} else if (ride.classifier.equals(EXPRESS_BUS)) {
// need to pay the upgrade cost
totalFare += EXPRESS_FARE - ORDINARY_FARE;
state = NycFareState.INIT;
} else if (ride.classifier.equals(EXPENSIVE_EXPRESS_BUS)) {
totalFare += EXPENSIVE_EXPRESS_FARE;
// no transfers to the BxMM4C
}
break;
case SIR_PRE_TRANSFER:
if (ride.classifier.equals(SUBWAY)) {
if (sirBonusTransfer && !SIR_BONUS_STOPS.contains(ride.firstStop.getId())) {
//we were relying on the bonus transfer to be in the "pre-transfer state",
//but the bonus transfer does not apply here
totalFare += ORDINARY_FARE;
}
if (CANARSIE.contains(ride.lastStop.getId())) {
canarsieFreeTransfer = true;
}
state = NycFareState.SUBWAY_POST_TRANSFER;
} else if (ride.classifier.equals(SIR)) {
/* should not happen, and unhandled */
_log.warn("Should not transfer from SIR to SIR");
} else if (ride.classifier.equals(LOCAL_BUS)) {
if (!SIR_BONUS_ROUTES.contains(ride.route)) {
totalFare += ORDINARY_FARE;
}
state = NycFareState.BUS_PRE_TRANSFER;
} else if (ride.classifier.equals(EXPRESS_BUS)) {
totalFare += EXPRESS_BUS;
state = NycFareState.BUS_PRE_TRANSFER;
} else if (ride.classifier.equals(EXPENSIVE_EXPRESS_BUS)) {
totalFare += EXPENSIVE_EXPRESS_BUS;
state = NycFareState.BUS_PRE_TRANSFER;
}
break;
case SIR_POST_TRANSFER_FROM_SUBWAY:
if (ride.classifier.equals(SUBWAY)) {
/* should not happen */
totalFare += ORDINARY_FARE;
state = NycFareState.SUBWAY_PRE_TRANSFER;
} else if (ride.classifier.equals(SIR)) {
/* should not happen, and unhandled */
_log.warn("Should not transfer from SIR to SIR");
} else if (ride.classifier.equals(LOCAL_BUS)) {
if (!ride.route.getId().startsWith("S")) {
totalFare += ORDINARY_FARE;
state = NycFareState.BUS_PRE_TRANSFER;
} else {
state = NycFareState.INIT;
}
} else if (ride.classifier.equals(EXPRESS_BUS)) {
// need to pay the full cost
totalFare += EXPRESS_FARE;
state = NycFareState.INIT;
} else if (ride.classifier.equals(EXPENSIVE_EXPRESS_BUS)) {
/* should not happen */
// no transfers to the BxMM4C
totalFare += EXPENSIVE_EXPRESS_FARE;
state = NycFareState.BUS_PRE_TRANSFER;
}
break;
case SUBWAY_POST_TRANSFER:
if (ride.classifier.equals(WALK)) {
if (!canarsieFreeTransfer) {
/* note: if we end up walking to another subway after alighting
* at Canarsie, we will mistakenly not be charged, but nobody
* would ever do this */
state = NycFareState.INIT;
}
} else if (ride.classifier.equals(SIR)) {
totalFare += ORDINARY_FARE;
state = NycFareState.SIR_PRE_TRANSFER;
} else if (ride.classifier.equals(LOCAL_BUS)) {
if (!(CANARSIE.contains(ride.firstStop.getId())
&& canarsieFreeTransfer)) {
totalFare += ORDINARY_FARE;
}
state = NycFareState.INIT;
} else if (ride.classifier.equals(SUBWAY)) {
//walking transfer
totalFare += ORDINARY_FARE;
state = NycFareState.SUBWAY_PRE_TRANSFER;
} else if (ride.classifier.equals(EXPRESS_BUS)) {
totalFare += EXPRESS_FARE;
state = NycFareState.BUS_PRE_TRANSFER;
} else if (ride.classifier.equals(EXPENSIVE_EXPRESS_BUS)) {
totalFare += EXPENSIVE_EXPRESS_FARE;
state = NycFareState.BUS_PRE_TRANSFER;
}
}
}
Currency currency = Currency.getInstance("USD");
Fare fare = new Fare();
fare.addFare(FareType.regular, new WrappedCurrency(currency),
(int) Math.round(totalFare
* Math.pow(10, currency.getDefaultFractionDigits())));
return fare;
}
|
diff --git a/kdcloud-webservice/src/main/java/com/kdcloud/server/rest/resource/ModalitiesServerResource.java b/kdcloud-webservice/src/main/java/com/kdcloud/server/rest/resource/ModalitiesServerResource.java
index 52eb88d..5da440c 100644
--- a/kdcloud-webservice/src/main/java/com/kdcloud/server/rest/resource/ModalitiesServerResource.java
+++ b/kdcloud-webservice/src/main/java/com/kdcloud/server/rest/resource/ModalitiesServerResource.java
@@ -1,40 +1,41 @@
package com.kdcloud.server.rest.resource;
import java.util.ArrayList;
import org.restlet.Application;
import org.restlet.client.resource.Post;
import org.restlet.resource.Get;
import com.kdcloud.server.entity.Modality;
import com.kdcloud.server.rest.api.ModalitiesResource;
public class ModalitiesServerResource extends KDServerResource implements ModalitiesResource {
public ModalitiesServerResource() {
super();
// TODO Auto-generated constructor stub
}
public ModalitiesServerResource(Application application) {
super(application);
// TODO Auto-generated constructor stub
}
@Override
@Get
public ArrayList<Modality> listModalities() {
ArrayList<Modality> list = new ArrayList<Modality>();
list.addAll(modalityDao.getAll());
+ getLogger().info("fetched " + list.size() + " modalities");
return list;
}
@Override
@Post
public void createModality(Modality modality) {
modalityDao.save(modality);
}
}
| true | true | public ArrayList<Modality> listModalities() {
ArrayList<Modality> list = new ArrayList<Modality>();
list.addAll(modalityDao.getAll());
return list;
}
| public ArrayList<Modality> listModalities() {
ArrayList<Modality> list = new ArrayList<Modality>();
list.addAll(modalityDao.getAll());
getLogger().info("fetched " + list.size() + " modalities");
return list;
}
|
diff --git a/cyklotron-core/src/main/java/net/cyklotron/cms/documents/calendar/CalendarAllRangeQuery.java b/cyklotron-core/src/main/java/net/cyklotron/cms/documents/calendar/CalendarAllRangeQuery.java
index 79d9ad7b4..e5870ae74 100644
--- a/cyklotron-core/src/main/java/net/cyklotron/cms/documents/calendar/CalendarAllRangeQuery.java
+++ b/cyklotron-core/src/main/java/net/cyklotron/cms/documents/calendar/CalendarAllRangeQuery.java
@@ -1,210 +1,214 @@
package net.cyklotron.cms.documents.calendar;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermEnum;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermRangeQuery;
import org.jcontainer.dna.Logger;
import net.cyklotron.cms.documents.DocumentNodeResource;
import net.cyklotron.cms.search.SearchUtil;
/**
* A calendar 'all' range query with heuristic rewriting which minimizes a number of term queries
* in rewritten version of this query. Also maximal number of boolean clauses is pumped up to avoid
* TooManyClauses exception.
*
* @author <a href="mailto:[email protected]">Damian Gajda</a>
* @version $Id: CalendarAllRangeQuery.java,v 1.6 2005-08-10 05:31:05 rafal Exp $
*/
public class CalendarAllRangeQuery extends Query
{
private Logger log;
private Date startDate;
private Date endDate;
private Term lowerEndDate;
private Term upperStartDate;
/**
* Constructs calendar range query.
*
* @param log the logger
* @param startDate
* @param endDate
*/
public CalendarAllRangeQuery(Logger log, Date startDate, Date endDate)
{
this.log = log;
this.startDate = startDate;
this.endDate = endDate;
// get terms
lowerEndDate = new Term("eventEnd", SearchUtil.dateToString(startDate));
upperStartDate = new Term("eventStart", SearchUtil.dateToString(endDate));
}
@Override
public Query rewrite(IndexReader indexReader) throws IOException
{
// total number of calendar documents in index
// it is equal or more than number of date terms per field
int numCalendarDocs = indexReader.maxDoc() -
indexReader.docFreq(new Term("titleCalendar", DocumentNodeResource.EMPTY_TITLE));
// remember max clause count
//int maxClauseCount = BooleanQuery.getMaxClauseCount();
// calculate which range is more efficient for query execution
// calculate number of terms in expanded RangeQueries
int termsAfterCut1 = termsInUpperRange(indexReader, lowerEndDate, numCalendarDocs);
int termsAfterCut2 = termsInUpperRange(indexReader, upperStartDate, numCalendarDocs);
int termsAfterCut = termsAfterCut1 > termsAfterCut2 ? termsAfterCut1 : termsAfterCut2;
// create boolean query with range queries
BooleanQuery rewritten = new BooleanQuery(); // and
// only both upper or both lower range boundaries are open
// reverse the query if number of terms before cut date is smaller
// than half of the total number of terms
if(termsAfterCut < (int)(0.5 * numCalendarDocs))
{
setMaxClauseCount(termsAfterCut);
- TermRangeQuery endDateAfterRangeStart = new TermRangeQuery(lowerEndDate.field(),
+ TermRangeQuery endDateAfterRangeStart = TermRangeQuery.newStringRange(
+ lowerEndDate.field(),
lowerEndDate.text(), null, true, true);
- TermRangeQuery startDateNotAfterRangeEnd = new TermRangeQuery(upperStartDate.field(),
+ TermRangeQuery startDateNotAfterRangeEnd = TermRangeQuery.newStringRange(
+ upperStartDate.field(),
upperStartDate.text(), null, false, false);
rewritten.add(new BooleanClause(endDateAfterRangeStart, BooleanClause.Occur.MUST));
rewritten
.add(new BooleanClause(startDateNotAfterRangeEnd, BooleanClause.Occur.MUST_NOT)); // negated
}
else
{
setMaxClauseCount(numCalendarDocs - termsAfterCut);
- TermRangeQuery endDateNotBeforeRangeStart = new TermRangeQuery(lowerEndDate.field(),
+ TermRangeQuery endDateNotBeforeRangeStart = TermRangeQuery.newStringRange(
+ lowerEndDate.field(),
null, lowerEndDate.text(), false, false);
- TermRangeQuery startDateBeforeRangeEnd = new TermRangeQuery(upperStartDate.field(),
+ TermRangeQuery startDateBeforeRangeEnd = TermRangeQuery.newStringRange(
+ upperStartDate.field(),
null, upperStartDate.text(), true, true);
rewritten.add(new BooleanClause(endDateNotBeforeRangeStart,
BooleanClause.Occur.MUST_NOT)); // negated
rewritten.add(new BooleanClause(startDateBeforeRangeEnd, BooleanClause.Occur.MUST));
}
// rewrite boolean query
BooleanQuery rewritten2 = (BooleanQuery) rewritten.rewrite(indexReader);
if(log.isDebugEnabled())
{
log.debug("CalendarAllRangeQuery: real number of clauses="+rewritten2.getClauses().length);
}
// bring back old value
//BooleanQuery.setMaxClauseCount(maxClauseCount);
return rewritten2;
}
private int termsInUpperRange(IndexReader indexReader, Term lowerTerm, int numCalendarDocs)
throws IOException
{
// compute date boundaries to estimate number of terms expanded by range query rewriting
long lowDate = 0L;
long cutDate = 0L;
try
{
// get lowest non null date in index
TermEnum te = indexReader.terms(new Term(lowerTerm.field(), ""));
// enumeration contains all terms in the document sorted lexicographically by
// field name then term content. it is positioned on the term greater than requested,
// so when no terms for the field are present enumeration points to a different field's
// term or null if the requested term was the farthest in the index
if(te.term() != null && te.term().field() == lowerTerm.field())
{
String lowestDateText = te.term().text();
lowDate = SearchUtil.dateFromString(lowestDateText).getTime();
}
// no need to rewrite - seems like the number of terms is small
if(lowDate == 0L)
{
return 1;
}
// get date from which date terms are collected (defined by query term)
cutDate = SearchUtil.dateFromString(lowerTerm.text()).getTime();
if(cutDate < lowDate)
{
cutDate = lowDate;
}
}
catch(ParseException e)
{
throw new RuntimeException("Could not rewrite calendar range query", e);
}
// get current date - this estimates highest date in index, because
// most of the documents are historical ones
long highDate = (new Date()).getTime();
if(highDate < cutDate)
{
highDate = cutDate + 24L*60L*60L*1000L;
}
// calc number of terms before cut date
int termsAfterCut = (int)Math.floor(
(double)(numCalendarDocs * (highDate - cutDate))
/
(double)(highDate - lowDate));
return termsAfterCut;
}
private final void setMaxClauseCount(int termsCount)
{
termsCount = (int) Math.ceil( termsCount * 1.5e0 );
if(termsCount > BooleanQuery.getMaxClauseCount())
{
log.debug("CalendarAllRangeQuery: calculated number of clauses="+termsCount);
BooleanQuery.setMaxClauseCount(termsCount);
}
}
/* (non-Javadoc)
* @see org.apache.lucene.search.Query#toString(java.lang.String)
*/
@Override
public String toString(String arg0)
{
StringBuilder buffer = new StringBuilder();
buffer.append("(");
buffer.append("+(");
buffer.append(lowerEndDate.field());
buffer.append(":[");
buffer.append(lowerEndDate.text());
buffer.append(" TO null]) ");
buffer.append("-(");
buffer.append(upperStartDate.field());
buffer.append(":{");
buffer.append(upperStartDate.text());
buffer.append(" TO null})");
buffer.append(")");
if (getBoost() != 1.0f)
{
buffer.append("^");
buffer.append(Float.toString(getBoost()));
}
return buffer.toString();
}
}
| false | true | public Query rewrite(IndexReader indexReader) throws IOException
{
// total number of calendar documents in index
// it is equal or more than number of date terms per field
int numCalendarDocs = indexReader.maxDoc() -
indexReader.docFreq(new Term("titleCalendar", DocumentNodeResource.EMPTY_TITLE));
// remember max clause count
//int maxClauseCount = BooleanQuery.getMaxClauseCount();
// calculate which range is more efficient for query execution
// calculate number of terms in expanded RangeQueries
int termsAfterCut1 = termsInUpperRange(indexReader, lowerEndDate, numCalendarDocs);
int termsAfterCut2 = termsInUpperRange(indexReader, upperStartDate, numCalendarDocs);
int termsAfterCut = termsAfterCut1 > termsAfterCut2 ? termsAfterCut1 : termsAfterCut2;
// create boolean query with range queries
BooleanQuery rewritten = new BooleanQuery(); // and
// only both upper or both lower range boundaries are open
// reverse the query if number of terms before cut date is smaller
// than half of the total number of terms
if(termsAfterCut < (int)(0.5 * numCalendarDocs))
{
setMaxClauseCount(termsAfterCut);
TermRangeQuery endDateAfterRangeStart = new TermRangeQuery(lowerEndDate.field(),
lowerEndDate.text(), null, true, true);
TermRangeQuery startDateNotAfterRangeEnd = new TermRangeQuery(upperStartDate.field(),
upperStartDate.text(), null, false, false);
rewritten.add(new BooleanClause(endDateAfterRangeStart, BooleanClause.Occur.MUST));
rewritten
.add(new BooleanClause(startDateNotAfterRangeEnd, BooleanClause.Occur.MUST_NOT)); // negated
}
else
{
setMaxClauseCount(numCalendarDocs - termsAfterCut);
TermRangeQuery endDateNotBeforeRangeStart = new TermRangeQuery(lowerEndDate.field(),
null, lowerEndDate.text(), false, false);
TermRangeQuery startDateBeforeRangeEnd = new TermRangeQuery(upperStartDate.field(),
null, upperStartDate.text(), true, true);
rewritten.add(new BooleanClause(endDateNotBeforeRangeStart,
BooleanClause.Occur.MUST_NOT)); // negated
rewritten.add(new BooleanClause(startDateBeforeRangeEnd, BooleanClause.Occur.MUST));
}
// rewrite boolean query
BooleanQuery rewritten2 = (BooleanQuery) rewritten.rewrite(indexReader);
if(log.isDebugEnabled())
{
log.debug("CalendarAllRangeQuery: real number of clauses="+rewritten2.getClauses().length);
}
// bring back old value
//BooleanQuery.setMaxClauseCount(maxClauseCount);
return rewritten2;
}
| public Query rewrite(IndexReader indexReader) throws IOException
{
// total number of calendar documents in index
// it is equal or more than number of date terms per field
int numCalendarDocs = indexReader.maxDoc() -
indexReader.docFreq(new Term("titleCalendar", DocumentNodeResource.EMPTY_TITLE));
// remember max clause count
//int maxClauseCount = BooleanQuery.getMaxClauseCount();
// calculate which range is more efficient for query execution
// calculate number of terms in expanded RangeQueries
int termsAfterCut1 = termsInUpperRange(indexReader, lowerEndDate, numCalendarDocs);
int termsAfterCut2 = termsInUpperRange(indexReader, upperStartDate, numCalendarDocs);
int termsAfterCut = termsAfterCut1 > termsAfterCut2 ? termsAfterCut1 : termsAfterCut2;
// create boolean query with range queries
BooleanQuery rewritten = new BooleanQuery(); // and
// only both upper or both lower range boundaries are open
// reverse the query if number of terms before cut date is smaller
// than half of the total number of terms
if(termsAfterCut < (int)(0.5 * numCalendarDocs))
{
setMaxClauseCount(termsAfterCut);
TermRangeQuery endDateAfterRangeStart = TermRangeQuery.newStringRange(
lowerEndDate.field(),
lowerEndDate.text(), null, true, true);
TermRangeQuery startDateNotAfterRangeEnd = TermRangeQuery.newStringRange(
upperStartDate.field(),
upperStartDate.text(), null, false, false);
rewritten.add(new BooleanClause(endDateAfterRangeStart, BooleanClause.Occur.MUST));
rewritten
.add(new BooleanClause(startDateNotAfterRangeEnd, BooleanClause.Occur.MUST_NOT)); // negated
}
else
{
setMaxClauseCount(numCalendarDocs - termsAfterCut);
TermRangeQuery endDateNotBeforeRangeStart = TermRangeQuery.newStringRange(
lowerEndDate.field(),
null, lowerEndDate.text(), false, false);
TermRangeQuery startDateBeforeRangeEnd = TermRangeQuery.newStringRange(
upperStartDate.field(),
null, upperStartDate.text(), true, true);
rewritten.add(new BooleanClause(endDateNotBeforeRangeStart,
BooleanClause.Occur.MUST_NOT)); // negated
rewritten.add(new BooleanClause(startDateBeforeRangeEnd, BooleanClause.Occur.MUST));
}
// rewrite boolean query
BooleanQuery rewritten2 = (BooleanQuery) rewritten.rewrite(indexReader);
if(log.isDebugEnabled())
{
log.debug("CalendarAllRangeQuery: real number of clauses="+rewritten2.getClauses().length);
}
// bring back old value
//BooleanQuery.setMaxClauseCount(maxClauseCount);
return rewritten2;
}
|
diff --git a/axis2/src/main/java/org/apache/ode/axis2/service/DeploymentBrowser.java b/axis2/src/main/java/org/apache/ode/axis2/service/DeploymentBrowser.java
index c50c2f41b..456919eab 100644
--- a/axis2/src/main/java/org/apache/ode/axis2/service/DeploymentBrowser.java
+++ b/axis2/src/main/java/org/apache/ode/axis2/service/DeploymentBrowser.java
@@ -1,336 +1,336 @@
package org.apache.ode.axis2.service;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.namespace.QName;
import org.apache.axis2.description.AxisOperation;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.commons.lang.StringUtils;
import org.apache.ode.store.ProcessStoreImpl;
import org.apache.ode.utils.fs.FileUtils;
/**
* handles a set of URLs all starting with /deployment to publish all files in
* deployed bundles, services and processes.
*/
public class DeploymentBrowser {
private ProcessStoreImpl _store;
private AxisConfiguration _config;
private File _appRoot;
public DeploymentBrowser(ProcessStoreImpl store, AxisConfiguration config, File appRoot) {
_store = store;
_config = config;
_appRoot = appRoot;
}
// A fake filter, directly called from the ODEAxisServlet
public boolean doFilter(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final String requestURI = request.getRequestURI();
final int deplUri = requestURI.indexOf("/deployment");
if (deplUri > 0) {
final String root = request.getScheme() + "://" + request.getServerName() +
":" + request.getServerPort() + requestURI.substring(0, deplUri);
int offset = requestURI.length() > (deplUri + 11) ? 1 : 0;
final String[] segments = requestURI.substring(deplUri + 11 + offset).split("/");
if (segments.length == 0 || segments[0].length() == 0) {
renderHtml(response, "ODE Deployment Browser", new DocBody() {
public void render(Writer out) throws IOException {
out.write("<p><a href=\"bundles/\">Deployed Bundles</a></p>");
out.write("<p><a href=\"services/\">Process Services</a></p>");
out.write("<p><a href=\"processes/\">Process Definitions</a></p>");
}
});
} else if (segments.length > 0) {
if ("services".equals(segments[0])) {
if (segments.length == 1) {
renderHtml(response, "Services Implemented by Your Processes", new DocBody() {
public void render(Writer out) throws IOException {
for (Object serviceName : _config.getServices().keySet())
if (!"Version".equals(serviceName)) {
AxisService service = _config.getService(serviceName.toString());
// The service can be one of the dynamically registered ODE services, a process
// service or an unknown service deployed in the same Axis2 instance.
String url = null;
if ("DeploymentService".equals(service.getName())
|| "InstanceManagement".equals(service.getName())
|| "ProcessManagement".equals(service.getName()))
url = service.getName();
else if (service.getFileName() != null) {
String relative = bundleUrlFor(service.getFileName().getFile());
if (relative != null) url = root + relative;
else url = root + "/services/" + service.getName() + "?wsdl";
}
out.write("<p><a href=\"" + url + "\">" + serviceName + "</a></p>");
out.write("<ul><li>Endpoint: " + (root + "/processes/" + serviceName) + "</li>");
Iterator iter = service.getOperations();
ArrayList<String> ops = new ArrayList<String>();
while (iter.hasNext()) ops.add(((AxisOperation)iter.next()).getName().getLocalPart());
out.write("<li>Operations: " + StringUtils.join(ops.iterator(), ", ") + "</li></ul>");
}
}
});
} else {
final String serviceName = requestURI.substring(deplUri + 12 + 9);
final AxisService axisService = _config.getService(serviceName);
if (axisService != null) {
renderXml(response, new DocBody() {
public void render(Writer out) throws IOException {
if ("InstanceManagement".equals(serviceName) || "ProcessManagement".equals(serviceName))
write(out, new File(_appRoot, "pmapi.wsdl").getPath());
else if (requestURI.indexOf("pmapi.xsd") > 0)
write(out, new File(_appRoot, "pmapi.xsd").getPath());
else if ("DeploymentService".equals(serviceName))
write(out, new File(_appRoot, "deploy.wsdl").getPath());
else
write(out, axisService.getFileName().getFile());
}
});
} else {
renderHtml(response, "Service Not Found", new DocBody() {
public void render(Writer out) throws IOException {
out.write("<p>Couldn't find service " + serviceName + "</p>");
}
});
}
}
} else if ("processes".equals(segments[0])) {
if (segments.length == 1) {
renderHtml(response, "Deployed Processes", new DocBody() {
public void render(Writer out) throws IOException {
for (QName process :_store.getProcesses()) {
String url = root + bundleUrlFor(_store.getProcessConfiguration(process).getBpelDocument());
String[] nameVer = process.getLocalPart().split("-");
out.write("<p><a href=\"" + url + "\">" + nameVer[0] + "</a> (v" + nameVer[1] + ")");
out.write(" - " + process.getNamespaceURI() + "</p>");
}
}
});
}
} else if ("bundles".equals(segments[0])) {
if (segments.length == 1) {
renderHtml(response, "Deployment Bundles", new DocBody() {
public void render(Writer out) throws IOException {
for (String bundle : _store.getPackages())
out.write("<p><a href=\"" + bundle + "\">" + bundle + "</a></p>");
}
});
} else if (segments.length == 2) {
renderHtml(response, "Files in Bundle " + segments[1], new DocBody() {
public void render(Writer out) throws IOException {
List<QName> processes = _store.listProcesses(segments[1]);
if (processes != null) {
List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles();
for (File file : files) {
String relativePath = file.getPath().substring(file.getPath()
.indexOf("processes")+10).replaceAll("\\\\", "/");
out.write("<p><a href=\"" + relativePath + "\">" + relativePath + "</a></p>");
}
} else {
- out.write("<p>Couldn't find bundle " + segments[2] + "</p>");
+ out.write("<p>Couldn't find bundle " + segments[1] + "</p>");
}
}
});
} else if (segments.length > 2) {
List<QName> processes = _store.listProcesses(segments[1]);
if (processes != null) {
List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles();
for (final File file : files) {
String relativePath = requestURI.substring(deplUri + 12 + 9 + segments[1].length());
if (file.getPath().endsWith(relativePath)) {
renderXml(response, new DocBody() {
public void render(Writer out) throws IOException {
write(out, file.getPath());
}
});
return true;
}
}
} else {
renderHtml(response, "No Bundle Found", new DocBody() {
public void render(Writer out) throws IOException {
out.write("<p>Couldn't find bundle " + segments[2] + "</p>");
}
});
}
}
} else if("getBundleDocs".equals(segments[0])){
if(segments.length == 1){
renderXml(response, new DocBody(){
public void render(Writer out) throws IOException{
out.write("<getBundleDocsResponse>");
out.write("<error>Not enough args..</error>");
out.write("</getBundleDocsResponse>");
}
});
}else if (segments.length == 2){
final String bundleName = segments[1];
final List<QName> processes = _store.listProcesses(bundleName);
if(processes != null){
renderXml(response, new DocBody(){
public void render(Writer out) throws IOException{
out.write("<getBundleDocsResponse><name>"+ bundleName +"</name>");
//final List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles();
//final String pid = _store.getProcessConfiguration(processes.get(0)).getProcessId().toString();
for(final QName process: processes){
List<File> files = _store.getProcessConfiguration(process).getFiles();
String pid = _store.getProcessConfiguration(process).getProcessId().toString();
out.write("<process><pid>"+pid+"</pid>");
for (final File file : files){
if(file.getPath().endsWith(".wsdl")){
String relativePath = file.getPath().substring(_store.getDeployDir().getCanonicalPath().length() + 1);
out.write("<wsdl>"+ relativePath + "</wsdl>");
}
if(file.getPath().endsWith(".bpel")){
String relativePath = file.getPath().substring(_store.getDeployDir().getCanonicalPath().length() + 1);
out.write("<bpel>"+ relativePath + "</bpel>");
}
}
out.write("</process>");
}
out.write("</getBundleDocsResponse>");
}
});
}
}
}else if("getProcessDefinition".equals(segments[0])){
if(segments.length == 1){
renderXml(response, new DocBody(){
public void render(Writer out) throws IOException{
out.write("<getProcessDefinitionResponse>");
out.write("<error>Not enough args..</error>");
out.write("</getProcessDefinitionResponse>");
}
});
}else if (segments.length == 2){
String processName = segments[1];
for (QName process :_store.getProcesses()) {
String[] nameVer = process.getLocalPart().split("-");
if(processName.equals(nameVer[0])){
final String url = root + bundleUrlFor(_store.getProcessConfiguration(process).getBpelDocument());
renderXml(response, new DocBody(){
public void render(Writer out) throws IOException{
out.write("<getProcessDefinition>");
out.write("<url>"+ url +"</url>");
out.write("</getProcessDefinition>");
}
});
}
}
}
}
}
return true;
}
return false;
}
static interface DocBody {
void render(Writer out) throws IOException;
}
private void renderHtml(HttpServletResponse response, String title, DocBody docBody) throws IOException {
response.setContentType("text/html");
Writer out = response.getWriter();
out.write("<html><header><style type=\"text/css\">" + CSS + "</style></header><body>\n");
out.write("<h2>" + title + "</h2><p/>\n");
docBody.render(out);
out.write("</body></html>");
}
private void renderXml(HttpServletResponse response, DocBody docBody) throws IOException {
response.setContentType("text/xml");
response.setCharacterEncoding("UTF-8");
Writer out = response.getWriter();
docBody.render(out);
}
private void write(Writer out, String filePath) throws IOException {
BufferedReader wsdlReader = new BufferedReader(new FileReader(filePath));
String line;
while((line = wsdlReader.readLine()) != null) out.write(line + "\n");
wsdlReader.close();
}
private String bundleUrlFor(String docFile) {
if (docFile.indexOf("processes") >= 0) docFile = docFile.substring(docFile.indexOf("processes")+10);
List<File> files = FileUtils.directoryEntriesInPath(_store.getDeployDir(), null);
for (final File bundleFile : files) {
if (bundleFile.getPath().replaceAll("\\\\", "/").endsWith(docFile))
return "/deployment/bundles/" + bundleFile.getPath()
.substring(_store.getDeployDir().getPath().length() + 1).replaceAll("\\\\", "/");
}
return null;
}
private static final String CSS =
"body {\n" +
" font: 75% Verdana, Helvetica, Arial, sans-serif;\n" +
" background: White;\n" +
" color: Black;\n" +
" margin: 1em;\n" +
" padding: 1em;\n" +
"}\n" +
"\n" +
"h1, h2, h3, h4, h5, h6 {\n" +
" color: Black;\n" +
" clear: left;\n" +
" font: 100% Verdana, Helvetica, Arial, sans-serif;\n" +
" margin: 0;\n" +
" padding-left: 0.5em;\n" +
"} \n" +
"\n" +
"h1 {\n" +
" font-size: 150%;\n" +
" border-bottom: none;\n" +
" text-align: right;\n" +
" border-bottom: 1px solid Gray;\n" +
"}\n" +
" \n" +
"h2 {\n" +
" font-size: 130%;\n" +
" border-bottom: 1px solid Gray;\n" +
"}\n" +
"\n" +
"h3 {\n" +
" font-size: 120%;\n" +
" padding-left: 1.0em;\n" +
" border-bottom: 1px solid Gray;\n" +
"}\n" +
"\n" +
"h4 {\n" +
" font-size: 110%;\n" +
" padding-left: 1.5em;\n" +
" border-bottom: 1px solid Gray;\n" +
"}\n" +
"\n" +
"p {\n" +
" text-align: justify;\n" +
" line-height: 1.5em;\n" +
" padding-left: 1.5em;\n" +
"}\n" +
"\n" +
"a {\n" +
" text-decoration: underline;\n" +
" color: Black;\n" +
"}";
}
| true | true | public boolean doFilter(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final String requestURI = request.getRequestURI();
final int deplUri = requestURI.indexOf("/deployment");
if (deplUri > 0) {
final String root = request.getScheme() + "://" + request.getServerName() +
":" + request.getServerPort() + requestURI.substring(0, deplUri);
int offset = requestURI.length() > (deplUri + 11) ? 1 : 0;
final String[] segments = requestURI.substring(deplUri + 11 + offset).split("/");
if (segments.length == 0 || segments[0].length() == 0) {
renderHtml(response, "ODE Deployment Browser", new DocBody() {
public void render(Writer out) throws IOException {
out.write("<p><a href=\"bundles/\">Deployed Bundles</a></p>");
out.write("<p><a href=\"services/\">Process Services</a></p>");
out.write("<p><a href=\"processes/\">Process Definitions</a></p>");
}
});
} else if (segments.length > 0) {
if ("services".equals(segments[0])) {
if (segments.length == 1) {
renderHtml(response, "Services Implemented by Your Processes", new DocBody() {
public void render(Writer out) throws IOException {
for (Object serviceName : _config.getServices().keySet())
if (!"Version".equals(serviceName)) {
AxisService service = _config.getService(serviceName.toString());
// The service can be one of the dynamically registered ODE services, a process
// service or an unknown service deployed in the same Axis2 instance.
String url = null;
if ("DeploymentService".equals(service.getName())
|| "InstanceManagement".equals(service.getName())
|| "ProcessManagement".equals(service.getName()))
url = service.getName();
else if (service.getFileName() != null) {
String relative = bundleUrlFor(service.getFileName().getFile());
if (relative != null) url = root + relative;
else url = root + "/services/" + service.getName() + "?wsdl";
}
out.write("<p><a href=\"" + url + "\">" + serviceName + "</a></p>");
out.write("<ul><li>Endpoint: " + (root + "/processes/" + serviceName) + "</li>");
Iterator iter = service.getOperations();
ArrayList<String> ops = new ArrayList<String>();
while (iter.hasNext()) ops.add(((AxisOperation)iter.next()).getName().getLocalPart());
out.write("<li>Operations: " + StringUtils.join(ops.iterator(), ", ") + "</li></ul>");
}
}
});
} else {
final String serviceName = requestURI.substring(deplUri + 12 + 9);
final AxisService axisService = _config.getService(serviceName);
if (axisService != null) {
renderXml(response, new DocBody() {
public void render(Writer out) throws IOException {
if ("InstanceManagement".equals(serviceName) || "ProcessManagement".equals(serviceName))
write(out, new File(_appRoot, "pmapi.wsdl").getPath());
else if (requestURI.indexOf("pmapi.xsd") > 0)
write(out, new File(_appRoot, "pmapi.xsd").getPath());
else if ("DeploymentService".equals(serviceName))
write(out, new File(_appRoot, "deploy.wsdl").getPath());
else
write(out, axisService.getFileName().getFile());
}
});
} else {
renderHtml(response, "Service Not Found", new DocBody() {
public void render(Writer out) throws IOException {
out.write("<p>Couldn't find service " + serviceName + "</p>");
}
});
}
}
} else if ("processes".equals(segments[0])) {
if (segments.length == 1) {
renderHtml(response, "Deployed Processes", new DocBody() {
public void render(Writer out) throws IOException {
for (QName process :_store.getProcesses()) {
String url = root + bundleUrlFor(_store.getProcessConfiguration(process).getBpelDocument());
String[] nameVer = process.getLocalPart().split("-");
out.write("<p><a href=\"" + url + "\">" + nameVer[0] + "</a> (v" + nameVer[1] + ")");
out.write(" - " + process.getNamespaceURI() + "</p>");
}
}
});
}
} else if ("bundles".equals(segments[0])) {
if (segments.length == 1) {
renderHtml(response, "Deployment Bundles", new DocBody() {
public void render(Writer out) throws IOException {
for (String bundle : _store.getPackages())
out.write("<p><a href=\"" + bundle + "\">" + bundle + "</a></p>");
}
});
} else if (segments.length == 2) {
renderHtml(response, "Files in Bundle " + segments[1], new DocBody() {
public void render(Writer out) throws IOException {
List<QName> processes = _store.listProcesses(segments[1]);
if (processes != null) {
List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles();
for (File file : files) {
String relativePath = file.getPath().substring(file.getPath()
.indexOf("processes")+10).replaceAll("\\\\", "/");
out.write("<p><a href=\"" + relativePath + "\">" + relativePath + "</a></p>");
}
} else {
out.write("<p>Couldn't find bundle " + segments[2] + "</p>");
}
}
});
} else if (segments.length > 2) {
List<QName> processes = _store.listProcesses(segments[1]);
if (processes != null) {
List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles();
for (final File file : files) {
String relativePath = requestURI.substring(deplUri + 12 + 9 + segments[1].length());
if (file.getPath().endsWith(relativePath)) {
renderXml(response, new DocBody() {
public void render(Writer out) throws IOException {
write(out, file.getPath());
}
});
return true;
}
}
} else {
renderHtml(response, "No Bundle Found", new DocBody() {
public void render(Writer out) throws IOException {
out.write("<p>Couldn't find bundle " + segments[2] + "</p>");
}
});
}
}
} else if("getBundleDocs".equals(segments[0])){
if(segments.length == 1){
renderXml(response, new DocBody(){
public void render(Writer out) throws IOException{
out.write("<getBundleDocsResponse>");
out.write("<error>Not enough args..</error>");
out.write("</getBundleDocsResponse>");
}
});
}else if (segments.length == 2){
final String bundleName = segments[1];
final List<QName> processes = _store.listProcesses(bundleName);
if(processes != null){
renderXml(response, new DocBody(){
public void render(Writer out) throws IOException{
out.write("<getBundleDocsResponse><name>"+ bundleName +"</name>");
//final List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles();
//final String pid = _store.getProcessConfiguration(processes.get(0)).getProcessId().toString();
for(final QName process: processes){
List<File> files = _store.getProcessConfiguration(process).getFiles();
String pid = _store.getProcessConfiguration(process).getProcessId().toString();
out.write("<process><pid>"+pid+"</pid>");
for (final File file : files){
if(file.getPath().endsWith(".wsdl")){
String relativePath = file.getPath().substring(_store.getDeployDir().getCanonicalPath().length() + 1);
out.write("<wsdl>"+ relativePath + "</wsdl>");
}
if(file.getPath().endsWith(".bpel")){
String relativePath = file.getPath().substring(_store.getDeployDir().getCanonicalPath().length() + 1);
out.write("<bpel>"+ relativePath + "</bpel>");
}
}
out.write("</process>");
}
out.write("</getBundleDocsResponse>");
}
});
}
}
}else if("getProcessDefinition".equals(segments[0])){
if(segments.length == 1){
renderXml(response, new DocBody(){
public void render(Writer out) throws IOException{
out.write("<getProcessDefinitionResponse>");
out.write("<error>Not enough args..</error>");
out.write("</getProcessDefinitionResponse>");
}
});
}else if (segments.length == 2){
String processName = segments[1];
for (QName process :_store.getProcesses()) {
String[] nameVer = process.getLocalPart().split("-");
if(processName.equals(nameVer[0])){
final String url = root + bundleUrlFor(_store.getProcessConfiguration(process).getBpelDocument());
renderXml(response, new DocBody(){
public void render(Writer out) throws IOException{
out.write("<getProcessDefinition>");
out.write("<url>"+ url +"</url>");
out.write("</getProcessDefinition>");
}
});
}
}
}
}
}
return true;
}
return false;
}
| public boolean doFilter(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final String requestURI = request.getRequestURI();
final int deplUri = requestURI.indexOf("/deployment");
if (deplUri > 0) {
final String root = request.getScheme() + "://" + request.getServerName() +
":" + request.getServerPort() + requestURI.substring(0, deplUri);
int offset = requestURI.length() > (deplUri + 11) ? 1 : 0;
final String[] segments = requestURI.substring(deplUri + 11 + offset).split("/");
if (segments.length == 0 || segments[0].length() == 0) {
renderHtml(response, "ODE Deployment Browser", new DocBody() {
public void render(Writer out) throws IOException {
out.write("<p><a href=\"bundles/\">Deployed Bundles</a></p>");
out.write("<p><a href=\"services/\">Process Services</a></p>");
out.write("<p><a href=\"processes/\">Process Definitions</a></p>");
}
});
} else if (segments.length > 0) {
if ("services".equals(segments[0])) {
if (segments.length == 1) {
renderHtml(response, "Services Implemented by Your Processes", new DocBody() {
public void render(Writer out) throws IOException {
for (Object serviceName : _config.getServices().keySet())
if (!"Version".equals(serviceName)) {
AxisService service = _config.getService(serviceName.toString());
// The service can be one of the dynamically registered ODE services, a process
// service or an unknown service deployed in the same Axis2 instance.
String url = null;
if ("DeploymentService".equals(service.getName())
|| "InstanceManagement".equals(service.getName())
|| "ProcessManagement".equals(service.getName()))
url = service.getName();
else if (service.getFileName() != null) {
String relative = bundleUrlFor(service.getFileName().getFile());
if (relative != null) url = root + relative;
else url = root + "/services/" + service.getName() + "?wsdl";
}
out.write("<p><a href=\"" + url + "\">" + serviceName + "</a></p>");
out.write("<ul><li>Endpoint: " + (root + "/processes/" + serviceName) + "</li>");
Iterator iter = service.getOperations();
ArrayList<String> ops = new ArrayList<String>();
while (iter.hasNext()) ops.add(((AxisOperation)iter.next()).getName().getLocalPart());
out.write("<li>Operations: " + StringUtils.join(ops.iterator(), ", ") + "</li></ul>");
}
}
});
} else {
final String serviceName = requestURI.substring(deplUri + 12 + 9);
final AxisService axisService = _config.getService(serviceName);
if (axisService != null) {
renderXml(response, new DocBody() {
public void render(Writer out) throws IOException {
if ("InstanceManagement".equals(serviceName) || "ProcessManagement".equals(serviceName))
write(out, new File(_appRoot, "pmapi.wsdl").getPath());
else if (requestURI.indexOf("pmapi.xsd") > 0)
write(out, new File(_appRoot, "pmapi.xsd").getPath());
else if ("DeploymentService".equals(serviceName))
write(out, new File(_appRoot, "deploy.wsdl").getPath());
else
write(out, axisService.getFileName().getFile());
}
});
} else {
renderHtml(response, "Service Not Found", new DocBody() {
public void render(Writer out) throws IOException {
out.write("<p>Couldn't find service " + serviceName + "</p>");
}
});
}
}
} else if ("processes".equals(segments[0])) {
if (segments.length == 1) {
renderHtml(response, "Deployed Processes", new DocBody() {
public void render(Writer out) throws IOException {
for (QName process :_store.getProcesses()) {
String url = root + bundleUrlFor(_store.getProcessConfiguration(process).getBpelDocument());
String[] nameVer = process.getLocalPart().split("-");
out.write("<p><a href=\"" + url + "\">" + nameVer[0] + "</a> (v" + nameVer[1] + ")");
out.write(" - " + process.getNamespaceURI() + "</p>");
}
}
});
}
} else if ("bundles".equals(segments[0])) {
if (segments.length == 1) {
renderHtml(response, "Deployment Bundles", new DocBody() {
public void render(Writer out) throws IOException {
for (String bundle : _store.getPackages())
out.write("<p><a href=\"" + bundle + "\">" + bundle + "</a></p>");
}
});
} else if (segments.length == 2) {
renderHtml(response, "Files in Bundle " + segments[1], new DocBody() {
public void render(Writer out) throws IOException {
List<QName> processes = _store.listProcesses(segments[1]);
if (processes != null) {
List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles();
for (File file : files) {
String relativePath = file.getPath().substring(file.getPath()
.indexOf("processes")+10).replaceAll("\\\\", "/");
out.write("<p><a href=\"" + relativePath + "\">" + relativePath + "</a></p>");
}
} else {
out.write("<p>Couldn't find bundle " + segments[1] + "</p>");
}
}
});
} else if (segments.length > 2) {
List<QName> processes = _store.listProcesses(segments[1]);
if (processes != null) {
List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles();
for (final File file : files) {
String relativePath = requestURI.substring(deplUri + 12 + 9 + segments[1].length());
if (file.getPath().endsWith(relativePath)) {
renderXml(response, new DocBody() {
public void render(Writer out) throws IOException {
write(out, file.getPath());
}
});
return true;
}
}
} else {
renderHtml(response, "No Bundle Found", new DocBody() {
public void render(Writer out) throws IOException {
out.write("<p>Couldn't find bundle " + segments[2] + "</p>");
}
});
}
}
} else if("getBundleDocs".equals(segments[0])){
if(segments.length == 1){
renderXml(response, new DocBody(){
public void render(Writer out) throws IOException{
out.write("<getBundleDocsResponse>");
out.write("<error>Not enough args..</error>");
out.write("</getBundleDocsResponse>");
}
});
}else if (segments.length == 2){
final String bundleName = segments[1];
final List<QName> processes = _store.listProcesses(bundleName);
if(processes != null){
renderXml(response, new DocBody(){
public void render(Writer out) throws IOException{
out.write("<getBundleDocsResponse><name>"+ bundleName +"</name>");
//final List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles();
//final String pid = _store.getProcessConfiguration(processes.get(0)).getProcessId().toString();
for(final QName process: processes){
List<File> files = _store.getProcessConfiguration(process).getFiles();
String pid = _store.getProcessConfiguration(process).getProcessId().toString();
out.write("<process><pid>"+pid+"</pid>");
for (final File file : files){
if(file.getPath().endsWith(".wsdl")){
String relativePath = file.getPath().substring(_store.getDeployDir().getCanonicalPath().length() + 1);
out.write("<wsdl>"+ relativePath + "</wsdl>");
}
if(file.getPath().endsWith(".bpel")){
String relativePath = file.getPath().substring(_store.getDeployDir().getCanonicalPath().length() + 1);
out.write("<bpel>"+ relativePath + "</bpel>");
}
}
out.write("</process>");
}
out.write("</getBundleDocsResponse>");
}
});
}
}
}else if("getProcessDefinition".equals(segments[0])){
if(segments.length == 1){
renderXml(response, new DocBody(){
public void render(Writer out) throws IOException{
out.write("<getProcessDefinitionResponse>");
out.write("<error>Not enough args..</error>");
out.write("</getProcessDefinitionResponse>");
}
});
}else if (segments.length == 2){
String processName = segments[1];
for (QName process :_store.getProcesses()) {
String[] nameVer = process.getLocalPart().split("-");
if(processName.equals(nameVer[0])){
final String url = root + bundleUrlFor(_store.getProcessConfiguration(process).getBpelDocument());
renderXml(response, new DocBody(){
public void render(Writer out) throws IOException{
out.write("<getProcessDefinition>");
out.write("<url>"+ url +"</url>");
out.write("</getProcessDefinition>");
}
});
}
}
}
}
}
return true;
}
return false;
}
|
diff --git a/de.peeeq.wurstscript/src/de/peeeq/wurstscript/types/CallSignature.java b/de.peeeq.wurstscript/src/de/peeeq/wurstscript/types/CallSignature.java
index 73f506c0..02ac8071 100644
--- a/de.peeeq.wurstscript/src/de/peeeq/wurstscript/types/CallSignature.java
+++ b/de.peeeq.wurstscript/src/de/peeeq/wurstscript/types/CallSignature.java
@@ -1,52 +1,55 @@
package de.peeeq.wurstscript.types;
import java.util.List;
import de.peeeq.wurstscript.ast.AstElement;
import de.peeeq.wurstscript.ast.Expr;
public class CallSignature {
private final Expr receiver;
private final List<Expr> arguments;
public CallSignature(Expr receiver, List<Expr> arguments) {
this.receiver = receiver;
this.arguments = arguments;
}
public List<Expr> getArguments() {
return arguments;
}
public Expr getReceiver() {
return receiver;
}
public void checkSignatureCompatibility(FunctionSignature sig, String funcName, AstElement pos) {
+ if (sig == FunctionSignature.empty) {
+ return;
+ }
if (receiver != null) {
if (sig.getReceiverType() == null) {
receiver.addError("No receiver expected for function " + funcName + ".");
} else if (!receiver.attrTyp().isSubtypeOf(sig.getReceiverType(), receiver)) {
receiver.addError("Incompatible receiver type at call to function " + funcName + ".\n" +
"Found " + receiver.attrTyp() + " but expected " + sig.getReceiverType());
}
}
if (getArguments().size() > sig.getParamTypes().size()) {
pos.addError("Too many arguments. Function " + funcName + " only takes " + sig.getParamTypes().size()
+ " parameters.");
return;
} else if (getArguments().size() < sig.getParamTypes().size()) {
pos.addError("Not enough arguments. Function " + funcName + " requires " + sig.getParamTypes().size()
+ " parameters.");
} else {
for (int i=0; i<getArguments().size(); i++) {
if (!getArguments().get(i).attrTyp().isSubtypeOf(sig.getParamTypes().get(i), pos)) {
getArguments().get(i).addError("Wrong parameter type when calling " + funcName + ".\n"
+ "Found " + getArguments().get(i).attrTyp() + " but expected " + sig.getParamTypes().get(i));
}
}
}
}
}
| true | true | public void checkSignatureCompatibility(FunctionSignature sig, String funcName, AstElement pos) {
if (receiver != null) {
if (sig.getReceiverType() == null) {
receiver.addError("No receiver expected for function " + funcName + ".");
} else if (!receiver.attrTyp().isSubtypeOf(sig.getReceiverType(), receiver)) {
receiver.addError("Incompatible receiver type at call to function " + funcName + ".\n" +
"Found " + receiver.attrTyp() + " but expected " + sig.getReceiverType());
}
}
if (getArguments().size() > sig.getParamTypes().size()) {
pos.addError("Too many arguments. Function " + funcName + " only takes " + sig.getParamTypes().size()
+ " parameters.");
return;
} else if (getArguments().size() < sig.getParamTypes().size()) {
pos.addError("Not enough arguments. Function " + funcName + " requires " + sig.getParamTypes().size()
+ " parameters.");
} else {
for (int i=0; i<getArguments().size(); i++) {
if (!getArguments().get(i).attrTyp().isSubtypeOf(sig.getParamTypes().get(i), pos)) {
getArguments().get(i).addError("Wrong parameter type when calling " + funcName + ".\n"
+ "Found " + getArguments().get(i).attrTyp() + " but expected " + sig.getParamTypes().get(i));
}
}
}
}
| public void checkSignatureCompatibility(FunctionSignature sig, String funcName, AstElement pos) {
if (sig == FunctionSignature.empty) {
return;
}
if (receiver != null) {
if (sig.getReceiverType() == null) {
receiver.addError("No receiver expected for function " + funcName + ".");
} else if (!receiver.attrTyp().isSubtypeOf(sig.getReceiverType(), receiver)) {
receiver.addError("Incompatible receiver type at call to function " + funcName + ".\n" +
"Found " + receiver.attrTyp() + " but expected " + sig.getReceiverType());
}
}
if (getArguments().size() > sig.getParamTypes().size()) {
pos.addError("Too many arguments. Function " + funcName + " only takes " + sig.getParamTypes().size()
+ " parameters.");
return;
} else if (getArguments().size() < sig.getParamTypes().size()) {
pos.addError("Not enough arguments. Function " + funcName + " requires " + sig.getParamTypes().size()
+ " parameters.");
} else {
for (int i=0; i<getArguments().size(); i++) {
if (!getArguments().get(i).attrTyp().isSubtypeOf(sig.getParamTypes().get(i), pos)) {
getArguments().get(i).addError("Wrong parameter type when calling " + funcName + ".\n"
+ "Found " + getArguments().get(i).attrTyp() + " but expected " + sig.getParamTypes().get(i));
}
}
}
}
|
diff --git a/web/src/main/java/org/fao/geonet/UpdateHarvesterIdsTask.java b/web/src/main/java/org/fao/geonet/UpdateHarvesterIdsTask.java
index 91adfc2076..2f5a2c40a2 100644
--- a/web/src/main/java/org/fao/geonet/UpdateHarvesterIdsTask.java
+++ b/web/src/main/java/org/fao/geonet/UpdateHarvesterIdsTask.java
@@ -1,71 +1,72 @@
package org.fao.geonet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jeeves.resources.dbms.Dbms;
import org.fao.geonet.kernel.setting.SettingManager;
import org.jdom.Element;
public class UpdateHarvesterIdsTask implements DatabaseMigrationTask {
@Override
public void update(SettingManager settings, Dbms dbms) throws SQLException {
final int MIN_HARVEST_ID = 100000;
Element result = dbms
.select("select * from Settings where parentid = 2 and id < "
+ MIN_HARVEST_ID);
if (result.getChildren().size() > 0) {
dbms.execute("SELECT * INTO Harvester FROM Settings WHERE parentid = 2");
int changed = result.getChildren().size();
while(changed > 0) {
changed = dbms.execute("INSERT INTO Harvester SELECT * FROM Settings WHERE parentid IN (SELECT id FROM Harvester) AND NOT id IN (SELECT id FROM Harvester)");
}
dbms.execute("DELETE FROM Settings WHERE id IN (SELECT id FROM Harvester)");
int newHarvesterBaseIndex = Math.max(max(dbms), 100000);
@SuppressWarnings("unchecked")
List<Element> harvesterValues = dbms.select(
"SELECT * from Harvester").getChildren();
Map<Integer, Integer> updates = new HashMap<Integer, Integer>();
+ updates.put(2,2); //Add harvesting node parentid to id map
for (Element element : harvesterValues) {
int id = Integer.parseInt(element.getChildText("id"));
newHarvesterBaseIndex++;
updates.put(id, newHarvesterBaseIndex);
}
StringBuilder builder = new StringBuilder("INSERT INTO Settings VALUES ");
for (Element element : harvesterValues) {
int id = Integer.parseInt(element.getChildText("id"));
int parentid = Integer.parseInt(element.getChildText("parentid"));
String name = element.getChildText("name");
String value = element.getChildText("value");
builder.append("(")
.append(updates.get(id))
.append(',')
.append(updates.get(parentid))
.append(",'")
.append(name)
.append("','")
.append(value)
.append("'),");
}
builder.deleteCharAt(builder.length()-1);
dbms.execute(builder.toString());
}
}
private int max(Dbms dbms) throws SQLException {
Element result = dbms.select("SELECT max(id) FROM Settings");
Element maxEl = (Element) result.getChildren().get(0);
String maxText = ((Element) maxEl.getChildren().get(0)).getText();
return Integer.parseInt(maxText);
}
}
| true | true | public void update(SettingManager settings, Dbms dbms) throws SQLException {
final int MIN_HARVEST_ID = 100000;
Element result = dbms
.select("select * from Settings where parentid = 2 and id < "
+ MIN_HARVEST_ID);
if (result.getChildren().size() > 0) {
dbms.execute("SELECT * INTO Harvester FROM Settings WHERE parentid = 2");
int changed = result.getChildren().size();
while(changed > 0) {
changed = dbms.execute("INSERT INTO Harvester SELECT * FROM Settings WHERE parentid IN (SELECT id FROM Harvester) AND NOT id IN (SELECT id FROM Harvester)");
}
dbms.execute("DELETE FROM Settings WHERE id IN (SELECT id FROM Harvester)");
int newHarvesterBaseIndex = Math.max(max(dbms), 100000);
@SuppressWarnings("unchecked")
List<Element> harvesterValues = dbms.select(
"SELECT * from Harvester").getChildren();
Map<Integer, Integer> updates = new HashMap<Integer, Integer>();
for (Element element : harvesterValues) {
int id = Integer.parseInt(element.getChildText("id"));
newHarvesterBaseIndex++;
updates.put(id, newHarvesterBaseIndex);
}
StringBuilder builder = new StringBuilder("INSERT INTO Settings VALUES ");
for (Element element : harvesterValues) {
int id = Integer.parseInt(element.getChildText("id"));
int parentid = Integer.parseInt(element.getChildText("parentid"));
String name = element.getChildText("name");
String value = element.getChildText("value");
builder.append("(")
.append(updates.get(id))
.append(',')
.append(updates.get(parentid))
.append(",'")
.append(name)
.append("','")
.append(value)
.append("'),");
}
builder.deleteCharAt(builder.length()-1);
dbms.execute(builder.toString());
}
}
| public void update(SettingManager settings, Dbms dbms) throws SQLException {
final int MIN_HARVEST_ID = 100000;
Element result = dbms
.select("select * from Settings where parentid = 2 and id < "
+ MIN_HARVEST_ID);
if (result.getChildren().size() > 0) {
dbms.execute("SELECT * INTO Harvester FROM Settings WHERE parentid = 2");
int changed = result.getChildren().size();
while(changed > 0) {
changed = dbms.execute("INSERT INTO Harvester SELECT * FROM Settings WHERE parentid IN (SELECT id FROM Harvester) AND NOT id IN (SELECT id FROM Harvester)");
}
dbms.execute("DELETE FROM Settings WHERE id IN (SELECT id FROM Harvester)");
int newHarvesterBaseIndex = Math.max(max(dbms), 100000);
@SuppressWarnings("unchecked")
List<Element> harvesterValues = dbms.select(
"SELECT * from Harvester").getChildren();
Map<Integer, Integer> updates = new HashMap<Integer, Integer>();
updates.put(2,2); //Add harvesting node parentid to id map
for (Element element : harvesterValues) {
int id = Integer.parseInt(element.getChildText("id"));
newHarvesterBaseIndex++;
updates.put(id, newHarvesterBaseIndex);
}
StringBuilder builder = new StringBuilder("INSERT INTO Settings VALUES ");
for (Element element : harvesterValues) {
int id = Integer.parseInt(element.getChildText("id"));
int parentid = Integer.parseInt(element.getChildText("parentid"));
String name = element.getChildText("name");
String value = element.getChildText("value");
builder.append("(")
.append(updates.get(id))
.append(',')
.append(updates.get(parentid))
.append(",'")
.append(name)
.append("','")
.append(value)
.append("'),");
}
builder.deleteCharAt(builder.length()-1);
dbms.execute(builder.toString());
}
}
|
diff --git a/protocol-shared/src/main/java/org/apache/directory/server/protocol/shared/transport/TcpTransport.java b/protocol-shared/src/main/java/org/apache/directory/server/protocol/shared/transport/TcpTransport.java
index efbfb1402e..1829aeeea9 100644
--- a/protocol-shared/src/main/java/org/apache/directory/server/protocol/shared/transport/TcpTransport.java
+++ b/protocol-shared/src/main/java/org/apache/directory/server/protocol/shared/transport/TcpTransport.java
@@ -1,177 +1,178 @@
/*
* 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.directory.server.protocol.shared.transport;
import java.net.InetSocketAddress;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @org.apache.xbean.XBean
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
* @version $Rev$, $Date$
*/
public class TcpTransport extends AbstractTransport
{
/** A logger for this class */
private static final Logger LOG = LoggerFactory.getLogger( TcpTransport.class );
/**
* Creates an instance of the TcpTransport class
*/
public TcpTransport()
{
super();
}
/**
* Creates an instance of the TcpTransport class on localhost
* @param tcpPort The port
*/
public TcpTransport( int tcpPort )
{
super( null, tcpPort, DEFAULT_NB_THREADS, DEFAULT_BACKLOG_NB );
this.acceptor = createAcceptor( null, tcpPort, DEFAULT_NB_THREADS, DEFAULT_BACKLOG_NB );
LOG.debug( "TCP Transport created : <*:{},>", tcpPort );
}
/**
* Creates an instance of the TcpTransport class on localhost
* @param tcpPort The port
* @param nbThreads The number of threads to create in the acceptor
*/
public TcpTransport( int tcpPort, int nbThreads )
{
super( null, tcpPort, nbThreads, DEFAULT_BACKLOG_NB );
this.acceptor = createAcceptor( null, tcpPort, nbThreads, DEFAULT_BACKLOG_NB );
LOG.debug( "TCP Transport created : <*:{},>", tcpPort );
}
/**
* Creates an instance of the TcpTransport class
* @param address The address
* @param port The port
*/
public TcpTransport( String address, int tcpPort )
{
super( address, tcpPort, DEFAULT_NB_THREADS, DEFAULT_BACKLOG_NB );
this.acceptor = createAcceptor( address, tcpPort, DEFAULT_NB_THREADS, DEFAULT_BACKLOG_NB );
LOG.debug( "TCP Transport created : <{}:{}>", address, tcpPort );
}
/**
* Creates an instance of the TcpTransport class on localhost
* @param tcpPort The port
* @param nbThreads The number of threads to create in the acceptor
* @param backlog The queue size for incoming messages, waiting for the
* acceptor to be ready
*/
public TcpTransport( int tcpPort, int nbThreads, int backLog )
{
super( LOCAL_HOST, tcpPort, nbThreads, backLog );
this.acceptor = createAcceptor( null, tcpPort, nbThreads, backLog );
LOG.debug( "TCP Transport created : <*:{},>", tcpPort );
}
/**
* Creates an instance of the TcpTransport class
* @param address The address
* @param tcpPort The port
* @param nbThreads The number of threads to create in the acceptor
* @param backlog The queue size for incoming messages, waiting for the
* acceptor to be ready
*/
public TcpTransport( String address, int tcpPort, int nbThreads, int backLog )
{
super( address, tcpPort, nbThreads, backLog );
this.acceptor = createAcceptor( address, tcpPort, nbThreads, backLog );
LOG.debug( "TCP Transport created : <{}:{},>", address, tcpPort );
}
/**
* Initialize the Acceptor if needed
*/
public void init()
{
acceptor = createAcceptor( getAddress(), getPort(), getNbThreads(), getBackLog() );
}
/**
* Helper method to create an IoAcceptor
*/
private IoAcceptor createAcceptor( String address, int port, int nbThreads, int backLog )
{
NioSocketAcceptor acceptor = new NioSocketAcceptor( nbThreads );
+ acceptor.setReuseAddress( true );
acceptor.setBacklog( backLog );
InetSocketAddress socketAddress = null;
// The address can be null here, if one want to connect using the wildcard address
if ( address == null )
{
// Create a socket listening on the wildcard address
socketAddress = new InetSocketAddress( port );
}
else
{
socketAddress = new InetSocketAddress( address, port );
}
acceptor.setDefaultLocalAddress( socketAddress );
return acceptor;
}
/**
* @return The associated SocketAcceptor
*/
public SocketAcceptor getSocketAcceptor()
{
return acceptor == null ? null : (SocketAcceptor)acceptor;
}
/**
* @see Object#toString()
*/
public String toString()
{
return "TcpTransport" + super.toString();
}
}
| true | true | private IoAcceptor createAcceptor( String address, int port, int nbThreads, int backLog )
{
NioSocketAcceptor acceptor = new NioSocketAcceptor( nbThreads );
acceptor.setBacklog( backLog );
InetSocketAddress socketAddress = null;
// The address can be null here, if one want to connect using the wildcard address
if ( address == null )
{
// Create a socket listening on the wildcard address
socketAddress = new InetSocketAddress( port );
}
else
{
socketAddress = new InetSocketAddress( address, port );
}
acceptor.setDefaultLocalAddress( socketAddress );
return acceptor;
}
| private IoAcceptor createAcceptor( String address, int port, int nbThreads, int backLog )
{
NioSocketAcceptor acceptor = new NioSocketAcceptor( nbThreads );
acceptor.setReuseAddress( true );
acceptor.setBacklog( backLog );
InetSocketAddress socketAddress = null;
// The address can be null here, if one want to connect using the wildcard address
if ( address == null )
{
// Create a socket listening on the wildcard address
socketAddress = new InetSocketAddress( port );
}
else
{
socketAddress = new InetSocketAddress( address, port );
}
acceptor.setDefaultLocalAddress( socketAddress );
return acceptor;
}
|
diff --git a/ui/ReportDialog.java b/ui/ReportDialog.java
index 516978b..151017e 100755
--- a/ui/ReportDialog.java
+++ b/ui/ReportDialog.java
@@ -1,127 +1,126 @@
/**
* ReportDialog.java
*
* This class provides a window for report no-catched exception in EduMips64 code.
* (c) 2006 EduMIPS64 project - Rizzo Vanni G.
*
* This file is part of the EduMIPS64 project, and is released under the GNU
* General Public License.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
//utente: edumips.org58154
//password: edubugreport
//alias: [email protected]
package edumips64.ui;
import edumips64.core.*;
import edumips64.utils.*;
import java.util.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.awt.font.*;
import java.text.*;
/**
* This class provides a window for configuration options.
*/
public class ReportDialog extends JDialog{
JButton okButton;
int width = 450, height = 400;
public ReportDialog(final JFrame owner,Exception exception,String title){
super(owner, title, true);
JPanel buttonPanel = new JPanel();
JButton okButton = new JButton(CurrentLocale.getString("ReportDialog.BUTTON"));
buttonPanel.add(okButton);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
setVisible(false);
dispose();
}
});
buttonPanel.add(okButton);
//Title's Icon and Text
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new BorderLayout());
String msg = CurrentLocale.getString("ReportDialog.MSG");
JTextArea textArea = new JTextArea(msg);
textArea.setFont(new Font("Verdana",0,20));
textArea.setForeground(new Color(0,0,85));
try{
JLabel label = new JLabel(new ImageIcon(edumips64.img.IMGLoader.getImage("fatal.png")),SwingConstants.LEFT);
titlePanel.add("West",label);
}catch(java.io.IOException e){}
titlePanel.add("Center",textArea);
//label style in TextArea
textArea.setLineWrap (true);
textArea.setWrapStyleWord (true);
textArea.setEditable (false);
textArea.setBackground ((Color)UIManager.get ("Label.background"));
textArea.setForeground ((Color)UIManager.get ("Label.foreground"));
textArea.setBorder (null);
//fill the Text Area whit Exception informations
String exmsg = new String();
- exception.fillInStackTrace();
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
exmsg = "------\r\n" + sw.toString() + "------\r\n";
}
catch(Exception exc) {
exmsg = "fatal error";
}
JTextArea ta = new JTextArea(exmsg);
JScrollPane scrollTable = new JScrollPane(ta);
getRootPane().setDefaultButton(okButton);
getContentPane().setLayout(new BorderLayout());
getContentPane().add("North", titlePanel);
getContentPane().add("Center", scrollTable);
getContentPane().add("South", buttonPanel);
setSize(width,height);
setLocation((getScreenWidth() - getWidth()) / 2, (getScreenHeight() - getHeight()) / 2);
setVisible(true);
}
public static int getScreenWidth() {
return (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth();
}
public static int getScreenHeight() {
return (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
}
}
| true | true | public ReportDialog(final JFrame owner,Exception exception,String title){
super(owner, title, true);
JPanel buttonPanel = new JPanel();
JButton okButton = new JButton(CurrentLocale.getString("ReportDialog.BUTTON"));
buttonPanel.add(okButton);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
setVisible(false);
dispose();
}
});
buttonPanel.add(okButton);
//Title's Icon and Text
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new BorderLayout());
String msg = CurrentLocale.getString("ReportDialog.MSG");
JTextArea textArea = new JTextArea(msg);
textArea.setFont(new Font("Verdana",0,20));
textArea.setForeground(new Color(0,0,85));
try{
JLabel label = new JLabel(new ImageIcon(edumips64.img.IMGLoader.getImage("fatal.png")),SwingConstants.LEFT);
titlePanel.add("West",label);
}catch(java.io.IOException e){}
titlePanel.add("Center",textArea);
//label style in TextArea
textArea.setLineWrap (true);
textArea.setWrapStyleWord (true);
textArea.setEditable (false);
textArea.setBackground ((Color)UIManager.get ("Label.background"));
textArea.setForeground ((Color)UIManager.get ("Label.foreground"));
textArea.setBorder (null);
//fill the Text Area whit Exception informations
String exmsg = new String();
exception.fillInStackTrace();
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
exmsg = "------\r\n" + sw.toString() + "------\r\n";
}
catch(Exception exc) {
exmsg = "fatal error";
}
JTextArea ta = new JTextArea(exmsg);
JScrollPane scrollTable = new JScrollPane(ta);
getRootPane().setDefaultButton(okButton);
getContentPane().setLayout(new BorderLayout());
getContentPane().add("North", titlePanel);
getContentPane().add("Center", scrollTable);
getContentPane().add("South", buttonPanel);
setSize(width,height);
setLocation((getScreenWidth() - getWidth()) / 2, (getScreenHeight() - getHeight()) / 2);
setVisible(true);
}
| public ReportDialog(final JFrame owner,Exception exception,String title){
super(owner, title, true);
JPanel buttonPanel = new JPanel();
JButton okButton = new JButton(CurrentLocale.getString("ReportDialog.BUTTON"));
buttonPanel.add(okButton);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
setVisible(false);
dispose();
}
});
buttonPanel.add(okButton);
//Title's Icon and Text
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new BorderLayout());
String msg = CurrentLocale.getString("ReportDialog.MSG");
JTextArea textArea = new JTextArea(msg);
textArea.setFont(new Font("Verdana",0,20));
textArea.setForeground(new Color(0,0,85));
try{
JLabel label = new JLabel(new ImageIcon(edumips64.img.IMGLoader.getImage("fatal.png")),SwingConstants.LEFT);
titlePanel.add("West",label);
}catch(java.io.IOException e){}
titlePanel.add("Center",textArea);
//label style in TextArea
textArea.setLineWrap (true);
textArea.setWrapStyleWord (true);
textArea.setEditable (false);
textArea.setBackground ((Color)UIManager.get ("Label.background"));
textArea.setForeground ((Color)UIManager.get ("Label.foreground"));
textArea.setBorder (null);
//fill the Text Area whit Exception informations
String exmsg = new String();
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
exmsg = "------\r\n" + sw.toString() + "------\r\n";
}
catch(Exception exc) {
exmsg = "fatal error";
}
JTextArea ta = new JTextArea(exmsg);
JScrollPane scrollTable = new JScrollPane(ta);
getRootPane().setDefaultButton(okButton);
getContentPane().setLayout(new BorderLayout());
getContentPane().add("North", titlePanel);
getContentPane().add("Center", scrollTable);
getContentPane().add("South", buttonPanel);
setSize(width,height);
setLocation((getScreenWidth() - getWidth()) / 2, (getScreenHeight() - getHeight()) / 2);
setVisible(true);
}
|
diff --git a/rdfbean-rdb/src/test/java/com/mysema/rdfbean/rdb/SchemaExport.java b/rdfbean-rdb/src/test/java/com/mysema/rdfbean/rdb/SchemaExport.java
index 21b5a179..4d71b77a 100644
--- a/rdfbean-rdb/src/test/java/com/mysema/rdfbean/rdb/SchemaExport.java
+++ b/rdfbean-rdb/src/test/java/com/mysema/rdfbean/rdb/SchemaExport.java
@@ -1,58 +1,62 @@
/*
* Copyright (c) 2010 Mysema Ltd.
* All rights reserved.
*
*/
package com.mysema.rdfbean.rdb;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import org.h2.jdbcx.JdbcDataSource;
import com.mysema.query.sql.DefaultNamingStrategy;
import com.mysema.query.sql.H2Templates;
import com.mysema.query.sql.MetaDataExporter;
import com.mysema.query.sql.MetaDataSerializer;
import com.mysema.query.sql.NamingStrategy;
import com.mysema.query.sql.SQLTemplates;
import com.mysema.rdfbean.model.MemoryIdSequence;
import com.mysema.rdfbean.model.Repository;
import com.mysema.rdfbean.object.Configuration;
import com.mysema.rdfbean.object.DefaultConfiguration;
/**
* SchemaExport provides
*
* @author tiwe
* @version $Id$
*/
public class SchemaExport {
public static void main(String[] args) throws SQLException{
JdbcDataSource ds = new JdbcDataSource();
ds.setURL("jdbc:h2:target/h2");
ds.setUser("sa");
ds.setPassword("");
Connection conn = ds.getConnection();
// export
try{
Configuration configuration = new DefaultConfiguration();
SQLTemplates templates = new H2Templates();
Repository repository = new RDBRepository(configuration, ds, templates, new MemoryIdSequence());
repository.initialize();
NamingStrategy namingStrategy = new DefaultNamingStrategy();
MetaDataSerializer serializer = new MetaDataSerializer("Q",namingStrategy);
- MetaDataExporter exporter = new MetaDataExporter("Q", "com.mysema.rdfbean.rdb.schema", new File("src/main/java"), namingStrategy, serializer);
+ MetaDataExporter exporter = new MetaDataExporter();
+ exporter.setPackageName("com.mysema.rdfbean.rdb.schema");
+ exporter.setTargetFolder(new File("src/main/java"));
+ exporter.setNamingStrategy(namingStrategy);
+ exporter.setSerializer(serializer);
exporter.export(conn.getMetaData());
}finally{
conn.close();
}
}
}
| true | true | public static void main(String[] args) throws SQLException{
JdbcDataSource ds = new JdbcDataSource();
ds.setURL("jdbc:h2:target/h2");
ds.setUser("sa");
ds.setPassword("");
Connection conn = ds.getConnection();
// export
try{
Configuration configuration = new DefaultConfiguration();
SQLTemplates templates = new H2Templates();
Repository repository = new RDBRepository(configuration, ds, templates, new MemoryIdSequence());
repository.initialize();
NamingStrategy namingStrategy = new DefaultNamingStrategy();
MetaDataSerializer serializer = new MetaDataSerializer("Q",namingStrategy);
MetaDataExporter exporter = new MetaDataExporter("Q", "com.mysema.rdfbean.rdb.schema", new File("src/main/java"), namingStrategy, serializer);
exporter.export(conn.getMetaData());
}finally{
conn.close();
}
}
| public static void main(String[] args) throws SQLException{
JdbcDataSource ds = new JdbcDataSource();
ds.setURL("jdbc:h2:target/h2");
ds.setUser("sa");
ds.setPassword("");
Connection conn = ds.getConnection();
// export
try{
Configuration configuration = new DefaultConfiguration();
SQLTemplates templates = new H2Templates();
Repository repository = new RDBRepository(configuration, ds, templates, new MemoryIdSequence());
repository.initialize();
NamingStrategy namingStrategy = new DefaultNamingStrategy();
MetaDataSerializer serializer = new MetaDataSerializer("Q",namingStrategy);
MetaDataExporter exporter = new MetaDataExporter();
exporter.setPackageName("com.mysema.rdfbean.rdb.schema");
exporter.setTargetFolder(new File("src/main/java"));
exporter.setNamingStrategy(namingStrategy);
exporter.setSerializer(serializer);
exporter.export(conn.getMetaData());
}finally{
conn.close();
}
}
|
diff --git a/src/main/java/thesmith/eventhorizon/controller/IndexController.java b/src/main/java/thesmith/eventhorizon/controller/IndexController.java
index cbdc442..ce4fe90 100644
--- a/src/main/java/thesmith/eventhorizon/controller/IndexController.java
+++ b/src/main/java/thesmith/eventhorizon/controller/IndexController.java
@@ -1,178 +1,179 @@
package thesmith.eventhorizon.controller;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import thesmith.eventhorizon.model.Status;
import com.google.appengine.repackaged.com.google.common.collect.Lists;
@Controller
public class IndexController extends BaseController {
public static final String FROM = "from";
private static final DateFormat format = new SimpleDateFormat("yyyy/MM/dd kk:mm:ss");
private static final DateFormat urlFormat = new SimpleDateFormat("yyyy/MM/dd/kk/mm/ss");
@RequestMapping(value = "/{personId}/{year}/{month}/{day}/{hour}/{min}/{sec}", method = RequestMethod.GET)
public String index(@PathVariable("personId") String personId, @PathVariable("year") int year,
@PathVariable("month") int month, @PathVariable("day") int day, @PathVariable("hour") int hour,
@PathVariable("min") int min, @PathVariable("sec") int sec, ModelMap model) {
try {
Date from = format.parse(String.format("%d/%d/%d %d:%d:%d", year, month, day, hour, min, sec));
this.setModel(personId, from, model);
} catch (ParseException e) {
if (logger.isWarnEnabled())
logger.warn(e);
return "redirect:/error";
}
return "index/index";
}
@RequestMapping(value = "/{personId}/{year}/{month}/{day}/{hour}/{min}/{sec}/{domain}/previous", method = RequestMethod.GET)
public String previous(@PathVariable("personId") String personId, @PathVariable("year") int year,
@PathVariable("month") int month, @PathVariable("day") int day, @PathVariable("hour") int hour,
@PathVariable("min") int min, @PathVariable("sec") int sec, @PathVariable("domain") String domain) {
try {
Date from = format.parse(String.format("%d/%d/%d %d:%d:%d", year, month, day, hour, min, sec));
Status status = statusService.previous(personId, domain, from);
if (null == status)
status = statusService.find(personId, domain, from);
return String.format("redirect:/%s/%s/", personId, urlFormat.format(status.getCreated()));
} catch (ParseException e) {
if (logger.isWarnEnabled())
logger.warn(e);
return "redirect:/error";
}
}
@RequestMapping(value = "/{personId}/{year}/{month}/{day}/{hour}/{min}/{sec}/{domain}/next", method = RequestMethod.GET)
public String next(@PathVariable("personId") String personId, @PathVariable("year") int year,
@PathVariable("month") int month, @PathVariable("day") int day, @PathVariable("hour") int hour,
@PathVariable("min") int min, @PathVariable("sec") int sec, @PathVariable("domain") String domain) {
try {
Date from = format.parse(String.format("%d/%d/%d %d:%d:%d", year, month, day, hour, min, sec));
Status status = statusService.next(personId, domain, from);
if (null == status)
status = statusService.find(personId, domain, from);
return String.format("redirect:/%s/%s/", personId, urlFormat.format(status.getCreated()));
} catch (ParseException e) {
if (logger.isWarnEnabled())
logger.warn(e);
return "redirect:/error";
}
}
@RequestMapping(value = "/{personId}/{domain}/previous", method = RequestMethod.GET)
public String previous(@PathVariable("personId") String personId, @PathVariable("domain") String domain,
@RequestParam("from") String from, ModelMap model) {
try {
Status status = statusService.previous(personId, domain, this.parseDate(from));
if (null != status)
this.setModel(personId, status.getCreated(), model);
} catch (ParseException e) {
if (logger.isWarnEnabled())
logger.warn(e);
return "redirect:/error";
}
return "index/index";
}
@RequestMapping(value = "/{personId}/{domain}/next", method = RequestMethod.GET)
public String next(@PathVariable("personId") String personId, @PathVariable("domain") String domain,
@RequestParam("from") String from, ModelMap model) {
try {
Status status = statusService.next(personId, domain, this.parseDate(from));
if (null != status)
this.setModel(personId, status.getCreated(), model);
} catch (ParseException e) {
if (logger.isWarnEnabled())
logger.warn(e);
return "redirect:/error";
}
return "index/index";
}
@RequestMapping(value = "/{personId}/now", method = RequestMethod.GET)
public String now(@PathVariable("personId") String personId, @RequestParam("from") String from, ModelMap model) {
if (null != from && from.length() > 0) {
try {
this.setModel(personId, this.parseDate(from), model);
} catch (ParseException e) {
if (logger.isWarnEnabled())
logger.warn(e);
return "redirect:/error";
}
}
return "index/index";
}
@RequestMapping(value = "/{personId}", method = RequestMethod.GET)
public String start(@PathVariable("personId") String personId, ModelMap model) {
this.setModel(personId, null, model);
return "index/index";
}
@RequestMapping(value = "/error", method = RequestMethod.GET)
public String error() {
return "error";
}
private void setModel(String personId, Date from, ModelMap model) {
List<String> domains = accountService.domains(personId);
List<Status> statuses = Lists.newArrayList();
if (null != from) {
for (String domain : domains) {
Status status = statusService.find(personId, domain, from);
if (null == status) {
status = defaultStatus(personId, domain, from);
}
statuses.add(status);
}
} else {
from = new Date();
for (String domain : domains) {
statuses.add(defaultStatus(personId, domain, from));
}
+ model.addAttribute("refresh", true);
}
model.addAttribute("statuses", statuses);
model.addAttribute("personId", personId);
model.addAttribute("from", from);
if (logger.isDebugEnabled())
logger.debug("Setting the model: "+model);
}
private Status defaultStatus(String personId, String domain, Date from) {
Status status = new Status();
status.setDomain(domain);
status.setPersonId(personId);
status.setStatus("");
status.setCreated(from);
status.setPeriod("today");
return status;
}
private Date parseDate(String from) throws ParseException {
if (from.startsWith("/"))
from = from.substring(1);
if (from.endsWith("/"))
from = from.substring(0, from.length());
return urlFormat.parse(from);
}
}
| true | true | private void setModel(String personId, Date from, ModelMap model) {
List<String> domains = accountService.domains(personId);
List<Status> statuses = Lists.newArrayList();
if (null != from) {
for (String domain : domains) {
Status status = statusService.find(personId, domain, from);
if (null == status) {
status = defaultStatus(personId, domain, from);
}
statuses.add(status);
}
} else {
from = new Date();
for (String domain : domains) {
statuses.add(defaultStatus(personId, domain, from));
}
}
model.addAttribute("statuses", statuses);
model.addAttribute("personId", personId);
model.addAttribute("from", from);
if (logger.isDebugEnabled())
logger.debug("Setting the model: "+model);
}
| private void setModel(String personId, Date from, ModelMap model) {
List<String> domains = accountService.domains(personId);
List<Status> statuses = Lists.newArrayList();
if (null != from) {
for (String domain : domains) {
Status status = statusService.find(personId, domain, from);
if (null == status) {
status = defaultStatus(personId, domain, from);
}
statuses.add(status);
}
} else {
from = new Date();
for (String domain : domains) {
statuses.add(defaultStatus(personId, domain, from));
}
model.addAttribute("refresh", true);
}
model.addAttribute("statuses", statuses);
model.addAttribute("personId", personId);
model.addAttribute("from", from);
if (logger.isDebugEnabled())
logger.debug("Setting the model: "+model);
}
|
diff --git a/src/no/runsafe/framework/hook/HookEngine.java b/src/no/runsafe/framework/hook/HookEngine.java
index ebc145c4..73945a26 100644
--- a/src/no/runsafe/framework/hook/HookEngine.java
+++ b/src/no/runsafe/framework/hook/HookEngine.java
@@ -1,30 +1,34 @@
package no.runsafe.framework.hook;
import org.picocontainer.DefaultPicoContainer;
import org.picocontainer.Startable;
public class HookEngine implements Startable
{
public static final DefaultPicoContainer hookContainer = new DefaultPicoContainer();
public HookEngine()
{
}
public HookEngine(FrameworkHook[] hooks)
{
for (FrameworkHook hook : hooks)
+ {
+ // Do this to avoid exceptions..
+ hookContainer.removeComponent(hook);
hookContainer.addComponent(hook);
+ }
}
@Override
public void start()
{
// This class is startable just so it gets instantiated - constructor handles hooking..
}
@Override
public void stop()
{
}
}
| false | true | public HookEngine(FrameworkHook[] hooks)
{
for (FrameworkHook hook : hooks)
hookContainer.addComponent(hook);
}
| public HookEngine(FrameworkHook[] hooks)
{
for (FrameworkHook hook : hooks)
{
// Do this to avoid exceptions..
hookContainer.removeComponent(hook);
hookContainer.addComponent(hook);
}
}
|
diff --git a/grids/src/sage/web/page/StreamPageController.java b/grids/src/sage/web/page/StreamPageController.java
index 80f0f6d..025035b 100644
--- a/grids/src/sage/web/page/StreamPageController.java
+++ b/grids/src/sage/web/page/StreamPageController.java
@@ -1,78 +1,78 @@
package sage.web.page;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import sage.domain.service.TagService;
import sage.domain.service.UserService;
import sage.entity.Tag;
import sage.transfer.TagCard;
import sage.transfer.TagLabel;
import sage.web.auth.AuthUtil;
import sage.web.context.FrontMap;
@Controller
public class StreamPageController {
@Autowired
private UserService userService;
@Autowired
private TagService tagService;
@RequestMapping("/public/{id}")
public String publicPage(@PathVariable("id") long id, ModelMap model) {
FrontMap fm = FrontMap.from(model);
fm.put("id", id);
List<TagLabel> coreTags = new ArrayList<>();
List<TagLabel> nonCoreTags = new ArrayList<>();
TagCard tagCard = tagService.getTagCard(id);
for (TagLabel child : tagCard.getChildren()) {
- if (child.isCore()) {
+ if (child.getIsCore()) {
coreTags.add(child);
} else {
nonCoreTags.add(child);
}
}
Collection<Tag> sameNameTags = tagService.getSameNameTags(id);
fm.put("coreTags", coreTags);
fm.put("nonCoreTags", nonCoreTags);
fm.put("sameNameTags", sameNameTags);
fm.put("relatedTags", null);
return "public-page";
}
@RequestMapping("/private")
public String privatePage() {
return "forward:/private/" + AuthUtil.checkCurrentUid();
}
@RequestMapping("/private/{id}")
public String privatePage(@PathVariable("id") long id, ModelMap model) {
Long uid = AuthUtil.checkCurrentUid();
FrontMap fm = FrontMap.from(model);
fm.put("id", id);
if (uid.equals(id)) {
fm.put("isSelfPage", true);
}
fm.put("thisUser", userService.getUserCard(uid, id));
model.remove("userSelfJson");
return "private-page";
}
@RequestMapping("/group/{id}")
public String groupPage(@PathVariable("id") long id) {
return "group-page";
}
}
| true | true | public String publicPage(@PathVariable("id") long id, ModelMap model) {
FrontMap fm = FrontMap.from(model);
fm.put("id", id);
List<TagLabel> coreTags = new ArrayList<>();
List<TagLabel> nonCoreTags = new ArrayList<>();
TagCard tagCard = tagService.getTagCard(id);
for (TagLabel child : tagCard.getChildren()) {
if (child.isCore()) {
coreTags.add(child);
} else {
nonCoreTags.add(child);
}
}
Collection<Tag> sameNameTags = tagService.getSameNameTags(id);
fm.put("coreTags", coreTags);
fm.put("nonCoreTags", nonCoreTags);
fm.put("sameNameTags", sameNameTags);
fm.put("relatedTags", null);
return "public-page";
}
| public String publicPage(@PathVariable("id") long id, ModelMap model) {
FrontMap fm = FrontMap.from(model);
fm.put("id", id);
List<TagLabel> coreTags = new ArrayList<>();
List<TagLabel> nonCoreTags = new ArrayList<>();
TagCard tagCard = tagService.getTagCard(id);
for (TagLabel child : tagCard.getChildren()) {
if (child.getIsCore()) {
coreTags.add(child);
} else {
nonCoreTags.add(child);
}
}
Collection<Tag> sameNameTags = tagService.getSameNameTags(id);
fm.put("coreTags", coreTags);
fm.put("nonCoreTags", nonCoreTags);
fm.put("sameNameTags", sameNameTags);
fm.put("relatedTags", null);
return "public-page";
}
|
diff --git a/src/gnu/io/RXTXCommDriver.java b/src/gnu/io/RXTXCommDriver.java
index 95e4c45..1ab6977 100644
--- a/src/gnu/io/RXTXCommDriver.java
+++ b/src/gnu/io/RXTXCommDriver.java
@@ -1,411 +1,411 @@
/*-------------------------------------------------------------------------
| A wrapper to convert RXTX into Linux Java Comm
| Copyright 1998 Kevin Hester, [email protected]
| Copyright 2000 Trent Jarvi, [email protected]
|
| This library is free software; you can redistribute it and/or
| modify it under the terms of the GNU Library General Public
| License as published by the Free Software Foundation; either
| version 2 of the License, or (at your option) any later version.
|
| This library is distributed in the hope that it will be useful,
| but WITHOUT ANY WARRANTY; without even the implied warranty of
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
| Library General Public License for more details.
|
| You should have received a copy of the GNU Library General Public
| License along with this library; if not, write to the Free
| Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--------------------------------------------------------------------------*/
/* Martin Pool <[email protected]> added support for explicitly-specified
* lists of ports, October 2000. */
package gnu.io;
import java.io.*;
import java.util.*;
import javax.comm.*;
import java.util.StringTokenizer;
/**
This is the JavaComm for Linux driver.
*/
public class RXTXCommDriver implements CommDriver
{
private static boolean debug = false;
static
{
System.loadLibrary( "Serial" );
}
/** Get the Serial port prefixes for the running OS */
private native boolean isDeviceGood(String dev);
private final String[] getPortPrefixes(String AllKnownPorts[]) {
/*
256 is the number of prefixes ( COM, cua, ttyS, ...) not
the number of devices (ttyS0, ttyS1, ttyS2, ...)
On a Linux system there are about 400 prefixes in /dev.
registerScannedPorts() assigns AllKnownPorts to something less
than 50 prefixes.
rxtx-1.5 uses Vectors to avoid this mess.
Trent
*/
String PortString[]=new String [256];
if(AllKnownPorts==null)
{
if (debug)
System.out.println("\nRXTXCommPort:getPortPrefixes() No ports are known for this System.\nPlease check the ports listed for " +osName+" in RXTXCommDriver:registerScannedPorts()\n");
}
int i=0;
for(int j=0;j<AllKnownPorts.length;j++){
if(isDeviceGood(AllKnownPorts[j])) {
PortString[i++]=new String(AllKnownPorts[j]);
}
}
String[] returnArray=new String[i];
System.arraycopy(PortString, 0, returnArray, 0, i);
if(PortString[0]==null)
{
if (debug)
System.out.println("\nRXTXCommPort:getPortPrefixes() No ports matched the list assumed for this\nSystem in the directory /dev. Please check the ports listed for \"" +osName+"\" in\nRXTXCommDriver:registerScannedPorts()\n");
}
else
{
if (debug)
System.out.println("\nRXTXCommPort:getPortPrefixes()\nThe following port prefixes have been identified as valid on "+osName+":\n");
for(int j=0;j<returnArray.length;j++)
{
if (debug)
System.out.println(j +" "+ PortString[j]);
}
}
return returnArray;
}
/*
* A primitive test of whether a specified device is available or
* not.
*
* FIXME: This is actually a pretty poor test. These Java calls
* map in the 1.2.2 Unix JDK into calls to access(2), which checks
* the permission bits on the file. There are at least two
* problems with this, however.
*
* Firstly, in Linux 2.2 it will fail with EROFS for a device node
* on a read-only device, even though you're allowed to write to
* them. This is fixed in Linux 2.4, but may exist on other
* systems as well.
*
* Secondly and more importantly, simply being permittedq to access
* the device doesn't mean that it physically exists, and therefore
* that an attempt to use it will succeed.
*
* One alternative approach would be to try to actually open the
* device for read/write, but that's not a good idea because
* opening a device can affect the control pins, etc.
*
* Even better might be to return all possible devices for this
* operating system or hardware without trying to check that
* they're usable, and then letting the application cope with ones
* that actually turn out not to work.
*
* @author Martin Pool
*/
private boolean accessReadWrite(String portName)
{
final File port = new File(portName);
return port.canRead() && port.canWrite();
}
private void RegisterValidPorts(
String devs[],
String Prefix[],
int PortType
) {
int p =0 ;
int i =0;
if (debug)
System.out.println("Entering RegisterValidPorts()");
if ( devs[0]==null || Prefix[0]==null) return;
for( i = 0;i<devs.length; i++ ) {
for( p = 0;p<Prefix.length; p++ ) {
String portName = new String("/dev/" + devs[ i ]);
if( devs[ i ].startsWith( Prefix[ p ] ) ) {
if (accessReadWrite(portName))
CommPortIdentifier.addPortName(
portName,
PortType,
this
);
}
}
}
if (debug)
System.out.println("Leaving RegisterValidPorts()");
}
String osName=System.getProperty("os.name");
/*
* initialize() will be called by the CommPortIdentifier's static
* initializer. The responsibility of this method is:
* 1) Ensure that that the hardware is present.
* 2) Load any required native libraries.
* 3) Register the port names with the CommPortIdentifier.
*
* <p>From the NullDriver.java CommAPI sample.
*
* added printerport stuff
* Holger Lehmann
* July 12, 1999
* IBM
* Added ttyM for Moxa boards
* Removed obsolete device cuaa
* Peter Bennett
* January 02, 2000
* Bencom
*/
public void initialize()
{
/*
First try to register ports specified in the properties
file. If that doesn't exist, then scan for ports.
*/
if (!registerSpecifiedPorts())
registerScannedPorts();
}
private void addSpecifiedPorts(String names, int type)
{
final String pathSep = System.getProperty("path.separator", ":");
final StringTokenizer tok = new StringTokenizer(names, pathSep);
while (tok.hasMoreElements())
{
String portName = tok.nextToken();
if (accessReadWrite(portName))
CommPortIdentifier.addPortName(portName,
type, this);
}
}
/*
* Register ports specified by the gnu.io.rxtx.SerialPorts and
* gnu.io.rxtx.ParallelPorts system properties.
*/
private boolean registerSpecifiedPorts()
{
boolean found = false;
String val;
val = System.getProperty("gnu.io.rxtx.SerialPorts");
if (val != null)
{
addSpecifiedPorts(val, CommPortIdentifier.PORT_SERIAL);
found = true;
}
val = System.getProperty("gnu.io.rxtx.ParallelPorts");
if (val != null)
{
addSpecifiedPorts(val, CommPortIdentifier.PORT_PARALLEL);
found = true;
}
return found;
}
/*
* Look for all entries in /dev, and if they look like they should
* be serial ports on this OS and they can be opened then register
* them.
*
*/
private void registerScannedPorts()
{
File dev = new File( "/dev" );
String[] devs = dev.list();
String[] AllKnownSerialPorts;
if(osName.equals("Linux"))
{
String[] Temp = {
"comx", // linux COMMX synchronous serial card
"holter", // custom card for heart monitoring
"modem", // linux symbolic link to modem.
"ttyircomm", // linux IrCommdevices (IrDA serial emu)
"ttycosa0c", // linux COSA/SRP synchronous serial card
"ttycosa1c", // linux COSA/SRP synchronous serial card
"ttyC", // linux cyclades cards
"ttyCH",// linux Chase Research AT/PCI-Fast serial card
"ttyD", // linux Digiboard serial card
"ttyE", // linux Stallion serial card
"ttyF", // linux Computone IntelliPort serial card
"ttyH", // linux Chase serial card
"ttyI", // linux virtual modems
"ttyL", // linux SDL RISCom serial card
"ttyM", // linux PAM Software's multimodem boards
// linux ISI serial card
"ttyMX",// linux Moxa Smart IO cards
"ttyP", // linux Hayes ESP serial card
"ttyR", // linux comtrol cards
// linux Specialix RIO serial card
"ttyS", // linux Serial Ports
"ttySI",// linux SmartIO serial card
"ttySR",// linux Specialix RIO serial card 257+
"ttyT", // linux Technology Concepts serial card
"ttyUSB",//linux USB serial converters
"ttyV", // linux Comtrol VS-1000 serial controller
"ttyW", // linux specialix cards
"ttyX", // linux SpecialX serial card
};
AllKnownSerialPorts=Temp;
}
- else if(osName.equals("irix")) // FIXME this is probably wrong
+ else if(osName.equals("Irix"))
{
String[] Temp = {
"ttyc", // irix raw character devices
"ttyd", // irix basic serial ports
"ttyf", // irix serial ports with hardware flow
"ttym", // irix modems
"ttyq", // irix pseudo ttys
"tty4d",// irix RS422
"tty4f",// irix RS422 with HSKo/HSki
"midi", // irix serial midi
"us" // irix mapped interface
};
AllKnownSerialPorts=Temp;
}
else if(osName.equals("FreeBSD")) //FIXME this is probably wrong
{
String[] Temp = {
"cuaa" // FreeBSD Serial Ports
};
AllKnownSerialPorts=Temp;
}
else if(osName.equals("NetBSD")) // FIXME this is probably wrong
{
String[] Temp = {
"tty0" // netbsd serial ports
};
AllKnownSerialPorts=Temp;
}
else if(osName.equals("HP-UX"))
{
String[] Temp = {
"tty0p",// HP-UX serial ports
"tty1p" // HP-UX serial ports
};
AllKnownSerialPorts=Temp;
}
else if(osName.equals("BeOS"))
{
String[] Temp = {
"serial" // BeOS serial ports
};
AllKnownSerialPorts=Temp;
}
else if(osName.equals("WIN32")) // FIXME this is probably wrong
{
String[] Temp = {
"COM" // win32 serial ports
};
AllKnownSerialPorts=Temp;
}
else
{
if (debug)
System.out.println(osName + " ports have not been entered in RXTXCommDriver.java. This may just be a typo in the method initialize().");
AllKnownSerialPorts=null;
}
/** Get the Parallel port prefixes for the running os
* Holger Lehmann
* July 12, 1999
* IBM
*/
String[] AllKnownParallelPorts;
if(osName.equals("Linux"))
{
String[] temp={
"lp" // linux printer port
};
AllKnownParallelPorts=temp;
}
else /* printer support is green */
{
AllKnownParallelPorts=null;
}
if (devs==null)
{
if (debug)
System.out.println("RXTXCommDriver:registerScannedPorts() no Device files to check ");
return;
}
RegisterValidPorts(
devs,
getPortPrefixes(AllKnownSerialPorts),
CommPortIdentifier.PORT_SERIAL
);
/*
if(AllKnownParallelPorts!=null)
RegisterValidPorts(
devs,
getPortPrefixes(AllKnownParallelPorts),
CommPortIdentifier.PORT_PARALLEL
);
else if (debug)
System.out.println("Skipping Printer Ports");
*/
}
/*
* getCommPort() will be called by CommPortIdentifier from its
* openPort() method. portName is a string that was registered earlier
* using the CommPortIdentifier.addPortName() method. getCommPort()
* returns an object that extends either SerialPort or ParallelPort.
*
* <p>From the NullDriver.java CommAPI sample.
*/
public CommPort getCommPort( String portName, int portType )
{
try {
if (portType==CommPortIdentifier.PORT_SERIAL)
{
return new RXTXPort( portName );
}
else if (portType==CommPortIdentifier.PORT_PARALLEL)
{
return new LPRPort( portName );
}
} catch( PortInUseException e ) {
if (debug)
System.out.println(
"Port in use by another application");
}
return null;
}
}
| true | true | private void registerScannedPorts()
{
File dev = new File( "/dev" );
String[] devs = dev.list();
String[] AllKnownSerialPorts;
if(osName.equals("Linux"))
{
String[] Temp = {
"comx", // linux COMMX synchronous serial card
"holter", // custom card for heart monitoring
"modem", // linux symbolic link to modem.
"ttyircomm", // linux IrCommdevices (IrDA serial emu)
"ttycosa0c", // linux COSA/SRP synchronous serial card
"ttycosa1c", // linux COSA/SRP synchronous serial card
"ttyC", // linux cyclades cards
"ttyCH",// linux Chase Research AT/PCI-Fast serial card
"ttyD", // linux Digiboard serial card
"ttyE", // linux Stallion serial card
"ttyF", // linux Computone IntelliPort serial card
"ttyH", // linux Chase serial card
"ttyI", // linux virtual modems
"ttyL", // linux SDL RISCom serial card
"ttyM", // linux PAM Software's multimodem boards
// linux ISI serial card
"ttyMX",// linux Moxa Smart IO cards
"ttyP", // linux Hayes ESP serial card
"ttyR", // linux comtrol cards
// linux Specialix RIO serial card
"ttyS", // linux Serial Ports
"ttySI",// linux SmartIO serial card
"ttySR",// linux Specialix RIO serial card 257+
"ttyT", // linux Technology Concepts serial card
"ttyUSB",//linux USB serial converters
"ttyV", // linux Comtrol VS-1000 serial controller
"ttyW", // linux specialix cards
"ttyX", // linux SpecialX serial card
};
AllKnownSerialPorts=Temp;
}
else if(osName.equals("irix")) // FIXME this is probably wrong
{
String[] Temp = {
"ttyc", // irix raw character devices
"ttyd", // irix basic serial ports
"ttyf", // irix serial ports with hardware flow
"ttym", // irix modems
"ttyq", // irix pseudo ttys
"tty4d",// irix RS422
"tty4f",// irix RS422 with HSKo/HSki
"midi", // irix serial midi
"us" // irix mapped interface
};
AllKnownSerialPorts=Temp;
}
else if(osName.equals("FreeBSD")) //FIXME this is probably wrong
{
String[] Temp = {
"cuaa" // FreeBSD Serial Ports
};
AllKnownSerialPorts=Temp;
}
else if(osName.equals("NetBSD")) // FIXME this is probably wrong
{
String[] Temp = {
"tty0" // netbsd serial ports
};
AllKnownSerialPorts=Temp;
}
else if(osName.equals("HP-UX"))
{
String[] Temp = {
"tty0p",// HP-UX serial ports
"tty1p" // HP-UX serial ports
};
AllKnownSerialPorts=Temp;
}
else if(osName.equals("BeOS"))
{
String[] Temp = {
"serial" // BeOS serial ports
};
AllKnownSerialPorts=Temp;
}
else if(osName.equals("WIN32")) // FIXME this is probably wrong
{
String[] Temp = {
"COM" // win32 serial ports
};
AllKnownSerialPorts=Temp;
}
else
{
if (debug)
System.out.println(osName + " ports have not been entered in RXTXCommDriver.java. This may just be a typo in the method initialize().");
AllKnownSerialPorts=null;
}
/** Get the Parallel port prefixes for the running os
* Holger Lehmann
* July 12, 1999
* IBM
*/
String[] AllKnownParallelPorts;
if(osName.equals("Linux"))
{
String[] temp={
"lp" // linux printer port
};
AllKnownParallelPorts=temp;
}
else /* printer support is green */
{
AllKnownParallelPorts=null;
}
if (devs==null)
{
if (debug)
System.out.println("RXTXCommDriver:registerScannedPorts() no Device files to check ");
return;
}
RegisterValidPorts(
devs,
getPortPrefixes(AllKnownSerialPorts),
CommPortIdentifier.PORT_SERIAL
);
/*
if(AllKnownParallelPorts!=null)
RegisterValidPorts(
devs,
getPortPrefixes(AllKnownParallelPorts),
CommPortIdentifier.PORT_PARALLEL
);
else if (debug)
System.out.println("Skipping Printer Ports");
*/
}
| private void registerScannedPorts()
{
File dev = new File( "/dev" );
String[] devs = dev.list();
String[] AllKnownSerialPorts;
if(osName.equals("Linux"))
{
String[] Temp = {
"comx", // linux COMMX synchronous serial card
"holter", // custom card for heart monitoring
"modem", // linux symbolic link to modem.
"ttyircomm", // linux IrCommdevices (IrDA serial emu)
"ttycosa0c", // linux COSA/SRP synchronous serial card
"ttycosa1c", // linux COSA/SRP synchronous serial card
"ttyC", // linux cyclades cards
"ttyCH",// linux Chase Research AT/PCI-Fast serial card
"ttyD", // linux Digiboard serial card
"ttyE", // linux Stallion serial card
"ttyF", // linux Computone IntelliPort serial card
"ttyH", // linux Chase serial card
"ttyI", // linux virtual modems
"ttyL", // linux SDL RISCom serial card
"ttyM", // linux PAM Software's multimodem boards
// linux ISI serial card
"ttyMX",// linux Moxa Smart IO cards
"ttyP", // linux Hayes ESP serial card
"ttyR", // linux comtrol cards
// linux Specialix RIO serial card
"ttyS", // linux Serial Ports
"ttySI",// linux SmartIO serial card
"ttySR",// linux Specialix RIO serial card 257+
"ttyT", // linux Technology Concepts serial card
"ttyUSB",//linux USB serial converters
"ttyV", // linux Comtrol VS-1000 serial controller
"ttyW", // linux specialix cards
"ttyX", // linux SpecialX serial card
};
AllKnownSerialPorts=Temp;
}
else if(osName.equals("Irix"))
{
String[] Temp = {
"ttyc", // irix raw character devices
"ttyd", // irix basic serial ports
"ttyf", // irix serial ports with hardware flow
"ttym", // irix modems
"ttyq", // irix pseudo ttys
"tty4d",// irix RS422
"tty4f",// irix RS422 with HSKo/HSki
"midi", // irix serial midi
"us" // irix mapped interface
};
AllKnownSerialPorts=Temp;
}
else if(osName.equals("FreeBSD")) //FIXME this is probably wrong
{
String[] Temp = {
"cuaa" // FreeBSD Serial Ports
};
AllKnownSerialPorts=Temp;
}
else if(osName.equals("NetBSD")) // FIXME this is probably wrong
{
String[] Temp = {
"tty0" // netbsd serial ports
};
AllKnownSerialPorts=Temp;
}
else if(osName.equals("HP-UX"))
{
String[] Temp = {
"tty0p",// HP-UX serial ports
"tty1p" // HP-UX serial ports
};
AllKnownSerialPorts=Temp;
}
else if(osName.equals("BeOS"))
{
String[] Temp = {
"serial" // BeOS serial ports
};
AllKnownSerialPorts=Temp;
}
else if(osName.equals("WIN32")) // FIXME this is probably wrong
{
String[] Temp = {
"COM" // win32 serial ports
};
AllKnownSerialPorts=Temp;
}
else
{
if (debug)
System.out.println(osName + " ports have not been entered in RXTXCommDriver.java. This may just be a typo in the method initialize().");
AllKnownSerialPorts=null;
}
/** Get the Parallel port prefixes for the running os
* Holger Lehmann
* July 12, 1999
* IBM
*/
String[] AllKnownParallelPorts;
if(osName.equals("Linux"))
{
String[] temp={
"lp" // linux printer port
};
AllKnownParallelPorts=temp;
}
else /* printer support is green */
{
AllKnownParallelPorts=null;
}
if (devs==null)
{
if (debug)
System.out.println("RXTXCommDriver:registerScannedPorts() no Device files to check ");
return;
}
RegisterValidPorts(
devs,
getPortPrefixes(AllKnownSerialPorts),
CommPortIdentifier.PORT_SERIAL
);
/*
if(AllKnownParallelPorts!=null)
RegisterValidPorts(
devs,
getPortPrefixes(AllKnownParallelPorts),
CommPortIdentifier.PORT_PARALLEL
);
else if (debug)
System.out.println("Skipping Printer Ports");
*/
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.